diff --git a/roles/web-app-wordpress/README.md b/roles/web-app-wordpress/README.md index e0077fa26b..090bd40392 100644 --- a/roles/web-app-wordpress/README.md +++ b/roles/web-app-wordpress/README.md @@ -34,7 +34,7 @@ This automated Docker Compose deployment streamlines the process by building a c ## Features - **Automated provisioning:** Configured by Ansible without manual steps. -- **WordPress options from the configuration:** Every entry of `services.wordpress.options` in [services.yml](meta/services.yml) is written with `wp option update` whenever WordPress stores a different value, and a change flushes the rewrite rules. An inventory sets any option through `applications.web-app-wordpress.services.wordpress.options.`: the key carries `# nocheck: inventory-open-subtree`, so the inventory validator accepts names [services.yml](meta/services.yml) does not declare. Options the role writes elsewhere (`WORDPRESS_OPTIONS_OWNED_ELSEWHERE` in [main.yml](vars/main.yml)) and keys that name a secret are refused. `permalink_structure` is pinned to `/blog/%year%/%monthnum%/%day%/%postname%/`, the structure the blog published its post URLs under. +- **WordPress options from the configuration:** `WORDPRESS_OPTIONS` in [main.yml](vars/main.yml) is one map: `admin_email` is the platform administrator's email, `blogname` is the design title while the `design` service is on, and the `config.options` of the `freedomtranslate-wp` addon join while that addon is on; `services.wordpress.options` from [services.yml](meta/services.yml) and the inventory overlay them, so an inventory entry wins. Every entry is written with `wp option update` whenever WordPress stores a different value, and a write that changes the stored value flushes the rewrite rules. Every deploy therefore sets `admin_email`, and `blogname` while the design is on, back to the configured value: a change made in wp-admin is reverted. An inventory sets any option through `applications.web-app-wordpress.services.wordpress.options.`: the key carries `# nocheck: inventory-open-subtree`, so the inventory validator accepts names [services.yml](meta/services.yml) does not declare. Options the role computes or WordPress manages (`WORDPRESS_OPTIONS_OWNED_ELSEWHERE` in [main.yml](vars/main.yml)) and keys that name a secret are refused. `permalink_structure` is pinned to `/blog/%year%/%monthnum%/%day%/%postname%/`, the structure the blog published its post URLs under. ## Purpose diff --git a/roles/web-app-wordpress/files/php/design.php b/roles/web-app-wordpress/files/php/design.php index d47624684d..1a72d2c78c 100644 --- a/roles/web-app-wordpress/files/php/design.php +++ b/roles/web-app-wordpress/files/php/design.php @@ -5,7 +5,6 @@ * Required env: * WORDPRESS_DESIGN base64 of a JSON object * enabled "true" applies the design, anything else withdraws what an earlier run applied - * title site title, "" for none * directory directory below wp-content that holds the stylesheets and the rendered logo set * logos {"site_icon": "", "site_logo": ""}, {} for none * stylesheets file names the mu-plugin enqueues from the directory @@ -13,8 +12,8 @@ * scheme {"name", "colors": [, ...], "icons": {"base", "focus", "current"}} * tokens URLs of the token stylesheets the editor canvas loads * - * Title, site icon, site logo and a global styles post are written only while they are unset or still hold what an - * earlier run wrote. An account moves from the default admin color scheme to the corporate one once. + * Site icon, site logo and a global styles post are written only while they are unset or still hold what an earlier + * run wrote. An account moves from the default admin color scheme to the corporate one once. * * Stdout, last line: changed | unchanged */ @@ -34,7 +33,7 @@ $config = json_decode((string) base64_decode((string) getenv('WORDPRESS_DESIGN') $enabled = filter_var($config['enabled'], FILTER_VALIDATE_BOOLEAN); $directory = WP_CONTENT_DIR . '/' . $config['directory']; $applied = (get_option(INFINITO_DESIGN_OPTION) ?: []) - + ['title' => '', 'logos' => [], 'global_styles' => [], 'stylesheets' => []]; + + ['logos' => [], 'global_styles' => [], 'stylesheets' => []]; $changed = false; $fail = static function (string $message): void { @@ -42,20 +41,7 @@ $fail = static function (string $message): void { exit(1); }; -$owned = ['title' => '', 'logos' => [], 'global_styles' => [], 'stylesheets' => []]; - -$title = $enabled ? (string) $config['title'] : ''; -$presentTitle = (string) get_option('blogname'); -if ($title !== '') { - if ($presentTitle === '' || ($presentTitle === $applied['title'] && $presentTitle !== $title)) { - update_option('blogname', $title); - $presentTitle = $title; - $changed = true; - } - if ($presentTitle === $title) { - $owned['title'] = $title; - } -} +$owned = ['logos' => [], 'global_styles' => [], 'stylesheets' => []]; $attachment = static function (string $option, string $file) use (&$changed, $fail): int { $bytes = file_get_contents($file); diff --git a/roles/web-app-wordpress/tasks/07_manager_ops.yml b/roles/web-app-wordpress/tasks/07_manager_ops.yml index 1dac11e59a..e3d32c9e48 100644 --- a/roles/web-app-wordpress/tasks/07_manager_ops.yml +++ b/roles/web-app-wordpress/tasks/07_manager_ops.yml @@ -66,6 +66,8 @@ label: "{{ item.item.key }}" when: item | wordpress_option_drifted register: wp_options_written + changed_when: >- + 'option is unchanged.' not in wp_options_written.stdout - name: "🚿 Flush the rewrite rules after a pinned option changed" shell: > @@ -73,6 +75,25 @@ wp rewrite flush --path={{ WORDPRESS_DOCKER_HTML_PATH }} when: wp_options_written is changed +- name: "🌍 Verify FreedomTranslate posts to the translation gateway" + when: WORDPRESS_TRANSLATE_ENABLED | bool + block: + - name: "🔎 Read the gateway URL back out of WordPress" + ansible.builtin.shell: > + container exec -u {{ WORDPRESS_USER }} {{ WORDPRESS_CONTAINER_ADDRESS }} + wp option get freedomtranslate_api_url --path={{ WORDPRESS_DOCKER_HTML_PATH }} + register: wordpress_translate_readback + changed_when: false + + - name: "🛑 Refuse a plugin that translates somewhere else" + ansible.builtin.assert: + that: + - (wordpress_translate_readback.stdout | trim) == WORDPRESS_TRANSLATE_ENDPOINT + fail_msg: >- + freedomtranslate-wp posts to '{{ wordpress_translate_readback.stdout | trim }}' + instead of {{ WORDPRESS_TRANSLATE_ENDPOINT }}, so the content would be + translated outside this deployment or not at all. + - name: 🔍 Detect if WordPress is Multisite shell: > container exec -u {{ WORDPRESS_USER }} {{ WORDPRESS_CONTAINER_ADDRESS }} diff --git a/roles/web-app-wordpress/tasks/addons/freedomtranslate-wp-stack-host.yml b/roles/web-app-wordpress/tasks/addons/freedomtranslate-wp-stack-host.yml index dc7369511a..f15fe261cb 100644 --- a/roles/web-app-wordpress/tasks/addons/freedomtranslate-wp-stack-host.yml +++ b/roles/web-app-wordpress/tasks/addons/freedomtranslate-wp-stack-host.yml @@ -3,30 +3,3 @@ ansible.builtin.include_tasks: ../utils/install/plugin.yml vars: plugin_name: freedomtranslate-wp - -- name: "🔧 Point FreedomTranslate at the translation gateway" - ansible.builtin.shell: > - container exec -u {{ WORDPRESS_USER }} {{ WORDPRESS_CONTAINER_ADDRESS }} - wp option update {{ item.name }} {{ item.value | quote }} - --path={{ WORDPRESS_DOCKER_HTML_PATH }} - loop: "{{ WORDPRESS_TRANSLATE_OPTIONS }}" - loop_control: - label: "{{ item.name }}" - register: wordpress_translate_option - changed_when: "'Success' in wordpress_translate_option.stdout" - -- name: "🔎 Read the gateway URL back out of WordPress" - ansible.builtin.shell: > - container exec -u {{ WORDPRESS_USER }} {{ WORDPRESS_CONTAINER_ADDRESS }} - wp option get freedomtranslate_api_url --path={{ WORDPRESS_DOCKER_HTML_PATH }} - register: wordpress_translate_readback - changed_when: false - -- name: "🛑 Refuse a plugin that translates somewhere else" - ansible.builtin.assert: - that: - - (wordpress_translate_readback.stdout | trim) == WORDPRESS_TRANSLATE_ENDPOINT - fail_msg: >- - freedomtranslate-wp posts to '{{ wordpress_translate_readback.stdout | trim }}' - instead of {{ WORDPRESS_TRANSLATE_ENDPOINT }}, so the content would be - translated outside this deployment or not at all. diff --git a/roles/web-app-wordpress/vars/main.yml b/roles/web-app-wordpress/vars/main.yml index e40f693219..36872353e8 100644 --- a/roles/web-app-wordpress/vars/main.yml +++ b/roles/web-app-wordpress/vars/main.yml @@ -62,18 +62,24 @@ WORDPRESS_PEERTUBE_INSTANCE_URL: >- WORDPRESS_S3_UPLOADS_ARCHIVE: >- {{ lookup('config', application_id, 'addons.s3-uploads.config.archive') if (lookup('config', application_id, 'addons.s3-uploads.enabled') | bool) else '' }} +WORDPRESS_TRANSLATE_ENABLED: "{{ lookup('config', application_id, 'addons.freedomtranslate-wp.enabled') | bool }}" WORDPRESS_TRANSLATE_OPTIONS: >- - {{ lookup('config', application_id, 'addons.freedomtranslate-wp.config.options') - if (lookup('config', application_id, 'addons.freedomtranslate-wp.enabled') | bool) else [] }} -WORDPRESS_TRANSLATE_ENDPOINT: >- - {{ (WORDPRESS_TRANSLATE_OPTIONS | selectattr('name', 'equalto', 'freedomtranslate_api_url') - | map(attribute='value') | first) | default('', true) }} + {{ (lookup('config', application_id, 'addons.freedomtranslate-wp.config.options') if WORDPRESS_TRANSLATE_ENABLED | bool else []) + | items2dict(key_name='name', value_name='value') }} +WORDPRESS_TRANSLATE_ENDPOINT: "{{ WORDPRESS_OPTIONS.freedomtranslate_api_url }}" WORDPRESS_S3_UPLOADS_SRC: "/usr/src/s3-uploads" WORDPRESS_S3_UPLOADS_DIR: "{{ [WORDPRESS_PLUGINS_DIR, 's3-uploads'] | path_join }}" -WORDPRESS_OPTIONS_OWNED_ELSEWHERE: "{{ ['home', 'siteurl', 'blogname', 'admin_email', 'active_plugins', 'rewrite_rules', 'openid_connect_generic_settings', 'mwai_options'] - + (lookup('config', application_id, 'addons.wp-discourse.config.discourse_settings') | map(attribute='name') | list) + (WORDPRESS_DESIGN_LOGOS.keys() | list) + - (WORDPRESS_TRANSLATE_OPTIONS | map(attribute='name') | list) }}" -WORDPRESS_OPTIONS: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.options') | wordpress_options_checked(WORDPRESS_OPTIONS_OWNED_ELSEWHERE) }}" +WORDPRESS_OPTIONS_OWNED_ELSEWHERE: >- + {{ ['home', 'siteurl', 'active_plugins', 'rewrite_rules', 'openid_connect_generic_settings', 'mwai_options'] + + (lookup('config', application_id, 'addons.wp-discourse.config.discourse_settings') | map(attribute='name') | list) + + (WORDPRESS_DESIGN_LOGOS.keys() | list) }} +WORDPRESS_OPTIONS_CONTRIBUTED: >- + {{ {'admin_email': WORDPRESS_ADMIN_EMAIL} + | combine({'blogname': WORDPRESS_DESIGN.title} if (WORDPRESS_DESIGN_ENABLED | bool and WORDPRESS_DESIGN.title is string and WORDPRESS_DESIGN.title) else {}) + | combine(WORDPRESS_TRANSLATE_OPTIONS) }} +WORDPRESS_OPTIONS: >- + {{ WORDPRESS_OPTIONS_CONTRIBUTED | combine(lookup('config', application_id, 'services.' ~ entity_name ~ '.options')) + | wordpress_options_checked(WORDPRESS_OPTIONS_OWNED_ELSEWHERE) }} WORDPRESS_ADMIN_EMAIL: "{{ lookup('config', application_id, 'users.platform_administrator.email') }}" WORDPRESS_ADMIN_USER: "{{ lookup('users', 'platform_administrator').username }}" @@ -94,7 +100,6 @@ WORDPRESS_DESIGN_SYNC: >- if cmp -s "$1.new" "$1"; then rm "$1.new"; else mv "$1.new" "$1" && echo CHANGED; fi WORDPRESS_DESIGN_CONFIG: enabled: "{{ WORDPRESS_DESIGN_ENABLED | string | lower }}" - title: "{{ WORDPRESS_DESIGN.title if WORDPRESS_DESIGN.title is string else '' }}" directory: "{{ WORDPRESS_DESIGN_DIRECTORY }}" logos: "{{ WORDPRESS_DESIGN_LOGOS if WORDPRESS_DESIGN.logo is string else {} }}" stylesheets: "{{ WORDPRESS_DESIGN_STYLESHEETS }}" diff --git a/tests/unit/python/roles/web-app-wordpress/filter_plugins/test_wordpress_options.py b/tests/unit/python/roles/web-app-wordpress/filter_plugins/test_wordpress_options.py index 8862a9b77b..a4be81e0de 100644 --- a/tests/unit/python/roles/web-app-wordpress/filter_plugins/test_wordpress_options.py +++ b/tests/unit/python/roles/web-app-wordpress/filter_plugins/test_wordpress_options.py @@ -30,7 +30,7 @@ MODULE = _load_module( ) STRUCTURE = "/blog/%year%/%monthnum%/%day%/%postname%/" -OWNED = ["home", "siteurl", "blogname", "admin_email", "discourse_connect"] +OWNED = ["home", "siteurl", "active_plugins", "discourse_connect"] def _checked(**options): @@ -58,6 +58,15 @@ class TestOptionsAccepted(unittest.TestCase): moderation_keys="spam", ) + def test_the_options_the_role_contributes_pass(self): + _checked( + permalink_structure=STRUCTURE, + admin_email="admin@example.test", + blogname="Blog by Example", + freedomtranslate_service="libretranslate", + freedomtranslate_api_url="https://translate.example.test/translate", + ) + class TestOptionsRefused(unittest.TestCase): def _refused(self, fragment: str, **options): @@ -95,7 +104,13 @@ class TestOptionsRefused(unittest.TestCase): MODULE.wordpress_options_checked(["permalink_structure"], OWNED) def test_a_secret_option_name_is_refused(self): - for name in ("mailserver_pass", "auth_key", "secure_auth_salt", "api_token"): + for name in ( + "mailserver_pass", + "auth_key", + "secure_auth_salt", + "api_token", + "freedomtranslate_api_key", + ): with self.subTest(name=name): self._refused( f"services.wordpress.options.{name}", diff --git a/tests/unit/python/roles/web-app-wordpress/test_options.py b/tests/unit/python/roles/web-app-wordpress/test_options.py index 0235016d2b..fa2c6cbf09 100644 --- a/tests/unit/python/roles/web-app-wordpress/test_options.py +++ b/tests/unit/python/roles/web-app-wordpress/test_options.py @@ -1,10 +1,12 @@ -"""``services.wordpress.options`` is the one place the role pins WordPress options. +"""``WORDPRESS_OPTIONS`` is the one map the role pins WordPress options from. -The permalink structure is pinned to the format the blog published its post -URLs under, the vars read the map through a strict config lookup, every option -the role writes through another path is refused by name, and the tasks in -``tasks/07_manager_ops.yml`` read each option, write only the ones that drift -and flush the rewrite rules after a write. +The map joins the role's contributions (``admin_email``, the design title as +``blogname``, the FreedomTranslate options) with ``services.wordpress.options`` +as the strict config lookup resolves it, so the role default and the +inventory both win over a contribution. Every option another path writes is +refused by name, and the tasks in ``tasks/07_manager_ops.yml`` read each +option, write only the ones that drift and flush the rewrite rules after a +write that changed the stored value. """ from __future__ import annotations @@ -16,8 +18,12 @@ import shlex import tempfile import unittest from pathlib import Path +from unittest import mock +from ansible.errors import AnsibleError from ansible.parsing.dataloader import DataLoader +from ansible.plugins.loader import filter_loader, lookup_loader +from ansible.plugins.lookup import LookupBase from ansible.template import Templar from plugins.lookup.config import LookupModule @@ -39,6 +45,13 @@ LITERAL_OPTION_WRITE = re.compile( r"wp option (?:update|add) ([a-z_][a-z0-9_]*)\b" r"|update_option\(\s*'([a-z_][a-z0-9_]*)'" ) +ADMIN_EMAIL = "admin@example.test" +DESIGN_TITLE = "Blog by Example & Partner" +DISCOURSE_OPTION = "discourse_connect" +TRANSLATE_ADDON = ROLE / "meta/addons/freedomtranslate-wp.yml" +TRANSLATE_TASKS = ROLE / "tasks/addons/freedomtranslate-wp-stack-host.yml" + +filter_loader.add_directory(str(ROLE / "filter_plugins")) def _vars() -> dict: @@ -53,11 +66,89 @@ def _task(fragment: str) -> dict: return next(t for t in _manager_tasks() if fragment in t["name"]) +def _position(fragment: str) -> int: + return next(i for i, t in enumerate(_manager_tasks()) if fragment in t["name"]) + + def _render(expression: str, **variables): templar = Templar(loader=DataLoader(), variables=variables) return templar.template(_trust_as_template(expression)) +def _translate_options() -> list[dict]: + addon = load_yaml_any(str(TRANSLATE_ADDON), default_if_missing={}) + return addon["config"]["options"] + + +class _Stub(LookupBase): + def __init__(self, answer): + super().__init__() + self._answer = answer + + def run(self, terms, variables=None, **kwargs): + return [self._answer(*terms)] + + +ALL_ON = { + "configured": {"permalink_structure": PINNED_STRUCTURE}, + "design": True, + "title": DESIGN_TITLE, + "translate": True, + "translate_options": _translate_options(), +} + + +def _resolve(name: str, scenario: dict): + """Resolve one variable of ``vars/main.yml`` through Ansible's templar. + + Args: + name: the variable to resolve. + scenario: ``configured`` is what ``services.wordpress.options`` + resolves to (role default and inventory merged), ``design`` is + ``services.design.enabled``, ``title`` is the design lookup's + ``title``, ``translate`` is ``addons.freedomtranslate-wp.enabled`` + and ``translate_options`` is that addon's ``config.options``. + + Returns: + The resolved value, with the role's own filter plugins loaded. + """ + config = { + "services.wordpress.options": scenario["configured"], + "users.platform_administrator.email": ADMIN_EMAIL, + "services.design.enabled": scenario["design"], + "addons.freedomtranslate-wp.enabled": scenario["translate"], + "addons.freedomtranslate-wp.config.options": scenario["translate_options"], + "addons.wp-discourse.config.discourse_settings": [{"name": DISCOURSE_OPTION}], + } + stubs = { + "config": lambda _app, path: config[path], + "design": lambda _app: {"title": scenario["title"]}, + } + real_get = lookup_loader.get + + def get(lookup_name, *args, **kwargs): + if lookup_name in stubs: + return _Stub(stubs[lookup_name]) + return real_get(lookup_name, *args, **kwargs) + + declared = DataLoader().load_from_file( + str(ROLE / ROLE_FILE_VARS_MAIN), trusted_as_template=True + ) + templar = Templar( + loader=DataLoader(), variables={**declared, "entity_name": "wordpress"} + ) + with mock.patch.object(lookup_loader, "get", side_effect=get): + return templar.template(declared[name]) + + +def _messages(error: BaseException) -> str: + parts = [] + while error is not None: + parts.append(str(error)) + error = error.__cause__ or error.__context__ + return "\n".join(parts) + + class TestPinnedStructure(unittest.TestCase): def test_services_pins_the_structure_of_the_published_urls(self): services = load_yaml_any( @@ -131,6 +222,77 @@ class TestStrictLookup(unittest.TestCase): self.assertEqual(out[0]["permalink_structure"], PINNED_STRUCTURE) +class TestEffectiveMap(unittest.TestCase): + def _options(self, scenario: dict) -> dict: + return _resolve("WORDPRESS_OPTIONS", scenario) + + def test_the_role_default_stays_in_the_map(self): + self.assertEqual(self._options(ALL_ON)["permalink_structure"], PINNED_STRUCTURE) + + def test_admin_email_is_the_platform_administrators(self): + self.assertEqual(self._options(ALL_ON)["admin_email"], ADMIN_EMAIL) + + def test_the_design_title_is_the_blogname_while_the_design_is_on(self): + self.assertEqual(self._options(ALL_ON)["blogname"], DESIGN_TITLE) + + def test_no_blogname_while_the_design_is_off(self): + self.assertNotIn("blogname", self._options(ALL_ON | {"design": False})) + + def test_no_blogname_when_the_design_replaces_no_title(self): + for title in (False, ""): + with self.subTest(title=title): + self.assertNotIn("blogname", self._options(ALL_ON | {"title": title})) + + def test_the_translate_options_join_while_the_addon_is_on(self): + options = self._options(ALL_ON) + declared = _translate_options() + self.assertTrue(declared, "the addon must declare its options") + for entry in declared: + with self.subTest(option=entry["name"]): + self.assertEqual(options[entry["name"]], entry["value"]) + + def test_no_translate_option_while_the_addon_is_off(self): + options = self._options(ALL_ON | {"translate": False}) + for entry in _translate_options(): + with self.subTest(option=entry["name"]): + self.assertNotIn(entry["name"], options) + + def test_an_inventory_entry_wins_over_every_contribution(self): + configured = { + "permalink_structure": PINNED_STRUCTURE, + "admin_email": "ops@example.test", + "blogname": "Own name", + "freedomtranslate_api_url": "https://translate.example.test/translate", + } + options = self._options(ALL_ON | {"configured": configured}) + for name, value in configured.items(): + with self.subTest(option=name): + self.assertEqual(options[name], value) + + def test_the_filter_guards_the_merged_map(self): + configured = {"permalink_structure": PINNED_STRUCTURE, "home": "https://x"} + with self.assertRaises(AnsibleError) as caught: + self._options(ALL_ON | {"configured": configured}) + self.assertIn("services.wordpress.options.home", _messages(caught.exception)) + + def test_a_secret_named_addon_option_is_refused(self): + leaked = [ + *_translate_options(), + {"name": "freedomtranslate_api_key", "value": "x"}, + ] + with self.assertRaises(AnsibleError) as caught: + self._options(ALL_ON | {"translate_options": leaked}) + self.assertIn("freedomtranslate_api_key", _messages(caught.exception)) + + def test_services_declares_no_option_a_contribution_sets(self): + services = load_yaml_any( + str(ROLE / ROLE_FILE_META_SERVICES), default_if_missing={} + ) + contributed = _resolve("WORDPRESS_OPTIONS_CONTRIBUTED", ALL_ON) + self.assertTrue(contributed) + self.assertFalse(set(services["wordpress"]["options"]) & set(contributed)) + + class TestOwnedElsewhere(unittest.TestCase): def test_every_option_the_role_writes_by_name_is_refused_by_the_map(self): owned = _vars()["WORDPRESS_OPTIONS_OWNED_ELSEWHERE"] @@ -147,12 +309,80 @@ class TestOwnedElsewhere(unittest.TestCase): with self.subTest(option=name): self.assertIn(f"'{name}'", owned) - def test_install_time_and_addon_options_are_owned(self): - owned = _vars()["WORDPRESS_OPTIONS_OWNED_ELSEWHERE"] - for name in ("home", "siteurl", "blogname", "admin_email", "active_plugins"): + def test_computed_and_wordpress_managed_options_stay_owned(self): + owned = _resolve("WORDPRESS_OPTIONS_OWNED_ELSEWHERE", ALL_ON) + for name in ( + "home", + "siteurl", + "active_plugins", + "rewrite_rules", + "openid_connect_generic_settings", + "mwai_options", + "site_icon", + "site_logo", + DISCOURSE_OPTION, + ): with self.subTest(option=name): - self.assertIn(f"'{name}'", owned) - self.assertIn("addons.wp-discourse.config.discourse_settings", owned) + self.assertIn(name, owned) + + def test_options_the_map_now_carries_left_the_owned_list(self): + owned = _resolve("WORDPRESS_OPTIONS_OWNED_ELSEWHERE", ALL_ON) + moved = ["admin_email", "blogname"] + [o["name"] for o in _translate_options()] + for name in moved: + with self.subTest(option=name): + self.assertNotIn(name, owned) + + def test_no_contribution_is_owned_elsewhere(self): + owned = _resolve("WORDPRESS_OPTIONS_OWNED_ELSEWHERE", ALL_ON) + contributed = _resolve("WORDPRESS_OPTIONS_CONTRIBUTED", ALL_ON) + self.assertFalse(set(owned) & set(contributed)) + + +class TestOrder(unittest.TestCase): + def test_options_are_read_after_the_plugins_are_installed(self): + self.assertLess( + _position("Iterate through WordPress plugins"), + _position("Read the WordPress options"), + ) + + def test_the_translate_readback_follows_the_options_write(self): + self.assertLess( + _position("Write each pinned WordPress option"), + _position("Verify FreedomTranslate"), + ) + + +class TestTranslateReadback(unittest.TestCase): + def test_the_addon_task_installs_the_plugin_and_writes_no_option(self): + tasks = load_yaml_any(str(TRANSLATE_TASKS), default_if_missing=[]) + self.assertEqual( + [t["vars"]["plugin_name"] for t in tasks], ["freedomtranslate-wp"] + ) + self.assertNotIn("wp option", read_text(str(TRANSLATE_TASKS))) + + def test_the_readback_runs_only_with_the_addon(self): + self.assertEqual( + _task("Verify FreedomTranslate")["when"], + "WORDPRESS_TRANSLATE_ENABLED | bool", + ) + + def test_the_expected_endpoint_follows_the_effective_map(self): + declared = {o["name"]: o["value"] for o in _translate_options()} + self.assertEqual( + _resolve("WORDPRESS_TRANSLATE_ENDPOINT", ALL_ON), + declared["freedomtranslate_api_url"], + ) + own = "https://translate.example.test/translate" + configured = { + "permalink_structure": PINNED_STRUCTURE, + "freedomtranslate_api_url": own, + } + self.assertEqual( + _resolve( + "WORDPRESS_TRANSLATE_ENDPOINT", ALL_ON | {"configured": configured} + ), + own, + ) class TestReadTask(unittest.TestCase): @@ -198,6 +428,15 @@ class TestWriteTask(unittest.TestCase): ) return shlex.split(rendered) + def _changed(self, stdout: str) -> bool: + changed_when = _task("Write each pinned WordPress option")["changed_when"] + return bool( + _render( + "{{ (" + changed_when + ") | bool }}", + wp_options_written={"stdout": stdout}, + ) + ) + def test_the_structure_reaches_wp_cli_as_one_json_argument(self): argv = self._argv("permalink_structure", PINNED_STRUCTURE) position = argv.index("update") @@ -217,6 +456,14 @@ class TestWriteTask(unittest.TestCase): self.assertEqual(task["when"], "item | wordpress_option_drifted") self.assertEqual(task["register"], "wp_options_written") + def test_an_updated_option_is_a_change(self): + self.assertTrue(self._changed("Success: Updated 'blogname' option.")) + + def test_a_value_wordpress_already_stores_sanitized_is_no_change(self): + self.assertFalse( + self._changed("Success: Value passed for 'blogname' option is unchanged.") + ) + class TestFlushTask(unittest.TestCase): def _flushes(self, written: dict) -> bool: