fix: harden CHRNX editor lifecycle

This commit is contained in:
chrnx committed 2026-08-11 15:06:50 -05:00
1 parent a5b94123a8
commit 835fb74ebf
12 files changed
+512 -95

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
import { execFileSync } from 'node:child_process';
import { expect, test } from '@playwright/test';
test.beforeAll( () => {
execFileSync(
'npm',
[ 'exec', '--', 'wp-env', 'run', 'cli', 'wp', 'eval', 'chrnx_seed_editorial_terms();' ],
{ cwd: process.cwd(), env: process.env, stdio: 'inherit' },
);
} );
test( 'editorial and podcast controls initialize in the real post editor', async ( { page } ) => {
const openPanel = async ( name ) => {
const button = page.getByRole( 'button', { name, exact: true } );
if ( ( await button.getAttribute( 'aria-expanded' ) ) !== 'true' ) {
await button.click();
}
};
await page.goto( '/wp-login.php' );
await page.locator( '#user_login' ).fill( 'admin' );
await page.locator( '#user_pass' ).fill( 'password' );
await Promise.all( [
page.waitForURL( /\/wp-admin\// ),
page.getByRole( 'button', { name: /log in/i } ).click(),
] );
await page.goto( '/wp-admin/post-new.php' );
const welcomeDialog = page.getByRole( 'dialog', { name: 'Welcome to the editor' } );
if ( await welcomeDialog.isVisible() ) {
await welcomeDialog.getByRole( 'button', { name: 'Close' } ).click();
}
await expect( page.getByRole( 'heading', { name: 'Add Post', exact: true } ) ).toBeVisible();
const podcasts = page.getByRole( 'radio', { name: 'Podcasts', exact: true } );
const settings = page.getByRole( 'button', { name: /^settings$/i } ).last();
if ( ( await settings.getAttribute( 'aria-expanded' ) ) !== 'true' ) {
await settings.click();
}
await openPanel( 'Topic' );
await expect( podcasts ).toBeVisible();
await openPanel( 'Language' );
await expect( page.getByRole( 'radio', { name: 'English', exact: true } ) ).toBeVisible();
await openPanel( 'Show' );
await expect( page.getByRole( 'radio', { name: 'Silicon Ranch', exact: true } ) ).toBeVisible();
await podcasts.check();
await openPanel( 'Podcast episode' );
await expect( page.getByLabel( 'Episode number', { exact: true } ) ).toBeVisible();
await expect( page.getByLabel( 'Duration', { exact: true } ) ).toBeVisible();
await expect( page.getByLabel( 'Participants (one per line)', { exact: true } ) ).toBeVisible();
await expect( page.getByLabel( 'Canonical episode URL', { exact: true } ) ).toBeVisible();
} );
+31 -3
View File
@@ -18,6 +18,7 @@ function createWp( topicSlug = 'podcasts' ) {
};
const wp = {
components: { TextControl: 'TextControl', TextareaControl: 'TextareaControl' },
i18n: { __: jest.fn( ( text ) => text ) },
data: {
select: ( store ) => {
if ( store === 'core/editor' ) {
@@ -55,6 +56,19 @@ describe( 'podcast editor helpers', () => {
);
} );
test( 'bounds participant transport to 50 names and 100 Unicode characters each', () => {
const helpers = require( modulePath );
const longUnicodeName = 'ñ'.repeat( 101 );
const lines = [ longUnicodeName ].concat(
Array.from( { length: 55 }, ( _value, index ) => `Guest ${ index }` ),
);
const participants = helpers.participantsFromText( lines.join( '\n' ) );
expect( participants ).toHaveLength( 50 );
expect( Array.from( participants[ 0 ] ) ).toHaveLength( 100 );
expect( participants[ 0 ] ).toBe( 'ñ'.repeat( 100 ) );
} );
test( 'updates one meta key while preserving unrelated metadata', () => {
const helpers = require( modulePath );
const editPost = jest.fn();
@@ -93,7 +107,7 @@ describe( 'podcast editor helpers', () => {
expect( nonPodcast.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull();
} );
test( 'fails closed when required globals or initial editor selector methods are missing', () => {
test( 'registers immediately while initial editor selectors are unresolved', () => {
const helpers = require( modulePath );
expect( helpers.initialize() ).toBe( false );
expect( helpers.initialize( {} ) ).toBe( false );
@@ -102,8 +116,8 @@ describe( 'podcast editor helpers', () => {
const missingEditorMethod = createWp();
missingEditorMethod.wp.data.select = () => editorSelector;
expect( () => helpers.initialize( missingEditorMethod.wp ) ).not.toThrow();
expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( false );
expect( missingEditorMethod.registerPlugin ).not.toHaveBeenCalled();
expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( true );
expect( missingEditorMethod.registerPlugin ).toHaveBeenCalledTimes( 2 );
expect( missingEditorMethod.editPost ).not.toHaveBeenCalled();
}
@@ -152,4 +166,18 @@ describe( 'podcast editor helpers', () => {
expect( unresolved.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull();
expect( unresolved.editPost ).not.toHaveBeenCalled();
} );
test( 'localizes podcast controls with the CHRNX text domain', () => {
const helpers = require( modulePath );
const { wp, registerPlugin } = createWp();
wp.i18n.__ = jest.fn( ( text, domain ) => `${ domain }:${ text }` );
helpers.initialize( wp );
const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render();
expect( tree.props.title ).toBe( 'chrnx:Podcast episode' );
expect( flatten( tree ).find( ( node ) => node.type === 'TextControl' ).props.label ).toBe(
'chrnx:Episode number',
);
expect( wp.i18n.__ ).toHaveBeenCalledWith( 'Podcast episode', 'chrnx' );
} );
} );
+38 -9
View File
@@ -14,9 +14,11 @@ function createWp( overrides = {} ) {
chrnx_language: [ { id: 4, name: 'English' } ],
chrnx_show: [ { id: 7, name: 'Silicon Ranch' } ],
};
const getEntityRecords = jest.fn( ( _kind, name ) => terms[ name ] );
const attributes = { type: 'post', topic: [ 3 ], language: [], show: [] };
const wp = {
components: { RadioControl: 'RadioControl' },
i18n: { __: jest.fn( ( text ) => text ) },
compose: {
compose:
( ...funcs ) =>
@@ -31,7 +33,7 @@ function createWp( overrides = {} ) {
getEditedPostAttribute: ( key ) => attributes[ key ],
};
}
return { getEntityRecords: ( _kind, name ) => terms[ name ] };
return { getEntityRecords };
},
dispatch: ( store ) => ( store === 'core/editor' ? { editPost } : {} ),
useDispatch,
@@ -48,7 +50,16 @@ function createWp( overrides = {} ) {
plugins: { registerPlugin },
...overrides,
};
return { wp, editPost, removeEditorPanel, registerPlugin, attributes, terms, useSelect };
return {
wp,
editPost,
getEntityRecords,
removeEditorPanel,
registerPlugin,
attributes,
terms,
useSelect,
};
}
describe( 'editor taxonomy helpers', () => {
@@ -71,7 +82,7 @@ describe( 'editor taxonomy helpers', () => {
test( 'removes native panels and registers three radio setting panels', () => {
const helpers = require( modulePath );
const { wp, removeEditorPanel, registerPlugin, useSelect } = createWp();
const { wp, getEntityRecords, removeEditorPanel, registerPlugin, useSelect } = createWp();
wp.data.dispatch = ( store ) =>
store === 'core/edit-post' ? { removeEditorPanel } : { editPost: jest.fn() };
@@ -81,13 +92,18 @@ describe( 'editor taxonomy helpers', () => {
const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render();
expect( useSelect ).toHaveBeenCalled();
expect( tree.children ).toHaveLength( 3 );
expect( getEntityRecords ).toHaveBeenCalledWith( 'taxonomy', 'chrnx_topic', {
per_page: 100,
orderby: 'name',
order: 'asc',
} );
tree.children.forEach( ( panel ) => {
expect( panel.type ).toBe( 'PluginDocumentSettingPanel' );
expect( panel.children[ 0 ].type ).toBe( 'RadioControl' );
} );
} );
test( 'fails closed when required globals or initial editor selector methods are missing', () => {
test( 'registers immediately while initial editor selectors are unresolved', () => {
const helpers = require( modulePath );
expect( helpers.initialize() ).toBe( false );
expect( helpers.initialize( {} ) ).toBe( false );
@@ -96,8 +112,8 @@ describe( 'editor taxonomy helpers', () => {
const missingEditorMethod = createWp();
missingEditorMethod.wp.data.select = () => editorSelector;
expect( () => helpers.initialize( missingEditorMethod.wp ) ).not.toThrow();
expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( false );
expect( missingEditorMethod.registerPlugin ).not.toHaveBeenCalled();
expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( true );
expect( missingEditorMethod.registerPlugin ).toHaveBeenCalledTimes( 2 );
expect( missingEditorMethod.editPost ).not.toHaveBeenCalled();
}
@@ -140,11 +156,24 @@ describe( 'editor taxonomy helpers', () => {
expect( editPost ).not.toHaveBeenCalled();
} );
test( 'does not register taxonomy panels outside post editors', () => {
test( 'registers safely but renders no taxonomy panels outside post editors', () => {
const helpers = require( modulePath );
const { wp, registerPlugin, attributes } = createWp();
attributes.type = 'page';
expect( helpers.initialize( wp ) ).toBe( false );
expect( registerPlugin ).not.toHaveBeenCalled();
expect( helpers.initialize( wp ) ).toBe( true );
expect( registerPlugin ).toHaveBeenCalledTimes( 1 );
expect( registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull();
} );
test( 'localizes taxonomy editor labels with the CHRNX text domain', () => {
const helpers = require( modulePath );
const { wp, registerPlugin } = createWp();
wp.i18n.__ = jest.fn( ( text, domain ) => `${ domain }:${ text }` );
helpers.initialize( wp );
const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render();
expect( tree.children[ 0 ].props.title ).toBe( 'chrnx:Topic' );
expect( tree.children[ 0 ].children[ 0 ].props.options[ 0 ].label ).toBe( 'chrnx:Not set' );
expect( wp.i18n.__ ).toHaveBeenCalledWith( 'Topic', 'chrnx' );
} );
} );
+2 -1
View File
@@ -84,7 +84,7 @@ class EditorAssetsTest extends WP_UnitTestCase {
);
$this->assertSame( array( 'chrnx-editor-taxonomies', 'chrnx-editor-podcast' ), $handles );
$expected_dependencies = array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' );
$expected_dependencies = array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-plugins' );
foreach (
array(
@@ -96,6 +96,7 @@ class EditorAssetsTest extends WP_UnitTestCase {
$this->assertSame( get_theme_file_uri( $asset ), $scripts->registered[ $handle ]->src );
$this->assertSame( $expected_dependencies, $scripts->registered[ $handle ]->deps );
$this->assertSame( CHRNX_VERSION, $scripts->registered[ $handle ]->ver );
$this->assertSame( 'chrnx', $scripts->registered[ $handle ]->textdomain );
}
}
+18 -1
View File
@@ -27,10 +27,14 @@ class PodcastMetaTest extends WP_UnitTestCase {
$this->assertSame( 0, $registered['chrnx_episode_number']['show_in_rest']['schema']['minimum'] );
$this->assertSame( 'string', $registered['chrnx_episode_duration']['show_in_rest']['schema']['type'] );
$this->assertSame(
array( 'type' => 'string' ),
array(
'type' => 'string',
'maxLength' => 100,
),
$registered['chrnx_episode_participants']['show_in_rest']['schema']['items']
);
$this->assertSame( 'array', $registered['chrnx_episode_participants']['show_in_rest']['schema']['type'] );
$this->assertSame( 50, $registered['chrnx_episode_participants']['show_in_rest']['schema']['maxItems'] );
$this->assertSame( 'string', $registered['canonical_episode_url']['show_in_rest']['schema']['type'] );
$this->assertArrayNotHasKey( 'chrnx_buzzsprout_embed', $registered );
$this->assertArrayNotHasKey( 'chrnx_episode_player', $registered );
@@ -78,6 +82,19 @@ class PodcastMetaTest extends WP_UnitTestCase {
$this->assertSame( array(), chrnx_sanitize_episode_participants( 'Ada Example' ) );
}
/**
* Participant bounds preserve Unicode and intentional order.
*/
public function test_participants_are_bounded_by_count_and_unicode_length() {
$long_name = str_repeat( 'ñ', 101 );
$input = array_merge( array( $long_name ), array_fill( 0, 55, 'Guest' ) );
$actual = chrnx_sanitize_episode_participants( $input );
$this->assertCount( 50, $actual );
$this->assertSame( str_repeat( 'ñ', 100 ), $actual[0] );
$this->assertSame( 100, mb_strlen( $actual[0], 'UTF-8' ) );
}
/**
* Canonical URLs allow HTTPS only.
*/
+171
View File
@@ -22,6 +22,7 @@ class TaxonomiesTest extends WP_UnitTestCase {
public function set_up() {
parent::set_up();
do_action( 'init' );
wp_set_current_user( 0 );
$this->definitions = array(
'chrnx_topic' => array(
'rest_base' => 'topic',
@@ -161,5 +162,175 @@ class TaxonomiesTest extends WP_UnitTestCase {
$this->assertStringContainsString( 'Topic', $notice );
$this->assertStringNotContainsString( 'Zulu', $notice );
$this->assertStringNotContainsString( 'Alpha', $notice );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean(), 'The notice should be consumed after one render.' );
}
/**
* A nested assignment for another post in the same taxonomy still normalizes.
*/
public function test_normalization_guard_is_scoped_by_taxonomy_and_object_id() {
$first_post = self::factory()->post->create();
$second_post = self::factory()->post->create();
$first_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) );
$second_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) );
$term_ids = array( min( $first_term, $second_term ), max( $first_term, $second_term ) );
remove_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10 );
wp_set_object_terms( $second_post, array_reverse( $term_ids ), 'chrnx_topic' );
add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 );
$nested = false;
$assign = static function ( $object_id, $terms, $term_taxonomy_ids, $taxonomy ) use ( $first_post, $second_post, $term_ids, &$nested ) {
if ( ! $nested && $first_post === $object_id && 'chrnx_topic' === $taxonomy && 1 === count( (array) $terms ) ) {
$nested = true;
wp_set_object_terms( $second_post, array_reverse( $term_ids ), 'chrnx_topic' );
}
};
add_action( 'set_object_terms', $assign, 20, 4 );
wp_set_object_terms( $first_post, array_reverse( $term_ids ), 'chrnx_topic' );
remove_action( 'set_object_terms', $assign, 20 );
$this->assertTrue( $nested );
$this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $first_post, 'chrnx_topic', array( 'fields' => 'ids' ) ) );
$this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $second_post, 'chrnx_topic', array( 'fields' => 'ids' ) ) );
}
/**
* An exception during correction cannot leave the same-object guard stuck.
*/
public function test_normalization_guard_clears_after_an_exception() {
$post_id = self::factory()->post->create();
$first_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) );
$second_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) );
$term_ids = array( min( $first_term, $second_term ), max( $first_term, $second_term ) );
$throw = static function ( $object_id, $terms, $term_taxonomy_ids, $taxonomy ) use ( $post_id ) {
if ( $post_id === $object_id && 'chrnx_topic' === $taxonomy && 1 === count( (array) $terms ) ) {
throw new RuntimeException( 'Synthetic corrective failure.' );
}
};
add_action( 'set_object_terms', $throw, 5, 4 );
try {
wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' );
$this->fail( 'The synthetic corrective failure should escape the nested assignment.' );
} catch ( RuntimeException $exception ) {
$this->assertSame( 'Synthetic corrective failure.', $exception->getMessage() );
} finally {
remove_action( 'set_object_terms', $throw, 5 );
}
remove_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10 );
wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' );
add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 );
wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' );
$this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'ids' ) ) );
}
/**
* Corrective failures produce only a generic one-time notice.
*/
public function test_corrective_failure_notice_is_generic_and_one_time() {
chrnx_record_editorial_normalization_result( 'chrnx_topic', new WP_Error( 'forced', 'Private detail' ) );
chrnx_record_editorial_normalization_result( 'chrnx_language', false );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$notice = ob_get_clean();
$this->assertStringContainsString( 'could not be normalized', $notice );
$this->assertStringNotContainsString( 'Private detail', $notice );
$this->assertStringNotContainsString( 'forced', $notice );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean() );
}
/**
* Notices cross requests for one user and never leak to another user.
*/
public function test_normalization_notice_is_user_scoped_and_cross_request_one_time() {
$first_user = self::factory()->user->create();
$second_user = self::factory()->user->create();
wp_set_current_user( $first_user );
chrnx_record_editorial_normalization_result( 'chrnx_topic', array( 1 ) );
wp_set_current_user( $second_user );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean() );
wp_set_current_user( $first_user );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertStringContainsString( 'Topic supports one value', ob_get_clean() );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean() );
}
/**
* Term insertion failures create a generic, one-time setup diagnostic.
*/
public function test_term_seeding_failure_creates_generic_one_time_diagnostic() {
$term = get_term_by( 'slug', 'research', 'chrnx_topic' );
if ( $term ) {
wp_delete_term( $term->term_id, 'chrnx_topic' );
}
$fail_insert = static function ( $term_name, $taxonomy ) {
return 'chrnx_topic' === $taxonomy && 'Research' === $term_name
? new WP_Error( 'forced_seed_error', 'Private seed detail' )
: $term_name;
};
add_filter( 'pre_insert_term', $fail_insert, 10, 2 );
do_action( 'after_switch_theme' );
remove_filter( 'pre_insert_term', $fail_insert, 10 );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$notice = ob_get_clean();
$this->assertStringContainsString( 'vocabulary setup was incomplete', $notice );
$this->assertStringNotContainsString( 'Private seed detail', $notice );
$this->assertStringNotContainsString( 'forced_seed_error', $notice );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean() );
}
/**
* Successful term seeding does not create a diagnostic.
*/
public function test_successful_term_seeding_creates_no_notice() {
do_action( 'after_switch_theme' );
ob_start();
chrnx_editorial_taxonomy_admin_notice();
$this->assertSame( '', ob_get_clean() );
}
/**
* Taxonomy labels and seed names use the CHRNX text domain.
*/
public function test_taxonomy_strings_are_localizable() {
$translate = static function ( $translated, $text, $domain ) {
if ( 'chrnx' !== $domain ) {
return $translated;
}
return array(
'Topic' => 'Tema',
'Research' => 'Investigación',
)[ $text ] ?? $translated;
};
add_filter( 'gettext', $translate, 10, 3 );
$definitions = chrnx_get_editorial_taxonomies();
remove_filter( 'gettext', $translate, 10 );
$this->assertSame( 'Tema', $definitions['chrnx_topic']['singular'] );
$this->assertSame( 'Investigación', $definitions['chrnx_topic']['terms']['research'] );
}
}