test_yaml_utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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(dedent(
  13. """\
  14. address:
  15. city: Example City
  16. country: Example Country
  17. age: 30
  18. gender: male
  19. languages:
  20. - Python
  21. - Java
  22. - C++
  23. empty_key:
  24. """))
  25. return str(file_path)
  26. @pytest.fixture
  27. def prepare_invalid_yaml_file(tmp_path, monkeypatch) -> str:
  28. monkeypatch.chdir(tmp_path)
  29. file_path = tmp_path.joinpath(INVALID_YAML_FILE)
  30. file_path.write_text(dedent(
  31. """\
  32. address:
  33. city: Example City
  34. country: Example Country
  35. age: 30
  36. gender: male
  37. languages:
  38. - Python
  39. - Java
  40. - C++
  41. """))
  42. return str(file_path)
  43. def test_load_yaml_non_existing_file():
  44. assert load_yaml_file(file_path=NON_EXISTING_YAML_FILE) == {}
  45. assert load_yaml_file(file_path='') == {}
  46. def test_load_valid_yaml_file(prepare_example_yaml_file):
  47. yaml_data = load_yaml_file(file_path=prepare_example_yaml_file)
  48. assert len(yaml_data) > 0
  49. assert yaml_data['age'] == 30
  50. assert yaml_data['gender'] == 'male'
  51. assert yaml_data['address']['city'] == 'Example City'
  52. assert set(yaml_data['languages']) == {'Python', 'Java', 'C++'}
  53. assert yaml_data.get('empty_key') is None
  54. assert yaml_data.get('non_existed_key') is None
  55. def test_load_invalid_yaml_file(prepare_invalid_yaml_file):
  56. # yaml syntax error
  57. with pytest.raises(YAMLError):
  58. load_yaml_file(file_path=prepare_invalid_yaml_file)
  59. # ignore error
  60. assert load_yaml_file(file_path=prepare_invalid_yaml_file, ignore_error=True) == {}