0

Here is my code, where I would like to test validate_yaml function (I removed the function bodies, because they don't needed in question):

yaml_file_name = "env.yaml"
 
def load_yaml(file: str) -> list:
    pass


def validate_yaml(env_list: list):
    pass


def yaml_to_env(env_list: list):
    pass


env_list = load_yaml(f"{yaml_file_name}")
validate_yaml(env_list)
yaml_to_env(env_list)

This is my test file:

import pytest
import jsonschema
from yaml_to_env import load_yaml, validate_yaml


@pytest.mark.parametrize(
    "invalid_yaml",
    [
        (load_yaml("tests/yaml_files/invalid_workload_type.yaml")),
    ],
)
def test_yaml_env(invalid_yaml):
    with pytest.raises(jsonschema.ValidationError):
        validate_yaml(invalid_yaml)

My problem is that when I run pytest then the last three rows are executed too:

env_list = load_yaml(f"{yaml_file_name}")
validate_yaml(env_list)
yaml_to_env(env_list)

Why it is doing this? I would like to test only validate_yaml function and not call that three lines during pytest.

Thanks in advance

[EDIT1]

This is the best solution what I found so far:

if __name__ == "__main__":
    env_list = load_yaml(f"{yaml_file_name}")
    validate_yaml(env_list)
    yaml_to_env(env_list)
Zili
  • 455
  • 2
  • 4
  • 10

1 Answers1

1

Your edit is exactly what you need to do here. In your previous attempt the code has been executed during import of your production code in the test file. This is not an issue with pytest but rather basic module structure of python. See this link for details: What does if __name__ == "__main__": do? First point in the short answer seems to be what you did. :)

FloWil
  • 432
  • 5
  • 15