repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
changedetection.io
changedetectionio/diff/tokenizers/__init__.py
.py
""" Tokenizers for diff operations. This module provides various tokenization strategies for use with the diff system. New tokenizers can be easily added by: 1. Creating a new module in this directory 2. Importing and registering it in the TOKENIZERS dictionary below """ from .natural_text import tokenize_words from ...
24
604
changedetection.io
changedetectionio/diff/tokenizers/words_and_html.py
.py
""" Tokenizer that preserves HTML tags as atomic units while splitting on whitespace. This tokenizer is specifically designed for HTML content where: - HTML tags should remain intact (e.g., '<p>', '<a href="...">') - Whitespace tokens are preserved for accurate diff reconstruction - Words are split on whitespace bound...
62
1,743
changedetection.io
changedetectionio/browser_steps/browser_steps.py
.py
import os import time import re from random import randint from loguru import logger from changedetectionio.content_fetchers import SCREENSHOT_MAX_HEIGHT_DEFAULT from changedetectionio.content_fetchers.base import manage_user_agent from changedetectionio.jinja2_custom import render as jinja_render def browser_steps_g...
509
21,234
changedetection.io
changedetectionio/widgets/__init__.py
.py
from .ternary_boolean import TernaryNoneBooleanWidget, TernaryNoneBooleanField __all__ = ['TernaryNoneBooleanWidget', 'TernaryNoneBooleanField']
3
145
changedetection.io
changedetectionio/widgets/ternary_boolean.py
.py
from wtforms import Field from markupsafe import Markup from flask_babel import lazy_gettext as _l class TernaryNoneBooleanWidget: """ A widget that renders a horizontal radio button group with either two options (Yes/No) or three options (Yes/No/Default), depending on the field's boolean_mode setting. ...
104
4,341
changedetection.io
changedetectionio/widgets/test_custom_text.py
.py
#!/usr/bin/env python3 import sys import os from changedetectionio.model import USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) from changedetectionio.widgets import TernaryNoneBooleanField from wtforms import Form class TestForm(Form): # De...
138
5,616
changedetection.io
changedetectionio/store/file_saving_datastore.py
.py
""" File-based datastore with individual watch persistence and immediate commits. This module provides the FileSavingDataStore abstract class that implements: - Individual watch.json file persistence - Immediate commit-based persistence (watch.commit(), datastore.commit()) - Atomic file writes safe for NFS/NAS """ im...
510
17,341
changedetection.io
changedetectionio/store/__init__.py
.py
import shutil from changedetectionio.strtobool import strtobool from changedetectionio.validate_url import is_safe_valid_url from flask import ( flash ) from flask_babel import gettext from ..model import App, Watch from copy import deepcopy from os import path, unlink import json import os import re import sec...
1,167
48,311
changedetection.io
changedetectionio/store/updates.py
.py
""" Schema update migrations for the datastore. This module contains all schema version upgrade methods (update_1 through update_N). These are mixed into ChangeDetectionStore to keep the main store file focused. IMPORTANT: Each update could be run even when they have a new install and the schema is correct. Therefore...
875
41,118
changedetection.io
changedetectionio/store/base.py
.py
""" Base classes for the datastore. This module defines the abstract interfaces that all datastore implementations must follow. """ from abc import ABC, abstractmethod from threading import Lock from loguru import logger class DataStore(ABC): """ Abstract base class for all datastore implementations. D...
84
1,827
changedetection.io
changedetectionio/jinja2_custom/__init__.py
.py
""" Jinja2 custom extensions and safe rendering utilities. """ from .extensions.TimeExtension import TimeExtension from .safe_jinja import ( render, render_fully_escaped, create_jinja_env, JINJA2_MAX_RETURN_PAYLOAD_SIZE, DEFAULT_JINJA2_EXTENSIONS, ) from .plugins.regex import regex_replace __all__ ...
23
505
changedetection.io
changedetectionio/jinja2_custom/safe_jinja.py
.py
""" Safe Jinja2 render with max payload sizes See https://jinja.palletsprojects.com/en/3.1.x/sandbox/#security-considerations """ import jinja2.sandbox import typing as t import os from .extensions.TimeExtension import TimeExtension from .plugins import regex_replace JINJA2_MAX_RETURN_PAYLOAD_SIZE = 1024 * int(os.ge...
65
2,149
changedetection.io
changedetectionio/jinja2_custom/extensions/TimeExtension.py
.py
""" Jinja2 TimeExtension - Custom date/time handling for templates. This extension provides the {% now %} tag for Jinja2 templates, offering timezone-aware date/time formatting with support for time offsets. Why This Extension Exists: The Arrow library has a now() function (arrow.now()), but Jinja2 templates cann...
221
8,276
changedetection.io
changedetectionio/jinja2_custom/plugins/__init__.py
.py
""" Jinja2 custom filter plugins for changedetection.io """ from .regex import regex_replace __all__ = ['regex_replace']
7
122
changedetection.io
changedetectionio/jinja2_custom/plugins/regex.py
.py
""" Regex filter plugin for Jinja2 templates. Provides regex_replace filter for pattern-based string replacements in templates. """ import re import signal from loguru import logger def regex_replace(value: str, pattern: str, replacement: str = '', count: int = 0) -> str: """ Replace occurrences of a regex p...
99
3,638
changedetection.io
changedetectionio/processors/exceptions.py
.py
class ProcessorException(Exception): def __init__(self, message=None, status_code=None, url=None, screenshot=None, has_filters=False, html_content='', xpath_data=None): self.message = message self.status_code = status_code self.url = url self.screenshot = screenshot self.has_...
11
435
changedetection.io
changedetectionio/processors/extract.py
.py
""" Base data extraction module for all processors. This module handles extracting data from watch history using regex patterns and exporting to CSV format. This is the default extractor that all processors (text_json_diff, restock_diff, etc.) can use by default or override. """ import os from flask_babel import gett...
130
4,825
changedetection.io
changedetectionio/processors/__init__.py
.py
from functools import lru_cache from loguru import logger from flask_babel import gettext, get_locale import importlib import inspect import os import pkgutil def find_sub_packages(package_name): """ Find all sub-packages within the given package. :param package_name: The name of the base package to scan ...
502
19,420
changedetection.io
changedetectionio/processors/magic.py
.py
""" Content Type Detection and Stream Classification This module provides intelligent content-type detection for changedetection.io. It addresses the common problem where HTTP Content-Type headers are missing, incorrect, or too generic, which would otherwise cause the wrong processor to be used. The guess_stream_type...
140
6,344
changedetection.io
changedetectionio/processors/difference_base.py
.py
""" Base contract + shared helpers for a processor's history/diff ("difference") page. Each processor can provide a custom history/diff view by shipping a ``processors/<name>/difference.py`` module that exposes a module-level ``render(...)`` function. The route ``blueprint/ui/diff.py::diff_history_page`` resolves it v...
98
4,383
changedetection.io
changedetectionio/processors/base.py
.py
import asyncio import re import hashlib from changedetectionio.browser_steps.browser_steps import browser_steps_get_valid_steps from changedetectionio.content_fetchers.base import Fetcher from changedetectionio.strtobool import strtobool from changedetectionio.validate_url import is_private_hostname, is_url_private_or...
396
17,050
changedetection.io
changedetectionio/processors/image_ssim_diff/difference.py
.py
""" Screenshot diff visualization for fast image comparison processor. All image operations now use ImageDiffHandler abstraction for clean separation of concerns and easy backend swapping (LibVIPS, OpenCV, PIL, etc.). """ import os import json import time from flask_babel import gettext from loguru import logger fro...
442
18,167
changedetection.io
changedetectionio/processors/image_ssim_diff/util.py
.py
""" DEPRECATED: All multiprocessing functions have been removed. The image_ssim_diff processor now uses LibVIPS via ImageDiffHandler abstraction, which provides superior performance and memory efficiency through streaming architecture and automatic threading. All image operations are now handled by: - imagehandler.py...
23
924
changedetection.io
changedetectionio/processors/image_ssim_diff/preview.py
.py
""" Preview rendering for SSIM screenshot processor. Renders images properly in the browser instead of showing raw bytes. """ from flask_babel import gettext from loguru import logger def get_asset(asset_name, watch, datastore, request): """ Get processor-specific binary assets for preview streaming. T...
111
3,721
changedetection.io
changedetectionio/processors/image_ssim_diff/__init__.py
.py
""" Visual/screenshot change detection using fast image comparison algorithms. This processor compares screenshots using OpenCV (cv2.absdiff), which is 10-100x faster than SSIM while still detecting meaningful visual changes. """ import os from pathlib import Path processor_description = "Visual/Screenshot change de...
40
1,378
changedetection.io
changedetectionio/processors/image_ssim_diff/edit_hook.py
.py
""" Optional hook called when processor settings are saved in edit page. This hook analyzes the selected region to determine if template matching should be enabled for tracking content movement. Template matching is controlled via ENABLE_TEMPLATE_TRACKING env var (default: False). """ import io import os from loguru...
152
5,904
changedetection.io
changedetectionio/processors/image_ssim_diff/processor.py
.py
""" Core fast screenshot comparison processor. Uses OpenCV with subprocess isolation for high-performance, low-memory image processing. All operations run in isolated subprocesses for complete memory cleanup and stability. """ import hashlib import time from loguru import logger from changedetectionio.processors.exce...
245
12,241
changedetection.io
changedetectionio/processors/image_ssim_diff/forms.py
.py
""" Configuration forms for fast screenshot comparison processor. """ from wtforms import SelectField, StringField, validators, ValidationError, IntegerField from flask_babel import lazy_gettext as _l from changedetectionio.forms import processor_text_json_diff_form import re from changedetectionio.processors.image_s...
121
5,035
changedetection.io
changedetectionio/processors/image_ssim_diff/image_handler/isolated_opencv.py
.py
""" OpenCV-based subprocess isolation for image comparison. OpenCV is much more stable in multiprocessing contexts than LibVIPS. No threading issues, no fork problems, picklable functions. """ import multiprocessing import numpy as np from .. import POLL_TIMEOUT_ABSOLUTE # Public implementation name for logging IMPL...
628
27,437
changedetection.io
changedetectionio/processors/image_ssim_diff/image_handler/__init__.py
.py
""" Abstract base class for image processing operations. All image operations for the image_ssim_diff processor must be implemented through this interface to allow different backends (libvips, OpenCV, PIL, etc.). """ from abc import ABC, abstractmethod from typing import Tuple, Optional, Any class ImageDiffHandler(...
243
6,273
changedetection.io
changedetectionio/processors/image_ssim_diff/image_handler/libvips_handler.py
.py
""" LibVIPS implementation of ImageDiffHandler. Uses pyvips for high-performance image processing with streaming architecture and low memory footprint. Ideal for large screenshots (8000px+). """ from __future__ import annotations import os from typing import Tuple, Any, TYPE_CHECKING from loguru import logger if TYP...
341
11,767
changedetection.io
changedetectionio/processors/image_ssim_diff/image_handler/isolated_libvips.py
.py
""" Subprocess-isolated image operations for memory leak prevention. LibVIPS accumulates C-level memory in long-running processes that cannot be reclaimed by Python's GC or libvips cache management. Using subprocess isolation ensures complete memory cleanup when the process exits. This module wraps LibvipsImageDiffHa...
352
12,993
changedetection.io
changedetectionio/processors/restock_diff/difference.py
.py
""" History/diff rendering for the restock_diff (price / stock availability) processor. A text diff is meaningless for restock watches - each history snapshot is just a short string like "In Stock: True - Price: 12.34". So instead of a diff, this renders the whole timeline as a simple smoothed line graph of price over...
208
8,075
changedetection.io
changedetectionio/processors/restock_diff/pure_python_extractor.py
.py
""" Pure Python metadata extractor - no lxml, no memory leaks. This module provides a fast, memory-efficient alternative to extruct for common e-commerce metadata extraction. It handles: - JSON-LD (covers 80%+ of modern sites) - OpenGraph meta tags - Basic microdata attributes Uses Python's built-in html.parser inste...
290
10,470
changedetection.io
changedetectionio/processors/restock_diff/__init__.py
.py
from babel.numbers import parse_decimal from changedetectionio.model.Watch import model as BaseWatch from decimal import Decimal, InvalidOperation from typing import Union import re # Processor capabilities supports_visual_selector = True supports_browser_steps = True supports_text_filters_and_triggers = True support...
139
5,418
changedetection.io
changedetectionio/processors/restock_diff/processor.py
.py
from ..base import difference_detection_processor from ..exceptions import ProcessorException from . import Restock from loguru import logger from changedetectionio.content_fetchers.exceptions import checksumFromPreviousCheckWasTheSame import urllib3 import time urllib3.disable_warnings(urllib3.exceptions.InsecureReq...
678
34,219
changedetection.io
changedetectionio/processors/restock_diff/forms.py
.py
from wtforms import ( BooleanField, validators, FloatField ) from wtforms.fields.choices import RadioField from wtforms.fields.form import FormField from wtforms.form import Form from flask_babel import lazy_gettext as _l from changedetectionio.forms import processor_text_json_diff_form class RestockSett...
82
4,571
changedetection.io
changedetectionio/processors/restock_diff/plugins/llm_restock.py
.py
""" LLM fallback plugin for price and restock info extraction. When the built-in structured-metadata extraction (JSON-LD, microdata, OpenGraph) fails to produce both a price and availability, this plugin is called as a last resort. It sends a trimmed, HTML-stripped version of the page to the configured LLM and asks i...
369
17,830
changedetection.io
changedetectionio/processors/text_json_diff/difference.py
.py
""" History/diff rendering for text_json_diff processor. This module handles the visualization of text/HTML/JSON changes by rendering a side-by-side or unified diff view with syntax highlighting and change markers. """ import os import time from flask_babel import gettext from loguru import logger from changedetecti...
247
10,566
changedetection.io
changedetectionio/processors/text_json_diff/__init__.py
.py
from loguru import logger # Processor capabilities supports_visual_selector = True supports_browser_steps = True supports_text_filters_and_triggers = True supports_text_filters_and_triggers_elements = True supports_request_type = True def _task(watch, update_handler): from changedetectionio.content_fetchers.exc...
207
9,800
changedetection.io
changedetectionio/processors/text_json_diff/processor.py
.py
# HTML to TEXT/JSON DIFFERENCE self.fetcher import hashlib import json import os import re import urllib3 from changedetectionio.conditions import execute_ruleset_against_all_plugins from changedetectionio.content_fetchers.exceptions import checksumFromPreviousCheckWasTheSame from ..base import difference_detection_p...
691
30,373
changedetection.io
changedetectionio/llm/evaluator.py
.py
""" LLM evaluation orchestration. Two public entry points: - run_setup(watch, datastore) — one-time: decide if pre-filter needed - evaluate_change(watch, datastore, diff, current_snapshot) — per-change evaluation Intent resolution: watch.llm_intent → first tag with llm_intent → None (no evaluation) Cache: ...
860
35,606
changedetection.io
changedetectionio/llm/prompt_builder.py
.py
""" Prompt construction for LLM evaluation calls. Pure functions — no side effects, fully testable. """ import re from .bm25_trim import trim_to_relevant _AGO_RE = re.compile(r'^\d+\s+\w+\s+ago$', re.IGNORECASE) SNAPSHOT_CONTEXT_CHARS = 30_000 # current page state excerpt sent alongside the diff def _annotate_m...
217
10,519
changedetection.io
changedetectionio/llm/client.py
.py
""" Thin wrapper around litellm.completion. Keeps litellm import isolated so the rest of the codebase doesn't depend on it directly, and makes the call easy to mock in tests. """ import logging import os from loguru import logger # Default output token cap for JSON-returning calls (intent eval, preview, setup). # The...
205
8,708
changedetection.io
changedetectionio/llm/bm25_trim.py
.py
""" BM25-based relevance trimming for large snapshot text. When a snapshot is large and no CSS pre-filter has narrowed it down, we use BM25 to select the lines most relevant to the user's intent before sending to the LLM. This keeps the context focused without an arbitrary char truncation. Pure functions — no side ef...
53
1,666
changedetection.io
changedetectionio/llm/ui_strings.py
.py
""" Shared UI placeholder strings for LLM fields. Used by WTForms field definitions in forms.py and blueprint/tags/form.py. Templates use their own _()-translated variants but should stay in sync with these. """ # llm_intent field — placeholder text for per-watch context LLM_INTENT_WATCH_PLACEHOLDER = ( "e.g. Ale...
19
623
changedetection.io
changedetectionio/llm/response_parser.py
.py
""" Parse and validate LLM JSON responses. Pure functions — no side effects, fully testable. LLMs occasionally return JSON wrapped in markdown fences or with trailing text. This module handles those cases gracefully. """ import json import re # Positional selectors are fragile — reject them even if the LLM generates...
85
2,760
changedetection.io
changedetectionio/notification/email_helpers.py
.py
def as_monospaced_html_email(content: str, title: str) -> str: """ Wraps `content` in a minimal, email-safe HTML template that forces monospace rendering across Gmail, Hotmail, Apple Mail, etc. Args: content: The body text (plain text or HTML-like). title: The title plaintext Return...
42
1,487
changedetection.io
changedetectionio/notification/__init__.py
.py
from changedetectionio.model import USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH default_notification_format = 'htmlcolor' default_notification_body = '{{watch_url}} had a change.\n---\n{{diff}}\n---\n' default_notification_title = 'ChangeDetection.io Notification - {{watch_url}}' # The values (markdown etc) are ...
17
729
changedetection.io
changedetectionio/notification/handler.py
.py
import time import re import apprise from apprise import NotifyFormat from loguru import logger from urllib.parse import urlparse from .apprise_plugin.assets import apprise_asset, APPRISE_AVATAR_URL from .email_helpers import as_monospaced_html_email from ..diff import HTML_REMOVED_STYLE, REMOVED_PLACEMARKER_OPEN, REM...
567
28,716
changedetection.io
changedetectionio/notification/apprise_plugin/assets.py
.py
from apprise import AppriseAsset # Refer to: # https://github.com/caronc/apprise/wiki/Development_API#the-apprise-asset-object APPRISE_APP_ID = "changedetection.io" APPRISE_APP_DESC = "ChangeDetection.io best and simplest website monitoring and change detection" APPRISE_APP_URL = "https://changedetection.io" APPRISE_...
17
614
changedetection.io
changedetectionio/notification/apprise_plugin/discord.py
.py
""" Custom Discord plugin for changedetection.io Extends Apprise's Discord plugin to support custom colored embeds for removed/added content """ from apprise.plugins.discord import NotifyDiscord from apprise.decorators import notify from apprise.common import NotifyFormat from loguru import logger # Import placeholder...
287
11,595
changedetection.io
changedetectionio/notification/apprise_plugin/custom_handlers.py
.py
""" Custom Apprise HTTP Handlers with format= Parameter Support IMPORTANT: This module works around a limitation in Apprise's @notify decorator. THE PROBLEM: ------------- When using Apprise's @notify decorator to create custom notification handlers, the decorator creates a CustomNotifyPlugin that uses parse_url(...,...
225
8,236
changedetection.io
changedetectionio/conditions/pluggy_interface.py
.py
import pluggy import os import importlib import sys from . import default_plugin # ✅ Ensure that the namespace in HookspecMarker matches PluginManager PLUGIN_NAMESPACE = "changedetectionio_conditions" hookspec = pluggy.HookspecMarker(PLUGIN_NAMESPACE) hookimpl = pluggy.HookimplMarker(PLUGIN_NAMESPACE) class Conditi...
75
2,374
changedetection.io
changedetectionio/conditions/exceptions.py
.py
class EmptyConditionRuleRowNotUsable(Exception): def __init__(self): super().__init__("One of the 'conditions' rulesets is incomplete, cannot run.") def __str__(self): return self.args[0]
6
212
changedetection.io
changedetectionio/conditions/__init__.py
.py
from json_logic.builtins import BUILTINS from flask_babel import lazy_gettext as _l from .exceptions import EmptyConditionRuleRowNotUsable from .pluggy_interface import plugin_manager # Import the pluggy plugin manager from . import default_plugin from loguru import logger # List of all supported JSON Logic operators...
169
6,589
changedetection.io
changedetectionio/conditions/default_plugin.py
.py
import re import pluggy from price_parser import Price from loguru import logger from flask_babel import lazy_gettext as _l hookimpl = pluggy.HookimplMarker("changedetectionio_conditions") @hookimpl def register_operators(): def starts_with(_, text, prefix): return text.lower().strip().startswith(str(pr...
85
2,921
changedetection.io
changedetectionio/conditions/form.py
.py
# Condition Rule Form (for each rule row) from wtforms import Form, SelectField, StringField, validators from wtforms import validators from flask_babel import lazy_gettext as _l class ConditionFormRow(Form): # ✅ Ensure Plugins Are Loaded BEFORE Importing Choices from changedetectionio.conditions import plugi...
45
1,724
changedetection.io
changedetectionio/conditions/blueprint.py
.py
# Flask Blueprint Definition import json from flask import Blueprint from changedetectionio.conditions import execute_ruleset_against_all_plugins def construct_blueprint(datastore): from changedetectionio.flask_app import login_optionally_required conditions_blueprint = Blueprint('conditions', __name__, te...
81
3,373
changedetection.io
changedetectionio/conditions/plugins/levenshtein_plugin.py
.py
""" Levenshtein distance and similarity plugin for text change detection. Provides metrics for measuring text similarity between snapshots. """ import pluggy from loguru import logger from flask_babel import gettext as _, lazy_gettext as _l LEVENSHTEIN_MAX_LEN_FOR_EDIT_STATS=100000 # Support both plugin systems condi...
125
4,675
changedetection.io
changedetectionio/conditions/plugins/wordcount_plugin.py
.py
""" Word count plugin for content analysis. Provides word count metrics for snapshot content. """ import pluggy from loguru import logger from flask_babel import gettext as _, lazy_gettext as _l # Support both plugin systems conditions_hookimpl = pluggy.HookimplMarker("changedetectionio_conditions") global_hookimpl = ...
87
2,822
changedetection.io
changedetectionio/model/persistence.py
.py
""" Entity persistence mixin for Watch and Tag models. Provides file-based persistence using atomic writes. """ import functools import inspect @functools.lru_cache(maxsize=None) def _determine_entity_type(cls): """ Determine entity type from class hierarchy (cached at class level). Args: cls: ...
85
2,605
changedetection.io
changedetectionio/model/App.py
.py
from os import getenv from copy import deepcopy from changedetectionio.blueprint.rss import RSS_FORMAT_TYPES, RSS_CONTENT_FORMAT_DEFAULT from changedetectionio.model.Tags import TagsDict from changedetectionio.notification import ( default_notification_body, default_notification_format, default_notificati...
110
5,870
changedetection.io
changedetectionio/model/Tag.py
.py
""" Tag/Group domain model for organizing and overriding watch settings. ARCHITECTURE NOTE: Configuration Override Hierarchy =================================================== Tags can override Watch settings when overrides_watch=True. Current implementation requires manual checking in processors: for tag_uuid ...
72
2,876
changedetection.io
changedetectionio/model/Watch.py
.py
""" Watch domain model for change detection monitoring. ARCHITECTURE NOTE: Configuration Override Hierarchy =================================================== This module implements Watch objects that inherit from dict (technical debt). The dream architecture would use Pydantic for: 1. CHAIN RESOLUTION (Watch → Tag...
1,315
52,875
changedetection.io
changedetectionio/model/__init__.py
.py
import os import uuid from changedetectionio import strtobool from .persistence import EntityPersistenceMixin, _determine_entity_type __all__ = ['EntityPersistenceMixin', 'watch_base'] from ..browser_steps.browser_steps import browser_steps_get_valid_steps USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH = 'System ...
680
29,625
changedetection.io
changedetectionio/model/schema_utils.py
.py
""" Schema utilities for Watch and Tag models. Provides functions to extract readonly fields and properties from OpenAPI spec. Shared by both the model layer and API layer to avoid circular dependencies. """ import functools # Watch fields written by workers/processors that are NOT part of the public OpenAPI spec. ...
122
4,381
changedetection.io
changedetectionio/model/LLMSettings.py
.py
""" Validation/typing layer for the LLM config dict stored at datastore.data['settings']['application']['llm'] Storage stays a plain dict (orjson-serialized). This model is hydrated on read (model_validate) and dumped on write (model_dump). WTForms field names match the storage field names exactly — no aliases nee...
71
3,067
changedetection.io
changedetectionio/model/Tags.py
.py
import os import shutil from pathlib import Path from loguru import logger _SENTINEL = object() class TagsDict(dict): """Dict subclass that removes the corresponding tag.json file when a tag is deleted.""" def __init__(self, *args, datastore_path: str | os.PathLike, **kwargs) -> None: self._datastor...
40
1,374
changedetection.io
changedetectionio/tests/test_block_while_text_present.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches from changedetectionio import html_tools import os def set_original_ignore_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> ...
154
5,081
changedetection.io
changedetectionio/tests/test_trigger_regex_with_filter.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, delete_all_watches, wait_for_all_checks import os def set_original_ignore_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Which is across multiple lines</p> ...
82
2,561
changedetection.io
changedetectionio/tests/test_clone.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks import os def test_clone_functionality(client, live_server, measure_memory_usage, datastore_path): # live_server_setup(live_server) # Setup on conftest per function with open(os.path.join(da...
38
1,226
changedetection.io
changedetectionio/tests/test_api.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches import os import json import uuid def set_original_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Which is across mul...
1,455
57,200
changedetection.io
changedetectionio/tests/test_xpath_selector.py
.py
# -*- coding: utf-8 -*- from flask import url_for from .util import wait_for_all_checks, delete_all_watches from ..processors.magic import RSS_XML_CONTENT_TYPES import os def set_rss_atom_feed_response(datastore_path, header='', ): test_return_data = f"""{header}<!-- Generated on Wed, 08 Oct 2025 08:42:33 -070...
671
26,153
changedetection.io
changedetectionio/tests/test_notification_restock_token.py
.py
""" Regression tests for issue #3490 - "'restock' is undefined". A `{{ restock.price }}` token is accepted in a per-watch notification body (restock watches inject the value via processors/restock_diff extra_notification_token_values()), but the same token in a system-wide / non-restock context had no default. That ma...
44
1,850
changedetection.io
changedetectionio/tests/test_source.py
.py
#!/usr/bin/env python3 import time from flask import url_for from urllib.request import urlopen from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks from ..diff import ADDED_STYLE def test_check_basic_change_detection_functionality_source(client, live_server, measure...
86
3,151
changedetection.io
changedetectionio/tests/test_add_replace_remove_filter.py
.py
#!/usr/bin/env python3 import os.path import os from flask import url_for from .util import live_server_setup, wait_for_all_checks, wait_for_notification_endpoint_output, delete_all_watches import time from ..diff import ADDED_PLACEMARKER_OPEN def set_original(datastore_path, excluding=None, add_line=None): te...
186
7,234
changedetection.io
changedetectionio/tests/test_queue_handler.py
.py
import os import time from flask import url_for from .util import set_original_response, wait_for_all_checks, wait_for_notification_endpoint_output from ..notification import valid_notification_formats from loguru import logger def test_queue_system(client, live_server, measure_memory_usage, datastore_path): """...
53
2,575
changedetection.io
changedetectionio/tests/test_backend.py
.py
#!/usr/bin/env python3 import os import time from flask import url_for from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks, extract_rss_token_from_UI, \ extract_UUID_from_client, delete_all_watches # Basic test to check inscriptus is not adding return line chars...
450
17,987
changedetection.io
changedetectionio/tests/test_download_patch.py
.py
#!/usr/bin/env python3 """ Tests for the /diff/<uuid>/download-patch endpoint. The route should accept from_version and to_version query parameters, read those two snapshots from the watch history, generate a unified diff patch, and return it as a downloadable text/plain file. """ from flask import url_for from chan...
107
3,951
changedetection.io
changedetectionio/tests/test_api_tags.py
.py
#!/usr/bin/env python3 from flask import url_for from .util import live_server_setup, wait_for_all_checks, set_original_response import json import time def test_api_tags_listing(client, live_server, measure_memory_usage, datastore_path): # live_server_setup(live_server) # Setup on conftest per function api_k...
324
11,073
changedetection.io
changedetectionio/tests/test_llm_api_key_security.py
.py
#!/usr/bin/env python3 """ Security tests: LLM API key must never appear in any API response. The LLM API key is a secret credential stored in datastore.data['settings']['application']['llm']['api_key']. It must never be leaked through any API endpoint — watch GET/list, tag GET/list, system-info, notifications — even ...
676
27,989
changedetection.io
changedetectionio/tests/test_commit_persistence.py
.py
#!/usr/bin/env python3 """ Tests for immediate commit-based persistence system. Tests cover: - Watch.commit() persistence to disk - Concurrent commit safety (race conditions) - Processor config separation - Data loss prevention (settings, tags, watch modifications) """ import json import os import threading import ti...
662
24,538
changedetection.io
changedetectionio/tests/test_nonrenderable_pages.py
.py
#!/usr/bin/env python3 from flask import url_for from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks, delete_all_watches import time import os def set_nonrenderable_response(datastore_path): test_return_data = """<html> <head><title>modified head title</titl...
119
3,874
changedetection.io
changedetectionio/tests/test_llm_token_budget.py
.py
#!/usr/bin/env python3 """ Tests that verify global LLM token budget counters cannot be tampered with via the API (watch PUT) or via form submissions (settings page POST). This is critical for hosted deployments where the operator sets LLM_TOKEN_BUDGET_MONTH in the container — tenants must not be able to reset or infl...
574
23,452
changedetection.io
changedetectionio/tests/test_conditions.py
.py
#!/usr/bin/env python3 import json import time import os from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches from ..model import CONDITIONS_MATCH_LOGIC_DEFAULT def set_original_response(datastore_path, number="50"): test_return_data = f"""<html> <body> ...
326
11,804
changedetection.io
changedetectionio/tests/test_llm_change_summary.py
.py
#!/usr/bin/env python3 """ Integration tests for AI Change Summary: - llm_change_summary field saved via watch edit form - llm_change_summary cascades from tag to watches - {{ diff }} replaced by AI summary in notifications - {{ raw_diff }} always contains original diff - summarise_change only runs when chang...
485
18,219
changedetection.io
changedetectionio/tests/test_pdf.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks import os # `subtractive_selectors` should still work in `source:` type requests def test_fetch_pdf(client, live_server, measure_memory_usage, datastore_...
85
3,540
changedetection.io
changedetectionio/tests/test_scheduler.py
.py
#!/usr/bin/env python3 import time from copy import copy from datetime import datetime, timezone from zoneinfo import ZoneInfo from flask import url_for from .util import live_server_setup, wait_for_all_checks, extract_UUID_from_client, delete_all_watches from ..forms import REQUIRE_ATLEAST_ONE_TIME_PART_MESSAGE_DEFA...
210
8,591
changedetection.io
changedetectionio/tests/test_llm_group_overrides.py
.py
#!/usr/bin/env python3 """ Tests for group/tag LLM field overrides on the watch edit page. When a watch's first linked tag has llm_intent or llm_change_summary set and the watch itself has no own value, the watch edit form should render the relevant textarea as readonly with a "From group '<name>': <value>" placeholde...
385
14,791
changedetection.io
changedetectionio/tests/test_encoding.py
.py
#!/usr/bin/env python3 # coding=utf-8 import hashlib import time from flask import url_for from .util import live_server_setup, wait_for_all_checks, extract_UUID_from_client import pytest import os def test_surrogate_characters_in_content_are_sanitized(): """Lone surrogates can appear in requests' r.text when...
138
5,933
changedetection.io
changedetectionio/tests/test_access_control.py
.py
from .util import live_server_setup, wait_for_all_checks from flask import url_for import time def test_check_access_control(app, client, live_server, measure_memory_usage, datastore_path): # Still doesnt work, but this is closer. # live_server_setup(live_server) # Setup on conftest per function with app....
211
8,768
changedetection.io
changedetectionio/tests/test_settings_tag_force_reprocess.py
.py
#!/usr/bin/env python3 """ Test that changing global settings or tag configurations forces reprocessing. When settings or tag configurations change, all affected watches need to reprocess even if their content hasn't changed, because configuration affects the processing result. """ import os import time from flask im...
209
7,856
changedetection.io
changedetectionio/tests/test_preview_endpoints.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks import os # `subtractive_selectors` should still work in `source:` type requests def test_fetch_pdf(client, live_server, measure_memory_usage, datastore_...
69
2,582
changedetection.io
changedetectionio/tests/test_jsonpath_jq_selector.py
.py
#!/usr/bin/env python3 # coding=utf-8 import time from flask import url_for from markupsafe import escape from . util import live_server_setup, wait_for_all_checks, delete_all_watches import pytest import os jq_support = True try: import jq except ModuleNotFoundError: jq_support = False def test_jsonp_trea...
597
24,739
changedetection.io
changedetectionio/tests/test_rss_single_watch.py
.py
#!/usr/bin/env python3 import time import os import xml.etree.ElementTree as ET from flask import url_for from .restock.test_restock import set_original_response from .util import live_server_setup, wait_for_all_checks, extract_rss_token_from_UI, extract_UUID_from_client, delete_all_watches, set_modified_response fro...
372
14,133
changedetection.io
changedetectionio/tests/test_llm_all_changes_diff.py
.py
#!/usr/bin/env python3 """ Tests for the 'AI: every change between versions' (all_changes=1) feature. Covers: - all_changes=1 builds a multi-segment diff (pairwise across intermediate snapshots) - all_changes=0 (default) uses a single from→to diff - the two modes are cached under separate keys (no cross-contamin...
184
6,812
changedetection.io
changedetectionio/tests/test_ignore_text.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches from changedetectionio import html_tools import os # Unit test of the stripper # Always we are dealing in utf-8 def test_strip_text_func(): test_content = """ Some conten...
262
9,537
changedetection.io
changedetectionio/tests/test_trigger.py
.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks import os def set_original_ignore_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Which is across multiple lines</p> <br> So let'...
158
5,320
changedetection.io
changedetectionio/tests/util.py
.py
#!/usr/bin/env python3 from operator import truediv from flask import make_response, request, current_app from flask import url_for import logging import time import os import threading # Thread-safe global storage for test endpoint content # Avoids filesystem cache issues in parallel tests _test_endpoint_content_loc...
436
15,509