Coverage for tests/fixtures.py: 92%

27 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-04-21 11:16 +0000

1"""Pytest fixtures.""" 

2 

3 

4import logging 

5import os 

6import shutil 

7from collections.abc import Iterator 

8 

9import pytest 

10 

11#: Base path to artifacts generated by the tests. 

12ARTIFACTS_PATH = os.path.join(os.path.normpath(os.path.dirname(__file__)), ".artifacts") 

13 

14 

15@pytest.fixture() 

16def adir(request: pytest.FixtureRequest) -> Iterator[str]: 

17 """A fixture that generates the specified folder in the artifacts directory, and provides it 

18 as a path to the tests. 

19 

20 The example below shows an example on how to use the fixture and its parameters: 

21 

22 .. code-block:: python 

23 

24 @pytest.mark.parametrize("adir", ["images"], indirect=True) 

25 def test_example(adir: str): 

26 pass 

27 

28 :param request: The Pytest request object. 

29 :return: The sample.""" 

30 # Fetch parameters from request. 

31 dir_name: str = request.param 

32 

33 if not os.path.exists(new_dir := os.path.join(ARTIFACTS_PATH, dir_name)): 

34 os.makedirs(new_dir) 

35 

36 yield new_dir 

37 

38 

39@pytest.fixture(autouse=True, scope="session") 

40def logger(request: pytest.FixtureRequest) -> Iterator[logging.Logger]: 

41 """Prepares the logger for the package and other functionality for testing. 

42 

43 :param request: The Pytest request object. 

44 :return: The logger used within the package.""" 

45 # pylint: disable=unused-argument 

46 

47 # If the artifacts path exists at the beginning of the session, then delete it entirely, and create it anew. 

48 if os.path.exists(ARTIFACTS_PATH): 48 ↛ 49line 48 didn't jump to line 49, because the condition on line 48 was never true

49 shutil.rmtree(ARTIFACTS_PATH) 

50 os.makedirs(ARTIFACTS_PATH) 

51 

52 # Disable matplotlib debug messages about fonts, as they pollute the reports. 

53 logging.getLogger("matplotlib.font_manager").setLevel(logging.INFO) 

54 

55 # Get package logger. 

56 logger_obj = logging.getLogger("python-signal-edges-logger") 

57 # Check if already initialized, in which case do nothing. 

58 if not getattr(logger_obj, "init", False): 58 ↛ 74line 58 didn't jump to line 74, because the condition on line 58 was never false

59 # Set logger level. 

60 logger_obj.setLevel(logging.DEBUG) 

61 # Configure stream to file and with specific formatting. 

62 tests_log_path = os.path.join(ARTIFACTS_PATH, "tests.log") 

63 stream_handler = logging.FileHandler(tests_log_path, mode="w+") 

64 stream_handler.setFormatter( 

65 logging.Formatter( 

66 r"[%(asctime)s.%(msecs)03d] [%(levelname)5.5s] [%(module)s:%(lineno)d] %(message)s", 

67 datefmt=r"%d/%m/%Y %H:%M:%S", 

68 ) 

69 ) 

70 logger_obj.addHandler(stream_handler) 

71 # Initialize logger for the package. 

72 setattr(logger_obj, "init", True) 

73 

74 yield logger_obj