aboutsummaryrefslogtreecommitdiff
path: root/tests/fixtures/http.py
blob: 0f88fb83dcdbf2af8ce85b5cc7d1ca0a86018563 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import secrets
from collections.abc import AsyncGenerator
from uuid import uuid4

import httpx
import pytest
import requests_mock
from asgi_lifespan import LifespanManager
from generalresearch.redis_helper import RedisConfig
from httpx import ASGITransport, AsyncClient

from jb.decorators import get_redis_config
from jb.main import app


@pytest.fixture(scope="session")
def anyio_backend():
    return "asyncio"


@pytest.fixture(scope="session")
async def httpxclient(redis_config: RedisConfig) -> AsyncGenerator[AsyncClient, None]:
    app.dependency_overrides[get_redis_config] = lambda: redis_config
    # limiter.enabled = True
    # limiter.reset()
    app.testing = True

    async with LifespanManager(app):
        # await FastAPICache.clear()
        transport = ASGITransport(app=app)
        async with AsyncClient(
            transport=transport, base_url="http://127.0.0.1:8001/"
        ) as client:
            yield client
        await client.aclose()

    app.dependency_overrides.clear()


@pytest.fixture()
def no_limit():
    """Fixture to execute asserts before and after a test is run"""
    # limiter.enabled = False
    yield  # this is where the testing happens
    # limiter.enabled = True


@pytest.fixture()
def httpxclient_ip(httpxclient: AsyncClient):
    """Fixture to execute asserts before and after a test is run"""
    httpxclient._transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 8001))  # type: ignore[attr-defined]
    yield httpxclient  # this is where the testing happens
    httpxclient._transport = httpx.ASGITransport(app=app)  # type: ignore[attr-defined]


@pytest.fixture
def mock_requests():
    with requests_mock.Mocker() as m:
        yield m


@pytest.fixture
def email() -> str:
    return "unittest@generalresearch.com"


@pytest.fixture
def amt_worker_id() -> str:
    return uuid4().hex


def generate_hex_id(length: int = 40) -> str:
    # length is number of hex chars, so we need length//2 bytes
    return secrets.token_hex(length // 2)