diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..69747db --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,56 @@ +name: Publish to PyPI + +on: + release: + types: [released, prereleased] + +permissions: + contents: read # to fetch code (actions/checkout) + +env: + PYTHON_LATEST: "3.11" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v4 + with: + python-version: ${{env.PYTHON_LATEST}} + cache: "pip" + cache-dependency-path: "pyproject.toml" + + - name: โฌ๏ธ Install dependencies + run: | + python -Im pip install flit + python -Im flit install --symlink + + - name: ๐๏ธ Build + run: python -Im flit build + + - uses: actions/upload-artifact@v3 + with: + path: ./dist + + # https://docs.pypi.org/trusted-publishers/using-a-publisher/ + pypi-publish: + needs: build + environment: 'release' + + name: โฌ๏ธ Upload release to PyPI + runs-on: ubuntu-latest + permissions: + # Mandatory for trusted publishing + id-token: write + steps: + - uses: actions/download-artifact@v3 + + - name: ๐ Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: artifact/ + print-hash: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..260738f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,101 @@ +name: CI + +on: + push: + branches: + - main + - 'stable/**' + + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read # to fetch code (actions/checkout) + +env: + FORCE_COLOR: "1" # Make tools pretty. + TOX_TESTENV_PASSENV: FORCE_COLOR + PIP_DISABLE_PIP_VERSION_CHECK: "1" + PIP_NO_PYTHON_VERSION_WARNING: "1" + PYTHON_LATEST: "3.11" + + +jobs: + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-python@v4 + with: + python-version: ${{env.PYTHON_LATEST}} + - uses: pre-commit/action@v3.0.0 + + tests: + runs-on: ubuntu-latest + needs: lint + strategy: + matrix: + python: ["3.8", "3.9", "3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v3 + - name: ๐ Setup Python ${{ matrix.python }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + - name: ๐ฆ Install dependencies + run: | + python -Im pip install tox tox-gh-actions flit + python -Im flit install --symlink + + - name: ๐๏ธ Build wheel + run: python -Im flit build --format wheel + + - name: ๐งช Run tox targets for Python ${{ matrix.python-version }} + run: tox --installpkg ./dist/*.whl + + - name: โฌ๏ธ Upload coverage data + uses: actions/upload-artifact@v3 + with: + name: coverage-data + path: .coverage.* + if-no-files-found: ignore + retention-days: 1 + + coverage: + runs-on: ubuntu-latest + needs: tests + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - uses: actions/setup-python@v4 + with: + # Use latest Python, so it understands all syntax. + python-version: ${{env.PYTHON_LATEST}} + + - run: python -Im pip install --upgrade "coverage[toml]>=7.2,<8.0" + + - name: โฌ๏ธ Download coverage data + uses: actions/download-artifact@v3 + with: + name: coverage-data + + - name: ๏ผ Combine coverage + run: | + python -Im coverage combine + python -Im coverage html --skip-covered --skip-empty + python -Im coverage report + echo "## Coverage summary" >> $GITHUB_STEP_SUMMARY + python -Im coverage report --format=markdown >> $GITHUB_STEP_SUMMARY + - name: ๐ Upload HTML report if check failed. + uses: actions/upload-artifact@v3 + with: + name: html-report + path: htmlcov diff --git a/.gitignore b/.gitignore index b8315bc..515ba64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,164 @@ -__pycache__ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class -dist/ +# C extensions +*.so + +# Distribution / packaging +.Python build/ -wagtail_footnotes.egg-info/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + + +# local +test_wagtail_footnotes.db diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..0073f0d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,46 @@ +ci: + autofix_prs: false + +default_language_version: + python: python3.11 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-json + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/psf/black + rev: 23.7.0 + hooks: + - id: black + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: 'v0.0.280' + hooks: + - id: ruff + - repo: https://github.com/adamchainz/blacken-docs + rev: 1.15.0 + hooks: + - id: blacken-docs + additional_dependencies: [black==23.7.0] + - repo: https://github.com/adamchainz/blacken-docs + rev: v1.12.1 + hooks: + - id: blacken-docs + additional_dependencies: + - black==23.7.0 + - repo: https://github.com/jackdewinter/pymarkdown + rev: v0.9.12 + hooks: + - id: pymarkdown + args: + - --disable-rules + - line-length + - scan diff --git a/CHANGELOG.md b/CHANGELOG.md index 39c0c64..0d57724 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,38 @@ ## Unreleased +- Add support for Wagtail 5.2 +- Add Wagtail 5.2 and Python 3.12 in test matrices @katdom13 + +## 0.10.0 + +- Add tests. (https://github.com/torchbox/wagtail-footnotes/pull/49) @nickmoreton + Includes tox 4, coverage configuration. +- Drop support for Python 3.7 and Wagtail < 4.1. (https://github.com/torchbox/wagtail-footnotes/pull/49) @nickmoreton +- Add the coverage report to the GitHub Actions summary. @zerolab +- Switch to using [ruff](https://beta.ruff.rs/docs/) for linting. (https://github.com/torchbox/wagtail-footnotes/pull/52) @zerolab +- Switched to using PyPI trusted publishing (https://github.com/torchbox/wagtail-footnotes/pull/53) @zerolab +- Switched to using [flit](https://flit.pypa.io/en/latest/) for packaging (https://github.com/torchbox/wagtail-footnotes/pull/54) @zerolab + +## 0.9.0 + +- Add support for Wagtail 4.0 +- Add GitHub Action to publish to PyPI on release by @zerolab in (https://github.com/torchbox/wagtail-footnotes/pull/45) + +## 0.8.0 + +- Add support for Wagtail 3.0 and drop support for all Wagtail versions before 2.15 +- Dropped support for all Django versions before 3.2 +- Removed support for Python 3.6 +- Fix previews (https://github.com/torchbox/wagtail-footnotes/pull/24) - [@jsma](https://github.com/jsma) + +## 0.7.0 + +- Clean up old step from README - It is no longer recommended to define footnotes in `WAGTAILADMIN_RICH_TEXT_EDITORS` +- Add `footnotes` rich text feature automatically +- Clean up `RichTextBlockWithFootnotes` +- Make Footnotes unique on `page` <-> `uuid` + ## 0.6.0 - Add `WAGTAIL_FOOTNOTES_TEXT_FEATURES` to add custom rich text features to footnote content @@ -33,4 +65,4 @@ ## 0.1.0 -- Initial release of the Wagtail Footnotes package \ No newline at end of file +- Initial release of the Wagtail Footnotes package diff --git a/LICENCE.txt b/LICENSE similarity index 100% rename from LICENCE.txt rename to LICENSE diff --git a/MANIFEST.in b/MANIFEST.in index b4959d9..ad5c4dd 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,5 +1,8 @@ -include LICENSE *.rst *.txt *.md +include LICENSE graft wagtail_footnotes -global-exclude __pycache__ +prune **/__pycache__ global-exclude *.py[co] global-exclude .DS_Store +recursive-include wagtail_footnotes/static/footnotes/js +recursive-include wagtail_footnotes/templates/wagtail_footnotes +prune **/tests diff --git a/README.md b/README.md index 7b38fc6..ae63f46 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,120 @@ # Wagtail Footnotes +[![PyPI](https://img.shields.io/pypi/v/wagtail-footnotes.svg)](https://pypi.org/project/wagtail-footnotes/) +[![PyPI downloads](https://img.shields.io/pypi/dm/wagtail-footnotes.svg)](https://pypi.org/project/wagtail-footnotes/) +[![Build Status](https://github.com/torchbox/wagtail-footnotes/workflows/CI/badge.svg)](https://github.com/torchbox/wagtail-footnotes/actions) + Add footnotes functionality to your Wagtail project. ## Usage - - Add the app to `INSTALLED_APPS`: - ```python - INSTALLED_APPS = [ - ... - "wagtail_footnotes", - ... - ] - ``` - - Add the footnotes `urls.py` to your project's `urls.py`: - ```python - from wagtail_footnotes import urls as footnotes_urls - urlpatterns = [ - ... - path("footnotes/", include(footnotes_urls)), - ... - ] - ``` - Note: The URL has to be defined as above as it is currently hardcoded in the Javascript. - - Update your page models to show the footnotes field: - ```python - class InformationPage(BasePage): - ... - content_panels = [ - ... - InlinePanel("footnotes", label="Footnotes"), - ] - ``` - - Update your `RichTextBlock`s - - Add `"footnotes"` to the `features` arg for each `RichTextBlock` that you want to have this functionality - - You will also need to change any `RichTextBlock`s to `wagtail_footnotes.blocks.RichTextBlockWithFootnotes` - - You can add the footnotes to `RichTextBlock`s across the project by updating `WAGTAILADMIN_RICH_TEXT_EDITORS["default"]["OPTIONS"]["features"]`: - ```python - WAGTAILADMIN_RICH_TEXT_EDITORS = { - "default": { - "WIDGET": "wagtail.admin.rich_text.DraftailRichTextArea", - "OPTIONS": {"features": ["bold", "italic", "h3", "h4", "ol", "ul", "link", "footnotes"]}, - } - } - ``` - - Update your page templates to include `{% include "wagtail_footnotes/includes/footnotes.html" %}` - - Make and run migrations: - ``` - ./manage.py makemigrations - ./manage.py migrate - ``` + +- Add the app to `INSTALLED_APPS`: + +```python +INSTALLED_APPS = [ + # ... + "wagtail_footnotes", + # ... +] +``` + +- Add the footnotes `urls.py` to your project's `urls.py`: + +```python +from wagtail_footnotes import urls as footnotes_urls + +urlpatterns = [ + # ... + path("footnotes/", include(footnotes_urls)), + # ... +] +``` + +Note: The URL has to be defined as above as it is currently hardcoded in the Javascript. + +- Update your page models to show the footnotes field: + +```python +class InformationPage(BasePage): + # ... + content_panels = [ + # ... + InlinePanel("footnotes", label="Footnotes"), + ] +``` + +- Update your `RichTextBlock`s + - Add `"footnotes"` to the `features` arg for each `RichTextBlock` that you want to have this functionality + - You will also need to change any `RichTextBlock`s to `wagtail_footnotes.blocks.RichTextBlockWithFootnotes` +- Update your page templates to include `{% include "wagtail_footnotes/includes/footnotes.html" %}` + +Make and run migrations: + +```bash +./manage.py makemigrations +./manage.py migrate +``` ## Settings - - `WAGTAIL_FOOTNOTES_TEXT_FEATURES` - - Default: `["bold", "italic", "link"]` - - Use this to update a list of Rich Text features allowed in the footnote text. +- `WAGTAIL_FOOTNOTES_TEXT_FEATURES` + - Default: `["bold", "italic", "link"]` + - Use this to update a list of Rich Text features allowed in the footnote text. ## Common issues - - I click on the `Fn` button in the editor and it stops working - - This is likely because the URL in the JS does not match the URL of the footnotes view. Check the URL in `wagtail_footnotes/static/footnotes/js/footnotes.js` matches the URL you set. - - `NoneType` error when rendering page. - - Make sure you are rendering the field in the template using `{% include_block page.field_name %}` + +- I click on the `Fn` button in the editor and it stops working + - This is likely because the URL in the JS does not match the URL of the footnotes view. Check the URL in `wagtail_footnotes/static/footnotes/js/footnotes.js` matches the URL you set. +- `NoneType` error when rendering page. + - Make sure you are rendering the field in the template using `{% include_block page.field_name %}` + +## Contributing + +All contributions are welcome! + +### Install + +To make changes to this project, first clone this repository: + +```sh +git clone git@github.com:torchbox/wagtail-footnotes.git +cd wagtail-footnotes +``` + +With your preferred virtualenv activated, install testing dependencies: + +```sh +pip install -e '.[testing]' -U +``` + +### pre-commit + +Note that this project uses [pre-commit](https://github.com/pre-commit/pre-commit). To set up locally: + +```shell +$ pip install pre-commit +# initialize pre-commit +$ pre-commit install +# Optional, run all checks once for this, then the checks will run only on the changed files +$ pre-commit run --all-files +``` + +### How to run tests + +To run all tests in all environments: + +```sh +tox +``` + +To run tests for a specific environment: + +```shell +tox -e python3.11-django4.2-wagtail5.2 +``` + +To run a single test method in a specific environment: + +```shell +tox -e python3.11-django4.2-wagtail5.2 -- tests.test.test_blocks.TestBlocks.test_block_with_features +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..01ff6f3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,147 @@ +[project] +name = "wagtail-footnotes" +description = "Add footnotes to rich text in your Wagtail pages" +authors = [{name = "Cameron Lamb ", email = "hello@torchbox.com"}] +maintainers = [ + {name = "Kevin Howbrook", email="kevin.howbrook@torchbox.com"}, + {name = "Dan Braghis", email="dan.braghis@torchbox.com"} +] +readme = "README.md" +license = {file = "LICENSE"} +keywords = ["Wagtail", "Django", "footnotes", "rich text"] +classifiers = [ + "Development Status :: 4 - Beta", + "Environment :: Web Environment", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Framework :: Django", + "Framework :: Django :: 3", + "Framework :: Django :: 3.2", + "Framework :: Django :: 4", + "Framework :: Django :: 4.1", + "Framework :: Django :: 4.2", + "Framework :: Wagtail", + "Framework :: Wagtail :: 4", + "Framework :: Wagtail :: 5", +] + +dynamic = ["version"] # will read __version__ from wagtail_footnotes/__init__.py +requires-python = ">=3.8" +dependencies = [ + "Wagtail>=4.1", + "Django>=3.2", +] + +[project.optional-dependencies] +testing = [ + "pre-commit>=3.3.0,<4", + "tox>=4.6.4,<5", + "black==23.7.0", + "ruff==0.0.280", + "coverage[toml]>=7.2,<8.0", +] + +[project.urls] +Repository = "https://github.com/torchbox/wagtail-footnotes" +Changelog = "https://github.com/torchbox/wagtail-footnotes/blob/main/CHANGELOG.md" + + +[build-system] +requires = ["flit_core >=3.2,<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.module] +name = "wagtail_footnotes" + +[tool.flit.sdist] +exclude = [ + "tests", + "Makefile", + "docs", + ".*", + "*.json", + "*.ini", + "*.yml", + "CHANGELOG.md", + "testmanage.py", +] + +[tool.black] +line_length = 88 +target-version = ["py38"] + + +[tool.ruff] +target-version = "py38" + +extend-select = [ + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "DJ", # flake8-django + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "PGH", # pygrep-hooks + "S", # flake8-bandit + "SIM", # flake8-simplify + "W", # pycodestyle warnings + "YTT", # flake8-2020 + "UP", # pyupgrade + "RUF100", # unused noqa +] + +# Never enforce `E501` (line length violations). +ignore = ["E501"] + +[tool.ruff.isort] +known-first-party = ["src"] +lines-between-types = 1 +lines-after-imports = 2 + + +[tool.coverage.run] +branch = true +concurrency = ["multiprocessing", "thread"] +parallel = true + +source = ["wagtail_footnotes"] +omit = ["**/migrations/*", "tests/*"] + +[tool.coverage.paths] +source = ["wagtail_footnotes", ".tox/py*/**/site-packages"] + +[tool.coverage.report] +show_missing = true +ignore_errors = true +skip_empty = true +skip_covered = true +exclude_lines = [ + # Have to re-enable the standard pragma + "pragma: no cover", + + # Don't complain about missing debug-only code: + "def __repr__", + "if self.debug", + + # Don't complain if tests don't hit defensive assertion code: + "raise AssertionError", + "raise NotImplementedError", + + # Don't complain if non-runnable code isn't run: + "if 0:", + "if __name__ == .__main__.:", + + # Don't complain about abstract methods, they aren't run: + "@(abc.)?abstractmethod", + + # Nor complain about type checking + "if TYPE_CHECKING:", +] diff --git a/setup.py b/setup.py deleted file mode 100644 index 6068493..0000000 --- a/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() diff --git a/testmanage.py b/testmanage.py new file mode 100644 index 0000000..77f635c --- /dev/null +++ b/testmanage.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +import argparse +import os +import shutil +import sys +import warnings + +from django.core.management import execute_from_command_line + + +os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" + + +def make_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--deprecation", + choices=["all", "pending", "imminent", "none"], + default="imminent", + ) + return parser + + +def parse_args(args=None): + return make_parser().parse_known_args(args) + + +def runtests(): + args, rest = parse_args() + + only_wagtail = r"^wagtail(\.|$)" + if args.deprecation == "all": + # Show all deprecation warnings from all packages + warnings.simplefilter("default", DeprecationWarning) + warnings.simplefilter("default", PendingDeprecationWarning) + elif args.deprecation == "pending": + # Show all deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + warnings.filterwarnings( + "default", category=PendingDeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "imminent": + # Show only imminent deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "none": + # Deprecation warnings are ignored by default + pass + + argv = [sys.argv[0]] + rest + + try: + execute_from_command_line(argv) + finally: + from wagtail.test.settings import MEDIA_ROOT, STATIC_ROOT + + shutil.rmtree(STATIC_ROOT, ignore_errors=True) + shutil.rmtree(MEDIA_ROOT, ignore_errors=True) + + +if __name__ == "__main__": + runtests() diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/apps.py b/tests/apps.py new file mode 100644 index 0000000..5996104 --- /dev/null +++ b/tests/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class WagtailFootnotesTestAppConfig(AppConfig): + label = "tests" + name = "tests" + verbose_name = "Wagtail Footnotes tests" diff --git a/tests/blocks.py b/tests/blocks.py new file mode 100644 index 0000000..54927f8 --- /dev/null +++ b/tests/blocks.py @@ -0,0 +1,7 @@ +from wagtail import blocks + +from wagtail_footnotes.blocks import RichTextBlockWithFootnotes + + +class CustomBlock(blocks.StreamBlock): + paragraph = RichTextBlockWithFootnotes(features=["footnotes"]) diff --git a/tests/migrations/0001_initial.py b/tests/migrations/0001_initial.py new file mode 100644 index 0000000..8693d50 --- /dev/null +++ b/tests/migrations/0001_initial.py @@ -0,0 +1,53 @@ +# Generated by Django 4.1.2 on 2022-10-14 21:06 + +import django.db.models.deletion +import wagtail.fields as wagtail_fields + +from django.db import migrations, models + +import wagtail_footnotes.blocks + + +class Migration(migrations.Migration): + initial = True + + dependencies = [ + ("wagtailcore", "0040_page_draft_title"), + ] + + operations = [ + migrations.CreateModel( + name="TestPageStreamField", + fields=[ + ( + "page_ptr", + models.OneToOneField( + auto_created=True, + on_delete=django.db.models.deletion.CASCADE, + parent_link=True, + primary_key=True, + serialize=False, + to="wagtailcore.page", + ), + ), + ( + "body", + wagtail_fields.StreamField( + [ + ( + "paragraph", + wagtail_footnotes.blocks.RichTextBlockWithFootnotes( + features=["footnotes"] + ), + ) + ], + use_json_field=True, + ), + ), + ], + options={ + "abstract": False, + }, + bases=("wagtailcore.page",), + ), + ] diff --git a/tests/migrations/__init__.py b/tests/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/models.py b/tests/models.py new file mode 100644 index 0000000..827e53c --- /dev/null +++ b/tests/models.py @@ -0,0 +1,16 @@ +from wagtail.admin.panels import FieldPanel, InlinePanel +from wagtail.fields import StreamField +from wagtail.models import Page + +from .blocks import CustomBlock + + +class TestPageStreamField(Page): + template = "test/test_page_stream_field.html" + + body = StreamField(CustomBlock(), use_json_field=True) + + content_panels = Page.content_panels + [ + FieldPanel("body"), + InlinePanel("footnotes", label="Footnotes"), + ] diff --git a/tests/settings.py b/tests/settings.py new file mode 100644 index 0000000..f51d490 --- /dev/null +++ b/tests/settings.py @@ -0,0 +1,138 @@ +""" +Django settings for temp project. + +For more information on this file, see +https://docs.djangoproject.com/en/stable/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/stable/ref/settings/ +""" + +import os + + +# Build paths inside the project like this: os.path.join(PROJECT_DIR, ...) +PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) +BASE_DIR = os.path.dirname(PROJECT_DIR) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/stable/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "not-a-secret!" # noqa: S105 + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["localhost", "testserver"] + + +# Application definition + +INSTALLED_APPS = [ + "wagtail_footnotes", + "tests", + "wagtail.users", + "wagtail.snippets", + "wagtail.documents", + "wagtail.images", + "wagtail.search", + "wagtail.admin", + "wagtail.contrib.modeladmin", + "wagtail.sites", + "wagtail", + "taggit", + "rest_framework", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", + "wagtail.contrib.redirects.middleware.RedirectMiddleware", +] + +ROOT_URLCONF = "tests.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ] + }, + } +] + +# don't use the intentionally slow default password hasher +PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",) + +# Database +# https://docs.djangoproject.com/en/stable/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": os.path.join(BASE_DIR, "test_wagtail_footnotes.db"), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + }, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + + +# Internationalization +# https://docs.djangoproject.com/en/stable/topics/i18n/ + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/stable/howto/static-files/ + +STATICFILES_FINDERS = [ + "django.contrib.staticfiles.finders.FileSystemFinder", + "django.contrib.staticfiles.finders.AppDirectoriesFinder", +] + +STATIC_ROOT = os.path.join(BASE_DIR, "test-static") +STATIC_URL = "/static/" + +MEDIA_ROOT = os.path.join(BASE_DIR, "test-media") + +WAGTAIL_SITE_NAME = "Wagtail Footnotes test site" + +# Search +# https://docs.wagtail.org/en/stable/topics/search/backends.html +WAGTAILSEARCH_BACKENDS = { + "default": { + "BACKEND": "wagtail.search.backends.database", + } +} + +WAGTAILADMIN_BASE_URL = "http://localhost:8000" diff --git a/tests/templates/base.html b/tests/templates/base.html new file mode 100644 index 0000000..f0a8cf7 --- /dev/null +++ b/tests/templates/base.html @@ -0,0 +1,17 @@ +{% load wagtailuserbar %} + + + +
+ + + +This is a paragraph with no footnote.
", + } + ] + ), + ) + home_page.add_child(instance=self.test_page_no_footnote) + self.test_page_no_footnote.save_revision().publish() + + uuid = "f291a4b7-5ac5-4030-b341-b1993efb2ad2" + self.test_page_with_footnote = TestPageStreamField( + title="Test Page With Footnote", + slug="test-page-with-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": f'This is a paragraph with a footnote.
This is a paragraph with a footnote. [1]
' + self.assertEqual(out, result) + + def test_block_replace_footnote_render(self): + rtb = self.test_page_with_footnote.body.stream_block.child_blocks["paragraph"] + value = rtb.get_prep_value(self.test_page_with_footnote.body[0].value) + context = self.test_page_with_footnote.get_context(self.client.get("/")) + out = rtb.render(value, context=context) + result = 'This is a paragraph with a footnote. [1]
' + self.assertEqual(out, result) diff --git a/tests/test/test_fields.py b/tests/test/test_fields.py new file mode 100644 index 0000000..20b7fa2 --- /dev/null +++ b/tests/test/test_fields.py @@ -0,0 +1,14 @@ +from django.test import TestCase + +from wagtail_footnotes.fields import CustomUUIDField + + +class TestFields(TestCase): + def test_custom_uuid_field(self): + uuid_field = CustomUUIDField() + self.assertEqual( + uuid_field.from_db_value( + "12345678-1234-5678-1234-567812345678", None, None + ), + "12345678-1234-5678-1234-567812345678", + ) diff --git a/tests/test/test_functional.py b/tests/test/test_functional.py new file mode 100644 index 0000000..9c25588 --- /dev/null +++ b/tests/test/test_functional.py @@ -0,0 +1,110 @@ +import json + +from bs4 import BeautifulSoup as bs4 +from django.contrib.auth.models import User +from django.test import TestCase +from wagtail.models import Page + +from wagtail_footnotes.models import Footnote + +from ..models import TestPageStreamField + + +class TestFunctional(TestCase): + def setUp(self): + home_page = Page.objects.get(title="Welcome to your new Wagtail site!") + + self.test_page_no_footnote = TestPageStreamField( + title="Test Page No Footnote", + slug="test-page-no-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": "This is a paragraph with no footnote.
", + } + ] + ), + ) + home_page.add_child(instance=self.test_page_no_footnote) + self.test_page_no_footnote.save_revision().publish() + + uuid = "f291a4b7-5ac5-4030-b341-b1993efb2ad2" + self.test_page_with_footnote = TestPageStreamField( + title="Test Page With Footnote", + slug="test-page-with-footnote", + body=json.dumps( + [ + { + "type": "paragraph", + "value": f'This is a paragraph with a footnote.