test_yaml_utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. with pytest.raises(FileNotFoundError):
  47. load_yaml_file(file_path=NON_EXISTING_YAML_FILE, ignore_error=False)
  48. def test_load_valid_yaml_file(prepare_example_yaml_file):
  49. yaml_data = load_yaml_file(file_path=prepare_example_yaml_file)
  50. assert len(yaml_data) > 0
  51. assert yaml_data['age'] == 30
  52. assert yaml_data['gender'] == 'male'
  53. assert yaml_data['address']['city'] == 'Example City'
  54. assert set(yaml_data['languages']) == {'Python', 'Java', 'C++'}
  55. assert yaml_data.get('empty_key') is None
  56. assert yaml_data.get('non_existed_key') is None
  57. def test_load_invalid_yaml_file(prepare_invalid_yaml_file):
  58. # yaml syntax error
  59. with pytest.raises(YAMLError):
  60. load_yaml_file(file_path=prepare_invalid_yaml_file, ignore_error=False)
  61. # ignore error
  62. assert load_yaml_file(file_path=prepare_invalid_yaml_file) == {}