def test_will_fails_on_invalid_module_name() -> None: # given app = Application() # then with pytest.raises(ApplicationError): app.use("invalid.name")
def test_can_load_dynamically_modules_with_asterisk_ending() -> None: # given app = Application() # when app.use("tests.fixtures.routes.*") # then assert sorted(app._loaded_modules) == [ "tests.fixtures.routes.a", "tests.fixtures.routes.b", ]
def test_can_load_dynamically_modules_with_const_ending() -> None: # given app = Application() # when app.use("tests.*.routes_a.*.routes") # then assert sorted(app._loaded_modules) == [ "tests.fixtures.routes_a.a.routes", "tests.fixtures.routes_a.b.routes", "tests.fixtures.routes_a.c.routes", ]
def test_handling_cookies_by_wsgi_handler() -> None: def _http_start(status_code, headers): assert headers == [ ("content-type", "text/plain"), ("set-cookie", "test=SuperCookie"), ] assert status_code == "200" def _serve_response(request: HttpRequest, next: Callable) -> HttpResponse: assert request.method == HttpMethod.POST response = HttpResponse("OK", headers=request.headers) response.cookies.append(HttpCookie(name="test", value="SuperCookie")) return response app = Application(_serve_response) handler = create_wsgi_handler(app) handler( { "CONTENT_TYPE": "text/plain", "REQUEST_METHOD": "POST", "wsgi.input": BytesIO(b"Test input"), }, _http_start, )
def test_router_not_found() -> None: app = Application() request = HttpRequest(HttpMethod.GET, "/petxxx") response = app(request) assert response.status_code == HttpStatus.NOT_FOUND
def test_can_define_sub_groups() -> None: app = Application() # /group_a with app.group("/group_a") as group_a: # /group_a/one @group_a.get("/one") def one(request: HttpRequest) -> HttpResponse: return HttpResponse("group a.1", status=200) # /group_a/two @group_a.get("/two") def two(request: HttpRequest) -> HttpResponse: return HttpResponse("group a.2", status=200) # /group_a/three with group_a.group("/three") as group_a_subgroup: # /group_a/three/one @group_a_subgroup.get("/one") def three(request: HttpRequest) -> HttpResponse: return HttpResponse("group a.3.1", status=200) # /group_b with app.group("/group_b") as group_b: # /group_b/one @group_b.get("/one") def one(request: HttpRequest) -> HttpResponse: return HttpResponse("group b.1", status=200) request = HttpRequest(HttpMethod.GET, "/group_a/one") response = app(request) assert str(response) == "group a.1" response = group_a(request) assert str(response) == "group a.1" response = group_b(request) assert response.status_code == HttpStatus.NOT_FOUND request = HttpRequest(HttpMethod.GET, "/group_b/one") response = app(request) assert str(response) == "group b.1"
def test_if_request_is_containing_a_handler_name() -> None: # given app = Application() @app.get("/pets") def get_pet(req: HttpRequest) -> HttpResponse: assert req.attributes["handler_name"] == "get_pet" return HttpResponse("pet")
def test_if_function_is_properly_wrapped() -> None: # given app = Application() @app.get("/pets") def get_pet(req: HttpRequest) -> HttpResponse: return HttpResponse("pet") # then assert get_pet.__name__ == "get_pet" func_sig = signature(get_pet) assert list(func_sig.parameters.keys()) == ["req"]
def test_create_wsgi_handler() -> None: def _http_start(status_code, headers): assert status_code == "200" def _serve_response(request: HttpRequest, next: Callable) -> HttpResponse: assert request.method == HttpMethod.POST return HttpResponse("OK") app = Application(_serve_response) handler = create_wsgi_handler(app) handler( { "CONTENT_TYPE": "text/plain", "REQUEST_METHOD": "POST", "wsgi.input": BytesIO(b"Test input"), }, _http_start, )
def test_can_run(): def _app_runner(handler: Callable, host: str, port: int): def _http_start(status_code, headers): assert status_code == "200" assert isinstance(handler, Application) assert host == "0.0.0.0" assert port == 80 response = handler( { "CONTENT_TYPE": "text/plain", "REQUEST_METHOD": "POST", "wsgi.input": BytesIO(b"Test input"), }, _http_start, ) assert response.read() == b"OK" app = Application() assert isinstance(app.middleware, MiddlewarePipeline)
def test_instantiate(self) -> None: client = TestClient(Application()) assert isinstance(client, TestClient)
from chocs import Application, HttpRequest, HttpResponse, HttpStatus, serve app = Application() @app.get("/hello/{name}") def hello(request: HttpRequest) -> HttpResponse: return HttpResponse(body=f"Hello {request.attributes['name']}!") @app.get("*") def default(request: HttpRequest) -> HttpResponse: return HttpResponse("Not found", HttpStatus.NOT_FOUND) serve(app)
def test_can_instantiate(): app = Application()
from chocs.middleware import OpenApiMiddleware open_api_filename = path.dirname(__file__) + "/openapi.yml" def error_handler(request, next) -> HttpResponse: try: return next(request) except ValidationError as error: json_error = {"error_code": error.code, "error_message": str(error)} return HttpResponse( json.dumps(json_error), status=HttpStatus.UNPROCESSABLE_ENTITY ) app = Application(error_handler, OpenApiMiddleware(open_api_filename)) @dataclass() class Pet: id: str name: str @app.post("/pets", parsed_body=Pet) def create_pet(request: HttpRequest) -> HttpResponse: assert isinstance(request.parsed_body, Pet) pet = request.parsed_body # type: Pet return HttpResponse(pet.name)
import time from chocs import Application, HttpRequest, HttpResponse, serve from chocs.middleware import MiddlewareHandler def time_load_middleware(request: HttpRequest, next: MiddlewareHandler) -> HttpResponse: started_at = time.time() response = next(request) total_time = (time.time() - started_at) * 100 response.write(f"\nTotal time taken for generating response: {total_time}") return response app = Application(time_load_middleware) @app.get("/hello/{name}") def hello(request: HttpRequest) -> HttpResponse: return HttpResponse(body=f"Hello {request.attributes['name']}!") serve(app)
def test_router_prioritise_routes_with_no_wildcards() -> None: def test_controller(): pass router = Router() router.append(Route("/pets/*"), test_controller) router.append(Route("/pets/{pet_id}"), test_controller) router.append(Route("*"), test_controller) route, controller = router.match("/pets/11a22") assert route.route == "/pets/{pet_id}" http = Application() @pytest.mark.parametrize( "router_decorator, method", [ (http.get, HttpMethod.GET), (http.post, HttpMethod.POST), (http.put, HttpMethod.PUT), (http.patch, HttpMethod.PATCH), (http.options, HttpMethod.OPTIONS), (http.delete, HttpMethod.DELETE), (http.head, HttpMethod.HEAD), ], ) def test_router_method(router_decorator: Callable, method: HttpMethod) -> None:
from chocs import Application, HttpRequest, HttpResponse, serve def authorise_user(req: HttpRequest, next) -> HttpResponse: ... req.authorised = True return next(req) app = Application(authorise_user) with app.group("/users") as users_module: @users_module.get("/{id}") # GET /users/{id} def get_user(req: HttpRequest) -> HttpResponse: ... @users_module.post("/") # POST /users def create_user(req: HttpRequest) -> HttpResponse: ... with app.group("/companies") as companies_module: ... serve(app)
from chocs import Application, HttpRequest, HttpResponse from chocs.middleware import Middleware, MiddlewareHandler def cors_middleware(request: HttpRequest, next: MiddlewareHandler) -> HttpResponse: response = next(request) response._headers.set("Access-Control-Allow-Origin", "*") return response class CorsMiddleware(Middleware): def __init__(self, allowed_access_from: str): self.cors = allowed_access_from def handle(self, request: HttpRequest, next: MiddlewareHandler) -> HttpResponse: response = next(request) response._headers.set("Access-Control-Allow-Origin", self.cors) return response app = Application(CorsMiddleware("*"))