Pytest Asyncio Fixture Lifespan
Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.
Page 2 of 3
Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.
Provide a pytest fixture that creates a fresh database per test and tears it down, so tests stay independent and order does not matter.
Configure Python logging with rotation by size and backups, per-module loggers, structured formatting, and a root-level filter guard.
Implement a token bucket that refills at a steady rate and allows short bursts, a standard algorithm for shaping request traffic.
Cache async function results in Redis with a decorator, TTL expiry, single-flight locking, and JSON serialization per call signature.
Connect through Redis Sentinel for automatic failover, detecting role changes, retrying reads on replicas, and fencing split-brain writes.
Decorate a function so transient exceptions are retried a fixed number of times with growing delay, keeping call sites free of retry plumbing.
Render dynamic CLI tables with Rich Live mode, updating rows in place as background tasks progress and finishing with a clean summary.
Generate cryptographically secure tokens with the secrets module, comparing them in constant time and binding usage scope per token.
Throttle FastAPI endpoints with SlowAPI using a Redis backend, per-user limits, custom headers, and exempted internal callers.
Drive async SQLAlchemy sessions with pooled engines, per-request session scopes, and transaction guards that always release connections.
Set per-session isolation levels in SQLAlchemy, using repeatable read for consistent reports and read committed for regular traffic.
Open a SQLite connection as a context manager so transactions commit on success and roll back on error, and the connection always closes.
Define a GraphQL schema with Strawberry on FastAPI, writing typed resolvers for queries and mutations with context dependency injection.
Bind request-scoped context with structlog, so every log line carries correlation fields without threading state through call stacks.
Configure a JSON formatter so every log record carries consistent fields, making logs searchable and correlatable across services.
Guard a flaky dependency with a circuit breaker state machine, falling back to cached defaults and opening after repeated failures.
Compose retry behavior with Tenacity using stop conditions, adaptive wait strategies, custom retry predicates, and typed final errors.
Build async CLI commands with Typer, combining type-annotated options, enum choices, environment fallbacks, and per-command validation.
Configure uvicorn worker shutdown with timeout windows, draining in-flight requests and cancelling background loops cleanly on signals.
Compute fixed monthly payments and a full amortization table with Decimal rounding, then total the interest paid.
Fan out jobs to a bounded asyncio queue, run a fixed worker pool, and shut down cleanly with sentinel values and task_done.
Relax all edges to compute shortest paths from one source, rebuild the route, and report a reachable negative cycle.
Find lower and upper insertion bounds in sorted sequences with optional key functions, plus exact search and duplicate counting.
Size a Bloom filter from an expected item count and false-positive rate, then add and test members using double hashing.
Estimate a confidence interval for any statistic by resampling with replacement, using a seeded random generator for repeatable runs.
Find a strict majority in one pass with constant memory, verify the candidate, and collect every value above one third.
Distribute keys across nodes with a SHA-256 consistent hash ring, virtual replicas, node add and remove, and minimal key movement.
Extract a safe basename from Content-Disposition headers, honoring RFC 5987 encoding and rejecting traversal segments.
Generate repeatable fake users from a seeded random source, with per-call overrides and stable identifiers for snapshots.
Track a smoothed moving average with a period-derived smoothing factor, plus a windowed simple average for comparison.
Compute file checksums in fixed-size chunks, support alternate hashlib algorithms, and verify expected digests in constant time.
Convert seconds into compact day, hour, minute, and second strings and parse those strings back with strict validation.
Abstract time behind a Clock protocol, provide a fake clock that can advance instantly, and drive a TTL cache without sleeping.
Normalize half-open intervals, merge overlaps or adjacent ranges, and reject invalid bounds with clear validation errors.
Apply RFC 6902 add, remove, replace, move, copy, and test operations through JSON Pointers while leaving the input document unchanged.
Compute edit distance in O(n*m) time and O(min(n,m)) space, calculate similarity, and suggest the closest matching candidate.
Memoize async loader results with a per-key TTL and lock so concurrent misses trigger one upstream call instead of a herd.
Cancel running asyncio workers, catch CancelledError for cleanup, and report how many items were processed before shutdown.
Limit concurrent asyncio tasks with a semaphore, keep input order in the results, and report per-task failures without cancelling the batch.
Run coroutines in an asyncio.TaskGroup so the first failure cancels siblings, then inspect the raised ExceptionGroup.
Encode integers with Crockford Base32 and decode human-typed values that contain hyphens or confusable letters like O and I.
Encode payloads as Base58 with a double SHA-256 checksum, preserve leading zero bytes, and reject corrupted input on decode.
Group any iterable into fixed-size lists lazily, preserve the final partial batch, and stop cleanly when the source is exhausted.
Wrap state changes in a context manager that commits on success, restores a snapshot on any exception, and re-raises the error.
Parse five-field cron expressions and compute the next run times, including weekday and month boundaries.
Detect a CSV delimiter and quote style from a sample, then parse rows into dictionaries without hard-coding comma assumptions.
Stream CSV rows with the csv module, validate required headers, convert typed fields, and route rejected rows to a separate file.
Enforce types and ranges on dataclass fields at construction time, normalize values, and raise one error listing every invalid field.
Split a Decimal amount across integer weights while keeping cent-level totals exact, distributing leftover cents deterministically.
Merge nested configuration mappings layer by layer, replacing scalars and lists while keeping the default tree untouched.
Race several async replicas, return the first successful result, cancel the losing tasks, and report a clear failure.
Compute shortest distances between every pair of nodes and reconstruct routes with a next-hop matrix in O(n^3) time.
Select the k largest or smallest scores with heapq, keep memory bounded at k entries, and sort ties by name for stable output.
Validate webhook payload signatures with HMAC-SHA256, constant-time comparison, and a timestamp window that blocks replay attacks.
Flag usernames that mix Latin with Cyrillic or Greek letters used as lookalikes, and explain each suspicious character.
Resume an interrupted HTTP download with a Range request, appending only missing bytes and restarting when the server ignores it.
Normalize and validate IBAN values with length, character, and mod-97 checksum rules before persisting account data.
Normalize hyphens and spaces, then verify ISBN-10 and ISBN-13 check digits with the official weighted modulo rules.
Convert nested JSON objects to dotted key paths and reconstruct them, rejecting conflicting paths instead of silently overwriting.
Iterate JSON Lines files lazily, skip blank lines, report malformed records with line numbers, and cap record size to avoid memory spikes.
Reduce floating-point drift with Kahan and Neumaier compensated summation, and see where plain left-to-right addition loses a value.
Fit a straight line through paired x and y values using least squares, then compute the coefficient of determination and predict new points.
Parse RFC 8288 Link headers into named relations while respecting commas inside quoted titles and target URLs.
Configure Python logging with a rotating file handler that caps file size, keeps numbered backups, and flushes each record.
Build a thread-safe LRU cache on OrderedDict with capacity eviction, hit and miss counters, and a memoize decorator for pure functions.
Run operator-supplied regular expressions with the regex module timeout, an input length cap, and explicit failure handling.
Resolve user-supplied relative paths under a fixed root, reject absolute or traversal inputs, and verify the final path stays inside.
Extract gzipped tar archives after rejecting absolute paths, parent traversal, and link members that escape the destination.
Parse and compare semantic version strings with prerelease precedence, then sort a mixed release list correctly.
Apply a batch of stock updates inside one SQLite transaction with validation, ON CONFLICT upserts, and rollback on any bad row.
Build a durable SQLite job queue that claims work with a time-limited lease, retries abandoned jobs, and deletes finished rows.
Parse text/event-stream frames into structured events and wrap the HTTP read loop with bounded reconnect attempts and backoff.
Emit JSON log lines with a custom formatter, attach request context through ContextVar, redact secret fields, and keep UTC timestamps.
Rank the most distinctive keywords in a small document set with term frequency, inverse document frequency, and stop-word filtering.
Implement a monotonic-clock token bucket that allows bursts, refills at a fixed rate, and returns the wait time when a request is denied.
Parse TOML into frozen dataclasses, validate nested service and database tables, and report missing or mistyped keys with clear errors.
Order build targets from a prerequisite graph with Kahn's algorithm and fail loudly when a dependency cycle prevents a complete order.
Insert weighted words into a trie, autocomplete by prefix, rank suggestions by weight, and reject empty or non-string input.
Turn Unicode headings into stable ASCII URL slugs with transliteration, separator collapsing, and length limits.
Track connected components with union by rank and path compression, then answer connectivity queries in near-constant time.
Encode non-negative integers as compact LEB128 bytes and decode them sequentially, with ZigZag helpers for signed values.
Track count, mean, and sample standard deviation in one pass with Welford's algorithm, avoiding catastrophic cancellation.
Read a large XML document without loading it whole, yield one record at a time, and clear processed elements to free memory.
Parse repeated query parameters into a multimap, rebuild a stable query string, and read typed single-value flags safely.
Keep the newest N items in a fixed-size circular buffer, return the evicted value on overflow, and read the latest slice.
Turn untrusted filenames into safe basenames by stripping paths, blocking reserved names, normalizing Unicode, and limiting length.
Split plain text into sentences while keeping common abbreviations, decimals, and closing quotes attached to the right sentence.
Run safe parameterized SQLite queries with bound values, allowlisted sort columns, dynamic IN clauses, and repository error handling.
Encode and decode length-prefixed binary packets with a magic header, version checks, payload limits, and truncation errors.
Walk a directory without following links that escape the root, recording skipped entries and enforcing a depth limit.
Map a function over items with a bounded thread pool, preserve input order, and cancel pending work when the overall deadline expires.
Normalize scheme, host, port, dot segments, and query order while dropping tracking parameters, producing a stable cache key.
An argument parser that reads flags from the command line and environment with declared precedence, reporting which source supplied each value.
A test sandbox that creates a private temporary directory tree, exposes path helpers, and removes everything even when assertions fail.
A staged data pipeline that runs named stages in order, stops at the first failure, and reports which stage and record index broke.
An atomic file writer that stages to a temporary file in the same directory, fsyncs, and renames so readers never observe partial content.
A chunked file reader that streams a file in bounded memory, handles partial multibyte characters, and reports exact bytes consumed.
An idempotency key store that replays the recorded response for duplicate keys and rejects reuse with a different payload.
A typed retry decorator that retries only transient failures, caps exponential backoff and adds jitter to avoid thundering herds.