pytest-jux 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pytest_jux/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ # Copyright 2025 Georges Martin
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ pytest-jux: A pytest plugin for signing and publishing JUnit XML test reports.
17
+
18
+ This plugin integrates with pytest to automatically:
19
+ 1. Sign JUnit XML test reports using XML digital signatures (XMLDSig)
20
+ 2. Calculate canonical hashes for duplicate detection
21
+ 3. Publish signed reports to a Jux REST API backend
22
+ """
23
+
24
+ __version__ = "0.1.5"
25
+ __author__ = "Georges Martin"
26
+ __email__ = "jrjsmrtn@gmail.com"
27
+
28
+ # Import plugin hooks when plugin module is available
29
+ try: # pragma: no cover
30
+ from pytest_jux.plugin import pytest_addoption, pytest_configure
31
+
32
+ __all__ = ["pytest_addoption", "pytest_configure", "__version__"]
33
+ except ImportError: # pragma: no cover
34
+ # Plugin module not yet implemented
35
+ __all__ = ["__version__"]
@@ -0,0 +1,129 @@
1
+ # Copyright 2025 Georges Martin
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """XML canonicalization and hashing for JUnit XML reports.
16
+
17
+ This module provides functionality to canonicalize JUnit XML reports using
18
+ the XML Canonicalization (C14N) algorithm and compute cryptographic hashes
19
+ of the canonical form for duplicate detection.
20
+ """
21
+
22
+ import hashlib
23
+ from pathlib import Path
24
+ from typing import cast # pragma: no cover
25
+
26
+ from lxml import etree
27
+
28
+
29
+ def load_xml(source: str | bytes | Path) -> etree._Element:
30
+ """Load XML from various sources.
31
+
32
+ Args:
33
+ source: XML source - can be:
34
+ - Path to XML file
35
+ - XML string
36
+ - XML bytes
37
+
38
+ Returns:
39
+ Parsed XML element tree root
40
+
41
+ Raises:
42
+ FileNotFoundError: If file path doesn't exist
43
+ etree.XMLSyntaxError: If XML is malformed
44
+ """
45
+ if isinstance(source, Path):
46
+ if not source.exists():
47
+ raise FileNotFoundError(f"XML file not found: {source}")
48
+ with open(source, "rb") as f:
49
+ return etree.parse(f).getroot()
50
+
51
+ if isinstance(source, str):
52
+ source = source.encode("utf-8")
53
+
54
+ return etree.fromstring(source)
55
+
56
+
57
+ def canonicalize_xml(
58
+ tree: etree._Element,
59
+ exclusive: bool = False,
60
+ with_comments: bool = False,
61
+ ) -> bytes:
62
+ """Canonicalize XML using C14N algorithm.
63
+
64
+ Converts XML to canonical form (C14N) which normalizes:
65
+ - Whitespace
66
+ - Attribute order
67
+ - Namespace declarations
68
+ - Comments (excluded by default)
69
+
70
+ This ensures that semantically equivalent XML produces identical
71
+ canonical output, enabling reliable duplicate detection via hashing.
72
+
73
+ Args:
74
+ tree: XML element tree to canonicalize
75
+ exclusive: Use exclusive canonicalization (default: False)
76
+ with_comments: Include comments in canonical form (default: False)
77
+
78
+ Returns:
79
+ Canonical XML as bytes
80
+
81
+ Raises:
82
+ TypeError: If tree is not an lxml element
83
+ """
84
+ if not isinstance(tree, etree._Element):
85
+ raise TypeError(f"Expected lxml Element, got {type(tree)}")
86
+
87
+ # etree.tostring with method="c14n" always returns bytes
88
+ return cast(
89
+ bytes,
90
+ etree.tostring(
91
+ tree,
92
+ method="c14n",
93
+ exclusive=exclusive,
94
+ with_comments=with_comments,
95
+ ),
96
+ )
97
+
98
+
99
+ def compute_canonical_hash(
100
+ tree: etree._Element,
101
+ algorithm: str = "sha256",
102
+ ) -> str:
103
+ """Compute cryptographic hash of canonical XML.
104
+
105
+ Canonicalizes the XML and computes a cryptographic hash of the
106
+ canonical form. This hash can be used for:
107
+ - Duplicate detection
108
+ - Content verification
109
+ - Change detection
110
+
111
+ Args:
112
+ tree: XML element tree to hash
113
+ algorithm: Hash algorithm to use (default: "sha256")
114
+
115
+ Returns:
116
+ Hexadecimal hash digest string
117
+
118
+ Raises:
119
+ ValueError: If hash algorithm is not supported
120
+ TypeError: If tree is not an lxml element
121
+ """
122
+ if algorithm not in hashlib.algorithms_available:
123
+ raise ValueError(f"Unsupported hash algorithm: {algorithm}")
124
+
125
+ canonical = canonicalize_xml(tree)
126
+ hasher = hashlib.new(algorithm)
127
+ hasher.update(canonical)
128
+
129
+ return hasher.hexdigest()
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 Georges Martin
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """CLI commands for pytest-jux."""
@@ -0,0 +1,357 @@
1
+ # Copyright 2025 Georges Martin
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Cache management command for pytest-jux."""
16
+
17
+ import argparse
18
+ import json
19
+ import sys
20
+ from datetime import datetime, timedelta
21
+ from pathlib import Path
22
+
23
+ from pytest_jux.storage import ReportStorage, StorageError, get_default_storage_path
24
+
25
+
26
+ def cmd_list(args: argparse.Namespace) -> int:
27
+ """List all cached reports.
28
+
29
+ Args:
30
+ args: Command-line arguments
31
+
32
+ Returns:
33
+ Exit code (0 = success, 1 = error)
34
+ """
35
+ try:
36
+ storage_path = (
37
+ Path(args.storage_path) if args.storage_path else get_default_storage_path()
38
+ )
39
+ storage = ReportStorage(storage_path=storage_path)
40
+
41
+ reports = storage.list_reports()
42
+
43
+ if args.json:
44
+ # JSON output
45
+ report_data = []
46
+ for report_hash in reports:
47
+ try:
48
+ metadata = storage.get_metadata(report_hash)
49
+ report_file = storage_path / "reports" / f"{report_hash}.xml"
50
+ report_data.append(
51
+ {
52
+ "hash": report_hash,
53
+ "timestamp": metadata.timestamp,
54
+ "hostname": metadata.hostname,
55
+ "size": report_file.stat().st_size
56
+ if report_file.exists()
57
+ else 0,
58
+ }
59
+ )
60
+ except StorageError:
61
+ # Skip reports with missing metadata
62
+ continue
63
+
64
+ output = {"reports": report_data, "total": len(report_data)}
65
+ print(json.dumps(output, indent=2))
66
+ else:
67
+ # Text output
68
+ if not reports:
69
+ print("No cached reports found.")
70
+ else:
71
+ print(f"Cached Reports ({len(reports)} total):")
72
+ print()
73
+ for report_hash in reports:
74
+ try:
75
+ metadata = storage.get_metadata(report_hash)
76
+ print(f" {report_hash}")
77
+ print(f" Timestamp: {metadata.timestamp}")
78
+ print(f" Hostname: {metadata.hostname}")
79
+ print(f" Username: {metadata.username}")
80
+ print()
81
+ except StorageError:
82
+ print(f" {report_hash} (metadata missing)")
83
+ print()
84
+
85
+ return 0
86
+
87
+ except Exception as e:
88
+ print(f"Error listing reports: {e}", file=sys.stderr)
89
+ return 1
90
+
91
+
92
+ def cmd_show(args: argparse.Namespace) -> int:
93
+ """Show details for a specific cached report.
94
+
95
+ Args:
96
+ args: Command-line arguments
97
+
98
+ Returns:
99
+ Exit code (0 = success, 1 = error)
100
+ """
101
+ try:
102
+ storage_path = (
103
+ Path(args.storage_path) if args.storage_path else get_default_storage_path()
104
+ )
105
+ storage = ReportStorage(storage_path=storage_path)
106
+
107
+ report_hash = args.hash
108
+
109
+ # Get report and metadata
110
+ report_xml = storage.get_report(report_hash)
111
+ metadata = storage.get_metadata(report_hash)
112
+
113
+ if args.json:
114
+ # JSON output
115
+ output = {
116
+ "hash": report_hash,
117
+ "metadata": metadata.to_dict(),
118
+ "report": report_xml.decode("utf-8"),
119
+ "size": len(report_xml),
120
+ }
121
+ print(json.dumps(output, indent=2))
122
+ else:
123
+ # Text output
124
+ print(f"Report: {report_hash}")
125
+ print()
126
+ print("Metadata:")
127
+ print(f" Hostname: {metadata.hostname}")
128
+ print(f" Username: {metadata.username}")
129
+ print(f" Platform: {metadata.platform}")
130
+ print(f" Python Version: {metadata.python_version}")
131
+ print(f" pytest Version: {metadata.pytest_version}")
132
+ print(f" Timestamp: {metadata.timestamp}")
133
+ if metadata.env:
134
+ print(" Environment:")
135
+ for key, value in metadata.env.items():
136
+ print(f" {key}: {value}")
137
+ print()
138
+ print(f"Report Content ({len(report_xml)} bytes):")
139
+ print(report_xml.decode("utf-8"))
140
+
141
+ return 0
142
+
143
+ except StorageError:
144
+ print(f"Error: Report not found: {args.hash}", file=sys.stderr)
145
+ return 1
146
+ except Exception as e:
147
+ print(f"Error showing report: {e}", file=sys.stderr)
148
+ return 1
149
+
150
+
151
+ def cmd_stats(args: argparse.Namespace) -> int:
152
+ """Show cache statistics.
153
+
154
+ Args:
155
+ args: Command-line arguments
156
+
157
+ Returns:
158
+ Exit code (0 = success)
159
+ """
160
+ try:
161
+ storage_path = (
162
+ Path(args.storage_path) if args.storage_path else get_default_storage_path()
163
+ )
164
+ storage = ReportStorage(storage_path=storage_path)
165
+
166
+ stats = storage.get_stats()
167
+
168
+ if args.json:
169
+ # JSON output
170
+ print(json.dumps(stats, indent=2))
171
+ else:
172
+ # Text output
173
+ print("Cache Statistics:")
174
+ print()
175
+ print(f" Total Reports: {stats['total_reports']}")
176
+ print(f" Queued Reports: {stats['queued_reports']}")
177
+ print(f" Total Size: {_format_size(stats['total_size'])}")
178
+ if stats["oldest_report"]:
179
+ print(f" Oldest Report: {stats['oldest_report']}")
180
+ else:
181
+ print(" Oldest Report: (none)")
182
+
183
+ return 0
184
+
185
+ except Exception as e:
186
+ print(f"Error getting statistics: {e}", file=sys.stderr)
187
+ return 1
188
+
189
+
190
+ def cmd_clean(args: argparse.Namespace) -> int:
191
+ """Clean old cached reports.
192
+
193
+ Args:
194
+ args: Command-line arguments
195
+
196
+ Returns:
197
+ Exit code (0 = success, 1 = error)
198
+ """
199
+ try:
200
+ storage_path = (
201
+ Path(args.storage_path) if args.storage_path else get_default_storage_path()
202
+ )
203
+ storage = ReportStorage(storage_path=storage_path)
204
+
205
+ cutoff_time = datetime.now() - timedelta(days=args.days)
206
+ cutoff_timestamp = cutoff_time.timestamp()
207
+
208
+ reports = storage.list_reports()
209
+ reports_to_delete = []
210
+
211
+ # Find reports older than cutoff
212
+ for report_hash in reports:
213
+ report_file = storage_path / "reports" / f"{report_hash}.xml"
214
+ if report_file.exists():
215
+ mtime = report_file.stat().st_mtime
216
+ if mtime < cutoff_timestamp:
217
+ reports_to_delete.append(report_hash)
218
+
219
+ if args.dry_run:
220
+ # Dry run - show what would be deleted
221
+ if reports_to_delete:
222
+ print(f"Dry run: Would remove {len(reports_to_delete)} report(s):")
223
+ for report_hash in reports_to_delete:
224
+ print(f" {report_hash}")
225
+ else:
226
+ print(f"Dry run: No reports older than {args.days} days found.")
227
+ else:
228
+ # Actually delete
229
+ if reports_to_delete:
230
+ for report_hash in reports_to_delete:
231
+ storage.delete_report(report_hash)
232
+ print(
233
+ f"Removed {len(reports_to_delete)} report(s) older than {args.days} days."
234
+ )
235
+ else:
236
+ print(f"No reports older than {args.days} days found.")
237
+
238
+ return 0
239
+
240
+ except Exception as e:
241
+ print(f"Error cleaning cache: {e}", file=sys.stderr)
242
+ return 1
243
+
244
+
245
+ def _format_size(size_bytes: int) -> str:
246
+ """Format byte size in human-readable format.
247
+
248
+ Args:
249
+ size_bytes: Size in bytes
250
+
251
+ Returns:
252
+ Formatted size string (e.g., "1.5 MB")
253
+ """
254
+ size_float = float(size_bytes)
255
+ for unit in ["B", "KB", "MB", "GB", "TB"]:
256
+ if size_float < 1024.0:
257
+ return f"{size_float:.1f} {unit}"
258
+ size_float /= 1024.0
259
+ return f"{size_float:.1f} PB"
260
+
261
+
262
+ def create_parser() -> argparse.ArgumentParser:
263
+ """Create argument parser for cache command.
264
+
265
+ Returns:
266
+ Configured ArgumentParser
267
+ """
268
+ parser = argparse.ArgumentParser(
269
+ prog="jux-cache",
270
+ description="Manage pytest-jux cached reports",
271
+ )
272
+
273
+ parser.add_argument(
274
+ "--storage-path",
275
+ type=str,
276
+ help="Custom storage directory path",
277
+ )
278
+
279
+ subparsers = parser.add_subparsers(dest="command", help="Subcommand to run")
280
+
281
+ # List subcommand
282
+ parser_list = subparsers.add_parser("list", help="List all cached reports")
283
+ parser_list.add_argument(
284
+ "--json",
285
+ action="store_true",
286
+ help="Output in JSON format",
287
+ )
288
+
289
+ # Show subcommand
290
+ parser_show = subparsers.add_parser("show", help="Show report details")
291
+ parser_show.add_argument(
292
+ "hash",
293
+ help="Report canonical hash",
294
+ )
295
+ parser_show.add_argument(
296
+ "--json",
297
+ action="store_true",
298
+ help="Output in JSON format",
299
+ )
300
+
301
+ # Stats subcommand
302
+ parser_stats = subparsers.add_parser("stats", help="Show cache statistics")
303
+ parser_stats.add_argument(
304
+ "--json",
305
+ action="store_true",
306
+ help="Output in JSON format",
307
+ )
308
+
309
+ # Clean subcommand
310
+ parser_clean = subparsers.add_parser("clean", help="Remove old reports")
311
+ parser_clean.add_argument(
312
+ "--days",
313
+ type=int,
314
+ required=True,
315
+ help="Remove reports older than N days",
316
+ )
317
+ parser_clean.add_argument(
318
+ "--dry-run",
319
+ action="store_true",
320
+ help="Show what would be removed without actually deleting",
321
+ )
322
+
323
+ return parser
324
+
325
+
326
+ def main(argv: list[str] | None = None) -> int:
327
+ """Main entry point for cache command.
328
+
329
+ Args:
330
+ argv: Command-line arguments (default: sys.argv[1:])
331
+
332
+ Returns:
333
+ Exit code (0 = success, 1 = error, 2 = usage error)
334
+ """
335
+ parser = create_parser()
336
+ args = parser.parse_args(argv)
337
+
338
+ if not args.command:
339
+ parser.print_help()
340
+ return 2
341
+
342
+ # Dispatch to subcommand handler
343
+ if args.command == "list":
344
+ return cmd_list(args)
345
+ elif args.command == "show":
346
+ return cmd_show(args)
347
+ elif args.command == "stats":
348
+ return cmd_stats(args)
349
+ elif args.command == "clean":
350
+ return cmd_clean(args)
351
+ else:
352
+ parser.print_help()
353
+ return 2
354
+
355
+
356
+ if __name__ == "__main__":
357
+ sys.exit(main())