feat: batch media metadata updates and delete with usage check

lit/media-update validates the whole batch first (edit_post, lengths, optional
modified lock) and restores already written items when a write fails midway.
lit/media-delete requires confirm, refuses used media without force and
reports refused deletes as write_failed.

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-26 02:49:41 +02:00
co-authored by Claude Opus 5.5
parent 56f561c436
commit 931ddeb137
9 changed files with 1145 additions and 1 deletions
@@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\Media;
use Brain\Monkey\Functions;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\Media\MediaDeleteAbility;
use LIT\MCP\Integrations\Media\MediaUsageFinder;
use LIT\MCP\Tests\Unit\TestCase;
use Mockery;
use RuntimeException;
use WP_Post;
final class MediaDeleteAbilityTest extends TestCase
{
private const USAGE = [['post_id' => 5, 'title' => 'Team', 'post_type' => 'page', 'where' => 'featured', 'certainty' => 'sicher']];
private const POSSIBLE = [['post_id' => 7, 'title' => 'Blog', 'post_type' => 'post', 'where' => 'content', 'certainty' => 'möglicherweise']];
protected function setUp(): void
{
parent::setUp();
Functions\when('get_post')->justReturn(new WP_Post(['ID' => 33, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_title' => 'Foto']));
Functions\when('current_user_can')->justReturn(true);
}
private function ability(array $usages, ChangeLog $log, bool $trash = false): MediaDeleteAbility
{
$finder = Mockery::mock(MediaUsageFinder::class);
$finder->allows('usages')->with(33)->andReturn($usages);
return new MediaDeleteAbility($finder, $log, static fn (): bool => $trash);
}
public function testConfirmationIsRequiredAndMentionsUsages(): void
{
Functions\expect('wp_delete_attachment')->never();
$result = $this->ability(self::USAGE, Mockery::mock(ChangeLog::class))->execute(['id' => 33]);
self::assertSame('lit_confirm_required', $result->get_error_code());
self::assertStringContainsString('endgültig', $result->get_error_message());
self::assertStringContainsString('1 Stelle', $result->get_error_message());
self::assertSame(self::USAGE, $result->get_error_data()['usages']);
}
public function testConfirmationMentionsTheTrashWhenMediaTrashIsOn(): void
{
$result = $this->ability([], Mockery::mock(ChangeLog::class), true)->execute(['id' => 33, 'confirm' => false]);
self::assertSame('lit_confirm_required', $result->get_error_code());
self::assertStringContainsString('Papierkorb', $result->get_error_message());
}
public function testUsedMediaNeedsForce(): void
{
Functions\expect('wp_delete_attachment')->never();
$result = $this->ability(self::USAGE, Mockery::mock(ChangeLog::class))->execute(['id' => 33, 'confirm' => true]);
self::assertSame('lit_in_use', $result->get_error_code());
self::assertSame(self::USAGE, $result->get_error_data()['usages']);
}
public function testPossibleUsageAlsoNeedsForce(): void
{
Functions\expect('wp_delete_attachment')->never();
$result = $this->ability(self::POSSIBLE, Mockery::mock(ChangeLog::class))->execute(['id' => 33, 'confirm' => true]);
self::assertSame('lit_in_use', $result->get_error_code());
}
public function testForceDeletesUsedMedia(): void
{
Functions\expect('wp_delete_attachment')->once()->with(33, false)->andReturn(new WP_Post(['ID' => 33]));
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->with('lit/media-delete', 'attachment', '33', 'Medium "Foto" gelöscht')->andReturn(50);
$result = $this->ability(self::USAGE, $log)->execute(['id' => 33, 'confirm' => true, 'force' => true]);
self::assertSame(['id' => '33', 'type' => 'attachment', 'action' => 'deleted', 'label' => 'Foto'], $result['changed'][0]);
self::assertSame(50, $result['log_id']);
self::assertSame(self::USAGE, $result['usages']);
}
public function testUnusedMediaGoesToTheTrashWhenMediaTrashIsOn(): void
{
Functions\expect('wp_delete_attachment')->once()->with(33, false)->andReturn(new WP_Post(['ID' => 33]));
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->with('lit/media-delete', 'attachment', '33', 'Medium "Foto" in den Papierkorb gelegt')->andReturn(51);
$result = $this->ability([], $log, true)->execute(['id' => 33, 'confirm' => true]);
self::assertSame('trashed', $result['changed'][0]['action']);
}
public function testRefusedDeleteIsAWriteFailure(): void
{
Functions\expect('wp_delete_attachment')->once()->andReturn(false);
$result = $this->ability([], Mockery::mock(ChangeLog::class))->execute(['id' => 33, 'confirm' => true]);
self::assertSame('lit_write_failed', $result->get_error_code());
}
public function testChangeLogFailureIsOnlyAWarning(): void
{
Functions\expect('wp_delete_attachment')->once()->andReturn(new WP_Post(['ID' => 33]));
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->andThrow(new RuntimeException('db down'));
$file = (string) tempnam(sys_get_temp_dir(), 'lit-mcp-log');
$previous = ini_set('error_log', $file);
try {
$result = $this->ability([], $log)->execute(['id' => 33, 'confirm' => true]);
} finally {
ini_set('error_log', (string) $previous);
unlink($file);
}
self::assertSame('deleted', $result['changed'][0]['action']);
self::assertNull($result['log_id']);
self::assertCount(1, $result['warnings']);
}
public function testTrashedAttachmentIsRefused(): void
{
Functions\when('get_post')->justReturn(new WP_Post(['ID' => 33, 'post_type' => 'attachment', 'post_status' => 'trash']));
Functions\expect('wp_delete_attachment')->never();
$ability = $this->ability([], Mockery::mock(ChangeLog::class));
self::assertSame('lit_validation_failed', $ability->permission(['id' => 33])->get_error_code());
self::assertSame('lit_validation_failed', $ability->execute(['id' => 33, 'confirm' => true])->get_error_code());
}
public function testChecksDeletePostOnTheAttachment(): void
{
Functions\when('current_user_can')->alias(static fn (string $cap, int $id): bool => ! ($cap === 'delete_post' && $id === 33));
$result = $this->ability([], Mockery::mock(ChangeLog::class))->permission(['id' => 33]);
self::assertSame('lit_forbidden', $result->get_error_code());
}
public function testIsDestructiveAndDescribesWhatTheUsageCheckMisses(): void
{
$ability = $this->ability([], Mockery::mock(ChangeLog::class));
self::assertSame(['readonly' => false, 'destructive' => true, 'idempotent' => false], $ability->annotations());
self::assertFalse($ability->isDirect());
foreach (['endgültig', 'Term-Meta', 'Benutzer-Meta', 'Pods', 'ACF', 'kommagetrennt', 'Optionen anderer Plugins'] as $needle) {
self::assertStringContainsString($needle, $ability->description());
}
}
}
@@ -22,6 +22,8 @@ final class MediaIntegrationTest extends TestCase
'lit/media-upload-from-url',
'lit/media-upload',
'lit/media-download',
'lit/media-update',
'lit/media-delete',
];
public function testProvidesTheMediaAbilities(): void
@@ -45,6 +45,7 @@ final class MediaPresenterTest extends TestCase
self::assertSame('Porträt', $summary['alt']);
self::assertSame(1600, $summary['width']);
self::assertSame(123456, $summary['filesize']);
self::assertSame('2026-09-25 08:00:00', $summary['modified']);
}
public function testFullListsSizesAndUsagesAndCopesWithMissingMetadata(): void
@@ -0,0 +1,271 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\Media;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\WriteFailed;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\Media\MediaUpdateAbility;
use LIT\MCP\Tests\Unit\TestCase;
use Mockery;
use RuntimeException;
use WP_Error;
use WP_Post;
final class MediaUpdateAbilityTest extends TestCase
{
/** @var list<array<string, mixed>> */
private array $postUpdates = [];
/** @var list<array{int, string}> */
private array $altUpdates = [];
protected function setUp(): void
{
parent::setUp();
$this->postUpdates = [];
$this->altUpdates = [];
$posts = [
33 => new WP_Post(['ID' => 33, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_title' => 'Foto',
'post_excerpt' => 'Alt-Unterschrift', 'post_modified_gmt' => '2026-09-25 08:00:00']),
34 => new WP_Post(['ID' => 34, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_title' => 'Logo',
'post_modified_gmt' => '2026-09-25 09:00:00']),
35 => new WP_Post(['ID' => 35, 'post_type' => 'attachment', 'post_status' => 'trash', 'post_title' => 'Alt']),
5 => new WP_Post(['ID' => 5, 'post_type' => 'page', 'post_title' => 'Seite']),
];
Functions\when('get_post')->alias(static fn ($id) => $posts[(int) $id] ?? null);
Functions\when('current_user_can')->justReturn(true);
Functions\when('wp_kses_post')->alias(static fn ($value): string => strip_tags((string) $value, '<a><em><strong>'));
Functions\when('metadata_exists')->justReturn(true);
Functions\when('get_post_meta')->justReturn('alter Alt-Text');
Functions\when('wp_update_post')->alias(function (array $data, bool $wpError) {
$this->postUpdates[] = $data;
return (int) $data['ID'];
});
Functions\when('update_post_meta')->alias(function (int $id, string $key, $value) {
$this->altUpdates[] = [$id, $value];
return true;
});
}
private function log(int ...$ids): ChangeLog
{
$log = Mockery::mock(ChangeLog::class);
if ($ids !== []) {
$log->expects('record')->times(count($ids))->andReturn(...$ids);
}
return $log;
}
public function testUpdatesEveryItemAndReportsPerItem(): void
{
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')
->with('lit/media-update', 'attachment', '33', 'Metadaten von "Foto" geändert: alt, caption')
->andReturn(41);
$log->expects('record')
->with('lit/media-update', 'attachment', '34', 'Metadaten von "Logo" geändert: title')
->andReturn(42);
$result = (new MediaUpdateAbility($log))->execute(['items' => [
['id' => 33, 'alt' => 'Team vor dem Haus', 'caption' => 'Unser <script>x</script>Team'],
['id' => 34, 'title' => '<b>Firmen</b>logo', 'modified' => '2026-09-25 09:00:00'],
]]);
self::assertSame([['post_excerpt' => 'Unser xTeam', 'ID' => 33], ['post_title' => 'Firmenlogo', 'ID' => 34]], $this->postUpdates);
self::assertSame([[33, 'Team vor dem Haus']], $this->altUpdates);
self::assertSame(['id' => 33, 'ok' => true, 'error' => null, 'log_id' => 41, 'modified' => '2026-09-25 08:00:00'], $result['results'][0]);
self::assertSame(42, $result['results'][1]['log_id']);
self::assertSame(['id' => '34', 'type' => 'attachment', 'action' => 'updated', 'label' => 'Firmenlogo'], $result['changed'][1]);
self::assertSame('2 von 2 Medien aktualisiert.', $result['summary']);
}
public function testAnInvalidItemRefusesTheWholeBatchAndNamesEveryFailure(): void
{
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [
['id' => 33, 'alt' => 'ok'],
['id' => 99, 'alt' => 'x'],
['id' => 5, 'alt' => 'x'],
['id' => 35, 'alt' => 'x'],
]]);
self::assertInstanceOf(WP_Error::class, $result);
self::assertSame('lit_validation_failed', $result->get_error_code());
self::assertStringContainsString('3 von 4', $result->get_error_message());
self::assertStringContainsString('nichts wurde gespeichert', $result->get_error_message());
$failures = $result->get_error_data()['failures'];
self::assertSame([1, 2, 3], array_column($failures, 'index'));
self::assertSame(['not_found', 'not_found', 'validation_failed'], array_column($failures, 'code'));
self::assertStringContainsString('nicht gefunden', $failures[0]['error']);
self::assertStringContainsString('Papierkorb', $failures[2]['error']);
self::assertSame([], $this->postUpdates);
self::assertSame([], $this->altUpdates);
}
public function testFailuresOfOneKindKeepTheirCode(): void
{
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [['id' => 99, 'alt' => 'x']]]);
self::assertSame('lit_not_found', $result->get_error_code());
}
public function testRejectsEmptyDuplicateAndOverlongItems(): void
{
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [
['id' => 33],
['id' => 34, 'alt' => str_repeat('a', 501)],
['id' => 34, 'title' => 'doppelt'],
['id' => 33, 'caption' => ['kein', 'Text']],
]]);
$failures = $result->get_error_data()['failures'];
self::assertSame([0, 1, 2, 3], array_column($failures, 'index'));
self::assertStringContainsString('Nichts zu ändern', $failures[0]['error']);
self::assertStringContainsString('alt', $failures[1]['error']);
self::assertStringContainsString('mehrfach', $failures[2]['error']);
self::assertStringContainsString('caption', $failures[3]['error']);
self::assertSame([], $this->postUpdates);
}
public function testStaleModifiedRefusesTheBatchWithRevMismatch(): void
{
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [
['id' => 33, 'alt' => 'neu', 'modified' => '2026-09-25 08:00:00'],
['id' => 34, 'alt' => 'neu', 'modified' => '2026-09-24 07:00:00'],
]]);
self::assertSame('lit_rev_mismatch', $result->get_error_code());
self::assertSame(1, $result->get_error_data()['failures'][0]['index']);
self::assertStringContainsString('lit/media-get', $result->get_error_data()['hint']);
self::assertSame([], $this->altUpdates);
}
public function testAFailedWriteRestoresTheItemsAlreadyChanged(): void
{
Functions\when('wp_update_post')->alias(function (array $data, bool $wpError) {
$this->postUpdates[] = $data;
return $data['ID'] === 34 && ($data['post_title'] ?? '') === 'Neu'
? new WP_Error('db', 'Datenbankfehler')
: (int) $data['ID'];
});
try {
(new MediaUpdateAbility($this->log()))->execute(['items' => [
['id' => 33, 'alt' => 'neu', 'caption' => 'neu'],
['id' => 34, 'title' => 'Neu'],
]]);
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
self::assertTrue($e->rolledBack);
self::assertSame('lit_write_failed', $e->toError()->get_error_code());
self::assertStringContainsString('Datenbankfehler', $e->getMessage());
}
// Item 34 was refused before anything was written; item 33 gets caption and alt back.
self::assertSame([
['post_excerpt' => 'neu', 'ID' => 33],
['post_title' => 'Neu', 'ID' => 34],
['post_excerpt' => 'Alt-Unterschrift', 'ID' => 33],
], $this->postUpdates);
self::assertSame([[33, 'neu'], [33, 'alter Alt-Text']], $this->altUpdates);
}
public function testAHookThrowingAfterTheWriteAlsoRestoresThatItem(): void
{
Functions\when('wp_update_post')->alias(function (array $data, bool $wpError) {
$this->postUpdates[] = $data;
if (($data['post_title'] ?? '') === 'Neu') {
throw new RuntimeException('save_post hook failed');
}
return (int) $data['ID'];
});
$this->expectException(WriteFailed::class);
try {
(new MediaUpdateAbility($this->log()))->execute(['items' => [['id' => 34, 'title' => 'Neu']]]);
} finally {
self::assertSame([['post_title' => 'Neu', 'ID' => 34], ['post_title' => 'Logo', 'ID' => 34]], $this->postUpdates);
}
}
public function testRestoreRemovesAnAltTextThatDidNotExistBefore(): void
{
Functions\when('metadata_exists')->justReturn(false);
Functions\when('wp_update_post')->alias(static fn (array $data) => $data['ID'] === 34
? new WP_Error('db', 'Datenbankfehler')
: (int) $data['ID']);
Functions\expect('delete_post_meta')->once()->with(33, '_wp_attachment_image_alt')->andReturn(true);
$this->expectException(WriteFailed::class);
(new MediaUpdateAbility($this->log()))->execute(['items' => [
['id' => 33, 'alt' => 'neu'],
['id' => 34, 'title' => 'Neu'],
]]);
}
public function testAFailedRestoreIsAPartialWriteNamingTheChangedIds(): void
{
Functions\when('wp_update_post')->alias(static fn (array $data) => $data['ID'] === 34
? new WP_Error('db', 'Datenbankfehler')
: (int) $data['ID']);
Functions\when('update_post_meta')->alias(static function (int $id, string $key, $value) {
if ($value === 'alter Alt-Text') {
throw new RuntimeException('meta write failed');
}
return true;
});
$log = Mockery::mock(ChangeLog::class);
$log->expects('recordPartial')->once()->with('lit/media-update', 'attachment', '33', Mockery::type('string'));
try {
(new MediaUpdateAbility($log))->execute(['items' => [
['id' => 33, 'alt' => 'neu'],
['id' => 34, 'title' => 'Neu'],
]]);
self::fail('WriteFailed expected');
} catch (WriteFailed $e) {
$error = $e->toError();
self::assertSame('lit_partial_write', $error->get_error_code());
self::assertSame([33], $error->get_error_data()['changed_ids']);
self::assertStringContainsString('33', $error->get_error_message());
}
}
public function testChangeLogFailureIsOnlyAWarning(): void
{
$log = Mockery::mock(ChangeLog::class);
$log->expects('record')->andThrow(new RuntimeException('db down'));
// error_log() is a PHP internal and cannot be stubbed; redirect it to a temp file instead.
$file = (string) tempnam(sys_get_temp_dir(), 'lit-mcp-log');
$previous = ini_set('error_log', $file);
try {
$result = (new MediaUpdateAbility($log))->execute(['items' => [['id' => 33, 'alt' => 'neu']]]);
} finally {
ini_set('error_log', (string) $previous);
unlink($file);
}
self::assertTrue($result['results'][0]['ok']);
self::assertNull($result['results'][0]['log_id']);
self::assertCount(1, $result['warnings']);
}
public function testIsIdempotentIndirectAndNotDestructive(): void
{
$ability = new MediaUpdateAbility($this->log());
self::assertSame(['readonly' => false, 'destructive' => false, 'idempotent' => true], $ability->annotations());
self::assertFalse($ability->isDirect());
self::assertSame(50, $ability->inputSchema()['properties']['items']['maxItems']);
self::assertStringContainsString('modified', $ability->description());
}
}