Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dynamic path params from route in aiohttp when mocking the request?

Using the below route definition, I am trying to extract the book_id out of the URL in aiohttp.

from aiohttp import web
routes = web.RouteTableDef()

@routes.get('/books/{book_id}')
async def get_book_pages(request: web.Request) -> web.Response:
    book_id = request.match_info.get('book_id', None)

    return web.json_response({'book_id': book_id})

Below is the test (using pytest) I have written

import asynctest
import pytest
import json

async def test_get_book() -> None:
    request = make_mocked_request('GET', '/books/1')
    response = await get_book(request)
    assert 200 == response.status
    body = json.loads(response.body)
    assert 1 == body['book_id']

Test Result:

None != 1

Expected :1
Actual   :None

Outside of the tests, when I run a request to /books/1 the response is {'book_id': 1}

What is the correct way to retrieve dynamic values from the path in aiohttp when mocking the request?

like image 319
Rastalamm Avatar asked Oct 14 '25 09:10

Rastalamm


1 Answers

make_mocked_request() knows nothing about an application and its routes.

To pass dynamic info you need to provide a custom match_info object:

async def test_get_book() -> None:
    request = make_mocked_request('GET', '/books/1', 
                                         match_info={'book_id': '1'})
    response = await get_book(request)
    assert 200 == response.status
    body = json.loads(response.body)
    assert 1 == body['book_id']

P.S.

In general, I want to warn about mocks over-usage. Usually, functional testing with aiohttp_client is easier to read and maintain.

I prefer mocking for really hard-to-rest things like network errors emulation. Otherwise your tests do test your own mocks, not a real code.

like image 145
Andrew Svetlov Avatar answered Oct 16 '25 22:10

Andrew Svetlov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!