diff --git a/babybuddy/settings/test.py b/babybuddy/settings/test.py index 14f2b59e..d5672d8d 100644 --- a/babybuddy/settings/test.py +++ b/babybuddy/settings/test.py @@ -24,3 +24,7 @@ AXES_ENABLED = False # See https://github.com/zlorf/django-dbsettings#a-note-about-caching DBSETTINGS_USE_CACHE = False + +# We want to test the home assistant middleware + +ENABLE_HOME_ASSISTANT_SUPPORT = True diff --git a/babybuddy/tests/tests_home_assistant.py b/babybuddy/tests/tests_home_assistant.py new file mode 100644 index 00000000..73243f1d --- /dev/null +++ b/babybuddy/tests/tests_home_assistant.py @@ -0,0 +1,70 @@ +import json + +from django.test import TestCase, override_settings, tag +from django.test import Client as HttpClient +from django.contrib.auth import get_user_model +from django.core import mail +from django.core.management import call_command + +from faker import Faker + +from babybuddy.views import UserUnlock + + +class HomeAssistantMiddlewareTestCase(TestCase): + """ + Tests are executed on the REST-API because that one constructs + full absolute URLs. However, the middleware is part of the babybuddy + so the test lives in here. + """ + + @classmethod + def setUpClass(cls): + super(HomeAssistantMiddlewareTestCase, cls).setUpClass() + fake = Faker() + call_command("migrate", verbosity=0) + + cls.c = HttpClient() + + fake_user = fake.simple_profile() + cls.credentials = { + "username": fake_user["username"], + "password": fake.password(), + } + cls.user = get_user_model().objects.create_user( + is_superuser=True, is_staff=True, **cls.credentials + ) + + def test_no_ingress_request(self): + self.c.login(**self.credentials) + + response = self.c.get("/api/", headers={"Accept": "application/json"}) + json_response = json.loads(response.content) + + self.assertEqual(json_response["profile"], "http://testserver/api/profile") + + def test_ingress_request_no_x_ingress_path(self): + self.c.login(**self.credentials) + + response = self.c.get( + "/api/", + headers={"Accept": "application/json", "X-Hass-Source": "core.ingress"}, + ) + json_response = json.loads(response.content) + + self.assertEqual(json_response["profile"], "http://testserver/api/profile") + + def test_ingress_request_with_x_ingress_path(self): + self.c.login(**self.credentials) + + response = self.c.get( + "/api/", + headers={ + "Accept": "application/json", + "X-Hass-Source": "core.ingress", + "X-Ingress-Path": "/magic/sub/url", + }, + ) + json_response = json.loads(response.content) + + self.assertEqual(json_response["profile"], "http://testserver/magic/sub/url/api/profile")