Coverage for src/pytest_xray/file_publisher.py: 100.0%

28 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-06 12:46 +0000

1import json 

2import os 

3import tempfile 

4from pathlib import Path 

5 

6from pytest_xray.exceptions import XrayError 

7 

8 

9class FilePublisher: 

10 """Atomically export a complete Xray report, preserving any existing file on failure.""" 

11 

12 def __init__(self, filepath: str) -> None: 

13 self.filepath = Path(os.path.expandvars(filepath)).expanduser().resolve() 

14 

15 def publish(self, data: dict) -> str: 

16 temporary = None 

17 cleanup_detail = '' 

18 try: 

19 try: 

20 content = json.dumps(data, indent=2, allow_nan=False) 

21 self.filepath.parent.mkdir(parents=True, exist_ok=True) 

22 with tempfile.NamedTemporaryFile( 

23 mode='w', encoding='utf-8', dir=self.filepath.parent, delete=False 

24 ) as file: 

25 temporary = Path(file.name) 

26 file.write(content + '\n') 

27 os.replace(temporary, self.filepath) 

28 temporary = None 

29 finally: 

30 if temporary is not None: 

31 try: 

32 temporary.unlink(missing_ok=True) 

33 except OSError as cleanup_error: 

34 cleanup_detail = f'; could not remove temporary report {temporary}: {cleanup_error}' 

35 except (OSError, TypeError, ValueError) as exc: 

36 raise XrayError(f'Cannot export Xray results to file: {exc}{cleanup_detail}') from exc 

37 return str(self.filepath)