EmilStenstrom / django-components

Create simple reusable template components in Django.
MIT License
953 stars 59 forks source link

Tests: Component registry is not isolated across tests #436

Closed JuroOravec closed 3 weeks ago

JuroOravec commented 1 month ago

I had difficulty creating tests for https://github.com/EmilStenstrom/django-components/pull/435. Things worked when I ran tests just for the import_file function, but I was seeing errors in different files and tests when I ran the whole suite of tests. See this comment and test for context. It looks to me like the state of either/both component_registry and sys.modules (imported modules) persists across tests.

Ideally, both sys.modules and component_registry would be isolated between tests.

Don't have deep knowledge about tox / pytest, so raising a ticket to discuss this, hoping someone more knowledgeable answers 😄

E.g., for component_registry, should we use a mock for the registry? Or run registry.clear() before each test? Or is there a simpler approach?

As for sys.modules, is it possible to restart/clear the modules that have been imported as part of the test run?

Also, component registrations like these in test_context should probably also be scoped not globally, but per test.

Lastly, related to tests, @dylanjcastillo, I like how the tests you wrote in https://github.com/EmilStenstrom/django-components/blob/edf3885632ff32406510693d63cfbddf1c71faa6/tests/test_component_as_view.py. But I can't wrap my head around how it works. How are the routes set there? Is it by setting the ROOT_URLCONF?

EmilStenstrom commented 1 month ago

@JuroOravec For #435 I think it's enough to unit test the code that translates a path to a dotted import path.

More generally, tests should of course not affect each other. I think simply running registry.clear() in teardown for each test class is probably a good idea. Maybe a new testcase base class that we use everywhere?

dylanjcastillo commented 1 month ago

@JuroOravec, yes, it uses ROOT_URLCONF=__name__, which essentially means that it uses the urlpatterns defined in the same file.