Imported from openwisp/django-swappable-models (
AGENTS.md). Install upstream withnpx skills add openwisp/django-swappable-models. Copyright stays with the author.
AGENTS.md
Project Overview
django-swappable-models provides the swapper utility used by OpenWISP Django apps to support swappable models.
Core code lives in swapper/:
__init__.pycontains the public model loading and dependency helpers.- Tests live in
tests/, including default and alternate apps for swapped-model behavior.
Source of Truth
- Use
README.mdfor setup, package usage, and baseline test commands. - Use
.github/workflows/ci.ymlandtox.inifor CI-tested dependencies, QA/test commands, env vars, and supported Python/Django versions. - Use GitHub issue/PR templates when asked to open issues or PRs.
If instructions conflict, repository config and CI workflows win first, docs next, and this file is supplemental.
Contributing Guidelines
- Before editing, inspect the relevant implementation, tests, documentation, and configuration. Follow existing repository patterns and do not invent behavior or requirements.
- Keep each contribution focused and change only the lines necessary for its goal. Do not include unrelated refactors, formatting churn, or generated and dependency-file changes unless explicitly required.
- Add or update focused tests for every behavior change. Use test-driven development when the scope is very clear, such as bug fixes or narrowly scoped changes. For new features, tests may be added after implementation, but confirm they fail when key feature code is removed. When a test failure does not clearly state the expected outcome that was not met, add an explicit assertion message.
- Run
openwisp-qa-formatafter each change when available. - Run the relevant targeted tests, builds, and documented QA checks, including
./run-qa-checkswhen provided. Do not claim a change is complete when verification fails; report the failure or blocker. - When requirements, intended behavior, or an unexpected failure are unclear, stop and seek clarification instead of making speculative changes.
- When starting work on a new issue, create a new branch from
master. Useissues/<issue-number>-<short-title>for issue work; otherwise, use a short, descriptive branch name. - Commit messages must be descriptive and use past tense. Past tense is a writing guideline that agents and contributors must follow; it is not checked automatically. For issue work, use an allowed prefix and a capitalized, past-tense subject ending with
#<issue-number>, for example[fix] Fixed perennial "modified" state #213. Repeat the issue reference in the body withFixes,Closes,Resolves, orRelated toas appropriate. After creating a commit, useopenwisp-commit --checkto validate the currentHEAD; it cannot validate a proposed message. Useopenwisp-commit --check --rev-range <range>for an existing commit range, andcz -n cz_openwisp infoto view allowed prefixes and message structure. - Add an explanatory commit body only for substantial changes, new features, or non-obvious bug fixes. The releaser automatically publishes the subject of
[feature],[change],[change!],[deps], and[fix]commits, including scoped variants, in the changelog. Write those subjects in clear, user-friendly language suitable for release notes. - Send new commits in response to review feedback instead of amending existing commits.
Development Rules
- Follow the DRY principle: do not duplicate information or code across files.
- Respect module boundaries and encapsulation. The module that owns a model, stored state, lifecycle, or domain invariant must expose the cohesive public operation that reads or changes it. Integrations must use that operation, not write its fields, coordinate multi-step changes to its internal state, or depend on its storage representation. Prefer behavior-oriented public APIs over setters for internal flags. When an integration needs a missing capability, add it to the owning module with invariant tests, then call it from the integration.
- Preserve public APIs, import-time behavior, Django app registry behavior, migration dependency helpers, and backward compatibility unless explicitly required.
- Place imports at the top of the file. Only defer imports when necessary (e.g., Django model imports inside functions or methods where the app registry is not yet ready).
- Avoid unnecessary blank lines inside function and method bodies.
- Prefer short, precise names that rely on their nearest meaningful scope. Do not repeat a feature, domain object, or namespace already named by the containing module, class, or function. For example, prefer
EstimatedLocation.refresh()overEstimatedLocation.refresh_estimated_location(). Repeat that context only when the name is used outside that scope or is needed to distinguish genuinely different concepts. When a concise name cannot express a necessary distinction, use a concise docstring to describe it rather than encoding it in an excessively long name. - Before adding a comment or docstring, ask whether it conveys information a reader cannot reasonably infer from clear code, names, and surrounding scope. Add a concise comment when it explains a non-obvious reason, constraint, compatibility or security requirement, side effect, or unavoidable complexity. In opaque syntax or domain-specific code, especially shell scripts, a comment may also explain what the code does. Do not add comments that merely restate adjacent code one-to-one.
- Update docs when behavior, settings, public APIs, setup steps, or supported versions change, including when a documented feature's behavior changes or a new user-facing feature is added.
Testing and QA
- When separate tests cover different cases of the same feature, share almost identical setup, and primarily vary in input or expected outcome, group them in one test method with
subTest. Keep each subtest's setup explicit and independent, and retain separate test methods when cases exercise genuinely distinct behavior. Leave one blank line before each withself.subTest(...)statement only when a test method contains multiple such statements. Do not add a blank line for a singlesubTeststatement inside a loop. - For focused tests, call
./tests/manage.py test <pythonpath>directly. Use./runtestsonly for the full suite because it runs multiple coverage and integration configurations and is not a focused-test runner. - Prefer in-process tests so coverage tools can measure changed code.
- Keep helpers and classes used by only one test method inside that method. Promote them to class or module scope only when genuinely reused.
- Keep tests quiet on success. When code under test writes to stdout or stderr, use
capture_stdout,capture_stderr, orcapture_any_outputfromopenwisp_utils.testsand assert the expected output. Do not leave unasserted output, logs, or warnings in test runs.
Django Rules
- Build internal URLs with named URL patterns and
reverse()orreverse_lazy(), including in tests. Use the appropriate namespace and URL arguments. - In the main behavior test for non-trivial, frequently called views, include
assertNumQueries()with representative data to enforce an intentional query budget and catch N+1 queries. UseAssertNumQueriesSubTestMixinfromopenwisp_utils.testswhere available: it records the query-count check as a subtest, so subsequent assertions in the method still run. Change the expected count only when the extra queries are necessary and understood. - When processing all records from a queryset in commands, tasks, imports, exports, migrations, or similar operations, use
QuerySet.iterator()or another bounded method. Do not load all matching records into memory at once. - When accessing related objects while processing a queryset, use
select_related()orprefetch_related()as needed to avoid N+1 queries.prefetch_related()used withiterator()requires an explicitchunk_size; otherwise useiterator()with its default behavior. - Paginate API list responses that can return many records. Do not return every matching record in one response unless the maximum result size is defined and safely bounded.
- Prefer bulk writes when writing many objects. Use
bulk_create()orbulk_update()unless model validation,save()behavior, signals, or another requirement prevents it. Explain the reason for not using a bulk write in a nearby code comment. - Test custom pagination, custom batching, and code that consumes paginated APIs beyond the first page or batch. Do not repeat coverage already provided by an unchanged shared pagination class or utility.
- Before defining a new class, view, URL, REST endpoint, or test layout, inspect analogous implementations in related OpenWISP modules. Match their established names, URL names, API shape, and test organization unless the behavior requires a difference.
- Cover both default and swapped-model apps when changing model resolution, dependency generation, or settings handling.
- Be careful with import timing, circular imports, app labels, migration dependencies, and Django version compatibility.
- Treat email addresses as case-insensitive when identifying, deduplicating, importing, migrating, or searching users by email. Use
email__iexactfor direct andQ()ORM lookups. Keep username matching case-sensitive unless explicitly required. Normalize email records this module owns to lowercase, and cover casing-only inputs, including legacy mixed-case records when relevant.
Security Rules
- Watch for unsafe dynamic imports, incorrect model resolution, and secrets in tests or docs.
Troubleshooting
- If documentation and CI commands differ, use CI for verification and report the exact documentation path, CI workflow path, and differing commands. Do not change the documentation until the user explicitly chooses one of these actions: update the named documentation file in the current change because the divergence was caused by that change, or leave it unchanged for a separate follow-up. Never decide that scope distinction independently.