Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Tests cleanup and better test isolation #452

Merged
merged 8 commits into from
Apr 25, 2024
17 changes: 15 additions & 2 deletions src/django_components/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import importlib.util
import os
from pathlib import Path
from typing import Callable, List, Optional

import django
from django.conf import settings
Expand All @@ -14,9 +15,15 @@
default_app_config = "django_components.apps.ComponentsConfig"


def autodiscover() -> None:
def autodiscover(map_import_paths: Optional[Callable[[str], str]] = None) -> List[str]:
"""
Search for component files and import them. Returns a list of module
paths of imported files.
"""
from django_components.app_settings import app_settings

imported_modules: List[str] = []

if app_settings.AUTODISCOVER:
# Autodetect a components.py file in each app directory
autodiscover_modules("components")
Expand All @@ -26,15 +33,21 @@ def autodiscover() -> None:
logger.debug(f"Autodiscover found {len(component_filepaths)} files in component directories.")

for path in component_filepaths:
module_name = _filepath_to_python_module(path)
if map_import_paths:
module_name = map_import_paths(module_name)

# This imports the file and runs it's code. So if the file defines any
# django components, they will be registered.
module_name = _filepath_to_python_module(path)
logger.debug(f'Importing module "{module_name}" (derived from path "{path}")')
importlib.import_module(module_name)
imported_modules.append(module_name)

for path_lib in app_settings.LIBRARIES:
importlib.import_module(path_lib)

return imported_modules


def _filepath_to_python_module(file_path: Path) -> str:
"""
Expand Down