Coverage for test/esxport/_export_test.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-22 17:59 +0530

1# Generated by CodiumAI 

2import inspect 

3import json 

4from pathlib import Path 

5from typing import Any 

6from unittest.mock import create_autospec, patch 

7 

8import pytest 

9from typing_extensions import Self 

10 

11from src.esxport import EsXport 

12 

13 

14@patch("src.esxport.EsXport._validate_fields") 

15class TestExport: 

16 """Tests that the method exports the data with valid arguments.""" 

17 

18 csv_header = ["age", "name"] 

19 

20 @staticmethod 

21 def rm_export_file(file_name: str) -> None: 

22 """Cleaer up resources.""" 

23 Path(f"{file_name}.tmp").unlink(missing_ok=True) 

24 

25 @staticmethod 

26 def rm_csv_export_file(file_name: str) -> None: 

27 """Cleaer up resources.""" 

28 Path(file_name).unlink(missing_ok=True) 

29 

30 def test_export_with_valid_arguments( 

31 self: Self, 

32 _: Any, 

33 esxport_obj: EsXport, 

34 ) -> None: 

35 """Checks if the method exports the data properly when given valid arguments.""" 

36 esxport_obj.opts.output_file = f"{inspect.stack()[0].function}.csv" 

37 export = create_autospec(esxport_obj.export) 

38 

39 export() 

40 

41 export.assert_called_once_with() 

42 TestExport.rm_export_file(f"{inspect.stack()[0].function}.csv") 

43 

44 def test_export_invalid_format( 

45 self: Self, 

46 _: Any, 

47 esxport_obj: EsXport, 

48 ) -> None: 

49 """Check if exception is raised when formatting is invalid.""" 

50 esxport_obj.opts.format = "invalid_format" 

51 with patch.object(EsXport, "_extract_headers", return_value=[]), pytest.raises(NotImplementedError): 

52 esxport_obj.export() 

53 TestExport.rm_export_file(f"{inspect.stack()[0].function}.csv") 

54 

55 def test_headers_extraction( 

56 self: Self, 

57 _: Any, 

58 esxport_obj: EsXport, 

59 ) -> None: 

60 """Check if exception is raised when formatting is invalid.""" 

61 esxport_obj.opts.output_file = f"{inspect.stack()[0].function}.csv" 

62 test_json = {"age": 2, "bar": "foo", "hello": "world"} 

63 with Path(f"{esxport_obj.opts.output_file}.tmp").open(mode="w", encoding="utf-8") as tmp_file: 

64 tmp_file.write(json.dumps(test_json)) 

65 tmp_file.write("\n") 

66 keys = list(test_json.keys()) 

67 assert esxport_obj._extract_headers() == keys 

68 TestExport.rm_export_file(f"{inspect.stack()[0].function}.csv")