from typing import Any, Dict from django.conf import settings from django.http import HttpResponse from django.template import Context, Template from django.test import Client from django.urls import path # isort: off from .django_test_setup import * # noqa from .testutils import BaseTestCase # isort: on from django_components import component class CustomClient(Client): def __init__(self, urlpatterns=None, *args, **kwargs): import types if urlpatterns: urls_module = types.ModuleType("urls") urls_module.urlpatterns = urlpatterns # type: ignore settings.ROOT_URLCONF = urls_module else: settings.ROOT_URLCONF = __name__ settings.SECRET_KEY = "secret" # noqa super().__init__(*args, **kwargs) class TestComponentAsView(BaseTestCase): def test_render_component_from_template(self): @component.register("testcomponent") class MockComponentRequest(component.Component): template = """
""" def get(self, request, *args, **kwargs) -> HttpResponse: return self.render_to_response({"variable": "GET"}) def get_context_data(self, variable, *args, **kwargs) -> Dict[str, Any]: return {"variable": variable} def render_template_view(request): template = Template( """ {% load component_tags %} {% component "testcomponent" variable="TEMPLATE" %}{% endcomponent %} """ ) return HttpResponse(template.render(Context({}))) client = CustomClient(urlpatterns=[path("test_template/", render_template_view)]) response = client.get("/test_template/") self.assertEqual(response.status_code, 200) self.assertIn( b'', response.content, ) def test_get_request(self): class MockComponentRequest(component.Component): template = """ """ def get(self, request, *args, **kwargs) -> HttpResponse: return self.render_to_response({"variable": "GET"}) def get_context_data(self, variable, *args, **kwargs) -> Dict[str, Any]: return {"variable": variable} client = CustomClient(urlpatterns=[path("test/", MockComponentRequest.as_view())]) response = client.get("/test/") self.assertEqual(response.status_code, 200) self.assertIn( b'', response.content, ) def test_post_request(self): class MockComponentRequest(component.Component): template = """ """ def post(self, request, *args, **kwargs) -> HttpResponse: variable = request.POST.get("variable") return self.render_to_response({"variable": variable}) def get_context_data(self, variable, *args, **kwargs) -> Dict[str, Any]: return {"variable": variable} client = CustomClient(urlpatterns=[path("test/", MockComponentRequest.as_view())]) response = client.post("/test/", {"variable": "POST"}) self.assertEqual(response.status_code, 200) self.assertIn( b'', response.content, ) def test_replace_slot_in_view(self): class MockComponentSlot(component.Component): template = """ {% load component_tags %}