Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions .wp-env.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
{
"$schema": "./schemas/json/wp-env.json",
"plugins": [ "." ]
"$schema": "./schemas/json/wp-env.json",
"plugins": ["."],
"env": {
"tests": {
"mappings": {
"wp-content/plugins/secure-custom-fields": ".",
"wp-content/plugins/scf-test-plugins": "./tests/e2e/plugins"
}
}
}
}
136 changes: 136 additions & 0 deletions tests/e2e/field-type-text.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* WordPress dependencies
*/
const { test, expect } = require('@wordpress/e2e-test-utils-playwright');

const PLUGIN_SLUG = 'secure-custom-fields';
const TEST_PLUGIN_SLUG = 'scf-test-plugin-get-field-movie-title';
const FIELD_GROUP_LABEL = 'Movie Details';
const FIELD_LABEL = 'Movie Title';

test.describe('Field Type > Text', () => {
test.beforeAll(async ({ requestUtils }) => {
await requestUtils.activatePlugin(PLUGIN_SLUG);
await requestUtils.activatePlugin(TEST_PLUGIN_SLUG);
});

test.afterAll(async ({ requestUtils }) => {
await requestUtils.deactivatePlugin(PLUGIN_SLUG);
await requestUtils.deactivatePlugin(TEST_PLUGIN_SLUG);
await requestUtils.deleteAllPosts();
});

test.beforeEach(async ({ page, admin, editor, requestUtils }) => {
await deleteFieldGroups(page, admin);
});

test('should create a text field and verify it in admin', async ({ page, admin, editor, requestUtils }) => {
// Navigate to Field Groups and create new.
await admin.visitAdminPage('edit.php', 'post_type=acf-field-group');
const addNewButton = page.locator('a.acf-btn:has-text("Add New")');
await addNewButton.click();

// Fill field group title.
await page.waitForSelector('#title');
await page.fill('#title', FIELD_GROUP_LABEL);

// Add text field.
const fieldLabel = page.locator('input[id^="acf_fields-field_"][id$="-label"]');
await fieldLabel.fill(FIELD_LABEL);
// The field name is generated automatically.

// Select field type as text (it's default, but let's be explicit).
const fieldType = page.locator('select[id^="acf_fields-field_"][id$="-type"]');
await fieldType.selectOption('text');

// Submit form.
const publishButton = page.locator('button.acf-btn.acf-publish[type="submit"]');
await publishButton.click();

// Verify success message.
const successNotice = page.locator('.updated.notice');
await expect(successNotice).toBeVisible();
await expect(successNotice).toContainText('Field group published');

// Verify field group appears in the list.
await admin.visitAdminPage('edit.php', 'post_type=acf-field-group');
const fieldGroupRow = page.locator(`tr:has-text("${FIELD_GROUP_LABEL}")`);
await expect(fieldGroupRow).toBeVisible();

await createAndVerifyMoviePost(page, admin, editor, requestUtils);

});
});

/**
* Helper function to delete the field group
*/
async function deleteFieldGroups(page, admin) {
await admin.visitAdminPage('edit.php', 'post_type=acf-field-group');

// Find and select the field group row
const allFieldGroupsCheckbox = page.locator('input#cb-select-all-1');

if (await allFieldGroupsCheckbox.isVisible()) {
await allFieldGroupsCheckbox.check();
// Use bulk actions to trash the field group
await page.selectOption('#bulk-action-selector-bottom', 'trash');
await page.click('#doaction2');

// Verify deletion success message
const deleteMessage = page.locator('.updated.notice');
await expect(deleteMessage).toBeVisible({ timeout: 5000 });
await expect(deleteMessage).toContainText('moved to the Trash');

await emptyTrash(page, admin);
}


}

/**
* Helper function to empty trash
*/
async function emptyTrash(page, admin) {
await admin.visitAdminPage('edit.php', 'post_status=trash&post_type=acf-field-group');
const emptyTrashButton = page.locator('.tablenav.bottom input[name="delete_all"][value="Empty Trash"]');
await emptyTrashButton.waitFor({ state: 'visible' });
await emptyTrashButton.click();

// Verify success notice
const successNotice = page.locator('.notice.updated p');
await expect(successNotice).toBeVisible();
await expect(successNotice).toHaveText(/permanently deleted/);
}


/**
* Helper function to create a post with movie title and verify it on frontend
*/
async function createAndVerifyMoviePost(page, admin, editor, requestUtils) {
// Create a new post
const post = await requestUtils.createPost({
title: 'Movie 1',
status: 'draft',
});

// Navigate to edit post page
await admin.visitAdminPage('post.php', `post=${post.id}&action=edit`);

// Fill in the movie title field using data-name attribute
const movieTitleField = page.locator('.acf-field[data-name="movie_title"] input[type="text"]');
await movieTitleField.fill('The Shawshank Redemption');

// Save Draft
await editor.saveDraft();

Check failure on line 125 in tests/e2e/field-type-text.spec.ts

View workflow job for this annotation

GitHub Actions / Playwright e2e Tests

[chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin

1) [chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin TimeoutError: locator.click: Timeout 10000ms exceeded. Call log: - waiting for getByRole('region', { name: 'Editor top bar' }).getByRole('button', { name: 'Save draft' }) 123 | 124 | // Save Draft > 125 | await editor.saveDraft(); | ^ 126 | 127 | // Verify the movie title is displayed 128 | const previewPage = await editor.openPreviewPage(); at Editor.saveDraft (/home/runner/work/secure-custom-fields/secure-custom-fields/node_modules/@wordpress/e2e-test-utils-playwright/src/editor/save-draft.ts:14:4) at createAndVerifyMoviePost (/home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:125:16) at /home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:60:5

Check failure on line 125 in tests/e2e/field-type-text.spec.ts

View workflow job for this annotation

GitHub Actions / Playwright e2e Tests

[chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin

1) [chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin Retry #1 ─────────────────────────────────────────────────────────────────────────────────────── TimeoutError: locator.click: Timeout 10000ms exceeded. Call log: - waiting for getByRole('region', { name: 'Editor top bar' }).getByRole('button', { name: 'Save draft' }) 123 | 124 | // Save Draft > 125 | await editor.saveDraft(); | ^ 126 | 127 | // Verify the movie title is displayed 128 | const previewPage = await editor.openPreviewPage(); at Editor.saveDraft (/home/runner/work/secure-custom-fields/secure-custom-fields/node_modules/@wordpress/e2e-test-utils-playwright/src/editor/save-draft.ts:14:4) at createAndVerifyMoviePost (/home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:125:16) at /home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:60:5

Check failure on line 125 in tests/e2e/field-type-text.spec.ts

View workflow job for this annotation

GitHub Actions / Playwright e2e Tests

[chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin

1) [chromium] › tests/e2e/field-type-text.spec.ts:27:3 › Field Type > Text › should create a text field and verify it in admin Retry #2 ─────────────────────────────────────────────────────────────────────────────────────── TimeoutError: locator.click: Timeout 10000ms exceeded. Call log: - waiting for getByRole('region', { name: 'Editor top bar' }).getByRole('button', { name: 'Save draft' }) 123 | 124 | // Save Draft > 125 | await editor.saveDraft(); | ^ 126 | 127 | // Verify the movie title is displayed 128 | const previewPage = await editor.openPreviewPage(); at Editor.saveDraft (/home/runner/work/secure-custom-fields/secure-custom-fields/node_modules/@wordpress/e2e-test-utils-playwright/src/editor/save-draft.ts:14:4) at createAndVerifyMoviePost (/home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:125:16) at /home/runner/work/secure-custom-fields/secure-custom-fields/tests/e2e/field-type-text.spec.ts:60:5

// Verify the movie title is displayed
const previewPage = await editor.openPreviewPage();

const movieTitleElement = previewPage.locator('#scf-test-movie-title');
await expect(movieTitleElement).toBeVisible();
await expect(movieTitleElement).toContainText('Movie title: The Shawshank Redemption');

// Close the preview tab
await previewPage.close();
}
2 changes: 1 addition & 1 deletion tests/e2e/plugin-activation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ test.describe('Plugin Activation', () => {
const pluginName = page.locator(`tr[data-plugin="${PLUGIN_PATH}"] .plugin-title strong`);
await expect(pluginName).toHaveText('Secure Custom Fields');
});
});
});
39 changes: 39 additions & 0 deletions tests/e2e/plugins/scf-test-get-field.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
/**
* Plugin Name: SCF Test Plugin, Get Field Movie Title
* Plugin URI: https://github.com/WordPress/secure-custom-fields
* Author: SCF Team
*
* @package scf-test-plugins
*/

add_filter( 'the_content', 'scf_add_get_field_at_the_end' );

/**
* Add post-formats support to pages
*/
function scf_add_get_field_at_the_end() {
// Get the field object to validate it exists.
$field_object = get_field_object( 'movie_title' );

// Only proceed if the field exists and is a valid type.
if ( $field_object && isset( $field_object['type'] ) && 'text' === $field_object['type'] ) {
$field = get_field( 'movie_title' );

// Ensure we have a string value and sanitize it.
$field = is_string( $field ) ? $field : '';

// Sanitize the field value using WordPress sanitization functions.
$field = sanitize_text_field( $field );

// Escape the output for HTML context.
$escaped_field = esc_html( $field );

// Use wp_kses_post to allow safe HTML if needed, but escape by default.
$output = wp_kses_post( '<br><p id="scf-test-movie-title">Movie title: ' . $escaped_field . '</p>' );
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkevan Should SCF escape automatically within the get_field function?

Docs says that you need to do this $escaped_wysiwyg = get_field('wysiwyg', false, true, true);, but also recommends using wp_kses_post.

Am I being redundant here? I have that feeling.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wp_kses_post filters out unallowed tags and attributes. In effect, if you would not escape the field and the HTML tags are allowed they would get printed inside the paragraph. So it sounds like a decision of whether you allow any HTML for the field here.

Copy link
Contributor

@pkevan pkevan Apr 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkevan Should SCF escape automatically within the get_field function?

Generally this isn't expected, and would more than likely get flagged when using phpcs anyway.

Escaping should be in the realm of whatever is outputting the data, so in this case it's not needed, but generally any outputting functions within the plugin which requires no user input should be escaping it after using get_field i.e. the shortcodes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one does not require user input cause the input will be only filled in an automated test. So I guess we are fine with removing it then.


return $output;
}

return '';
}
Loading