provide-testkit 0.0.0.dev0__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.
Files changed (66) hide show
  1. provide/__init__.py +3 -0
  2. provide/testkit/__init__.py +248 -0
  3. provide/testkit/archive/__init__.py +24 -0
  4. provide/testkit/archive/fixtures.py +217 -0
  5. provide/testkit/cli.py +229 -0
  6. provide/testkit/common/__init__.py +32 -0
  7. provide/testkit/common/fixtures.py +234 -0
  8. provide/testkit/crypto.py +163 -0
  9. provide/testkit/environment.py +79 -0
  10. provide/testkit/file/__init__.py +40 -0
  11. provide/testkit/file/content_fixtures.py +275 -0
  12. provide/testkit/file/directory_fixtures.py +105 -0
  13. provide/testkit/file/fixtures.py +49 -0
  14. provide/testkit/file/special_fixtures.py +141 -0
  15. provide/testkit/fixtures.py +52 -0
  16. provide/testkit/harness.py +122 -0
  17. provide/testkit/hub.py +22 -0
  18. provide/testkit/logger/__init__.py +39 -0
  19. provide/testkit/logger/hooks.py +100 -0
  20. provide/testkit/logger/reset.py +230 -0
  21. provide/testkit/main.py +22 -0
  22. provide/testkit/mocking/__init__.py +46 -0
  23. provide/testkit/mocking/fixtures.py +340 -0
  24. provide/testkit/process/__init__.py +48 -0
  25. provide/testkit/process/async_fixtures.py +410 -0
  26. provide/testkit/process/fixtures.py +54 -0
  27. provide/testkit/process/subprocess_fixtures.py +208 -0
  28. provide/testkit/quality/__init__.py +101 -0
  29. provide/testkit/quality/artifacts.py +360 -0
  30. provide/testkit/quality/base.py +158 -0
  31. provide/testkit/quality/cli.py +394 -0
  32. provide/testkit/quality/complexity/__init__.py +30 -0
  33. provide/testkit/quality/complexity/analyzer.py +392 -0
  34. provide/testkit/quality/complexity/fixture.py +196 -0
  35. provide/testkit/quality/coverage/__init__.py +36 -0
  36. provide/testkit/quality/coverage/fixture.py +236 -0
  37. provide/testkit/quality/coverage/reporter.py +150 -0
  38. provide/testkit/quality/coverage/tracker.py +313 -0
  39. provide/testkit/quality/decorators.py +380 -0
  40. provide/testkit/quality/documentation/__init__.py +29 -0
  41. provide/testkit/quality/documentation/checker.py +361 -0
  42. provide/testkit/quality/documentation/fixture.py +187 -0
  43. provide/testkit/quality/profiling/__init__.py +30 -0
  44. provide/testkit/quality/profiling/fixture.py +332 -0
  45. provide/testkit/quality/profiling/profiler.py +428 -0
  46. provide/testkit/quality/report.py +266 -0
  47. provide/testkit/quality/runner.py +319 -0
  48. provide/testkit/quality/security/__init__.py +29 -0
  49. provide/testkit/quality/security/fixture.py +196 -0
  50. provide/testkit/quality/security/scanner.py +338 -0
  51. provide/testkit/streams.py +54 -0
  52. provide/testkit/threading/__init__.py +38 -0
  53. provide/testkit/threading/basic_fixtures.py +103 -0
  54. provide/testkit/threading/data_fixtures.py +101 -0
  55. provide/testkit/threading/execution_fixtures.py +268 -0
  56. provide/testkit/threading/fixtures.py +50 -0
  57. provide/testkit/threading/sync_fixtures.py +98 -0
  58. provide/testkit/time/__init__.py +32 -0
  59. provide/testkit/time/fixtures.py +416 -0
  60. provide/testkit/transport/__init__.py +30 -0
  61. provide/testkit/transport/fixtures.py +278 -0
  62. provide_testkit-0.0.0.dev0.dist-info/METADATA +145 -0
  63. provide_testkit-0.0.0.dev0.dist-info/RECORD +66 -0
  64. provide_testkit-0.0.0.dev0.dist-info/WHEEL +5 -0
  65. provide_testkit-0.0.0.dev0.dist-info/entry_points.txt +2 -0
  66. provide_testkit-0.0.0.dev0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,410 @@
1
+ """
2
+ Async-specific test fixtures for process testing.
3
+
4
+ Provides fixtures for testing async operations, event loops, and
5
+ async context management across the provide-io ecosystem.
6
+ """
7
+
8
+ import asyncio
9
+ from collections.abc import AsyncGenerator, Callable
10
+ from unittest.mock import AsyncMock
11
+
12
+ import pytest
13
+
14
+
15
+ @pytest.fixture
16
+ async def clean_event_loop() -> AsyncGenerator[None, None]:
17
+ """
18
+ Ensure clean event loop for async tests.
19
+
20
+ Cancels all pending tasks after the test to prevent event loop issues.
21
+
22
+ Yields:
23
+ None - fixture for test setup/teardown.
24
+ """
25
+ yield
26
+
27
+ # Clean up any pending tasks
28
+ loop = asyncio.get_event_loop()
29
+ pending = asyncio.all_tasks(loop)
30
+
31
+ for task in pending:
32
+ if not task.done():
33
+ task.cancel()
34
+
35
+ # Wait for all tasks to complete cancellation
36
+ if pending:
37
+ await asyncio.gather(*pending, return_exceptions=True)
38
+
39
+
40
+ @pytest.fixture
41
+ def async_timeout() -> Callable[[float], asyncio.Task]:
42
+ """
43
+ Provide configurable timeout wrapper for async operations.
44
+
45
+ Returns:
46
+ A function that wraps async operations with a timeout.
47
+ """
48
+
49
+ def _timeout_wrapper(coro, seconds: float = 5.0):
50
+ """
51
+ Wrap a coroutine with a timeout.
52
+
53
+ Args:
54
+ coro: Coroutine to wrap
55
+ seconds: Timeout in seconds
56
+
57
+ Returns:
58
+ Result of the coroutine or raises asyncio.TimeoutError
59
+ """
60
+ return asyncio.wait_for(coro, timeout=seconds)
61
+
62
+ return _timeout_wrapper
63
+
64
+
65
+ @pytest.fixture
66
+ def event_loop_policy():
67
+ """
68
+ Set event loop policy for tests to avoid conflicts.
69
+
70
+ Returns:
71
+ New event loop policy for isolated testing.
72
+ """
73
+ policy = asyncio.get_event_loop_policy()
74
+ new_policy = asyncio.DefaultEventLoopPolicy()
75
+ asyncio.set_event_loop_policy(new_policy)
76
+
77
+ yield new_policy
78
+
79
+ # Restore original policy
80
+ asyncio.set_event_loop_policy(policy)
81
+
82
+
83
+ @pytest.fixture
84
+ async def async_context_manager():
85
+ """
86
+ Factory for creating mock async context managers.
87
+
88
+ Returns:
89
+ Function that creates configured async context manager mocks.
90
+ """
91
+
92
+ def _create_async_cm(enter_value=None, exit_value=None):
93
+ """
94
+ Create a mock async context manager.
95
+
96
+ Args:
97
+ enter_value: Value to return from __aenter__
98
+ exit_value: Value to return from __aexit__
99
+
100
+ Returns:
101
+ AsyncMock configured as context manager
102
+ """
103
+ mock_cm = AsyncMock()
104
+ mock_cm.__aenter__ = AsyncMock(return_value=enter_value)
105
+ mock_cm.__aexit__ = AsyncMock(return_value=exit_value)
106
+ return mock_cm
107
+
108
+ return _create_async_cm
109
+
110
+
111
+ @pytest.fixture
112
+ async def async_iterator():
113
+ """
114
+ Factory for creating mock async iterators.
115
+
116
+ Returns:
117
+ Function that creates async iterator mocks with specified values.
118
+ """
119
+
120
+ def _create_async_iter(values):
121
+ """
122
+ Create a mock async iterator.
123
+
124
+ Args:
125
+ values: List of values to yield
126
+
127
+ Returns:
128
+ Async iterator that yields the specified values
129
+ """
130
+
131
+ class AsyncIterator:
132
+ def __init__(self, vals):
133
+ self.vals = vals
134
+ self.index = 0
135
+
136
+ def __aiter__(self):
137
+ return self
138
+
139
+ async def __anext__(self):
140
+ if self.index >= len(self.vals):
141
+ raise StopAsyncIteration
142
+ value = self.vals[self.index]
143
+ self.index += 1
144
+ return value
145
+
146
+ return AsyncIterator(values)
147
+
148
+ return _create_async_iter
149
+
150
+
151
+ @pytest.fixture
152
+ def async_queue():
153
+ """
154
+ Create an async queue for testing producer/consumer patterns.
155
+
156
+ Returns:
157
+ asyncio.Queue instance for testing.
158
+ """
159
+ return asyncio.Queue()
160
+
161
+
162
+ @pytest.fixture
163
+ async def async_lock():
164
+ """
165
+ Create an async lock for testing synchronization.
166
+
167
+ Returns:
168
+ asyncio.Lock instance for testing.
169
+ """
170
+ return asyncio.Lock()
171
+
172
+
173
+ @pytest.fixture
174
+ def mock_async_sleep():
175
+ """
176
+ Mock asyncio.sleep to speed up tests.
177
+
178
+ Returns:
179
+ Mock that replaces asyncio.sleep with instant return.
180
+ """
181
+ original_sleep = asyncio.sleep
182
+
183
+ async def instant_sleep(seconds):
184
+ """Sleep replacement that returns immediately."""
185
+ return None
186
+
187
+ asyncio.sleep = instant_sleep
188
+
189
+ yield instant_sleep
190
+
191
+ # Restore original
192
+ asyncio.sleep = original_sleep
193
+
194
+
195
+ @pytest.fixture
196
+ def async_gather_helper():
197
+ """
198
+ Helper for testing asyncio.gather operations.
199
+
200
+ Returns:
201
+ Function to gather async results with error handling.
202
+ """
203
+
204
+ async def _gather(*coroutines, return_exceptions: bool = False):
205
+ """
206
+ Gather results from multiple coroutines.
207
+
208
+ Args:
209
+ *coroutines: Coroutines to gather
210
+ return_exceptions: Whether to return exceptions as results
211
+
212
+ Returns:
213
+ List of results from coroutines
214
+ """
215
+ return await asyncio.gather(*coroutines, return_exceptions=return_exceptions)
216
+
217
+ return _gather
218
+
219
+
220
+ @pytest.fixture
221
+ def async_task_group():
222
+ """
223
+ Manage a group of async tasks with cleanup.
224
+
225
+ Returns:
226
+ AsyncTaskGroup instance for managing tasks.
227
+ """
228
+
229
+ class AsyncTaskGroup:
230
+ def __init__(self):
231
+ self.tasks = []
232
+
233
+ def create_task(self, coro):
234
+ """Create and track a task."""
235
+ task = asyncio.create_task(coro)
236
+ self.tasks.append(task)
237
+ return task
238
+
239
+ async def wait_all(self, timeout: float = None):
240
+ """Wait for all tasks to complete."""
241
+ if not self.tasks:
242
+ return []
243
+
244
+ done, pending = await asyncio.wait(self.tasks, timeout=timeout, return_when=asyncio.ALL_COMPLETED)
245
+
246
+ if pending:
247
+ for task in pending:
248
+ task.cancel()
249
+
250
+ results = []
251
+ for task in done:
252
+ try:
253
+ results.append(task.result())
254
+ except Exception as e:
255
+ results.append(e)
256
+
257
+ return results
258
+
259
+ async def cancel_all(self):
260
+ """Cancel all tasks."""
261
+ for task in self.tasks:
262
+ if not task.done():
263
+ task.cancel()
264
+
265
+ if self.tasks:
266
+ await asyncio.gather(*self.tasks, return_exceptions=True)
267
+
268
+ async def __aenter__(self):
269
+ return self
270
+
271
+ async def __aexit__(self, *args):
272
+ await self.cancel_all()
273
+
274
+ return AsyncTaskGroup()
275
+
276
+
277
+ @pytest.fixture
278
+ def async_condition_waiter():
279
+ """
280
+ Helper for waiting on async conditions in tests.
281
+
282
+ Returns:
283
+ Function to wait for conditions with timeout.
284
+ """
285
+
286
+ async def _wait_for(condition: Callable[[], bool], timeout: float = 5.0, interval: float = 0.1):
287
+ """
288
+ Wait for a condition to become true.
289
+
290
+ Args:
291
+ condition: Function that returns True when condition is met
292
+ timeout: Maximum wait time
293
+ interval: Check interval
294
+
295
+ Returns:
296
+ True if condition met, False if timeout
297
+ """
298
+ start = asyncio.get_event_loop().time()
299
+
300
+ while asyncio.get_event_loop().time() - start < timeout:
301
+ if condition():
302
+ return True
303
+ await asyncio.sleep(interval)
304
+
305
+ return False
306
+
307
+ return _wait_for
308
+
309
+
310
+ @pytest.fixture
311
+ def async_pipeline():
312
+ """
313
+ Create an async pipeline for testing data flow.
314
+
315
+ Returns:
316
+ AsyncPipeline instance for chaining async operations.
317
+ """
318
+
319
+ class AsyncPipeline:
320
+ def __init__(self):
321
+ self.stages = []
322
+ self.results = []
323
+
324
+ def add_stage(self, func: Callable):
325
+ """Add a processing stage."""
326
+ self.stages.append(func)
327
+ return self
328
+
329
+ async def process(self, data):
330
+ """Process data through all stages."""
331
+ result = data
332
+ for stage in self.stages:
333
+ if asyncio.iscoroutinefunction(stage):
334
+ result = await stage(result)
335
+ else:
336
+ result = stage(result)
337
+ self.results.append(result)
338
+ return result
339
+
340
+ async def process_batch(self, items: list):
341
+ """Process multiple items."""
342
+ tasks = [self.process(item) for item in items]
343
+ return await asyncio.gather(*tasks)
344
+
345
+ def clear(self):
346
+ """Clear stages and results."""
347
+ self.stages.clear()
348
+ self.results.clear()
349
+
350
+ return AsyncPipeline()
351
+
352
+
353
+ @pytest.fixture
354
+ def async_rate_limiter():
355
+ """
356
+ Create an async rate limiter for testing.
357
+
358
+ Returns:
359
+ AsyncRateLimiter instance for controlling request rates.
360
+ """
361
+
362
+ class AsyncRateLimiter:
363
+ def __init__(self, rate: int = 10, per: float = 1.0):
364
+ self.rate = rate
365
+ self.per = per
366
+ self.allowance = rate
367
+ self.last_check = asyncio.get_event_loop().time()
368
+
369
+ async def acquire(self):
370
+ """Acquire permission to proceed."""
371
+ current = asyncio.get_event_loop().time()
372
+ time_passed = current - self.last_check
373
+ self.last_check = current
374
+
375
+ self.allowance += time_passed * (self.rate / self.per)
376
+ if self.allowance > self.rate:
377
+ self.allowance = self.rate
378
+
379
+ if self.allowance < 1.0:
380
+ sleep_time = (1.0 - self.allowance) * (self.per / self.rate)
381
+ await asyncio.sleep(sleep_time)
382
+ self.allowance = 0.0
383
+ else:
384
+ self.allowance -= 1.0
385
+
386
+ async def __aenter__(self):
387
+ await self.acquire()
388
+ return self
389
+
390
+ async def __aexit__(self, *args):
391
+ pass
392
+
393
+ return AsyncRateLimiter()
394
+
395
+
396
+ __all__ = [
397
+ "async_condition_waiter",
398
+ "async_context_manager",
399
+ "async_gather_helper",
400
+ "async_iterator",
401
+ "async_lock",
402
+ "async_pipeline",
403
+ "async_queue",
404
+ "async_rate_limiter",
405
+ "async_task_group",
406
+ "async_timeout",
407
+ "clean_event_loop",
408
+ "event_loop_policy",
409
+ "mock_async_sleep",
410
+ ]
@@ -0,0 +1,54 @@
1
+ """
2
+ Process Test Fixtures.
3
+
4
+ Core process testing fixtures with re-exports from specialized modules.
5
+ Utilities for testing async code, managing event loops, and handling
6
+ async subprocess mocking across the provide-io ecosystem.
7
+ """
8
+
9
+ # Re-export all fixtures from specialized modules
10
+ from provide.testkit.process.async_fixtures import (
11
+ async_condition_waiter,
12
+ async_context_manager,
13
+ async_gather_helper,
14
+ async_iterator,
15
+ async_lock,
16
+ async_pipeline,
17
+ async_queue,
18
+ async_rate_limiter,
19
+ async_task_group,
20
+ async_timeout,
21
+ clean_event_loop,
22
+ event_loop_policy,
23
+ mock_async_sleep,
24
+ )
25
+ from provide.testkit.process.subprocess_fixtures import (
26
+ async_mock_server,
27
+ async_stream_reader,
28
+ async_subprocess,
29
+ async_test_client,
30
+ mock_async_process,
31
+ )
32
+
33
+ __all__ = [
34
+ # Async fixtures
35
+ "clean_event_loop",
36
+ "async_timeout",
37
+ "event_loop_policy",
38
+ "async_context_manager",
39
+ "async_iterator",
40
+ "async_queue",
41
+ "async_lock",
42
+ "mock_async_sleep",
43
+ "async_gather_helper",
44
+ "async_task_group",
45
+ "async_condition_waiter",
46
+ "async_pipeline",
47
+ "async_rate_limiter",
48
+ # Subprocess fixtures
49
+ "mock_async_process",
50
+ "async_stream_reader",
51
+ "async_subprocess",
52
+ "async_mock_server",
53
+ "async_test_client",
54
+ ]
@@ -0,0 +1,208 @@
1
+ """
2
+ Subprocess-specific test fixtures for process testing.
3
+
4
+ Provides fixtures for mocking and testing subprocess operations,
5
+ stream handling, and process communication.
6
+ """
7
+
8
+ from unittest.mock import AsyncMock, Mock
9
+
10
+ import pytest
11
+
12
+
13
+ @pytest.fixture
14
+ def mock_async_process() -> AsyncMock:
15
+ """
16
+ Mock async subprocess for testing.
17
+
18
+ Returns:
19
+ AsyncMock configured as a subprocess with common attributes.
20
+ """
21
+ mock_process = AsyncMock()
22
+ mock_process.communicate = AsyncMock(return_value=(b"output", b""))
23
+ mock_process.returncode = 0
24
+ mock_process.pid = 12345
25
+ mock_process.stdin = AsyncMock()
26
+ mock_process.stdout = AsyncMock()
27
+ mock_process.stderr = AsyncMock()
28
+ mock_process.wait = AsyncMock(return_value=0)
29
+ mock_process.kill = Mock()
30
+ mock_process.terminate = Mock()
31
+
32
+ return mock_process
33
+
34
+
35
+ @pytest.fixture
36
+ async def async_stream_reader() -> AsyncMock:
37
+ """
38
+ Mock async stream reader for subprocess stdout/stderr.
39
+
40
+ Returns:
41
+ AsyncMock configured as a stream reader.
42
+ """
43
+ reader = AsyncMock()
44
+
45
+ # Simulate reading lines
46
+ async def readline_side_effect():
47
+ for line in [b"line1\n", b"line2\n", b""]:
48
+ yield line
49
+
50
+ reader.readline = AsyncMock(side_effect=readline_side_effect().__anext__)
51
+ reader.read = AsyncMock(return_value=b"full content")
52
+ reader.at_eof = Mock(side_effect=[False, False, True])
53
+
54
+ return reader
55
+
56
+
57
+ @pytest.fixture
58
+ def async_subprocess():
59
+ """
60
+ Create mock async subprocess for testing.
61
+
62
+ Returns:
63
+ Function that creates mock subprocess with configurable behavior.
64
+ """
65
+
66
+ def _create_subprocess(
67
+ returncode: int = 0, stdout: bytes = b"", stderr: bytes = b"", pid: int = 12345
68
+ ) -> AsyncMock:
69
+ """
70
+ Create a mock async subprocess.
71
+
72
+ Args:
73
+ returncode: Process return code
74
+ stdout: Process stdout output
75
+ stderr: Process stderr output
76
+ pid: Process ID
77
+
78
+ Returns:
79
+ AsyncMock configured as subprocess
80
+ """
81
+ process = AsyncMock()
82
+ process.returncode = returncode
83
+ process.pid = pid
84
+ process.communicate = AsyncMock(return_value=(stdout, stderr))
85
+ process.wait = AsyncMock(return_value=returncode)
86
+ process.kill = Mock()
87
+ process.terminate = Mock()
88
+ process.send_signal = Mock()
89
+
90
+ # Add stdout/stderr as async stream readers
91
+ process.stdout = AsyncMock()
92
+ process.stdout.read = AsyncMock(return_value=stdout)
93
+ process.stdout.readline = AsyncMock(side_effect=[stdout, b""])
94
+ process.stdout.at_eof = Mock(side_effect=[False, True])
95
+
96
+ process.stderr = AsyncMock()
97
+ process.stderr.read = AsyncMock(return_value=stderr)
98
+ process.stderr.readline = AsyncMock(side_effect=[stderr, b""])
99
+ process.stderr.at_eof = Mock(side_effect=[False, True])
100
+
101
+ process.stdin = AsyncMock()
102
+ process.stdin.write = AsyncMock()
103
+ process.stdin.drain = AsyncMock()
104
+ process.stdin.close = Mock()
105
+
106
+ return process
107
+
108
+ return _create_subprocess
109
+
110
+
111
+ @pytest.fixture
112
+ def async_mock_server():
113
+ """
114
+ Create a mock async server for testing.
115
+
116
+ Returns:
117
+ Mock server with async methods.
118
+ """
119
+
120
+ class AsyncMockServer:
121
+ def __init__(self):
122
+ self.started = False
123
+ self.connections = []
124
+ self.requests = []
125
+
126
+ async def start(self, host: str = "localhost", port: int = 8080):
127
+ """Start the mock server."""
128
+ self.started = True
129
+ self.host = host
130
+ self.port = port
131
+
132
+ async def stop(self):
133
+ """Stop the mock server."""
134
+ self.started = False
135
+ for conn in self.connections:
136
+ await conn.close()
137
+
138
+ async def handle_connection(self, reader, writer):
139
+ """Mock connection handler."""
140
+ conn = {"reader": reader, "writer": writer}
141
+ self.connections.append(conn)
142
+
143
+ # Mock reading request
144
+ data = await reader.read(1024)
145
+ self.requests.append(data)
146
+
147
+ # Mock sending response
148
+ writer.write(b"HTTP/1.1 200 OK\r\n\r\nOK")
149
+ await writer.drain()
150
+
151
+ writer.close()
152
+ await writer.wait_closed()
153
+
154
+ def get_url(self) -> str:
155
+ """Get server URL."""
156
+ return f"http://{self.host}:{self.port}"
157
+
158
+ return AsyncMockServer()
159
+
160
+
161
+ @pytest.fixture
162
+ def async_test_client():
163
+ """
164
+ Create an async HTTP test client.
165
+
166
+ Returns:
167
+ Mock async HTTP client for testing.
168
+ """
169
+
170
+ class AsyncTestClient:
171
+ def __init__(self):
172
+ self.responses = {}
173
+ self.requests = []
174
+
175
+ def set_response(self, url: str, response: dict):
176
+ """Set a mock response for a URL."""
177
+ self.responses[url] = response
178
+
179
+ async def get(self, url: str, **kwargs) -> dict:
180
+ """Mock GET request."""
181
+ self.requests.append({"method": "GET", "url": url, "kwargs": kwargs})
182
+ return self.responses.get(url, {"status": 404, "body": "Not Found"})
183
+
184
+ async def post(self, url: str, data=None, **kwargs) -> dict:
185
+ """Mock POST request."""
186
+ self.requests.append({"method": "POST", "url": url, "data": data, "kwargs": kwargs})
187
+ return self.responses.get(url, {"status": 200, "body": "OK"})
188
+
189
+ async def close(self):
190
+ """Close the client."""
191
+ pass
192
+
193
+ async def __aenter__(self):
194
+ return self
195
+
196
+ async def __aexit__(self, *args):
197
+ await self.close()
198
+
199
+ return AsyncTestClient()
200
+
201
+
202
+ __all__ = [
203
+ "async_mock_server",
204
+ "async_stream_reader",
205
+ "async_subprocess",
206
+ "async_test_client",
207
+ "mock_async_process",
208
+ ]