### Install Looptime and pytest-asyncio Source: https://github.com/nolar/looptime/blob/main/docs/getting-started.rst Installs the necessary packages for running asynchronous tests with looptime. This includes the looptime library itself and pytest-asyncio to support async test execution. ```bash pip install pytest-asyncio pip install looptime ``` -------------------------------- ### Configure start and end times Source: https://context7.com/nolar/looptime/llms.txt Demonstrates setting initial loop time and end-of-time timeouts using marker arguments or module-level configuration. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime(start=100, end=200) async def test_configured_time(): await asyncio.sleep(50) assert asyncio.get_running_loop().time() == 150 @pytest.mark.asyncio @pytest.mark.looptime(start=lambda: 1000) async def test_dynamic_start(): await asyncio.sleep(10) assert asyncio.get_running_loop().time() == 1010 pytestmark = [ pytest.mark.asyncio, pytest.mark.looptime(end=60), ] ``` -------------------------------- ### Run asyncio tests with fast time forwarding Source: https://github.com/nolar/looptime/blob/main/README.md This example demonstrates how to run asyncio tests with looptime enabled using pytest. It shows the basic setup and how to verify that the event loop's time advances as expected after an asyncio.sleep call. Ensure pytest-asyncio and looptime are installed. ```python import asyncio import pytest @pytest.mark.asyncio async def test_me(): await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` -------------------------------- ### Activate Looptime using Marks Source: https://github.com/nolar/looptime/blob/main/docs/getting-started.rst Shows how to activate looptime's fast time forwarding for individual async tests by applying the '@pytest.mark.looptime' decorator. This allows for selective acceleration of tests without needing a global command-line flag. The example test function is identical to the CLI activation example. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_me(): await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` ```bash pytest ``` -------------------------------- ### Configuring looptime Settings for Tests (Python) Source: https://github.com/nolar/looptime/blob/main/docs/configuration.rst Illustrates how to configure `looptime` settings, specifically `end` and `idle_timeout`, at different levels. This example shows module-level defaults and function-level overrides for the `end` time, demonstrating how the closest marker's value is applied. It also includes an assertion to verify the loop time. ```python import asyncio import pytest pytestmark = pytest.mark.looptime(end=10, idle_timeout=1) @pytest.mark.asyncio @pytest.mark.looptime(end=101) async def test_me(): await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` -------------------------------- ### Demonstrate floating point precision issues Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Examples showing common floating-point arithmetic inaccuracies in Python that can affect time-based assertions in tests. ```python >>> 0.2-0.05 0.15000000000000002 >>> 0.2-0.19 0.010000000000000009 >>> 0.2+0.21 0.41000000000000003 >>> 100_000 * 0.000_001 0.09999999999999999 ``` -------------------------------- ### Integrate looptime with Custom Event Loops (Python) Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Provides examples for integrating the looptime library with custom event loops in pytest, catering to different versions of pytest-asyncio. This involves creating descendant classes and configuring event loop policies. ```python import looptime import pytest from wherever import CustomEventLoop class LooptimeCustomEventLoop(looptime.LoopTimeEventLoop, CustomEventLoop): pass @pytest.fixture def event_loop(): return LooptimeCustomEventLoop() ``` ```python import asyncio import looptime import pytest from wherever import CustomEventLoop class LooptimeCustomEventLoop(looptime.LoopTimeEventLoop, CustomEventLoop): pass class LooptimeCustomEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def new_event_loop(self): return LooptimeCustomEventLoop() @pytest.fixture(scope='session') def event_loop_policy(): return LooptimeCustomEventLoopPolicy() ``` -------------------------------- ### Mark individual asyncio tests for fast time forwarding Source: https://github.com/nolar/looptime/blob/main/README.md This example shows how to selectively enable looptime for specific asyncio tests using the `@pytest.mark.looptime` decorator. This approach is useful when you don't want to apply fast time forwarding to all tests in your suite. It also verifies the event loop's time advancement after a sleep. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_me(): await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` -------------------------------- ### Disable Looptime for Specific Tests with @pytest.mark.looptime(False) Source: https://context7.com/nolar/looptime/llms.txt Shows how to disable LoopTime's time fast-forwarding for individual tests by applying the `@pytest.mark.looptime(False)` marker. This is useful for tests that must execute in real-time, ensuring accurate measurement of time-dependent operations. The example asserts that a real-time sleep duration is respected. ```python import asyncio import time import pytest @pytest.mark.asyncio @pytest.mark.looptime(False) # Disable looptime for this test async def test_real_time_only(): """This test always uses real time, even with --looptime flag.""" start = time.monotonic() await asyncio.sleep(0.1) elapsed = time.monotonic() - start assert elapsed >= 0.1 # Real time passed # In conftest.py or test file def pytest_configure(config): """Configure --no-looptime to disable globally.""" # pytest --no-looptime disables the plugin entirely pass ``` -------------------------------- ### Enable Looptime globally via CLI Source: https://context7.com/nolar/looptime/llms.txt Demonstrates how to enable time fast-forwarding for all async tests using the --looptime flag. ```python import asyncio import pytest @pytest.mark.asyncio async def test_basic_sleep(): """Test completes in ~0.01 seconds real time, but loop time shows 100 seconds.""" await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` ```bash pytest --looptime ``` -------------------------------- ### Advanced Looptime Configuration Source: https://context7.com/nolar/looptime/llms.txt Demonstrates fine-tuning looptime using parameters like resolution, noop_cycles, and idle_timeout, as well as overriding module-level defaults. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime(start=0, end=1000, resolution=1e-6, noop_cycles=42) async def test_all_options(looptime): await asyncio.sleep(100) assert looptime == 100 ``` -------------------------------- ### Configure Looptime Event Loop Policies Source: https://context7.com/nolar/looptime/llms.txt Demonstrates how to create custom event loop policies and mixins to enable looptime functionality within asyncio applications. ```python import asyncio import looptime class LooptimeEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def new_event_loop(self): loop = super().new_event_loop() return looptime.patch_event_loop(loop) class LooptimeCustomEventLoop(looptime.LoopTimeEventLoop, asyncio.SelectorEventLoop): pass ``` -------------------------------- ### Enable time compaction in async fixtures Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Demonstrates how to manually wrap async fixture logic with looptime.enabled() to achieve time compaction. This approach is necessary because automatic compaction is limited to the test function scope. ```python import looptime import pytest_async @pytest_async.fixture def async_fixture_example(): with looptime.enabled(): # Execute some async time-based code, but compacted. await asyncio.sleep(1) # Go to the test(s). yield with looptime.enabled(): # Execute some async time-based code, but compacted. await asyncio.sleep(1) ``` ```python import asyncio import pytest @pytest.fixture async def fixt(): loop = asyncio.get_running_loop() loop.setup_looptime(start=123, end=456) with loop.looptime_enabled(): await do_things() ``` -------------------------------- ### Integrate Looptime with async-timeout Source: https://context7.com/nolar/looptime/llms.txt Shows how to use the async-timeout library alongside looptime, including handling no-op cycles for complex timeout scenarios. ```python import asyncio import async_timeout import pytest @pytest.mark.asyncio @pytest.mark.looptime(noop_cycles=100) async def test_complex_timeout_scenario(): async with async_timeout.timeout(9): await asyncio.sleep(1) await asyncio.sleep(1) await asyncio.sleep(1) assert asyncio.get_running_loop().time() == 3 ``` -------------------------------- ### Activate Looptime via CLI Source: https://github.com/nolar/looptime/blob/main/docs/getting-started.rst Demonstrates how to activate looptime's fast time forwarding for async tests using the '--looptime' command-line flag. The provided Python code shows a simple async test that utilizes asyncio.sleep, which will be significantly sped up when the flag is active. ```python import asyncio import pytest @pytest.mark.asyncio async def test_me(): await asyncio.sleep(100) assert asyncio.get_running_loop().time() == 100 ``` ```bash pytest --looptime ``` -------------------------------- ### Applying looptime Marker to Test Suites (Python) Source: https://github.com/nolar/looptime/blob/main/docs/configuration.rst Demonstrates how to apply the `pytest.mark.looptime` marker to an entire test suite (module level) using `pytestmark`. This configures the specified loop time settings for all tests within that suite. It also includes the `pytest.mark.asyncio` marker for asynchronous tests. ```python import asyncio import pytest pytestmark = [ pytest.mark.asyncio, pytest.mark.looptime(end=60), ] async def test_me(): await asyncio.sleep(100) ``` -------------------------------- ### Synchronize Thread Pools with Fake Time Source: https://context7.com/nolar/looptime/llms.txt Configures idle_step to synchronize fake looptime with real-time thread pool executors, ensuring blocking operations complete correctly. ```python import asyncio import threading import pytest @pytest.mark.asyncio @pytest.mark.looptime(idle_step=0.01) async def test_executor_sync(event_loop): sync_event = threading.Event() result = await event_loop.run_in_executor(None, lambda: sync_event.set() or "completed") assert result == "completed" assert sync_event.is_set() ``` -------------------------------- ### Perform Loop Time Assertions with looptime Fixture (Python) Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Shows how to use the looptime fixture for syntactic sugar in asserting loop times within asynchronous tests. It acts as a proxy for asyncio.get_running_loop().time() and supports comparisons and basic arithmetic. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime(start=100) async def test_me(looptime): await asyncio.sleep(1.23) assert looptime == 101.23 ``` -------------------------------- ### Synchronize sync and async code with looptime in Python Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Illustrates how looptime addresses synchronization issues between synchronous and asynchronous code when using fake time. It explains the problem where synchronous tasks submitted to executors might not complete before a timeout occurs and describes looptime's solution of stepping through time with real-time sleeps. ```python import asyncio import async_timeout import contextlib import pytest import threading def sync_fn(event: threading.Event): event.set() @pytest.mark.asyncio @pytest.mark.looptime async def test_me(event_loop): sync_event = threading.Event() with contextlib.suppress(asyncio.TimeoutError): async with async_timeout.timeout(9): await event_loop.run_in_executor(None, sync_fn, sync_event) assert sync_event.is_set() ``` -------------------------------- ### Assert time with the looptime fixture Source: https://context7.com/nolar/looptime/llms.txt Uses the looptime fixture to perform clean time assertions and avoid floating-point precision issues in tests. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime(start=100) async def test_looptime_fixture(looptime): await asyncio.sleep(1.23) assert looptime == 101.23 assert looptime - 100 == 1.73 @pytest.mark.asyncio @pytest.mark.looptime async def test_looptime_precision(looptime): await asyncio.sleep(0.1) await asyncio.sleep(0.2) assert looptime == 0.3 ``` -------------------------------- ### Bind LoopTimeProxy to Specific Event Loops with @ Operator Source: https://context7.com/nolar/looptime/llms.txt Demonstrates how to bind the LoopTimeProxy to specific event loops using the '@' operator. This allows for precise control over which event loop the proxy interacts with, useful for testing scenarios involving multiple concurrent event loops. It shows creating a patched event loop and asserting the proxy's time value against it. ```python import asyncio import looptime import pytest def test_multiple_loops(looptime): """Use looptime proxy with different event loops.""" # Create a separate patched event loop other_loop = looptime.patch_event_loop( asyncio.new_event_loop(), start=500 ) async def run_in_other(): await asyncio.sleep(25) other_loop.run_until_complete(run_in_other()) # Use @ operator to bind proxy to specific loop assert looptime @ other_loop == 525 other_loop.close() @pytest.mark.asyncio @pytest.mark.looptime(start=100) async def test_proxy_binding(looptime): """Bind LoopTimeProxy to the current loop.""" current_loop = asyncio.get_running_loop() await asyncio.sleep(10) # Both ways give the same result assert looptime == 110 assert looptime @ current_loop == 110 ``` -------------------------------- ### Constructing and Patching Event Loop Classes with Looptime Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Demonstrates how looptime constructs and patches asyncio event loop classes. `make_event_loop_class` creates a new class inheriting from a given class and looptime's specialized loop, caching the result. `patch_event_loop` applies this patching to an existing event loop instance. ```python # Constructs a new class inheriting from cls and looptime's specialized event loop. # looptime.make_event_loop_class(cls) # Replaces the event loop's class with the newly constructed one. # looptime.patch_event_loop(loop) # Equivalent hack for patching an existing event loop instance: # loop.__class__ = looptime.make_event_loop_class(loop.__class__) ``` -------------------------------- ### Enable Time Compaction with looptime.enabled() Source: https://context7.com/nolar/looptime/llms.txt Use the enabled() context manager or decorator to temporarily enable time compaction. This is useful for fast-forwarding sleep calls in fixtures or helper functions. ```python import asyncio import looptime @looptime.enabled(strict=True) async def helper_function(): await asyncio.sleep(5) return "done" async def manual_looptime_control(): loop = looptime.new_event_loop() with looptime.enabled(loop=loop): await asyncio.sleep(100) print(f"Loop time: {loop.time()}") ``` -------------------------------- ### Use @pytest.mark.looptime for selective tests Source: https://context7.com/nolar/looptime/llms.txt Shows how to apply the looptime marker to specific tests to isolate time manipulation, leaving other tests unaffected. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_with_marker(): """Only this test uses fake time.""" await asyncio.sleep(50) assert asyncio.get_running_loop().time() == 50 @pytest.mark.asyncio async def test_without_marker(): """This test runs with real time.""" await asyncio.sleep(0.1) ``` -------------------------------- ### Bind looptime Proxy to Specific Event Loop (Python) Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Illustrates how to create a new proxy object bound to a specific event loop using the '@' operation. This works for both fake and real-world time event loops and is useful for precise timing assertions. ```python import asyncio from looptime import patch_event_loop def test_me(looptime): new_loop = patch_event_loop(asyncio.new_event_loop(), start=100) new_loop.run_until_complete(asyncio.sleep(1.23)) assert looptime @ new_loop == 101.23 ``` -------------------------------- ### Patch Event Loop with looptime for Timing (Python) Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Demonstrates how to patch an existing event loop object or class using looptime.patch_event_loop to enable loop time measurement and assertions. This is shown for different pytest-asyncio versions. ```python import asyncio import looptime import pytest @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() return looptime.patch_event_loop(loop) ``` ```python import asyncio import looptime import pytest @pytest.fixture def event_loop_policy(): loop = asyncio.new_event_loop() return looptime.patch_event_loop(loop) ``` -------------------------------- ### Injecting looptime Marker via Pytest Hook (Python) Source: https://github.com/nolar/looptime/blob/main/docs/configuration.rst Shows how to dynamically inject `pytest.mark.asyncio` and `pytest.mark.looptime` markers into test functions using a pytest hook (`pytest_pycollect_makeitem`). This allows for programmatic control over test marking based on certain conditions, such as identifying coroutine functions. ```python import inspect import pytest @pytest.hookimpl(hookwrapper=True) def pytest_pycollect_makeitem(collector, name, obj): if collector.funcnamefilter(name) and inspect.iscoroutinefunction(obj): pytest.mark.asyncio(obj) pytest.mark.looptime(end=60)(obj) yield ``` -------------------------------- ### Measure Code Block Duration with Chronometer (Python) Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Demonstrates using the looptime.Chronometer as a context manager to measure the real-world time duration of asynchronous code blocks. It can be used with pytest fixtures and asyncio. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_me(chronometer): with chronometer: await asyncio.sleep(1) await asyncio.sleep(1) assert chronometer.seconds < 0.01 # random code overhead ``` ```python import asyncio import looptime import pytest @pytest.mark.asyncio @pytest.mark.looptime(start=100) async def test_me(chronometer, event_loop): with chronometer, looptime.Chronometer(event_loop.time) as loopometer: await asyncio.sleep(1) await asyncio.sleep(1) assert chronometer.seconds < 0.01 # random code overhead assert loopometer.seconds == 2 # precise timing, no code overhead assert event_loop.time() == 102 ``` -------------------------------- ### Patch Custom Event Loops Source: https://context7.com/nolar/looptime/llms.txt Integrate looptime functionality into custom event loops using patch_event_loop. This enables time control features for existing asyncio loop instances. ```python import asyncio import looptime import pytest @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() return looptime.patch_event_loop(loop, start=0, end=100) ``` -------------------------------- ### Handle premature finalization with looptime in Python Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Demonstrates how looptime prevents premature timeouts in asynchronous operations by performing dummy zero-time cycles. This ensures that tasks and coroutines have a chance to be scheduled before time is advanced, resolving issues with libraries like async_timeout. ```python import asyncio import async_timeout import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_me(): async with async_timeout.timeout(9): await asyncio.sleep(1) ``` -------------------------------- ### Measure Duration with Chronometer Source: https://context7.com/nolar/looptime/llms.txt The Chronometer class and fixture allow for measuring both real-world elapsed time and virtual loop time. It supports both synchronous and asynchronous code blocks. ```python import asyncio import looptime import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_chronometer_fixture(chronometer): with chronometer: await asyncio.sleep(100) await asyncio.sleep(100) assert chronometer.seconds < 0.1 assert asyncio.get_running_loop().time() == 200 def test_sync_chronometer(): import time with looptime.Chronometer() as chrono: time.sleep(0.1) assert 0.1 <= chrono.seconds < 0.2 ``` -------------------------------- ### Manage idle I/O activities with looptime in Python Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Explains how looptime handles tests involving external I/O operations that might otherwise hang indefinitely. It addresses the scenario where the event loop is left with only I/O tasks and no internal callbacks, preventing tests from progressing. ```python import aiohttp import pytest @pytest.mark.asyncio @pytest.mark.looptime async def test_me(): async with aiohttp.ClientSession(timeout=None) as session: await session.get('http://some-unresponsive-web-site.com') ``` -------------------------------- ### Test event loop time limits with pytest Source: https://github.com/nolar/looptime/blob/main/docs/nuances.rst Demonstrates how to use the @pytest.mark.looptime decorator to enforce time limits on asynchronous tests. It compares the behavior of looptime's end-of-time setting against standard asyncio timeout mechanisms. ```python import asyncio import pytest @pytest.mark.asyncio @pytest.mark.looptime(end=10) async def test_the_end_of_time(chronometer, looptime): with chronometer: with pytest.raises(asyncio.TimeoutError): await asyncio.Event().wait() assert looptime == 10 assert chronometer >= 10 @pytest.mark.asyncio @pytest.mark.looptime async def test_async_timeout(chronometer, looptime): with chronometer: with pytest.raises(asyncio.TimeoutError): await asyncio.wait_for(asyncio.Event().wait(), timeout=10) assert looptime == 10 assert chronometer < 0.1 ``` -------------------------------- ### Custom Event Loop Policy for Looptime Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst Defines a custom asyncio event loop policy that integrates with looptime. This policy ensures that new event loops created are patched by looptime. It inherits from asyncio.DefaultEventLoopPolicy and overrides the new_event_loop method. ```python import asyncio import looptime class LooptimeEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def new_event_loop(self): loop = super().new_event_loop() return looptime.patch_event_loop(loop) ``` -------------------------------- ### Pytest Fixture for Event Loop Policy Source: https://github.com/nolar/looptime/blob/main/docs/tools.rst A pytest fixture that provides the custom LooptimeEventLoopPolicy for session-scoped use. This allows tests to run with the looptime-patched event loop policy automatically. ```python import pytest @pytest.fixture(scope='session') def event_loop_policy(): return LooptimeEventLoopPolicy() ``` -------------------------------- ### Handle LoopTimeoutError and IdleTimeoutError Source: https://context7.com/nolar/looptime/llms.txt Manage loop execution limits by catching LoopTimeoutError when the loop reaches a configured end time, or IdleTimeoutError when the loop waits indefinitely for I/O. ```python import asyncio import looptime import pytest @pytest.mark.asyncio @pytest.mark.looptime(end=10) async def test_end_of_time(chronometer, looptime): with chronometer: with pytest.raises(asyncio.TimeoutError) as exc_info: await asyncio.Event().wait() assert isinstance(exc_info.value, looptime.LoopTimeoutError) @pytest.mark.asyncio @pytest.mark.looptime(idle_timeout=2.0) async def test_idle_timeout(): with pytest.raises(asyncio.TimeoutError) as exc_info: await asyncio.Event().wait() assert isinstance(exc_info.value, looptime.IdleTimeoutError) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.