harfile 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.
harfile/__init__.py ADDED
@@ -0,0 +1,203 @@
1
+ """Write HTTP Archive (HAR) files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ import json
7
+ from dataclasses import asdict
8
+ from datetime import datetime
9
+ from os import PathLike
10
+ from types import TracebackType
11
+ from typing import IO, Any
12
+
13
+ from ._models import (
14
+ Browser,
15
+ Cache,
16
+ Content,
17
+ Cookie,
18
+ Creator,
19
+ PostData,
20
+ PostParameter,
21
+ Record,
22
+ Request,
23
+ Response,
24
+ Timings,
25
+ )
26
+ from ._version import VERSION
27
+
28
+ __all__ = [
29
+ "open",
30
+ "HarFile",
31
+ "Browser",
32
+ "Creator",
33
+ "Cache",
34
+ "Request",
35
+ "Response",
36
+ "Timings",
37
+ "Cookie",
38
+ "Record",
39
+ "PostData",
40
+ "PostParameter",
41
+ "Content",
42
+ "HAR_VERSION",
43
+ ]
44
+
45
+ HAR_VERSION = "1.2"
46
+
47
+
48
+ class HarFile:
49
+ _fd: IO[str]
50
+ _creator: Creator
51
+ _browser: Browser
52
+ _comment: str | None
53
+ _is_first_entry: bool = True
54
+ _has_preable: bool = False
55
+ closed: bool = False
56
+
57
+ def __init__(
58
+ self,
59
+ fd: IO[str],
60
+ *,
61
+ creator: Creator | None = None,
62
+ browser: Browser | None = None,
63
+ comment: str | None = None,
64
+ ):
65
+ self._fd = fd
66
+ self._creator = creator or Creator(name="harfile", version=VERSION)
67
+ self._browser = browser or Browser(name="", version="")
68
+ self._comment = comment
69
+
70
+ @classmethod
71
+ def open(
72
+ cls,
73
+ name_or_fd: str | PathLike | IO[str],
74
+ *,
75
+ creator: Creator | None = None,
76
+ browser: Browser | None = None,
77
+ comment: str | None = None,
78
+ ) -> HarFile:
79
+ """Open a HAR file for writing."""
80
+ fd: IO[str]
81
+ if isinstance(name_or_fd, (str, PathLike)):
82
+ fd = builtins.open(name_or_fd, "w")
83
+ else:
84
+ fd = name_or_fd
85
+ return cls(fd=fd, creator=creator, browser=browser, comment=comment)
86
+
87
+ def close(self) -> None:
88
+ """Close the HAR file."""
89
+ if self.closed:
90
+ return None
91
+ self.closed = True
92
+ if not self._has_preable:
93
+ self._write_preamble()
94
+ self._has_preable = True
95
+ self._write_postscript()
96
+
97
+ def __enter__(self) -> HarFile:
98
+ return self
99
+
100
+ def __exit__(
101
+ self,
102
+ type: type[BaseException] | None,
103
+ value: BaseException | None,
104
+ traceback: TracebackType | None,
105
+ ) -> None:
106
+ if type is None:
107
+ self.close()
108
+ return None
109
+
110
+ def add_entry(
111
+ self,
112
+ *,
113
+ startedDateTime: datetime,
114
+ time: int | float,
115
+ request: Request,
116
+ response: Response,
117
+ timings: Timings,
118
+ cache: Cache | None = None,
119
+ serverIPAddress: str | None = None,
120
+ connection: str | None = None,
121
+ comment: str | None = None,
122
+ ) -> None:
123
+ """Add an HTTP request to the HAR file."""
124
+ if not self._has_preable:
125
+ self._write_preamble()
126
+ self._has_preable = True
127
+ self._write_entry(
128
+ startedDateTime=startedDateTime,
129
+ time=time,
130
+ request=request,
131
+ response=response,
132
+ cache=cache,
133
+ timings=timings,
134
+ serverIPAddress=serverIPAddress,
135
+ connection=connection,
136
+ comment=comment,
137
+ )
138
+
139
+ def _write_entry(
140
+ self,
141
+ *,
142
+ startedDateTime: datetime,
143
+ time: int | float,
144
+ request: Request,
145
+ response: Response,
146
+ timings: Timings,
147
+ cache: Cache | None = None,
148
+ serverIPAddress: str | None = None,
149
+ connection: str | None = None,
150
+ comment: str | None = None,
151
+ ) -> None:
152
+ separator = "\n" if self._is_first_entry else ",\n"
153
+ self._is_first_entry = False
154
+ self._fd.write(f"{separator} {{")
155
+ self._fd.write(f'\n "startedDateTime": "{startedDateTime.isoformat()}",')
156
+ self._fd.write(f'\n "time": {time},')
157
+ self._fd.write(f'\n "request": {json.dumps(asdict(request, dict_factory=_dict_factory))},')
158
+ self._fd.write(f'\n "response": {json.dumps(asdict(response, dict_factory=_dict_factory))},')
159
+ self._fd.write(f'\n "timings": {json.dumps(asdict(timings, dict_factory=_dict_factory))}')
160
+ if cache:
161
+ self._fd.write(f',\n "cache": {json.dumps(asdict(cache, dict_factory=_dict_factory))}')
162
+ if serverIPAddress:
163
+ self._fd.write(f',\n "serverIPAddress": {json.dumps(serverIPAddress)}')
164
+ if connection:
165
+ self._fd.write(f',\n "connection": {json.dumps(connection)}')
166
+ if comment:
167
+ self._fd.write(f',\n "comment": {json.dumps(comment)}')
168
+ self._fd.write("\n }")
169
+
170
+ def _write_preamble(self) -> None:
171
+ creator = f"""{{
172
+ "name": "{self._creator.name}",
173
+ "version": "{self._creator.version}\""""
174
+ if self._creator.comment:
175
+ creator += f',\n "comment": "{self._creator.comment}"'
176
+ creator += "\n }"
177
+ browser = f"""{{
178
+ "name": "{self._browser.name}",
179
+ "version": "{self._browser.version}\""""
180
+ if self._browser.comment:
181
+ browser += f',\n "comment": "{self._browser.comment}"'
182
+ browser += "\n }"
183
+ self._fd.write(f"""{{
184
+ "log": {{
185
+ "version": "{HAR_VERSION}",
186
+ "creator": {creator},
187
+ "browser": {browser}""")
188
+ if self._comment:
189
+ self._fd.write(f' "comment": "{self._comment}"')
190
+ self._fd.write(',\n "entries": [')
191
+
192
+ def _write_postscript(self) -> None:
193
+ if self._is_first_entry:
194
+ self._fd.write("]\n }\n}")
195
+ else:
196
+ self._fd.write("\n ]\n }\n}")
197
+
198
+
199
+ def _dict_factory(value: list[tuple[str, Any]]) -> dict[str, Any]:
200
+ return {key: value for key, value in value if value is not None}
201
+
202
+
203
+ open = HarFile.open
harfile/_models.py ADDED
@@ -0,0 +1,167 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ @dataclass
7
+ class Creator:
8
+ # Name of the application used to export the log
9
+ name: str
10
+ # Version of the application used to export the log
11
+ version: str
12
+ comment: str | None = None
13
+
14
+
15
+ @dataclass
16
+ class Browser:
17
+ # Name of the browser used to export the log
18
+ name: str
19
+ # Version of the browser used to export the log
20
+ version: str
21
+ comment: str | None = None
22
+
23
+
24
+ @dataclass
25
+ class Cache:
26
+ """Info about a request coming from browser cache."""
27
+
28
+ # State of a cache entry before the request
29
+ beforeRequest: CacheEntry | None = None
30
+ # State of a cache entry after the request
31
+ afterRequest: CacheEntry | None = None
32
+ comment: str | None = None
33
+
34
+
35
+ @dataclass
36
+ class CacheEntry:
37
+ # Expiration time of the cache entry
38
+ expires: str
39
+ # The last time the cache entry was opened
40
+ lastAccess: str
41
+ eTag: str
42
+ # The number of times the cache entry has been opened
43
+ hitCount: int
44
+ comment: str | None = None
45
+
46
+
47
+ @dataclass
48
+ class Request:
49
+ method: str
50
+ # Absolute URL of the request (fragments are not included)
51
+ url: str
52
+ # Request HTTP Version
53
+ httpVersion: str
54
+ cookies: list[Cookie] = field(default_factory=list)
55
+ headers: list[Record] = field(default_factory=list)
56
+ queryString: list[Record] = field(default_factory=list)
57
+ postData: PostData | None = None
58
+ # Total number of bytes from the start of the HTTP request message until (and including) the double CRLF
59
+ # before the body
60
+ headersSize: int = -1
61
+ # Size of the request body (POST data payload) in bytes
62
+ bodySize: int = -1
63
+ comment: str | None = None
64
+
65
+
66
+ @dataclass
67
+ class Cookie:
68
+ # The name of the cookie
69
+ name: str
70
+ # The cookie value
71
+ value: str
72
+ # The path pertaining to the cookie
73
+ path: str | None = None
74
+ # The host of the cookie
75
+ domain: str | None = None
76
+ # Cookie expiration time
77
+ expires: str | None = None
78
+ # Set to true if the cookie is HTTP only, false otherwise
79
+ httpOnly: bool | None = None
80
+ # True if the cookie was transmitted over ssl, false otherwise
81
+ secure: bool | None = None
82
+ comment: str | None = None
83
+
84
+
85
+ @dataclass
86
+ class Record:
87
+ name: str
88
+ value: str
89
+ comment: str | None = None
90
+
91
+
92
+ @dataclass
93
+ class PostData:
94
+ # MIME type of the posted data
95
+ mimeType: str
96
+ # List of posted parameters (in case of URL encoded parameters)
97
+ params: list[PostParameter] | None = None
98
+ # Plain text posted data
99
+ text: str | None = None
100
+ comment: str | None = None
101
+
102
+
103
+ @dataclass
104
+ class PostParameter:
105
+ name: str
106
+ value: str | None = None
107
+ fileName: str | None = None
108
+ contentType: str | None = None
109
+ comment: str | None = None
110
+
111
+
112
+ @dataclass
113
+ class Content:
114
+ size: int = 0
115
+ # Number of bytes saved
116
+ compression: int | float | None = None
117
+ # MIME type of the response text (value of the Content-Type response header).
118
+ # The charset attribute of the MIME type is included
119
+ mimeType: str | None = None
120
+ # Response body sent from the server or loaded from the browser cache.
121
+ # This field is populated with textual content only.
122
+ # The text field is either HTTP decoded text or a encoded (e.g. "base64") representation of the response body
123
+ text: str | None = None
124
+ encoding: str | None = None
125
+ # Encoding used for response text field e.g "base64"
126
+ comment: str | None = None
127
+
128
+
129
+ @dataclass
130
+ class Response:
131
+ # Response status
132
+ status: int
133
+ # Response status description
134
+ statusText: str
135
+ # Response HTTP Version
136
+ httpVersion: str
137
+ cookies: list[Cookie] = field(default_factory=list)
138
+ headers: list[Record] = field(default_factory=list)
139
+ # Details about the response body
140
+ content: Content = field(default_factory=Content)
141
+ # Redirection target URL from the Location response header
142
+ redirectURL: str = ""
143
+ # Total number of bytes from the start of the HTTP response message
144
+ # until (and including) the double CRLF before the body
145
+ headersSize: int = -1
146
+ # Size of the received response body in bytes
147
+ bodySize: int = -1
148
+ comment: str | None = None
149
+
150
+
151
+ @dataclass
152
+ class Timings:
153
+ # Time required to send HTTP request to the server
154
+ send: int | float
155
+ # Waiting for a response from the server
156
+ wait: int | float
157
+ # Time required to read entire response from the server (or cache)
158
+ receive: int | float
159
+ # Time spent in a queue waiting for a network connection
160
+ blocked: int | float = -1
161
+ # DNS resolution time. The time required to resolve a host name
162
+ dns: int | float = -1
163
+ # Time required to create TCP connection
164
+ connect: int | float = -1
165
+ # Time required for SSL/TLS negotiation
166
+ ssl: int | float = -1
167
+ comment: str | None = None
harfile/_version.py ADDED
@@ -0,0 +1,7 @@
1
+ from importlib import metadata
2
+
3
+ try:
4
+ VERSION = metadata.version(__package__)
5
+ except metadata.PackageNotFoundError:
6
+ # Local run without installation
7
+ VERSION = "dev"
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.3
2
+ Name: harfile
3
+ Version: 0.1.0
4
+ Summary: Writer for HTTP Archive (HAR) files
5
+ Project-URL: Changelog, https://github.com/schemathesis/harfile/blob/main/CHANGELOG.md
6
+ Project-URL: Bug Tracker, https://github.com/schemathesis/harfile
7
+ Project-URL: Funding, https://github.com/sponsors/Stranger6667
8
+ Project-URL: Source Code, https://github.com/schemathesis/harfile
9
+ Author-email: Dmitry Dygalo <dmitry@dygalo.dev>
10
+ Maintainer-email: Dmitry Dygalo <dmitry@dygalo.dev>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: har,http,testing
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Topic :: Software Development :: Testing
27
+ Requires-Python: >=3.8
28
+ Provides-Extra: bench
29
+ Requires-Dist: pytest-codspeed==2.2.1; extra == 'bench'
30
+ Provides-Extra: cov
31
+ Requires-Dist: coverage-enable-subprocess; extra == 'cov'
32
+ Requires-Dist: coverage[toml]>=7; extra == 'cov'
33
+ Provides-Extra: dev
34
+ Requires-Dist: coverage-enable-subprocess; extra == 'dev'
35
+ Requires-Dist: coverage>=7; extra == 'dev'
36
+ Requires-Dist: coverage[toml]>=7; extra == 'dev'
37
+ Requires-Dist: hypothesis-jsonschema>=0.23.1; extra == 'dev'
38
+ Requires-Dist: hypothesis>=6; extra == 'dev'
39
+ Requires-Dist: jsonschema>=4.18.0; extra == 'dev'
40
+ Requires-Dist: pytest-codspeed==2.2.1; extra == 'dev'
41
+ Requires-Dist: pytest<8,>=6.2.0; extra == 'dev'
42
+ Provides-Extra: tests
43
+ Requires-Dist: coverage>=7; extra == 'tests'
44
+ Requires-Dist: hypothesis-jsonschema>=0.23.1; extra == 'tests'
45
+ Requires-Dist: hypothesis>=6; extra == 'tests'
46
+ Requires-Dist: jsonschema>=4.18.0; extra == 'tests'
47
+ Requires-Dist: pytest<8,>=6.2.0; extra == 'tests'
48
+ Description-Content-Type: text/markdown
49
+
50
+ # harfile
51
+
52
+ [![CI](https://github.com/schemathesis/harfile/actions/workflows/ci.yml/badge.svg)](https://github.com/schemathesis/harfile/actions/workflows/ci.yml)
53
+ [![Coverage](https://codecov.io/gh/Stranger6667/hypothesis-openapi/branch/main/graph/badge.svg)](https://codecov.io/gh/schemathesis/harfile/branch/main)
54
+ [![Version](https://img.shields.io/pypi/v/harfile.svg)](https://pypi.org/project/harfile/)
55
+ [![Python versions](https://img.shields.io/pypi/pyversions/harfile.svg)](https://pypi.org/project/harfile/)
56
+ [![License](https://img.shields.io/pypi/l/harfile.svg)](https://opensource.org/licenses/MIT)
57
+
58
+ This package provides zero dependency writer for building HAR (HTTP Archive) files in Python.
59
+
60
+ **NOTES**:
61
+
62
+ - The writer assumes single-threaded
63
+ - Pages are not supported
64
+
65
+ ## Usage
66
+
67
+ ```python
68
+ import datetime
69
+ import io
70
+
71
+ import harfile
72
+
73
+
74
+ # Write to a file
75
+ with harfile.open("filename.har") as har:
76
+ har.add_entry(
77
+ started_date_time=datetime.datetime.now(),
78
+ time=42,
79
+ request=harfile.Request(
80
+ method="GET",
81
+ url="http://example.com",
82
+ http_version="HTTP/1.1",
83
+ ),
84
+ response=harfile.Response(
85
+ status=200,
86
+ status_text="OK",
87
+ http_version="HTTP/1.1",
88
+ ),
89
+ )
90
+
91
+
92
+ # Write to a string buffer
93
+ buffer = io.StringIO()
94
+ with harfile.open(buffer) as har:
95
+ pass
96
+
97
+ ```
98
+
99
+ ## License
100
+
101
+ The code in this project is licensed under [MIT license](https://opensource.org/licenses/MIT).
102
+ By contributing to `harfile`, you agree that your contributions will be licensed under its MIT license.
@@ -0,0 +1,7 @@
1
+ harfile/__init__.py,sha256=XrVHjEI-gAfXMhwW--MZTlm0gQ1WhpEwdlVfn6FmP0s,5939
2
+ harfile/_models.py,sha256=hrf41xCIFQ7YXxvnbD_42COIc-LoxDDGg3qLLRqmFLU,4791
3
+ harfile/_version.py,sha256=VCop0CrAbqvQduFEZTE_e_8_qX6zTfpFuZrfAdZpV4Y,176
4
+ harfile-0.1.0.dist-info/METADATA,sha256=I3RoFojBPNjcmTw7OUn6j3CiGhwumS6zDq7Ak5Dhs1c,3772
5
+ harfile-0.1.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
6
+ harfile-0.1.0.dist-info/licenses/LICENSE,sha256=_OO4n40mf404q5aONT_bSm6rHzhRZ398bDtxkOQ2Qms,1072
7
+ harfile-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Schemathesis.io
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.