Dataset Viewer
repo
stringclasses 37
values | instance_id
stringlengths 17
34
| base_commit
stringlengths 40
40
| patch
stringlengths 291
1.62M
| test_patch
stringlengths 307
76.5k
| problem_statement
stringlengths 40
59.9k
| hints_text
stringlengths 0
149k
| created_at
stringdate 2018-06-13 17:01:37
2024-12-20 00:40:00
| merged_at
stringdate 2018-09-24 06:57:54
2024-12-20 20:16:12
| PASS_TO_PASS
stringlengths 2
601k
| PASS_TO_FAIL
stringclasses 11
values | FAIL_TO_PASS
stringlengths 18
605k
| FAIL_TO_FAIL
stringclasses 60
values | install
stringlengths 217
12.7k
| test_framework
stringclasses 10
values | test_commands
stringclasses 10
values | version
null | environment_setup_commit
null |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kibitzr/kibitzr | kibitzr__kibitzr-108 | c3073a81ebbabf35f351d29a8096486f8c17aaf5 | diff --git a/docs/gotify.rst b/docs/gotify.rst
new file mode 100644
index 0000000..9a1ec8d
--- /dev/null
+++ b/docs/gotify.rst
@@ -0,0 +1,57 @@
+.. _gotify:
+
+=================
+Gotify Notifier
+=================
+
+Kibitzr supports sending notifications via Gotify_.
+
+Configuration
+-------------
+
+The Gotify notifier needs an ``url`` and an application ``token`` to send notifications.
+
+Example of ``kibitzr-creds.yml`` file:
+
+.. code-block:: yaml
+
+ gotify:
+ url: https://gotify.example.net/
+ token: A0dIInnCs1J1zNN
+
+
+Now the notifier can be configured in ``kibitzr.yml`` using following syntax:
+
+.. code-block:: yaml
+
+ checks:
+ ...
+ notify:
+ - gotify
+
+
+Some defaults can be overridden for each check:
+
+.. code-block:: yaml
+
+ checks:
+ ...
+ notify:
+ - gotify:
+ title: Important Notification # default: kibitzr
+ priority: 7 # default: 4
+
+
+The request to the Gotify server performs an SSL certificate verification.
+If you are **aware of the implications** and still want to bypass this verification,
+you can do that by adding a ``verify: false`` flag to the configuration:
+
+.. code-block:: yaml
+
+ gotify:
+ url: https://gotify.example.net/
+ token: A0dIInnCs1J1zNN
+ verify: false
+
+
+.. _Gotify: https://gotify.net/
diff --git a/docs/notifiers.rst b/docs/notifiers.rst
index 7f74743..3c93871 100644
--- a/docs/notifiers.rst
+++ b/docs/notifiers.rst
@@ -14,10 +14,11 @@ Kibitzr supports following notifier types:
3. ``slack`` - Trigger `Slack Incoming Webhook`_
4. ``telegram`` - Send message through :ref:`private Telegram Bot <telegram>`
5. ``zapier`` - Trigger `Zapier Catch Hook`_
-6. ``gitter`` - Or post to gitter's chat
-7. ``python`` - Run :ref:`Python script <python>`
-8. ``shell`` - Run :ref:`shell script <shell>`
-9. ``stash`` - Save to persistent global key-value storage; See :ref:`stash` for details
+6. ``gitter`` - Post to gitter's chat
+7. ``gotify`` - Push notification via :ref:`Gotify <gotify>`
+8. ``python`` - Run :ref:`Python script <python>`
+9. ``shell`` - Run :ref:`shell script <shell>`
+10. ``stash`` - Save to persistent global key-value storage; See :ref:`stash` for details
Each notifier requires different configuration.
For the sake of security, sensitive information
@@ -57,3 +58,7 @@ Example configurations
zapier:
url: https://hooks.zapier.com/hooks/catch/1670195/9asu13/
+
+ gotify:
+ url: https://gotify.example.de/
+ token: A0dIInnCs1J1zNN
diff --git a/kibitzr/notifier/gotify.py b/kibitzr/notifier/gotify.py
new file mode 100644
index 0000000..32d2650
--- /dev/null
+++ b/kibitzr/notifier/gotify.py
@@ -0,0 +1,53 @@
+import logging
+import urllib3
+
+from ..conf import settings
+
+
+logger = logging.getLogger(__name__)
+
+
+class GotifyNotify(object):
+ def __init__(self, value):
+ import requests
+ self.session = requests.Session()
+ gotify_creds = settings().creds['gotify']
+ self.url = gotify_creds['url'].rstrip('/') + '/message'
+ self.token = gotify_creds['token']
+ self.verify = gotify_creds.get('verify', True)
+ if not self.verify:
+ # Since certificate validation was disabled, do not show the warning
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+ if value is None:
+ value = {}
+ self.title = value.get('title', 'kibitzr')
+ self.priority = value.get('priority', 4)
+
+ def post(self, report):
+ logger.info("Executing Gotify notifier")
+ response = self.session.post(
+ url=self.url,
+ json=self.json(report),
+ params=self.params(),
+ verify=self.verify
+ )
+ logger.debug(response.text)
+ response.raise_for_status()
+ return response
+ __call__ = post
+
+ def params(self):
+ return {
+ 'token': self.token
+ }
+
+ def json(self, report):
+ return {
+ 'title': self.title,
+ 'message': report,
+ 'priority': self.priority
+ }
+
+
+def notify_factory(conf, value):
+ return GotifyNotify(value)
| diff --git a/tests/unit/notifiers/test_gotify.py b/tests/unit/notifiers/test_gotify.py
new file mode 100644
index 0000000..cfbcc45
--- /dev/null
+++ b/tests/unit/notifiers/test_gotify.py
@@ -0,0 +1,81 @@
+import pytest
+from kibitzr.notifier.gotify import GotifyNotify
+
+from ...compat import mock
+from ...helpers import SettingsMock
+
+
[email protected]()
+def settings():
+ """Override native settings singleton with empty one"""
+ return SettingsMock.instance()
+
+
+def test_gotify_sample(settings):
+ settings.creds.update({
+ 'gotify': {
+ 'url': 'http://localhost:8080',
+ 'token': '123456',
+ }
+ })
+ value = {}
+ notify = GotifyNotify(value=value)
+ with mock.patch.object(notify.session, 'post') as fake_post:
+ notify('report')
+ fake_post.assert_called_once_with(
+ url='http://localhost:8080/message',
+ json={
+ 'title': 'kibitzr',
+ 'message': 'report',
+ 'priority': 4
+ },
+ params={'token': '123456'},
+ verify=True
+ )
+
+
+def test_gotify_no_verification(settings):
+ settings.creds.update({
+ 'gotify': {
+ 'url': 'https://localhost:8080',
+ 'token': '123456',
+ 'verify': False,
+ }
+ })
+ value = {}
+ notify = GotifyNotify(value=value)
+ with mock.patch.object(notify.session, 'post') as fake_post:
+ notify('report')
+ fake_post.assert_called_once_with(
+ url='https://localhost:8080/message',
+ json={
+ 'title': 'kibitzr',
+ 'message': 'report',
+ 'priority': 4,
+ },
+ params={'token': '123456'},
+ verify=False
+ )
+
+
+def test_gotify_override_defaults(settings):
+ settings.creds.update({
+ 'gotify': {
+ 'url': 'http://localhost:8080',
+ 'token': '123456',
+ }
+ })
+ value = {'title': 'Important Notification', 'priority': 7}
+ notify = GotifyNotify(value=value)
+ with mock.patch.object(notify.session, 'post') as fake_post:
+ notify('report')
+ fake_post.assert_called_once_with(
+ url='http://localhost:8080/message',
+ json={
+ 'title': 'Important Notification',
+ 'message': 'report',
+ 'priority': 7
+ },
+ params={'token': '123456'},
+ verify=True
+ )
| Add http notifier
Please and a notifier which executes http requests. This could be used to communicate with web hooks or other web based API. For example sending messages via [Gotify](https://gotify.net/).
| There are so many nuances to send HTTP requests, that I've left this task to `shell` and `python` notifiers.
Consider authentication, methods, payloads, content types. Exposing all these options through YAML config seems to be not maintainable.
But you're welcome to add a PR with `gotify` notifier, that will load credentials from `kibitzr-creds` and POST the request according to protocol.
Yes, you're right.
I tried `shell` first, but the Docker container does not contain `curl`. So I'm using `python`:
```yaml
notify:
- python: |
import requests
requests.post('http://localhost:8008/message?token=<apptoken>', json={
"message": content,
"title": "This is my title"
})
```
---
I have already taken a look at the code. A gotify notifier should not be very complicated. I will try to create a first draft in the next few days. :) | 2021-10-10T19:58:18Z | 2021-10-11T15:06:03Z | [] | [] | ["tests/unit/notifiers/test_gotify.py::test_gotify_sample", "tests/unit/notifiers/test_gotify.py::test_gotify_no_verification", "tests/unit/notifiers/test_gotify.py::test_gotify_override_defaults"] | [] | {"install": ["curl -L https://github.com/mozilla/geckodriver/releases/download/v0.29.1/geckodriver-v0.29.1-linux64.tar.gz | tar zxf -", "uv pip install -e ."], "pre_install": ["tee tox.ini <<EOF_1234810234\n[tox]\nenvlist = py27, py3{5,6,7}, flake8\n\n[testenv:flake8]\nbasepython=python\ndeps=flake8\ncommands=flake8 kibitzr tests\n\n[testenv]\nsetenv =\n PYTHONPATH = {toxinidir}:{toxinidir}/kibitzr\ndeps =\n -r{toxinidir}/requirements/dev.txt\ncommands =\n pip install -U pip\n pytest --color=no -rA --tb=no -p no:cacheprovider --basetemp={envtmpdir} -v --cov kibitzr --cov-report term-missing {posargs:tests/}\n\nEOF_1234810234"], "python": "3.7", "pip_packages": ["alabaster==0.7.12", "apipkg==1.5", "appdirs==1.4.4", "apscheduler==3.6.3", "astroid==1.6.6", "atomicwrites==1.4.0", "attrs==20.2.0", "babel==2.8.0", "beautifulsoup4==4.9.3", "bs4==0.0.1", "bump2version==1.0.1", "cachecontrol==0.12.6", "certifi==2020.6.20", "cffi==1.14.3", "chardet==3.0.4", "click==7.1.2", "coverage==5.3", "coveralls==3.3.1", "cryptography==3.2.1", "decorator==4.4.2", "defusedxml==0.5.0", "distlib==0.3.1", "docopt==0.6.2", "docutils==0.16", "entrypoints==0.3", "execnet==1.7.1", "filelock==3.0.12", "flake8==3.8.4", "freezegun==1.0.0", "idna==2.10", "imagesize==1.2.0", "importlib-metadata==2.0.0", "importlib-resources==3.3.0", "isort==5.6.4", "jinja2==2.11.2", "lazy-object-proxy==1.5.1", "lxml==4.6.1", "markupsafe==1.1.1", "mccabe==0.6.1", "mock==4.0.2", "more-itertools==5.0.0", "msgpack==1.0.0", "packaging==20.4", "pathtools==0.1.2", "pep8==1.7.1", "pip==22.3.1", "pip-compile-multi==2.1.0", "pip-tools==5.3.1", "pluggy==0.13.1", "py==1.9.0", "pycodestyle==2.6.0", "pycparser==2.20", "pyflakes==2.2.0", "pygments==2.7.2", "pylint==1.9.4", "pyparsing==2.4.7", "pytest==4.6.0", "pytest-cache==1.0", "pytest-cov==2.10.1", "pytest-mock==2.0.0", "pytest-pep8==1.0.6", "python-dateutil==2.8.1", "python-telegram-bot==13.0", "pytimeparse==1.1.8", "pytz==2020.1", "pyyaml==5.3.1", "requests==2.24.0", "schedule==0.6.0", "selenium==3.141.0", "setuptools==65.6.3", "sh==1.14.3", "six==1.15.0", "snowballstemmer==2.0.0", "soupsieve==2.0.1", "sphinx==1.8.5", "sphinxcontrib-serializinghtml==1.1.4", "sphinxcontrib-websupport==1.2.4", "toml==0.10.1", "toposort==1.5", "tornado==6.0.4", "tox==3.20.1", "tzlocal==2.1", "urllib3==1.25.11", "virtualenv==20.1.0", "watchdog==0.10.3", "wcwidth==0.2.5", "wheel==0.35.1", "wrapt==1.12.1", "zipp==3.4.0"]} | pytest --tb=no -rA -p no:cacheprovider | null | null | null |
getnikola/nikola | getnikola__nikola-3728 | b28c2bcd1dac5a03cc5554d4ed09693c2afcaf4c | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7476c2077..ae5f499fa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -15,13 +15,13 @@ jobs:
strategy:
fail-fast: false
matrix:
- python: ['3.7', '3.8', '3.9', '3.10', '3.11']
+ python: ['3.7', '3.8', '3.9', '3.10', '3.11', '3.12']
image:
- ubuntu-latest
include:
- - python: '3.11'
+ - python: '3.12'
image: macos-latest
- - python: '3.11'
+ - python: '3.12'
image: windows-latest
runs-on: '${{ matrix.image }}'
steps:
@@ -84,7 +84,7 @@ jobs:
strategy:
matrix:
python:
- - '3.11'
+ - '3.12'
runs-on: ubuntu-latest
steps:
- name: Check out code
@@ -112,6 +112,7 @@ jobs:
matrix:
python:
- '3.11'
+ - '3.12'
runs-on: ubuntu-latest
steps:
- name: Check out code
diff --git a/CHANGES.txt b/CHANGES.txt
index 12e58f07d..63870f5cc 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -4,11 +4,16 @@ New in master
Features
--------
+* Implement a new plugin manager from scratch to replace Yapsy,
+ which does not work on Python 3.12 due to Python 3.12 carelessly
+ removing parts of the standard library (Issue #3719)
* Support for Discourse as comment system (Issue #3689)
Bugfixes
--------
+* Fix loading of templates from plugins with ``__init__.py`` files
+ (Issue #3725)
* Fix margins of paragraphs at the end of sections (Issue #3704)
* Ignore ``.DS_Store`` files in listing indexes (Issue #3698)
* Fix baguetteBox.js invoking in the base theme (Issue #3687)
@@ -16,6 +21,14 @@ Bugfixes
for non-root SITE_URL, in particular when URL_TYPE is full_path.
(Issue #3715)
+For plugin developers
+---------------------
+
+Nikola now requires the ``.plugin`` file to contain a ``[Nikola]``
+section with a ``PluginCategory`` entry set to the name of the plugin
+category class. This was already required by ``plugins.getnikola.com``,
+but you may have custom plugins that don’t have this set.
+
New in v8.2.4
=============
diff --git a/docs/internals.rst b/docs/internals.rst
index 0180f0d39..a3b7af2fc 100644
--- a/docs/internals.rst
+++ b/docs/internals.rst
@@ -15,7 +15,7 @@ So, this is a short document explaining what each piece of Nikola does and
how it all fits together.
Nikola is a Pile of Plugins
- Most of Nikola is implemented as plugins using `Yapsy <http://yapsy.sourceforge.net/>`_.
+ Most of Nikola is implemented as plugins (using a custom plugin manager inspired by Yapsy).
You can ignore that they are plugins and just think of them as regular python
modules and packages with a funny little ``.plugin`` file next to them.
@@ -65,7 +65,7 @@ basename:name
If you ever want to do your own tasks, you really should read the doit
`documentation on tasks <https://pydoit.org/tasks.html>`_.
-
+
Notably, by default doit redirects ``stdout`` and ``stderr``. To get a
proper PDB debugging shell, you need to use doit's own
`set_trace <https://pydoit.org/tools.html#set-trace>`_ function.
diff --git a/nikola/nikola.py b/nikola/nikola.py
index 056f606dd..dd39e82d9 100644
--- a/nikola/nikola.py
+++ b/nikola/nikola.py
@@ -35,6 +35,7 @@
import os
import pathlib
import sys
+import typing
import mimetypes
from collections import defaultdict
from copy import copy
@@ -47,27 +48,14 @@
import PyRSS2Gen as rss
from pkg_resources import resource_filename
from blinker import signal
-from yapsy.PluginManager import PluginManager
from . import DEBUG, SHOW_TRACEBACKS, filters, utils, hierarchy_utils, shortcodes
from . import metadata_extractors
from .metadata_extractors import default_metadata_extractors_by
from .post import Post # NOQA
+from .plugin_manager import PluginCandidate, PluginInfo, PluginManager
from .plugin_categories import (
- Command,
- LateTask,
- PageCompiler,
- CompilerExtension,
- MarkdownExtension,
- RestExtension,
- MetadataExtractor,
- ShortcodePlugin,
- Task,
- TaskMultiplier,
TemplateSystem,
- SignalHandler,
- ConfigPlugin,
- CommentSystem,
PostScanner,
Taxonomy,
)
@@ -377,25 +365,15 @@ def _enclosure(post, lang):
return url, length, mime
-def _plugin_load_callback(plugin_info):
- """Set the plugin's module path.
-
- So we can find its template path later.
- """
- try:
- plugin_info.plugin_object.set_module_path(plugin_info.path)
- except AttributeError:
- # this is just for safety in case plugin_object somehow
- # isn't set
- pass
-
-
class Nikola(object):
"""Class that handles site generation.
Takes a site config as argument on creation.
"""
+ plugin_manager: PluginManager
+ _template_system: TemplateSystem
+
def __init__(self, **config):
"""Initialize proper environment for running tasks."""
# Register our own path handlers
@@ -1019,57 +997,47 @@ def __init__(self, **config):
# WebP files have no official MIME type yet, but we need to recognize them (Issue #3671)
mimetypes.add_type('image/webp', '.webp')
- def _filter_duplicate_plugins(self, plugin_list):
+ def _filter_duplicate_plugins(self, plugin_list: typing.Iterable[PluginCandidate]):
"""Find repeated plugins and discard the less local copy."""
- def plugin_position_in_places(plugin):
+ def plugin_position_in_places(plugin: PluginInfo):
# plugin here is a tuple:
# (path to the .plugin file, path to plugin module w/o .py, plugin metadata)
for i, place in enumerate(self._plugin_places):
- if plugin[0].startswith(place):
+ place: pathlib.Path
+ try:
+ # Path.is_relative_to backport
+ plugin.source_dir.relative_to(place)
return i
- utils.LOGGER.warn("Duplicate plugin found in unexpected location: {}".format(plugin[0]))
+ except ValueError:
+ pass
+ utils.LOGGER.warning("Duplicate plugin found in unexpected location: {}".format(plugin.source_dir))
return len(self._plugin_places)
plugin_dict = defaultdict(list)
- for data in plugin_list:
- plugin_dict[data[2].name].append(data)
+ for plugin in plugin_list:
+ plugin_dict[plugin.name].append(plugin)
result = []
- for _, plugins in plugin_dict.items():
+ for name, plugins in plugin_dict.items():
if len(plugins) > 1:
# Sort by locality
plugins.sort(key=plugin_position_in_places)
utils.LOGGER.debug("Plugin {} exists in multiple places, using {}".format(
- plugins[-1][2].name, plugins[-1][0]))
+ name, plugins[-1].source_dir))
result.append(plugins[-1])
return result
def init_plugins(self, commands_only=False, load_all=False):
"""Load plugins as needed."""
- self.plugin_manager = PluginManager(categories_filter={
- "Command": Command,
- "Task": Task,
- "LateTask": LateTask,
- "TemplateSystem": TemplateSystem,
- "PageCompiler": PageCompiler,
- "TaskMultiplier": TaskMultiplier,
- "CompilerExtension": CompilerExtension,
- "MarkdownExtension": MarkdownExtension,
- "RestExtension": RestExtension,
- "MetadataExtractor": MetadataExtractor,
- "ShortcodePlugin": ShortcodePlugin,
- "SignalHandler": SignalHandler,
- "ConfigPlugin": ConfigPlugin,
- "CommentSystem": CommentSystem,
- "PostScanner": PostScanner,
- "Taxonomy": Taxonomy,
- })
- self.plugin_manager.getPluginLocator().setPluginInfoExtension('plugin')
extra_plugins_dirs = self.config['EXTRA_PLUGINS_DIRS']
+ self._loading_commands_only = commands_only
self._plugin_places = [
resource_filename('nikola', 'plugins'),
os.path.expanduser(os.path.join('~', '.nikola', 'plugins')),
os.path.join(os.getcwd(), 'plugins'),
] + [path for path in extra_plugins_dirs if path]
+ self._plugin_places = [pathlib.Path(p) for p in self._plugin_places]
+
+ self.plugin_manager = PluginManager(plugin_places=self._plugin_places)
compilers = defaultdict(set)
# Also add aliases for combinations with TRANSLATIONS_PATTERN
@@ -1088,41 +1056,37 @@ def init_plugins(self, commands_only=False, load_all=False):
self.disabled_compilers = {}
self.disabled_compiler_extensions = defaultdict(list)
- self.plugin_manager.getPluginLocator().setPluginPlaces(self._plugin_places)
- self.plugin_manager.locatePlugins()
- bad_candidates = set([])
+ candidates = self.plugin_manager.locate_plugins()
+ good_candidates = set()
if not load_all:
- for p in self.plugin_manager._candidates:
+ for p in candidates:
if commands_only:
- if p[-1].details.has_option('Nikola', 'PluginCategory'):
- # FIXME TemplateSystem should not be needed
- if p[-1].details.get('Nikola', 'PluginCategory') not in {'Command', 'Template'}:
- bad_candidates.add(p)
- else:
- bad_candidates.add(p)
+ if p.category != 'Command':
+ continue
elif self.configured: # Not commands-only, and configured
# Remove blacklisted plugins
- if p[-1].name in self.config['DISABLED_PLUGINS']:
- bad_candidates.add(p)
- utils.LOGGER.debug('Not loading disabled plugin {}', p[-1].name)
- # Remove compilers we don't use
- if p[-1].details.has_option('Nikola', 'PluginCategory') and p[-1].details.get('Nikola', 'PluginCategory') in ('Compiler', 'PageCompiler'):
- bad_candidates.add(p)
- self.disabled_compilers[p[-1].name] = p
+ if p.name in self.config['DISABLED_PLUGINS']:
+ utils.LOGGER.debug('Not loading disabled plugin {}', p.name)
+ continue
+ # Remove compilers - will be loaded later based on usage
+ if p.category == "PageCompiler":
+ self.disabled_compilers[p.name] = p
+ continue
# Remove compiler extensions we don't need
- if p[-1].details.has_option('Nikola', 'compiler') and p[-1].details.get('Nikola', 'compiler') in self.disabled_compilers:
- bad_candidates.add(p)
- self.disabled_compiler_extensions[p[-1].details.get('Nikola', 'compiler')].append(p)
- self.plugin_manager._candidates = list(set(self.plugin_manager._candidates) - bad_candidates)
+ if p.compiler and p.compiler in self.disabled_compilers:
+ self.disabled_compiler_extensions[p.compiler].append(p)
+ continue
+ good_candidates.add(p)
- self.plugin_manager._candidates = self._filter_duplicate_plugins(self.plugin_manager._candidates)
- self.plugin_manager.loadPlugins(callback_after=_plugin_load_callback)
+ good_candidates = self._filter_duplicate_plugins(good_candidates)
+ self.plugin_manager.load_plugins(good_candidates)
# Search for compiler plugins which we disabled but shouldn't have
self._activate_plugins_of_category("PostScanner")
if not load_all:
file_extensions = set()
- for post_scanner in [p.plugin_object for p in self.plugin_manager.getPluginsOfCategory('PostScanner')]:
+ for post_scanner in [p.plugin_object for p in self.plugin_manager.get_plugins_of_category('PostScanner')]:
+ post_scanner: PostScanner
exts = post_scanner.supported_extensions()
if exts is not None:
file_extensions.update(exts)
@@ -1141,13 +1105,13 @@ def init_plugins(self, commands_only=False, load_all=False):
for p in self.disabled_compiler_extensions.pop(k, []):
to_add.append(p)
for _, p in self.disabled_compilers.items():
- utils.LOGGER.debug('Not loading unneeded compiler {}', p[-1].name)
+ utils.LOGGER.debug('Not loading unneeded compiler %s', p.name)
for _, plugins in self.disabled_compiler_extensions.items():
for p in plugins:
- utils.LOGGER.debug('Not loading compiler extension {}', p[-1].name)
+ utils.LOGGER.debug('Not loading compiler extension %s', p.name)
if to_add:
- self.plugin_manager._candidates = self._filter_duplicate_plugins(to_add)
- self.plugin_manager.loadPlugins(callback_after=_plugin_load_callback)
+ extra_candidates = self._filter_duplicate_plugins(to_add)
+ self.plugin_manager.load_plugins(extra_candidates)
# Jupyter theme configuration. If a website has ipynb enabled in post_pages
# we should enable the Jupyter CSS (leaving that up to the theme itself).
@@ -1160,7 +1124,8 @@ def init_plugins(self, commands_only=False, load_all=False):
self._activate_plugins_of_category("Taxonomy")
self.taxonomy_plugins = {}
- for taxonomy in [p.plugin_object for p in self.plugin_manager.getPluginsOfCategory('Taxonomy')]:
+ for taxonomy in [p.plugin_object for p in self.plugin_manager.get_plugins_of_category('Taxonomy')]:
+ taxonomy: Taxonomy
if not taxonomy.is_enabled():
continue
if taxonomy.classification_name in self.taxonomy_plugins:
@@ -1186,10 +1151,9 @@ def init_plugins(self, commands_only=False, load_all=False):
# Activate all required compiler plugins
self.compiler_extensions = self._activate_plugins_of_category("CompilerExtension")
- for plugin_info in self.plugin_manager.getPluginsOfCategory("PageCompiler"):
+ for plugin_info in self.plugin_manager.get_plugins_of_category("PageCompiler"):
if plugin_info.name in self.config["COMPILERS"].keys():
- self.plugin_manager.activatePluginByName(plugin_info.name)
- plugin_info.plugin_object.set_site(self)
+ self._activate_plugin(plugin_info)
# Activate shortcode plugins
self._activate_plugins_of_category("ShortcodePlugin")
@@ -1198,10 +1162,8 @@ def init_plugins(self, commands_only=False, load_all=False):
self.compilers = {}
self.inverse_compilers = {}
- for plugin_info in self.plugin_manager.getPluginsOfCategory(
- "PageCompiler"):
- self.compilers[plugin_info.name] = \
- plugin_info.plugin_object
+ for plugin_info in self.plugin_manager.get_plugins_of_category("PageCompiler"):
+ self.compilers[plugin_info.name] = plugin_info.plugin_object
# Load comment systems, config plugins and register templated shortcodes
self._activate_plugins_of_category("CommentSystem")
@@ -1344,13 +1306,26 @@ def _set_all_page_deps_from_config(self):
self.ALL_PAGE_DEPS['index_read_more_link'] = self.config.get('INDEX_READ_MORE_LINK')
self.ALL_PAGE_DEPS['feed_read_more_link'] = self.config.get('FEED_READ_MORE_LINK')
- def _activate_plugins_of_category(self, category):
+ def _activate_plugin(self, plugin_info: PluginInfo) -> None:
+ plugin_info.plugin_object.set_site(self)
+
+ if plugin_info.category == "TemplateSystem" or self._loading_commands_only:
+ return
+
+ templates_directory_candidates = [
+ plugin_info.source_dir / "templates" / self.template_system.name,
+ plugin_info.source_dir / plugin_info.module_name / "templates" / self.template_system.name
+ ]
+ for candidate in templates_directory_candidates:
+ if candidate.exists() and candidate.is_dir():
+ self.template_system.inject_directory(str(candidate))
+
+ def _activate_plugins_of_category(self, category) -> typing.List[PluginInfo]:
"""Activate all the plugins of a given category and return them."""
# this code duplicated in tests/base.py
plugins = []
- for plugin_info in self.plugin_manager.getPluginsOfCategory(category):
- self.plugin_manager.activatePluginByName(plugin_info.name)
- plugin_info.plugin_object.set_site(self)
+ for plugin_info in self.plugin_manager.get_plugins_of_category(category):
+ self._activate_plugin(plugin_info)
plugins.append(plugin_info)
return plugins
@@ -1414,13 +1389,12 @@ def _get_template_system(self):
if self._template_system is None:
# Load template plugin
template_sys_name = utils.get_template_engine(self.THEMES)
- pi = self.plugin_manager.getPluginByName(
- template_sys_name, "TemplateSystem")
+ pi = self.plugin_manager.get_plugin_by_name(template_sys_name, "TemplateSystem")
if pi is None:
sys.stderr.write("Error loading {0} template system "
"plugin\n".format(template_sys_name))
sys.exit(1)
- self._template_system = pi.plugin_object
+ self._template_system = typing.cast(TemplateSystem, pi.plugin_object)
lookup_dirs = ['templates'] + [os.path.join(utils.get_theme_path(name), "templates")
for name in self.THEMES]
self._template_system.set_directories(lookup_dirs,
@@ -2089,7 +2063,7 @@ def flatten(task):
yield ft
task_dep = []
- for pluginInfo in self.plugin_manager.getPluginsOfCategory(plugin_category):
+ for pluginInfo in self.plugin_manager.get_plugins_of_category(plugin_category):
for task in flatten(pluginInfo.plugin_object.gen_tasks()):
if 'basename' not in task:
raise ValueError("Task {0} does not have a basename".format(task))
@@ -2098,7 +2072,7 @@ def flatten(task):
task['task_dep'] = []
task['task_dep'].extend(self.injected_deps[task['basename']])
yield task
- for multi in self.plugin_manager.getPluginsOfCategory("TaskMultiplier"):
+ for multi in self.plugin_manager.get_plugins_of_category("TaskMultiplier"):
flag = False
for task in multi.plugin_object.process(task, name):
flag = True
@@ -2207,7 +2181,7 @@ def scan_posts(self, really=False, ignore_quit=False, quiet=False):
self.timeline = []
self.pages = []
- for p in sorted(self.plugin_manager.getPluginsOfCategory('PostScanner'), key=operator.attrgetter('name')):
+ for p in sorted(self.plugin_manager.get_plugins_of_category('PostScanner'), key=operator.attrgetter('name')):
try:
timeline = p.plugin_object.scan()
except Exception:
diff --git a/nikola/plugin_categories.py b/nikola/plugin_categories.py
index 08316284d..980f9106a 100644
--- a/nikola/plugin_categories.py
+++ b/nikola/plugin_categories.py
@@ -33,7 +33,6 @@
import doit
from doit.cmd_base import Command as DoitCommand
-from yapsy.IPlugin import IPlugin
from .utils import LOGGER, first_line, get_logger, req_missing
@@ -58,7 +57,7 @@
)
-class BasePlugin(IPlugin):
+class BasePlugin:
"""Base plugin class."""
logger = None
@@ -66,7 +65,6 @@ class BasePlugin(IPlugin):
def set_site(self, site):
"""Set site, which is a Nikola instance."""
self.site = site
- self.inject_templates()
self.logger = get_logger(self.name)
if not site.debug:
self.logger.level = logging.INFO
@@ -75,21 +73,6 @@ def set_module_path(self, module_path):
"""Set the plugin's module path."""
self.module_path = module_path
- def inject_templates(self):
- """Inject 'templates/<engine>' (if exists) very early in the theme chain."""
- try:
- mod_dir = os.path.dirname(self.module_path)
- tmpl_dir = os.path.join(
- mod_dir, 'templates', self.site.template_system.name
- )
- if os.path.isdir(tmpl_dir):
- # Inject tmpl_dir low in the theme chain
- self.site.template_system.inject_directory(tmpl_dir)
- except AttributeError:
- # This would likely mean we don't have module_path set.
- # this should not usually happen, so log a warning
- LOGGER.warning("Could not find template path for module {0}".format(self.name))
-
def inject_dependency(self, target, dependency):
"""Add 'dependency' to the target task's task_deps."""
self.site.injected_deps[target].append(dependency)
@@ -359,7 +342,7 @@ def get_compiler_extensions(self) -> list:
"""Activate all the compiler extension plugins for a given compiler and return them."""
plugins = []
for plugin_info in self.site.compiler_extensions:
- if plugin_info.plugin_object.compiler_name == self.name:
+ if plugin_info.compiler == self.name or plugin_info.plugin_object.compiler_name == self.name:
plugins.append(plugin_info)
return plugins
@@ -371,11 +354,8 @@ class CompilerExtension(BasePlugin):
(a) create a new plugin class for them; or
(b) use this class and filter them yourself.
If you choose (b), you should the compiler name to the .plugin
- file in the Nikola/Compiler section and filter all plugins of
- this category, getting the compiler name with:
- p.details.get('Nikola', 'Compiler')
- Note that not all compiler plugins have this option and you might
- need to catch configparser.NoOptionError exceptions.
+ file in the Nikola/compiler section and filter all plugins of
+ this category, getting the compiler name with `plugin_info.compiler`.
"""
name = "dummy_compiler_extension"
@@ -904,3 +884,23 @@ def get_other_language_variants(self, classification: str, lang: str, classifica
Provided is a set of classifications per language (`classifications_per_language`).
"""
return []
+
+
+CATEGORIES = {
+ "Command": Command,
+ "Task": Task,
+ "LateTask": LateTask,
+ "TemplateSystem": TemplateSystem,
+ "PageCompiler": PageCompiler,
+ "TaskMultiplier": TaskMultiplier,
+ "CompilerExtension": CompilerExtension,
+ "MarkdownExtension": MarkdownExtension,
+ "RestExtension": RestExtension,
+ "MetadataExtractor": MetadataExtractor,
+ "ShortcodePlugin": ShortcodePlugin,
+ "SignalHandler": SignalHandler,
+ "ConfigPlugin": ConfigPlugin,
+ "CommentSystem": CommentSystem,
+ "PostScanner": PostScanner,
+ "Taxonomy": Taxonomy,
+}
diff --git a/nikola/plugin_manager.py b/nikola/plugin_manager.py
new file mode 100644
index 000000000..5c1a29a10
--- /dev/null
+++ b/nikola/plugin_manager.py
@@ -0,0 +1,264 @@
+# -*- coding: utf-8 -*-
+
+# Copyright © 2012-2024 Chris Warrick and others.
+
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the
+# Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice
+# shall be included in all copies or substantial portions of
+# the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""The Nikola plugin manager. Inspired by yapsy."""
+
+import configparser
+import importlib
+import importlib.util
+import time
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Dict, List, Optional, Type, TYPE_CHECKING, Set
+
+from .plugin_categories import BasePlugin, CATEGORIES
+from .utils import get_logger
+
+if TYPE_CHECKING:
+ import logging
+
+LEGACY_PLUGIN_NAMES: Dict[str, str] = {
+ "Compiler": "PageCompiler",
+ "Shortcode": "ShortcodePlugin",
+ "Template": "TemplateSystem",
+}
+
+CATEGORY_NAMES: Set[str] = set(CATEGORIES.keys())
+CATEGORY_TYPES: Set[Type[BasePlugin]] = set(CATEGORIES.values())
+
+
+@dataclass(frozen=True)
+class PluginCandidate:
+ """A candidate plugin that was located but not yet loaded (imported)."""
+
+ name: str
+ description: Optional[str]
+ plugin_id: str
+ category: str
+ compiler: Optional[str]
+ source_dir: Path
+ module_name: str
+
+
+@dataclass(frozen=True)
+class PluginInfo:
+ """A plugin that was loaded (imported)."""
+
+ name: str
+ description: Optional[str]
+ plugin_id: str
+ category: str
+ compiler: Optional[str]
+ source_dir: Path
+ module_name: str
+ module_object: object
+ plugin_object: BasePlugin
+
+
+class PluginManager:
+ """The Nikola plugin manager."""
+
+ categories_filter: Dict[str, Type[BasePlugin]]
+ plugin_places: List[Path]
+ logger: "logging.Logger"
+ candidates: List[PluginCandidate]
+ plugins: List[PluginInfo]
+ _plugins_by_category: Dict[str, List[PluginInfo]]
+ has_warnings: bool = False
+
+ def __init__(self, plugin_places: List[Path]):
+ """Initialize the plugin manager."""
+ self.plugin_places = plugin_places
+ self.candidates = []
+ self.plugins = []
+ self._plugins_by_category = {}
+ self.logger = get_logger("PluginManager")
+
+ def locate_plugins(self) -> List[PluginCandidate]:
+ """Locate plugins in plugin_places."""
+ self.candidates = []
+
+ plugin_files: List[Path] = []
+ for place in self.plugin_places:
+ plugin_files += place.rglob("*.plugin")
+
+ for plugin_file in plugin_files:
+ source_dir = plugin_file.parent
+ config = configparser.ConfigParser()
+ config.read(plugin_file)
+ name = config["Core"]["name"]
+ module_name = config["Core"]["module"]
+ plugin_id = f"Plugin {name} from {plugin_file}"
+ description = None
+ if "Documentation" in config:
+ description = config["Documentation"].get("Description")
+ if "Nikola" not in config:
+ self.logger.warning(f"{plugin_id} does not specify Nikola configuration - plugin will not be loaded")
+ self.logger.warning("Please add a [Nikola] section to the {plugin_file} file with a PluginCategory entry")
+ self.has_warnings = True
+ continue
+ category = config["Nikola"].get("PluginCategory")
+ compiler = config["Nikola"].get("Compiler")
+ if not category:
+ self.logger.warning(f"{plugin_id} does not specify any category (Nikola.PluginCategory is missing in .plugin file) - plugin will not be loaded")
+ self.has_warnings = True
+ continue
+ if category in LEGACY_PLUGIN_NAMES:
+ category = LEGACY_PLUGIN_NAMES[category]
+ if category not in CATEGORY_NAMES:
+ self.logger.warning(f"{plugin_id} specifies invalid category '{category}' in the .plugin file - plugin will not be loaded")
+ self.has_warnings = True
+ continue
+ self.logger.debug(f"Discovered {plugin_id}")
+ self.candidates.append(
+ PluginCandidate(
+ name=name,
+ description=description,
+ plugin_id=plugin_id,
+ category=category,
+ compiler=compiler,
+ source_dir=source_dir,
+ module_name=module_name,
+ )
+ )
+ return self.candidates
+
+ def load_plugins(self, candidates: List[PluginCandidate]) -> None:
+ """Load selected candidate plugins."""
+ plugins_root = Path(__file__).parent.parent
+
+ for candidate in candidates:
+ name = candidate.name
+ module_name = candidate.module_name
+ source_dir = candidate.source_dir
+ py_file_location = source_dir / f"{module_name}.py"
+ plugin_id = candidate.plugin_id
+ if not py_file_location.exists():
+ py_file_location = source_dir / module_name / "__init__.py"
+ if not py_file_location.exists():
+ self.logger.warning(f"{plugin_id} could not be loaded (no valid module detected)")
+ self.has_warnings = True
+ continue
+
+ plugin_id += f" ({py_file_location})"
+ full_module_name = module_name
+
+ try:
+ name_parts = list(py_file_location.relative_to(plugins_root).parts)
+ if name_parts[-1] == "__init__.py":
+ name_parts.pop(-1)
+ elif name_parts[-1].endswith(".py"):
+ name_parts[-1] = name_parts[-1][:-3]
+ full_module_name = ".".join(name_parts)
+ except ValueError:
+ pass
+
+ try:
+ spec = importlib.util.spec_from_file_location(full_module_name, py_file_location)
+ module_object = importlib.util.module_from_spec(spec)
+ if full_module_name not in sys.modules:
+ sys.modules[full_module_name] = module_object
+ spec.loader.exec_module(module_object)
+ except Exception:
+ self.logger.exception(f"{plugin_id} threw an exception while loading")
+ self.has_warnings = True
+ continue
+
+ plugin_classes = [
+ c
+ for c in vars(module_object).values()
+ if isinstance(c, type) and issubclass(c, BasePlugin) and c not in CATEGORY_TYPES
+ ]
+ if len(plugin_classes) == 0:
+ self.logger.warning(f"{plugin_id} does not have any plugin classes - plugin will not be loaded")
+ self.has_warnings = True
+ continue
+ elif len(plugin_classes) > 1:
+ self.logger.warning(f"{plugin_id} has multiple plugin classes; this is not supported - plugin will not be loaded")
+ self.has_warnings = True
+ continue
+
+ plugin_class = plugin_classes[0]
+
+ if not issubclass(plugin_class, CATEGORIES[candidate.category]):
+ self.logger.warning(f"{plugin_id} has category '{candidate.category}' in the .plugin file, but the implementation class {plugin_class} does not inherit from this category - plugin will not be loaded")
+ self.has_warnings = True
+ continue
+
+ try:
+ plugin_object = plugin_class()
+ except Exception:
+ self.logger.exception(f"{plugin_id} threw an exception while creating the instance")
+ self.has_warnings = True
+ continue
+ self.logger.debug(f"Loaded {plugin_id}")
+ info = PluginInfo(
+ name=name,
+ description=candidate.description,
+ plugin_id=candidate.plugin_id,
+ category=candidate.category,
+ compiler=candidate.compiler,
+ source_dir=source_dir,
+ module_name=module_name,
+ module_object=module_object,
+ plugin_object=plugin_object,
+ )
+ self.plugins.append(info)
+
+ self._plugins_by_category = {category: [] for category in CATEGORY_NAMES}
+ for plugin_info in self.plugins:
+ self._plugins_by_category[plugin_info.category].append(plugin_info)
+
+ if self.has_warnings:
+ self.logger.warning("Some plugins failed to load. Please review the above warning messages.")
+ # TODO remove following messages and delay in v8.3.1
+ self.logger.warning("You may need to update some plugins (from plugins.getnikola.com) or to fix their .plugin files.")
+ self.logger.warning("Waiting 2 seconds before continuing.")
+ time.sleep(2)
+
+ def get_plugins_of_category(self, category: str) -> List[PluginInfo]:
+ """Get loaded plugins of a given category."""
+ return self._plugins_by_category.get(category, [])
+
+ def get_plugin_by_name(self, name: str, category: Optional[str] = None) -> Optional[PluginInfo]:
+ """Get a loaded plugin by name and optionally by category. Returns None if no such plugin is loaded."""
+ for p in self.plugins:
+ if p.name == name and (category is None or p.category == category):
+ return p
+
+ # Aliases for Yapsy compatibility
+ # TODO: remove in v9
+ def getPluginsOfCategory(self, category: str) -> List[PluginInfo]:
+ """Get loaded plugins of a given category."""
+ self.logger.warning("Legacy getPluginsOfCategory method was used, it may be removed in the future. Please change it to get_plugins_of_category.")
+ return self._plugins_by_category.get(category, [])
+
+ # TODO: remove in v9
+ def getPluginByName(self, name: str, category: Optional[str] = None) -> Optional[PluginInfo]:
+ """Get a loaded plugin by name and optionally by category. Returns None if no such plugin is loaded."""
+ self.logger.warning("Legacy getPluginByName method was used, it may be removed in the future. Please change it to get_plugin_by_name.")
+ return self.get_plugin_by_name(name, category)
diff --git a/nikola/plugins/command/import_wordpress.py b/nikola/plugins/command/import_wordpress.py
index e419c8a1b..27f58b0da 100644
--- a/nikola/plugins/command/import_wordpress.py
+++ b/nikola/plugins/command/import_wordpress.py
@@ -66,7 +66,7 @@ def install_plugin(site, plugin_name, output_dir=None, show_install_notes=False)
"""Install a Nikola plugin."""
LOGGER.info("Installing plugin '{0}'".format(plugin_name))
# Get hold of the 'plugin' plugin
- plugin_installer_info = site.plugin_manager.getPluginByName('plugin', 'Command')
+ plugin_installer_info = site.plugin_manager.get_plugin_by_name('plugin', 'Command')
if plugin_installer_info is None:
LOGGER.error('Internal error: cannot find the "plugin" plugin which is supposed to come with Nikola!')
return False
@@ -236,10 +236,9 @@ def _get_compiler(self):
self._find_wordpress_compiler()
if self.wordpress_page_compiler is not None:
return self.wordpress_page_compiler
- plugin_info = self.site.plugin_manager.getPluginByName('markdown', 'PageCompiler')
+ plugin_info = self.site.plugin_manager.get_plugin_by_name('markdown', 'PageCompiler')
if plugin_info is not None:
if not plugin_info.is_activated:
- self.site.plugin_manager.activatePluginByName(plugin_info.name)
plugin_info.plugin_object.set_site(self.site)
return plugin_info.plugin_object
else:
@@ -249,7 +248,7 @@ def _find_wordpress_compiler(self):
"""Find WordPress compiler plugin."""
if self.wordpress_page_compiler is not None:
return
- plugin_info = self.site.plugin_manager.getPluginByName('wordpress', 'PageCompiler')
+ plugin_info = self.site.plugin_manager.get_plugin_by_name('wordpress', 'PageCompiler')
if plugin_info is not None:
if not plugin_info.is_activated:
self.site.plugin_manager.activatePluginByName(plugin_info.name)
diff --git a/nikola/plugins/command/new_page.py b/nikola/plugins/command/new_page.py
index cde5e5c6c..780e5db2f 100644
--- a/nikola/plugins/command/new_page.py
+++ b/nikola/plugins/command/new_page.py
@@ -109,5 +109,5 @@ def _execute(self, options, args):
options['date-path'] = False
# Even though stuff was split into `new_page`, it’s easier to do it
# there not to duplicate the code.
- p = self.site.plugin_manager.getPluginByName('new_post', 'Command').plugin_object
+ p = self.site.plugin_manager.get_plugin_by_name('new_post', 'Command').plugin_object
return p.execute(options, args)
diff --git a/nikola/plugins/command/new_post.py b/nikola/plugins/command/new_post.py
index 45ca1a11f..2c03fa5c7 100644
--- a/nikola/plugins/command/new_post.py
+++ b/nikola/plugins/command/new_post.py
@@ -216,9 +216,7 @@ class CommandNewPost(Command):
def _execute(self, options, args):
"""Create a new post or page."""
global LOGGER
- compiler_names = [p.name for p in
- self.site.plugin_manager.getPluginsOfCategory(
- "PageCompiler")]
+ compiler_names = [p.name for p in self.site.plugin_manager.get_plugins_of_category("PageCompiler")]
if len(args) > 1:
print(self.help())
@@ -298,7 +296,7 @@ def _execute(self, options, args):
self.print_compilers()
return
- compiler_plugin = self.site.plugin_manager.getPluginByName(
+ compiler_plugin = self.site.plugin_manager.get_plugin_by_name(
content_format, "PageCompiler").plugin_object
# Guess where we should put this
diff --git a/nikola/plugins/command/rst2html/__init__.py b/nikola/plugins/command/rst2html/__init__.py
index a133bd5ec..d2854df94 100644
--- a/nikola/plugins/command/rst2html/__init__.py
+++ b/nikola/plugins/command/rst2html/__init__.py
@@ -44,7 +44,7 @@ class CommandRst2Html(Command):
def _execute(self, options, args):
"""Compile reStructuredText to standalone HTML files."""
- compiler = self.site.plugin_manager.getPluginByName('rest', 'PageCompiler').plugin_object
+ compiler = self.site.plugin_manager.get_plugin_by_name('rest', 'PageCompiler').plugin_object
if len(args) != 1:
print("This command takes only one argument (input file name).")
return 2
diff --git a/nikola/plugins/compile/pandoc.py b/nikola/plugins/compile/pandoc.py
index c79c4d88e..f51025617 100644
--- a/nikola/plugins/compile/pandoc.py
+++ b/nikola/plugins/compile/pandoc.py
@@ -62,10 +62,10 @@ def _get_pandoc_options(self, source: str) -> List[str]:
try:
pandoc_options = list(config_options[ext])
except KeyError:
- self.logger.warn('Setting PANDOC_OPTIONS to [], because extension {} is not defined in PANDOC_OPTIONS: {}.'.format(ext, config_options))
+ self.logger.warning('Setting PANDOC_OPTIONS to [], because extension {} is not defined in PANDOC_OPTIONS: {}.'.format(ext, config_options))
pandoc_options = []
else:
- self.logger.warn('Setting PANDOC_OPTIONS to [], because PANDOC_OPTIONS is expected to be of type Union[List[str], Dict[str, List[str]]] but this is not: {}'.format(config_options))
+ self.logger.warning('Setting PANDOC_OPTIONS to [], because PANDOC_OPTIONS is expected to be of type Union[List[str], Dict[str, List[str]]] but this is not: {}'.format(config_options))
pandoc_options = []
return pandoc_options
diff --git a/nikola/plugins/compile/rest/chart.py b/nikola/plugins/compile/rest/chart.py
index d217c1bf2..558fe7c90 100644
--- a/nikola/plugins/compile/rest/chart.py
+++ b/nikola/plugins/compile/rest/chart.py
@@ -153,7 +153,7 @@ class Chart(Directive):
def run(self):
"""Run the directive."""
self.options['site'] = None
- html = _site.plugin_manager.getPluginByName(
+ html = _site.plugin_manager.get_plugin_by_name(
'chart', 'ShortcodePlugin').plugin_object.handler(
self.arguments[0],
data='\n'.join(self.content),
diff --git a/nikola/plugins/compile/rest/post_list.py b/nikola/plugins/compile/rest/post_list.py
index f5b86baef..9f6607364 100644
--- a/nikola/plugins/compile/rest/post_list.py
+++ b/nikola/plugins/compile/rest/post_list.py
@@ -88,7 +88,7 @@ def run(self):
date = self.options.get('date')
filename = self.state.document.settings._nikola_source_path
- output, deps = self.site.plugin_manager.getPluginByName(
+ output, deps = self.site.plugin_manager.get_plugin_by_name(
'post_list', 'ShortcodePlugin').plugin_object.handler(
start,
stop,
diff --git a/nikola/plugins/misc/scan_posts.plugin b/nikola/plugins/misc/scan_posts.plugin
index f4af81127..0fb946c79 100644
--- a/nikola/plugins/misc/scan_posts.plugin
+++ b/nikola/plugins/misc/scan_posts.plugin
@@ -8,3 +8,5 @@ Version = 1.0
Website = https://getnikola.com/
Description = Scan posts and create timeline
+[Nikola]
+PluginCategory = PostScanner
diff --git a/nikola/plugins/shortcode/chart.plugin b/nikola/plugins/shortcode/chart.plugin
index edcbc1310..be1fbc6ef 100644
--- a/nikola/plugins/shortcode/chart.plugin
+++ b/nikola/plugins/shortcode/chart.plugin
@@ -3,7 +3,7 @@ name = chart
module = chart
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Roberto Alsina
diff --git a/nikola/plugins/shortcode/emoji.plugin b/nikola/plugins/shortcode/emoji.plugin
index c9a272cdc..4c09f0315 100644
--- a/nikola/plugins/shortcode/emoji.plugin
+++ b/nikola/plugins/shortcode/emoji.plugin
@@ -3,7 +3,7 @@ name = emoji
module = emoji
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Roberto Alsina
diff --git a/nikola/plugins/shortcode/gist.plugin b/nikola/plugins/shortcode/gist.plugin
index b61076383..ee62c2706 100644
--- a/nikola/plugins/shortcode/gist.plugin
+++ b/nikola/plugins/shortcode/gist.plugin
@@ -3,7 +3,7 @@ name = gist
module = gist
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Roberto Alsina
diff --git a/nikola/plugins/shortcode/listing.plugin b/nikola/plugins/shortcode/listing.plugin
index 90fb6ebb2..70fa1cf41 100644
--- a/nikola/plugins/shortcode/listing.plugin
+++ b/nikola/plugins/shortcode/listing.plugin
@@ -3,7 +3,7 @@ name = listing_shortcode
module = listing
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Roberto Alsina
diff --git a/nikola/plugins/shortcode/post_list.plugin b/nikola/plugins/shortcode/post_list.plugin
index 494a1d875..9c39eb9e9 100644
--- a/nikola/plugins/shortcode/post_list.plugin
+++ b/nikola/plugins/shortcode/post_list.plugin
@@ -3,7 +3,7 @@ name = post_list
module = post_list
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Udo Spallek
diff --git a/nikola/plugins/shortcode/thumbnail.plugin b/nikola/plugins/shortcode/thumbnail.plugin
index e55d34f6c..bd3616900 100644
--- a/nikola/plugins/shortcode/thumbnail.plugin
+++ b/nikola/plugins/shortcode/thumbnail.plugin
@@ -3,7 +3,7 @@ name = thumbnail
module = thumbnail
[Nikola]
-PluginCategory = Shortcode
+PluginCategory = ShortcodePlugin
[Documentation]
author = Chris Warrick
diff --git a/nikola/plugins/task/bundles.plugin b/nikola/plugins/task/bundles.plugin
index 939065b7c..4afc3ecd3 100644
--- a/nikola/plugins/task/bundles.plugin
+++ b/nikola/plugins/task/bundles.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Bundle assets
[Nikola]
-PluginCategory = Task
+PluginCategory = LateTask
diff --git a/nikola/plugins/task/gzip.plugin b/nikola/plugins/task/gzip.plugin
index 70e966b83..b1aab25dc 100644
--- a/nikola/plugins/task/gzip.plugin
+++ b/nikola/plugins/task/gzip.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Create gzipped copies of files
[Nikola]
-PluginCategory = Task
+PluginCategory = TaskMultiplier
diff --git a/nikola/plugins/task/listings.py b/nikola/plugins/task/listings.py
index 4c1636e55..f4933e937 100644
--- a/nikola/plugins/task/listings.py
+++ b/nikola/plugins/task/listings.py
@@ -113,7 +113,7 @@ def render_listing(in_name, out_name, input_folder, output_folder, folders=[], f
needs_ipython_css = False
if in_name and in_name.endswith('.ipynb'):
# Special handling: render ipynbs in listings (Issue #1900)
- ipynb_plugin = self.site.plugin_manager.getPluginByName("ipynb", "PageCompiler")
+ ipynb_plugin = self.site.plugin_manager.get_plugin_by_name("ipynb", "PageCompiler")
if ipynb_plugin is None:
msg = "To use .ipynb files as listings, you must set up the Jupyter compiler in COMPILERS and POSTS/PAGES."
utils.LOGGER.error(msg)
diff --git a/nikola/plugins/task/robots.plugin b/nikola/plugins/task/robots.plugin
index 51f778183..81c4c9a6b 100644
--- a/nikola/plugins/task/robots.plugin
+++ b/nikola/plugins/task/robots.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Generate /robots.txt exclusion file and promote sitemap.
[Nikola]
-PluginCategory = Task
+PluginCategory = LateTask
diff --git a/nikola/plugins/task/sitemap.plugin b/nikola/plugins/task/sitemap.plugin
index c8aa83239..8367d8eca 100644
--- a/nikola/plugins/task/sitemap.plugin
+++ b/nikola/plugins/task/sitemap.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Generate google sitemap.
[Nikola]
-PluginCategory = Task
+PluginCategory = LateTask
diff --git a/nikola/plugins/task/sitemap.py b/nikola/plugins/task/sitemap.py
index bc9a5d656..3c045eb0d 100644
--- a/nikola/plugins/task/sitemap.py
+++ b/nikola/plugins/task/sitemap.py
@@ -309,7 +309,7 @@ def get_lastmod(self, p):
# RFC 3339 (web ISO 8601 profile) represented in UTC with Zulu
# zone desgignator as recommeded for sitemaps. Second and
# microsecond precision is stripped for compatibility.
- lastmod = datetime.datetime.utcfromtimestamp(os.stat(p).st_mtime).replace(tzinfo=dateutil.tz.gettz('UTC'), second=0, microsecond=0).isoformat().replace('+00:00', 'Z')
+ lastmod = datetime.datetime.fromtimestamp(os.stat(p).st_mtime, dateutil.tz.tzutc()).replace(second=0, microsecond=0).isoformat().replace('+00:00', 'Z')
return lastmod
diff --git a/nikola/plugins/template/jinja.plugin b/nikola/plugins/template/jinja.plugin
index 629b20e88..45dd62164 100644
--- a/nikola/plugins/template/jinja.plugin
+++ b/nikola/plugins/template/jinja.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Support for Jinja2 templates.
[Nikola]
-PluginCategory = Template
+PluginCategory = TemplateSystem
diff --git a/nikola/plugins/template/mako.plugin b/nikola/plugins/template/mako.plugin
index 2d353bf1d..a46575255 100644
--- a/nikola/plugins/template/mako.plugin
+++ b/nikola/plugins/template/mako.plugin
@@ -9,5 +9,5 @@ website = https://getnikola.com/
description = Support for Mako templates.
[Nikola]
-PluginCategory = Template
+PluginCategory = TemplateSystem
diff --git a/nikola/post.py b/nikola/post.py
index 1dcd33d60..d4172d548 100644
--- a/nikola/post.py
+++ b/nikola/post.py
@@ -350,8 +350,8 @@ def _set_date(self, default_metadata):
if self.config['__invariant__']:
default_metadata['date'] = datetime.datetime(2013, 12, 31, 23, 59, 59, tzinfo=self.config['__tzinfo__'])
else:
- default_metadata['date'] = datetime.datetime.utcfromtimestamp(
- os.stat(self.source_path).st_ctime).replace(tzinfo=dateutil.tz.tzutc()).astimezone(self.config['__tzinfo__'])
+ default_metadata['date'] = datetime.datetime.fromtimestamp(
+ os.stat(self.source_path).st_ctime, dateutil.tz.tzutc()).astimezone(self.config['__tzinfo__'])
# If time zone is set, build localized datetime.
try:
diff --git a/requirements.txt b/requirements.txt
index e4ef1a36a..5e7f0b01b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -7,7 +7,6 @@ mako>=1.0.0
Markdown>=3.0.0
unidecode>=0.04.16
lxml>=3.3.5
-Yapsy>=1.12.0
PyRSS2Gen>=1.1
blinker>=1.3
setuptools>=24.2.0
diff --git a/setup.py b/setup.py
index f2f5615ad..5db7f8947 100755
--- a/setup.py
+++ b/setup.py
@@ -133,6 +133,7 @@ def run(self):
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
+ 'Programming Language :: Python :: 3.12',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Text Processing :: Markup'],
diff --git a/snapcraft.yaml b/snapcraft.yaml
index 50962eaa6..bd7ce8b5f 100644
--- a/snapcraft.yaml
+++ b/snapcraft.yaml
@@ -40,7 +40,6 @@ parts:
- mako
- unidecode
- lxml
- - Yapsy
- PyRSS2Gen
- blinker
- setuptools
| diff --git a/tests/data/plugin_manager/broken.plugin b/tests/data/plugin_manager/broken.plugin
new file mode 100644
index 000000000..1a5f9e05c
--- /dev/null
+++ b/tests/data/plugin_manager/broken.plugin
@@ -0,0 +1,12 @@
+[Core]
+name = broken
+module = broken
+
+[Documentation]
+author = Chris Warrick
+version = 1.0
+website = https://getnikola.com/
+description = Broken (wrong category)
+
+[Nikola]
+PluginCategory = Task
diff --git a/tests/data/plugin_manager/broken.py b/tests/data/plugin_manager/broken.py
new file mode 100644
index 000000000..68af857cb
--- /dev/null
+++ b/tests/data/plugin_manager/broken.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+
+# Copyright © 2012-2024 Chris Warrick and others.
+
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the
+# Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice
+# shall be included in all copies or substantial portions of
+# the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""The second plugin."""
+
+from nikola.plugin_categories import TemplateSystem
+
+
+class BrokenPlugin(TemplateSystem):
+ """The TemplateSystem plugin whose .plugin file says it’s a Task plugin."""
+
+ name = "broken"
+ broken_site_set = False
+
+ def set_site(self, site):
+ super().set_site(site)
+ print("Site for broken was set")
+ self.broken_site_set = True
+ raise Exception("Site for broken was set")
diff --git a/tests/data/plugin_manager/first.plugin b/tests/data/plugin_manager/first.plugin
new file mode 100644
index 000000000..cae444202
--- /dev/null
+++ b/tests/data/plugin_manager/first.plugin
@@ -0,0 +1,13 @@
+[Core]
+name = first
+module = one
+
+[Documentation]
+author = Chris Warrick
+version = 1.0
+website = https://getnikola.com/
+description = Do one thing
+
+[Nikola]
+PluginCategory = Command
+compiler = foo
diff --git a/tests/data/plugin_manager/one.py b/tests/data/plugin_manager/one.py
new file mode 100644
index 000000000..817bd0770
--- /dev/null
+++ b/tests/data/plugin_manager/one.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+
+# Copyright © 2012-2024 Chris Warrick and others.
+
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the
+# Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice
+# shall be included in all copies or substantial portions of
+# the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""The first command."""
+
+from nikola.plugin_categories import Command
+
+
+class CommandOne(Command):
+ """The first command."""
+
+ name = "one"
+ doc_purpose = "do one thing"
+ doc_description = "Do a thing."
+ one_site_set = False
+
+ def set_site(self, site):
+ super().set_site(site)
+ print("Site for 1 was set")
+ self.one_site_set = True
+
+ def _execute(self, options, args):
+ """Run the command."""
+ print("Hello world!")
diff --git a/tests/data/plugin_manager/second/second.plugin b/tests/data/plugin_manager/second/second.plugin
new file mode 100644
index 000000000..ad1e4b8ca
--- /dev/null
+++ b/tests/data/plugin_manager/second/second.plugin
@@ -0,0 +1,13 @@
+[Core]
+name = 2nd
+module = two
+
+[Documentation]
+author = Chris Warrick
+version = 1.0
+website = https://getnikola.com/
+description = Do another thing
+
+[Nikola]
+PluginCategory = ConfigPlugin
+
diff --git a/tests/data/plugin_manager/second/two/__init__.py b/tests/data/plugin_manager/second/two/__init__.py
new file mode 100644
index 000000000..14794c07e
--- /dev/null
+++ b/tests/data/plugin_manager/second/two/__init__.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+
+# Copyright © 2012-2024 Chris Warrick and others.
+
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the
+# Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice
+# shall be included in all copies or substantial portions of
+# the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""The second plugin."""
+
+from nikola.plugin_categories import ConfigPlugin
+
+
+class TwoConfigPlugin(ConfigPlugin):
+ """The second plugin."""
+
+ name = "2nd"
+ two_site_set = False
+
+ def set_site(self, site):
+ super().set_site(site)
+ print("Site for 2 was set")
+ self.two_site_set = True
diff --git a/tests/helper.py b/tests/helper.py
index a39ad88f7..8fbebdb45 100644
--- a/tests/helper.py
+++ b/tests/helper.py
@@ -6,23 +6,12 @@
"""
import os
+import pathlib
from contextlib import contextmanager
-from yapsy.PluginManager import PluginManager
-
-import nikola.utils
import nikola.shortcodes
-from nikola.plugin_categories import (
- Command,
- Task,
- LateTask,
- TemplateSystem,
- PageCompiler,
- TaskMultiplier,
- CompilerExtension,
- MarkdownExtension,
- RestExtension,
-)
+import nikola.utils
+from nikola.plugin_manager import PluginManager
__all__ = ["cd", "FakeSite"]
@@ -55,24 +44,11 @@ def __init__(self):
"TRANSLATIONS": {"en": ""},
}
self.EXTRA_PLUGINS = self.config["EXTRA_PLUGINS"]
- self.plugin_manager = PluginManager(
- categories_filter={
- "Command": Command,
- "Task": Task,
- "LateTask": LateTask,
- "TemplateSystem": TemplateSystem,
- "PageCompiler": PageCompiler,
- "TaskMultiplier": TaskMultiplier,
- "CompilerExtension": CompilerExtension,
- "MarkdownExtension": MarkdownExtension,
- "RestExtension": RestExtension,
- }
- )
+ places = [pathlib.Path(nikola.utils.__file__).parent / "plugins"]
+ self.plugin_manager = PluginManager(plugin_places=places)
self.shortcode_registry = {}
- self.plugin_manager.setPluginInfoExtension("plugin")
- places = [os.path.join(os.path.dirname(nikola.utils.__file__), "plugins")]
- self.plugin_manager.setPluginPlaces(places)
- self.plugin_manager.collectPlugins()
+ candidates = self.plugin_manager.locate_plugins()
+ self.plugin_manager.load_plugins(candidates)
self.compiler_extensions = self._activate_plugins_of_category(
"CompilerExtension"
)
@@ -88,13 +64,9 @@ def _activate_plugins_of_category(self, category):
"""Activate all the plugins of a given category and return them."""
# this code duplicated in nikola/nikola.py
plugins = []
- for plugin_info in self.plugin_manager.getPluginsOfCategory(category):
- if plugin_info.name in self.config.get("DISABLED_PLUGINS"):
- self.plugin_manager.removePluginFromCategory(plugin_info, category)
- else:
- self.plugin_manager.activatePluginByName(plugin_info.name)
- plugin_info.plugin_object.set_site(self)
- plugins.append(plugin_info)
+ for plugin_info in self.plugin_manager.get_plugins_of_category(category):
+ plugin_info.plugin_object.set_site(self)
+ plugins.append(plugin_info)
return plugins
def render_template(self, name, _, context):
diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py
new file mode 100644
index 000000000..8deb7a60b
--- /dev/null
+++ b/tests/test_plugin_manager.py
@@ -0,0 +1,142 @@
+# -*- coding: utf-8 -*-
+
+# Copyright © 2012-2024 Chris Warrick and others.
+
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the
+# Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice
+# shall be included in all copies or substantial portions of
+# the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+import nikola.plugin_manager
+
+from .helper import FakeSite
+from nikola.plugin_manager import PluginManager
+from pathlib import Path
+
+
+def test_locate_plugins_finds_core_plugins():
+ """Ensure that locate_plugins can find some core plugins."""
+ places = [Path(nikola.plugin_manager.__file__).parent / "plugins"]
+ plugin_manager = PluginManager(places)
+ candidates = plugin_manager.locate_plugins()
+ plugin_names = [p.name for p in candidates]
+ assert plugin_manager.candidates == candidates
+
+ assert "emoji" in plugin_names
+ assert "copy_assets" in plugin_names
+ assert "scan_posts" in plugin_names
+
+ template_plugins = [p for p in candidates if p.category == "TemplateSystem"]
+ template_plugins.sort(key=lambda p: p.name)
+ assert len(template_plugins) == 2
+ assert template_plugins[0].name == "jinja"
+ assert template_plugins[1].name == "mako"
+
+
+def test_locate_plugins_finds_core_and_custom_plugins():
+ """Ensure that locate_plugins can find some custom plugins."""
+ places = [
+ Path(nikola.plugin_manager.__file__).parent / "plugins",
+ Path(__file__).parent / "data" / "plugin_manager",
+ ]
+ plugin_manager = PluginManager(places)
+ candidates = plugin_manager.locate_plugins()
+ plugin_names = [p.name for p in candidates]
+ assert plugin_manager.candidates == candidates
+
+ assert "emoji" in plugin_names
+ assert "copy_assets" in plugin_names
+ assert "scan_posts" in plugin_names
+
+ assert "first" in plugin_names
+ assert "2nd" in plugin_names
+
+ first_plugin = next(p for p in candidates if p.name == "first")
+ second_plugin = next(p for p in candidates if p.name == "2nd")
+
+ assert first_plugin.category == "Command"
+ assert first_plugin.compiler == "foo"
+ assert first_plugin.source_dir == places[1]
+
+ assert second_plugin.category == "ConfigPlugin"
+ assert second_plugin.compiler is None
+ assert second_plugin.source_dir == places[1] / "second"
+
+
+def test_load_plugins():
+ """Ensure that locate_plugins can load some core and custom plugins."""
+ places = [
+ Path(nikola.plugin_manager.__file__).parent / "plugins",
+ Path(__file__).parent / "data" / "plugin_manager",
+ ]
+ plugin_manager = PluginManager(places)
+ candidates = plugin_manager.locate_plugins()
+ plugins_to_load = [p for p in candidates if p.name in {"first", "2nd", "emoji"}]
+
+ plugin_manager.load_plugins(plugins_to_load)
+
+ assert len(plugin_manager.plugins) == 3
+ assert plugin_manager._plugins_by_category["ShortcodePlugin"][0].name == "emoji"
+ assert plugin_manager._plugins_by_category["Command"][0].name == "first"
+ assert plugin_manager._plugins_by_category["ConfigPlugin"][0].name == "2nd"
+
+ site = FakeSite()
+ for plugin in plugin_manager.plugins:
+ plugin.plugin_object.set_site(site)
+
+ assert "emoji" in site.shortcode_registry
+ assert plugin_manager.get_plugin_by_name("first", "Command").plugin_object.one_site_set
+ assert plugin_manager.get_plugin_by_name("2nd").plugin_object.two_site_set
+ assert plugin_manager.get_plugin_by_name("2nd", "Command") is None
+
+
+def test_load_plugins_twice():
+ """Ensure that extra plugins can be added."""
+ places = [
+ Path(nikola.plugin_manager.__file__).parent / "plugins",
+ Path(__file__).parent / "data" / "plugin_manager",
+ ]
+ plugin_manager = PluginManager(places)
+ candidates = plugin_manager.locate_plugins()
+ plugins_to_load_first = [p for p in candidates if p.name in {"first", "emoji"}]
+ plugins_to_load_second = [p for p in candidates if p.name in {"2nd"}]
+
+ plugin_manager.load_plugins(plugins_to_load_first)
+ assert len(plugin_manager.plugins) == 2
+ plugin_manager.load_plugins(plugins_to_load_second)
+ assert len(plugin_manager.plugins) == 3
+
+
+def test_load_plugins_skip_mismatching_category(caplog):
+ """If a plugin specifies a different category than it actually implements, refuse to load it."""
+ places = [
+ Path(__file__).parent / "data" / "plugin_manager",
+ ]
+ plugin_manager = PluginManager(places)
+ candidates = plugin_manager.locate_plugins()
+ plugins_to_load = [p for p in candidates if p.name in {"broken"}]
+ plugin_to_load = plugins_to_load[0]
+ assert len(plugins_to_load) == 1
+
+ plugin_manager.load_plugins(plugins_to_load)
+
+ py_file = plugin_to_load.source_dir / "broken.py"
+ assert f"{plugin_to_load.plugin_id} ({py_file}) has category '{plugin_to_load.category}' in the .plugin file, but the implementation class <class 'tests.data.plugin_manager.broken.BrokenPlugin'> does not inherit from this category - plugin will not be loaded" in caplog.text
+ assert len(plugin_manager.plugins) == 0
diff --git a/tests/test_template_shortcodes.py b/tests/test_template_shortcodes.py
index c6c948da9..148f7e609 100644
--- a/tests/test_template_shortcodes.py
+++ b/tests/test_template_shortcodes.py
@@ -67,7 +67,7 @@ class ShortcodeFakeSite(Nikola):
def _get_template_system(self):
if self._template_system is None:
# Load template plugin
- self._template_system = self.plugin_manager.getPluginByName(
+ self._template_system = self.plugin_manager.get_plugin_by_name(
"jinja", "TemplateSystem"
).plugin_object
self._template_system.set_directories(".", "cache")
| Templates can no longer be found in plugins
### Environment
**Python Version:** 3.11.6
**Nikola Version:** GitHub master
**Operating System:** Linux
### Description:
```pytb
Traceback (most recent call last):
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/mako/lookup.py", line 240, in get_template
return self._check(uri, self._collection[uri])
~~~~~~~~~~~~~~~~^^^^^
KeyError: 'localsearch.tmpl'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/doit/doit_cmd.py", line 294, in run
return command.parse_execute(args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/doit/cmd_base.py", line 150, in parse_execute
return self.execute(params, args)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/doit/cmd_base.py", line 556, in execute
self.task_list = self.loader.load_tasks(cmd=self, pos_args=args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/git/nikola/nikola/__main__.py", line 285, in load_tasks
tasks = generate_tasks(
^^^^^^^^^^^^^^^
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/doit/loader.py", line 390, in generate_tasks
for task_dict, x_doc in flat_generator(gen_result, gen_doc):
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/doit/loader.py", line 27, in flat_generator
for item in gen:
File "/home/kwpolska/git/nikola/nikola/nikola.py", line 2093, in gen_tasks
for task in flatten(pluginInfo.plugin_object.gen_tasks()):
File "/home/kwpolska/git/nikola/nikola/nikola.py", line 2087, in flatten
for t in task:
File "/home/kwpolska/git/nikola/nikola/plugins/task/pages.py", line 66, in gen_tasks
for task in self.site.generic_page_renderer(lang, post, kw["filters"], context):
File "/home/kwpolska/git/nikola/nikola/nikola.py", line 2395, in generic_page_renderer
yield self.generic_renderer(lang, output_name, post.template_name, filters,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/git/nikola/nikola/nikola.py", line 2305, in generic_renderer
file_deps += self.template_system.template_deps(template_name, template_dep_context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/git/nikola/nikola/plugins/template/mako.py", line 135, in template_deps
template = self.lookup.get_template(template_name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/kwpolska/virtualenvs/nikola/lib64/python3.11/site-packages/mako/lookup.py", line 253, in get_template
raise exceptions.TopLevelLookupException(
mako.exceptions.TopLevelLookupException: Can't locate template for uri 'localsearch.tmpl'
```
| 2024-01-02T23:22:05Z | 2024-01-07T12:43:54Z | [] | [] | ["tests/integration/test_future_post.py::test_archive_exists", "tests/integration/test_dev_server.py::test_basepath[http://local.host:456/-]", "tests/test_command_import_wordpress.py::test_transform_multiple_captions_in_a_post", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-index:path/to/tags.html]", "tests/integration/test_page_index_pretty_urls.py::test_page_index[subdir3-page4]", "tests/test_shortcodes.py::test_data[test({{% arg \"123 foo\" foobar foo=bar baz=\"quotes rock.\" %}}Hello test suite!!{{% /arg %}})-test(arg ('123 foo', 'foobar')/[('baz', 'quotes rock.'), ('foo', 'bar')]/Hello test suite!!)]", "tests/test_slugify.py::test_slugify[ASCII with fancy characters]", "tests/integration/test_page_index_pretty_urls.py::test_check_files", "tests/test_task_scale_images.py::test_handling_icc_profiles[with icc filename-profiles preserved]", "tests/integration/test_future_post.py::test_future_post_not_in_indexes[sitemap.xml]", "tests/integration/test_translated_content_secondary_language.py::test_archive_exists", "tests/test_rst_compiler.py::test_rendering_codeblock_alias[.. code-block:: python\\n\\n import antigravity]", "tests/test_utils.py::test_get_crumbs[listings/foo/bar-True-expected_crumbs2]", "tests/integration/test_dev_server.py::test_basepath[http://local.host-]", "tests/test_slugify.py::test_slugify[ASCII two words]", "tests/test_slugify.py::test_slugify[ASCII with dashes]", "tests/test_task_scale_images.py::test_handling_icc_profiles[without icc filename-profiles preserved]", "tests/integration/test_page_index_normal_urls.py::test_page_index[subdir3-page4]", "tests/integration/test_dev_server.py::test_basepath[https://localhost/-]", "tests/integration/test_page_index_pretty_urls.py::test_page_index[subdir2-page3]", "tests/test_locale.py::test_format_date_in_string_month_day_year_gb[pl]", "tests/test_utils.py::test_write_metadata_with_formats[yaml----\\na: '1'\\nb: '2'\\nslug: hello-world\\ntitle: Hello, world!\\n---\\n]", "tests/test_template_shortcodes.py::test_applying_shortcode[data={{ data }}-{{% test1 %}}spamm spamm{{% /test1 %}}-data=spamm spamm]", "tests/test_utils.py::test_bool_from_meta[0-False0]", "tests/test_rst_compiler.py::test_soundcloud_iframe", "tests/integration/test_archive_per_month.py::test_check_files", "tests/test_locale.py::test_format_date_in_string_month_day_year[default]", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-index:tags.html]", "tests/integration/test_redirection.py::test_absolute_redirection", "tests/test_slugify.py::test_slugify[Polish diacritical characters and fancy characters]", "tests/test_metadata_extractors.py::test_compiler_metadata[CompileHtml-html-html-HTML]", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[yaml-YAML-1-onefile-twofile]", "tests/test_utils.py::test_get_asset_path[assets/css/nikola_rst.css-files_folders0-nikola/data/themes/base/assets/css/nikola_rst.css]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-index:path/to/tags.html]", "tests/test_locale.py::test_initilalize_failure[]", "tests/integration/test_translated_content.py::test_avoid_double_slash_in_rss", "tests/test_metadata_extractors.py::test_check_conditions[conditions0]", "tests/integration/test_archive_full.py::test_check_files", "tests/integration/test_building_in_subdir.py::test_index_in_sitemap", "tests/test_utils.py::test_bool_from_meta[false-False]", "tests/test_command_import_wordpress_translation.py::test_split_a_two_language_post", "tests/test_shortcodes.py::test_errors[{{% start \"asdf %}}-^Unexpected end of unquoted string]", "tests/test_scheduling.py::test_current_time_matching_rule_no_given_date[False]", "tests/integration/test_check_absolute_subfolder.py::test_check_links", "tests/integration/test_dev_server.py::test_basepath[http://localhost/-]", "tests/test_utils.py::test_bool_from_meta[0-False2]", "tests/test_template_shortcodes.py::test_applying_shortcode[arg={{ _args[0] }}-{{% test1 onearg %}}-arg=onearg]", "tests/test_utils.py::test_bool_from_meta[1-True0]", "tests/integration/test_empty_build.py::test_archive_exists", "tests/test_slugify.py::test_disarmed[polish with banned characters]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-base:/path/with/leading/slash]", "tests/test_compile_markdown.py::test_compiling_markdown[empty]", "tests/test_utils.py::test_bool_from_meta[Yes-True]", "tests/test_utils.py::test_write_metadata_default", "tests/integration/test_translated_content.py::test_check_files", "tests/test_command_import_wordpress_translation.py::test_legacy_split_a_two_language_post[withintermission]", "tests/test_metadata_extractors.py::test_compiler_metadata[CompileIPynb-ipynb-ipynb-Jupyter Notebook]", "tests/test_utils.py::test_demoting_headers[by minus one]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-base:path/with/trailing/slash/]", "tests/integration/test_page_index_normal_urls.py::test_page_index_in_subdir[subdir2-index.html]", "tests/test_locale.py::test_format_date_locale_variants[GB]", "tests/integration/test_archive_per_day.py::test_index_in_sitemap", "tests/test_shortcodes.py::test_errors[{{% start a\"b\" %}}-^Unexpected quotation mark in unquoted string]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[authors-base:]", "tests/test_utils.py::test_bool_from_meta[unknown-F]", "tests/test_utils.py::test_get_asset_path[nikola.py-files_folders2-nikola/nikola.py]", "tests/test_command_import_wordpress.py::test_get_configuration_output_path", "tests/integration/test_dev_server.py::test_serves_root_dir[https://example.org:1234/blog]", "tests/integration/test_future_post.py::test_avoid_double_slash_in_rss", "tests/test_utils.py::test_demoting_headers[by zero]", "tests/test_utils.py::test_write_metadata_compiler[markdown_meta-expected_results1]", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-cache/pages/charts.html-en-cache/pages/charts.html]", "tests/test_locale.py::test_locale_base[sr-10. \\u0458\\u0443\\u043b 1856. 12:34:56 UTC]", "tests/test_metadata_extractors.py::test_yaml_none_handling", "tests/test_locale.py::test_initialize[pl]", "tests/test_shortcodes.py::test_extract_shortcodes[{{% foo %}}-expected0]", "tests/integration/test_redirection.py::test_index_in_sitemap", "tests/test_utils.py::test_write_metadata_fallbacks[foo]", "tests/test_locale.py::test_format_date_webiso_basic", "tests/test_locale.py::test_format_date_basic[pl]", "tests/test_scheduling.py::test_current_time_matching_rule", "tests/integration/test_page_index_pretty_urls.py::test_index_in_sitemap", "tests/test_shortcodes.py::test_errors[{{% wrong ending %%}-^Syntax error in shortcode 'wrong' at .*: expecting whitespace!]", "tests/test_plugins.py::test_importing_plugin_compile_pandoc", "tests/test_plugin_manager.py::test_load_plugins", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-cache/posts/fancy.post.html-es-cache/posts/fancy.post.es.html]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_content_in_subdir1", "tests/test_utils.py::test_bool_from_meta[YES-True]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-index:tags.html]", "tests/integration/test_building_in_subdir.py::test_avoid_double_slash_in_rss", "tests/integration/test_archive_full.py::test_full_archive[month]", "tests/test_utils.py::test_get_asset_path[nikola/nikola.py-files_folders3-nikola/nikola.py]", "tests/test_rst_compiler.py::test_youtube_iframe", "tests/test_utils.py::test_write_metadata_pelican_detection[rest-==\\nxx\\n==\\n\\n]", "tests/integration/test_page_index_normal_urls.py::test_index_in_sitemap", "tests/test_scheduling.py::test_current_time_not_matching_rule", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-base:]", "tests/test_command_import_wordpress_translation.py::test_split_a_two_language_post_with_teaser", "tests/test_locale.py::test_set_locale[pl-pl]", "tests/test_utils.py::test_bool_from_meta[NO-False]", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-base:blog]", "tests/test_compile_markdown.py::test_compiling_markdown[hilite]", "tests/integration/test_page_index_pretty_urls.py::test_archive_exists", "tests/test_command_import_wordpress_translation.py::test_legacy_split_a_two_language_post[pre modern with intermission]", "tests/integration/test_archive_full.py::test_full_archive[overall]", "tests/integration/test_empty_build.py::test_index_in_sitemap", "tests/integration/test_wordpress_import.py::test_import_created_files", "tests/test_shortcodes.py::test_extract_shortcodes[AAA{{% foo %}} {{% bar %}} {{% /foo %}}BBB-expected3]", "tests/test_shortcodes.py::test_data[test({{% arg 123 %}}Hello!{{% /arg %}})-test(arg ('123',)/[]/Hello!)]", "tests/integration/test_translated_content.py::test_index_in_sitemap", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-index:/path/with/leading/slash.html]", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-base:/path/with/leading/slash]", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-fancy.post.rst-es-fancy.post.es.rst]", "tests/test_shortcodes.py::test_errors[{{% start \"a\"b %}}-^Syntax error in shortcode 'start' at .*: expecting whitespace!]", "tests/test_locale.py::test_format_date_in_string_month_day_year_gb[default]", "tests/integration/test_archive_full.py::test_full_archive[day]", "tests/integration/test_translation_patterns.py::test_archive_exists", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-index:blog/tags.html]", "tests/integration/test_building_in_subdir.py::test_check_links", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-base:blog]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_in_subdir[subdir2-index.html]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-base:]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-index:path/to/tags.html]", "tests/integration/test_dev_server.py::test_basepath[http://local.host/-]", "tests/test_utils.py::test_TranslatableSettingsTest_with_string_input", "tests/test_command_import_wordpress.py::test_create_import[options1-None]", "tests/test_plugin_manager.py::test_load_plugins_skip_mismatching_category", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[authors-base:]", "tests/test_rst_compiler.py::test_youtube_iframe_start_at", "tests/test_locale.py::test_locale_base[sr_latin-10. jul 1856. 12:34:56 UTC]", "tests/test_scheduling.py::test_last_date_in_the_past_not_matching_rule", "tests/integration/test_page_index_normal_urls.py::test_page_index[pages-page0]", "tests/integration/test_translation_patterns.py::test_check_files", "tests/test_locale.py::test_format_date_long", "tests/test_config.py::test_simple_config", "tests/test_utils.py::test_bool_from_meta[None-B]", "tests/test_shortcodes.py::test_errors[{{% / %}}-^Found shortcode ending '{{% / %}}' which isn't closing a started shortcode]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_content_in_pages", "tests/integration/test_archive_per_month.py::test_monthly_archive", "tests/integration/test_repeated_posts_setting.py::test_index_in_sitemap", "tests/integration/test_translated_content_secondary_language.py::test_avoid_double_slash_in_rss", "tests/integration/test_future_post.py::test_check_links", "tests/test_shortcodes.py::test_errors[{{% start =b %}}-^String starting at .* must be non-empty!]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-base:blog]", "tests/integration/test_demo_build.py::test_archive_exists", "tests/integration/test_page_index_normal_urls.py::test_page_index_content_in_subdir2", "tests/test_metadata_extractors.py::test_nikola_meta_markdown[1-onefile-twofile]", "tests/test_utils.py::test_TemplateHookRegistry", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-base:blog]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-base:blog]", "tests/integration/test_redirection.py::test_relative_redirection", "tests/integration/test_relative_links_with_pages_in_root.py::test_index_in_sitemap", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-base:blog]", "tests/integration/test_page_index_normal_urls.py::test_check_files", "tests/test_rss_feeds.py::test_feed_is_valid", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-base:path/with/trailing/slash/]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-index:/path/with/leading/slash.html]", "tests/test_shortcodes.py::test_errors[{{% start a\\\\-^Unexpected end of data while escaping]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-base:/path/with/leading/slash]", "tests/test_utils.py::test_bool_from_meta[0-False1]", "tests/test_shortcodes.py::test_positional_arguments[test({{% arg 1 2aa %}})-test(arg ('1', '2aa')/[]/)]", "tests/test_shortcodes.py::test_data[test({{% arg 123 456 foo=bar baz=\"quotes rock.\" %}}Hello test suite!{{% /arg %}})-test(arg ('123', '456')/[('baz', 'quotes rock.'), ('foo', 'bar')]/Hello test suite!)]", "tests/integration/test_check_failure.py::test_avoid_double_slash_in_rss", "tests/test_utils.py::test_write_metadata_compiler[rest_docinfo-expected_results0]", "tests/test_utils.py::test_get_translation_candidate[{path}.{ext}.{lang}-cache/posts/fancy.post.html.es-en-cache/posts/fancy.post.html]", "tests/test_locale.py::test_format_date_basic[en]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[authors-base:path/with/trailing/slash/]", "tests/test_utils.py::test_bool_from_meta[yes-True]", "tests/integration/test_wordpress_import.py::test_filled_directories[posts]", "tests/integration/test_relative_links.py::test_avoid_double_slash_in_rss", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-index:/path/with/leading/slash.html]", "tests/integration/test_page_index_normal_urls.py::test_page_index_in_subdir[subdir3-index.php]", "tests/test_template_shortcodes.py::test_applying_shortcode[data={{ data }}-{{% test1 data=dummy %}}-data=]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-base:/path/with/leading/slash]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[authors-base:]", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[toml-TOML-1-onefile-twofile]", "tests/test_command_import_wordpress.py::test_ignoring_drafts_during_import[options1]", "tests/integration/test_check_full_path_subfolder.py::test_index_in_sitemap", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[yaml-YAML-2-twofile-onefile]", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-*.es.rst-en-*.rst]", "tests/integration/test_repeated_posts_setting.py::test_check_files", "tests/test_locale.py::test_format_date_in_string_month[default]", "tests/integration/test_archive_full.py::test_avoid_double_slash_in_rss", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-index:tags.html]", "tests/integration/test_archive_per_month.py::test_archive_exists", "tests/test_utils.py::test_write_metadata_comment_wrap[True-<!--\\n.. title: Hello, world!\\n.. slug: hello-world\\n-->\\n\\n]", "tests/test_locale.py::test_uninitialized_error", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-index:/path/with/leading/slash.html]", "tests/integration/test_future_post.py::test_index_in_sitemap", "tests/test_metadata_extractors.py::test_check_conditions[conditions5]", "tests/test_command_init.py::test_command_init_with_empty_dir", "tests/test_plugins.py::test_command_version", "tests/integration/test_translation_patterns.py::test_translated_titles", "tests/integration/test_relative_links_with_pages_in_root.py::test_relative_links", "tests/integration/test_demo_build.py::test_avoid_double_slash_in_rss", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-index:/path/with/leading/slash.html]", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-index:tags.html]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_in_subdir[pages-index.html]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-index:tags.html]", "tests/test_rst_compiler.py::test_doc_doesnt_exist", "tests/test_shortcodes.py::test_errors[{{% start \"a\\\\-^Unexpected end of data while escaping]", "tests/test_command_import_wordpress.py::test_write_content_does_not_detroy_text", "tests/test_plugin_manager.py::test_load_plugins_twice", "tests/integration/test_relative_links.py::test_relative_links", "tests/test_test_helper.py::test_test_helper", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-cache/posts/fancy.post.es.html-en-cache/posts/fancy.post.html]", "tests/integration/test_demo_build.py::test_check_links", "tests/test_locale.py::test_format_date_in_string_month[pl]", "tests/test_command_import_wordpress_translation.py::test_modernize_a_wordpress_export_xml_chunk", "tests/integration/test_check_failure.py::test_index_in_sitemap", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-index:blog/tags.html]", "tests/test_utils.py::test_bool_from_meta[No-False]", "tests/test_locale.py::test_format_date_in_string_month_year[default]", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[nikola-Nikola-2-twofile-onefile]", "tests/test_shortcodes.py::test_arg_keyword[test({{% arg 1a=2b %}})-test(arg ()/[('1a', '2b')]/)]", "tests/test_command_import_wordpress.py::test_populate_context[BLOG_TITLE-Wordpress blog title]", "tests/test_utils.py::test_bool_from_meta[True-True1]", "tests/test_scheduling.py::test_last_date_in_the_future_not_matching_rule", "tests/test_utils.py::test_get_title_from_fname", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-index:path/to/tags.html]", "tests/test_template_shortcodes.py::test_applying_shortcode[arg={{ _args[0] }}-{{% test1 \"one two\" %}}-arg=one two]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-index:path/to/tags.html]", "tests/integration/test_page_index_pretty_urls.py::test_check_links", "tests/test_command_import_wordpress.py::test_populate_context[BLOG_DESCRIPTION-Nikola test blog ;) - with mor\\xe9 \\xdcml\\xe4\\xfcts]", "tests/test_utils.py::test_TranslatableSetting_with_dict_input", "tests/integration/test_archive_per_day.py::test_check_files", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-base:/path/with/leading/slash]", "tests/test_shortcodes.py::test_extract_shortcodes[AAA{{% foo %}} BBB {{% bar %}} quux {{% /bar %}} CCC-expected6]", "tests/integration/test_check_full_path_subfolder.py::test_archive_exists", "tests/test_command_import_wordpress.py::test_transform_caption", "tests/test_path_handlers.py::test_taxonomy_overview_path[authors-base:blog]", "tests/test_command_import_wordpress.py::test_create_import_work_without_argument", "tests/integration/test_page_index_normal_urls.py::test_page_index[subdir2-page3]", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-cache/pages/charts.html-es-cache/pages/charts.es.html]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-index:path/to/tags.html]", "tests/test_scheduling.py::test_last_date_in_the_past_matching_rule", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-base:]", "tests/integration/test_dev_server.py::test_serves_root_dir[https://example.org]", "tests/test_shortcodes.py::test_positional_arguments[test({{% arg back\\\\ slash arg2 %}})-test(arg ('back slash', 'arg2')/[]/)]", "tests/test_utils.py::test_get_asset_path[nikola.py-files_folders4-None]", "tests/test_command_import_wordpress_translation.py::test_modernize_qtranslate_tags", "tests/test_command_init.py::test_init_called_without_target_quiet", "tests/test_utils.py::test_get_translation_candidate[{path}.{ext}.{lang}-cache/posts/fancy.post.html-es-cache/posts/fancy.post.html.es]", "tests/test_utils.py::test_bool_from_meta[True-True0]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[authors-base:/path/with/leading/slash]", "tests/test_config.py::test_config_with_illegal_filename", "tests/integration/test_page_index_pretty_urls.py::test_avoid_double_slash_in_rss", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-base:path/with/trailing/slash/]", "tests/test_rst_compiler.py::test_ReST_extension", "tests/test_shortcodes.py::test_errors[{{% -^Syntax error: '{{%' must be followed by shortcode name]", "tests/integration/test_page_index_normal_urls.py::test_page_index[subdir1-page1]", "tests/integration/test_demo_build.py::test_check_files", "tests/test_utils.py::test_bool_from_meta[1-True1]", "tests/test_utils.py::test_bool_from_meta[-B]", "tests/integration/test_page_index_normal_urls.py::test_avoid_double_slash_in_rss", "tests/integration/test_check_absolute_subfolder.py::test_index_in_sitemap", "tests/integration/test_category_destpath.py::test_check_files", "tests/integration/test_translated_content_secondary_language.py::test_check_files", "tests/test_plugins.py::test_importing_plugin_task_galleries", "tests/test_command_init.py::test_configure_translations_without_additional_languages", "tests/integration/test_dev_server.py::test_basepath[http://example.org:124/blog-/blog]", "tests/test_shortcodes.py::test_errors[{{% %}}-^Syntax error: '{{%' must be followed by shortcode name]", "tests/integration/test_dev_server.py::test_basepath[http://example.org/blog-/blog]", "tests/test_command_import_wordpress.py::test_create_import[None-additional_args2]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-index:path/to/tags.html]", "tests/test_command_import_wordpress_translation.py::test_legacy_split_a_two_language_post[with uneven repartition bis]", "tests/test_path_handlers.py::test_taxonomy_overview_path[authors-base:path/with/trailing/slash/]", "tests/test_command_import_wordpress.py::test_populate_context[SITE_URL-http://some.blog/]", "tests/integration/test_check_absolute_subfolder.py::test_archive_exists", "tests/test_command_import_wordpress.py::test_transforming_source_code", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-base:path/with/trailing/slash/]", "tests/integration/test_archive_per_month.py::test_check_links", "tests/integration/test_relative_links.py::test_check_files", "tests/integration/test_page_index_normal_urls.py::test_check_links", "tests/test_locale.py::test_format_date_translatablesetting[en-en July]", "tests/test_command_import_wordpress.py::test_populate_context[DEFAULT_LANG-de]", "tests/integration/test_demo_build.py::test_gallery_rss", "tests/integration/test_page_index_normal_urls.py::test_page_index_in_subdir[pages-index.html]", "tests/integration/test_repeated_posts_setting.py::test_archive_exists", "tests/test_slugify.py::test_slugify[Polish diacritical characters]", "tests/test_slugify.py::test_slugify[Polish diacritical characters and dashes]", "tests/integration/test_archive_per_day.py::test_day_archive", "tests/test_command_import_wordpress.py::test_configure_redirections", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[authors-base:blog]", "tests/test_utils.py::test_get_crumbs[galleries-False-expected_crumbs0]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_content_in_subdir3", "tests/integration/test_wordpress_import.py::test_filled_directories[pages]", "tests/integration/test_translated_content_secondary_language.py::test_index_in_sitemap", "tests/test_utils.py::test_demoting_headers[by one]", "tests/integration/test_archive_per_month.py::test_index_in_sitemap", "tests/test_shortcodes.py::test_extract_shortcodes[AAA{{% foo %}} {{% bar %}} quux {{% /bar %}} {{% /foo %}}BBB-expected5]", "tests/test_utils.py::test_sitemap_get_base_path[http://some.site/-/]", "tests/integration/test_page_index_normal_urls.py::test_page_index_content_in_subdir3", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-base:path/with/trailing/slash/]", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-base:blog]", "tests/test_utils.py::test_bool_from_meta[False-False0]", "tests/test_locale.py::test_format_date_in_string_month_year[pl]", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-base:]", "tests/test_command_init.py::test_configure_translations_with_2_additional_languages", "tests/integration/test_dev_server.py::test_basepath[https://local.host/-]", "tests/test_shortcodes.py::test_errors[==> {{% <==-^Shortcode '<==' starting at .* is not terminated correctly with '%}}'!]", "tests/test_slugify.py::test_slugify[ASCII]", "tests/test_metadata_extractors.py::test_compiler_metadata[CompileMarkdown-md-markdown-Markdown]", "tests/test_rst_compiler.py::test_doc_titled", "tests/integration/test_relative_links.py::test_index_in_sitemap", "tests/integration/test_check_full_path_subfolder.py::test_avoid_double_slash_in_rss", "tests/test_locale.py::test_format_date_locale_variants[US]", "tests/integration/test_page_index_normal_urls.py::test_page_index_content_in_pages", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-index:tags.html]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-index:path/to/tags.html]", "tests/integration/test_empty_build.py::test_avoid_double_slash_in_rss", "tests/test_shortcodes.py::test_positional_arguments[test({{% arg 1 %}})-test(arg ('1',)/[]/)]", "tests/test_utils.py::test_nikola_find_formatter_class_returns_pygments_class", "tests/integration/test_check_failure.py::test_check_files_fail", "tests/test_utils.py::test_demoting_headers[by two]", "tests/integration/test_redirection.py::test_external_redirection", "tests/integration/test_archive_per_month.py::test_avoid_double_slash_in_rss", "tests/integration/test_archive_full.py::test_full_archive[year]", "tests/test_locale.py::test_initialize[en]", "tests/integration/test_relative_links_with_pages_in_root.py::test_archive_exists", "tests/test_utils.py::test_sitemap_get_base_path[http://some.site/some/sub-path-/some/sub-path/]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-base:/path/with/leading/slash]", "tests/integration/test_building_in_subdir.py::test_archive_exists", "tests/test_utils.py::test_parselinenos", "tests/integration/test_relative_links_with_pages_in_root.py::test_check_files", "tests/test_utils.py::test_write_metadata_from_site", "tests/test_utils.py::test_get_asset_path[assets/css/theme.css-files_folders1-nikola/data/themes/bootstrap4/assets/css/theme.css]", "tests/test_shortcodes.py::test_positional_arguments[test({{% arg \"%}}\" %}})-test(arg ('%}}',)/[]/)]", "tests/test_utils.py::test_get_crumbs[galleries/demo-False-expected_crumbs1]", "tests/test_shortcodes.py::test_noargs[test({{% noargs %}}\\\\hello world/{{% /noargs %}})-test(noargs \\\\hello world/ success!)]", "tests/test_shortcodes.py::test_noargs[test({{% noargs %}})-test(noargs success!)]", "tests/test_command_import_wordpress.py::test_create_import[only import filename]", "tests/integration/test_category_destpath.py::test_avoid_double_slash_in_rss", "tests/integration/test_translation_patterns.py::test_index_in_sitemap", "tests/test_utils.py::test_sitemap_get_base_path[http://some.site/some/sub-path/-/some/sub-path/]", "tests/integration/test_dev_server.py::test_basepath[http://example.org:124/Deep/Rab_bit/hol.e/-/Deep/Rab_bit/hol.e]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-index:blog/tags.html]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-base:]", "tests/integration/test_dev_server.py::test_basepath[https://local.host:456/-]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-index:/path/with/leading/slash.html]", "tests/test_rst_compiler.py::test_vimeo", "tests/integration/test_archive_per_day.py::test_check_links", "tests/integration/test_page_index_normal_urls.py::test_page_index[subdir1-page2]", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-base:]", "tests/integration/test_future_post.py::test_future_post_deployment", "tests/integration/test_page_index_pretty_urls.py::test_page_index_in_subdir[subdir3-index.php]", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-index:/path/with/leading/slash.html]", "tests/integration/test_category_destpath.py::test_check_links", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-index:blog/tags.html]", "tests/test_slugify.py::test_disarmed[polish]", "tests/test_task_scale_images.py::test_handling_icc_profiles[without icc filename-profiles not preserved]", "tests/test_compile_markdown.py::test_compiling_markdown[mdx podcast]", "tests/integration/test_relative_links.py::test_check_links", "tests/test_path_handlers.py::test_taxonomy_overview_path[authors-base:]", "tests/integration/test_repeated_posts_setting.py::test_check_links", "tests/test_command_import_wordpress_translation.py::test_legacy_split_a_two_language_post[simple]", "tests/test_rst_compiler.py::test_math_extension_outputs_tex", "tests/test_rst_compiler.py::test_doc", "tests/test_command_init.py::test_command_init_with_arguments", "tests/test_command_import_wordpress_translation.py::test_legacy_split_a_two_language_post[with uneven repartition]", "tests/integration/test_dev_server.py::test_basepath[http://localhost-]", "tests/test_locale.py::test_format_date_in_string_month_day_year[pl]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-base:path/with/trailing/slash/]", "tests/test_shortcodes.py::test_extract_shortcodes[{{% foo %}} bar {{% /foo %}}-expected1]", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-base:path/with/trailing/slash/]", "tests/test_utils.py::test_bool_from_meta[TRUE-True]", "tests/integration/test_check_absolute_subfolder.py::test_check_files", "tests/test_utils.py::test_bool_from_meta[no-False]", "tests/test_slugify.py::test_slugify[ASCII uppercase]", "tests/test_utils.py::test_extracting_metadata_from_filename[False-dub_dub_title]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-base:blog]", "tests/test_utils.py::test_bool_from_meta[False-False1]", "tests/integration/test_wordpress_import.py::test_avoid_double_slash_in_rss", "tests/test_command_import_wordpress.py::test_transform_caption_with_link_inside", "tests/integration/test_repeated_posts_setting.py::test_avoid_double_slash_in_rss", "tests/test_utils.py::test_get_meta_slug_only_from_filename", "tests/test_scheduling.py::test_current_time_matching_rule_no_given_date[True]", "tests/integration/test_category_destpath.py::test_destpath_with_avoidance", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[authors-base:/path/with/leading/slash]", "tests/test_path_handlers.py::test_taxonomy_overview_path[authors-base:/path/with/leading/slash]", "tests/integration/test_dev_server.py::test_basepath[https://localhost:123/-]", "tests/test_utils.py::test_write_metadata_pelican_detection[markdown-title: xx\\n\\n]", "tests/test_locale.py::test_set_locale[fake language]", "tests/test_utils.py::test_write_metadata_comment_wrap[wrap2-111\\n.. title: Hello, world!\\n.. slug: hello-world\\n222\\n\\n]", "tests/test_template_shortcodes.py::test_applying_shortcode[foo={{ foo }}-{{% test1 foo=\"bar baz\" spamm=ham %}}-foo=bar baz]", "tests/test_template_shortcodes.py::test_applying_shortcode[foo={{ foo }}-{{% test1 foo=bar %}}-foo=bar]", "tests/integration/test_redirection.py::test_archive_exists", "tests/integration/test_check_full_path_subfolder.py::test_check_links", "tests/test_utils.py::test_write_metadata_pelican_detection[html-.. title: xx\\n\\n]", "tests/test_utils.py::test_extracting_metadata_from_filename[True-Dub dub title]", "tests/test_metadata_extractors.py::test_compiler_metadata[CompileRest-rst-rest-reST]", "tests/test_utils.py::test_write_metadata_with_format_toml", "tests/integration/test_check_failure.py::test_check_links_fail", "tests/test_template_shortcodes.py::test_mixedargs", "tests/test_shortcodes.py::test_arg_keyword[test({{% arg 1a=\"2b 3c\" 4d=5f back=slash\\\\ slash %}})-test(arg ()/[('1a', '2b 3c'), ('4d', '5f'), ('back', 'slash slash')]/)]", "tests/integration/test_future_post.py::test_check_files", "tests/test_rss_feeds.py::test_feed_items_have_valid_URLs[guid]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[categories-index:blog/tags.html]", "tests/integration/test_translated_content.py::test_translated_titles", "tests/test_shortcodes.py::test_extract_shortcodes[AAA{{% foo %}} bar {{% /foo %}}BBB-expected2]", "tests/test_rss_feeds.py::test_feed_items_have_valid_URLs[link]", "tests/integration/test_check_absolute_subfolder.py::test_avoid_double_slash_in_rss", "tests/test_plugin_manager.py::test_locate_plugins_finds_core_plugins", "tests/integration/test_dev_server.py::test_serves_root_dir[http://example.org/deep/down/a/rabbit/hole]", "tests/test_path_handlers.py::test_taxonomy_overview_path[categories-index:blog/tags.html]", "tests/integration/test_empty_build.py::test_check_files", "tests/test_shortcodes.py::test_errors[{{% start-^Shortcode 'start' starting at .* is not terminated correctly with '%}}'!]", "tests/integration/test_dev_server.py::test_basepath[https://local.host-]", "tests/test_shortcodes.py::test_data[test({{% arg 123 456 foo=bar %}}Hello world!{{% /arg %}})-test(arg ('123', '456')/[('foo', 'bar')]/Hello world!)]", "tests/integration/test_building_in_subdir.py::test_check_files", "tests/integration/test_empty_build.py::test_check_links", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-index:tags.html]", "tests/test_utils.py::test_use_filename_as_slug_fallback", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[tags-index:blog/tags.html]", "tests/test_locale.py::test_format_date_timezone", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-base:/path/with/leading/slash]", "tests/integration/test_translated_content.py::test_archive_exists", "tests/test_template_shortcodes.py::test_applying_shortcode[data={{ data }}-{{% test1 spamm %}}-data=]", "tests/integration/test_archive_full.py::test_index_in_sitemap", "tests/test_template_shortcodes.py::test_applying_shortcode[foo={{ foo }}-{{% test1 foo=\"bar baz\" %}}-foo=bar baz]", "tests/test_command_import_wordpress.py::test_transform_multiple_newlines", "tests/integration/test_category_destpath.py::test_index_in_sitemap", "tests/integration/test_translation_patterns.py::test_check_links", "tests/test_utils.py::test_bool_from_meta[FALSE-False]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[authors-base:/path/with/leading/slash]", "tests/test_task_scale_images.py::test_handling_icc_profiles[with icc filename-profiles not preserved]", "tests/test_utils.py::test_write_metadata_comment_wrap[False-.. title: Hello, world!\\n.. slug: hello-world\\n\\n]", "tests/test_shortcodes.py::test_extract_shortcodes[AAA{{% foo %}} {{% /bar %}} {{% /foo %}}BBB-expected4]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[authors-base:path/with/trailing/slash/]", "tests/integration/test_redirection.py::test_check_links", "tests/test_locale.py::test_set_locale_for_template", "tests/test_utils.py::test_bool_from_meta[true-True]", "tests/test_utils.py::test_write_metadata_pelican_detection_default", "tests/test_utils.py::test_get_translation_candidate[{path}.{ext}.{lang}-*.rst-es-*.rst.es]", "tests/test_shortcodes.py::test_errors[{{% start %}} {{% /end %}}-^Found shortcode ending '{{% /end %}}' which isn't closing a started shortcode]", "tests/test_command_import_wordpress.py::test_populate_context[BLOG_AUTHOR-Niko]", "tests/integration/test_translation_patterns.py::test_avoid_double_slash_in_rss", "tests/test_scheduling.py::test_last_date_in_the_future_matching_rule", "tests/integration/test_page_index_normal_urls.py::test_page_index_in_subdir[subdir1-index.html]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-base:]", "tests/test_locale.py::test_format_date_in_string_customization[Foo {month:'miesi\\u0105ca' MMMM} Bar-Foo miesi\\u0105ca lipca Bar]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[categories-index:blog/tags.html]", "tests/test_command_import_wordpress.py::test_ignoring_drafts_during_import[options0]", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-*.es.rst-es-*.es.rst]", "tests/test_plugin_manager.py::test_locate_plugins_finds_core_and_custom_plugins", "tests/test_shortcodes.py::test_positional_arguments[test({{% arg \"hello world\" %}})-test(arg ('hello world',)/[]/)]", "tests/integration/test_dev_server.py::test_serves_root_dir[https://example.org:3456/blog/]", "tests/test_compile_markdown.py::test_compiling_markdown[strikethrough]", "tests/test_command_import_wordpress.py::test_transforming_content", "tests/test_locale.py::test_initilalize_failure[None]", "tests/integration/test_demo_build.py::test_index_in_sitemap", "tests/integration/test_wordpress_import.py::test_archive_exists", "tests/test_command_import_wordpress.py::test_populate_context[[email protected]]", "tests/test_shortcodes.py::test_arg_keyword[test({{% arg 1a=\"2b 3c\" 4d=5f %}})-test(arg ()/[('1a', '2b 3c'), ('4d', '5f')]/)]", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[authors-base:path/with/trailing/slash/]", "tests/test_utils.py::test_TranslatableSetting_with_language_change", "tests/integration/test_dev_server.py::test_basepath[http://localhost:123/-]", "tests/test_utils.py::test_write_metadata_with_formats[nikola-.. title: Hello, world!\\n.. slug: hello-world\\n.. a: 1\\n.. b: 2\\n\\n]", "tests/integration/test_page_index_pretty_urls.py::test_page_index[subdir1-page1]", "tests/integration/test_category_destpath.py::test_archive_exists", "tests/integration/test_page_index_normal_urls.py::test_page_index_content_in_subdir1", "tests/test_command_import_wordpress_translation.py::test_conserves_qtranslate_less_post", "tests/test_path_handlers.py::test_taxonomy_index_path_helper[categories-index:tags.html]", "tests/integration/test_redirection.py::test_check_files", "tests/test_utils.py::test_write_metadata_fallbacks[filename_regex]", "tests/integration/test_dev_server.py::test_basepath[https://localhost-]", "tests/integration/test_archive_per_day.py::test_archive_exists", "tests/test_utils.py::test_getting_metadata_from_content", "tests/test_rst_compiler.py::test_rendering_codeblock_alias[.. sourcecode:: python\\n\\n import antigravity]", "tests/integration/test_archive_full.py::test_check_links", "tests/test_metadata_extractors.py::test_check_conditions[conditions3]", "tests/integration/test_page_index_pretty_urls.py::test_page_index_content_in_subdir2", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[authors-base:blog]", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[toml-TOML-2-twofile-onefile]", "tests/integration/test_dev_server.py::test_basepath[http://example.org:124/blog?lorem=ipsum&dol=et-/blog]", "tests/integration/test_translated_content_secondary_language.py::test_check_links", "tests/test_config.py::test_inherited_config", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-base:path/with/trailing/slash/]", "tests/test_path_handlers.py::test_render_taxonomies_permalink[authors-base:blog]", "tests/integration/test_wordpress_import.py::test_check_files", "tests/integration/test_page_index_pretty_urls.py::test_page_index_in_subdir[subdir1-index.html]", "tests/integration/test_relative_links.py::test_archive_exists", "tests/test_path_handlers.py::test_taxonomy_overview_path[tags-base:/path/with/leading/slash]", "tests/integration/test_archive_per_day.py::test_avoid_double_slash_in_rss", "tests/test_locale.py::test_format_date_translatablesetting[pl-lipca pl]", "tests/integration/test_relative_links_with_pages_in_root.py::test_avoid_double_slash_in_rss", "tests/integration/test_translated_content.py::test_check_links", "tests/test_utils.py::test_get_translation_candidate[{path}.{lang}.{ext}-*.rst-es-*.es.rst]", "tests/integration/test_dev_server.py::test_basepath[https://lorem.ipsum/dolet/-/dolet]", "tests/test_metadata_extractors.py::test_builtin_extractors_rest[nikola-Nikola-1-onefile-twofile]", "tests/test_utils.py::test_get_translation_candidate[{path}.{ext}.{lang}-*.rst.es-es-*.rst.es]", "tests/integration/test_page_index_pretty_urls.py::test_page_index[subdir1-page2]", "tests/test_command_import_wordpress.py::test_importing_posts_and_attachments", "tests/test_command_init.py::test_command_init_with_defaults", "tests/integration/test_check_full_path_subfolder.py::test_check_files", "tests/test_path_handlers.py::test_render_taxonomies_permalink[tags-index:/path/with/leading/slash.html]", "tests/test_utils.py::test_get_translation_candidate[{path}.{ext}.{lang}-*.rst.es-en-*.rst]", "tests/test_metadata_extractors.py::test_nikola_meta_markdown[2-twofile-onefile]", "tests/test_locale.py::test_format_date_in_string_customization[Foo {month_year:MMMM yyyy} Bar-Foo lipca 1856 Bar]", "tests/test_shortcodes.py::test_errors[{{% / a %}}-^Syntax error: '{{% /' must be followed by ' %}}']", "tests/integration/test_redirection.py::test_avoid_double_slash_in_rss", "tests/test_utils.py::test_sitemap_get_base_path[http://some.site-/]", "tests/test_shortcodes.py::test_errors[{{%-^Syntax error: '{{%' must be followed by shortcode name]", "tests/test_path_handlers.py::test_taxonomy_classifier_index_path[tags-base:]", "tests/integration/test_page_index_pretty_urls.py::test_page_index[pages-page0]", "tests/integration/test_future_post.py::test_future_post_not_in_indexes[index.html]", "tests/integration/test_page_index_normal_urls.py::test_archive_exists"] | [] | {"install": ["uv pip install -e ."], "pre_install": [], "python": "3.11", "pip_packages": ["aiohttp==3.9.1", "aiosignal==1.3.1", "anyio==4.2.0", "argon2-cffi==23.1.0", "argon2-cffi-bindings==21.2.0", "arrow==1.3.0", "asttokens==2.4.1", "async-lru==2.0.4", "attrs==23.2.0", "babel==2.14.0", "beautifulsoup4==4.12.2", "bleach==6.1.0", "blinker==1.7.0", "certifi==2023.11.17", "cffi==1.16.0", "charset-normalizer==3.3.2", "cloudpickle==3.0.0", "comm==0.2.1", "coverage==7.4.0", "debugpy==1.8.0", "decorator==5.1.1", "defusedxml==0.7.1", "docutils==0.20.1", "doit==0.36.0", "executing==2.0.1", "fastjsonschema==2.19.1", "feedparser==6.0.11", "flake8==7.0.0", "fqdn==1.5.1", "freezegun==1.4.0", "frozenlist==1.4.1", "ghp-import==2.1.0", "hsluv==5.0.4", "html5lib==1.1", "idna==3.6", "importlib-metadata==7.0.1", "iniconfig==2.0.0", "ipykernel==6.28.0", "ipython==8.18.1", "isoduration==20.11.0", "jedi==0.19.1", "jinja2==3.1.2", "json5==0.9.14", "jsonpointer==2.4", "jsonschema==4.20.0", "jsonschema-specifications==2023.12.1", "jupyter-client==8.6.0", "jupyter-core==5.7.0", "jupyter-events==0.9.0", "jupyter-lsp==2.2.1", "jupyter-server==2.12.2", "jupyter-server-terminals==0.5.1", "jupyterlab==4.0.10", "jupyterlab-pygments==0.3.0", "jupyterlab-server==2.25.2", "lxml==5.0.1", "mako==1.3.0", "markdown==3.5.1", "markupsafe==2.1.3", "matplotlib-inline==0.1.6", "mccabe==0.7.0", "micawber==0.5.5", "mistune==3.0.2", "multidict==6.0.4", "natsort==8.4.0", "nbclient==0.9.0", "nbconvert==7.14.0", "nbformat==5.9.2", "nest-asyncio==1.5.8", "notebook==7.0.6", "notebook-shim==0.2.3", "overrides==7.4.0", "packaging==23.2", "pandocfilters==1.5.0", "parso==0.8.3", "pexpect==4.9.0", "phpserialize==1.3", "piexif==1.1.3", "pillow==10.2.0", "platformdirs==4.1.0", "pluggy==1.3.0", "prometheus-client==0.19.0", "prompt-toolkit==3.0.43", "psutil==5.9.7", "ptyprocess==0.7.0", "pure-eval==0.2.2", "pycodestyle==2.11.1", "pycparser==2.21", "pyflakes==3.2.0", "pygal==3.0.4", "pygments==2.17.2", "pyphen==0.14.0", "pyrss2gen==1.1", "pytest==7.4.4", "pytest-cov==4.1.0", "python-dateutil==2.8.2", "python-json-logger==2.0.7", "pyyaml==6.0.1", "pyzmq==25.1.2", "referencing==0.32.1", "requests==2.31.0", "rfc3339-validator==0.1.4", "rfc3986-validator==0.1.1", "rpds-py==0.16.2", "ruamel-yaml==0.18.5", "ruamel-yaml-clib==0.2.8", "send2trash==1.8.2", "setuptools==69.0.3", "sgmllib3k==1.0.0", "six==1.16.0", "smartypants==2.0.1", "sniffio==1.3.0", "soupsieve==2.5", "stack-data==0.6.3", "terminado==0.18.0", "tinycss2==1.2.1", "toml==0.10.2", "tornado==6.4", "traitlets==5.14.1", "types-python-dateutil==2.8.19.20240106", "typogrify==2.0.7", "unidecode==1.3.7", "uri-template==1.3.0", "urllib3==2.1.0", "watchdog==3.0.0", "wcwidth==0.2.13", "webcolors==1.13", "webencodings==0.5.1", "websocket-client==1.7.0", "wheel==0.44.0", "yapsy==1.12.2", "yarl==1.9.4", "zipp==3.17.0"]} | null | ["pytest --tb=no -rA -p no:cacheprovider"] | null | null |
|
aimhubio/aim | aimhubio__aim-2671 | fba120b9c1d47261dac68041d9938b9caa257b79 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57c867207b..b7a5e45a19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@
- Add the ability to create custom UI boards (roubkar, arsengit, KaroMourad)
- Relocate aim explorers to `Explorers` page (arsengit)
- Add functionality for custom context in the PyTorch Ignite (tmynn)
+- Extend `aim.ext.tensorboard_tracker.run.Run` to allow stdout logging and system stats and parameter logging (alansaul)
### Fixes
diff --git a/aim/ext/tensorboard_tracker/run.py b/aim/ext/tensorboard_tracker/run.py
index 4df3add602..c95b616e38 100644
--- a/aim/ext/tensorboard_tracker/run.py
+++ b/aim/ext/tensorboard_tracker/run.py
@@ -1,6 +1,6 @@
from typing import Optional, Union
-from aim.sdk.run import BasicRun
+from aim.sdk.run import Run as SdkRun
from aim.ext.tensorboard_tracker.tracker import TensorboardTracker
from typing import TYPE_CHECKING
@@ -9,14 +9,23 @@
from aim.sdk.repo import Repo
-class Run(BasicRun):
- def __init__(self, run_hash: Optional[str] = None, *,
- sync_tensorboard_log_dir: str,
- repo: Optional[Union[str, 'Repo']] = None,
- experiment: Optional[str] = None,
- force_resume: Optional[bool] = False,
- ):
- super().__init__(run_hash, repo=repo, read_only=False, experiment=experiment, force_resume=force_resume)
+class Run(SdkRun):
+ def __init__(
+ self, run_hash: Optional[str] = None, *,
+ sync_tensorboard_log_dir: str,
+ repo: Optional[Union[str, 'Repo']] = None,
+ experiment: Optional[str] = None,
+ force_resume: Optional[bool] = False,
+ system_tracking_interval: Optional[Union[int, float]] = None,
+ log_system_params: Optional[bool] = False,
+ capture_terminal_logs: Optional[bool] = False,
+ ):
+ super().__init__(
+ run_hash, repo=repo, read_only=False, experiment=experiment, force_resume=force_resume,
+ system_tracking_interval=system_tracking_interval, log_system_params=log_system_params,
+ capture_terminal_logs=capture_terminal_logs
+ )
+
self['tb_log_directory'] = sync_tensorboard_log_dir
self._tensorboard_tracker = TensorboardTracker(self._tracker, sync_tensorboard_log_dir)
self._tensorboard_tracker.start()
| diff --git a/tests/ext/test_tensorboard_run.py b/tests/ext/test_tensorboard_run.py
new file mode 100644
index 0000000000..2738244eb3
--- /dev/null
+++ b/tests/ext/test_tensorboard_run.py
@@ -0,0 +1,86 @@
+import time
+
+from aim.ext.resource.log import LogLine
+from aim.ext.tensorboard_tracker.run import Run as TensorboardRun
+
+from tests.base import TestBase
+from tests.utils import full_class_name
+
+
+class TestTensorboardRun(TestBase):
+
+ def test_tensorboard_tracker_run__default_no_capture(self):
+ # Given
+ run = TensorboardRun(sync_tensorboard_log_dir="dummy", repo=self.repo)
+ run['testcase'] = full_class_name(TensorboardRun)
+ run_hash = run.hash
+ console_statement = 'no console capture is being done'
+
+ # When
+ print(console_statement)
+ time.sleep(3) # allow tracker to add resource usage metrics
+ del run
+
+ # Then
+ tracked_run = self.repo.get_run(run_hash)
+ self.assertIsNone(tracked_run.metrics().dataframe())
+
+ def test_tensorboard_tracker_run__system_stats_captured(self):
+ # Given
+ run = TensorboardRun(
+ sync_tensorboard_log_dir="dummy", repo=self.repo, system_tracking_interval=1
+ )
+ run['testcase'] = full_class_name(TensorboardRun)
+ run_hash = run.hash
+
+ # When
+ time.sleep(3) # allow tracker to add resource usage metrics
+ del run
+
+ # Then
+ tracked_run = self.repo.get_run(run_hash)
+ metrics_recorded = set(tracked_run.metrics().dataframe()['metric.name'].unique())
+ self.assertTrue("__system__cpu" in metrics_recorded)
+
+ def test_tensorboard_tracker_run__terminal_capture(self):
+ # Given
+ run = TensorboardRun(
+ sync_tensorboard_log_dir="dummy", repo=self.repo, capture_terminal_logs=True,
+ )
+ run['testcase'] = full_class_name(TensorboardRun)
+ run_hash = run.hash
+ console_statement = 'no console capture has worked'
+
+ # When
+ print(console_statement)
+ time.sleep(3) # allow tracker to add terminal logs
+ del run
+
+ # Then
+ tracked_run = self.repo.get_run(run_hash)
+ terminal_logs = tracked_run.get_terminal_logs()
+ log_found = False
+ for log_item in terminal_logs.data.values():
+ log_line = log_item[0][0]
+ if isinstance(log_line, LogLine):
+ if console_statement in str(log_line.data):
+ log_found = True
+
+ self.assertTrue(log_found)
+
+ def test_tensorboard_tracker_run__system_params_captured(self):
+ # Given
+ run = TensorboardRun(
+ sync_tensorboard_log_dir="dummy", repo=self.repo, log_system_params=True
+ )
+ run['testcase'] = full_class_name(TensorboardRun)
+ run_hash = run.hash
+
+ # When
+ time.sleep(3) # allow tracker to add system params
+ del run
+
+ # Then
+ tracked_run = self.repo.get_run(run_hash)
+ system_params = tracked_run.get('__system_params')
+ self.assertIsNotNone(system_params)
| Extend `aim.ext.tensorboard_tracker.run.Run` to also allow system stats, parameters, and stdout capture.
## 🚀 Feature
Allow capturing of system parameters and terminal logs by the `aim.ext.tensorboard_tracker.run.Run`, as this is great feature shouldn't be only available to the default `Run`.
### Motivation
The new feature of allowing continuous syncing from `tensorboard` files to `aim` is really nice, but because `aim.ext.tensorboard_tracker.run.Run` inherits from `BasicRun` rather than `Run`, it misses out on the ability to log the standard out, system stats and system parameters. Since `aim.ext.tensorboard_tracker.run.Run` should be a possible replacement for `Run`, I don't see a reason why this behaviour shouldn't be allowed.
It has been highlighted in Discord by @mihran113:
> The reason behind inheriting from basic run is exactly to avoid terminal log tracking and system param tracking actually, cause we don’t want to add anything else rather than what’s tracked via tensorboard. Cause there can be times when live tracking is done from a different process, and catching that process’s terminal logs and system params won’t make any sense I guess. If you’re interested you can open a PR to address those points, cause adding the possibility to enable those won’t make any harm as well.
so I believe the *default* arguments should *not* do this extra logging, but still optionally allow this behaviour.
### Pitch
Have `aim.ext.tensorboard_tracker.run.Run` inherit from `aim.sdk.run.Run` instead of `aim.sdk.run.BasicRun`, so that it can utilise it's extra capabilities.
### Alternatives
Instead of inheritance we could change the system resource tracking be a mixin?
Extend `aim.ext.tensorboard_tracker.run.Run` to also allow system stats, parameters, and stdout capture.
## 🚀 Feature
Allow capturing of system parameters and terminal logs by the `aim.ext.tensorboard_tracker.run.Run`, as this is great feature shouldn't be only available to the default `Run`.
### Motivation
The new feature of allowing continuous syncing from `tensorboard` files to `aim` is really nice, but because `aim.ext.tensorboard_tracker.run.Run` inherits from `BasicRun` rather than `Run`, it misses out on the ability to log the standard out, system stats and system parameters. Since `aim.ext.tensorboard_tracker.run.Run` should be a possible replacement for `Run`, I don't see a reason why this behaviour shouldn't be allowed.
It has been highlighted in Discord by @mihran113:
> The reason behind inheriting from basic run is exactly to avoid terminal log tracking and system param tracking actually, cause we don’t want to add anything else rather than what’s tracked via tensorboard. Cause there can be times when live tracking is done from a different process, and catching that process’s terminal logs and system params won’t make any sense I guess. If you’re interested you can open a PR to address those points, cause adding the possibility to enable those won’t make any harm as well.
so I believe the *default* arguments should *not* do this extra logging, but still optionally allow this behaviour.
### Pitch
Have `aim.ext.tensorboard_tracker.run.Run` inherit from `aim.sdk.run.Run` instead of `aim.sdk.run.BasicRun`, so that it can utilise it's extra capabilities.
### Alternatives
Instead of inheritance we could change the system resource tracking be a mixin?
| 2023-04-21T18:03:17Z | 2023-05-04T19:09:01Z | [] | [] | ["tests/ext/test_tensorboard_run.py::TestTensorboardRun::test_tensorboard_tracker_run__terminal_capture", "tests/ext/test_tensorboard_run.py::TestTensorboardRun::test_tensorboard_tracker_run__system_params_captured", "tests/ext/test_tensorboard_run.py::TestTensorboardRun::test_tensorboard_tracker_run__system_stats_captured", "tests/ext/test_tensorboard_run.py::TestTensorboardRun::test_tensorboard_tracker_run__default_no_capture"] | [] | {"install": ["uv pip install -e ."], "pre_install": ["tee pytest.ini <<EOF_1234810234\n[pytest]\naddopts = --color=no -rA --tb=no -p no:cacheprovider --pdbcls=IPython.terminal.debugger:Pdb\n\n\nEOF_1234810234"], "python": "3.11", "pip_packages": ["absl-py==1.4.0", "aimrecords==0.0.7", "aimrocks==0.4.0", "aiofiles==23.1.0", "alembic==1.10.4", "anyio==3.6.2", "astunparse==1.6.3", "backoff==2.2.1", "base58==2.0.1", "bleach==6.0.0", "cachetools==5.3.0", "certifi==2022.12.7", "cffi==1.15.1", "charset-normalizer==3.1.0", "click==8.1.3", "cmake==3.26.3", "coverage==7.2.5", "cryptography==40.0.2", "docutils==0.19", "fastapi==0.95.1", "filelock==3.12.0", "flake8==6.0.0", "flatbuffers==23.3.3", "gast==0.4.0", "google-auth==2.17.3", "google-auth-oauthlib==1.0.0", "google-pasta==0.2.0", "greenlet==2.0.2", "grpcio==1.54.0", "h11==0.14.0", "h5py==3.8.0", "httpcore==0.17.0", "httpx==0.24.0", "idna==3.4", "importlib-metadata==6.6.0", "iniconfig==2.0.0", "jaraco-classes==3.2.3", "jax==0.4.8", "jeepney==0.8.0", "jinja2==3.1.2", "keras==2.12.0", "keyring==23.13.1", "libclang==16.0.0", "lit==16.0.2", "mako==1.2.4", "markdown==3.4.3", "markdown-it-py==2.2.0", "markupsafe==2.1.2", "mccabe==0.7.0", "mdurl==0.1.2", "ml-dtypes==0.1.0", "monotonic==1.6", "more-itertools==9.1.0", "mpmath==1.3.0", "networkx==3.1", "numpy==1.23.5", "nvidia-cublas-cu11==11.10.3.66", "nvidia-cuda-cupti-cu11==11.7.101", "nvidia-cuda-nvrtc-cu11==11.7.99", "nvidia-cuda-runtime-cu11==11.7.99", "nvidia-cudnn-cu11==8.5.0.96", "nvidia-cufft-cu11==10.9.0.58", "nvidia-curand-cu11==10.2.10.91", "nvidia-cusolver-cu11==11.4.0.1", "nvidia-cusparse-cu11==11.7.4.91", "nvidia-nccl-cu11==2.14.3", "nvidia-nvtx-cu11==11.7.91", "oauthlib==3.2.2", "opt-einsum==3.3.0", "packaging==23.1", "pandas==2.0.1", "parameterized==0.8.1", "pillow==9.5.0", "pip==23.1.2", "pkginfo==1.9.6", "pluggy==1.0.0", "protobuf==4.22.4", "psutil==5.9.5", "py3nvml==0.2.7", "pyasn1==0.5.0", "pyasn1-modules==0.3.0", "pycodestyle==2.10.0", "pycparser==2.21", "pydantic==1.10.7", "pyflakes==3.0.1", "pygments==2.15.1", "pytest==7.3.1", "pytest-cov==2.12.1", "python-dateutil==2.8.2", "pytz==2023.3", "readme-renderer==37.3", "requests==2.30.0", "requests-oauthlib==1.3.1", "requests-toolbelt==1.0.0", "restrictedpython==6.0", "rfc3986==2.0.0", "rich==13.3.5", "rsa==4.9", "scipy==1.10.1", "secretstorage==3.3.3", "segment-analytics-python==2.2.2", "setuptools==67.7.2", "six==1.16.0", "sniffio==1.3.0", "sqlalchemy==1.4.48", "starlette==0.26.1", "sympy==1.11.1", "tensorboard==2.12.3", "tensorboard-data-server==0.7.0", "tensorflow==2.12.0", "tensorflow-estimator==2.12.0", "tensorflow-io-gcs-filesystem==0.32.0", "termcolor==2.3.0", "toml==0.10.2", "torch==2.0.0", "tqdm==4.65.0", "triton==2.0.0", "twine==4.0.2", "typing-extensions==4.5.0", "tzdata==2023.3", "urllib3==2.0.2", "uvicorn==0.22.0", "webencodings==0.5.1", "werkzeug==2.3.3", "wheel==0.40.0", "wrapt==1.14.1", "xmltodict==0.13.0", "zipp==3.15.0"]} | pytest --tb=no -rA -p no:cacheprovider | null | null | null |
|
aimhubio/aim | aimhubio__aim-2669 | fba120b9c1d47261dac68041d9938b9caa257b79 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57c867207b..2017eb2edd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,8 @@
### Fixes
-- Convert NaNs and Infs in responses to strings (n-gao)
+- Convert NaNs and Infs in responses to strings (n-gao)
+- Import `Image` and `Audio` for `TensorboardFolderTracker` (alansaul)
## 3.17.4 May 4, 2023
diff --git a/aim/ext/tensorboard_tracker/tracker.py b/aim/ext/tensorboard_tracker/tracker.py
index ce00b5e1e0..2d86d3c92a 100644
--- a/aim/ext/tensorboard_tracker/tracker.py
+++ b/aim/ext/tensorboard_tracker/tracker.py
@@ -10,10 +10,8 @@
import weakref
import queue
-from typing import TYPE_CHECKING, Any
-
-if TYPE_CHECKING:
- from aim import Audio, Image
+from typing import Any
+from aim import Audio, Image
class TensorboardTracker:
| diff --git a/tests/README.md b/tests/README.md
index 3b7f693039..8dbe0c6f2e 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -5,6 +5,7 @@ Be able to test the correctness of the
- `aim engine`
- `aim sdk`
- `aim ql`
+ - `extensions`
### Folder Structure
@@ -16,6 +17,8 @@ tests
test_*.py
ql
test_*.py
+ ext
+ test_*.py
```
## Run
diff --git a/tests/ext/__init__.py b/tests/ext/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/ext/test_tensorboard_tracker.py b/tests/ext/test_tensorboard_tracker.py
new file mode 100644
index 0000000000..545af772e0
--- /dev/null
+++ b/tests/ext/test_tensorboard_tracker.py
@@ -0,0 +1,113 @@
+from queue import Queue
+import numpy as np
+from PIL import ImageChops as PILImageChops
+import tensorflow as tf
+from tensorboard.compat.proto.summary_pb2 import SummaryMetadata, Summary
+from tensorboard.compat.proto.tensor_pb2 import TensorProto
+from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto
+from tensorboard.compat.proto.event_pb2 import Event
+from torch.utils.tensorboard.summary import image, scalar
+
+from aim import Image
+from aim.ext.tensorboard_tracker.tracker import TensorboardFolderTracker
+
+from tests.base import TestBase
+
+
+def images_same_data(image1: Image, image2: Image) -> bool:
+ """
+ Compare two Aim images to see if they contain the same values
+ """
+ image_diff = PILImageChops.difference(
+ image1.to_pil_image(), image2.to_pil_image()
+ )
+ return image_diff.getbbox() is None
+
+
+class TestTensorboardTracker(TestBase):
+
+ def test__process_tb_image_event(self):
+ # Given
+ queue = Queue()
+ tracker = TensorboardFolderTracker(tensorboard_event_folder='dummy', queue=queue)
+ height, width, channels = 5, 4, 3
+ # Note channels is last
+ image_np = np.random.randint(0, 16, (height, width, channels)).astype(dtype=np.uint8)
+ # Create image summary in standard format
+ image_summary = image(tag='test_image', tensor=image_np, dataformats='HWC')
+ event = Event(summary=image_summary)
+
+ # When
+ tracker._process_tb_event(event)
+
+ # Then
+ tracked_image = queue.get().value
+ original_image = Image(image_np)
+ self.assertTrue(isinstance(tracked_image, Image))
+ self.assertTrue(tracked_image.size == original_image.size)
+ self.assertTrue(images_same_data(tracked_image, original_image))
+
+ def test__process_tb_image_plugin_event(self):
+ # Given
+ queue = Queue()
+ tracker = TensorboardFolderTracker(tensorboard_event_folder='dummy', queue=queue)
+ height, width, channels = 5, 4, 3
+ # Note channels is last
+ image_np = np.random.randint(0, 16, (height, width, channels)).astype(dtype=np.uint8)
+ # Create image summary in format of plugin
+ plugin_data = SummaryMetadata.PluginData(plugin_name='images')
+ smd = SummaryMetadata(plugin_data=plugin_data, )
+ tensor = TensorProto(dtype='DT_STRING',
+ string_val=[
+ f"{height}".encode(encoding='utf_8'),
+ f"{width}".encode(encoding='utf_8'),
+ tf.image.encode_png(image_np).numpy(),
+ ],
+ tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=3)]))
+
+ image_summary = Summary(
+ value=[Summary.Value(tag='test_image', metadata=smd, tensor=tensor)]
+ )
+ event = Event(summary=image_summary)
+
+ # When
+ tracker._process_tb_event(event)
+
+ # Then
+ tracked_image = queue.get().value
+ original_image = Image(image_np)
+ self.assertTrue(isinstance(tracked_image, Image))
+ self.assertTrue(tracked_image.size == original_image.size)
+ self.assertTrue(images_same_data(tracked_image, original_image))
+
+ def test__process_tb_scalar_simple_value_event(self):
+ # Given
+ queue = Queue()
+ tracker = TensorboardFolderTracker(tensorboard_event_folder='dummy', queue=queue)
+ scalar_np = np.array(0.32, dtype=np.float32)
+ scalar_summary = scalar('test_scalar', scalar_np, new_style=False)
+ event = Event(summary=scalar_summary)
+
+ # When
+ tracker._process_tb_event(event)
+
+ # Then
+ tracked_scalar = queue.get().value
+ self.assertTrue(isinstance(tracked_scalar, float))
+ self.assertTrue(np.allclose(tracked_scalar, scalar_np))
+
+ def test__process_tb_scalar_plugin_event(self):
+ # Given
+ queue = Queue()
+ tracker = TensorboardFolderTracker(tensorboard_event_folder='dummy', queue=queue)
+ scalar_np = np.array(0.32, dtype=np.float32)
+ scalar_summary = scalar('test_scalar', scalar_np, new_style=True)
+ event = Event(summary=scalar_summary)
+
+ # When
+ tracker._process_tb_event(event)
+
+ # Then
+ tracked_scalar = queue.get().value
+ self.assertTrue(isinstance(tracked_scalar, np.ndarray))
+ self.assertTrue(np.allclose(tracked_scalar, scalar_np))
| `TensorboardFolderTracker` missing Image import
## 🐛 Bug
Currently the `TensorboardFolderTracker` will crash if there are any images that need to be parsed. This is because currently `aim.Image` is only imported during type checking, however `_process_tb_event` attempts to create an `Image` instance, without access
### To reproduce
- Create a tensorboard events file that contains an image
- Create a run using the `aim.ext.tensorboard_tracker.tracker.Run` runner.
- Observe the console
### Expected behavior
Images are converted and added to the RocksDB database.
### Environment
- Aim Version 3.17.3
- Python version 3.10.5
- pip version 22.0.4
- OS Ubuntu
- Any other relevant information
| 2023-04-21T16:13:40Z | 2023-05-04T18:59:37Z | ["tests/ext/test_tensorboard_tracker.py::TestTensorboardTracker::test__process_tb_scalar_plugin_event"] | [] | ["tests/ext/test_tensorboard_tracker.py::TestTensorboardTracker::test__process_tb_image_event", "tests/ext/test_tensorboard_tracker.py::TestTensorboardTracker::test__process_tb_image_plugin_event", "tests/ext/test_tensorboard_tracker.py::TestTensorboardTracker::test__process_tb_scalar_simple_value_event"] | [] | {"install": ["uv pip install -e ."], "pre_install": ["tee pytest.ini <<EOF_1234810234\n[pytest]\naddopts = --color=no -rA --tb=no -p no:cacheprovider --pdbcls=IPython.terminal.debugger:Pdb\n\n\nEOF_1234810234"], "python": "3.11", "pip_packages": ["absl-py==1.4.0", "aimrecords==0.0.7", "aimrocks==0.4.0", "aiofiles==23.1.0", "alembic==1.10.4", "anyio==3.6.2", "astunparse==1.6.3", "backoff==2.2.1", "base58==2.0.1", "bleach==6.0.0", "cachetools==5.3.0", "certifi==2022.12.7", "cffi==1.15.1", "charset-normalizer==3.1.0", "click==8.1.3", "cmake==3.26.3", "coverage==7.2.5", "cryptography==40.0.2", "docutils==0.19", "fastapi==0.95.1", "filelock==3.12.0", "flake8==6.0.0", "flatbuffers==23.3.3", "gast==0.4.0", "google-auth==2.17.3", "google-auth-oauthlib==1.0.0", "google-pasta==0.2.0", "greenlet==2.0.2", "grpcio==1.54.0", "h11==0.14.0", "h5py==3.8.0", "httpcore==0.17.0", "httpx==0.24.0", "idna==3.4", "importlib-metadata==6.6.0", "iniconfig==2.0.0", "jaraco-classes==3.2.3", "jax==0.4.8", "jeepney==0.8.0", "jinja2==3.1.2", "keras==2.12.0", "keyring==23.13.1", "libclang==16.0.0", "lit==16.0.2", "mako==1.2.4", "markdown==3.4.3", "markdown-it-py==2.2.0", "markupsafe==2.1.2", "mccabe==0.7.0", "mdurl==0.1.2", "ml-dtypes==0.1.0", "monotonic==1.6", "more-itertools==9.1.0", "mpmath==1.3.0", "networkx==3.1", "numpy==1.23.5", "nvidia-cublas-cu11==11.10.3.66", "nvidia-cuda-cupti-cu11==11.7.101", "nvidia-cuda-nvrtc-cu11==11.7.99", "nvidia-cuda-runtime-cu11==11.7.99", "nvidia-cudnn-cu11==8.5.0.96", "nvidia-cufft-cu11==10.9.0.58", "nvidia-curand-cu11==10.2.10.91", "nvidia-cusolver-cu11==11.4.0.1", "nvidia-cusparse-cu11==11.7.4.91", "nvidia-nccl-cu11==2.14.3", "nvidia-nvtx-cu11==11.7.91", "oauthlib==3.2.2", "opt-einsum==3.3.0", "packaging==23.1", "pandas==2.0.1", "parameterized==0.8.1", "pillow==9.5.0", "pip==23.1.2", "pkginfo==1.9.6", "pluggy==1.0.0", "protobuf==4.22.4", "psutil==5.9.5", "py3nvml==0.2.7", "pyasn1==0.5.0", "pyasn1-modules==0.3.0", "pycodestyle==2.10.0", "pycparser==2.21", "pydantic==1.10.7", "pyflakes==3.0.1", "pygments==2.15.1", "pytest==7.3.1", "pytest-cov==2.12.1", "python-dateutil==2.8.2", "pytz==2023.3", "readme-renderer==37.3", "requests==2.30.0", "requests-oauthlib==1.3.1", "requests-toolbelt==1.0.0", "restrictedpython==6.0", "rfc3986==2.0.0", "rich==13.3.5", "rsa==4.9", "scipy==1.10.1", "secretstorage==3.3.3", "segment-analytics-python==2.2.2", "setuptools==67.7.2", "six==1.16.0", "sniffio==1.3.0", "sqlalchemy==1.4.48", "starlette==0.26.1", "sympy==1.11.1", "tensorboard==2.12.3", "tensorboard-data-server==0.7.0", "tensorflow==2.12.0", "tensorflow-estimator==2.12.0", "tensorflow-io-gcs-filesystem==0.32.0", "termcolor==2.3.0", "toml==0.10.2", "torch==2.0.0", "tqdm==4.65.0", "triton==2.0.0", "twine==4.0.2", "typing-extensions==4.5.0", "tzdata==2023.3", "urllib3==2.0.2", "uvicorn==0.22.0", "webencodings==0.5.1", "werkzeug==2.3.3", "wheel==0.40.0", "wrapt==1.14.1", "xmltodict==0.13.0", "zipp==3.15.0"]} | pytest --tb=no -rA -p no:cacheprovider | null | null | null |
|
jpadilla/pyjwt | jpadilla__pyjwt-1005 | 26a63fc7cd54caa84aef7b4ac30f3f69b0037f6f | diff --git a/.gitignore b/.gitignore
index 1ab5db68..5cf69467 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,6 @@ target/
.mypy_cache
pip-wheel-metadata/
.venv/
+
+
+.idea
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 1ea1758b..0241b5b3 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -27,6 +27,8 @@ Changed
jwt.encode({"payload":"abc"}, key=None, algorithm='none')
```
+- Added validation for 'sub' (subject) and 'jti' (JWT ID) claims in tokens
+
Fixed
~~~~~
diff --git a/jwt/api_jwt.py b/jwt/api_jwt.py
index c82e6371..fa4d5e6f 100644
--- a/jwt/api_jwt.py
+++ b/jwt/api_jwt.py
@@ -15,6 +15,8 @@
InvalidAudienceError,
InvalidIssuedAtError,
InvalidIssuerError,
+ InvalidJTIError,
+ InvalidSubjectError,
MissingRequiredClaimError,
)
from .warnings import RemovedInPyjwt3Warning
@@ -39,6 +41,8 @@ def _get_default_options() -> dict[str, bool | list[str]]:
"verify_iat": True,
"verify_aud": True,
"verify_iss": True,
+ "verify_sub": True,
+ "verify_jti": True,
"require": [],
}
@@ -112,6 +116,7 @@ def decode_complete(
# consider putting in options
audience: str | Iterable[str] | None = None,
issuer: str | Sequence[str] | None = None,
+ subject: str | None = None,
leeway: float | timedelta = 0,
# kwargs
**kwargs: Any,
@@ -145,6 +150,8 @@ def decode_complete(
options.setdefault("verify_iat", False)
options.setdefault("verify_aud", False)
options.setdefault("verify_iss", False)
+ options.setdefault("verify_sub", False)
+ options.setdefault("verify_jti", False)
decoded = api_jws.decode_complete(
jwt,
@@ -158,7 +165,12 @@ def decode_complete(
merged_options = {**self.options, **options}
self._validate_claims(
- payload, merged_options, audience=audience, issuer=issuer, leeway=leeway
+ payload,
+ merged_options,
+ audience=audience,
+ issuer=issuer,
+ leeway=leeway,
+ subject=subject,
)
decoded["payload"] = payload
@@ -193,6 +205,7 @@ def decode(
# passthrough arguments to _validate_claims
# consider putting in options
audience: str | Iterable[str] | None = None,
+ subject: str | None = None,
issuer: str | Sequence[str] | None = None,
leeway: float | timedelta = 0,
# kwargs
@@ -214,6 +227,7 @@ def decode(
verify=verify,
detached_payload=detached_payload,
audience=audience,
+ subject=subject,
issuer=issuer,
leeway=leeway,
)
@@ -225,6 +239,7 @@ def _validate_claims(
options: dict[str, Any],
audience=None,
issuer=None,
+ subject: str | None = None,
leeway: float | timedelta = 0,
) -> None:
if isinstance(leeway, timedelta):
@@ -254,6 +269,12 @@ def _validate_claims(
payload, audience, strict=options.get("strict_aud", False)
)
+ if options["verify_sub"]:
+ self._validate_sub(payload, subject)
+
+ if options["verify_jti"]:
+ self._validate_jti(payload)
+
def _validate_required_claims(
self,
payload: dict[str, Any],
@@ -263,6 +284,39 @@ def _validate_required_claims(
if payload.get(claim) is None:
raise MissingRequiredClaimError(claim)
+ def _validate_sub(self, payload: dict[str, Any], subject=None) -> None:
+ """
+ Checks whether "sub" if in the payload is valid ot not.
+ This is an Optional claim
+
+ :param payload(dict): The payload which needs to be validated
+ :param subject(str): The subject of the token
+ """
+
+ if "sub" not in payload:
+ return
+
+ if not isinstance(payload["sub"], str):
+ raise InvalidSubjectError("Subject must be a string")
+
+ if subject is not None:
+ if payload.get("sub") != subject:
+ raise InvalidSubjectError("Invalid subject")
+
+ def _validate_jti(self, payload: dict[str, Any]) -> None:
+ """
+ Checks whether "jti" if in the payload is valid ot not
+ This is an Optional claim
+
+ :param payload(dict): The payload which needs to be validated
+ """
+
+ if "jti" not in payload:
+ return
+
+ if not isinstance(payload.get("jti"), str):
+ raise InvalidJTIError("JWT ID must be a string")
+
def _validate_iat(
self,
payload: dict[str, Any],
diff --git a/jwt/exceptions.py b/jwt/exceptions.py
index 0d985882..9b45ae48 100644
--- a/jwt/exceptions.py
+++ b/jwt/exceptions.py
@@ -72,3 +72,11 @@ class PyJWKClientError(PyJWTError):
class PyJWKClientConnectionError(PyJWKClientError):
pass
+
+
+class InvalidSubjectError(InvalidTokenError):
+ pass
+
+
+class InvalidJTIError(InvalidTokenError):
+ pass
| diff --git a/tests/test_api_jwt.py b/tests/test_api_jwt.py
index 3c0a975b..43fa2e21 100644
--- a/tests/test_api_jwt.py
+++ b/tests/test_api_jwt.py
@@ -14,6 +14,8 @@
InvalidAudienceError,
InvalidIssuedAtError,
InvalidIssuerError,
+ InvalidJTIError,
+ InvalidSubjectError,
MissingRequiredClaimError,
)
from jwt.utils import base64url_decode
@@ -816,3 +818,121 @@ def test_decode_strict_ok(self, jwt, payload):
options={"strict_aud": True},
algorithms=["HS256"],
)
+
+ # -------------------- Sub Claim Tests --------------------
+
+ def test_encode_decode_sub_claim(self, jwt):
+ payload = {
+ "sub": "user123",
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+ decoded = jwt.decode(token, secret, algorithms=["HS256"])
+
+ assert decoded["sub"] == "user123"
+
+ def test_decode_without_and_not_required_sub_claim(self, jwt):
+ payload = {}
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ decoded = jwt.decode(token, secret, algorithms=["HS256"])
+
+ assert "sub" not in decoded
+
+ def test_decode_missing_sub_but_required_claim(self, jwt):
+ payload = {}
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ with pytest.raises(MissingRequiredClaimError):
+ jwt.decode(
+ token, secret, algorithms=["HS256"], options={"require": ["sub"]}
+ )
+
+ def test_decode_invalid_int_sub_claim(self, jwt):
+ payload = {
+ "sub": 1224344,
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ with pytest.raises(InvalidSubjectError):
+ jwt.decode(token, secret, algorithms=["HS256"])
+
+ def test_decode_with_valid_sub_claim(self, jwt):
+ payload = {
+ "sub": "user123",
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ decoded = jwt.decode(token, secret, algorithms=["HS256"], subject="user123")
+
+ assert decoded["sub"] == "user123"
+
+ def test_decode_with_invalid_sub_claim(self, jwt):
+ payload = {
+ "sub": "user123",
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ with pytest.raises(InvalidSubjectError) as exc_info:
+ jwt.decode(token, secret, algorithms=["HS256"], subject="user456")
+
+ assert "Invalid subject" in str(exc_info.value)
+
+ def test_decode_with_sub_claim_and_none_subject(self, jwt):
+ payload = {
+ "sub": "user789",
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ decoded = jwt.decode(token, secret, algorithms=["HS256"], subject=None)
+ assert decoded["sub"] == "user789"
+
+ # -------------------- JTI Claim Tests --------------------
+
+ def test_encode_decode_with_valid_jti_claim(self, jwt):
+ payload = {
+ "jti": "unique-id-456",
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+ decoded = jwt.decode(token, secret, algorithms=["HS256"])
+
+ assert decoded["jti"] == "unique-id-456"
+
+ def test_decode_missing_jti_when_required_claim(self, jwt):
+ payload = {"name": "Bob", "admin": False}
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ with pytest.raises(MissingRequiredClaimError) as exc_info:
+ jwt.decode(
+ token, secret, algorithms=["HS256"], options={"require": ["jti"]}
+ )
+
+ assert "jti" in str(exc_info.value)
+
+ def test_decode_missing_jti_claim(self, jwt):
+ payload = {}
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ decoded = jwt.decode(token, secret, algorithms=["HS256"])
+
+ assert decoded.get("jti") is None
+
+ def test_jti_claim_with_invalid_int_value(self, jwt):
+ special_jti = 12223
+ payload = {
+ "jti": special_jti,
+ }
+ secret = "your-256-bit-secret"
+ token = jwt.encode(payload, secret, algorithm="HS256")
+
+ with pytest.raises(InvalidJTIError):
+ jwt.decode(token, secret, algorithms=["HS256"])
| Implement sub and jti check
Hello,
As per the jwt.org site, our library does not fully support all checks.
https://jwt.io/libraries?language=Python
Do we have a timeline for when sub and jti check might be implemented?
Thanks
| This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days
@jpadilla I've opened a PR #991 which can close this issue. Do let me know if it needs changes
@Divan009 thanks for the great for fixing this issue. The codecoverage test fails though on your PR.
When you have some free time, can you please take a look ?
Thanks again for your contribution !
@jpadilla @eddy2by4 I will write the test cases and fix the issue
Update: Added the Test cases | 2024-10-10T20:09:21Z | 2024-10-13T19:03:37Z | [] | [] | ["tests/test_api_jwt.py::TestJWT::test_check_issuer_list_when_valid", "tests/test_api_jwt.py::TestJWT::test_decode_no_algorithms_verify_signature_false", "tests/test_api_jwt.py::TestJWT::test_check_audience_when_valid", "tests/test_api_jwt.py::TestJWT::test_custom_json_encoder", "tests/test_api_jwt.py::TestJWT::test_decode_missing_jti_claim", "tests/test_api_jwt.py::TestJWT::test_raise_exception_token_without_issuer", "tests/test_api_jwt.py::TestJWT::test_decode_strict_aud_forbids_list_audience", "tests/test_api_jwt.py::TestJWT::test_decode_with_invalid_sub_claim", "tests/test_api_jwt.py::TestJWT::test_raise_exception_audience_as_bytes", "tests/test_api_jwt.py::TestJWT::test_check_issuer_when_valid", "tests/test_api_jwt.py::TestJWT::test_decode_with_verify_exp_option_and_signature_off", "tests/test_api_jwt.py::TestJWT::test_decode_with_invalid_audience_param_throws_exception", "tests/test_api_jwt.py::TestJWT::test_encode_decode_sub_claim", "tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_aud_is_none", "tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_iat_is_greater_than_now", "tests/test_api_jwt.py::TestJWT::test_decode_with_verify_exp_option", "tests/test_api_jwt.py::TestJWT::test_raise_exception_token_without_audience", "tests/test_api_jwt.py::TestJWT::test_check_audience_in_array_when_valid", "tests/test_api_jwt.py::TestJWT::test_raise_exception_invalid_issuer_list", "tests/test_api_jwt.py::TestJWT::test_check_audience_none_specified", "tests/test_api_jwt.py::TestJWT::test_decode_with_sub_claim_and_none_subject", "tests/test_api_jwt.py::TestJWT::test_decode_legacy_verify_warning", "tests/test_api_jwt.py::TestJWT::test_skip_check_audience", "tests/test_api_jwt.py::TestJWT::test_decode_strict_ok", "tests/test_api_jwt.py::TestJWT::test_decode_with_non_mapping_payload_throws_exception", "tests/test_api_jwt.py::TestJWT::test_raise_exception_invalid_audience_in_array", "tests/test_api_jwt.py::TestJWT::test_skip_check_nbf", "tests/test_api_jwt.py::TestJWT::test_decode_with_nonlist_aud_claim_throws_exception", "tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_exp_is_not_int", "tests/test_api_jwt.py::TestJWT::test_decode_warns_on_unsupported_kwarg", "tests/test_api_jwt.py::TestJWT::test_decode_with_expiration_with_leeway", "tests/test_api_jwt.py::TestJWT::test_raise_exception_invalid_audience_list", "tests/test_api_jwt.py::TestJWT::test_decodes_valid_rs384_jwt", "tests/test_api_jwt.py::TestJWT::test_decode_strict_aud_does_not_match", "tests/test_api_jwt.py::TestJWT::test_encode_bad_type", "tests/test_api_jwt.py::TestJWT::test_decode_skip_expiration_verification", "tests/test_api_jwt.py::TestJWT::test_raise_exception_invalid_audience", "tests/test_api_jwt.py::TestJWT::test_decodes_complete_valid_jwt", "tests/test_api_jwt.py::TestJWT::test_decode_with_optional_algorithms", "tests/test_api_jwt.py::TestJWT::test_decode_invalid_payload_string", "tests/test_api_jwt.py::TestJWT::test_encode_decode_with_valid_jti_claim", "tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_nbf_is_not_int", "tests/test_api_jwt.py::TestJWT::test_decode_with_notbefore_with_leeway", "tests/test_api_jwt.py::TestJWT::test_decode_without_and_not_required_sub_claim", "tests/test_api_jwt.py::TestJWT::test_decode_should_raise_error_if_iat_required_but_not_present", "tests/test_api_jwt.py::TestJWT::test_encode_with_typ", "tests/test_api_jwt.py::TestJWT::test_load_verify_valid_jwt", "tests/test_api_jwt.py::TestJWT::test_decode_with_invalid_aud_list_member_throws_exception", "tests/test_api_jwt.py::TestJWT::test_decode_should_raise_error_if_nbf_required_but_not_present", "tests/test_api_jwt.py::TestJWT::test_decode_with_expiration", "tests/test_api_jwt.py::TestJWT::test_skip_check_exp", "tests/test_api_jwt.py::TestJWT::test_skip_check_signature", "tests/test_api_jwt.py::TestJWT::test_decode_with_valid_sub_claim", "tests/test_api_jwt.py::TestJWT::test_skip_check_iat", "tests/test_api_jwt.py::TestJWT::test_decode_strict_aud_forbids_list_claim", "tests/test_api_jwt.py::TestJWT::test_decodes_valid_es256_jwt", "tests/test_api_jwt.py::TestJWT::test_decode_missing_jti_when_required_claim", "tests/test_api_jwt.py::TestJWT::test_raise_exception_token_with_aud_none_and_without_audience", "tests/test_api_jwt.py::TestJWT::test_decode_works_if_iat_is_str_of_a_number", "tests/test_api_jwt.py::TestJWT::test_decode_skip_notbefore_verification", "tests/test_api_jwt.py::TestJWT::test_decode_complete_warns_on_unsupported_kwarg", "tests/test_api_jwt.py::TestJWT::test_decode_raises_exception_if_iat_is_not_int", "tests/test_api_jwt.py::TestJWT::test_decode_invalid_int_sub_claim", "tests/test_api_jwt.py::TestJWT::test_jti_claim_with_invalid_int_value", "tests/test_api_jwt.py::TestJWT::test_raise_exception_invalid_issuer", "tests/test_api_jwt.py::TestJWT::test_decode_no_options_mutation", "tests/test_api_jwt.py::TestJWT::test_decode_with_notbefore", "tests/test_api_jwt.py::TestJWT::test_decode_missing_sub_but_required_claim", "tests/test_api_jwt.py::TestJWT::test_check_audience_list_when_valid", "tests/test_api_jwt.py::TestJWT::test_decode_should_raise_error_if_exp_required_but_not_present", "tests/test_api_jwt.py::TestJWT::test_decodes_valid_jwt", "tests/test_api_jwt.py::TestJWT::test_encode_datetime"] | [] | {"install": [], "pre_install": ["tee tox.ini <<EOF_1234810234\n[flake8]\nmin_python_version = 3.8\nignore= E501, E203, W503, E704\n\n[pytest]\naddopts = -ra\ntestpaths = tests\nfilterwarnings =\n once::Warning\n ignore:::pympler[.*]\n\n\n[gh-actions]\npython =\n 3.8: py38, typing\n 3.9: py39\n 3.10: py310\n 3.11: py311, docs\n 3.12: py312\n 3.13: py313\n pypy3.8: pypy3\n pypy3.9: pypy3\n\n\n[tox]\nenvlist =\n # lint\n # typing\n py{38,39,310,311,312,313,py3}-{crypto,nocrypto}\n # docs\n pypi-description\n coverage-report\nisolated_build = True\n\n\n[testenv]\n# Prevent random setuptools/pip breakages like\n# https://github.com/pypa/setuptools/issues/1042 from breaking our builds.\nsetenv =\n VIRTUALENV_NO_DOWNLOAD=1\nextras =\n tests\n crypto: crypto\ncommands = {envpython} -b -m coverage run -m pytest --color=no -rA --tb=no -p no:cacheprovider {posargs}\n\n\n[testenv:docs]\n# The tox config must match the ReadTheDocs config.\nbasepython = python3.11\nextras =\n docs\n crypto\ncommands =\n sphinx-build -n -T -W -b html -d {envtmpdir}/doctrees docs docs/_build/html\n sphinx-build -n -T -W -b doctest -d {envtmpdir}/doctrees docs docs/_build/html\n python -m doctest README.rst docs/usage.rst\n\n\n[testenv:lint]\nbasepython = python3.8\nextras = dev\npassenv = HOMEPATH # needed on Windows\ncommands = pre-commit run --all-files\n\n\n[testenv:pypi-description]\nbasepython = python3.8\nskip_install = true\ndeps =\n twine\n pip >= 18.0.0\ncommands =\n pip wheel -w {envtmpdir}/build --no-deps .\n twine check {envtmpdir}/build/*\n\n\n[testenv:coverage-report]\nbasepython = python3.8\nskip_install = true\ndeps = coverage[toml]==5.0.4\ncommands =\n coverage combine\n coverage report\n\nEOF_1234810234"], "python": "3.12", "pip_packages": ["cachetools==5.5.0", "cffi==1.17.1", "chardet==5.2.0", "colorama==0.4.6", "cryptography==43.0.1", "distlib==0.3.9", "filelock==3.16.1", "packaging==24.1", "platformdirs==4.3.6", "pluggy==1.5.0", "pycparser==2.22", "pyproject-api==1.8.0", "setuptools==75.1.0", "tox==4.21.2", "virtualenv==20.26.6", "wheel==0.44.0"]} | tox -- | null | null | null |
jpadilla/pyjwt | jpadilla__pyjwt-886 | 12420204cfef8fea7644532b9ca82c0cc5ca3abe | "diff --git a/docs/usage.rst b/docs/usage.rst\nindex 9a673c3e..55097e82 100644\n--- a/docs/usage.rst(...TRUNCATED) | "diff --git a/tests/test_api_jwk.py b/tests/test_api_jwk.py\nindex 4754db60..326e012a 100644\n--- a/(...TRUNCATED) | "Should `jwt.decode` accept `PyJWK` keys?\nFirst of all, thanks for `pyjwt`!\r\n\r\nI'm implementing(...TRUNCATED) | "Oh, I see now that each `PyJWK` also has a `key` attribute, which provides a concrete `Algorithm` i(...TRUNCATED) | 2023-04-28T23:01:35Z | 2024-05-11T19:55:49Z | "[\"tests/test_api_jws.py::TestJWS::test_decode_warns_on_unsupported_kwarg\", \"tests/test_api_jws.p(...TRUNCATED) | [] | "[\"tests/test_api_jwk.py::TestPyJWK::test_should_load_key_okp_without_alg_from_dict\", \"tests/test(...TRUNCATED) | [] | "{\"install\": [], \"pre_install\": [\"tee tox.ini <<EOF_1234810234\\n[flake8]\\nmin_python_version (...TRUNCATED) | tox -- | null | null | null |
jpadilla/pyjwt | jpadilla__pyjwt-881 | d8b12421654840418fd25b86553795c0c09ed0a9 | "diff --git a/jwt/algorithms.py b/jwt/algorithms.py\nindex 4bcf81b6..ed187152 100644\n--- a/jwt/algo(...TRUNCATED) | "diff --git a/tests/test_algorithms.py b/tests/test_algorithms.py\nindex 7a90376b..1a395527 100644\n(...TRUNCATED) | "Support returning `Algorithm.to_jwk(key)` as dict\nCurrently, the when generating a JWK, the only w(...TRUNCATED) | "Maybe with a `as_dict` argument to `to_jwk`, with a default value of `False` for backwards compatib(...TRUNCATED) | 2023-04-14T07:25:52Z | 2023-05-09T19:03:15Z | "[\"tests/test_algorithms.py::TestOKPAlgorithms::test_okp_ed448_jwk_fails_on_invalid_json\", \"tests(...TRUNCATED) | [] | "[\"tests/test_algorithms.py::TestOKPAlgorithms::test_okp_ed448_to_jwk_works_with_from_jwk[True]\", (...TRUNCATED) | [] | "{\"install\": [], \"pre_install\": [\"tee tox.ini <<EOF_1234810234\\n[flake8]\\nmin_python_version (...TRUNCATED) | tox -- | null | null | null |
jpadilla/pyjwt | jpadilla__pyjwt-847 | 4e15dbd9aaef56b78ac8f885220d94f785d2b30c | "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 3c69338f..12117ecc 100644\n--- a/CHANGELOG.rst\n+(...TRUNCATED) | "diff --git a/tests/test_api_jwt.py b/tests/test_api_jwt.py\nindex d74973df..24ed240d 100644\n--- a/(...TRUNCATED) | "PyJWT 2.6.0 IAT Decode Error - TypeError: '>' not supported between instances of 'str' and 'int'\n#(...TRUNCATED) | "+1, same for me\r\n\r\nmy test is\r\n```Python\r\nimport jwt\r\n\r\ndecoded = jwt.decode(data, pub_(...TRUNCATED) | 2023-01-04T18:40:06Z | 2023-01-15T03:13:02Z | "[\"tests/test_api_jwt.py::TestJWT::test_decode_no_algorithms_verify_signature_false\", \"tests/test(...TRUNCATED) | [] | "[\"tests/test_api_jwt.py::TestJWT::test_decode_works_if_iat_is_str_of_a_number\", \"tests/test_api_(...TRUNCATED) | [] | "{\"install\": [], \"pre_install\": [\"tee tox.ini <<EOF_1234810234\\n[flake8]\\nmin_python_version (...TRUNCATED) | tox -- | null | null | null |
jpadilla/pyjwt | jpadilla__pyjwt-775 | 345549567dbb58fd7bf901392cf6b1a626f36e24 | "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 8ec7ede8..4d562070 100644\n--- a/CHANGELOG.rst\n+(...TRUNCATED) | "diff --git a/tests/test_algorithms.py b/tests/test_algorithms.py\nindex 538078af..894ce282 100644\n(...TRUNCATED) | "Support exposure of hash algorithm digest to handle OIDC at_hash, potentially other spec extensions(...TRUNCATED) | "This issue is stale because it has been open 60 days with no activity. Remove stale label or commen(...TRUNCATED) | 2022-07-03T17:06:45Z | 2022-11-02T11:01:53Z | "[\"tests/test_algorithms.py::TestOKPAlgorithms::test_okp_ed448_jwk_fails_on_invalid_json\", \"tests(...TRUNCATED) | [] | "[\"tests/test_algorithms.py::TestOKPAlgorithms::test_rsa_can_compute_digest\", \"tests/test_algorit(...TRUNCATED) | [] | "{\"install\": [], \"pre_install\": [\"tee tox.ini <<EOF_1234810234\\n[flake8]\\nmin_python_version (...TRUNCATED) | tox -- | null | null | null |
jpadilla/pyjwt | jpadilla__pyjwt-725 | 77d791681fa3d0ba65a648de42dd3d671138cb95 | "diff --git a/CHANGELOG.rst b/CHANGELOG.rst\nindex 498a544a..06d281c1 100644\n--- a/CHANGELOG.rst\n+(...TRUNCATED) | "diff --git a/tests/test_api_jwk.py b/tests/test_api_jwk.py\nindex 53c05473..6f6cb899 100644\n--- a/(...TRUNCATED) | "New API: Retrieving a key by KID from a `PyJWKSet`?\nFirst of all, thanks for creating and maintain(...TRUNCATED) | 2022-01-21T15:45:48Z | 2022-01-25T02:12:53Z | "[\"tests/test_api_jwk.py::TestPyJWK::test_should_load_key_ec_p521_from_dict\", \"tests/test_api_jwk(...TRUNCATED) | [] | "[\"tests/test_api_jwk.py::TestPyJWKSet::test_keyset_should_index_by_kid\", \"tests/test_api_jwk.py:(...TRUNCATED) | [] | "{\"install\": [], \"pre_install\": [\"tee tox.ini <<EOF_1234810234\\n[pytest]\\naddopts = -ra\\ntes(...TRUNCATED) | tox -- | null | null | null |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 38