diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml deleted file mode 100644 index 7fdf3a1..0000000 --- a/.github/workflows/linting.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Linting - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - flake8: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - - name: Install dependencies - run: pip install flake8 - - name: Run flake8 - run: flake8 --max-line-length=120 linkcheck - isort: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - - uses: jamescurtin/isort-action@master - with: - configuration: --multi-line=3 --trailing-comma --check-only diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 289608a..0000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Test - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - build: - runs-on: ubuntu-latest - strategy: - max-parallel: 5 - matrix: - python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] - django-version: ['4.2', '5.2', '6.0'] - exclude: - - python-version: '3.10' - django-version: '6.0' - - python-version: '3.11' - django-version: '6.0' - - python-version: '3.13' - django-version: '4.2' - - python-version: '3.14' - django-version: '4.2' - - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - python -m pip install --upgrade django~=${{ matrix.django-version }}.0 - python -m pip install --upgrade requests - python -m pip install --upgrade requests_mock - - - name: Run tests - run: python runtests.py diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 61d9422..0000000 --- a/.gitignore +++ /dev/null @@ -1,58 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] - -# C extensions -*.so - -# Distribution / packaging -.Python -.venv/ -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml deleted file mode 100644 index 870722b..0000000 --- a/.pre-commit-config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -repos: - - repo: https://github.com/pycqa/flake8 - rev: 6.1.0 - hooks: - - id: flake8 - args: [--max-line-length=120] - - repo: https://github.com/PyCQA/isort - rev: 5.12.0 - hooks: - - id: isort - args: [--multi-line=3, --trailing-comma] diff --git a/CHANGELOG b/CHANGELOG deleted file mode 100644 index 1b24a94..0000000 --- a/CHANGELOG +++ /dev/null @@ -1,227 +0,0 @@ -Unreleased - - * Add support for Django 6.0 - * Add support for Python 3.14 - * Remove support for Python 3.9 - -2.4.0 (2025-09-28) - -* Add index to Link (David Venhoff, #202) -* Add support for Django 5.1 and 5.2 -* Add support for Python 3.13 -* Remove support for Django < 4.2 -* Remove support for Python 3.8 -* Remove `raven_compat` middleware if present -* Updated fallback User Agent string -* Reference object primary key by `pk` instead of `id` (Ben Stockermans) -* More robust check for unsaved instances in `instance_pre_save` (Ben Stockermans) -* Add `LINKCHECK_PROXIES` and `LINKCHECK_TRUST_PROXY_SSL` settings to be able to - pass a proxy to requests when cheking links. (Ben Stockermans) -* Add `LINKCHECK_SKIP_TRANSLATIONS` env variable to skip translation compilation - during package building (Ben Stockermans) - -2.3.0 (2023-12-27) - -* Fix encoding of utf-8 domain names (Timo Brembeck, #190) -* Move coverage view to management command (Timo Brembeck, #187) - * Add new management command `linkcheck_suggest_config` - * Delete coverage view -* Improve formatting for `NameResolutionError` (Timo Brembeck, #192) -* Fix internal redirect checker (Timo Ludwig, #180) -* Fix SSL status of unreachable domains (Timo Ludwig, #184) -* Fix URL message for internal server errorrs (Timo Ludwig, #182) -* Add support for Django 4.2 and 5.0 -* Add support for Python 3.12 -* Remove support for Django 4.0 -* Remove support for Python 3.7 - -2.2.1 (2023-04-03) - -* Include the compiled translations in the released package (#177) - -2.2.0 (2023-04-01) - -* Enable internationalization for URL status messages (Timo Ludwig, #125) -* Enable re-checking after rate limit was hit (Timo Ludwig, #153) -* Ignore raw `post_save` signal (Timo Ludwig, #106) -* Retry with fallback user agent on forbidden response (Timo Ludwig, #159) -* Also set `redirect_to` on internal redirects (Timo Ludwig, #163) -* Add new fields to `Url` model: - * `status_code`: The HTTP status code of the initial request - * `redirect_status_code`: The HTTP status code of the final request - * `anchor_status`: The validity of the HTML hash anchor - * `ssl_status` The validity of the SSL certificate - * `error_message` The error message if the request failed -* Add new properties to `Url` model: - * `anchor_message`: The human-readable meaning of the `anchor_status` - * `ssl_message` The human-readable meaning of the `ssl_status` -* Add French translations. - -2.1.0 (2023-02-05) - -* Fix `SSL Error` for missing root certificates (Timo Ludwig, #157) -* Fix `NotImplementedError`/`AssertionError` when checking - video links with hash anchors (Timo Ludwig, #150) -* Skip checking of hash anchors for non-html files -* Avoid decorating the `report` view with `csrf_exempt` (#155) -* recheck/ignore/unignore requests were using an obsolete `request.is_ajax` call - (#147) - -2.0.0 (2022-12-17) - -* Add German translations for filebrowser integration -* Fix django-filebrowser integration (Timo Ludwig, #144) -* Use `django.db.models.BigAutoField` as default auto field - (Timo Ludwig, #137) -* Add German translations for the templates -* Fix `type` property for internal URLs (Timo Ludwig, #141) -* Fix incorrect message when redirect has broken anchor - (Timo Ludwig, #128) -* Breaking change: Treat broken hash anchors as valid - unless `LINKCHECK_TOLERATE_BROKEN_ANCHOR` is manually - set to `False` (Timo Ludwig, #98) -* Remove unused field `still_exists` from `Url` model -* Delete outdated `Url` and `Link` objects when - running `findlinks` command (Timo Ludwig, #101) -* Avoid crash when unexpected error in signal listener occurs - (Sven Seeberg, #117) -* Ignore Urls longer than `MAX_URL_LENGTH` in signal listeners - (Timo Ludwig, #115) -* Verify SSL certificates (Timo Ludwig, #118) -* Added support for Python 3.10/3.11 and Django 4.1. -* Dropped support for Python 3.6 and Django < 3.2. - -1.9.1 (2022-03-23) - -* Added `Linklist.filter_callable` optional hook to allow for more - flexible link list filtering (Giuliano Mele). - -1.9 (2021-12-23) - -* Added support for Django 3.2 and 4.0 and removed support for Django < 2.2. -* Ignore raw `pre_save` signal (Timo Ludwig, #106). - -1.8.1 (2021-04-01) - -* The 1.8 release contained unwanted temporary stuff and was - therefore a broken release. Many thanks to Stefan Borer for - noticing that. - -1.8 (2021-02-25) - -* Added explicit `listeners.register_listeners` and - `listeners.unregister_listeners` functions. -* Added `listeners.enable_listeners` and `listeners.disable_listeners` context - managers. -* Avoid crash when looking for anchors in response content. -* Avoid possible failures when checking internal links depending on - ALLOWED_HOSTS setting. -* Confirmed compatibility with Django 3.1. -* Dropped support for Python 3.4. - -1.7 (2020-01-13) - -* Dropped support for Python 2 and Django < 1.11. -* Added support for Django 3.0. -* Made more usage of the requests library. - -1.6 (2019-03-20) - -* Use requests library when getting 'certificate verify failed' errors. -* Fixed compatibility issues with newer versions of Django. -* Fixed pip installation issues with encoding errors (#87). - -1.5 (2017-09-16) - -* Added support for `tel:` links. -* For redirecting links, linkcheck now reports the status of the redirect - target (#78). -* Dropped South migrations. -* 'Url.redirect_to' was migrated to a TextField to not limit its length (#75). -* Fixed handling of the '--limit' argument of the 'checklinks' command (#73). -* Fixed the task queue of links to check (#69). - -1.4 (2017-01-13) - -* Dropped support for Django 1.6 and Django 1.7, the minimal Python version is - now Python 2.7. Django 1.10 is also supported. -* Listeners registration and post_delete signal are now happening in the app - config ready() method. This means that the process can be customized by - having custom AppConfig classes and referring to those classes in the - INSTALLED_APPS setting. -* A new DISABLE_LISTENERS setting has been added to ease deactivation of - listeners registration. -* A task queue is now used to process link checking, so as to prevent exhaustion - of available threads during massive updates. - -1.3 (2016-06-05) - -* Django 1.9 compatibility added. -* When checking internal links, redirects are not followed any longer. -* Added support for the django-admin-tools dashboard, if present. -* Fixed a bug where internal links were skipped based on the external interval - setting. -* Handle situations where content_type.model_class() returns None. -* Allow extra field types to be added via settings. (Used for coverage view only). -* Improve coverage suggested configs - include 'ignore_empty' settings plus a - raw code view via /linkcheck/coverage?config=1. -* Fix - correctly handle tags that are inside tags. -* Fix - don't run pre_save if it's a new instance. - -1.2 (2015-11-13) - -* Added migration folders (missing in the 1.1 package). Also added support for - South migrations (compatibility). -* When a link produces a 301 Moved Permanently redirection, the redirect target - is stored in Url.redirect_to and displayed in the link report. -* Better support for URLs containing non-ASCII characters. - -1.1 (2015-06-03) - -* Minimal software requirements are now Python 2.6 / Django 1.6 (and South 1.0 if - you still use Django 1.6). -* Python 3 is supported. -* Django 1.7 / 1.8 compatibility added. -* notifications.py is now based on django-admin-blocks. -* Linklist classes now support an ignore_empty list to ignore empty URLField values. - -1.0 - -Changes: - -Bug fixes since 0.6 Please see commit log here: https://github.com/andybak/django-linkcheck/commits/master - -0.6.0 - -Changes: - -* Support ignoring (and unignoring) external broken links via buttons in the linkcheck report -* 'Recheck' button in the linkcheck report -* External links with anchors were being reported as broken because we switched to a HEAD request -* One particular url caused a crash in urllib2 when doing a HEAD request. Implemented a workaround: catch the exception and run a normal GET -* Inconsistant use of seconds in some places and minutes in others. Switch to minutes for all parameters. -* Clean up CSS -* Use normal links for navigating between report types instead of javascript+radio buttons -* Removed some unused javascript -* Fixed some issues with anchor links -* Broken link notification count was counting urls rather than links -* Mark length of url field configurable for those not cursed with MySQl -* Remove the pointless disinguishing images/documents/other in Url.type -* Document settings properly -* Remove unused pagination tag from template and thus dependency on django-pagination -* All tests now pass ( because I commented out the one that didn't :-P ) - -0.5.0 - -Start this changelog -Added some more comments throughout -Fixed dependency on django-filebrowser by wrapping it in an exception check -Handle get_absolute_url returning None -Use HEAD requests for checking external URLs -Handle HREF="#" correctly -Cleaner display of hashtag links in reports -Handle 'Bad Status Line' responses from remote servers. -Don't spawn a thread if running from tests as this prevents the new thread from seeing the same database transaction as the parent thread -Fix some tests from prior to the big refactor. nb Tests are still incomplete and many are broken :( -document filebrowser dependency - diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 839f8a1..0000000 --- a/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2009-2010, Andy Baker and contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the author nor the names of other - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index b979465..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,7 +0,0 @@ -include LICENSE -include CHANGELOG -include README.rst -include linkcheck/locale/*/LC_MESSAGES/django.mo -exclude linkcheck/locale/*/LC_MESSAGES/django.po -recursive-include linkcheck/templates/linkcheck * -recursive-include linkcheck/tests/media * diff --git a/README.rst b/README.rst deleted file mode 100644 index 4978fe2..0000000 --- a/README.rst +++ /dev/null @@ -1,319 +0,0 @@ - -django-linkcheck -=================== - -.. image:: https://github.com/DjangoAdminHackers/django-linkcheck/workflows/Test/badge.svg - :target: https://github.com/DjangoAdminHackers/django-linkcheck/actions - :alt: GitHub Actions - -.. image:: https://img.shields.io/pypi/v/django-linkcheck.svg - :alt: PyPI version - :target: https://pypi.org/project/django-linkcheck/ - -A fairly flexible app that will analyze and report on links in any model that -you register with it. - -.. image:: https://github.com/DjangoAdminHackers/django-linkcheck/raw/master/linkcheck.jpg - -Links can be bare (urls or image and file fields) or -embedded in HTML (linkcheck handles the parsing). It's fairly easy to override -methods of the Linkcheck object should you need to do anything more -complicated (like generate URLs from slug fields etc). - -You should run its management command via cron or similar to check external -links regularly to see if their status changes. All links are checked -automatically when objects are saved. This is handled by signals. - -Minimal requirements --------------------- - -django-linkcheck requires Python 3.10 and Django 4.2. - -Basic usage ------------ - -#. Install app to somewhere on your Python path (e.g. ``pip install - django-linkcheck``). If you do not need multilingual support, you can skip - the compilation of the translation files with an environment variable, e.g. - (``LINKCHECK_SKIP_TRANSLATIONS=true pip install django-linkcheck``). - -#. Add ``'linkcheck'`` to your ``settings.INSTALLED_APPS``. - -#. Add a file named ``linklists.py`` to every app (see an example in ``examples/linklists.py``) that either: - - #) has models that contain content (e.g. url/image fields, chunks of markup - or anything that gets transformed into a IMG or HREF when displayed - #) can be the target of a link - i.e. is addressed by a url - in this case - make sure it has an instance method named 'get_absolute_url' - - *Hint:* You can create a sample config for your model with:: - - manage.py linkcheck_suggest_config --model sampleapp.SampleModel > sampleapp/linklists.py - -#. Run ``./manage.py migrate``. - -#. Add to your root url config:: - - path('admin/linkcheck/', include('linkcheck.urls')) - -#. View ``/admin/linkcheck/`` from your browser. - -We are aware that this documentation is on the brief side of things so any -suggestions for elaboration or clarification would be gratefully accepted. - -Linklist classes ----------------- - -The following class attributes can be added to your ``Linklist`` subclasses to -customize the extracted links: - - ``object_filter``: a dictionary which will be passed as a filter argument to - the ``filter`` applied to the default queryset of the target class. This - allows you to filter the objects from which the links will be extracted. - (example: ``{'active': True}``) - - ``object_exclude``: a dictionary which will be passed as a filter argument to - the ``exclude`` applied to the default queryset of the target class. As with - ``object_filter``, this allows you to exclude objects from which the links - will be extracted. - - ``html_fields``: a list of field names which will be searched for links. - - ``url_fields``: a list of ``URLField`` field names whose content will be - considered as links. If the field content is empty and the field name is - in ``ignore_empty``, the content is ignored. - - ``ignore_empty``: a list of fields from ``url_fields``. See the explanation - above. (new in django-linkcheck 1.1) - - ``image_fields``: a list of ``ImageField`` field names whose content will be - considered as links. Empty ``ImageField`` content is always ignored. - - ``filter_callable``: a callable which allows to pass a function as filter - for your linklist class. It allows to apply more advanced filter operations. - This function must be a class method and it should be passed the objects query - set and return the filtered objects. - Example usage in your linklists.py - only check latest versions:: - - @classmethod - def filter_callable(cls, objects): - latest = Model.objects.filter(id=OuterRef('id')).order_by('-version') - return objects.filter(version=Subquery(latest.values('version')[:1])) - -Management commands -------------------- - -findlinks -~~~~~~~~~ - -This command goes through all registered fields and records the URLs it finds. -This command does not validate anything. Typically run just after installing -and configuring django-linkcheck. - -checklinks -~~~~~~~~~~ - -For each recorded URL, check and report the validity of the URL. All internal -links are checked, but only external links that have not been checked during -the last ``LINKCHECK_EXTERNAL_RECHECK_INTERVAL`` minutes are checked. This -interval can be adapted per-invocation by using the ``--externalinterval`` -(``-e``) command option (in minutes). - -You can also limit the maximum number of links to be checked by passing a number -to the ``--limit`` (``--l``) command option. - -linkcheck_suggest_config -~~~~~~~~~~~~~~~~~~~~~~~~ - -This command goes through all models and checks whether they contain fields that -can potentially be checked by linkcheck. -If they are not yet registered, a sample config is suggested. - -You can also pass the option ``--model`` to generate a sample config for the given model. - -Settings --------- - -LINKCHECK_DISABLE_LISTENERS -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A setting to totally disable linkcheck, typically when running tests. See also -the context managers below. - -LINKCHECK_EXTERNAL_RECHECK_INTERVAL -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: 10080 (1 week in minutes) - -Will not recheck any external link that has been checked more recently than this value. - -LINKCHECK_EXTERNAL_REGEX_STRING -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: r'^https?://' - -A string applied as a regex to a URL to determine whether it's internal or external. - -LINKCHECK_MEDIA_PREFIX -~~~~~~~~~~~~~~~~~~~~~~ - -Default: '/media/' - -Currently linkcheck tests whether links to internal static media are correct by wrangling the URL to be a local filesystem path. - -It strips MEDIA_PREFIX off the interal link and concatenates the result onto settings.MEDIA_ROOT and tests that using os.path.exists - -This 'works for me' but it is probably going to break for other people's setups. Patches welcome. - -LINKCHECK_RESULTS_PER_PAGE -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Controls pagination. - -Pagination is slightly peculiar at the moment due to the way links are grouped by object. - - -LINKCHECK_MAX_URL_LENGTH -~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: 255 - -The length of the URL field. Defaults to 255 for compatibility with MySQL (see http://docs.djangoproject.com/en/dev/ref/databases/#notes-on-specific-fields ) - - -LINKCHECK_CONNECTION_ATTEMPT_TIMEOUT -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: 10 - -The timeout in seconds for each connection attempts. Sometimes it is useful to limit check time per connection in order to hold at bay the total check time. - - -SITE_DOMAIN and LINKCHECK_SITE_DOMAINS -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Linkcheck tests external and internal using differently. Internal links use the Django test client whereas external links are tested using urllib2. - -Testing internal links this as if they were external can cause errors in some circumstances so Linkcheck needs to know which external urls are to be treated as internal. - -Linkcheck looks for either of the settings above. It only uses SITE_DOMAIN if LINKCHECK_SITE_DOMAINS isn't present - - -SITE_DOMAIN = "mysite.com" - -would tell linkchecker to treat the following as internal links: - -mysite.com -www.mysite.com -test.mysite.com - -If you instead set LINKCHECK_SITE_DOMAINS to be a list or tuple then you can explicitly list the domains that should be treated as internal. - - -LINKCHECK_TOLERATE_BROKEN_ANCHOR -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: ``True`` - -Whether links with broken hash anchors should be marked as valid. -Disable this if you want that links to anchors which are not contained in the link target's HTML source are marked as invalid. - - -LINKCHECK_PROXIES -~~~~~~~~~~~~~~~~~ - -Default: `{}` - -Allows you to make your `check_external` requests via a proxy. Expects a dictionary, e.g.: - -.. code-block:: python3 - - LINKCHECK_PROXIES = { - "http": "http://.../", - "https": "https://.../", - } - - -LINKCHECK_TRUST_PROXY_SSL -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Default: `False` - -If you are making your requests via a proxy, you can use this setting to turn off SSL verification for the proxy. - - -django-filebrowser integration ------------------------------- - -If django-filebrowser is present on your path then linkcheck will listen to the post-upload, delete and rename signals and update itself according - - -Contributing ------------- - -You can install all requirements of the development setup with the extra ``dev``: - -.. code-block:: bash - - $ python3 -m venv .venv - $ source .venv/bin/activate - $ pip install -e .[dev] - $ django-admin compilemessages --ignore=.venv # Optionally compile translation file - -If you want to make use of the flake8 and isort pre-commit hooks, enable them with: - -.. code-block:: bash - - $ pre-commit install - -Running tests -~~~~~~~~~~~~~ - -Tests can be run standalone by using the ``runtests.py`` script in linkcheck root: - -.. code-block:: bash - - $ python runtests.py - -If you want to run linkcheck tests in the context of your project, you should include ``'linkcheck.tests.sampleapp'`` in your ``INSTALLED_APPS`` setting. - -Linkcheck gives you two context managers to enable or disable listeners in your -own tests. For example: - -.. code-block:: python3 - - def test_something_without_listeners(self): - with listeners.disable_listeners(): - # Create/update here without linkcheck intervening. - -In the case you defined the ``LINKCHECK_DISABLE_LISTENERS`` setting, you can -temporarily enable it by: - -.. code-block:: python3 - - def test_something_with_listeners(self): - with listeners.enable_listeners(): - # Create/update here and see linkcheck activated. - -Translations -~~~~~~~~~~~~ - -At the moment this app is available in English, German, and French. -If you want to contribute translations for ``LOCALE``, run: - -.. code-block:: bash - - django-admin makemessages --locale LOCALE - -and edit the corresponding file in ``linkcheck/locale/LOCALE/LC_MESSAGES/django.po``. - -Create new release -~~~~~~~~~~~~~~~~~~ - -1. Bump version in `pyproject.toml <./pyproject.toml>`_ -2. Update `CHANGELOG <./CHANGELOG>`_ -3. Create release commit: ``git commit --message "Release vX.Y.Z"`` -4. Create git tag: ``git tag -a "X.Y.Z" -m "Release vX.Y.Z"`` -5. Push the commit and tag to the repository: ``git push && git push --tags`` -6. Build the source distribution: ``python -m build`` -7. Publish the package to PyPI: ``twine upload dist/django-linkcheck-X.Y.Z*`` diff --git a/examples/linkcheck.jpg b/examples/linkcheck.jpg deleted file mode 100644 index 2172184..0000000 Binary files a/examples/linkcheck.jpg and /dev/null differ diff --git a/examples/linklists.py b/examples/linklists.py deleted file mode 100644 index 1c0391e..0000000 --- a/examples/linklists.py +++ /dev/null @@ -1,13 +0,0 @@ -from cms.models import Page - -from linkcheck import Linklist - - -class PageLinklist(Linklist): - - model = Page - object_filter = {'active': True} - html_fields = ['content', 'extra_content'] - - -linklists = {'Pages': PageLinklist} diff --git a/index.html b/index.html new file mode 100644 index 0000000..f32976b --- /dev/null +++ b/index.html @@ -0,0 +1,119 @@ + + + +
+ + +
+
+ http://cms.andybak.webfactional.com/media/linkcheck.jpg + +A fairly flexible app that will analyze and report on links in any model that you register with it. Links can be bare (urls or image and file fields) or embedded in HTML (linkcheck handles the parsing). It's fairly easy to override methods of the Linkcheck object should you need to do anything more complicated (like generate URLs from slug fields etc). + +The current version does all the finding and checking of links as a bulk job you can run from cron but it's fairly easy to hook up signals to your model's save and delete to keep the data updated once an initial sweep has been done. + +Another future enhancement would be the ability to automatically fix links when the related object is changed. + +This is working code but it currently comes with a few caveats: + + # It's been extracted from my homespun CMS and in some places that still shows. + # No tests :( + # Few comments or docstrings :( + # The documentation was rather a rush job :( + +Yes I'm a bad person. I'm putting this out there because doing so might inspire someone - hopefully me - to fix the above issues.
Jquery (my base admin template already links to it. If your's doesn't then add it to base_linkcheck.html +
+1. Install app to somewhere on your Python path +2. Edit examples/linkcheck_config.py to include references to all your models that might contain links. +3. Add something along the lines of linklists.py to every app you referenced in linkcheck_config.py +4. Import linkcheck_config.py from your root urls. +5. Syncdb +6. Run findlinks management command or the utils.find() +7. Run checklinks management command or the utils.check() +8. Add (r'^admin/linkcheck/', include('linkcheck.urls')) to your root url config +9. View /admin/linkcheck/ from your browser +
+New BSD License
+andybak (andy@andybak.net)
Andy Baker (andy@andybak.net)
+ You can download this project in either + zip or + tar formats. +
+You can also clone the project with Git + by running: +
$ git clone git://github.com/andybak/django-linkcheck+ + + + +
.
- """
- html_codes = (("'", "'"), ('"', """), (">", ">"), ("<", "<"), ("&", "&"))
- for code in html_codes:
- s = s.replace(code[1], code[0])
- return s
-
-
-STATUS_CODE_CHOICES = [(s.value, f"{s.value} {s.phrase}") for s in HTTPStatus]
-DEFAULT_USER_AGENT = f"{settings.SITE_DOMAIN} Linkchecker"
-FALLBACK_USER_AGENT = (
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
-)
-
-
-class Url(models.Model):
- """
- Represents a distinct URL found somewhere in the models registered with linkcheck
- A single Url can have multiple Links associated with it.
- """
-
- # See http://www.boutell.com/newfaq/misc/urllength.html
- url = models.CharField(max_length=MAX_URL_LENGTH, unique=True)
- last_checked = models.DateTimeField(blank=True, null=True)
- anchor_status = models.BooleanField(null=True)
- ssl_status = models.BooleanField(null=True)
- status = models.BooleanField(null=True)
- status_code = models.IntegerField(choices=STATUS_CODE_CHOICES, null=True)
- redirect_status_code = models.IntegerField(choices=STATUS_CODE_CHOICES, null=True)
- message = models.CharField(max_length=1024, blank=True, null=True)
- error_message = models.CharField(max_length=1024, default="", blank=True)
- redirect_to = models.TextField(blank=True)
-
- @property
- def redirect_ok(self):
- return self.redirect_status_code < 300 if self.redirect_status_code else None
-
- @property
- def type(self):
- if self.external:
- return "external"
- if self.url.startswith("mailto:"):
- return "mailto"
- if self.url.startswith("tel:"):
- return "phone"
- elif self.internal_url == "":
- return "empty"
- elif self.internal_url.startswith("#"):
- return "anchor"
- elif self.internal_url.startswith(MEDIA_PREFIX):
- return "file"
- elif self.internal_url.startswith("/"):
- return "internal"
- else:
- return "invalid"
-
- @property
- def has_anchor(self):
- return "#" in self.url
-
- @property
- def anchor(self):
- return self.url.split("#")[1] if self.has_anchor else None
-
- @property
- def anchor_message(self):
- if not self.has_anchor or not self.last_checked:
- return ""
- if self.anchor == "":
- return _("Working empty anchor")
- if self.anchor_status is None:
- return _("Anchor could not be checked")
- elif self.anchor_status is False:
- return _("Broken anchor")
- return _("Working anchor")
-
- @property
- def ssl_message(self):
- if self.internal:
- return ""
- if self.external_url.startswith("http://"):
- return _("Insecure link")
- if self.ssl_status is None:
- return _("SSL certificate could not be checked")
- elif self.ssl_status is False:
- return _("Broken SSL certificate")
- return _("Valid SSL certificate")
-
- @property
- def get_message(self):
- if not self.last_checked and self.status is None:
- return _("URL Not Yet Checked")
- elif self.type == "empty":
- return _("Empty link")
- elif self.type == "invalid":
- return _("Invalid URL")
- elif self.type == "mailto":
- return "{} ({})".format(_("Email link"), _("not automatically checked"))
- elif self.type == "phone":
- return "{} ({})".format(_("Phone number link"), _("not automatically checked"))
- elif self.type == "anchor":
- return "{} ({})".format(_("Anchor link"), _("not automatically checked"))
- elif self.type == "file":
- return _("Working file link") if self.status else _("Missing file")
- elif not self.status_code:
- return self.error_message
- elif self.status_code < 300:
- return _("Working external link") if self.external else _("Working internal link")
- elif self.status_code < 400:
- permanent = self.status_code in [HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.PERMANENT_REDIRECT]
- if self.redirect_ok:
- return _("Working permanent redirect") if permanent else _("Working temporary redirect")
- else:
- return _("Broken permanent redirect") if permanent else _("Broken temporary redirect")
- return _("Broken external link") if self.external else _("Broken internal link")
-
- @property
- def colour(self):
- if not self.last_checked:
- return "blue"
- elif self.status is True:
- return "green"
- else:
- return "red"
-
- def __str__(self):
- return self.url
-
- def __repr__(self):
- return f" No results{% translate "Link Checker" %}
-
-
- {% endfor %}
- {% else %}
-
- {{content_type.content_type|get_verbose_name_plural}}
- {% for object in content_type.object_list %}
- {{report_type}} in '{{object.object}}'
- {% blocktrans with content_type_name=content_type.content_type.name %}View {{ content_type_name }}{% endblocktrans %}
- {% if object.admin_url %}{% blocktrans with content_type_name=content_type.content_type.name %}Edit {{ content_type_name }}{% endblocktrans %}{% endif %}
-
-
- {% translate "Destination" %}
- {% translate "Linked Text" %}
- {% translate "Field to edit" %}
- {% translate "Status" %}
-
-
- {% for link in object.link_list %}
-
-
- {% if link.url.redirect_to %}
- {{link.display_url}}
- {% if link.text == "empty" %}none{% else %}"{{link.text}}"{% endif %}
- {{link.field}}
-
-
- {% if not link.url.status %}
-
- {% endif %}
-
-
- {% if not link.url.status %}
- {% if link.url.external %}
- {% if not link.ignore %}
-
- {% else %}
-
- {% endif %}
- {% endif %}
- {% endif %}
-
-
- {% endif %}
- {% endfor %}
- {% translate "Redirects to" %}: {{ link.url.redirect_to }} Anchor
")
-
-
-def http_redirect_to_anchor(request):
- return HttpResponseRedirect("/http/anchor/")
-
-
-def static_video(request):
- return HttpResponse(b'', content_type='video/mp4')
-
-
-def static_video_forged_content_type(request):
- return HttpResponse(b': "
- "Failed to resolve 'name-resolution-error.example.com' ([Errno -2] Name or service not known)\"))"
- )
- mocked_url = 'https://name-resolution-error.example.com/'
- mocker.register_uri('HEAD', mocked_url, exc=exc),
- uv = Url(url=mocked_url)
- uv.check_url()
- formatted_message = (
- "Name Resolution Error: Failed to resolve 'name-resolution-error.example.com' "
- "([Errno -2] Name or service not known)"
- )
- self.assertEqual(uv.message, formatted_message)
- self.assertEqual(uv.get_message, formatted_message)
- self.assertEqual(uv.error_message, formatted_message)
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'SSL certificate could not be checked')
- self.assertEqual(uv.get_status_code_display(), None)
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_200_utf8(self):
- uv = Url(url=f"{self.live_server_url}/http/200/r%C3%BCckmeldung/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_200_utf8_not_encoded(self):
- uv = Url(url=f"{self.live_server_url}/http/200/rückmeldung/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- @requests_mock.Mocker()
- def test_external_check_200_utf8_domain(self, mocker):
- mocker.register_uri('HEAD', 'https://xn--utf8-test--z5a0txc.example.com/', reason='OK'),
- uv = Url(url='https://xn--utf8-test--z5a0txc.example.com/')
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, True)
- self.assertEqual(uv.ssl_message, 'Valid SSL certificate')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- @requests_mock.Mocker()
- def test_external_check_200_punycode_domain(self, mocker):
- punycode_domain = 'https://xn--utf8-test--z5a0txc.example.com/'
- mocker.register_uri('HEAD', punycode_domain, reason='OK'),
- uv = Url(url=punycode_domain)
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, True)
- self.assertEqual(uv.ssl_message, 'Valid SSL certificate')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_301(self):
- uv = Url(url=f"{self.live_server_url}/http/301/")
- uv.check_url()
- self.assertEqual(uv.message, '301 Moved Permanently')
- self.assertEqual(uv.get_message, 'Broken permanent redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '301 Moved Permanently')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_301_followed(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect/301/")
- uv.check_url()
- self.assertEqual(uv.message, '301 Moved Permanently')
- self.assertEqual(uv.get_message, 'Working permanent redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '301 Moved Permanently')
- self.assertEqual(uv.get_redirect_status_code_display(), '200 OK')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/200/')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_302_followed(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect/302/")
- uv.check_url()
- self.assertEqual(uv.message, '302 Found')
- self.assertEqual(uv.get_message, 'Working temporary redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '302 Found')
- self.assertEqual(uv.get_redirect_status_code_display(), '200 OK')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/200/')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_404(self):
- uv = Url(url=f"{self.live_server_url}/whatever/")
- uv.check_url()
- self.assertEqual(uv.message, '404 Not Found')
- self.assertEqual(uv.get_message, 'Broken external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '404 Not Found')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_redirect_final_404(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect_to_404/")
- uv.check_url()
- self.assertEqual(uv.message, '404 Not Found')
- self.assertEqual(uv.get_message, 'Broken permanent redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '301 Moved Permanently')
- self.assertEqual(uv.get_redirect_status_code_display(), '404 Not Found')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/404/')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_get_only_405(self):
- # An URL that allows GET but not HEAD, linkcheck should fallback on GET.
- uv = Url(url=f"{self.live_server_url}/http/getonly/405/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_get_only_400(self):
- uv = Url(url=f"{self.live_server_url}/http/getonly/400/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_blocked_user_agent(self):
- uv = Url(url=f"{self.live_server_url}/http/block-user-agent/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_blocked_user_agent_blocked_head(self):
- uv = Url(url=f"{self.live_server_url}/http/block-user-agent/block-head/")
- uv.check_url()
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- @patch(
- 'linkcheck.models.PROXIES',
- {'http': 'http://proxy.example.com:8080/'},
- )
- @requests_mock.Mocker()
- def test_external_proxy_request(self, mocker):
- mocker.register_uri('HEAD', 'http://test.com/', reason='OK'),
- uv = Url(url='http://test.com/')
- self.assertEqual(mocker.called, False)
- uv.check_url()
- self.assertEqual(mocker.called, True)
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.message, '200 OK')
- self.assertEqual(uv.type, 'external')
- last_request = mocker.last_request
- self.assertEqual(last_request.hostname, 'test.com')
- self.assertEqual(last_request.scheme, 'http')
- self.assertEqual(last_request.proxies, {'http': 'http://proxy.example.com:8080/'})
-
- def test_external_check_timedout(self):
- uv = Url(url=f"{self.live_server_url}/timeout/")
- uv.check_url()
- self.assertEqual(uv.message, 'Other Error: The read operation timed out')
- self.assertEqual(uv.get_message, 'The read operation timed out')
- self.assertEqual(uv.error_message, 'The read operation timed out')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), None)
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_external_check_rate_limit(self):
- uv = Url(url=f"{self.live_server_url}/http/429/")
- uv.check_url()
- self.assertEqual(uv.last_checked, None)
- self.assertEqual(uv.message, '429 Too Many Requests')
- self.assertEqual(uv.get_message, 'Broken external link')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.anchor_message, '')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '429 Too Many Requests')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_working_external_anchor(self):
- uv = Url(url=f"{self.live_server_url}/http/anchor/#anchor")
- uv.check_url()
- self.assertEqual(uv.message, "200 OK, working external hash anchor")
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, 'Working anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- @patch("linkcheck.models.TOLERATE_BROKEN_ANCHOR", False)
- def test_broken_external_anchor(self):
- uv = Url(url=f"{self.live_server_url}/http/anchor/#broken-anchor")
- uv.check_url()
- self.assertEqual(uv.message, "200 OK, broken external hash anchor")
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, 'Broken anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_broken_external_anchor_tolerated(self):
- uv = Url(url=f"{self.live_server_url}/http/anchor/#broken-anchor")
- uv.check_url()
- self.assertEqual(uv.message, "200 OK, broken external hash anchor")
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, 'Broken anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_redirect_working_external_anchor(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect_to_anchor/#anchor")
- uv.check_url()
- self.assertEqual(uv.message, "302 Found, working external hash anchor")
- self.assertEqual(uv.get_message, 'Working temporary redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, 'Working anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '302 Found')
- self.assertEqual(uv.get_redirect_status_code_display(), '200 OK')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/anchor/')
- self.assertEqual(uv.type, 'external')
-
- @patch("linkcheck.models.TOLERATE_BROKEN_ANCHOR", False)
- def test_redirect_broken_external_anchor(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect_to_anchor/#broken-anchor")
- uv.check_url()
- self.assertEqual(uv.message, "302 Found, broken external hash anchor")
- self.assertEqual(uv.get_message, 'Working temporary redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, False)
- self.assertEqual(uv.anchor_message, 'Broken anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '302 Found')
- self.assertEqual(uv.get_redirect_status_code_display(), '200 OK')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/anchor/')
- self.assertEqual(uv.type, 'external')
-
- def test_redirect_broken_external_anchor_tolerated(self):
- uv = Url(url=f"{self.live_server_url}/http/redirect_to_anchor/#broken-anchor")
- uv.check_url()
- self.assertEqual(uv.message, "302 Found, broken external hash anchor")
- self.assertEqual(uv.get_message, 'Working temporary redirect')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, 'Broken anchor')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '302 Found')
- self.assertEqual(uv.get_redirect_status_code_display(), '200 OK')
- self.assertEqual(uv.redirect_to, f'{self.live_server_url}/http/anchor/')
- self.assertEqual(uv.type, 'external')
-
- def test_video_with_time_anchor(self):
- uv = Url(url=f"{self.live_server_url}/static-files/video.mp4#t=2.0")
- uv.check_url()
- self.assertEqual(uv.message, "200 OK")
- self.assertEqual(uv.get_message, 'Working external link')
- self.assertEqual(uv.error_message, '')
- self.assertEqual(uv.status, True)
- self.assertEqual(uv.anchor_message, 'Anchor could not be checked')
- self.assertEqual(uv.ssl_status, None)
- self.assertEqual(uv.ssl_message, 'Insecure link')
- self.assertEqual(uv.get_status_code_display(), '200 OK')
- self.assertEqual(uv.get_redirect_status_code_display(), None)
- self.assertEqual(uv.redirect_to, '')
- self.assertEqual(uv.type, 'external')
-
- def test_forged_video_with_time_anchor(self):
- uv = Url(url=f"{self.live_server_url}/static-files/fake-video.mp4#
""")
-
- out = StringIO()
- call_command('checklinks', stdout=out)
- self.assertEqual(
- out.getvalue(),
- "Checking all links that haven't been tested for 10080 minutes.\n"
- "1 internal URLs and 0 external URLs have been checked.\n"
- )
-
- yesterday = datetime.now() - timedelta(days=1)
- Url.objects.all().update(last_checked=yesterday)
- out = StringIO()
- call_command('checklinks', externalinterval=20, stdout=out)
- self.assertEqual(
- out.getvalue(),
- "Checking all links that haven't been tested for 20 minutes.\n"
- "1 internal URLs and 2 external URLs have been checked.\n"
- )
-
- Url.objects.all().update(last_checked=yesterday)
- out = StringIO()
- call_command('checklinks', externalinterval=20, limit=1, stdout=out)
- self.assertEqual(
- out.getvalue(),
- "Checking all links that haven't been tested for 20 minutes.\n"
- "Will run maximum of 1 checks this run.\n"
- "1 internal URLs and 1 external URLs have been checked.\n"
- )
-
-
-class FindingLinksTestCase(TestCase):
- def test_found_links(self):
- self.assertEqual(Url.objects.all().count(), 0)
- Book.objects.create(title='My Title', description="""
- Here's a link: Example,
- and an image:
""")
- self.assertEqual(Url.objects.all().count(), 2)
- self.assertQuerySetEqual(
- Url.objects.all().order_by('url'),
- ["http://www.example.org/", "http://www.example.org/logo.png"],
- transform=lambda obj: obj.url
- )
-
- def test_urls_exceeding_max_length(self):
- self.assertEqual(Url.objects.all().count(), 0)
- with self.assertLogs(logger="linkcheck", level="WARN") as cm:
- Book.objects.create(
- title="My Title",
- description=(
- "Here's a link: Example, and here's a url exceeding "
- f"the max length: "
- ),
- )
- # We skip urls which are too long because we can't store them in the database
- self.assertIn(
- (
- "WARNING:linkcheck.listeners:URL exceeding max length will be skipped: "
- f"http://www.example.org/%7BMAX_URL_LENGTH%20*'X'}"
- ),
- cm.output,
- )
- self.assertEqual(Url.objects.all().count(), 1)
-
- def test_empty_url_field(self):
- """
- Test that URLField empty content is excluded depending on ignore_empty list.
- """
- all_linklists = apps.get_app_config('linkcheck').all_linklists
- all_linklists['Authors'].ignore_empty = ['website']
- try:
- Author.objects.create(name="William Shakespeare")
- Author.objects.create(name="John Smith", website="http://www.example.org/smith")
- self.assertEqual(Url.objects.all().count(), 1)
- finally:
- all_linklists['Authors'].ignore_empty = []
- Author.objects.create(name="Alphonse Daudet")
- # This time, the empty 'website' is extracted
- self.assertEqual(Url.objects.all().count(), 2)
-
- def test_findlinks_command(self):
- # Disable listeners to only check the management command
- with disable_listeners():
- Author.objects.create(name="John Smith", website="https://www.example.org/smith")
- self.assertEqual(
- findlinks(),
- "Updating all links...\n"
- "Urls: 1 created, 0 deleted, 0 unchanged\n"
- "Links: 1 created, 0 deleted, 0 unchanged\n"
- )
- Author.objects.create(name="John Doe", website="https://www.example.org/doe")
- Book.objects.create(
- title='My Title',
- description="My fav author: John Doe"
- )
- self.assertEqual(
- findlinks(),
- "Updating all links...\n"
- "Urls: 1 created, 0 deleted, 1 unchanged\n"
- "Links: 2 created, 0 deleted, 1 unchanged\n"
- )
- Author.objects.get(name="John Doe").delete()
- self.assertEqual(
- findlinks(),
- "Updating all links...\n"
- "Urls: 0 created, 0 deleted, 2 unchanged\n"
- "Links: 0 created, 1 deleted, 2 unchanged\n"
- )
- Book.objects.first().delete()
- self.assertEqual(
- findlinks(),
- "Updating all links...\n"
- "Urls: 0 created, 1 deleted, 1 unchanged\n"
- "Links: 0 created, 1 deleted, 1 unchanged\n"
- )
-
-
-class ManagementCommandTestCase(TestCase):
-
- def test_linkcheck_suggest_config(self):
- """
- Test that the config of uncovered models is correctly suggested
- """
- out, err = get_command_output('linkcheck_suggest_config')
- self.assertEqual(
- out,
- 'All covered models:\n'
- '\x1b[36msampleapp.Book\x1b[0m, \x1b[36msampleapp.Page\x1b[0m\n\n'
- 'Suggested config for model sampleapp.UncoveredModel:\n'
- '\x1b[36mfrom sampleapp.models import UncoveredModel\n\n'
- 'class UncoveredModelLinklist(Linklist):\n'
- ' model = UncoveredModel\n\n'
- 'linklists = {\n'
- ' "UncoveredModel": UncoveredModelLinklist,\n'
- '}\n\x1b[0m\n'
- )
- self.assertEqual(err, '')
-
- def test_linkcheck_suggest_config_model(self):
- """
- Test that the config of given model is correctly printed
- """
- out, err = get_command_output('linkcheck_suggest_config', '--model', 'sampleapp.Author')
- self.assertEqual(
- out,
- 'from sampleapp.models import Author\n\n'
- 'class AuthorLinklist(Linklist):\n'
- ' model = Author\n\n'
- 'linklists = {\n'
- ' "Author": AuthorLinklist,\n'
- '}\n'
- )
- self.assertEqual(err, '')
-
- def test_linkcheck_suggest_config_model_non_existing(self):
- """
- Test that the command raises an error when the model does not exist
- """
- with self.assertRaises(CommandError) as cm:
- get_command_output('linkcheck_suggest_config', '--model', 'non-existing')
- self.assertEqual(str(cm.exception), 'Model "non-existing" does not exist.')
-
-
-class ObjectsUpdateTestCase(TestCase):
- def test_update_object(self):
- """
- Test that updating a broken URL in an object also updates the
- corresponding Link, and don't leak the old URL.
- """
- bad_url = "/broken/internal/link"
- good_url = "/public/"
- author = Author.objects.create(name="John Smith", website=bad_url)
- self.assertEqual(
- Link.objects.filter(ignore=False, url__status=False).count(),
- 1
- )
- self.assertEqual(
- Link.objects.filter(ignore=False, url__status=True).count(),
- 0
- )
- self.assertEqual(Url.objects.all().count(), 1)
- self.assertEqual(Url.objects.all()[0].url, bad_url)
- # Fix the link
- author.website = good_url
- author.save()
- self.assertEqual(
- Link.objects.filter(ignore=False, url__status=False).count(),
- 0
- )
- self.assertEqual(
- Link.objects.filter(ignore=False, url__status=True).count(),
- 1
- )
- self.assertEqual(Url.objects.all().count(), 1)
- self.assertEqual(Url.objects.all()[0].url, good_url)
-
-
-class RegisteringTests(TestCase):
- good_url = "/public/"
-
- def test_unregister(self):
- self.assertEqual(Link.objects.count(), 0)
- unregister_listeners()
- Author.objects.create(name="John Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 0)
- register_listeners()
- Author.objects.create(name="Jill Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 1)
-
- def test_disable_listeners(self):
- self.assertEqual(Link.objects.count(), 0)
- with disable_listeners():
- Author.objects.create(name="John Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 0)
- Author.objects.create(name="Jill Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 1)
-
- def test_enable_listeners(self):
- self.assertEqual(Link.objects.count(), 0)
- unregister_listeners()
- with enable_listeners():
- Author.objects.create(name="John Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 1)
- Author.objects.create(name="Jill Smith", website=self.good_url)
- self.assertEqual(Link.objects.count(), 1)
- register_listeners()
-
-
-class QueueTests(TestCase):
- def test_queue_handling_continue_on_task_crash(self):
- assert tasks_queue.empty() is True
-
- def raising():
- raise RuntimeError("Failing task")
-
- def passing():
- pass
-
- for func in (raising, passing):
- tasks_queue.put({
- 'target': func,
- 'args': (),
- 'kwargs': {},
- })
- with self.assertLogs() as cm:
- linkcheck_worker(block=False)
- self.assertEqual(
- cm.output[0].split('\n')[0],
- 'ERROR:linkcheck.listeners:RuntimeError while running raising with '
- 'args=() and kwargs={}: Failing task'
- )
-
-
-class ViewTestCase(TestCase):
- def setUp(self):
- self.user = User.objects.create_superuser('admin', 'admin@example.org', 'password')
-
- def test_display_url(http://github.com/self):
- Book.objects.create(
- title='My Title', description="Here's a link: Example"
- )
- Author.objects.create(name="John Smith", website="http://www.example.org/#john")
- self.assertEqual(Link.objects.count(), 2)
- self.assertEqual(
- set([link.display_url for link in Link.objects.all()]),
- set(["http://www.example.org/", "http://www.example.org/#john"]),
- )
-
- def test_report_view(self):
- self.client.force_login(self.user)
- response = self.client.get(reverse('linkcheck_report'))
- self.assertContains(response, "
Link Checker
")
-
- def test_report_ignore_unignore(self):
- Author.objects.create(name="John Smith", website="http://www.example.org/john")
- self.client.force_login(self.user)
- link = Link.objects.first()
- self.assertFalse(link.ignore)
- response = self.client.post(
- reverse('linkcheck_report') + f"?ignore={link.pk}",
- HTTP_X_REQUESTED_WITH='XMLHttpRequest'
- )
- self.assertEqual(response.json(), {'link': link.pk})
- link.refresh_from_db()
- self.assertTrue(link.ignore)
- response = self.client.post(
- reverse('linkcheck_report') + f"?unignore={link.pk}",
- HTTP_X_REQUESTED_WITH='XMLHttpRequest'
- )
- self.assertEqual(response.json(), {'link': link.pk})
- link.refresh_from_db()
- self.assertFalse(link.ignore)
-
- def test_report_recheck(self):
- Author.objects.create(name="John Smith", website="http://www.example.org/john")
- self.client.force_login(self.user)
- link = Link.objects.first()
- response = self.client.post(
- reverse('linkcheck_report') + f"?recheck={link.pk}",
- HTTP_X_REQUESTED_WITH='XMLHttpRequest'
- )
- self.assertEqual(response.json(), {
- 'colour': 'red',
- 'links': [link.pk],
- 'message': '404 Not Found',
- })
-
-
-class GetJqueryMinJsTestCase(TestCase):
- def test(self):
- self.assertEqual(
- 'admin/js/vendor/jquery/jquery.min.js', get_jquery_min_js()
- )
-
-
-class FixtureTestCase(TestCase):
- fixtures = ['linkcheck/tests/sampleapp/fixture.json']
-
- def test_fixture(self):
- self.assertEqual(Book.objects.count(), 1)
- self.assertEqual(Page.objects.count(), 1)
-
-
-class FilterCallableTestCase(TestCase):
- def test_filter_callable(self):
- all_linklists = apps.get_app_config('linkcheck').all_linklists
- all_linklists['Journals'].html_fields = []
- Journal.objects.create(title='My Title', description="""
- My description Example""")
- Journal.objects.create(title='My Title', version=1, description="""
- My new description Example""")
- all_linklists['Journals'].html_fields = ['description']
- # assert there are two versions of the same journal
- self.assertEqual(Journal.objects.count(), 2)
- # assert command just finds the latest version of same journals
- self.assertEqual(
- findlinks(),
- "Updating all links...\n"
- "Urls: 1 created, 0 deleted, 0 unchanged\n"
- "Links: 1 created, 0 deleted, 0 unchanged\n"
- )
-
-
-def get_command_output(command, *args, **kwargs):
- """
- Helper function for running a management command and checking its output
- """
- out = StringIO()
- err = StringIO()
- call_command(command, *args, stdout=out, stderr=err, **kwargs)
- return out.getvalue(), err.getvalue()
-
-
-def findlinks():
- """
- Helper function for running the findlinks command and checking its output
- """
- return get_command_output('findlinks')[0]
diff --git a/linkcheck/tests/urls.py b/linkcheck/tests/urls.py
deleted file mode 100644
index 408675f..0000000
--- a/linkcheck/tests/urls.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from django import http
-from django.contrib import admin
-from django.urls import include, path
-from django.views.generic import RedirectView
-
-from linkcheck.tests.sampleapp import views
-
-
-def handler404(*args, **kwargs):
- return http.HttpResponseNotFound("")
-
-
-urlpatterns = [
- path('admin/linkcheck/', include('linkcheck.urls')),
- path('admin/', admin.site.urls),
- path('public/', views.http_response, {'code': '200'}),
- path('http/
"
- "View/fix broken links".format(
- broken_links,
- "s" if broken_links > 1 else "",
- reverse('linkcheck_report'),
- )
- )
- else:
- return ''
-
-
-def is_ajax(request):
- return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
diff --git a/pyproject.toml b/pyproject.toml
deleted file mode 100644
index 4206c9c..0000000
--- a/pyproject.toml
+++ /dev/null
@@ -1,63 +0,0 @@
-[build-system]
-requires = ["setuptools>=61.2"]
-build-backend = "build_meta"
-backend-path = ["linkcheck"]
-
-[project]
-name = "django-linkcheck"
-version = "2.4.0"
-authors = [
- {name = "Andy Baker", email = "andy@andybak.net"},
- {name = "Fruits Chen", email = "fruitschen@gmail.com"},
- {name = "Tim Graves", email = "gravesit@gmail.com"},
- {name = "Jannis Leidel", email = "jannis@leidel.info"},
- {name = "Claude Paroz", email = "claude@2xlibre.net"},
- {name = "Timo Brembeck", email = "opensource@timo.brembeck.email"}
-]
-description = "A Django app that will analyze and report on links in any model that you register with it."
-readme = "README.rst"
-classifiers = [
- "Development Status :: 5 - Production/Stable",
- "Environment :: Web Environment",
- "Intended Audience :: Developers",
- "Operating System :: OS Independent",
- "Programming Language :: Python",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3 :: Only",
- "Programming Language :: Python :: 3.10",
- "Programming Language :: Python :: 3.11",
- "Programming Language :: Python :: 3.12",
- "Programming Language :: Python :: 3.13",
- "Programming Language :: Python :: 3.14",
- "Framework :: Django",
- "Framework :: Django :: 4.2",
- "Framework :: Django :: 5.2",
- "Framework :: Django :: 6.0",
-]
-license = "BSD-3-Clause"
-license-files = ["LICENSE"]
-requires-python = ">=3.10"
-dependencies = [
- "django>=4.2",
- "requests",
-]
-
-[project.urls]
-Homepage = "https://github.com/DjangoAdminHackers/django-linkcheck"
-Issues = "https://github.com/DjangoAdminHackers/django-linkcheck/issues"
-Changelog = "https://github.com/DjangoAdminHackers/django-linkcheck/blob/master/CHANGELOG"
-
-[project.optional-dependencies]
-dev = [
- "build",
- "flake8",
- "isort",
- "pre-commit",
- "requests_mock",
-]
-
-[tool.setuptools]
-include-package-data = true
-
-[tool.setuptools.packages.find]
-include = ["linkcheck*"]
diff --git a/runtests.py b/runtests.py
deleted file mode 100644
index c9e50d7..0000000
--- a/runtests.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-import sys
-from os.path import abspath, dirname
-
-import django
-from django.conf import settings
-
-if not settings.configured:
- test_settings = {
- 'DATABASES': {'default': {'ENGINE': 'django.db.backends.sqlite3'}},
- 'STATIC_URL': '/static/',
- 'MEDIA_URL': '/media/',
- 'INSTALLED_APPS': [
- 'django.contrib.admin', 'django.contrib.auth',
- 'django.contrib.sessions', 'django.contrib.contenttypes',
- 'django.contrib.messages',
- 'linkcheck', 'linkcheck.tests.sampleapp',
- ],
- 'ROOT_URLCONF': "linkcheck.tests.urls",
- 'SITE_DOMAIN': "localhost",
- 'MIDDLEWARE': [
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- 'django.middleware.common.CommonMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- ],
- 'TEMPLATES': [{
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'APP_DIRS': True,
- 'OPTIONS': {
- 'context_processors': [
- 'django.contrib.auth.context_processors.auth',
- 'django.contrib.messages.context_processors.messages',
- 'django.template.context_processors.static',
- 'django.template.context_processors.request',
- ],
- },
- }],
- 'DEFAULT_AUTO_FIELD': 'django.db.models.AutoField',
- 'SECRET_KEY': 'arandomstring',
- 'LINKCHECK_CONNECTION_ATTEMPT_TIMEOUT': 1,
- }
- settings.configure(**test_settings)
-
-
-def runtests(*test_args):
- from django.test.runner import DiscoverRunner
-
- parent = dirname(abspath(__file__))
- sys.path.insert(0, parent)
- test_runner = DiscoverRunner(verbosity=1, interactive=True)
- failures = test_runner.run_tests(test_args)
- sys.exit(failures)
-
-
-if __name__ == '__main__':
- django.setup()
- runtests(*sys.argv[1:])