Coverage for src/pytest_gitlab_code_quality/recorder.py: 95%

19 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-03 22:19 +0200

1from dataclasses import asdict 

2from io import TextIOWrapper 

3from json import dumps 

4 

5from pytest_gitlab_code_quality.report import Violation 

6 

7 

8class ViolationRecorder: 

9 """ 

10 Records violations by streaming them to a file. 

11 """ 

12 

13 def __init__(self, file: TextIOWrapper) -> None: 

14 self._file = file 

15 self._first = True 

16 

17 def prepare(self) -> None: 

18 """ 

19 Writes an initial opening array bracket to the file. 

20 """ 

21 _ = self._file.write("[\n") 

22 

23 def record(self, violation: Violation) -> None: 

24 """ 

25 Writes a line containing the violation to the file. 

26 """ 

27 serialized = dumps(asdict(violation)) 

28 if self._first: 

29 self._first = False 

30 else: 

31 serialized = f",\n{serialized}" 

32 

33 _ = self._file.write(serialized) 

34 

35 def close(self) -> None: 

36 """ 

37 Closes the violation array and the file. 

38 """ 

39 _ = self._file.write("\n]\n") 

40 self._file.close()