diff --git a/tests/Unit/MaintenancePurgeTest.php b/tests/Unit/MaintenancePurgeTest.php new file mode 100644 index 0000000..f75cb5c --- /dev/null +++ b/tests/Unit/MaintenancePurgeTest.php @@ -0,0 +1,51 @@ + 3600, 'DAY_IN_SECONDS' => 86400 ) as $k => $v ) { + if ( ! defined( $k ) ) { + define( $k, $v ); + } + } + $this->previous = $GLOBALS['wpdb'] ?? null; + } + + protected function tearDown(): void { + $GLOBALS['wpdb'] = $this->previous; + } + + public function test_purge_sql_only_targets_abandoned_pending_rows_older_than_a_week(): void { + $GLOBALS['wpdb'] = new class() { + public string $prefix = 'wp_'; + public array $queries = array(); + public function prepare( string $q, ...$args ): string { return vsprintf( str_replace( '%s', "'%s'", $q ), $args ); } + public function query( string $q ): int { $this->queries[] = $q; return 3; } + }; + $before = time(); + $n = Maintenance::purge_abandoned(); + $sql = $GLOBALS['wpdb']->queries[0] ?? ''; + + $this->assertSame( 3, $n ); + $this->assertStringStartsWith( 'DELETE FROM wp_sg_donations', $sql ); + $this->assertStringContainsString( "status = 'pending'", $sql, 'completed donations must never be deleted' ); + $this->assertStringContainsString( "paypal_capture_id IS NULL OR paypal_capture_id = ''", $sql, 'anything with a PayPal capture must be kept' ); + $this->assertStringContainsString( 'goal_id > 0', $sql, 'test donations (goal_id 0) are handled separately and kept' ); + $this->assertMatchesRegularExpression( "/created_at < '(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'/", $sql ); + preg_match( "/created_at < '([^']+)'/", $sql, $m ); + $cutoff = strtotime( $m[1] . ' UTC' ); + $this->assertEqualsWithDelta( $before - 7 * 86400, $cutoff, 5, 'cutoff must be 7 days ago' ); + } +}