feat(cache): Tool lit/cache-clear zum gezielten Leeren des Caches

lit/cache-clear leert den Seiten-Cache von WP Super Cache für die ganze Website (scope all, Recht manage_options) oder einen Beitrag (scope post, Recht edit_post); Probelauf ohne confirm, Ausführen mit confirm: true. Das CapabilityGate sperrt das Tool, wenn WP Super Cache bricht; eine Sperre zur Laufzeit wird als Fehler gemeldet. Listener und Tool teilen die 30-s-Drosselung mit Nachlauf (SuperCachePurger); der Listener ignoriert die Einträge des Tools. Behoben vor dem Commit: die Verdrahtung des Purgers erfasste die Registry zu früh (immer gesperrt), jetzt per Referenz und mit Test über Plugin::integrations().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan-Niclas Loosen
2026-11-06 19:05:21 +01:00
co-authored by Claude Opus 5.5
parent d3e5d4fac0
commit 1ac347e76f
12 changed files with 883 additions and 86 deletions
@@ -0,0 +1,288 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\SuperCache;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Annotations;
use LIT\MCP\Abilities\DeclaresRequirements;
use LIT\MCP\Integrations\SuperCache\CacheClearAbility;
use LIT\MCP\Integrations\SuperCache\SuperCacheFeature;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Support\FakeChangeLog;
use LIT\MCP\Tests\Unit\TestCase;
use WP_Error;
use WP_Post;
final class CacheClearAbilityTest extends TestCase
{
/** @var list<string> */
private array $purges = [];
/** @var list<string> */
private array $scheduled = [];
private int|false $lastPurge = false;
protected function setUp(): void
{
parent::setUp();
$this->purges = [];
$this->scheduled = [];
$this->lastPurge = false;
Functions\when('is_multisite')->justReturn(false);
Functions\when('get_transient')->alias(fn (): int|false => $this->lastPurge);
Functions\when('set_transient')->justReturn(true);
Functions\when('wp_next_scheduled')->justReturn(false);
Functions\when('wp_schedule_single_event')->alias(function (int $at, string $hook): bool {
$this->scheduled[] = $hook;
return true;
});
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_post')->alias(
static fn (int $id): ?WP_Post => $id === 7
? new WP_Post(['ID' => 7, 'post_type' => 'page', 'post_title' => 'Start', 'post_status' => 'publish'])
: ($id === 8
? new WP_Post(['ID' => 8, 'post_type' => 'page', 'post_title' => 'Idee', 'post_status' => 'draft'])
: null)
);
}
protected function tearDown(): void
{
unset($GLOBALS['cache_enabled']);
parent::tearDown();
}
private function ability(?FakeChangeLog $log = null, bool $cacheOn = true, bool $usable = true): CacheClearAbility
{
$purger = new SuperCachePurger(
static fn (SuperCacheFeature $feature): bool => $usable,
static fn (): bool => $cacheOn,
function (int $id): void {
$this->purges[] = 'post:' . $id;
},
function (int $blog): void {
$this->purges[] = 'all:' . $blog;
}
);
return new CacheClearAbility($purger, $log ?? FakeChangeLog::forbidden());
}
public function testDescribesItselfLikeAGuardedWriteTool(): void
{
$ability = $this->ability();
self::assertInstanceOf(Ability::class, $ability);
self::assertSame('lit/cache-clear', $ability->name());
self::assertFalse($ability->isDirect());
self::assertSame(Annotations::write(true), $ability->annotations());
self::assertStringContainsString('confirm: true', $ability->description());
self::assertStringContainsString('WP Super Cache', $ability->description());
$schema = $ability->inputSchema();
self::assertSame(['scope'], $schema['required']);
self::assertFalse($schema['additionalProperties']);
self::assertSame(['all', 'post'], $schema['properties']['scope']['enum']);
self::assertSame(['scope', 'post_id', 'confirm'], array_keys($schema['properties']));
self::assertArrayHasKey('outcome', $ability->outputSchema()['properties']);
}
public function testDeclaresTheCapabilityOfTheScope(): void
{
$ability = $this->ability();
self::assertInstanceOf(DeclaresRequirements::class, $ability);
self::assertSame(['wpsc-purge-all'], $ability->requirements(['scope' => 'all']));
self::assertSame(['wpsc-purge-post'], $ability->requirements(['scope' => 'post', 'post_id' => 7]));
self::assertSame([], $ability->requirements(['scope' => 'x']));
self::assertSame([], $ability->requirements([]));
}
public function testAllNeedsManageOptions(): void
{
$asked = [];
Functions\when('current_user_can')->alias(function (string $cap) use (&$asked): bool {
$asked[] = $cap;
return false;
});
self::assertToolError($this->ability()->permission(['scope' => 'all']), 'forbidden');
self::assertSame(['manage_options'], $asked);
Functions\when('current_user_can')->justReturn(true);
self::assertTrue($this->ability()->permission(['scope' => 'all']));
}
public function testPostNeedsEditPostForThatId(): void
{
$asked = [];
Functions\when('current_user_can')->alias(function (string $cap, int $id) use (&$asked): bool {
$asked[] = [$cap, $id];
return false;
});
self::assertToolError($this->ability()->permission(['scope' => 'post', 'post_id' => 7]), 'forbidden');
self::assertSame([['edit_post', 7]], $asked);
Functions\when('current_user_can')->justReturn(true);
self::assertTrue($this->ability()->permission(['scope' => 'post', 'post_id' => 7]));
}
public function testAnUnknownPostIsNotFound(): void
{
self::assertToolError($this->ability()->permission(['scope' => 'post', 'post_id' => 99]), 'not_found');
self::assertToolError($this->ability()->execute(['scope' => 'post', 'post_id' => 99, 'confirm' => true]), 'not_found');
self::assertSame([], $this->purges);
}
/** @return array<string, array{array<string, mixed>}> */
public static function invalidInputs(): array
{
return [
'no scope' => [[]],
'unknown scope' => [['scope' => 'site']],
'post without id' => [['scope' => 'post']],
'post with zero' => [['scope' => 'post', 'post_id' => 0]],
'post with text' => [['scope' => 'post', 'post_id' => 'abc']],
];
}
/**
* @dataProvider invalidInputs
* @param array<string, mixed> $input
*/
public function testInvalidInputIsRefusedWithoutEffect(array $input): void
{
self::assertToolError($this->ability()->permission($input), 'validation_failed');
self::assertToolError($this->ability()->execute($input + ['confirm' => true]), 'validation_failed');
self::assertSame([], $this->purges);
}
public function testTheDryRunClearsNothingAndReportsTheState(): void
{
$GLOBALS['cache_enabled'] = true;
$this->lastPurge = time() - 5;
$payload = self::assertToolError($this->ability()->execute(['scope' => 'all']), 'confirm_required');
self::assertSame([], $this->purges);
self::assertSame([], $this->scheduled);
self::assertSame('all', $payload['scope']);
self::assertTrue($payload['cache_enabled']);
self::assertTrue($payload['throttled']);
self::assertStringContainsString('Probelauf', $payload['message']);
}
public function testTheDryRunOfAPostNamesThePostAndIgnoresAConfirmThatIsNotTrue(): void
{
$payload = self::assertToolError(
$this->ability(cacheOn: false)->execute(['scope' => 'post', 'post_id' => 7, 'confirm' => 'true']),
'confirm_required'
);
self::assertSame([], $this->purges);
self::assertSame(7, $payload['post_id']);
self::assertFalse($payload['cache_enabled']);
self::assertStringContainsString('Start', $payload['message']);
self::assertStringContainsString('ausgeschaltet', $payload['message']);
}
public function testConfirmClearsThePageOfThePostAndLogsIt(): void
{
$log = new FakeChangeLog(4);
$result = $this->ability($log)->execute(['scope' => 'post', 'post_id' => 7, 'confirm' => true]);
self::assertSame(['post:7'], $this->purges);
self::assertTrue($result['ok']);
self::assertSame('purged', $result['outcome']);
self::assertSame(4, $result['log_id']);
$log->assertRecorded(['ability' => 'lit/cache-clear', 'object_type' => 'wpsc', 'object_id' => '7']);
}
public function testADraftHasNothingToClear(): void
{
$GLOBALS['cache_enabled'] = true;
$result = $this->ability()->execute(['scope' => 'post', 'post_id' => 8, 'confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame('nothing', $result['outcome']);
self::assertStringContainsString('Entwurf', $result['summary']);
}
public function testConfirmClearsTheWholeCacheAtOnce(): void
{
$log = new FakeChangeLog(1);
$result = $this->ability($log)->execute(['scope' => 'all', 'confirm' => true]);
self::assertSame(['all:0'], $this->purges);
self::assertSame('purged', $result['outcome']);
$log->assertRecorded(['ability' => 'lit/cache-clear', 'object_type' => 'wpsc', 'object_id' => 'all']);
}
public function testAWholePurgeInsideTheLockTimeIsThrottledWithATrailingPurge(): void
{
$this->lastPurge = time() - 5;
$result = $this->ability(new FakeChangeLog(1))->execute(['scope' => 'all', 'confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame([SuperCachePurger::TRAILING_HOOK], $this->scheduled);
self::assertSame('throttled', $result['outcome']);
self::assertStringContainsString('Nachlauf', $result['summary']);
}
/** @return array<string, array{array<string, mixed>}> */
public static function scopes(): array
{
return ['all' => [['scope' => 'all']], 'post' => [['scope' => 'post', 'post_id' => 7]]];
}
/**
* @dataProvider scopes
* @param array<string, mixed> $input
*/
public function testWithTheCacheOffNothingHappensAndNothingIsLogged(array $input): void
{
$result = $this->ability(FakeChangeLog::forbidden(), cacheOn: false)->execute($input + ['confirm' => true]);
self::assertSame([], $this->purges);
self::assertSame('cache_off', $result['outcome']);
self::assertNull($result['log_id']);
}
/**
* @dataProvider confirmedScopes
* @param array<string, mixed> $input
*/
public function testALockedPurgeIsReportedAsAnErrorAndNeitherPurgesNorLogs(array $input): void
{
$previous = ini_set('error_log', '/dev/null');
$result = $this->ability(FakeChangeLog::forbidden(), usable: false)->execute($input);
ini_set('error_log', (string) $previous);
self::assertInstanceOf(WP_Error::class, $result);
self::assertSame('lit_compat_incompatible', $result->get_error_code());
self::assertStringContainsString(
'WP Super Cache ist gesperrt (siehe Reiter Kompatibilität). Es wurde nichts geleert.',
$result->get_error_message()
);
self::assertSame([], $this->purges);
}
/** @return array<string, array{array<string, mixed>}> */
public static function confirmedScopes(): array
{
return [
'all' => [['scope' => 'all', 'confirm' => true]],
'post' => [['scope' => 'post', 'post_id' => 7, 'confirm' => true]],
];
}
}
@@ -11,30 +11,37 @@ use LIT\MCP\Integrations\Bootable;
use LIT\MCP\Integrations\Integration;
use LIT\MCP\Integrations\SuperCache\SuperCacheCompatibility;
use LIT\MCP\Integrations\SuperCache\SuperCacheIntegration;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Support\FakeChangeLog;
use LIT\MCP\Tests\Unit\TestCase;
final class SuperCacheIntegrationTest extends TestCase
{
public function testIsAnIntegrationWithoutAbilitiesThatProvidesItsProfile(): void
private static function purger(): SuperCachePurger
{
$integration = new SuperCacheIntegration();
return new SuperCachePurger(static fn (): bool => true);
}
public function testIsAnIntegrationThatProvidesItsProfileAndTheCacheClearTool(): void
{
$integration = new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden());
self::assertInstanceOf(Integration::class, $integration);
self::assertInstanceOf(ProvidesCompatibility::class, $integration);
self::assertSame('wpsc', $integration->id());
self::assertSame('WP Super Cache', $integration->label());
self::assertSame([], $integration->abilities());
self::assertEquals(['lit/cache-clear'], array_map(static fn ($a): string => $a->name(), $integration->abilities()));
self::assertEquals([SuperCacheCompatibility::profile()], $integration->compatibilities());
}
public function testIsAvailableOnlyWithSuperCache(): void
{
self::assertSame(defined('WPCACHEHOME'), (new SuperCacheIntegration())->isAvailable());
self::assertSame(defined('WPCACHEHOME'), (new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden()))->isAvailable());
}
public function testBootHooksTheOrphanCleanupIntoTheProfileLoad(): void
{
$integration = new SuperCacheIntegration();
$integration = new SuperCacheIntegration(null, self::purger(), FakeChangeLog::forbidden());
$integration->boot();
self::assertInstanceOf(Bootable::class, $integration);
@@ -45,11 +52,11 @@ final class SuperCacheIntegrationTest extends TestCase
{
Functions\expect('get_posts')->never();
Functions\when('current_user_can')->justReturn(true);
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('pods');
(new SuperCacheIntegration(static fn (): bool => false))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('pods');
(new SuperCacheIntegration(static fn (): bool => false, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
Functions\when('current_user_can')->justReturn(false);
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
$this->addToAssertionCount(1);
}
@@ -63,6 +70,6 @@ final class SuperCacheIntegrationTest extends TestCase
return [];
});
(new SuperCacheIntegration(static fn (): bool => true))->removeOrphans('wpsc');
(new SuperCacheIntegration(static fn (): bool => true, self::purger(), FakeChangeLog::forbidden()))->removeOrphans('wpsc');
}
}
@@ -200,6 +200,18 @@ final class SuperCacheListenerTest extends TestCase
self::assertSame([], $this->purges);
}
/** lit/cache-clear purges itself; its change log entry must not trigger a second purge. */
public function testTheCacheClearToolsOwnEntriesPurgeNothing(): void
{
$listener = $this->listener();
$listener->onChange('lit/cache-clear', 'wpsc', 'all', 1);
$listener->onChange('lit/cache-clear', 'wpsc', '12', 2);
$listener->flush();
self::assertSame([], $this->purges);
self::assertFalse(has_action('shutdown', [$listener, 'flush']));
}
public function testNothingHappensWhileTheCacheIsOff(): void
{
$listener = $this->listener(cacheOn: false);
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\SuperCache;
use Brain\Monkey\Functions;
use LIT\MCP\Integrations\SuperCache\SuperCacheFeature;
use LIT\MCP\Integrations\SuperCache\SuperCachePurger;
use LIT\MCP\Tests\Unit\TestCase;
final class SuperCachePurgerTest extends TestCase
{
public function testALockedWholePurgeDoesNothingAndSaysSo(): void
{
$previous = ini_set('error_log', '/dev/null');
Functions\expect('get_transient')->never();
$purger = new SuperCachePurger(
static fn (SuperCacheFeature $feature): bool => false,
static fn (): bool => true,
static fn (int $id) => self::fail('no post purge'),
static fn (int $blog) => self::fail('no whole purge')
);
self::assertSame(SuperCachePurger::LOCKED, $purger->everything());
self::assertFalse($purger->post(3));
ini_set('error_log', (string) $previous);
}
public function testThrottledReadsTheStamp(): void
{
$stamp = false;
Functions\when('get_transient')->alias(static function () use (&$stamp) {
return $stamp;
});
$purger = new SuperCachePurger(static fn (): bool => true);
self::assertFalse($purger->throttled());
$stamp = (string) (time() - 5);
self::assertTrue($purger->throttled());
$stamp = time() - 31;
self::assertFalse($purger->throttled());
}
/** The stamp is read once: a transient expiring between two reads must not schedule the trailing purge in 1970. */
public function testEverythingReadsTheStampOnceAndSchedulesTheTrailingPurgeInTheFuture(): void
{
$reads = 0;
$scheduledAt = [];
Functions\when('get_transient')->alias(static function () use (&$reads) {
return ++$reads === 1 ? time() - 5 : false;
});
Functions\when('wp_next_scheduled')->justReturn(false);
Functions\when('wp_schedule_single_event')->alias(static function (int $at) use (&$scheduledAt): bool {
$scheduledAt[] = $at;
return true;
});
$purger = new SuperCachePurger(static fn (): bool => true);
self::assertSame(SuperCachePurger::THROTTLED, $purger->everything());
self::assertSame(1, $reads);
self::assertCount(1, $scheduledAt);
self::assertGreaterThanOrEqual(time(), $scheduledAt[0]);
}
}