import pytest from src.turbosloth.exceptions import NotFoundException, MethodNotAllowedException from src.turbosloth.router import Router def test_router_root_handler(): async def f(*args): pass async def d(*args): pass async def a(*args): pass r = Router() r.add('GET', '/', f) r.add('GET', '', f) assert len(r._root.static_subroutes) == 0 assert len(r._root.handler) == 1 assert r._root.handler['GET'] == f r.add('POST', '/', a) assert len(r._root.static_subroutes) == 0 assert len(r._root.handler) == 2 assert r._root.handler['GET'] == f assert r._root.handler['POST'] == a r.add('GET', '/asdf', d) assert len(r._root.static_subroutes) == 1 assert len(r._root.handler) == 2 assert r._root.handler['GET'] == f assert r._root.handler['POST'] == a assert len(r._root.static_subroutes['asdf'].static_subroutes) == 0 assert len(r._root.static_subroutes['asdf'].handler) == 1 assert r._root.static_subroutes['asdf'].handler['GET'] == d def test_router_match(): async def f(*args): pass async def d(*args): pass r = Router() r.add('GET', 'asdf', f) assert r.match('GET', '/asdf') == ({}, f) with pytest.raises(NotFoundException, match='404\tNot Found: asd'): r.match('GET', 'asd') with pytest.raises(MethodNotAllowedException, match=f'405\tMethod Not Allowed: POST /asdf, allowed: GET'): r.match('POST', 'asdf') with pytest.raises(NotFoundException, match=f'404\tNot Found'): r.match('POST', '') def test_router_pattern_match(): async def f(*args): pass r = Router() r.add('GET', '/{some}/asdf', f) r.add('GET', '/{some}/b{some1}c', f) assert r.match('GET', '/1234/asdf') == ({'some': '1234'}, f) assert r.match('GET', '/ /asdf') == ({'some': ' '}, f) assert r.match('GET', '/ /basdfc') == ({'some': ' ', 'some1': 'asdf'}, f) with pytest.raises(NotFoundException, match='404\tNot Found: asd'): r.match('GET', 'asd') with pytest.raises(NotFoundException, match='404\tNot Found: asd'): r.match('GET', 'asd/') with pytest.raises(NotFoundException, match='404\tNot Found: asd'): r.match('GET', 'asd/b') with pytest.raises(NotFoundException, match='404\tNot Found: asd'): r.match('GET', 'asd/basdf') def test_subroutes(): async def f(*args): pass async def d(*args): pass r1 = Router() r2 = Router() r1.add('GET', '/asdf', f) r2.add('GET', '/asdf/a', d) r1.add_subroute(r2, '') assert r1.match('GET', '/asdf') == ({}, f) assert r1.match('GET', '/asdf/a') == ({}, d) r1.add_subroute(r2, '/asdf') assert r1.match('GET', '/asdf/asdf/a') == ({}, d) r1.add_subroute(r2, '/asdf' * 5) assert r1.match('GET', '/asdf' * 5 + '/asdf/a') == ({}, d) with pytest.raises(NotFoundException): r1.match('GET', '/asdf/' * 5 + '/asdf/a') r1.add_subroute(r2, '/asdf/' * 5) assert r1.match('GET', '/asdf/' * 5 + '/asdf/a') == ({}, d)