feat: draft copies and replace-with-copy

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
2026-09-25 23:27:07 +02:00
co-authored by Claude Opus 5.5
parent 346619d6da
commit 4fed69cf65
8 changed files with 1215 additions and 0 deletions
@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\WordPress\Status;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\WriteFailed;
use LIT\MCP\Integrations\WordPress\Status\PostCloner;
use LIT\MCP\Tests\Unit\TestCase;
use RuntimeException;
use WP_Error;
use WP_Post;
final class PostClonerTest extends TestCase
{
private function original(): WP_Post
{
return new WP_Post([
'ID' => 5,
'post_type' => 'page',
'post_title' => 'Team',
'post_content' => '<!-- wp:divi/section /-->',
'post_excerpt' => 'Kurz',
'post_parent' => 2,
'menu_order' => 3,
]);
}
private function copy(): WP_Post
{
return new WP_Post([
'ID' => 77,
'post_type' => 'page',
'post_title' => 'Team (Kopie)',
'post_content' => 'neu',
'post_excerpt' => 'Neu kurz',
]);
}
public function testDuplicateCopiesContentMetaAndTermsAsDraft(): void
{
Functions\when('get_current_user_id')->justReturn(4);
Functions\when('maybe_unserialize')->returnArg();
Functions\expect('wp_insert_post')->once()->with($this->draftMatcher(), true)->andReturn(77);
Functions\when('get_post_meta')->alias(static fn (int $id) => $id === 5
? [
'_edit_lock' => ['123:1'],
'_edit_last' => ['1'],
'_wp_old_slug' => ['team-alt'],
'_et_pb_use_builder' => ['on'],
'_et_pb_use_divi_5' => ['on'],
'_wp_page_template' => ['page-template-blank.php'],
'_thumbnail_id' => ['31'],
'role' => ['Leitung'],
]
: ['_edit_lock' => ['999:4'], '_et_pb_use_builder' => ['off']]);
// Meta a save hook put on the fresh copy is replaced by the original's.
Functions\expect('delete_post_meta')->once()->with(77, '_et_pb_use_builder');
Functions\expect('add_post_meta')->once()->with(77, '_et_pb_use_builder', 'on');
Functions\expect('add_post_meta')->once()->with(77, '_et_pb_use_divi_5', 'on');
Functions\expect('add_post_meta')->once()->with(77, '_wp_page_template', 'page-template-blank.php');
Functions\expect('add_post_meta')->once()->with(77, '_thumbnail_id', '31');
Functions\expect('add_post_meta')->once()->with(77, 'role', 'Leitung');
Functions\when('get_object_taxonomies')->justReturn(['category']);
Functions\when('wp_get_object_terms')->justReturn([4, 9]);
Functions\expect('wp_set_object_terms')->once()->with(77, [4, 9], 'category', false);
Functions\expect('update_post_meta')->once()->with(77, '_lit_mcp_copy_of', 5);
self::assertSame(77, (new PostCloner())->duplicate($this->original()));
}
public function testDuplicateFailureThrows(): void
{
Functions\when('get_current_user_id')->justReturn(4);
Functions\when('wp_insert_post')->justReturn(new WP_Error('x', 'kaputt'));
$this->expectException(RuntimeException::class);
(new PostCloner())->duplicate($this->original());
}
public function testDuplicateFailingAfterInsertDeletesTheNewDraft(): void
{
Functions\when('get_current_user_id')->justReturn(4);
Functions\when('maybe_unserialize')->returnArg();
Functions\when('wp_insert_post')->justReturn(77);
Functions\when('get_post_meta')->alias(static fn (int $id) => $id === 5 ? ['role' => ['Leitung']] : []);
Functions\when('add_post_meta')->justReturn(false);
Functions\expect('wp_delete_post')->once()->with(77, true)->andReturn(new WP_Post(['ID' => 77]));
try {
(new PostCloner())->duplicate($this->original());
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
self::assertTrue($e->rolledBack);
}
}
public function testDuplicateReportsALeftoverDraftWhenItCannotBeDeleted(): void
{
Functions\when('get_current_user_id')->justReturn(4);
Functions\when('maybe_unserialize')->returnArg();
Functions\when('wp_insert_post')->justReturn(77);
Functions\when('get_post_meta')->justReturn([]);
Functions\when('get_object_taxonomies')->justReturn(['category']);
Functions\when('wp_get_object_terms')->justReturn(new WP_Error('x', 'kaputt'));
Functions\when('wp_delete_post')->justReturn(false);
try {
(new PostCloner())->duplicate($this->original());
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
self::assertFalse($e->rolledBack);
self::assertSame(77, $e->postId);
}
}
public function testReplaceOverwritesContentMetaAndTermsButKeepsTheOriginalsIdentity(): void
{
Functions\when('maybe_unserialize')->returnArg();
Functions\expect('wp_update_post')->once()->with([
'ID' => 5,
'post_title' => 'Team',
'post_content' => 'neu',
'post_excerpt' => 'Neu kurz',
], true)->andReturn(5);
Functions\when('get_post_meta')->alias(static fn (int $id) => $id === 5
? ['_edit_lock' => ['1'], '_wp_old_slug' => ['alt'], 'role' => ['Alt'], 'city' => ['Trier']]
: ['_lit_mcp_copy_of' => ['5'], '_edit_last' => ['4'], 'role' => ['Neu']]);
Functions\expect('delete_post_meta')->once()->with(5, 'role');
Functions\expect('delete_post_meta')->once()->with(5, 'city');
Functions\expect('add_post_meta')->once()->with(5, 'role', 'Neu');
Functions\when('get_object_taxonomies')->justReturn(['category']);
Functions\when('wp_get_object_terms')->justReturn([12]);
Functions\expect('wp_set_object_terms')->once()->with(5, [12], 'category', false);
(new PostCloner())->replace($this->original(), $this->copy());
}
public function testReplaceThrowsWhenWordPressRejectsTheUpdate(): void
{
Functions\when('wp_update_post')->justReturn(new WP_Error('x', 'kaputt'));
Functions\expect('delete_post_meta')->never();
$this->expectException(RuntimeException::class);
(new PostCloner())->replace($this->original(), $this->copy());
}
public function testReplaceThrowsWhenTermsCannotBeSet(): void
{
Functions\when('wp_update_post')->justReturn(5);
Functions\when('get_post_meta')->justReturn([]);
Functions\when('get_object_taxonomies')->justReturn(['category']);
Functions\when('wp_get_object_terms')->justReturn([12]);
Functions\when('wp_set_object_terms')->justReturn(new WP_Error('x', 'kaputt'));
$this->expectException(RuntimeException::class);
(new PostCloner())->replace($this->original(), $this->copy());
}
public function testSnapshotAndRestoreBringBackRowMetaAndTerms(): void
{
$meta = ['_edit_lock' => ['1'], 'role' => ['Alt']];
Functions\when('get_post_meta')->alias(static function () use (&$meta): array {
return $meta;
});
Functions\when('get_object_taxonomies')->justReturn(['category']);
Functions\when('wp_get_object_terms')->justReturn([4]);
$cloner = new PostCloner();
$snapshot = $cloner->snapshot($this->original());
self::assertSame(['post_title' => 'Team', 'post_content' => '<!-- wp:divi/section /-->', 'post_excerpt' => 'Kurz'], $snapshot['post']);
self::assertSame(['role' => ['Alt']], $snapshot['meta']);
self::assertSame(['category' => [4]], $snapshot['terms']);
$meta = ['_edit_lock' => ['1'], 'role' => ['Neu'], 'city' => ['Trier']];
Functions\when('maybe_unserialize')->returnArg();
Functions\expect('wp_update_post')->once()
->with(array_merge(['ID' => 5], $snapshot['post']), true)->andReturn(5);
Functions\expect('delete_post_meta')->once()->with(5, 'role');
Functions\expect('delete_post_meta')->once()->with(5, 'city');
Functions\expect('add_post_meta')->once()->with(5, 'role', 'Alt');
Functions\expect('wp_set_object_terms')->once()->with(5, [4], 'category', false);
$cloner->restore($this->original(), $snapshot);
}
public function testRestoreTriesEveryPartAndReportsFailures(): void
{
Functions\when('wp_update_post')->justReturn(new WP_Error('x', 'kaputt'));
Functions\when('get_post_meta')->justReturn([]);
Functions\expect('wp_set_object_terms')->once()->with(5, [4], 'category', false);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Restore incomplete');
(new PostCloner())->restore($this->original(), [
'post' => ['post_title' => 'Team', 'post_content' => '', 'post_excerpt' => ''],
'meta' => [],
'terms' => ['category' => [4]],
]);
}
private function draftMatcher(): \Mockery\Matcher\Closure
{
return \Mockery::on(static fn (array $data): bool => $data['post_status'] === 'draft'
&& $data['post_type'] === 'page'
&& $data['post_title'] === 'Team (Kopie)'
&& $data['post_content'] === '<!-- wp:divi/section /-->'
&& $data['post_excerpt'] === 'Kurz'
&& $data['post_parent'] === 2
&& $data['menu_order'] === 3
&& $data['post_author'] === 4);
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\WordPress\Status;
use Brain\Monkey\Actions;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\Rev;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
use LIT\MCP\Integrations\WordPress\Status\PostCloner;
use LIT\MCP\Integrations\WordPress\Status\PostDuplicateAbility;
use LIT\MCP\Tests\Unit\TestCase;
use Mockery;
use WP_Post;
final class PostDuplicateAbilityTest extends TestCase
{
private WP_Post $original;
private WP_Post $copy;
protected function setUp(): void
{
parent::setUp();
$this->original = new WP_Post(['ID' => 5, 'post_type' => 'page', 'post_title' => 'Team']);
$this->copy = new WP_Post(['ID' => 77, 'post_type' => 'page', 'post_title' => 'Team (Kopie)']);
Functions\when('get_post')->alias(fn (int $id) => $id === 5 ? $this->original : $this->copy);
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_post_type_object')->justReturn((object) ['cap' => (object) ['create_posts' => 'edit_pages']]);
Functions\when('get_preview_post_link')->justReturn('https://kunde.de/?p=77&preview=true');
Functions\when('get_edit_post_link')->justReturn('https://kunde.de/wp-admin/post.php?post=77&action=edit');
}
private function ability(PostCloner $cloner, ChangeLog $log): PostDuplicateAbility
{
$schema = Mockery::mock(ContentSchema::class);
$schema->allows('isManaged')->andReturn(true);
return new PostDuplicateAbility($schema, $cloner, $log);
}
public function testCreatesADraftCopyAndReportsIt(): void
{
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('duplicate')->with($this->original)->andReturn(77);
Actions\expectDone('lit_mcp_after_save')->once()->with(77, 'lit/post-duplicate', ['post_id' => 5]);
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->with('lit/post-duplicate', 'page', '77', 'Kopie von "Team" (ID 5) angelegt')->andReturn(8);
$result = $this->ability($cloner, $log)->execute(['post_id' => 5]);
self::assertSame([['id' => '77', 'type' => 'page', 'action' => 'created', 'label' => 'Team (Kopie)']], $result['changed']);
self::assertSame(5, $result['original_id']);
self::assertSame(8, $result['log_id']);
self::assertSame(Rev::ofPost($this->copy), $result['rev']);
self::assertSame([], $result['warnings']);
}
public function testNeedsTheRightToCreateEntriesOfThatType(): void
{
Functions\when('current_user_can')->alias(static fn (string $cap): bool => $cap !== 'edit_pages');
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('duplicate')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class))->execute(['post_id' => 5]);
self::assertSame('lit_forbidden', $result->get_error_code());
}
public function testIsIndirectAndNotIdempotent(): void
{
$ability = $this->ability(Mockery::mock(PostCloner::class), Mockery::mock(ChangeLog::class));
self::assertFalse($ability->isDirect());
self::assertFalse($ability->annotations()['idempotent']);
self::assertFalse($ability->annotations()['destructive']);
}
}
@@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\WordPress\Status;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\Rev;
use LIT\MCP\Abilities\WriteFailed;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
use LIT\MCP\Integrations\WordPress\Status\PostCloner;
use LIT\MCP\Integrations\WordPress\Status\PostReplaceWithCopyAbility;
use LIT\MCP\Tests\Unit\TestCase;
use Mockery;
use RuntimeException;
use WP_Post;
final class PostReplaceWithCopyAbilityTest extends TestCase
{
private const SNAPSHOT = ['post' => ['post_title' => 'Team'], 'meta' => [], 'terms' => []];
private WP_Post $original;
private WP_Post $copy;
protected function setUp(): void
{
parent::setUp();
$this->original = new WP_Post(['ID' => 5, 'post_type' => 'page', 'post_title' => 'Team', 'post_status' => 'publish']);
$this->copy = new WP_Post(['ID' => 77, 'post_type' => 'page', 'post_title' => 'Team (Kopie)', 'post_status' => 'draft']);
Functions\when('get_post')->alias(fn (int $id) => $id === 5 ? $this->original : $this->copy);
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_post_meta')->justReturn('5');
Functions\when('get_permalink')->justReturn('https://kunde.de/team/');
Functions\when('get_edit_post_link')->justReturn('https://kunde.de/wp-admin/post.php?post=5&action=edit');
}
private function ability(PostCloner $cloner, ChangeLog $log, bool $trash = true): PostReplaceWithCopyAbility
{
$schema = Mockery::mock(ContentSchema::class);
$schema->allows('isManaged')->andReturn(true);
return new PostReplaceWithCopyAbility($schema, $cloner, $log, static fn (): bool => $trash);
}
/** @return array<string, mixed> */
private function input(array $extra = []): array
{
return array_merge(
['original_id' => 5, 'copy_id' => 77, 'rev' => Rev::ofPost($this->original), 'confirm' => true],
$extra
);
}
private function revisionAt900(): void
{
Functions\when('wp_save_post_revision')->justReturn(900);
Functions\when('wp_get_post_revisions')->justReturn([900 => new WP_Post(['ID' => 900])]);
}
public function testRequiresConfirmation(): void
{
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('replace')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class))
->execute(['original_id' => 5, 'copy_id' => 77, 'rev' => Rev::ofPost($this->original)]);
self::assertSame('lit_confirm_required', $result->get_error_code());
}
public function testCopyMustStemFromTheOriginal(): void
{
Functions\when('get_post_meta')->justReturn('12');
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('replace')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class))->execute($this->input());
self::assertSame('lit_validation_failed', $result->get_error_code());
}
public function testATrashedCopyIsRefused(): void
{
$this->copy->post_status = 'trash';
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('replace')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class))->execute($this->input());
self::assertSame('lit_validation_failed', $result->get_error_code());
}
public function testAStaleRevOfTheOriginalIsRefused(): void
{
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('replace')->never();
Functions\expect('wp_save_post_revision')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class))->execute($this->input(['rev' => 'veraltet']));
self::assertSame('lit_rev_mismatch', $result->get_error_code());
}
public function testDisabledTrashIsRefusedBeforeAnyChange(): void
{
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('replace')->never();
$result = $this->ability($cloner, Mockery::mock(ChangeLog::class), false)->execute($this->input());
self::assertSame('lit_unsupported', $result->get_error_code());
}
public function testRevisionThenReplaceThenTrashTheCopy(): void
{
$order = [];
Functions\expect('wp_save_post_revision')->once()->with(5)->andReturnUsing(static function () use (&$order) {
$order[] = 'revision';
return 900;
});
Functions\when('wp_get_post_revisions')->justReturn([900 => new WP_Post(['ID' => 900])]);
$cloner = Mockery::mock(PostCloner::class);
$cloner->expects('snapshot')->with($this->original)->andReturnUsing(static function () use (&$order): array {
$order[] = 'snapshot';
return self::SNAPSHOT;
});
$cloner->expects('replace')->with($this->original, $this->copy)->andReturnUsing(static function () use (&$order): void {
$order[] = 'replace';
});
$cloner->expects('restore')->never();
Functions\expect('wp_trash_post')->once()->with(77)->andReturnUsing(static function () use (&$order): WP_Post {
$order[] = 'trash';
return new WP_Post(['ID' => 77]);
});
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->with('lit/post-replace-with-copy', 'page', '5', Mockery::type('string'), 900)->andReturn(11);
$result = $this->ability($cloner, $log)->execute($this->input());
self::assertSame(['snapshot', 'revision', 'replace', 'trash'], $order);
self::assertSame(900, $result['revision_id']);
self::assertSame(11, $result['log_id']);
self::assertSame(Rev::ofPost($this->original), $result['rev']);
self::assertSame(['replaced', 'trashed'], array_column($result['changed'], 'action'));
self::assertSame([], $result['warnings']);
}
public function testAFailedTrashOfTheCopyIsAWarningOnly(): void
{
$this->revisionAt900();
$cloner = Mockery::mock(PostCloner::class);
$cloner->allows('snapshot')->andReturn(self::SNAPSHOT);
$cloner->expects('replace');
Functions\when('wp_trash_post')->justReturn(false);
$log = Mockery::mock(ChangeLog::class);
$log->allows('record')->andReturn(11);
$result = $this->ability($cloner, $log)->execute($this->input());
self::assertTrue($result['ok']);
self::assertSame(['replaced'], array_column($result['changed'], 'action'));
self::assertSame(['Kopie 77 konnte nicht in den Papierkorb gelegt werden'], $result['warnings']);
}
public function testAFailedReplaceRestoresTheOriginal(): void
{
$this->revisionAt900();
$cloner = Mockery::mock(PostCloner::class);
$cloner->allows('snapshot')->andReturn(self::SNAPSHOT);
$cloner->expects('replace')->andThrow(new RuntimeException('meta kaputt'));
$cloner->expects('restore')->with($this->original, self::SNAPSHOT);
Functions\expect('wp_trash_post')->never();
try {
$this->ability($cloner, Mockery::mock(ChangeLog::class))->execute($this->input());
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
self::assertTrue($e->rolledBack);
self::assertSame('lit_write_failed', $e->toError()->get_error_code());
}
}
public function testAnIncompleteRestoreIsAPartialWrite(): void
{
$this->revisionAt900();
$cloner = Mockery::mock(PostCloner::class);
$cloner->allows('snapshot')->andReturn(self::SNAPSHOT);
$cloner->expects('replace')->andThrow(new RuntimeException('meta kaputt'));
$cloner->expects('restore')->andThrow(new RuntimeException('Restore incomplete: terms'));
Functions\expect('wp_trash_post')->never();
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')
->with('lit/post-replace-with-copy', 'page', '5', Mockery::type('string'), 900, null, 'partial')
->andReturn(12);
try {
$this->ability($cloner, $log)->execute($this->input());
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
self::assertFalse($e->rolledBack);
self::assertSame(5, $e->postId);
self::assertSame(900, $e->revisionId);
self::assertSame('lit_partial_write', $e->toError()->get_error_code());
}
}
public function testRequiresRevAndIsDestructive(): void
{
$ability = $this->ability(Mockery::mock(PostCloner::class), Mockery::mock(ChangeLog::class));
self::assertContains('rev', $ability->inputSchema()['required']);
self::assertTrue($ability->annotations()['destructive']);
self::assertFalse($ability->annotations()['idempotent']);
self::assertFalse($ability->isDirect());
}
}