├── .bumpversion.cfg
├── .editorconfig
├── .github
├── ISSUE_TEMPLATE.md
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ ├── custom.md
│ └── feature_request.md
├── dependabot.yml
└── workflows
│ ├── codeql-analysis.yml
│ ├── dev.yml
│ └── release.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .pre-commit-hooks.yaml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── django_urlconfchecks
├── __init__.py
├── apps.py
├── check.py
├── cli.py
└── cli_utils.py
├── docs
├── changelog.md
├── contributing.md
├── index.md
├── installation.md
└── usage.md
├── makefile
├── mkdocs.yml
├── poetry.lock
├── pyproject.toml
├── pytest.ini
├── setup.cfg
└── tests
├── __init__.py
├── dummy_project
├── __init__.py
├── settings.py
├── urls
│ ├── __init__.py
│ ├── admin_urls.py
│ ├── cbv_urls.py
│ ├── child_urls.py
│ ├── converter_urls.py
│ ├── correct_urls.py
│ ├── includes.py
│ ├── incorrect_urls.py
│ ├── optional_args.py
│ ├── parameterized_generics.py
│ ├── parent_urls.py
│ └── path_kwargs_urls.py
└── views.py
├── test_as_django_app.py
├── test_cli.py
├── test_url_checker.py
└── utils.py
/.bumpversion.cfg:
--------------------------------------------------------------------------------
1 | [bumpversion]
2 | current_version = 0.11.0
3 | commit = True
4 | tag = True
5 |
6 | [bumpversion:file:pyproject.toml]
7 | search = version = "{current_version}"
8 | replace = version = "{new_version}"
9 |
10 | [bumpversion:file:django_urlconfchecks/__init__.py]
11 | search = __version__ = '{current_version}'
12 | replace = __version__ = '{new_version}'
13 |
14 | [bumpversion:file:README.md]
15 | search = rev: v{current_version}
16 | replace = rev: v{new_version}
17 |
18 | [bumpversion:file:docs/usage.md]
19 | search = rev: v{current_version}
20 | replace = rev: v{new_version}
21 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | indent_style = space
7 | indent_size = 4
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 | charset = utf-8
11 | end_of_line = lf
12 |
13 | [*.bat]
14 | indent_style = tab
15 | end_of_line = crlf
16 |
17 | [LICENSE]
18 | insert_final_newline = false
19 |
20 | [Makefile]
21 | indent_style = tab
22 |
23 | [*.{yml, yaml}]
24 | indent_size = 2
25 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | * django-UrlConfChecks version:
2 | * Python version:
3 | * Operating System:
4 |
5 | ### Description
6 |
7 | Describe what you were trying to get done.
8 | Tell us what happened, what went wrong, and what you expected to happen.
9 |
10 | ### What I Did
11 |
12 | ```
13 | Paste the command(s) you ran and the output.
14 | If there was a crash, please include the traceback here.
15 | ```
16 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/custom.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Custom issue template
3 | about: Describe this issue template's purpose here.
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "pip" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "daily"
12 | allow:
13 | - dependency-type: "direct"
14 |
15 |
16 | - package-ecosystem: "github-actions"
17 | directory: "/"
18 | schedule:
19 | # Check for updates to GitHub Actions every weekday
20 | interval: "daily"
21 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ main ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ main ]
20 | schedule:
21 | - cron: '45 5 * * 2'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'python' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support
38 |
39 | steps:
40 | - name: Checkout repository
41 | uses: actions/checkout@v4
42 |
43 | # Initializes the CodeQL tools for scanning.
44 | - name: Initialize CodeQL
45 | uses: github/codeql-action/init@v3
46 | with:
47 | languages: ${{ matrix.language }}
48 | # If you wish to specify custom queries, you can do so here or in a config file.
49 | # By default, queries listed here will override any specified in a config file.
50 | # Prefix the list here with "+" to use these queries and those in the config file.
51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
52 |
53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
54 | # If this step fails, then you should remove it and run the build manually (see below)
55 | - name: Autobuild
56 | uses: github/codeql-action/autobuild@v3
57 |
58 | # ℹ️ Command-line programs to run using the OS shell.
59 | # 📚 https://git.io/JvXDl
60 |
61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
62 | # and modify them (or add more) to build your code if your project
63 | # uses a compiled language
64 |
65 | #- run: |
66 | # make bootstrap
67 | # make release
68 |
69 | - name: Perform CodeQL Analysis
70 | uses: github/codeql-action/analyze@v3
71 |
--------------------------------------------------------------------------------
/.github/workflows/dev.yml:
--------------------------------------------------------------------------------
1 | # This is a basic workflow to help you get started with Actions
2 |
3 | name: dev workflow
4 |
5 | # Controls when the action will run.
6 | on:
7 | # Triggers the workflow on push or pull request events but only for the master branch
8 | push:
9 | branches: [ master, main ]
10 | pull_request:
11 | branches: [ master, main ]
12 |
13 | # Allows you to run this workflow manually from the Actions tab
14 | workflow_dispatch:
15 |
16 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel
17 | jobs:
18 | # This workflow contains a single job called "test"
19 | test:
20 | # The type of runner that the job will run on
21 | strategy:
22 | matrix:
23 | python-versions: [ 3.9, '3.10', '3.11', '3.12', '3.13']
24 | runs-on: ubuntu-latest
25 |
26 | # Steps represent a sequence of tasks that will be executed as part of the job
27 | steps:
28 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
29 | - uses: actions/checkout@v4
30 | - uses: actions/setup-python@v5
31 | with:
32 | python-version: ${{ matrix.python-versions }}
33 |
34 | - name: Install dependencies
35 | run: |
36 | python -m pip install --upgrade pip
37 | pip install poetry tox tox-gh-actions
38 |
39 | - name: Set up cache
40 | uses: actions/cache@v4
41 | id: cache
42 | with:
43 | path: .venv
44 | key: venv-${{ runner.os }}-${{ steps.full-python-version.outputs.version }}-${{ hashFiles('**/poetry.lock') }}
45 |
46 | - name: Ensure cache is healthy
47 | if: steps.cache.outputs.cache-hit == 'true'
48 | shell: bash
49 | run: poetry run pip --version >/dev/null 2>&1 || rm -rf .venv
50 |
51 | - name: test with tox
52 | run:
53 | tox
54 |
55 | - name: list files
56 | run: ls -l .
57 |
58 | - uses: codecov/codecov-action@v4
59 | with:
60 | fail_ci_if_error: false
61 | files: coverage.xml
62 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | # Publish package on main branch if it's tagged with 'v*'
2 |
3 | name: release & publish workflow
4 |
5 | # Controls when the action will run.
6 | on:
7 | # Triggers the workflow on push events but only for the master branch
8 | push:
9 | tags:
10 | - 'v*'
11 |
12 | # Allows you to run this workflow manually from the Actions tab
13 | workflow_dispatch:
14 |
15 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel
16 | jobs:
17 | # This workflow contains a single job called "release"
18 | release:
19 | name: Create Release
20 | runs-on: ubuntu-20.04
21 |
22 | strategy:
23 | matrix:
24 | python-versions: [3.9]
25 |
26 | # Steps represent a sequence of tasks that will be executed as part of the job
27 | steps:
28 | - name: Get version from tag
29 | id: tag_name
30 | run: |
31 | echo ::set-output name=current_version::${GITHUB_REF#refs/tags/v}
32 | shell: bash
33 |
34 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
35 | - uses: actions/checkout@v4
36 |
37 | - name: Get Changelog Entry
38 | id: changelog_reader
39 | uses: mindsers/changelog-reader-action@v2
40 | with:
41 | validation_depth: 10
42 | version: ${{ steps.tag_name.outputs.current_version }}
43 | path: ./CHANGELOG.md
44 |
45 | - uses: actions/setup-python@v5
46 | with:
47 | python-version: ${{ matrix.python-versions }}
48 |
49 | - name: Install dependencies
50 | run: |
51 | python -m pip install --upgrade pip
52 | pip install poetry
53 |
54 | - name: build documentation
55 | run: |
56 | poetry install -E doc
57 | poetry run mkdocs build
58 |
59 | - name: publish documentation
60 | uses: peaceiris/actions-gh-pages@v4
61 | with:
62 | personal_token: ${{ secrets.PERSONAL_TOKEN }}
63 | publish_dir: ./site
64 |
65 | - name: Build wheels and source tarball
66 | run: >-
67 | poetry build
68 |
69 | - name: show temporary files
70 | run: >-
71 | ls -l
72 |
73 | - name: create github release
74 | id: create_release
75 | uses: softprops/action-gh-release@v2
76 | env:
77 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
78 | with:
79 | body: ${{ steps.changelog_reader.outputs.changes }}
80 | files: dist/*.whl
81 | draft: false
82 | prerelease: false
83 |
84 | - name: publish to PyPI
85 | uses: pypa/gh-action-pypi-publish@release/v1
86 | with:
87 | user: __token__
88 | password: ${{ secrets.PYPI_API_TOKEN }}
89 | skip_existing: true
90 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # macOS
2 | .DS_Store
3 | .AppleDouble
4 | .LSOverride
5 |
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | env/
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | .hypothesis/
53 | .pytest_cache/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 |
63 | # Flask stuff:
64 | instance/
65 | .webassets-cache
66 |
67 | # Scrapy stuff:
68 | .scrapy
69 |
70 | # Sphinx documentation
71 | docs/_build/
72 |
73 | # PyBuilder
74 | target/
75 |
76 | # Jupyter Notebook
77 | .ipynb_checkpoints
78 |
79 | # pyenv
80 | .python-version
81 |
82 | # celery beat schedule file
83 | celerybeat-schedule
84 |
85 | # SageMath parsed files
86 | *.sage.py
87 |
88 | # dotenv
89 | .env
90 |
91 | # virtualenv
92 | .venv
93 | venv/
94 | ENV/
95 |
96 | # Spyder project settings
97 | .spyderproject
98 | .spyproject
99 |
100 | # Rope project settings
101 | .ropeproject
102 |
103 | # mkdocs documentation
104 | /site
105 |
106 | # mypy
107 | .mypy_cache/
108 |
109 | # IDE settings
110 | .vscode/
111 | .idea/
112 |
113 | # mkdocs build dir
114 | site/
115 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/Lucas-C/pre-commit-hooks
3 | rev: v1.5.5
4 | hooks:
5 | - id: forbid-crlf
6 | - id: remove-crlf
7 | - repo: https://github.com/pre-commit/pre-commit-hooks
8 | rev: v5.0.0
9 | hooks:
10 | - id: trailing-whitespace
11 | - id: end-of-file-fixer
12 | - id: check-merge-conflict
13 | - id: check-yaml
14 | args: [ --unsafe ]
15 | - repo: https://github.com/PyCQA/isort
16 | rev: 6.0.1
17 | hooks:
18 | - id: isort
19 | args: [ "--filter-files" ]
20 | - repo: https://github.com/psf/black
21 | rev: 25.1.0
22 | hooks:
23 | - id: black
24 | language_version: python3.10
25 | - repo: https://github.com/pycqa/flake8
26 | rev: 7.2.0
27 | hooks:
28 | - id: flake8
29 | additional_dependencies: [ flake8-typing-imports==1.12.0 ]
30 | - repo: https://github.com/pre-commit/mirrors-mypy
31 | rev: v1.15.0
32 | hooks:
33 | - id: mypy
34 | exclude: tests/
35 |
--------------------------------------------------------------------------------
/.pre-commit-hooks.yaml:
--------------------------------------------------------------------------------
1 | - id: django-urlconfchecks
2 | name: Django UrlConf Checks
3 | description: a pre-commit for type checking the urls and associated views
4 | entry: urlconfchecks
5 | pass_filenames: false
6 | language: python
7 | types: [ python ]
8 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [0.1.0] - 2022-01-28
4 |
5 | ### Added
6 |
7 | - First release on PyPI.
8 |
9 | ## [0.2.0] - 2022-01-29
10 |
11 | ### Added
12 |
13 | - Added the actual functionality.
14 | - updated dependencies.
15 |
16 | ## [0.3.0] - 2022-02-04
17 |
18 | ### Changed
19 |
20 | - fixed a bug that caused the checks to not work. Package is functional now.
21 |
22 | ## [0.3.1] - 2022-02-07
23 |
24 | ### Fixed
25 |
26 | - fixed a dependency issue that caused the `mkdocs-material-extensions` to install as a runtime dependency.
27 |
28 | ## [0.4.0] - 2022-02-07
29 |
30 | ### Changed
31 |
32 | - Now, `django_urlconfchecks` is a Django app. This means that it can be installed as a Django app. For more
33 | information, see [the documentation](https://alisayyah.github.io/django-urlconfchecks/usage/).
34 |
35 | ## [0.5.0] - 2022-02-21
36 |
37 | ### Added
38 |
39 | - Added two more ways to use the package: a `CLI tool` and a `pre-commit hook`. For more information, see
40 | the [usage documentation](https://alisayyah.github.io/django-urlconfchecks/usage/).
41 |
42 | ## [0.6.0] - 2022-04-01
43 |
44 | ### Fixed
45 |
46 | - Fixed a bug that caused `urlconfchecks` to show warnings for Django's `admin` app. Now, `admin` app will be ignored.
47 | Courtesy @nightboard.
48 |
49 | ## [0.7.0] - 2022-08-11
50 |
51 | ### Added
52 |
53 | - Added fine-grained method for silencing errors. Courtesy @spookylukey
54 |
55 | ## [0.7.1] - 2022-08-11
56 |
57 | ### Added
58 |
59 | - Support subclasses of builtin converters.
60 | - More tests.
61 | - Cleanup output text to be more clear and informative.
62 |
63 | ## [0.7.2] - 2022-08-12
64 |
65 | ### Added
66 |
67 | - Handle default arguments passed via path(kwargs). Courtesy @spookylukey
68 |
69 |
70 | ## [0.7.3] - 2022-08-25
71 |
72 | ### Fixed
73 |
74 | - Fixed an issue where default CBV silencing only worked for django 4
75 |
76 |
77 | ## [0.8.0] - 2022-09-16
78 |
79 | ### Fixed
80 |
81 | - Made error reporting of view reprs consistent with silencer.
82 | - Correctly handle views with Optional arguments.
83 |
84 |
85 | ## [0.9.0] - 2023-02-10
86 |
87 | ### Fixed
88 |
89 | - Fixed crasher when urlconf has optional types. Courtesy @spookylukey
90 | - added python 3.11 support
91 |
92 |
93 | ## [0.10.0] - 2023-08-15
94 |
95 | ### Added
96 |
97 | - Handle cases involving `path` and `include`. Courtesy @spookylukey
98 |
99 |
100 | ## [0.11.0] - 2024-02-27
101 |
102 | ### Added
103 |
104 | - Python 3.12 support
105 | - Django 5 support
106 |
107 | ### Removed
108 |
109 | - Python 3.7 support
110 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | ali.sayyah2@gmail.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are welcome, and they are greatly appreciated! Every little bit
4 | helps, and credit will always be given.
5 |
6 | You can contribute in many ways:
7 |
8 | ## Types of Contributions
9 |
10 | ### Report Bugs
11 |
12 | Report bugs at https://github.com/AliSayyah/django-urlconfchecks/issues.
13 |
14 | If you are reporting a bug, please include:
15 |
16 | * Your operating system name and version.
17 | * Any details about your local setup that might be helpful in troubleshooting.
18 | * Detailed steps to reproduce the bug.
19 |
20 | ### Fix Bugs
21 |
22 | Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
23 | wanted" is open to whoever wants to implement it.
24 |
25 | ### Implement Features
26 |
27 | Look through the GitHub issues for features. Anything tagged with "enhancement"
28 | and "help wanted" is open to whoever wants to implement it.
29 |
30 | ### Write Documentation
31 |
32 | django-UrlConfChecks could always use more documentation, whether as part of the
33 | official django-UrlConfChecks docs, in docstrings, or even on the web in blog posts,
34 | articles, and such.
35 |
36 | ### Submit Feedback
37 |
38 | The best way to send feedback is to file an issue at https://github.com/AliSayyah/django-urlconfchecks/issues.
39 |
40 | If you are proposing a feature:
41 |
42 | * Explain in detail how it would work.
43 | * Keep the scope as narrow as possible, to make it easier to implement.
44 | * Remember that this is a volunteer-driven project, and that contributions
45 | are welcome :)
46 |
47 | ## Get Started!
48 |
49 | Ready to contribute? Here's how to set up `django-urlconfchecks` for local development.
50 |
51 | 1. Fork the `django-urlconfchecks` repo on GitHub.
52 | 2. Clone your fork locally
53 |
54 | ```
55 | $ git clone git@github.com:your_name_here/django-urlconfchecks.git
56 | ```
57 |
58 | 3. Ensure [poetry](https://python-poetry.org/docs/) is installed.
59 | 4. Install dependencies and start your virtualenv:
60 |
61 | ```
62 | $ poetry install -E test -E doc -E dev
63 | ```
64 |
65 | 5. Create a branch for local development:
66 |
67 | ```
68 | $ git checkout -b name-of-your-bugfix-or-feature
69 | ```
70 |
71 | Now you can make your changes locally.
72 |
73 | 6. When you're done making changes, check that your changes pass the
74 | tests, including testing other Python versions, with tox:
75 |
76 | ```
77 | $ poetry run tox
78 | ```
79 |
80 | 7. Commit your changes and push your branch to GitHub:
81 |
82 | ```
83 | $ git add .
84 | $ git commit -m "Your detailed description of your changes."
85 | $ git push origin name-of-your-bugfix-or-feature
86 | ```
87 |
88 | 8. Submit a pull request through the GitHub website.
89 |
90 | ## Pull Request Guidelines
91 |
92 | Before you submit a pull request, check that it meets these guidelines:
93 |
94 | 1. The pull request should include tests.
95 | 2. If the pull request adds functionality, the docs should be updated. Put
96 | your new functionality into a function with a docstring, and add the
97 | feature to the list in README.md.
98 | 3. The pull request should work for Python 3.8, 3.9, 3.10, 3.11 and 3.12. Check
99 | https://github.com/AliSayyah/django-urlconfchecks/actions
100 | and make sure that the tests pass for all supported Python versions.
101 |
102 | ## Tips
103 |
104 | ```
105 | $ poetry run pytest tests
106 | ```
107 |
108 | To run a subset of tests.
109 |
110 |
111 | ## Deploying
112 |
113 | A reminder for the maintainers on how to deploy.
114 | Make sure all your changes are committed (including an entry in CHANGELOG.md).
115 | Then run:
116 |
117 | ```
118 | $ poetry run bump2version patch # possible: major / minor / patch
119 | $ git push
120 | $ git push --tags
121 | ```
122 |
123 | GitHub Actions will then deploy to PyPI if tests pass.
124 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Django UrlConf Checks
2 |
3 | [](https://pypi.org/project/django-urlconfchecks/)
4 | [](https://pypi.org/project/django-urlconfchecks/)
5 | [](https://github.com/AliSayyah/django-urlconfchecks/actions/workflows/dev.yml)
6 | [](https://codecov.io/github/AliSayyah/django-urlconfchecks)
7 | [](https://www.gnu.org/licenses/gpl-3.0.en.html)
8 |
9 | django-urlconfchecks is a static type checker that checks your URLconf parameter types with argument types specified in associated views.
10 | It leverages the Django's static check system.
11 |
12 | * [Documentation](https://AliSayyah.github.io/django-urlconfchecks)
13 | * [GitHub](https://github.com/AliSayyah/django-urlconfchecks)
14 | * [PyPI](https://pypi.org/project/django-urlconfchecks/)
15 |
16 | ## Installation
17 |
18 | pip install django-urlconfchecks
19 |
20 | Python 3.8 or later is required. However, before Python 3.10 some checks
21 | relating to `Optional` types in view signatures are skipped due to stdlib
22 | limitations.
23 |
24 | ## Usage
25 |
26 | You can use this package in different ways:
27 |
28 | ### As a Django app
29 |
30 | Add `django_urlconfchecks` to your `INSTALLED_APPS` list in your `settings.py` file.
31 |
32 | ```python
33 | INSTALLED_APPS = [
34 | ...
35 | 'django_urlconfchecks',
36 | ]
37 | ```
38 |
39 | ### As a command line tool
40 |
41 | Run this command from the root of your project, were `manage.py` is located:
42 |
43 | ```bash
44 | $ urlconfchecks --help
45 |
46 | Usage: urlconfchecks [OPTIONS]
47 |
48 | Check all URLConfs for errors.
49 |
50 | Options:
51 | --version
52 | -u, --urlconf PATH Specify the URLconf to check.
53 | --install-completion Install completion for the current shell.
54 | --show-completion Show completion for the current shell, to copy it or
55 | customize the installation.
56 | --help Show this message and exit.
57 | ```
58 |
59 | ### As a pre-commit hook
60 |
61 | Add the following to your `.pre-commit-config.yaml` file:
62 |
63 | ```yaml
64 | - repo: https://github.com/AliSayyah/django-urlconfchecks
65 | rev: v0.11.0
66 | hooks:
67 | - id: django-urlconfchecks
68 | ```
69 |
70 | For more information, see the [usage documentation](https://alisayyah.github.io/django-urlconfchecks/usage/).
71 |
72 | ## Features
73 |
74 | Using this package, URL pattern types will automatically be matched with associated views, and in case of mismatch, an
75 | error will be raised.
76 |
77 | Example:
78 |
79 | ```python
80 | # urls.py
81 | from django.urls import path
82 |
83 | from . import views
84 |
85 | urlpatterns = [
86 | path('articles//', views.year_archive),
87 | path('articles///', views.month_archive),
88 | path('articles////', views.article_detail),
89 | ]
90 | ```
91 |
92 | ```python
93 | # views.py
94 |
95 | def year_archive(request, year: int):
96 | pass
97 |
98 |
99 | def month_archive(request, year: int, month: int):
100 | pass
101 |
102 |
103 | def article_detail(request, year: int, month: int, slug: str):
104 | pass
105 | ```
106 |
107 | output will be:
108 |
109 | ```
110 | (urlchecker.E002) For parameter `year`, annotated type int does not match expected `str` from urlconf
111 | ```
112 |
113 | * TODO:
114 | - Handle type checking parameterized generics e.g. `typing.List[int]`, `list[str]` etc.
115 | - Should only warn for each unhandled Converter once.
116 | - Regex patterns perhaps? (only RoutePattern supported at the moment).
117 |
118 | ## Credits
119 |
120 | - [Luke Plant](https://github.com/spookylukey) for providing the idea and the initial code.
121 | - This package was created with [Cookiecutter](https://github.com/audreyr/cookiecutter) and
122 | the [waynerv/cookiecutter-pypackage](https://github.com/waynerv/cookiecutter-pypackage) project template.
123 |
--------------------------------------------------------------------------------
/django_urlconfchecks/__init__.py:
--------------------------------------------------------------------------------
1 | """Top-level package for django-UrlConfChecks."""
2 |
3 | __author__ = """ali sayyah"""
4 | __email__ = 'ali.sayyah2@gmail.com'
5 | __version__ = '0.11.0'
6 |
--------------------------------------------------------------------------------
/django_urlconfchecks/apps.py:
--------------------------------------------------------------------------------
1 | """An apps module for django_urlconfchecks."""
2 |
3 | from django.apps import AppConfig
4 |
5 |
6 | class UrlConfChecksConfig(AppConfig):
7 | """An AppConfig for django_urlconfchecks."""
8 |
9 | name = 'django_urlconfchecks'
10 | verbose_name = 'URL Conf Checks'
11 |
12 | # noinspection PyUnresolvedReferences
13 | def ready(self):
14 | """We only need to import the module to register it as a checker."""
15 | from django_urlconfchecks import check # noqa
16 |
--------------------------------------------------------------------------------
/django_urlconfchecks/check.py:
--------------------------------------------------------------------------------
1 | """Quick and dirty URL checker."""
2 |
3 | import fnmatch
4 | import typing as t
5 | import uuid
6 | from inspect import Parameter, _empty, signature # type: ignore[attr-defined]
7 |
8 | from django.conf import settings
9 | from django.core import checks
10 | from django.urls import URLPattern, URLResolver, converters, get_resolver
11 | from django.urls.resolvers import RoutePattern
12 |
13 | Problem = t.Union[checks.Error, checks.Warning]
14 |
15 | # Update docs about default value if you change this:
16 | _DEFAULT_SILENCED_VIEWS = {
17 | # for CBVs
18 | "*.View.as_view": "W001",
19 | # RedirectView is used in a way that makes it appear directly, and it has **kwargs
20 | "django.views.generic.base.RedirectView": "W001",
21 | # Django contrib views currently don’t have type annotations:
22 | "django.contrib.*": "W003",
23 | }
24 |
25 |
26 | @checks.register(checks.Tags.urls)
27 | def check_url_signatures(app_configs, **kwargs) -> t.List[Problem]:
28 | """Check that all callbacks in the main urlconf have the correct signature.
29 |
30 | Args:
31 | app_configs: A list of AppConfig instances that will be checked.
32 | **kwargs: Not used.
33 |
34 | Returns:
35 | A list of errors.
36 | """
37 | if not getattr(settings, 'ROOT_URLCONF', None):
38 | return []
39 |
40 | resolver = get_resolver()
41 | errors = []
42 | silencers = _build_view_silencers(getattr(settings, "URLCONFCHECKS_SILENCED_VIEWS", _DEFAULT_SILENCED_VIEWS))
43 | for route, parent_converters in get_all_routes(resolver, {}):
44 | errors.extend(check_url_args_match(route, parent_converters))
45 | return _filter_errors(errors, silencers)
46 |
47 |
48 | def get_all_routes(resolver: URLResolver, parent_converters: dict) -> t.Iterable[t.Tuple[URLPattern, dict]]:
49 | """Recursively get all routes from the resolver."""
50 | for pattern in resolver.url_patterns:
51 | if isinstance(pattern, URLResolver):
52 | if hasattr(pattern, 'pattern') and pattern.pattern is not None:
53 | # This handles cases involving `include` where the parent `path`
54 | # may have captured some parameters in its first argument. Those
55 | # parameters will also need to be passed down.
56 | new_parent_converters = {**parent_converters, **pattern.pattern.converters}
57 | else:
58 | new_parent_converters = parent_converters
59 | yield from get_all_routes(pattern, new_parent_converters)
60 | else:
61 | if isinstance(pattern.pattern, RoutePattern):
62 | yield pattern, parent_converters
63 |
64 |
65 | def _make_callback_repr(callback):
66 | if hasattr(callback, "view_class"):
67 | qualname = callback.view_class.as_view.__qualname__
68 | module = callback.view_class.as_view.__module__
69 | else:
70 | qualname = callback.__qualname__
71 | module = callback.__module__
72 | return f"{module}.{qualname}"
73 |
74 |
75 | def check_url_args_match(url_pattern: URLPattern, parent_converters: dict) -> t.List[Problem]:
76 | """Check that all callbacks in the main urlconf have the correct signature."""
77 | callback = url_pattern.callback
78 | callback_repr = _make_callback_repr(callback)
79 | errors = []
80 | sig = signature(callback)
81 | parameters = sig.parameters
82 |
83 | # We need to match everything defined in route definition, plus the kwargs
84 | # passed to path if any, against the signature of the view function.
85 |
86 | # Overall strategy:
87 |
88 | # 1. For all arguments captured by the RoutePattern, check they are in the
89 | # view sig and that the type matches.
90 |
91 | # 2. For any parameter left in the view sig we didn't see yet,
92 | # check that it either has a default arg in the sig,
93 | # or that we can get it from the default_args in the URLPattern (and the type matches)
94 |
95 | # 3. For anything left over in URLPattern.default_arguments, complain.
96 |
97 | has_star_args = False
98 | if any(p.kind in [Parameter.VAR_KEYWORD, Parameter.VAR_POSITIONAL] for p in parameters.values()):
99 | errors.append(
100 | checks.Warning(
101 | f'View {callback_repr} signature contains *args or **kwarg syntax, can\'t properly check args',
102 | obj=url_pattern,
103 | id='urlchecker.W001',
104 | )
105 | )
106 | has_star_args = True
107 |
108 | used_from_sig = []
109 | parameter_list = list(sig.parameters)
110 | if parameter_list and parameter_list[0] == 'self':
111 | # HACK: we need to find some nice way to detect closures/bound methods,
112 | # while also getting the final signature.
113 | parameter_list.pop(0)
114 | used_from_sig.append('self')
115 |
116 | if not parameter_list or parameter_list[0] != 'request':
117 | if not has_star_args:
118 | if parameter_list:
119 | message = (
120 | f'View {callback_repr} signature does not start with `request` parameter, '
121 | f'found `{parameter_list[0]}`.'
122 | )
123 | else:
124 | message = f'View {callback_repr} signature does not have `request` parameter.'
125 | errors.append(
126 | checks.Error(
127 | message,
128 | obj=url_pattern,
129 | id='urlchecker.E001',
130 | )
131 | )
132 | else:
133 | used_from_sig.append('request')
134 |
135 | combined_converters = {**parent_converters, **url_pattern.pattern.converters}
136 | # Everything in RoutePattern must be in signature
137 | for name, converter in combined_converters.items():
138 | if has_star_args:
139 | used_from_sig.append(name)
140 | elif name in sig.parameters:
141 | used_from_sig.append(name)
142 | urlconf_type = get_converter_output_type(converter)
143 | sig_type = sig.parameters[name].annotation
144 | if urlconf_type == Parameter.empty:
145 | # TODO - only output this warning once per converter
146 | obj = converter.__class__
147 | errors.append(
148 | checks.Warning(
149 | f"Don\'t know output type for converter {obj.__module__}.{obj.__name__},"
150 | " can\'t verify URL signatures.",
151 | obj=obj,
152 | id=f'urlchecker.W002.{obj.__module__}.{obj.__name__}',
153 | )
154 | )
155 | elif sig_type == Parameter.empty:
156 | errors.append(
157 | # This should be synced with W003 below.
158 | checks.Warning(
159 | f'View {callback_repr} missing type annotation for parameter `{name}`, can\'t check type.',
160 | obj=url_pattern,
161 | id='urlchecker.W003',
162 | )
163 | )
164 | elif not _type_is_compatible(urlconf_type, sig_type): # type: ignore
165 | errors.append(
166 | checks.Error(
167 | f'View {callback_repr} for parameter `{name}`,' # type: ignore[union-attr]
168 | f' annotated type {_name_type(sig_type)} does not match' # type: ignore[union-attr]
169 | f' expected `{_name_type(urlconf_type)}` from urlconf', # type: ignore[union-attr]
170 | obj=url_pattern,
171 | id='urlchecker.E002',
172 | )
173 | )
174 | else:
175 | errors.append(
176 | checks.Error(
177 | f'View {callback_repr} signature does not contain `{name}` parameter',
178 | obj=url_pattern,
179 | id='urlchecker.E003',
180 | )
181 | )
182 |
183 | # Anything left over must have a default argument, either from signature, or from url_pattern.default_args
184 | used_from_default_args = []
185 | for name, param in sig.parameters.items():
186 | if name in used_from_sig:
187 | continue
188 | if name in url_pattern.default_args:
189 | used_from_default_args.append(name)
190 | sig_type = param.annotation
191 | default_arg = url_pattern.default_args[name]
192 | if sig_type == Parameter.empty:
193 | errors.append(
194 | checks.Warning(
195 | f'View {callback_repr} missing type annotation for parameter `{name}`, can\'t check type.',
196 | obj=url_pattern,
197 | id='urlchecker.W003',
198 | )
199 | )
200 | elif not _instance_is_compatible(default_arg, sig_type):
201 | errors.append(
202 | checks.Error(
203 | f'View {callback_repr}: for parameter `{name}`,'
204 | f' default argument {repr(default_arg)} in urlconf, type {_name_type(type(default_arg))},'
205 | f' does not match annotated type {_name_type(sig_type)} from view signature',
206 | obj=url_pattern,
207 | id='urlchecker.E005',
208 | )
209 | )
210 | continue
211 | if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
212 | # *args and **kwargs
213 | continue
214 | if param.default == Parameter.empty:
215 | errors.append(
216 | checks.Error(
217 | f'View {callback_repr} signature contains `{name}` parameter without default or ULRconf parameter',
218 | obj=url_pattern,
219 | id='urlchecker.E004',
220 | )
221 | )
222 |
223 | # Anything left over in default_args is also an error
224 | for name in url_pattern.default_args:
225 | if name in used_from_default_args:
226 | continue
227 | errors.append(
228 | checks.Error(
229 | f'View {callback_repr} is being passed additional unexpected '
230 | f'parameter `{name}` from default arguments in urlconf',
231 | obj=url_pattern,
232 | id='urlchecker.E006',
233 | )
234 | )
235 |
236 | return errors
237 |
238 |
239 | def _type_is_compatible(passed_type, accepted_type):
240 | try:
241 | return issubclass(passed_type, accepted_type)
242 | except TypeError as e:
243 | # For Python < 3.10 we get:
244 | # Subscripted generics cannot be used with class and instance checks
245 | if 'Subscripted generics' in e.args[0]:
246 | # It's difficult to replicate Python 3.10 behaviour. So just let it pass,
247 | # rather than falsely say it's incompatible.
248 | return True
249 | elif 'parameterized generic' in e.args[0]:
250 | # Tricky to handle correctly
251 | return True
252 | elif 'must be a class' in e.args[0]:
253 | # Can happen for passed_type == `Optional[int]`
254 | # Tricky to handle correctly
255 | return True
256 | else:
257 | raise # pragma: no cover
258 |
259 |
260 | def _instance_is_compatible(instance, accepted_type):
261 | try:
262 | return isinstance(instance, accepted_type)
263 | except TypeError as e:
264 | # Same as in _type_is_compatible
265 | if 'Subscripted generics' in e.args[0]:
266 | return True
267 | elif 'parameterized generic' in e.args[0]:
268 | return True
269 | else:
270 | raise # pragma: no cover
271 |
272 |
273 | def _name_type(type_hint):
274 | # Things like `Optional[int]`:
275 | # - repr() does a better job than `__name__`
276 | # - `__name__` is not available in some Python versions.
277 | return type_hint.__name__ if (hasattr(type_hint, "__name__") and isinstance(type_hint, type)) else repr(type_hint)
278 |
279 |
280 | CONVERTER_TYPES = {
281 | converters.IntConverter: int,
282 | converters.StringConverter: str,
283 | converters.UUIDConverter: uuid.UUID,
284 | converters.SlugConverter: str,
285 | converters.PathConverter: str,
286 | }
287 |
288 |
289 | def get_converter_output_type(converter) -> t.Union[int, str, uuid.UUID, t.Type[_empty]]:
290 | """Return the type that the converter will output."""
291 | for cls in converter.__class__.__mro__:
292 | if cls in CONVERTER_TYPES:
293 | return CONVERTER_TYPES[cls]
294 |
295 | if hasattr(cls, "to_python"):
296 | sig = signature(cls.to_python)
297 | if sig.return_annotation != Parameter.empty:
298 | return sig.return_annotation
299 |
300 | return Parameter.empty
301 |
302 |
303 | class ViewSilencer:
304 | """Utility that checks whether errors for a view or set of views should be ignored."""
305 |
306 | def __init__(self, view_glob: str, errors: t.Iterable[str]):
307 | self.view_glob = view_glob
308 | self.errors = set(errors)
309 |
310 | def matches(self, error: Problem):
311 | """Returns True if this silencer matches the given error or warning."""
312 | url_pattern = error.obj
313 | if not isinstance(url_pattern, URLPattern):
314 | # Some other error, eg. for a convertor
315 | return False
316 | if error.id not in self.errors:
317 | return False
318 |
319 | view_name = _make_callback_repr(url_pattern.callback)
320 | if fnmatch.fnmatch(view_name, self.view_glob):
321 | return True
322 | return False
323 |
324 |
325 | def _build_view_silencers(silenced_views: t.Dict[str, str]) -> t.List[ViewSilencer]:
326 | return [
327 | ViewSilencer(view_glob=view_glob, errors=[f"urlchecker.{error}" for error in error_list.split(",")])
328 | for view_glob, error_list in silenced_views.items()
329 | ]
330 |
331 |
332 | def _filter_errors(errors: t.List[Problem], silencers: t.List[ViewSilencer]) -> t.List[Problem]:
333 | return [error for error in errors if not any(silencer.matches(error) for silencer in silencers)]
334 |
--------------------------------------------------------------------------------
/django_urlconfchecks/cli.py:
--------------------------------------------------------------------------------
1 | """CLI module for django_urlconfchecks."""
2 |
3 | from typing import Optional
4 |
5 | from django.core.checks import Error
6 |
7 | from django_urlconfchecks import __version__
8 | from django_urlconfchecks.cli_utils import setup_django
9 |
10 | try:
11 | import django
12 | except ImportError:
13 | raise ImportError('django_urlconfchecks requires django. Install it with `pip install django`.')
14 | import typer
15 |
16 | app = typer.Typer()
17 |
18 |
19 | def version_callback(value: bool):
20 | """Print version and exit."""
21 | if value:
22 | typer.echo(f"Django Urlconf Checks Version: {__version__}")
23 | raise typer.Exit()
24 |
25 |
26 | # noinspection PyUnusedLocal
27 | @app.command()
28 | def run(
29 | version: Optional[bool] = typer.Option(None, "--version", callback=version_callback),
30 | urlconf: Optional[str] = typer.Option(None, "-u", "--urlconf", help="Specify the URLconf to check."),
31 | ) -> None:
32 | """Check all URLConfs for errors."""
33 | if django.VERSION[0:2] < (3, 2):
34 | typer.secho("Django version 3.2 or higher is required.", fg=typer.colors.RED)
35 | raise typer.Exit(1)
36 |
37 | setup_django(urlconf=urlconf)
38 |
39 | from django_urlconfchecks.check import check_url_signatures
40 |
41 | errors = check_url_signatures(None)
42 | if errors:
43 | typer.secho(f"{len(errors)} error{'s' if len(errors) > 1 else ''} found:", fg=typer.colors.BRIGHT_RED)
44 |
45 | for error in errors:
46 | if isinstance(error, Error):
47 | typer.secho(f"\t{error}", fg=typer.colors.RED)
48 | else:
49 | typer.secho(f"\t{error}", fg=typer.colors.YELLOW)
50 | raise typer.Exit(1)
51 | else:
52 | typer.secho("Done. No errors found.", fg=typer.colors.GREEN)
53 | raise typer.Exit(0)
54 |
--------------------------------------------------------------------------------
/django_urlconfchecks/cli_utils.py:
--------------------------------------------------------------------------------
1 | """Utils for cli."""
2 |
3 | import importlib
4 | import os
5 | import sys
6 | import typing as t
7 | from contextlib import contextmanager, redirect_stderr, redirect_stdout
8 | from os import devnull
9 |
10 | import django
11 | import typer
12 | from django.conf import settings
13 |
14 |
15 | @contextmanager
16 | def suppress_std():
17 | """A context manager that redirects stdout and stderr to devnull."""
18 | with open(devnull, 'w') as fnull:
19 | with redirect_stderr(fnull) as err, redirect_stdout(fnull) as out:
20 | yield err, out
21 |
22 |
23 | def setup_django(urlconf: t.Optional[str]):
24 | """We need to set up Django before running checks.
25 |
26 | For running checks, we need to access UrlConf module correctly;
27 | so we use manage.py to set the `DJANGO_SETTINGS_MODULE`.
28 |
29 | Returns:
30 | str: the path to the settings.py
31 | """
32 | if not settings.configured:
33 | if urlconf:
34 | settings.configure(ROOT_URLCONF=urlconf)
35 | else:
36 | get_manage()
37 |
38 | django.setup()
39 | if urlconf:
40 | settings.ROOT_URLCONF = urlconf
41 |
42 |
43 | def get_manage():
44 | """Get the path to manage.py and import it with `importlib.import_module`."""
45 | if os.getcwd() not in sys.path:
46 | sys.path.insert(0, os.getcwd())
47 |
48 | try:
49 | manage = importlib.import_module("manage", ".")
50 | except ImportError:
51 | typer.secho(
52 | "Could not find manage.py in current directory or subdirectories.\n"
53 | "Make sure you are in the project root directory where manage.py exists."
54 | "Or you can specify your main urlconf module path with -u or --urlconf option.",
55 | fg=typer.colors.RED,
56 | )
57 | raise typer.Exit(1)
58 | else:
59 | main = getattr(manage, 'main', None)
60 | if main:
61 | with suppress_std():
62 | main()
63 | return
64 |
--------------------------------------------------------------------------------
/docs/changelog.md:
--------------------------------------------------------------------------------
1 | {%
2 | include-markdown "../CHANGELOG.md"
3 | %}
4 |
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | {%
2 | include-markdown "../CONTRIBUTING.md"
3 | %}
4 |
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 | {%
2 | include-markdown "../README.md"
3 | %}
4 |
--------------------------------------------------------------------------------
/docs/installation.md:
--------------------------------------------------------------------------------
1 | # Installation
2 |
3 | ## Stable release
4 |
5 | To install django-UrlConfChecks, run this command in your
6 | terminal:
7 |
8 | ``` console
9 | $ pip install django-urlconfchecks
10 | ```
11 |
12 | This is the preferred method to install django-UrlConfChecks, as it will always install the most recent stable release.
13 |
14 | If you don't have [pip][] installed, this [Python installation guide][]
15 | can guide you through the process.
16 |
17 | ## From source
18 |
19 | The source for django-UrlConfChecks can be downloaded from
20 | the [Github repo][].
21 |
22 | You can either clone the public repository:
23 |
24 | ``` console
25 | $ git clone git://github.com/AliSayyah/django-urlconfchecks
26 | ```
27 |
28 | Or download the [tarball][]:
29 |
30 | ``` console
31 | $ curl -OJL https://github.com/AliSayyah/django-urlconfchecks/tarball/master
32 | ```
33 |
34 | Once you have a copy of the source, you can install it with:
35 |
36 | ``` console
37 | $ pip install .
38 | ```
39 |
40 | [pip]: https://pip.pypa.io
41 | [Python installation guide]: http://docs.python-guide.org/en/latest/starting/installation/
42 | [Github repo]: https://github.com/%7B%7B%20cookiecutter.github_username%20%7D%7D/%7B%7B%20cookiecutter.project_slug%20%7D%7D
43 | [tarball]: https://github.com/%7B%7B%20cookiecutter.github_username%20%7D%7D/%7B%7B%20cookiecutter.project_slug%20%7D%7D/tarball/master
44 |
--------------------------------------------------------------------------------
/docs/usage.md:
--------------------------------------------------------------------------------
1 | # Usage
2 |
3 | You can use this package in different ways:
4 |
5 | ### As a Django app
6 |
7 | Add `django_urlconfchecks` to your `INSTALLED_APPS` list in your `settings.py` file.
8 |
9 | ```python
10 | INSTALLED_APPS = [
11 | ...
12 | 'django_urlconfchecks',
13 | ]
14 | ```
15 |
16 | Now, if there is any error, you can check it when you run `python manage.py check` or when your django server runs or
17 | reloads with `python manage.py runserver`.
18 |
19 | ### As a command line tool
20 |
21 | `urlconfchecks` uses the `Typer` module to parse command line arguments.
22 |
23 | Run this command from the root of your project, were `manage.py` is located:
24 |
25 | ```bash
26 | $ urlconfchecks --help
27 |
28 | Usage: urlconfchecks [OPTIONS]
29 |
30 | Check all URLConfs for errors.
31 |
32 | Options:
33 | --version
34 | -u, --urlconf PATH Specify the URLconf to check.
35 | --install-completion Install completion for the current shell.
36 | --show-completion Show completion for the current shell, to copy it or
37 | customize the installation.
38 | --help Show this message and exit.
39 |
40 | ```
41 |
42 | `--urlconf` is optional, and if not specified, app will try to find the manage.py in your current directory for
43 | accessing the main URLConf module.
44 |
45 | Example:
46 |
47 | ```bash
48 | $ urlconfchecks --urlconf my_project.urls
49 |
50 | Done. No errors found.
51 | ```
52 |
53 | ### As a pre-commit hook
54 | Make sure you have `pre-commit` installed and if not, install it with `pip install pre-commit && pre-commit install`.
55 |
56 | Then, add the following to your `.pre-commit-config.yaml` file:
57 |
58 | ```yaml
59 | - repo: https://github.com/AliSayyah/django-urlconfchecks
60 | rev: v0.11.0
61 | hooks:
62 | - id: django-urlconfchecks
63 | ```
64 |
65 | Run `pre-commit run` to check all URLConfs for errors.
66 |
67 |
68 | ## Silencing errors and warnings
69 |
70 | You can silence specific errors and warnings as described in the [System check
71 | framework
72 | documentation](https://docs.djangoproject.com/en/stable/topics/checks/).
73 |
74 | For example:
75 |
76 | ```python
77 | SILENCED_SYSTEM_CHECKS = [
78 | "urlchecker.W003“,
79 | ]
80 | ```
81 |
82 | However, this turns off the check for all view functions. Instead of this you
83 | can use the `URLCONFCHECKS_SILENCED_VIEWS` setting for more fine grained
84 | silencing. The value must be a dictionary:
85 |
86 | - whose keys are fully qualified dotted paths to view functions or callables,
87 | with globbing syntax allowed, e.g. `"my_project.views.my_view"` or
88 | `"other_project.*"`
89 |
90 | - whose values are comma separated lists of warning or error IDs (without the
91 | `urlchecker` prefix), e.g. `"E001,W003”`
92 |
93 |
94 | The default value of `URLCONFCHECKS_SILENCED_VIEWS` is below. If you override it
95 | in your `settings.py`, you will probably want to include the following and add
96 | more items:
97 |
98 | ```python
99 | URLCONFCHECKS_SILENCED_VIEWS = {
100 | "*.View.as_view": "W001", # CBVs
101 | "django.views.generic.base.RedirectView": "W001",
102 | "django.contrib.*": "W003", # admin etc.
103 | }
104 | ```
105 |
--------------------------------------------------------------------------------
/makefile:
--------------------------------------------------------------------------------
1 | sources = django_urlconfchecks
2 |
3 | .PHONY: test format lint unittest coverage pre-commit clean
4 | test: format lint unittest
5 |
6 | format:
7 | isort $(sources) tests
8 | black $(sources) tests
9 |
10 | lint:
11 | flake8 $(sources) tests
12 | mypy $(sources) tests
13 |
14 | unittest:
15 | pytest
16 |
17 | coverage:
18 | pytest --cov=$(sources) --cov-branch --cov-report=term-missing tests
19 |
20 | pre-commit:
21 | pre-commit run --all-files
22 |
23 | clean:
24 | rm -rf .mypy_cache .pytest_cache
25 | rm -rf *.egg-info
26 | rm -rf .tox dist site
27 | rm -rf coverage.xml .coverage
28 |
--------------------------------------------------------------------------------
/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: Django UrlConf Checks
2 | site_url: https://AliSayyah.github.io/django-urlconfchecks
3 | repo_url: https://github.com/AliSayyah/django-urlconfchecks
4 | repo_name: AliSayyah/django-urlconfchecks
5 | #strict: true
6 | nav:
7 | - Home: index.md
8 | - Installation: installation.md
9 | - Usage: usage.md
10 | - Contributing: contributing.md
11 | - Changelog: changelog.md
12 | theme:
13 | name: material
14 | language: en
15 | palette:
16 | - media: "(prefers-color-scheme: light)"
17 | scheme: default
18 | primary: black
19 | toggle:
20 | icon: material/toggle-switch-off-outline
21 | name: Switch to dark mode
22 | - media: "(prefers-color-scheme: dark)"
23 | scheme: slate
24 | primary: red
25 | accent: red
26 | toggle:
27 | icon: material/toggle-switch
28 | name: Switch to light mode
29 | features:
30 | - navigation.indexes
31 | - navigation.instant
32 | - navigation.tabs.sticky
33 | - navigation.tracking
34 | markdown_extensions:
35 | - pymdownx.emoji:
36 | emoji_index: !!python/name:material.extensions.emoji.twemoji
37 | emoji_generator: !!python/name:material.extensions.emoji.to_svg
38 | - pymdownx.critic
39 | - pymdownx.caret
40 | - pymdownx.mark
41 | - pymdownx.tilde
42 | - pymdownx.tabbed
43 | - attr_list
44 | - pymdownx.arithmatex:
45 | generic: true
46 | - pymdownx.highlight:
47 | linenums: false
48 | - pymdownx.superfences
49 | - pymdownx.inlinehilite
50 | - pymdownx.details
51 | - admonition
52 | - toc:
53 | baselevel: 2
54 | permalink: true
55 | slugify: !!python/name:pymdownx.slugs.uslugify
56 | - meta
57 | plugins:
58 | - include-markdown
59 | - search:
60 | lang: en
61 |
62 | extra:
63 | social:
64 | - icon: fontawesome/brands/github
65 | link: https://github.com/AliSayyah/django-urlconfchecks
66 | name: Github
67 | - icon: material/email
68 | link: "mailto:ali.sayyah2@gmail.com"
69 | watch:
70 | - django-urlconfchecks
71 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool]
2 | [tool.poetry]
3 | name = "django-urlconfchecks"
4 | version = "0.11.0"
5 | homepage = "https://github.com/AliSayyah/django-urlconfchecks"
6 | description = "a python package for type checking the urls and associated views."
7 | authors = ["ali sayyah "]
8 | readme = "README.md"
9 | license = "GPLv3"
10 | classifiers = [
11 | 'Development Status :: 5 - Production/Stable',
12 | 'Intended Audience :: Developers',
13 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
14 | 'Natural Language :: English',
15 | 'Programming Language :: Python :: 3.9',
16 | 'Programming Language :: Python :: 3.10',
17 | 'Programming Language :: Python :: 3.11',
18 | 'Programming Language :: Python :: 3.12',
19 | 'Programming Language :: Python :: 3.13',
20 | 'Framework :: Django :: 4.0',
21 | 'Framework :: Django :: 5.0',
22 | ]
23 | packages = [
24 | { include = "django_urlconfchecks" },
25 | { include = "tests", format = "sdist" },
26 | ]
27 |
28 | [tool.poetry.scripts]
29 | urlconfchecks = "django_urlconfchecks.cli:app"
30 |
31 | [tool.poetry.dependencies]
32 | python = ">=3.9.0,<4"
33 | Django = ">=4.2"
34 | typer = { extras = ["all"], version = ">=0.9.0,<1.0.0" }
35 |
36 | black = { version = "^25.1.0", optional = true }
37 | isort = { version = "^6.0", optional = true }
38 | flake8 = { version = "^7.2.0", optional = true }
39 | flake8-docstrings = { version = "^1.6.0", optional = true }
40 | mypy = { version = "^1.15.0", optional = true }
41 | pytest = { version = "^8.0.2", optional = true }
42 | pytest-cov = { version = "^6.1.1", optional = true }
43 | pytest-django = { version = "^4.5.2", optional = true }
44 | tox = { version = "^4.13.0", optional = true }
45 | virtualenv = { version = "^20.2.2", optional = true }
46 | mkdocs = { version = "^1.5.3", optional = true }
47 | mkdocs-include-markdown-plugin = { version = "^7.1.5", optional = true }
48 | mkdocs-material = { version = "^9.5.11", optional = true }
49 | twine = { version = "^6.1.0", optional = true }
50 | mkdocs-autorefs = { version = "^1.4.0", optional = true }
51 | pre-commit = { version = "^4.2.0", optional = true }
52 | toml = { version = "^0.10.2", optional = true }
53 | bump2version = { version = "^1.0.1", optional = true }
54 | Markdown = { version = "^3.3.4", optional = true }
55 |
56 | [tool.poetry.extras]
57 | test = [
58 | "pytest",
59 | "black",
60 | "isort",
61 | "mypy",
62 | "flake8",
63 | "flake8-docstrings",
64 | "pytest-cov",
65 | "pytest-django",
66 | "pyupgrade",
67 | ]
68 |
69 | dev = ["tox", "pre-commit", "virtualenv", "twine", "toml", "bump2version", 'Markdown']
70 |
71 | doc = [
72 | 'Markdown',
73 | "mkdocs",
74 | "mkdocs-include-markdown-plugin",
75 | "mkdocs-material",
76 | "mkdocs-autorefs"
77 | ]
78 |
79 | [tool.black]
80 | line-length = 120
81 | skip-string-normalization = true
82 | target-version = ['py38']
83 | include = '\.pyi?$'
84 | exclude = '''
85 | /(
86 | \.eggs
87 | | \.git
88 | | \.hg
89 | | \.mypy_cache
90 | | \.tox
91 | | \.venv
92 | | _build
93 | | buck-out
94 | | build
95 | | dist
96 | )/
97 | '''
98 |
99 | [tool.isort]
100 | multi_line_output = 3
101 | include_trailing_comma = true
102 | force_grid_wrap = 0
103 | use_parentheses = true
104 | ensure_newline_before_comments = true
105 | line_length = 120
106 | skip_gitignore = true
107 | # you can skip files as below
108 | #skip_glob = docs/conf.py
109 |
110 | [build-system]
111 | requires = ["poetry-core>=1.0.0"]
112 | build-backend = "poetry.core.masonry.api"
113 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | DJANGO_SETTINGS_MODULE = tests.dummy_project.settings
3 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | min_python_version = 3.9.0
3 | max-line-length = 120
4 | max-complexity = 18
5 | ignore = E203, E266, W503, D107, C901
6 | docstring-convention = google
7 | per-file-ignores =
8 | __init__.py:F401
9 | tests/*:D101,D102,D103,E704
10 | exclude = .git,
11 | __pycache__,
12 | setup.py,
13 | build,
14 | dist,
15 | docs,
16 | releases,
17 | .venv,
18 | .tox,
19 | .mypy_cache,
20 | .pytest_cache,
21 | .vscode,
22 | .github,
23 | # By default test codes will be linted.
24 | # tests
25 |
26 | [mypy]
27 | ignore_missing_imports = True
28 |
29 | [coverage:run]
30 | # uncomment the following to omit files during running
31 | #omit =
32 | [coverage:report]
33 | exclude_lines =
34 | pragma: no cover
35 | def __repr__
36 | if self.debug:
37 | if settings.DEBUG
38 | raise AssertionError
39 | raise NotImplementedError
40 | if 0:
41 | if __name__ == .__main__.:
42 | def main
43 |
44 | [tox:tox]
45 | isolated_build = true
46 | env_list = py{39, 310, 311, 312}-django42, py{310, 311, 312}-django{50, 51, 52}, py313-django{51, 52}, format, lint, build
47 |
48 | [gh-actions]
49 | python =
50 | 3.13: py313
51 | 3.12: py312
52 | 3.11: py311
53 | 3.10: py310
54 | 3.9: py39, format, lint, build
55 |
56 | [testenv]
57 | allowlist_externals = pytest
58 | deps =
59 | django42: django==4.2.8
60 | django50: django==5.0.0
61 | django51: django==5.1.3
62 | django52: django==5.2.0
63 | extras =
64 | test
65 | passenv = *
66 | setenv =
67 | PYTHONPATH = {toxinidir}
68 | PYTHONWARNINGS = ignore
69 | commands =
70 | pytest --cov=django_urlconfchecks --cov-branch --cov-report=xml --cov-report=term-missing tests
71 |
72 | [testenv:format]
73 | allowlist_externals =
74 | isort
75 | black
76 | extras =
77 | test
78 | commands =
79 | isort django_urlconfchecks
80 | black django_urlconfchecks tests
81 |
82 | [testenv:lint]
83 | allowlist_externals =
84 | flake8
85 | mypy
86 | extras =
87 | test
88 | commands =
89 | flake8 django_urlconfchecks tests
90 | mypy django_urlconfchecks tests --show-error-codes
91 |
92 | [testenv:build]
93 | allowlist_externals =
94 | poetry
95 | mkdocs
96 | twine
97 | extras =
98 | doc
99 | dev
100 | commands =
101 | poetry build
102 | mkdocs build
103 | twine check dist/*
104 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | """Unit test package for django-urlconfchecks."""
2 |
--------------------------------------------------------------------------------
/tests/dummy_project/__init__.py:
--------------------------------------------------------------------------------
1 | """Dummy project."""
2 |
--------------------------------------------------------------------------------
/tests/dummy_project/settings.py:
--------------------------------------------------------------------------------
1 | """Settings module for dummy_project."""
2 |
3 | DEBUG = True
4 | USE_TZ = True
5 | DATABASES = {
6 | "default": {
7 | "ENGINE": "django.db.backends.sqlite3",
8 | }
9 | }
10 | ROOT_URLCONF = ("tests.dummy_project.urls.correct_urls",)
11 | INSTALLED_APPS = [
12 | "django.contrib.admin",
13 | "django.contrib.auth",
14 | "django.contrib.contenttypes",
15 | "django.contrib.sites",
16 | "django_urlconfchecks",
17 | ]
18 | SECRET_KEY = "secret"
19 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/__init__.py:
--------------------------------------------------------------------------------
1 | """urls module for tests."""
2 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/admin_urls.py:
--------------------------------------------------------------------------------
1 | """admin urls for test."""
2 |
3 | from django.contrib import admin
4 | from django.urls import path
5 |
6 | urlpatterns = [path('admin/', admin.site.urls)]
7 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/cbv_urls.py:
--------------------------------------------------------------------------------
1 | """CBV urls for tests."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | path('cbv_view/', views.CBVView.as_view()),
9 | ]
10 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/child_urls.py:
--------------------------------------------------------------------------------
1 | """child urls for test."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | path('articles///', views.month_archive),
9 | path('articles////', views.article_detail),
10 | path('/', views.bad_view),
11 | path('special-case//', views.special_case),
12 | ]
13 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/converter_urls.py:
--------------------------------------------------------------------------------
1 | """URLs using custom converters and subclassed converters, with errors."""
2 |
3 | from django.urls import path, register_converter
4 | from django.urls.converters import IntConverter
5 |
6 | from tests.dummy_project import views
7 |
8 |
9 | class YearConverter:
10 | # Converter with type hint on to_python, should be handled automatically.
11 | regex = "[0-9]{4}"
12 |
13 | def to_python(self, value: str) -> int:
14 | return int(value)
15 |
16 | def to_url(self, value: int):
17 | return f"{value:04}"
18 |
19 |
20 | class YearConverterNoTypeHint:
21 | # Converter with no type hint, should raise warning
22 | regex = "[0-9]{4}"
23 |
24 | def to_python(self, value: str):
25 | return int(value)
26 |
27 | def to_url(self, value: int):
28 | return f"{value:04}"
29 |
30 |
31 | class YearConverterViaSubclass(IntConverter):
32 | # Subclass converter, no to_python method,
33 | # so we should default to the type inferred for base class
34 | regex = "[0-9]{4}"
35 |
36 |
37 | class YearConverterAsFloat(IntConverter):
38 | # Subclass - for this case we should infer from the sig on to_python
39 | # method, not the base class (this float type will cause a type error)
40 | def to_python(self, value: str) -> float:
41 | return float(super().to_python(value))
42 |
43 |
44 | register_converter(YearConverter, "yyyy")
45 | register_converter(YearConverterNoTypeHint, "yyyy_notype")
46 | register_converter(YearConverterViaSubclass, "yyyy_subclass")
47 | register_converter(YearConverterAsFloat, "yyyy_float")
48 |
49 | urlpatterns = [
50 | path('articles_yyyy//', views.year_archive),
51 | path('articles_yyyy_notype//', views.year_archive),
52 | path('articles_yyyy_subclass//', views.year_archive),
53 | path('articles_yyyy_float//', views.year_archive),
54 | ]
55 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/correct_urls.py:
--------------------------------------------------------------------------------
1 | """Correct URLs."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | path('articles//', views.year_archive),
9 | path('articles///', views.month_archive),
10 | path('articles////', views.article_detail),
11 | ]
12 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/includes.py:
--------------------------------------------------------------------------------
1 | """URLs for testing `django.urls.include` support."""
2 |
3 | from django.urls import include, path
4 |
5 | from tests.dummy_project import views
6 |
7 | # When using 'include' which should include parameters collected from before
8 |
9 | urlpatterns = [
10 | # All these are valid:
11 | path(
12 | "/",
13 | include(
14 | [
15 | # `year` is passed from above
16 | path('', views.year_archive, name="good-year-archive"),
17 | path('/', views.month_archive, name="good-month-archive"),
18 | path('//', views.article_detail, name="good-detail"),
19 | path(
20 | 'nested//',
21 | include(
22 | [
23 | # `year` and `month` are passed from above
24 | path('', views.month_archive, name="good-month-archive-nested"),
25 | ]
26 | ),
27 | ),
28 | ]
29 | ),
30 | ),
31 | # These are not
32 | path(
33 | "bad-include//",
34 | include(
35 | [
36 | # year_archive does not take `slug` param
37 | path('bad-year/', views.year_archive, name="bad-year-archive"),
38 | ]
39 | ),
40 | ),
41 | ]
42 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/incorrect_urls.py:
--------------------------------------------------------------------------------
1 | """Incorrect URLs."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | path('articles//', views.year_archive),
9 | path('articles///', views.month_archive),
10 | path('articles////', views.article_detail),
11 | ]
12 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/optional_args.py:
--------------------------------------------------------------------------------
1 | """Views with Optional args."""
2 |
3 | from typing import Optional
4 |
5 | from django.urls import path, register_converter
6 |
7 | from tests.dummy_project import views
8 |
9 |
10 | class OptInt:
11 | """Optional int - zero or more digits, converted to None if zero length."""
12 |
13 | regex = r"\d*"
14 |
15 | def to_python(self, value) -> Optional[int]:
16 | return None if value == "" else int(value)
17 |
18 | def to_url(self, value):
19 | return "" if value is None else str(value)
20 |
21 |
22 | class OptStr:
23 | """Optional str, converted to None if zero length."""
24 |
25 | regex = r".*"
26 |
27 | def to_python(self, value) -> Optional[str]:
28 | return None if value == "" else value
29 |
30 | def to_url(self, value):
31 | return "" if value is None else str(value)
32 |
33 |
34 | register_converter(OptInt, "optint")
35 | register_converter(OptStr, "optstr")
36 |
37 |
38 | # We currently don't check all of these properly. Our tests ensure that
39 | # valid ones are not rejected, but not that invalid ones are rejected.
40 | urlpatterns = [
41 | # All these are valid.
42 | path('good-with-val/', views.optional_arg_view),
43 | path('good-without-val/', views.optional_arg_view),
44 | path('good-with-kwarg1/', views.optional_arg_view, kwargs={'val': None}),
45 | path('good-with-kwarg2/', views.optional_arg_view, kwargs={'val': 123}),
46 | path('good-with-optint/', views.optional_arg_view),
47 | # These are not
48 | path('bad-with-val/', views.optional_arg_view),
49 | path('bad-with-kwarg1/', views.optional_arg_view, kwargs={'val': "abc"}),
50 | path('bad-with-optint/', views.non_optional_arg_view),
51 | path('bad-with-optstr/', views.non_optional_arg_view),
52 | path('bad-with-optstr-2/', views.optional_arg_view),
53 | ]
54 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/parameterized_generics.py:
--------------------------------------------------------------------------------
1 | """Views with parameterized generics."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | # Currently we aren't able to check to these types (we just allow them to pass
8 | # and don't crash), but this lists some of the cases we'd need to handle
9 |
10 | urlpatterns = [
11 | # All these are valid
12 | path('good-with-kwarg2/', views.parameterized_generic_view, kwargs={'val': [123]}),
13 | # These are not
14 | path('bad-with-val/', views.parameterized_generic_view),
15 | path('bad-with-kwarg1/', views.parameterized_generic_view, kwargs={'val': "abc"}),
16 | path('bad-with-kwarg2/', views.parameterized_generic_view, kwargs={'val': ["abc"]}),
17 | ]
18 |
19 | if views.parameterized_generic_view_2 is not None:
20 | urlpatterns = [
21 | # All these are valid
22 | path('good-2-with-kwarg2/', views.parameterized_generic_view_2, kwargs={'val': [123]}),
23 | # These are not
24 | path('bad-2-with-val/', views.parameterized_generic_view_2),
25 | path('bad-2-with-kwarg1/', views.parameterized_generic_view_2, kwargs={'val': "abc"}),
26 | path('bad-2-with-kwarg2/', views.parameterized_generic_view_2, kwargs={'val': ["abc"]}),
27 | ]
28 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/parent_urls.py:
--------------------------------------------------------------------------------
1 | """parent urls for tests."""
2 |
3 | from django.urls import include, path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | path('child_urls/', include('tests.dummy_project.urls.child_urls')),
9 | path('articles//', views.year_archive),
10 | ]
11 |
--------------------------------------------------------------------------------
/tests/dummy_project/urls/path_kwargs_urls.py:
--------------------------------------------------------------------------------
1 | """URLs using path(kwargs=)."""
2 |
3 | from django.urls import path
4 |
5 | from tests.dummy_project import views
6 |
7 | urlpatterns = [
8 | # This one is valid, should produce no error
9 | path('articles-2020/', views.year_archive, kwargs={'year': 2020}),
10 | # This one is missing 'year',
11 | path('articles-2021/', views.year_archive),
12 | # This one has wrong type:
13 | path('articles-2022/', views.year_archive, kwargs={'year': '2022'}),
14 | # This one has extra arg which will cause type error:
15 | path('articles-2023/', views.year_archive, kwargs={'year': 2023, 'other': 123}),
16 | # This one is not typed, can't check
17 | path('articles-2024/', views.year_archive_untyped, kwargs={'year': 2024}),
18 | ]
19 |
--------------------------------------------------------------------------------
/tests/dummy_project/views.py:
--------------------------------------------------------------------------------
1 | """views for tests."""
2 |
3 | from typing import List, Optional
4 |
5 | from django.views import View
6 |
7 |
8 | def bad_view(slug: str):
9 | """View missing the `request` parameter."""
10 | ...
11 |
12 |
13 | def special_case(request):
14 | """This is a special case.
15 |
16 | Args:
17 | request: The request object.
18 |
19 | Returns:
20 | A response object.
21 | """
22 | ...
23 |
24 |
25 | def year_archive(request, year: int):
26 | """This is a year archive.
27 |
28 | Args:
29 | request: The request object.
30 | year: The year.
31 |
32 | Returns:
33 | A response object.
34 | """
35 | ...
36 |
37 |
38 | def year_archive_untyped(request, year):
39 | """This is a year archive (with no type hint)."""
40 | ...
41 |
42 |
43 | def month_archive(request, year: int, month: int):
44 | """This is a month archive.
45 |
46 | Args:
47 | request: The request object.
48 | year: The year.
49 | month: The month.
50 |
51 | Returns:
52 | A response object.
53 | """
54 | ...
55 |
56 |
57 | def article_detail(request, year: int, month: int, slug: str):
58 | """This is an article detail.
59 |
60 | Args:
61 | request: The request object.
62 | year: The year.
63 | month: The month.
64 | slug: The slug.
65 |
66 | Returns:
67 | A response object.
68 | """
69 | ...
70 |
71 |
72 | class CBVView(View):
73 | """This is a simple class based view."""
74 |
75 | def get(self, request): ...
76 |
77 |
78 | def non_optional_arg_view(request, val: int): ...
79 |
80 |
81 | def optional_arg_view(request, val: Optional[int] = None): ...
82 |
83 |
84 | def parameterized_generic_view(request, val: List[int]): ...
85 |
86 |
87 | try:
88 |
89 | def parameterized_generic_view_2(request, val: list[int]): # type: ignore
90 | ...
91 |
92 | except TypeError:
93 | parameterized_generic_view_2 = None # type: ignore
94 |
--------------------------------------------------------------------------------
/tests/test_as_django_app.py:
--------------------------------------------------------------------------------
1 | """Test module as a django app."""
2 |
3 |
4 | def test_app_is_recognized():
5 | """Test that the app is recognized by Django.
6 |
7 | Returns:
8 | None
9 | """
10 | from django.apps import apps
11 |
12 | assert apps.is_installed('django_urlconfchecks')
13 |
--------------------------------------------------------------------------------
/tests/test_cli.py:
--------------------------------------------------------------------------------
1 | """Test module for cli."""
2 |
3 | import pytest
4 | from django.conf import settings
5 | from django.utils.functional import empty
6 | from typer.testing import CliRunner
7 |
8 | from django_urlconfchecks import __version__
9 | from django_urlconfchecks.cli import app
10 |
11 | runner = CliRunner()
12 |
13 |
14 | @pytest.fixture(autouse=True)
15 | def configure():
16 | """Configure."""
17 | settings._wrapped = empty
18 |
19 |
20 | def test_cli_no_manage():
21 | """Test no manage.py module and no urlconf."""
22 | result = runner.invoke(app)
23 | assert result.exit_code == 1
24 | assert (
25 | "Could not find manage.py in current directory or subdirectories.\n"
26 | "Make sure you are in the project root directory where manage.py exists.Or you can specify your main"
27 | " urlconf module path with -u or --urlconf option.\n" in result.output
28 | )
29 |
30 |
31 | def test_cli_urlconf_incorrect_one_error():
32 | """Test when one urlconf is incorrect."""
33 | result = runner.invoke(app, ["--urlconf", "tests.dummy_project.urls.incorrect_urls"])
34 | assert (
35 | "1 error found:\n"
36 | "\t/'>: (urlchecker.E002) View"
37 | " tests.dummy_project.views.year_archive for parameter `year`,"
38 | " annotated type int does not match expected `str` from urlconf\n" in result.output
39 | )
40 | assert result.exit_code == 1
41 |
42 |
43 | def test_cli_urlconf_incorrect_multiple_errors():
44 | """Test when multiple urlconfs are incorrect."""
45 | result = runner.invoke(app, ["--urlconf", "tests.dummy_project.urls.child_urls"])
46 |
47 | assert (
48 | "5 errors found:\n"
49 | "\t//'>: (urlchecker.E002) View"
50 | " tests.dummy_project.views.month_archive for parameter `year`,"
51 | " annotated type int does not match expected `str` from urlconf\n"
52 | "\t//'>: (urlchecker.E002) View"
53 | " tests.dummy_project.views.month_archive for parameter `month`,"
54 | " annotated type int does not match expected `str` from urlconf\n"
55 | "\t///'>: (urlchecker.E002) View"
56 | " tests.dummy_project.views.article_detail for parameter `year`,"
57 | " annotated type int does not match expected `str` from urlconf\n"
58 | "\t/'>: (urlchecker.E001) View tests.dummy_project.views.bad_view signature "
59 | "does not start with `request` parameter, found `slug`.\n"
60 | "\t/'>: (urlchecker.E003) View tests.dummy_project.views.special_case "
61 | "signature does not contain `param` parameter\n" == result.output
62 | )
63 | assert result.exit_code == 1
64 |
65 |
66 | def test_cli_urlconf_correct():
67 | """Test when all urlconfs are correct."""
68 | result = runner.invoke(app, ["--urlconf", "tests.dummy_project.urls.correct_urls"])
69 | assert "Done. No errors found.\n" == result.output
70 | assert result.exit_code == 0
71 |
72 |
73 | def test_cli_version():
74 | """Test version."""
75 | result = runner.invoke(app, ["--version"])
76 | assert result.exit_code == 0
77 | assert f"Django Urlconf Checks Version: {__version__}\n" == result.output
78 |
--------------------------------------------------------------------------------
/tests/test_url_checker.py:
--------------------------------------------------------------------------------
1 | """Tests for `django_urlconfchecks` package."""
2 |
3 | import sys
4 |
5 | from django.core import checks
6 | from django.test.utils import override_settings
7 | from django.urls import URLPattern
8 | from django.urls.resolvers import RoutePattern, get_resolver
9 |
10 | from django_urlconfchecks.check import (
11 | _DEFAULT_SILENCED_VIEWS,
12 | check_url_signatures,
13 | get_all_routes,
14 | get_converter_output_type,
15 | )
16 | from tests.dummy_project.urls import converter_urls
17 | from tests.dummy_project.views import year_archive, year_archive_untyped
18 | from tests.utils import error_eql
19 |
20 |
21 | def test_correct_urls():
22 | """Test that no errors are raised when the urlconf is correct.
23 |
24 | Returns:
25 | None
26 | """
27 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.correct_urls'):
28 | errors = check_url_signatures(None)
29 | assert not errors
30 |
31 |
32 | def test_incorrect_urls():
33 | """Test that errors are raised when the urlconf is incorrect.
34 |
35 | Returns:
36 | None
37 | """
38 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.incorrect_urls'):
39 | errors = check_url_signatures(None)
40 | expected_error = checks.Error(
41 | 'View tests.dummy_project.views.year_archive for parameter `year`, annotated '
42 | 'type int does not match expected `str` from urlconf',
43 | hint=None,
44 | obj=URLPattern(
45 | pattern=RoutePattern(route='articles//', is_endpoint=True),
46 | callback=year_archive,
47 | default_args={},
48 | ),
49 | id='urlchecker.E002',
50 | )
51 | assert len(errors) == 1
52 |
53 | assert error_eql(errors[0], expected_error)
54 |
55 |
56 | def test_silencing():
57 | """Test that fine-grained error silencing mechanisms work."""
58 | # Specific view silenced
59 | with override_settings(
60 | ROOT_URLCONF="tests.dummy_project.urls.incorrect_urls",
61 | URLCONFCHECKS_SILENCED_VIEWS={"tests.dummy_project.views.year_archive": "E002"},
62 | ):
63 | assert len(check_url_signatures(None)) == 0
64 |
65 | # Glob pattern
66 | with override_settings(
67 | ROOT_URLCONF="tests.dummy_project.urls.incorrect_urls",
68 | URLCONFCHECKS_SILENCED_VIEWS={"tests.dummy_project.views.*": "E002"},
69 | ):
70 | assert len(check_url_signatures(None)) == 0
71 |
72 | # Non-matching silencer
73 | with override_settings(
74 | ROOT_URLCONF="tests.dummy_project.urls.incorrect_urls",
75 | URLCONFCHECKS_SILENCED_VIEWS={"tests.dummy_project.views.month_archive": "E002"},
76 | ):
77 | assert len(check_url_signatures(None)) > 0
78 |
79 |
80 | def test_default_silencing_for_cbv():
81 | with override_settings(
82 | ROOT_URLCONF="tests.dummy_project.urls.cbv_urls", URLCONFCHECKS_SILENCED_VIEWS=_DEFAULT_SILENCED_VIEWS
83 | ):
84 | assert len(check_url_signatures(None)) == 0
85 |
86 |
87 | def test_all_urls_checked():
88 | """Test that all urls are checked.
89 |
90 | Returns:
91 | None
92 | """
93 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.correct_urls'):
94 | resolver = get_resolver()
95 | routes = get_all_routes(resolver, {})
96 | assert len(list(routes)) == 3
97 |
98 |
99 | def test_child_urls_checked():
100 | """Test that child urls are checked.
101 |
102 | Returns:
103 | None
104 | """
105 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.parent_urls'):
106 | resolver = get_resolver()
107 | routes = get_all_routes(resolver, {})
108 | assert len(list(routes)) == 5
109 |
110 |
111 | def test_admin_urls_ignored():
112 | """Test that admin urls errors are ignored with default settings.
113 |
114 | Returns:
115 | None
116 | """
117 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.admin_urls'):
118 | errors = check_url_signatures(None)
119 | assert len(errors) == 0
120 |
121 |
122 | def test_converters():
123 | assert get_converter_output_type(converter_urls.YearConverterViaSubclass()) == int
124 | assert get_converter_output_type(converter_urls.YearConverterAsFloat()) == float
125 |
126 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.converter_urls'):
127 | errors = check_url_signatures(None)
128 | assert len(errors) == 2
129 | assert error_eql(
130 | errors[0],
131 | checks.Warning(
132 | msg="Don't know output type for converter "
133 | "tests.dummy_project.urls.converter_urls.YearConverterNoTypeHint, can't verify URL signatures.",
134 | hint=None,
135 | obj=converter_urls.YearConverterNoTypeHint,
136 | id='urlchecker.W002.tests.dummy_project.urls.converter_urls.YearConverterNoTypeHint',
137 | ),
138 | )
139 | assert error_eql(
140 | errors[1],
141 | checks.Error(
142 | msg="View tests.dummy_project.views.year_archive for parameter `year`, "
143 | "annotated type int does not match expected `float` from urlconf",
144 | hint=None,
145 | obj=URLPattern(
146 | pattern=RoutePattern(route="articles_yyyy_float//", is_endpoint=True),
147 | callback=year_archive,
148 | default_args={},
149 | ),
150 | id="urlchecker.E002",
151 | ),
152 | )
153 |
154 |
155 | def test_path_kwargs():
156 | """Test that kwargs specified in path(kwargs=...) are included in analysis."""
157 | with override_settings(ROOT_URLCONF='tests.dummy_project.urls.path_kwargs_urls'):
158 | errors = check_url_signatures(None)
159 | assert len(errors) == 4
160 |
161 | assert error_eql(
162 | errors[0],
163 | checks.Error(
164 | msg="View tests.dummy_project.views.year_archive signature contains `year` parameter "
165 | "without default or ULRconf parameter",
166 | hint=None,
167 | obj=URLPattern(
168 | pattern=RoutePattern(route='articles-2021/', is_endpoint=True),
169 | callback=year_archive,
170 | default_args={},
171 | ),
172 | id="urlchecker.E004",
173 | ),
174 | )
175 |
176 | assert error_eql(
177 | errors[1],
178 | checks.Error(
179 | msg="View tests.dummy_project.views.year_archive: for parameter `year`, default argument"
180 | " '2022' in urlconf, type str, does not match annotated type int from view signature",
181 | hint=None,
182 | obj=URLPattern(
183 | pattern=RoutePattern(route='articles-2022/', is_endpoint=True),
184 | callback=year_archive,
185 | default_args={'year': '2022'},
186 | ),
187 | id="urlchecker.E005",
188 | ),
189 | )
190 |
191 | assert error_eql(
192 | errors[2],
193 | checks.Error(
194 | msg="View tests.dummy_project.views.year_archive is being passed additional unexpected "
195 | "parameter `other` from default arguments in urlconf",
196 | hint=None,
197 | obj=URLPattern(
198 | pattern=RoutePattern(route='articles-2023/', is_endpoint=True),
199 | callback=year_archive,
200 | default_args={'year': 2023, 'other': 123},
201 | ),
202 | id="urlchecker.E006",
203 | ),
204 | )
205 | assert error_eql(
206 | errors[3],
207 | checks.Warning(
208 | msg="View tests.dummy_project.views.year_archive_untyped missing type annotation for "
209 | "parameter `year`, can\'t check type.",
210 | hint=None,
211 | obj=URLPattern(
212 | pattern=RoutePattern(route='articles-2024/', is_endpoint=True),
213 | callback=year_archive_untyped,
214 | default_args={'year': 2024},
215 | ),
216 | id="urlchecker.W003",
217 | ),
218 | )
219 |
220 |
221 | @override_settings(ROOT_URLCONF='tests.dummy_project.urls.optional_args')
222 | def test_optional_args():
223 | errors = check_url_signatures(None)
224 | if sys.version_info >= (3, 10):
225 | assert len(errors) > 0
226 | for error in errors:
227 | assert error.obj.pattern._route.startswith('bad-')
228 |
229 |
230 | @override_settings(ROOT_URLCONF='tests.dummy_project.urls.parameterized_generics')
231 | def test_parameterized_generics():
232 | errors = check_url_signatures(None)
233 | # Currently errors is empty, but at least we didn't crash
234 | # or falsely return errors for things that are fine
235 | for error in errors:
236 | assert error.obj.pattern._route.startswith('bad-') # pragma: no cover
237 |
238 |
239 | @override_settings(ROOT_URLCONF='tests.dummy_project.urls.includes')
240 | def test_includes():
241 | # Positive and negative tests that parameters collected by `path` should be
242 | # taken into account by routes that are `include`d
243 | errors = check_url_signatures(None)
244 | assert len(errors) > 0
245 | for error in errors:
246 | assert error.obj.pattern._route.startswith('bad-')
247 |
--------------------------------------------------------------------------------
/tests/utils.py:
--------------------------------------------------------------------------------
1 | """util functions for tests."""
2 |
3 | import typing
4 |
5 | from django.core import checks
6 | from django.urls import URLPattern
7 | from django.urls.resolvers import RoutePattern
8 |
9 |
10 | # noinspection PyProtectedMember
11 | def route_pattern_eql(route_pattern: RoutePattern, expected_route_pattern: RoutePattern) -> bool:
12 | """Compare two RoutePatterns.
13 |
14 | Args:
15 | route_pattern: The RoutePattern to compare.
16 | expected_route_pattern: The expected RoutePattern.
17 |
18 | Returns:
19 | True if the RoutePatterns are equal, False otherwise.
20 | """
21 | return (
22 | route_pattern._route == expected_route_pattern._route
23 | and route_pattern._is_endpoint == expected_route_pattern._is_endpoint
24 | )
25 |
26 |
27 | def url_pattern_eql(urlpatterns: URLPattern, expected_urlpatterns: URLPattern) -> bool:
28 | """Compare two URLPatterns.
29 |
30 | Args:
31 | urlpatterns: The URLPattern to compare.
32 | expected_urlpatterns: The expected URLPattern.
33 |
34 | Returns:
35 | True if the URLPatterns are equal, False otherwise.
36 |
37 | """
38 | return (
39 | urlpatterns.callback == expected_urlpatterns.callback
40 | and urlpatterns.default_args == expected_urlpatterns.default_args
41 | and route_pattern_eql(urlpatterns.pattern, expected_urlpatterns.pattern)
42 | )
43 |
44 |
45 | def error_eql(
46 | error: typing.Union[checks.Error, checks.Warning], expected_error: typing.Union[checks.Error, checks.Warning]
47 | ) -> bool:
48 | """Compare two Error objects.
49 |
50 | Args:
51 | error: The Error to compare.
52 | expected_error: The expected Error.
53 |
54 | Returns:
55 | True if the Error objects are equal, False otherwise.
56 | """
57 | if isinstance(error.obj, URLPattern) and isinstance(expected_error.obj, URLPattern):
58 | obj_equal = url_pattern_eql(error.obj, expected_error.obj)
59 | elif isinstance(error.obj, type) and isinstance(expected_error.obj, type):
60 | obj_equal = error.obj == expected_error.obj
61 | else:
62 | obj_equal = False
63 | return (
64 | error.msg == expected_error.msg
65 | and error.hint == expected_error.hint
66 | and error.id == expected_error.id
67 | and obj_equal
68 | )
69 |
--------------------------------------------------------------------------------