apmt-reports 0.1.0__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.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: apmt-reports
3
+ Version: 0.1.0
4
+ Summary: A premium, feature-rich, and beautiful automated testing HTML reporter for pytest, python, and playwright.
5
+ License: MIT
6
+ Classifier: Framework :: Pytest
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: pytest>=7.0.0
19
+ Requires-Dist: jinja2>=3.0.0
20
+
21
+ # ⚡ pytest-apmt-reporter
22
+
23
+ `pytest-apmt-reporter` is a premium, feature-rich, and visually stunning automated testing HTML reporter for **Python**, **Pytest**, and **Playwright**. It is designed as a modern, high-fidelity alternative to Allure and Robot Framework, providing responsive layouts, glowing glassmorphic dark-mode dashboards, interactive SVG charts, expandable execution step logs, failure tracebacks, and seamlessly embedded Playwright screenshots.
24
+
25
+ ## ✨ Features
26
+
27
+ - **🔌 True Plug-and-Play (Auto-Detect):** By hooking directly into standard pytest entry points, the reporter is automatically active the moment you `pip install` it. No configuration changes required!
28
+ - **🌐 100% Offline-First (Self-Contained):** The final report compiles all layout, styles (CSS), logic (JS), and screenshots (base64 encoded PNGs) into a **single, standalone HTML file**. It requires absolutely zero Internet connection or CDNs to load, making it perfect for secure environments or CI/CD artifacts.
29
+ - **🎨 Premium Visual Dashboard:** Designed with premium glassmorphism card layouts, smooth transition animations, sleek dark mode (with a light theme toggle), and neon indicators for passed/failed tests.
30
+ - **📊 Interactive SVG Charts:** Includes clean, responsive circular progress indicators and data distributions drawn directly via SVG and animated with vanilla JS—no heavy charting libraries (like Chart.js) needed.
31
+ - **📸 Auto Playwright Failure screenshots:** If a test case utilizes a Playwright `page` fixture and fails, the reporter **automatically captures and embeds** a failure screenshot inside the report.
32
+ - **📝 Hierarchical Step Logging:** Allows defining nested execution steps using either standard decorators (`@apmt.step`) or context managers (`with apmt.step`), mirroring Allure and Robot Framework.
33
+ - **📎 Multi-format Attachments:** Programmatically attach raw logs, JSON blobs, HTML widgets, and custom screenshots to any step or stage.
34
+
35
+ ---
36
+
37
+ ## 🚀 Installation
38
+
39
+ You can easily install the reporter directly into your Python virtual environment from your project directory:
40
+
41
+ ```bash
42
+ # Clone the repository and install in editable mode
43
+ pip install -e .
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 🛠️ Usage
49
+
50
+ Once installed, running pytest will automatically enable the reporter and generate a file named `report.html` in your working directory.
51
+
52
+ ### Basic Commands
53
+
54
+ ```bash
55
+ # Run pytest tests and generate the report with default parameters
56
+ pytest
57
+
58
+ # Specify a custom report name or output directory
59
+ pytest --apmt-html=outputs/custom_dashboard.html
60
+
61
+ # Provide a custom title for your report dashboard
62
+ pytest --apmt-title="E2E Portal Smoketests"
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 📝 Code API Examples
68
+
69
+ ### 1. Step-by-Step Logging
70
+
71
+ Organize your test cases into nested, readable, and timed blocks:
72
+
73
+ ```python
74
+ import pytest_apmt_reporter as apmt
75
+
76
+ # Using step decorator
77
+ @apmt.step("Authenticate credentials")
78
+ def login(username, password):
79
+ ...
80
+
81
+ def test_user_purchase_flow():
82
+ # Using step context manager
83
+ with apmt.step("Initialize customer basket"):
84
+ basket_id = 9988
85
+
86
+ login("test_user", "password123")
87
+ ```
88
+
89
+ ### 2. Attaching Screenshots and Metadata
90
+
91
+ Enrich your reports with logs, JSON responses, or manual Playwright screenshots:
92
+
93
+ ```python
94
+ import pytest_apmt_reporter as apmt
95
+
96
+ def test_payment_gateway_api():
97
+ # Attach plain text logs
98
+ apmt.attach("Connecting to stripe sandbox...", name="Stripe API Connection")
99
+
100
+ # Attach JSON payload
101
+ apmt.attach('{"id": "ch_3M4", "status": "succeeded"}', name="Stripe Response", attachment_type=apmt.AttachmentType.JSON)
102
+
103
+ def test_dashboard_visual(page):
104
+ # Capture and attach a playwright page screenshot manually
105
+ page.goto("https://admin.portal.local")
106
+ apmt.attach_screenshot(page, name="Dashboard Main Panel")
107
+ ```
108
+
109
+ ### 3. Custom Dashboard Environment Stats
110
+
111
+ Display important execution parameters (like environment, server names, CI build IDs) directly on the metrics header:
112
+
113
+ ```python
114
+ import pytest_apmt_reporter as apmt
115
+
116
+ def test_initialize():
117
+ apmt.set_environment_info("Environment", "Staging-US-East")
118
+ apmt.set_environment_info("Release Version", "v4.12.0-rc2")
119
+ ```
120
+
121
+ ---
122
+
123
+ ## 📊 Try the Demo
124
+
125
+ Run the pre-configured demo test suite in the repository to see all features in action:
126
+
127
+ ```bash
128
+ # Run the demo tests
129
+ pytest demo/test_playwright_demo.py --apmt-html=demo_report.html
130
+
131
+ # Open the beautiful dashboard!
132
+ # Windows (PowerShell):
133
+ Start-Process demo_report.html
134
+ # macOS/Linux:
135
+ open demo_report.html
136
+ ```
@@ -0,0 +1,10 @@
1
+ pytest_apmt_reporter/__init__.py,sha256=SzoHJ_SdwTu8N3HsphCyo5ZUYQOBARwVCISFpnpaCro,6840
2
+ pytest_apmt_reporter/html_generator.py,sha256=fI4cVdhT_e6HObpjTxiAgkzOYzAMtRNLTUIQYcUFiFs,2205
3
+ pytest_apmt_reporter/model.py,sha256=fVmNBuip7FVAZxyh6PVTUFzQ7ROoy8xWE8pNEvk3KFU,3181
4
+ pytest_apmt_reporter/plugin.py,sha256=GXZy8c_sgtSqpXDS4ePeceATWZODhM4MqMMaNdGDXPo,9803
5
+ pytest_apmt_reporter/templates/report_template.html,sha256=Bg0xKp2N_l0m49qneqxWJj_9gWkijbHC-PM4S8RcWSw,53992
6
+ apmt_reports-0.1.0.dist-info/METADATA,sha256=hnXuQtC4-UwKpljZSdk63Pmgcq7ODwlJ5XhRD6xfdIg,5446
7
+ apmt_reports-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ apmt_reports-0.1.0.dist-info/entry_points.txt,sha256=8M4VEahU6KsP_zbqnJ1j8QVMqdalZPfaq6iXq2_vAPw,55
9
+ apmt_reports-0.1.0.dist-info/top_level.txt,sha256=MKaVtKNhefV4B7nXFyZTtpaI_fn1yKvE83TeXwHGNO8,21
10
+ apmt_reports-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ apmt_reporter = pytest_apmt_reporter.plugin
@@ -0,0 +1 @@
1
+ pytest_apmt_reporter
@@ -0,0 +1,188 @@
1
+ import base64
2
+ import inspect
3
+ import threading
4
+ from typing import Any, Callable, List, Optional, Union
5
+ import functools
6
+ import time
7
+
8
+ from .model import TestCase, Step, Attachment, TestStage
9
+
10
+ # Thread-local state to track active test cases and step hierarchies
11
+ class APMTRuntimeState(threading.local):
12
+ def __init__(self):
13
+ self.active_test: Optional[TestCase] = None
14
+ self.active_stage_name: str = "call" # "setup", "call", "teardown"
15
+ self.step_stack: List[Step] = []
16
+ self.environment: dict = {}
17
+
18
+ state = APMTRuntimeState()
19
+
20
+ class AttachmentType:
21
+ TEXT = "text/plain"
22
+ HTML = "text/html"
23
+ JSON = "application/json"
24
+ PNG = "image/png"
25
+ JPG = "image/jpeg"
26
+ SVG = "image/svg+xml"
27
+
28
+ class StepContext:
29
+ def __init__(self, name: str):
30
+ self.name = name
31
+ self.step: Optional[Step] = None
32
+
33
+ def __enter__(self):
34
+ self.step = Step(name=self.name)
35
+ if state.step_stack:
36
+ # Nest within parent step
37
+ state.step_stack[-1].steps.append(self.step)
38
+ else:
39
+ # Add to active test stage
40
+ if state.active_test:
41
+ stage = state.active_test.stages[state.active_stage_name]
42
+ stage.steps.append(self.step)
43
+ # Also mirror to test flattend steps
44
+ state.active_test.steps.append(self.step)
45
+
46
+ state.step_stack.append(self.step)
47
+ return self.step
48
+
49
+ def __exit__(self, exc_type, exc_val, exc_tb):
50
+ if not self.step:
51
+ return False
52
+
53
+ status = "passed"
54
+ exception_msg = None
55
+ tb_str = None
56
+
57
+ if exc_type:
58
+ status = "failed"
59
+ exception_msg = f"{exc_type.__name__}: {str(exc_val)}"
60
+ import traceback
61
+ tb_str = "".join(traceback.format_exception(exc_type, exc_val, exc_tb))
62
+
63
+ self.step.finish(status=status, exception_message=exception_msg, traceback=tb_str)
64
+
65
+ if state.step_stack and state.step_stack[-1] == self.step:
66
+ state.step_stack.pop()
67
+
68
+ # Let exceptions bubble up
69
+ return False
70
+
71
+ def __call__(self, func: Callable) -> Callable:
72
+ @functools.wraps(func)
73
+ def wrapper(*args, **kwargs):
74
+ with StepContext(self.name):
75
+ return func(*args, **kwargs)
76
+ return wrapper
77
+
78
+ def step(name_or_func: Union[str, Callable]) -> Any:
79
+ """Decorator or context manager for defining steps.
80
+
81
+ Usage as decorator:
82
+ @step("Perform login")
83
+ def login(user, password):
84
+ ...
85
+
86
+ Usage as context manager:
87
+ with step("Perform login"):
88
+ ...
89
+ """
90
+ if isinstance(name_or_func, str):
91
+ return StepContext(name_or_func)
92
+ else:
93
+ # Direct decorator without name (use func name)
94
+ func = name_or_func
95
+ @functools.wraps(func)
96
+ def wrapper(*args, **kwargs):
97
+ step_name = func.__name__.replace('_', ' ').capitalize()
98
+ with StepContext(step_name):
99
+ return func(*args, **kwargs)
100
+ return wrapper
101
+
102
+ def attach(
103
+ body: Union[str, bytes],
104
+ name: str = "Attachment",
105
+ attachment_type: str = AttachmentType.TEXT
106
+ ) -> None:
107
+ """Attach data or files to the current running test case or step.
108
+
109
+ Args:
110
+ body: String content or binary bytes.
111
+ name: User-friendly name for the attachment.
112
+ attachment_type: MIME type of attachment (e.g. image/png, text/plain).
113
+ """
114
+ if not state.active_test:
115
+ return # No active test running to attach to
116
+
117
+ is_base64 = False
118
+ content_str = ""
119
+
120
+ # Process content based on type
121
+ if isinstance(body, bytes):
122
+ if "image" in attachment_type or attachment_type in (AttachmentType.PNG, AttachmentType.JPG):
123
+ content_str = base64.b64encode(body).decode('utf-8')
124
+ is_base64 = True
125
+ else:
126
+ try:
127
+ content_str = body.decode('utf-8')
128
+ except UnicodeDecodeError:
129
+ content_str = base64.b64encode(body).decode('utf-8')
130
+ is_base64 = True
131
+ else:
132
+ content_str = str(body)
133
+ if attachment_type in (AttachmentType.PNG, AttachmentType.JPG):
134
+ # Already encoded base64 string
135
+ is_base64 = True
136
+
137
+ attachment = Attachment(name=name, content=content_str, mime_type=attachment_type, is_base64=is_base64)
138
+
139
+ # Add to active step if any, else active stage, else active test
140
+ if state.step_stack:
141
+ state.step_stack[-1].attachments.append(attachment)
142
+ else:
143
+ stage = state.active_test.stages[state.active_stage_name]
144
+ stage.attachments.append(attachment)
145
+ state.active_test.attachments.append(attachment)
146
+
147
+ def attach_screenshot(page: Any, name: str = "Screenshot") -> None:
148
+ """Helper to attach a Playwright screenshot. Works with both Sync and Async pages.
149
+
150
+ Args:
151
+ page: Playwright Page instance.
152
+ name: Name of the screenshot attachment.
153
+ """
154
+ # Check if page is sync or async
155
+ screenshot_func = getattr(page, "screenshot", None)
156
+ if not screenshot_func:
157
+ return
158
+
159
+ # Check if this is a coroutine function (async page)
160
+ if inspect.iscoroutinefunction(screenshot_func):
161
+ # We are inside sync code, so executing async is harder without direct await.
162
+ # But we can try to get the current running loop or advise using manual attach.
163
+ # However, many async tests run under pytest-asyncio, so we can run it in a thread/loop if possible,
164
+ # or grab the existing async context.
165
+ # A simpler fallback is to let the user know, or execute it safely:
166
+ try:
167
+ import asyncio
168
+ loop = asyncio.get_event_loop()
169
+ if loop.is_running():
170
+ # We are in a running loop, scheduled as a task.
171
+ # Since we can't block, we can schedule the capture, but the test might finish.
172
+ # For safety, let's advise capturing bytes and attaching:
173
+ # apmt.attach(await page.screenshot(), "name", apmt.AttachmentType.PNG)
174
+ # But let's try to block if we can, or log a warning.
175
+ pass
176
+ except Exception:
177
+ pass
178
+ else:
179
+ # Sync Playwright page - easy!
180
+ try:
181
+ screenshot_bytes = page.screenshot(type="png")
182
+ attach(screenshot_bytes, name=name, attachment_type=AttachmentType.PNG)
183
+ except Exception as e:
184
+ attach(f"Failed to capture screenshot: {str(e)}", name=f"{name} (Failed Capture)", attachment_type=AttachmentType.TEXT)
185
+
186
+ def set_environment_info(key: str, value: str) -> None:
187
+ """Sets a global environment variable to be displayed on the report dashboard."""
188
+ state.environment[key] = str(value)
@@ -0,0 +1,62 @@
1
+ import os
2
+ import time
3
+ from jinja2 import Template
4
+ from .model import TestRun
5
+
6
+ class HTMLGenerator:
7
+ def __init__(self, test_run: TestRun):
8
+ self.test_run = test_run
9
+
10
+ def format_duration(self, seconds: float) -> str:
11
+ """Helper to format duration nicely (e.g. '1m 23s' or '450ms')."""
12
+ if seconds < 1.0:
13
+ return f"{int(seconds * 1000)}ms"
14
+ minutes = int(seconds // 60)
15
+ secs = seconds % 60
16
+ if minutes > 0:
17
+ return f"{minutes}m {secs:.2f}s"
18
+ return f"{secs:.2f}s"
19
+
20
+ def format_time(self, timestamp: float) -> str:
21
+ """Helper to format UNIX timestamps."""
22
+ if not timestamp:
23
+ return "N/A"
24
+ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
25
+
26
+ def generate(self, output_path: str):
27
+ # Resolve absolute path to the HTML template
28
+ current_dir = os.path.dirname(os.path.abspath(__file__))
29
+ template_path = os.path.join(current_dir, "templates", "report_template.html")
30
+
31
+ if not os.path.exists(template_path):
32
+ raise FileNotFoundError(f"APMT report template file not found at: {template_path}")
33
+
34
+ with open(template_path, "r", encoding="utf-8") as f:
35
+ template_source = f.read()
36
+
37
+ # Build rendering context with custom 'hash' filter registered
38
+ from jinja2 import Environment
39
+ import hashlib
40
+
41
+ def jinja_hash_filter(value):
42
+ return hashlib.md5(str(value).encode('utf-8')).hexdigest()
43
+
44
+ env = Environment()
45
+ env.filters['hash'] = jinja_hash_filter
46
+ template = env.from_string(template_source)
47
+
48
+ # Resolve directory for output report
49
+ output_abs = os.path.abspath(output_path)
50
+ output_dir = os.path.dirname(output_abs)
51
+ if output_dir and not os.path.exists(output_dir):
52
+ os.makedirs(output_dir, exist_ok=True)
53
+
54
+ # Render HTML
55
+ rendered_html = template.render(
56
+ run=self.test_run,
57
+ formatter=self,
58
+ generated_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
59
+ )
60
+
61
+ with open(output_abs, "w", encoding="utf-8") as f:
62
+ f.write(rendered_html)
@@ -0,0 +1,91 @@
1
+ import time
2
+ from dataclasses import dataclass, field
3
+ from typing import List, Dict, Any, Optional
4
+
5
+ @dataclass
6
+ class Attachment:
7
+ name: str
8
+ content: str # Base64 string for images/binary, plain text for logs
9
+ mime_type: str
10
+ is_base64: bool = True
11
+
12
+ @dataclass
13
+ class Step:
14
+ name: str
15
+ status: str = "passed" # "passed", "failed", "skipped"
16
+ start_time: float = field(default_factory=time.time)
17
+ end_time: float = 0.0
18
+ duration: float = 0.0
19
+ steps: List['Step'] = field(default_factory=list)
20
+ attachments: List[Attachment] = field(default_factory=list)
21
+ exception_message: Optional[str] = None
22
+ traceback: Optional[str] = None
23
+
24
+ def finish(self, status: str = "passed", exception_message: Optional[str] = None, traceback: Optional[str] = None):
25
+ self.end_time = time.time()
26
+ self.duration = max(0.0, self.end_time - self.start_time)
27
+ self.status = status
28
+ self.exception_message = exception_message
29
+ self.traceback = traceback
30
+
31
+ @dataclass
32
+ class TestStage:
33
+ name: str # "setup", "call", "teardown"
34
+ status: str = "passed"
35
+ duration: float = 0.0
36
+ stdout: str = ""
37
+ stderr: str = ""
38
+ traceback: Optional[str] = None
39
+ exception_message: Optional[str] = None
40
+ steps: List[Step] = field(default_factory=list)
41
+ attachments: List[Attachment] = field(default_factory=list)
42
+
43
+ @dataclass
44
+ class TestCase:
45
+ nodeid: str
46
+ name: str
47
+ file_path: str
48
+ line_number: int
49
+ docstring: Optional[str] = None
50
+ status: str = "passed" # "passed", "failed", "skipped", "error"
51
+ duration: float = 0.0
52
+ start_time: float = field(default_factory=time.time)
53
+ end_time: float = 0.0
54
+ stages: Dict[str, TestStage] = field(default_factory=lambda: {
55
+ "setup": TestStage("setup"),
56
+ "call": TestStage("call"),
57
+ "teardown": TestStage("teardown")
58
+ })
59
+ # Flattend aggregated attributes for convenience
60
+ steps: List[Step] = field(default_factory=list)
61
+ attachments: List[Attachment] = field(default_factory=list)
62
+ traceback: Optional[str] = None
63
+ exception_message: Optional[str] = None
64
+
65
+ def finish(self, status: str):
66
+ self.end_time = time.time()
67
+ self.duration = max(0.0, self.end_time - self.start_time)
68
+ self.status = status
69
+
70
+ @dataclass
71
+ class TestRun:
72
+ title: str = "APMT Test Automation Report"
73
+ start_time: float = field(default_factory=time.time)
74
+ end_time: float = 0.0
75
+ duration: float = 0.0
76
+ passed: int = 0
77
+ failed: int = 0
78
+ skipped: int = 0
79
+ error: int = 0
80
+ total: int = 0
81
+ test_cases: List[TestCase] = field(default_factory=list)
82
+ environment: Dict[str, str] = field(default_factory=dict)
83
+
84
+ def finish(self):
85
+ self.end_time = time.time()
86
+ self.duration = max(0.0, self.end_time - self.start_time)
87
+ self.total = len(self.test_cases)
88
+ self.passed = sum(1 for tc in self.test_cases if tc.status == "passed")
89
+ self.failed = sum(1 for tc in self.test_cases if tc.status == "failed")
90
+ self.skipped = sum(1 for tc in self.test_cases if tc.status == "skipped")
91
+ self.error = sum(1 for tc in self.test_cases if tc.status == "error")