您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

test_yaml_utils.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from textwrap import dedent
  2. import pytest
  3. from yaml import YAMLError
  4. from core.tools.utils.yaml_utils import _load_yaml_file
  5. EXAMPLE_YAML_FILE = "example_yaml.yaml"
  6. INVALID_YAML_FILE = "invalid_yaml.yaml"
  7. NON_EXISTING_YAML_FILE = "non_existing_file.yaml"
  8. @pytest.fixture
  9. def prepare_example_yaml_file(tmp_path, monkeypatch) -> str:
  10. monkeypatch.chdir(tmp_path)
  11. file_path = tmp_path.joinpath(EXAMPLE_YAML_FILE)
  12. file_path.write_text(
  13. dedent(
  14. """\
  15. address:
  16. city: Example City
  17. country: Example Country
  18. age: 30
  19. gender: male
  20. languages:
  21. - Python
  22. - Java
  23. - C++
  24. empty_key:
  25. """
  26. )
  27. )
  28. return str(file_path)
  29. @pytest.fixture
  30. def prepare_invalid_yaml_file(tmp_path, monkeypatch) -> str:
  31. monkeypatch.chdir(tmp_path)
  32. file_path = tmp_path.joinpath(INVALID_YAML_FILE)
  33. file_path.write_text(
  34. dedent(
  35. """\
  36. address:
  37. city: Example City
  38. country: Example Country
  39. age: 30
  40. gender: male
  41. languages:
  42. - Python
  43. - Java
  44. - C++
  45. """
  46. )
  47. )
  48. return str(file_path)
  49. def test_load_yaml_non_existing_file():
  50. with pytest.raises(FileNotFoundError):
  51. _load_yaml_file(file_path=NON_EXISTING_YAML_FILE)
  52. with pytest.raises(FileNotFoundError):
  53. _load_yaml_file(file_path="")
  54. def test_load_valid_yaml_file(prepare_example_yaml_file):
  55. yaml_data = _load_yaml_file(file_path=prepare_example_yaml_file)
  56. assert len(yaml_data) > 0
  57. assert yaml_data["age"] == 30
  58. assert yaml_data["gender"] == "male"
  59. assert yaml_data["address"]["city"] == "Example City"
  60. assert set(yaml_data["languages"]) == {"Python", "Java", "C++"}
  61. assert yaml_data.get("empty_key") is None
  62. assert yaml_data.get("non_existed_key") is None
  63. def test_load_invalid_yaml_file(prepare_invalid_yaml_file):
  64. # yaml syntax error
  65. with pytest.raises(YAMLError):
  66. _load_yaml_file(file_path=prepare_invalid_yaml_file)