75 lines
3.0 KiB
Python
75 lines
3.0 KiB
Python
from typing import Sequence, Tuple, Optional, List
|
|
|
|
from bugis.core import Tree, PathHandler, HttpContext, HttpMethod, PathIterator
|
|
from bugis.core import HttpMethod
|
|
from pwo import Maybe
|
|
import unittest
|
|
|
|
|
|
class PathIteratorTest(unittest.TestCase):
|
|
cases: Tuple[Tuple[str, Tuple[str, ...]], ...] = (
|
|
('/', tuple()),
|
|
('root/foo', ('root', 'foo')),
|
|
('/root', ('root',)),
|
|
('/root', ('root',)),
|
|
('/root/', ('root',)),
|
|
('/root/bar/', ('root', 'bar')),
|
|
)
|
|
|
|
def test_path_iterator(self):
|
|
for (case, expected) in self.cases:
|
|
with self.subTest(case) as _:
|
|
components = tuple((c for c in PathIterator(case)))
|
|
self.assertEqual(expected, components)
|
|
|
|
|
|
class TreeTest(unittest.TestCase):
|
|
tree: Tree
|
|
handlers: List[PathHandler]
|
|
|
|
def setUp(self):
|
|
self.tree = Tree()
|
|
|
|
class TestHandler(PathHandler):
|
|
|
|
def match(self, subpath: Sequence[str], method: HttpMethod) -> bool:
|
|
return True
|
|
|
|
def handle_request(self, ctx: HttpContext):
|
|
pass
|
|
|
|
self.handlers = [TestHandler() for _ in range(10)]
|
|
|
|
routes: Tuple[Tuple[Tuple[str, ...], Optional[HttpMethod], PathHandler], ...] = (
|
|
(('home', 'something'), HttpMethod.GET, self.handlers[0]),
|
|
(('home', 'something_else'), HttpMethod.GET, self.handlers[1]),
|
|
(('home', 'something_else'), HttpMethod.POST, self.handlers[2]),
|
|
(('home', 'something', 'object'), HttpMethod.GET, self.handlers[3]),
|
|
(('home', 'something_else', 'foo'), HttpMethod.GET, self.handlers[4]),
|
|
(('home',), HttpMethod.GET, self.handlers[5]),
|
|
(('home',), HttpMethod.POST, self.handlers[6]),
|
|
(('home',), None, self.handlers[7]),
|
|
)
|
|
|
|
for path, method, handler in routes:
|
|
self.tree.add((p for p in path), method, handler)
|
|
|
|
def test_tree(self):
|
|
|
|
cases: Tuple[Tuple[str, HttpMethod, Optional[int]], ...] = (
|
|
('http://localhost:127.0.0.1:5432/home/something', HttpMethod.GET, 0),
|
|
('http://localhost:127.0.0.1:5432/home/something_else', HttpMethod.GET, 1),
|
|
('http://localhost:127.0.0.1:5432/home/something_else', HttpMethod.POST, 2),
|
|
('http://localhost:127.0.0.1:5432/home/something/object', HttpMethod.GET, 3),
|
|
('http://localhost:127.0.0.1:5432/home/something_else/foo', HttpMethod.GET, 4),
|
|
('http://localhost:127.0.0.1:5432/', HttpMethod.GET, None),
|
|
('http://localhost:127.0.0.1:5432/home', HttpMethod.GET, 5),
|
|
('http://localhost:127.0.0.1:5432/home', HttpMethod.POST, 6),
|
|
('http://localhost:127.0.0.1:5432/home', HttpMethod.PUT, 7),
|
|
)
|
|
for url, method, handler_num in cases:
|
|
with self.subTest(f"{str(method)} {url}"):
|
|
res = self.tree.get_handler(url, method)
|
|
self.assertIs(Maybe.of(handler_num).map(self.handlers.__getitem__).or_none(), res)
|
|
|