robotframework-requests-log 1.0.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.
RequestsLog.py ADDED
@@ -0,0 +1,359 @@
1
+ import json
2
+ import html as html_module
3
+ import uuid
4
+ import shlex
5
+ import time
6
+
7
+ import requests
8
+ from robot.api import logger
9
+ from robot.api.deco import keyword
10
+
11
+ METHOD_COLORS = {
12
+ 'GET': '#10b981',
13
+ 'POST': '#3b82f6',
14
+ 'PUT': '#f59e0b',
15
+ 'PATCH': '#8b5cf6',
16
+ 'DELETE': '#ef4444',
17
+ 'HEAD': '#6b7280',
18
+ 'OPTIONS': '#6b7280',
19
+ }
20
+
21
+ BINARY_CONTENT_TYPES = ('image/', 'audio/', 'video/', 'application/octet-stream', 'application/pdf')
22
+ MAX_BODY_DISPLAY = 50_000
23
+
24
+
25
+ class RequestsLog:
26
+ ROBOT_LIBRARY_SCOPE = 'GLOBAL'
27
+ ROBOT_LIBRARY_DOC_FORMAT = 'ROBOT'
28
+ ROBOT_AUTO_KEYWORDS = True
29
+
30
+ def __init__(self):
31
+ self._session = requests.Session()
32
+
33
+ # ── Public keywords ────────────────────────────────────────────────────
34
+
35
+ @keyword
36
+ def GET(self, url, params=None, headers=None, timeout=30, verify=True,
37
+ expected_status=None, msg=None, **kwargs):
38
+ return self._make_request('GET', url, params=params, headers=headers,
39
+ timeout=timeout, verify=verify,
40
+ expected_status=expected_status, msg=msg, **kwargs)
41
+
42
+ @keyword
43
+ def POST(self, url, data=None, json=None, params=None, headers=None,
44
+ timeout=30, verify=True, expected_status=None, msg=None, **kwargs):
45
+ return self._make_request('POST', url, data=data, json=json, params=params,
46
+ headers=headers, timeout=timeout, verify=verify,
47
+ expected_status=expected_status, msg=msg, **kwargs)
48
+
49
+ @keyword
50
+ def PUT(self, url, data=None, json=None, params=None, headers=None,
51
+ timeout=30, verify=True, expected_status=None, msg=None, **kwargs):
52
+ return self._make_request('PUT', url, data=data, json=json, params=params,
53
+ headers=headers, timeout=timeout, verify=verify,
54
+ expected_status=expected_status, msg=msg, **kwargs)
55
+
56
+ @keyword
57
+ def PATCH(self, url, data=None, json=None, params=None, headers=None,
58
+ timeout=30, verify=True, expected_status=None, msg=None, **kwargs):
59
+ return self._make_request('PATCH', url, data=data, json=json, params=params,
60
+ headers=headers, timeout=timeout, verify=verify,
61
+ expected_status=expected_status, msg=msg, **kwargs)
62
+
63
+ @keyword
64
+ def DELETE(self, url, params=None, headers=None, timeout=30, verify=True,
65
+ expected_status=None, msg=None, **kwargs):
66
+ return self._make_request('DELETE', url, params=params, headers=headers,
67
+ timeout=timeout, verify=verify,
68
+ expected_status=expected_status, msg=msg, **kwargs)
69
+
70
+ @keyword
71
+ def HEAD(self, url, params=None, headers=None, timeout=30, verify=True,
72
+ expected_status=None, msg=None, **kwargs):
73
+ return self._make_request('HEAD', url, params=params, headers=headers,
74
+ timeout=timeout, verify=verify,
75
+ expected_status=expected_status, msg=msg, **kwargs)
76
+
77
+ @keyword
78
+ def OPTIONS(self, url, params=None, headers=None, timeout=30, verify=True,
79
+ expected_status=None, msg=None, **kwargs):
80
+ return self._make_request('OPTIONS', url, params=params, headers=headers,
81
+ timeout=timeout, verify=verify,
82
+ expected_status=expected_status, msg=msg, **kwargs)
83
+
84
+ # ── Core request dispatcher ────────────────────────────────────────────
85
+
86
+ def _make_request(self, method, url, expected_status=None, msg=None, **kwargs):
87
+ response = self._session.request(method, url, **kwargs)
88
+ card_id = uuid.uuid4().hex[:12]
89
+ self._log_card(response, card_id)
90
+ self._check_status(response, expected_status, msg)
91
+ return response
92
+
93
+ def _check_status(self, response, expected_status, msg=None):
94
+ if expected_status is None:
95
+ response.raise_for_status()
96
+ elif str(expected_status).lower() in ('any', 'anything'):
97
+ pass
98
+ else:
99
+ actual = response.status_code
100
+ expected = int(expected_status)
101
+ if actual != expected:
102
+ raise AssertionError(
103
+ msg or f'Expected status {expected} but got {actual}.'
104
+ )
105
+
106
+ # ── Card logging ───────────────────────────────────────────────────────
107
+
108
+ def _log_card(self, response, card_id):
109
+ req_data = self._extract_request_data(response)
110
+ resp_data = self._extract_response_data(response)
111
+ curl_str = self._build_curl_command(response)
112
+ html_str = self._build_card_html(req_data, resp_data, curl_str, card_id)
113
+ logger.info(html_str, html=True)
114
+
115
+ # ── Data extraction ────────────────────────────────────────────────────
116
+
117
+ def _extract_request_data(self, response):
118
+ req = response.request
119
+ body_raw = req.body
120
+ body_display, is_json = self._parse_body(body_raw)
121
+ return {
122
+ 'method': req.method,
123
+ 'url': req.url,
124
+ 'headers': dict(req.headers),
125
+ 'body_display': body_display,
126
+ 'body_is_json': is_json,
127
+ }
128
+
129
+ def _extract_response_data(self, response):
130
+ ct = response.headers.get('Content-Type', '')
131
+ if any(ct.startswith(b) for b in BINARY_CONTENT_TYPES):
132
+ body_display = f'[binary content, {len(response.content)} bytes]'
133
+ is_json = False
134
+ else:
135
+ try:
136
+ raw = response.text
137
+ except Exception:
138
+ raw = '[could not decode response body]'
139
+ body_display, is_json = self._parse_body(raw)
140
+
141
+ return {
142
+ 'status_code': response.status_code,
143
+ 'reason': response.reason or '',
144
+ 'elapsed_ms': round(response.elapsed.total_seconds() * 1000, 1),
145
+ 'headers': dict(response.headers),
146
+ 'body_display': body_display,
147
+ 'body_is_json': is_json,
148
+ 'content_type': ct,
149
+ }
150
+
151
+ def _parse_body(self, raw):
152
+ if raw is None:
153
+ return '', False
154
+ if isinstance(raw, bytes):
155
+ try:
156
+ raw = raw.decode('utf-8')
157
+ except Exception:
158
+ return f'[binary, {len(raw)} bytes]', False
159
+ try:
160
+ parsed = json.loads(raw)
161
+ display = json.dumps(parsed, indent=2, ensure_ascii=False)
162
+ is_json = True
163
+ except (json.JSONDecodeError, TypeError, ValueError):
164
+ display = raw
165
+ is_json = False
166
+ if len(display) > MAX_BODY_DISPLAY:
167
+ display = display[:MAX_BODY_DISPLAY] + f'\n... [truncated, {len(display)} chars total]'
168
+ return display, is_json
169
+
170
+ # Headers that curl adds automatically — no need to include in generated command
171
+ _SKIP_HEADERS = frozenset({
172
+ 'user-agent', 'accept-encoding', 'accept', 'connection', 'content-length',
173
+ })
174
+
175
+ def _build_curl_command(self, response):
176
+ req = response.request
177
+ body = None
178
+ if req.body:
179
+ body = req.body
180
+ if isinstance(body, bytes):
181
+ body = body.decode('utf-8', errors='replace')
182
+
183
+ parts = ['curl', '-X', req.method]
184
+ for k, v in req.headers.items():
185
+ if k.lower() in self._SKIP_HEADERS:
186
+ continue
187
+ safe_v = f'{k}: {v}'.replace("'", "'\\''")
188
+ parts += ['-H', f"'{safe_v}'"]
189
+ if body:
190
+ safe_body = body.replace("'", "'\\''")
191
+ parts += ['--data-raw', f"'{safe_body}'"]
192
+ parts.append(f"'{req.url}'")
193
+ return ' '.join(parts)
194
+
195
+ # ── HTML card builder ──────────────────────────────────────────────────
196
+
197
+ def _build_card_html(self, req_data, resp_data, curl_str, card_id):
198
+ outer_style = (
199
+ 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;'
200
+ 'border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;'
201
+ 'margin:8px 0;box-shadow:0 1px 4px rgba(0,0,0,0.08);'
202
+ 'max-width:100%;background:#ffffff;'
203
+ )
204
+ parts = [f'<div id="card-{card_id}" style="{outer_style}">']
205
+ parts.append(self._build_card_header(req_data, resp_data))
206
+ parts.append(self._build_section_headers('REQUEST HEADERS', req_data['headers'], card_id + 'rqh'))
207
+ parts.append(self._build_section_body('REQUEST BODY', req_data['body_display'], req_data['body_is_json'], card_id + 'rqb', open=True))
208
+ parts.append(self._build_section_headers('RESPONSE HEADERS', resp_data['headers'], card_id + 'rph'))
209
+ parts.append(self._build_section_body('RESPONSE BODY', resp_data['body_display'], resp_data['body_is_json'], card_id + 'rpb', open=True))
210
+ parts.append(self._build_section_curl(curl_str, card_id))
211
+ parts.append('</div>')
212
+ return ''.join(parts)
213
+
214
+ def _build_card_header(self, req_data, resp_data):
215
+ method = req_data['method']
216
+ method_color = METHOD_COLORS.get(method, '#6b7280')
217
+ status_color = self._status_color(resp_data['status_code'])
218
+
219
+ method_badge = (
220
+ f'<span style="background:{method_color};color:#fff;font-weight:700;'
221
+ f'font-size:11px;padding:3px 9px;border-radius:4px;'
222
+ f'letter-spacing:0.5px;font-family:monospace;white-space:nowrap;">'
223
+ f'{html_module.escape(method)}</span>'
224
+ )
225
+ url_span = (
226
+ f'<span style="font-family:monospace;font-size:13px;color:#1e293b;'
227
+ f'flex:1;word-break:break-all;min-width:0;">'
228
+ f'{html_module.escape(req_data["url"])}</span>'
229
+ )
230
+ status_badge = (
231
+ f'<span style="background:{status_color};color:#fff;font-weight:600;'
232
+ f'font-size:12px;padding:3px 10px;border-radius:4px;white-space:nowrap;">'
233
+ f'{resp_data["status_code"]} {html_module.escape(resp_data["reason"])}</span>'
234
+ )
235
+ timing = (
236
+ f'<span style="color:#64748b;font-size:12px;white-space:nowrap;">'
237
+ f'{resp_data["elapsed_ms"]} ms</span>'
238
+ )
239
+ header_style = (
240
+ 'display:flex;align-items:center;gap:10px;padding:10px 14px;'
241
+ 'background:#f8fafc;border-bottom:1px solid #e2e8f0;flex-wrap:wrap;'
242
+ )
243
+ return f'<div style="{header_style}">{method_badge}{url_span}{status_badge}{timing}</div>'
244
+
245
+ def _build_section_headers(self, label, headers_dict, section_id):
246
+ if not headers_dict:
247
+ return ''
248
+ count = len(headers_dict)
249
+ rows = []
250
+ for k, v in headers_dict.items():
251
+ rows.append(
252
+ f'<tr style="border-bottom:1px solid #f1f5f9;">'
253
+ f'<td style="padding:5px 14px;color:#64748b;width:35%;vertical-align:top;'
254
+ f'font-family:monospace;font-size:12px;word-break:break-word;">'
255
+ f'{html_module.escape(str(k))}</td>'
256
+ f'<td style="padding:5px 14px;color:#1e293b;word-break:break-all;'
257
+ f'font-family:monospace;font-size:12px;">'
258
+ f'{html_module.escape(str(v))}</td>'
259
+ f'</tr>'
260
+ )
261
+ table = (
262
+ f'<table style="width:100%;border-collapse:collapse;">{"".join(rows)}</table>'
263
+ )
264
+ return self._wrap_details(label, f'({count} headers)', table)
265
+
266
+ def _build_section_body(self, label, body_display, is_json, section_id, open=False):
267
+ if not body_display:
268
+ content_type = '· JSON' if is_json else ''
269
+ empty = f'<div style="padding:10px 14px;color:#94a3b8;font-size:12px;font-style:italic;">No body</div>'
270
+ return self._wrap_details(f'{label} {content_type}'.strip(), '', empty, open=open)
271
+
272
+ content_type_label = '· JSON' if is_json else ''
273
+ escaped_body = html_module.escape(body_display)
274
+ pre_id = section_id + 'pre'
275
+ pre = (
276
+ f'<pre id="{pre_id}" style="margin:0;padding:12px 14px;'
277
+ f'background:#0f172a;color:#e2e8f0;font-size:12px;'
278
+ f'font-family:\'Cascadia Code\',\'Fira Code\',monospace;'
279
+ f'overflow-x:auto;overflow-y:auto;white-space:pre-wrap;word-break:break-word;'
280
+ f'line-height:1.6;max-height:300px;">{escaped_body}</pre>'
281
+ )
282
+ script = ''
283
+ if is_json:
284
+ script = (
285
+ '<script>(function(){'
286
+ f'var p=document.getElementById("{pre_id}");if(!p)return;'
287
+ 'p.innerHTML=p.innerHTML'
288
+ r'.replace(/(&quot;(?:[^&]|&(?!quot;))*&quot;)(\s*:)/g,'
289
+ '\'<span style="color:#7dd3fc">$1</span>$2\')'
290
+ r'.replace(/:\s*(&quot;(?:[^&]|&(?!quot;))*&quot;)/g,'
291
+ '\': <span style="color:#a3e635">$1</span>\')'
292
+ r'.replace(/\b(true|false)\b/g,\'<span style="color:#fb923c">$1</span>\')'
293
+ r'.replace(/\b(null)\b/g,\'<span style="color:#f87171">$1</span>\')'
294
+ r'.replace(/(?<!["\w])(-?\d+\.?\d*)(?!["\w])/g,\'<span style="color:#c084fc">$1</span>\');'
295
+ '})();</script>'
296
+ )
297
+ return self._wrap_details(f'{label} {content_type_label}'.strip(), '', pre + script, open=open)
298
+
299
+ def _build_section_curl(self, curl_str, card_id):
300
+ curl_pre_id = f'curl-{card_id}'
301
+ copy_id = f'copybtn-{card_id}'
302
+ esc_curl = html_module.escape(curl_str)
303
+
304
+ script = (
305
+ f'<script>'
306
+ f'function copyCurl_{card_id}(){{'
307
+ f'var pre=document.getElementById("{curl_pre_id}");'
308
+ f'navigator.clipboard.writeText(pre.textContent).then(function(){{'
309
+ f'var btn=document.getElementById("{copy_id}");'
310
+ f'btn.textContent="Copied!";'
311
+ f'setTimeout(function(){{btn.textContent="Copy";}},1500);'
312
+ f'}});'
313
+ f'}}'
314
+ f'</script>'
315
+ )
316
+ content = (
317
+ f'{script}'
318
+ f'<div style="position:relative;background:#0f172a;padding:10px 14px;">'
319
+ f'<button id="{copy_id}" onclick="copyCurl_{card_id}()" '
320
+ f'style="position:absolute;top:8px;right:12px;background:#334155;color:#94a3b8;'
321
+ f'border:none;border-radius:4px;padding:3px 10px;font-size:11px;cursor:pointer;">Copy</button>'
322
+ f'<pre id="{curl_pre_id}" style="margin:0;color:#a3e635;font-size:12px;'
323
+ f'font-family:monospace;white-space:pre-wrap;word-break:break-all;padding-right:60px;">'
324
+ f'{esc_curl}</pre>'
325
+ f'</div>'
326
+ )
327
+ return self._wrap_details('CURL', '', content)
328
+
329
+ def _wrap_details(self, label, meta, content_html, open=False):
330
+ summary_style = (
331
+ 'padding:9px 14px;cursor:pointer;font-size:11px;font-weight:600;'
332
+ 'color:#475569;text-transform:uppercase;letter-spacing:0.5px;'
333
+ 'list-style:none;display:flex;align-items:center;gap:6px;'
334
+ 'user-select:none;background:#f8fafc;'
335
+ )
336
+ meta_span = (
337
+ f'<span style="color:#94a3b8;font-weight:400;text-transform:none;margin-left:auto;">'
338
+ f'{html_module.escape(meta)}</span>'
339
+ ) if meta else ''
340
+ open_attr = ' open' if open else ''
341
+ return (
342
+ f'<details{open_attr} style="border-top:1px solid #e2e8f0;">'
343
+ f'<summary style="{summary_style}">'
344
+ f'{html_module.escape(label)}{meta_span}'
345
+ f'</summary>'
346
+ f'{content_html}'
347
+ f'</details>'
348
+ )
349
+
350
+ def _status_color(self, code):
351
+ if 200 <= code < 300:
352
+ return '#10b981'
353
+ if 300 <= code < 400:
354
+ return '#3b82f6'
355
+ if 400 <= code < 500:
356
+ return '#f59e0b'
357
+ if code >= 500:
358
+ return '#ef4444'
359
+ return '#6b7280'
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: robotframework-requests-log
3
+ Version: 1.0.0
4
+ Summary: Robot Framework library for beautiful API request/response HTML log cards
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/heynirinx/request-log-rf
7
+ Project-URL: Repository, https://github.com/heynirinx/request-log-rf
8
+ Keywords: robotframework,testing,api,http,logging,requests
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Framework :: Robot Framework
11
+ Classifier: Framework :: Robot Framework :: Library
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: robotframework>=5.0
19
+ Requires-Dist: requests>=2.20
20
+ Dynamic: license-file
21
+
22
+ # robotframework-requests-log
23
+
24
+ A [Robot Framework](https://robotframework.org/) library that logs HTTP API requests and responses as beautiful interactive HTML cards — with color-coded method badges, status indicators, JSON syntax highlighting, and one-click curl commands.
25
+
26
+ ## Features
27
+
28
+ - All HTTP methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`
29
+ - Color-coded method badges and status code indicators
30
+ - JSON syntax highlighting in request/response bodies
31
+ - Collapsible request/response headers
32
+ - Auto-generated curl command with copy button
33
+ - Binary content detection (images, PDFs, audio, video)
34
+ - Body truncation at 50KB with total size shown
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install robotframework-requests-log
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```robot
45
+ *** Settings ***
46
+ Library RequestsLog
47
+
48
+ *** Test Cases ***
49
+ Test GET Request
50
+ ${response}= GET https://jsonplaceholder.typicode.com/todos/1
51
+ Log ${response.status_code}
52
+
53
+ Test POST Request
54
+ ${body}= Create Dictionary title=foo body=bar userId=${1}
55
+ ${response}= POST https://jsonplaceholder.typicode.com/posts
56
+ ... json=${body}
57
+ ... expected_status=201
58
+ ```
59
+
60
+ ## Keywords
61
+
62
+ | Keyword | Description |
63
+ |---------|-------------|
64
+ | `GET` | Send an HTTP GET request |
65
+ | `POST` | Send an HTTP POST request |
66
+ | `PUT` | Send an HTTP PUT request |
67
+ | `PATCH` | Send an HTTP PATCH request |
68
+ | `DELETE` | Send an HTTP DELETE request |
69
+ | `HEAD` | Send an HTTP HEAD request |
70
+ | `OPTIONS` | Send an HTTP OPTIONS request |
71
+
72
+ ### Common Parameters
73
+
74
+ | Parameter | Description | Default |
75
+ |-----------|-------------|---------|
76
+ | `url` | Target URL | required |
77
+ | `headers` | Additional headers (dict) | `None` |
78
+ | `json` | JSON body (dict) | `None` |
79
+ | `data` | Raw body | `None` |
80
+ | `params` | URL query parameters (dict) | `None` |
81
+ | `expected_status` | Assert response status code | `None` |
82
+ | `timeout` | Request timeout in seconds | `30` |
83
+ | `verify` | SSL certificate verification | `True` |
84
+ | `msg` | Custom error message on failure | `None` |
85
+
86
+ ## Requirements
87
+
88
+ - Python >= 3.8
89
+ - Robot Framework >= 5.0
90
+ - requests >= 2.20
91
+
92
+ ## License
93
+
94
+ MIT
@@ -0,0 +1,6 @@
1
+ RequestsLog.py,sha256=z8Jld8Jx8txlaOjCHl8MJggfrA5kZrT4IsPWK2jTPOI,16743
2
+ robotframework_requests_log-1.0.0.dist-info/licenses/LICENSE,sha256=Oow6bpC39ifxx3shl_UD96yrItZjq1MbcBlXPxarGvs,1066
3
+ robotframework_requests_log-1.0.0.dist-info/METADATA,sha256=5xlP-9xj__psVh3dzv3yqr0QaQ2x6QWvNkyc2potgMk,3052
4
+ robotframework_requests_log-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ robotframework_requests_log-1.0.0.dist-info/top_level.txt,sha256=0o75q6TNyjMJdH0fIut0nVNvhZkMkZfyAFnGk2qRnsg,12
6
+ robotframework_requests_log-1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 heynirinx
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ RequestsLog