yandex / yandex-taxi-testsuite

testsuite: microservices testing framework
MIT License
146 stars 39 forks source link

[feature-request] Variable Resources #4

Open Kaveshnikov opened 3 years ago

Kaveshnikov commented 3 years ago

There is such a feature in aiohttp called Variable Resources. It's possible to implement similar functionality inside a handler registered with a prefix. In my opinion Variable Resources is more suitable solution.

So here is two examples with the same logic:

Handler With Prefix Path

prefix = '/a'

def split_path(path, prefix):
    return path[len(prefix) + 1:].split('/')

@mockserver.json_handler(prefix, prefix=True)
async def handle(request):
    path_parts = split_path(request.path, prefix)

    if not path_parts or len(path_parts) > 2 or path_parts[1] != 'c':
        raise web.HTTPNotFound

    b = path_parts[0]
    response = {'b': b, 'resource': 'c'}
    return response

Handler With Variable Resource

@mockserver.json_handler('/a/{b}/c')
async def handle(request):
    b = request.match_info['b']
    return {'b': b, 'resource': 'c'}
vitek commented 2 years ago

You can use regex pattern, see:

@mockserver.handler(r'/path/(?P<num>\d+)', regex=True)
def my_handler(request: http.Request, num: str):
    ...

Will update docs later, see example usage here:

https://github.com/yandex/yandex-taxi-testsuite/blob/develop/tests/plugins/mockserver/test_parametrized_paths.py#L8