feat: add decorator for writing component tests (#1008)

* feat: add decorator for writing component tests

* refactor: udpate changelog + update deps pins

* refactor: fix deps

* refactor: make cached_ref into generic and fix linter errors

* refactor: fix coverage testing

* refactor: use global var instead of env var for is_testing state
This commit is contained in:
Juro Oravec 2025-03-02 19:46:12 +01:00 committed by GitHub
parent 81ac59f7fb
commit 7dfcb447c4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
62 changed files with 4428 additions and 3661 deletions

View file

@ -6,23 +6,25 @@ in an actual browser.
import re
from playwright.async_api import Page
from pytest_django.asserts import assertHTMLEqual, assertInHTML
from django_components import types
from tests.django_test_setup import setup_test_config
from django_components.testing import djc_test
from tests.testutils import setup_test_config
from tests.e2e.utils import TEST_SERVER_URL, with_playwright
from tests.testutils import BaseTestCase
setup_test_config({"autodiscover": False})
# NOTE: All views, components, and associated JS and CSS are defined in
# `tests/e2e/testserver/testserver`
class E2eDependencyRenderingTests(BaseTestCase):
@djc_test
class TestE2eDependencyRendering:
@with_playwright
async def test_single_component_dependencies(self):
single_comp_url = TEST_SERVER_URL + "/single"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -46,24 +48,23 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
# Check that the actual HTML content was loaded
self.assertRegex(
data["bodyHTML"],
re.compile(r'Variable: <strong class="inner" data-djc-id-\w{6}="">foo</strong>'),
)
self.assertInHTML('<div class="my-style"> 123 </div>', data["bodyHTML"], count=1)
self.assertInHTML('<div class="my-style2"> xyz </div>', data["bodyHTML"], count=1)
assert re.compile(
r'Variable: <strong class="inner" data-djc-id-\w{6}="">foo</strong>'
).search(data["bodyHTML"]) is not None
assertInHTML('<div class="my-style"> 123 </div>', data["bodyHTML"], count=1)
assertInHTML('<div class="my-style2"> xyz </div>', data["bodyHTML"], count=1)
# Check components' inlined JS got loaded
self.assertEqual(data["componentJsMsg"], "kapowww!")
assert data["componentJsMsg"] == "kapowww!"
# Check JS from Media.js got loaded
self.assertEqual(data["scriptJsMsg"], {"hello": "world"})
assert data["scriptJsMsg"] == {"hello": "world"}
# Check components' inlined CSS got loaded
self.assertEqual(data["innerFontSize"], "4px")
assert data["innerFontSize"] == "4px"
# Check CSS from Media.css got loaded
self.assertIn("rgb(0, 0, 255)", data["myStyleBg"]) # AKA 'background: blue'
assert "rgb(0, 0, 255)" in data["myStyleBg"] # AKA 'background: blue'
await page.close()
@ -71,7 +72,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_multiple_component_dependencies(self):
single_comp_url = TEST_SERVER_URL + "/multi"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -111,8 +112,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
# Check that the actual HTML content was loaded
self.assertRegex(
data["bodyHTML"],
assert re.compile(
# <div class="outer" data-djc-id-10uLMD>
# Variable:
# <strong class="inner" data-djc-id-DZEnUC>
@ -125,39 +125,37 @@ class E2eDependencyRenderingTests(BaseTestCase):
# </div>
# <div class="my-style">123</div>
# <div class="my-style2">xyz</div>
re.compile(
r'<div class="outer" data-djc-id-\w{6}="">\s*'
r"Variable:\s*"
r'<strong class="inner" data-djc-id-\w{6}="">\s*'
r"variable\s*"
r"<\/strong>\s*"
r"XYZ:\s*"
r'<strong class="other" data-djc-id-\w{6}="">\s*'
r"variable_inner\s*"
r"<\/strong>\s*"
r"<\/div>\s*"
r'<div class="my-style">123<\/div>\s*'
r'<div class="my-style2">xyz<\/div>\s*'
),
)
r'<div class="outer" data-djc-id-\w{6}="">\s*'
r"Variable:\s*"
r'<strong class="inner" data-djc-id-\w{6}="">\s*'
r"variable\s*"
r"<\/strong>\s*"
r"XYZ:\s*"
r'<strong class="other" data-djc-id-\w{6}="">\s*'
r"variable_inner\s*"
r"<\/strong>\s*"
r"<\/div>\s*"
r'<div class="my-style">123<\/div>\s*'
r'<div class="my-style2">xyz<\/div>\s*'
).search(data["bodyHTML"]) is not None
# Check components' inlined JS got loaded
self.assertEqual(data["component1JsMsg"], "kapowww!")
self.assertEqual(data["component2JsMsg"], "bongo!")
self.assertEqual(data["component3JsMsg"], "wowzee!")
assert data["component1JsMsg"] == "kapowww!"
assert data["component2JsMsg"] == "bongo!"
assert data["component3JsMsg"] == "wowzee!"
# Check JS from Media.js got loaded
self.assertEqual(data["scriptJs1Msg"], {"hello": "world"})
self.assertEqual(data["scriptJs2Msg"], {"hello2": "world2"})
assert data["scriptJs1Msg"] == {"hello": "world"}
assert data["scriptJs2Msg"] == {"hello2": "world2"}
# Check components' inlined CSS got loaded
self.assertEqual(data["innerFontSize"], "4px")
self.assertEqual(data["outerFontSize"], "40px")
self.assertEqual(data["otherDisplay"], "flex")
assert data["innerFontSize"] == "4px"
assert data["outerFontSize"] == "40px"
assert data["otherDisplay"] == "flex"
# Check CSS from Media.css got loaded
self.assertIn("rgb(0, 0, 255)", data["myStyleBg"]) # AKA 'background: blue'
self.assertEqual("rgb(255, 0, 0)", data["myStyle2Color"]) # AKA 'color: red'
assert "rgb(0, 0, 255)" in data["myStyleBg"] # AKA 'background: blue'
assert data["myStyle2Color"] == "rgb(255, 0, 0)" # AKA 'color: red'
await page.close()
@ -165,7 +163,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_renders_css_nojs_env(self):
single_comp_url = TEST_SERVER_URL + "/multi"
page: Page = await self.browser.new_page(java_script_enabled=False)
page: Page = await self.browser.new_page(java_script_enabled=False) # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -205,53 +203,51 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
# Check that the actual HTML content was loaded
self.assertRegex(
data["bodyHTML"],
# <div class="outer" data-djc-id-10uLMD>
# Variable:
# <strong class="inner" data-djc-id-DZEnUC>
# variable
# </strong>
# XYZ:
# <strong data-djc-id-IYirHK class="other">
# variable_inner
# </strong>
# </div>
# <div class="my-style">123</div>
# <div class="my-style2">xyz</div>
re.compile(
r'<div class="outer" data-djc-id-\w{6}="">\s*'
r"Variable:\s*"
r'<strong class="inner" data-djc-id-\w{6}="">\s*'
r"variable\s*"
r"<\/strong>\s*"
r"XYZ:\s*"
r'<strong class="other" data-djc-id-\w{6}="">\s*'
r"variable_inner\s*"
r"<\/strong>\s*"
r"<\/div>\s*"
r'<div class="my-style">123<\/div>\s*'
r'<div class="my-style2">xyz<\/div>\s*'
),
)
#
# <div class="outer" data-djc-id-10uLMD>
# Variable:
# <strong class="inner" data-djc-id-DZEnUC>
# variable
# </strong>
# XYZ:
# <strong data-djc-id-IYirHK class="other">
# variable_inner
# </strong>
# </div>
# <div class="my-style">123</div>
# <div class="my-style2">xyz</div>
assert re.compile(
r'<div class="outer" data-djc-id-\w{6}="">\s*'
r"Variable:\s*"
r'<strong class="inner" data-djc-id-\w{6}="">\s*'
r"variable\s*"
r"<\/strong>\s*"
r"XYZ:\s*"
r'<strong class="other" data-djc-id-\w{6}="">\s*'
r"variable_inner\s*"
r"<\/strong>\s*"
r"<\/div>\s*"
r'<div class="my-style">123<\/div>\s*'
r'<div class="my-style2">xyz<\/div>\s*'
).search(data["bodyHTML"]) is not None
# Check components' inlined JS did NOT get loaded
self.assertEqual(data["component1JsMsg"], None)
self.assertEqual(data["component2JsMsg"], None)
self.assertEqual(data["component3JsMsg"], None)
assert data["component1JsMsg"] is None
assert data["component2JsMsg"] is None
assert data["component3JsMsg"] is None
# Check JS from Media.js did NOT get loaded
self.assertEqual(data["scriptJs1Msg"], None)
self.assertEqual(data["scriptJs2Msg"], None)
assert data["scriptJs1Msg"] is None
assert data["scriptJs2Msg"] is None
# Check components' inlined CSS got loaded
self.assertEqual(data["innerFontSize"], "4px")
self.assertEqual(data["outerFontSize"], "40px")
self.assertEqual(data["otherDisplay"], "flex")
assert data["innerFontSize"] == "4px"
assert data["outerFontSize"] == "40px"
assert data["otherDisplay"] == "flex"
# Check CSS from Media.css got loaded
self.assertIn("rgb(0, 0, 255)", data["myStyleBg"]) # AKA 'background: blue'
self.assertEqual("rgb(255, 0, 0)", data["myStyle2Color"]) # AKA 'color: red'
assert "rgb(0, 0, 255)" in data["myStyleBg"] # AKA 'background: blue'
assert "rgb(255, 0, 0)" in data["myStyle2Color"] # AKA 'color: red'
await page.close()
@ -259,7 +255,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_js_executed_in_order__js(self):
single_comp_url = TEST_SERVER_URL + "/js-order/js"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -271,13 +267,13 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
# Check components' inlined JS got loaded
self.assertEqual(data["testSimpleComponent"], "kapowww!")
self.assertEqual(data["testSimpleComponentNested"], "bongo!")
self.assertEqual(data["testOtherComponent"], "wowzee!")
assert data["testSimpleComponent"] == "kapowww!"
assert data["testSimpleComponentNested"] == "bongo!"
assert data["testOtherComponent"] == "wowzee!"
# Check JS from Media.js got loaded
self.assertEqual(data["testMsg"], {"hello": "world"})
self.assertEqual(data["testMsg2"], {"hello2": "world2"})
assert data["testMsg"] == {"hello": "world"}
assert data["testMsg2"] == {"hello2": "world2"}
await page.close()
@ -285,7 +281,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_js_executed_in_order__media(self):
single_comp_url = TEST_SERVER_URL + "/js-order/media"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -298,13 +294,13 @@ class E2eDependencyRenderingTests(BaseTestCase):
# Check components' inlined JS got loaded
# NOTE: The Media JS are loaded BEFORE the components' JS, so they should be empty
self.assertEqual(data["testSimpleComponent"], None)
self.assertEqual(data["testSimpleComponentNested"], None)
self.assertEqual(data["testOtherComponent"], None)
assert data["testSimpleComponent"] is None
assert data["testSimpleComponentNested"] is None
assert data["testOtherComponent"] is None
# Check JS from Media.js
self.assertEqual(data["testMsg"], {"hello": "world"})
self.assertEqual(data["testMsg2"], {"hello2": "world2"})
assert data["testMsg"] == {"hello": "world"}
assert data["testMsg2"] == {"hello2": "world2"}
await page.close()
@ -315,7 +311,7 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_js_executed_in_order__invalid(self):
single_comp_url = TEST_SERVER_URL + "/js-order/invalid"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
test_js: types.js = """() => {
@ -326,20 +322,20 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
# Check components' inlined JS got loaded
self.assertEqual(data["testSimpleComponent"], None)
self.assertEqual(data["testSimpleComponentNested"], None)
self.assertEqual(data["testOtherComponent"], None)
assert data["testSimpleComponent"] is None
assert data["testSimpleComponentNested"] is None
assert data["testOtherComponent"] is None
# Check JS from Media.js got loaded
self.assertEqual(data["testMsg"], None)
self.assertEqual(data["testMsg2"], None)
assert data["testMsg"] is None
assert data["testMsg2"] is None
await page.close()
# Fragment where JS and CSS is defined on Component class
@with_playwright
async def test_fragment_comp(self):
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(f"{TEST_SERVER_URL}/fragment/base/js?frag=comp")
test_before_js: types.js = """() => {
@ -353,8 +349,8 @@ class E2eDependencyRenderingTests(BaseTestCase):
data_before = await page.evaluate(test_before_js)
self.assertEqual(data_before["targetHtml"], '<div id="target">OLD</div>')
self.assertEqual(data_before["fragHtml"], None)
assert data_before["targetHtml"] == '<div id="target">OLD</div>'
assert data_before["fragHtml"] is None
# Clicking button should load and insert the fragment
await page.locator("button").click()
@ -380,21 +376,18 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
self.assertEqual(data["targetHtml"], None)
self.assertRegex(
data["fragHtml"],
re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
),
)
self.assertIn("rgb(0, 0, 255)", data["fragBg"]) # AKA 'background: blue'
assert data["targetHtml"] is None
assert re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
).search(data["fragHtml"]) is not None
assert "rgb(0, 0, 255)" in data["fragBg"] # AKA 'background: blue'
await page.close()
# Fragment where JS and CSS is defined on Media class
@with_playwright
async def test_fragment_media(self):
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(f"{TEST_SERVER_URL}/fragment/base/js?frag=media")
test_before_js: types.js = """() => {
@ -408,8 +401,8 @@ class E2eDependencyRenderingTests(BaseTestCase):
data_before = await page.evaluate(test_before_js)
self.assertEqual(data_before["targetHtml"], '<div id="target">OLD</div>')
self.assertEqual(data_before["fragHtml"], None)
assert data_before["targetHtml"] == '<div id="target">OLD</div>'
assert data_before["fragHtml"] is None
# Clicking button should load and insert the fragment
await page.locator("button").click()
@ -433,21 +426,18 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
self.assertEqual(data["targetHtml"], None)
self.assertRegex(
data["fragHtml"],
re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
),
)
self.assertIn("rgb(0, 0, 255)", data["fragBg"]) # AKA 'background: blue'
assert data["targetHtml"] is None
assert re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
).search(data["fragHtml"]) is not None
assert "rgb(0, 0, 255)" in data["fragBg"] # AKA 'background: blue'
await page.close()
# Fragment loaded by AlpineJS
@with_playwright
async def test_fragment_alpine(self):
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(f"{TEST_SERVER_URL}/fragment/base/alpine?frag=comp")
test_before_js: types.js = """() => {
@ -461,8 +451,8 @@ class E2eDependencyRenderingTests(BaseTestCase):
data_before = await page.evaluate(test_before_js)
self.assertEqual(data_before["targetHtml"], '<div id="target" x-html="htmlVar">OLD</div>')
self.assertEqual(data_before["fragHtml"], None)
assert data_before["targetHtml"] == '<div id="target" x-html="htmlVar">OLD</div>'
assert data_before["fragHtml"] is None
# Clicking button should load and insert the fragment
await page.locator("button").click()
@ -490,20 +480,17 @@ class E2eDependencyRenderingTests(BaseTestCase):
# NOTE: Unlike the vanilla JS tests, for the Alpine test we don't remove the targetHtml,
# but only change its contents.
self.assertRegex(
data["targetHtml"],
re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
),
)
self.assertIn("rgb(0, 0, 255)", data["fragBg"]) # AKA 'background: blue'
assert re.compile(
r'<div class="frag" data-djc-id-\w{6}="">\s*' r"123\s*" r'<span id="frag-text">xxx</span>\s*' r"</div>"
).search(data["targetHtml"]) is not None
assert "rgb(0, 0, 255)" in data["fragBg"] # AKA 'background: blue'
await page.close()
# Fragment loaded by HTMX
@with_playwright
async def test_fragment_htmx(self):
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(f"{TEST_SERVER_URL}/fragment/base/htmx?frag=comp")
test_before_js: types.js = """() => {
@ -517,8 +504,8 @@ class E2eDependencyRenderingTests(BaseTestCase):
data_before = await page.evaluate(test_before_js)
self.assertEqual(data_before["targetHtml"], '<div id="target">OLD</div>')
self.assertEqual(data_before["fragHtml"], None)
assert data_before["targetHtml"] == '<div id="target">OLD</div>'
assert data_before["fragHtml"] is None
# Clicking button should load and insert the fragment
await page.locator("button").click()
@ -544,14 +531,11 @@ class E2eDependencyRenderingTests(BaseTestCase):
data = await page.evaluate(test_js)
self.assertEqual(data["targetHtml"], None)
assert data["targetHtml"] is None
# NOTE: We test only the inner HTML, because the element itself may or may not have
# extra CSS classes added by HTMX, which results in flaky tests.
self.assertRegex(
data["fragInnerHtml"],
re.compile(r'123\s*<span id="frag-text">xxx</span>'),
)
self.assertIn("rgb(0, 0, 255)", data["fragBg"]) # AKA 'background: blue'
assert re.compile(r'123\s*<span id="frag-text">xxx</span>').search(data["fragInnerHtml"]) is not None
assert "rgb(0, 0, 255)" in data["fragBg"] # AKA 'background: blue'
await page.close()
@ -559,11 +543,11 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_alpine__head(self):
single_comp_url = TEST_SERVER_URL + "/alpine/head"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
component_text = await page.locator('[x-data="alpine_test"]').text_content()
self.assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
await page.close()
@ -571,11 +555,11 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_alpine__body(self):
single_comp_url = TEST_SERVER_URL + "/alpine/body"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
component_text = await page.locator('[x-data="alpine_test"]').text_content()
self.assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
await page.close()
@ -583,11 +567,11 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_alpine__body2(self):
single_comp_url = TEST_SERVER_URL + "/alpine/body2"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
component_text = await page.locator('[x-data="alpine_test"]').text_content()
self.assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
assertHTMLEqual(component_text.strip(), "ALPINE_TEST: 123")
await page.close()
@ -595,10 +579,10 @@ class E2eDependencyRenderingTests(BaseTestCase):
async def test_alpine__invalid(self):
single_comp_url = TEST_SERVER_URL + "/alpine/invalid"
page: Page = await self.browser.new_page()
page: Page = await self.browser.new_page() # type: ignore[attr-defined]
await page.goto(single_comp_url)
component_text = await page.locator('[x-data="alpine_test"]').text_content()
self.assertHTMLEqual(component_text.strip(), "ALPINE_TEST:")
assertHTMLEqual(component_text.strip(), "ALPINE_TEST:")
await page.close()