簡體   English   中英

在 Pytest 測試中緩存異步請求 function

[英]Caching async requests in Pytest test function

I have implemented a test function in pytest which loads data from files, casts it into Python objects and provides a new object for each test.

這些對象中的每一個都包含我需要向服務器發出的請求和預期的響應,function 如下所示:

@pytest.mark.asyncio
@pytest.mark.parametrize('test', TestLoader.load(JSONTest, 'json_tests'))
async def test_json(test: JSONTest, groups: Set[TestGroup], client: httpx.AsyncClient):
    skip_if_not_in_groups(test, groups)

    request = Request(url=test.url, body=test.body.dict())
    response = await client.post(request.url, json=request.body)

    # Assertions down here...

很多時候,我發送許多請求,其中包含相同的http端點和相同的body ,所以響應是相同的,但我正在測試響應中的不同內容。

正因為如此,我想實現一個內存緩存,這樣每次測試運行時,相同的請求就不會被實現兩次。

我試圖做的是創建一個請求 object,它有自己的__hash__實現,並在 function 上使用@asyncstdlib.lru_cache ,它似乎不起作用。

# Does not work...

@asyncstdlib.lru_cache
async def send_request(request: Request, client: httpx.AsyncClient):
    return await client.post(request.url, json=request.body)


@pytest.mark.asyncio
@pytest.mark.parametrize('test', TestLoader.load(JSONTest, 'json_tests'))
async def test_json(test: JSONTest, groups: Set[TestGroup], client: httpx.AsyncClient):
    skip_if_not_in_groups(test, groups)

    request = Request(url=test.url, body=test.body.dict())
    response = await send_request(request)

我正在使用的客戶端: httpx.AsyncClient也實現__hash__ ,它來自pytest.fixture中的conftest.py ,它有一個 scope 的“會話”:

# conftest.py

@pytest.fixture(scope='session')
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.fixture(scope='session')
async def client() -> httpx.AsyncClient:
    async with httpx.AsyncClient() as client:
        yield client

就讓不透明的3rdy方緩存的go,自己緩存。 由於您不需要在單次執行期間清理緩存,因此可以使用普通字典:

_cache = {}


async def send_request(request: Request, client: httpx.AsyncClient):
    if request.url not in _cache:
        _cache[request.url] = await client.post(request.url, json=request.body)
    return _cache[request.url]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM