Coverage for src/pytest_xray/file_publisher.py: 95.8%
22 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 14:00 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 14:00 +0000
1import json
2import os
3import tempfile
4from pathlib import Path
6from pytest_xray.exceptions import XrayError
9class FilePublisher:
10 """Atomically export a complete Xray report, preserving any existing file on failure."""
12 def __init__(self, filepath: str) -> None:
13 self.filepath = Path(os.path.expandvars(filepath)).expanduser().resolve()
15 def publish(self, data: dict) -> str:
16 temporary = None
17 try:
18 content = json.dumps(data, indent=2, allow_nan=False)
19 self.filepath.parent.mkdir(parents=True, exist_ok=True)
20 with tempfile.NamedTemporaryFile(
21 mode='w', encoding='utf-8', dir=self.filepath.parent, delete=False
22 ) as file:
23 temporary = Path(file.name)
24 file.write(content + '\n')
25 os.replace(temporary, self.filepath)
26 except (OSError, TypeError, ValueError) as exc:
27 raise XrayError(f'Cannot export Xray results to file: {exc}') from exc
28 finally:
29 if temporary is not None: 29 ↛ 31line 29 didn't jump to line 31 because the condition on line 29 was always true
30 temporary.unlink(missing_ok=True)
31 return str(self.filepath)