From 7dc22784cb55d00386c5894ef08fbf16164b92d5 Mon Sep 17 00:00:00 2001 From: peptiderepo Date: Tue, 21 Apr 2026 02:26:34 +0700 Subject: [PATCH] =?UTF-8?q?test(cost):=20ResearchReaperTest=20=E2=80=94=20?= =?UTF-8?q?five=20cases=20per=20spec?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Covers the five scenarios from convo thread research-cost-reaper seq 1: - test_reaps_orphan_with_matching_run_id_posts — meta lookup returns two post IDs; reaper delegates to amortize_research_costs which inserts two rows and deletes the orphan. - test_skips_orphan_within_grace_period — the SELECT's `created_at < now - 1h` clause filters fresh orphans at the DB; the reaper's stats stay zero and no side effects fire. - test_deletes_orphan_with_no_articles_after_7_days — orphan is 8 days old, zero siblings via meta or gen_log; reaper deletes outright. - test_falls_back_to_gen_log_when_post_meta_missing — meta returns empty (legacy pre-v0.8.1 post); gen_log has two distinct post_ids; amortize still runs. - test_idempotent_on_repeat_run — second pass on a cleaned state returns 0/0/0 with no inserts or deletes. All DB interaction mocked via $wpdb stub — no real DB round-trips. Fixtures are driven by property mutations in the test methods so PHPUnit's "one stub per method" restriction on mocks doesn't bite. Part of the v0.8.1 bundle. Co-Authored-By: Claude Opus 4.7 (1M context) --- tests/unit/Core/ResearchReaperTest.php | 260 +++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 tests/unit/Core/ResearchReaperTest.php diff --git a/tests/unit/Core/ResearchReaperTest.php b/tests/unit/Core/ResearchReaperTest.php new file mode 100644 index 0000000..476a1d6 --- /dev/null +++ b/tests/unit/Core/ResearchReaperTest.php @@ -0,0 +1,260 @@ +insert). + * + * @var array> + */ + private array $inserted_rows = []; + + /** + * Captured DELETE calls: [$table, $where-array]. + * + * @var array}> + */ + private array $deleted_rows = []; + + /** + * Fixture: the rows get_results should hand back for the orphan scan. + * + * @var array + */ + private array $orphan_fixtures = []; + + /** + * Fixture: post IDs the reaper's fallback gen_log query should return. + * + * @var int[] + */ + private array $gen_log_post_ids = []; + + protected function setUp(): void { + parent::setUp(); + + $this->inserted_rows = []; + $this->deleted_rows = []; + $this->orphan_fixtures = []; + $this->gen_log_post_ids = []; + + $this->wpdb = $this->create_mock_wpdb(); + $this->wpdb->insert_id = 1; + $this->wpdb->method( 'insert' )->willReturnCallback( + function ( $table, $row ) { + $this->inserted_rows[] = array_merge( [ '__table' => $table ], $row ); + return 1; + } + ); + $this->wpdb->method( 'delete' )->willReturnCallback( + function ( $table, $where ) { + $this->deleted_rows[] = [ (string) $table, (array) $where ]; + return 1; + } + ); + // prepare() returns its args joined so we can pattern-match in get_* stubs. + $this->wpdb->method( 'prepare' )->willReturnCallback( + function ( $sql, ...$args ) { + return $sql . '|' . implode( '|', array_map( 'strval', $args ) ); + } + ); + // get_results routes by SQL fragment between the reaper's orphan scan + // and the occasional Logger insert probes. + $this->wpdb->method( 'get_results' )->willReturnCallback( + function ( $sql ) { + if ( false !== stripos( (string) $sql, "post_id IS NULL AND created_at <" ) ) { + return $this->orphan_fixtures; + } + return []; + } + ); + // get_row serves amortize_research_costs's research-row lookup. + $this->wpdb->method( 'get_row' )->willReturnCallback( + function ( $sql ) { + foreach ( $this->orphan_fixtures as $o ) { + if ( false !== stripos( (string) $sql, (string) $o->run_id ) ) { + return (object) [ + 'id' => $o->id, + 'estimated_cost' => $o->estimated_cost ?? 0.50, + 'provider' => $o->provider ?? 'openrouter', + 'model' => $o->model ?? 'gemini-flash', + 'prompt_tokens' => $o->prompt_tokens ?? 1000, + 'completion_tokens' => $o->completion_tokens ?? 500, + ]; + } + } + return null; + } + ); + // get_col is the reaper's fallback "posts by run_id" and amortize's + // "distinct post_ids" query — both read from the same fixture. + $this->wpdb->method( 'get_col' )->willReturnCallback( + fn() => array_map( 'strval', $this->gen_log_post_ids ) + ); + + $GLOBALS['wpdb'] = $this->wpdb; + + $this->stub_get_option( [ + 'prautoblogger_log_level' => 'info', + ] ); + + // Reaper uses get_posts to look up sibling posts via post_meta. + Functions\when( 'get_posts' )->justReturn( [] ); + } + + protected function tearDown(): void { + unset( $GLOBALS['wpdb'] ); + parent::tearDown(); + } + + /** + * Helper: seed the orphan list returned by the reaper's primary SELECT. + * + * @param array $orphans + */ + private function seed_orphans( array $orphans ): void { + $this->orphan_fixtures = array_map( + static fn( $r ) => (object) $r, + $orphans + ); + } + + /** + * Helper: set the post_ids the gen_log fallback query returns. + * + * @param int[] $post_ids + */ + private function seed_gen_log_posts_for_run( array $post_ids ): void { + $this->gen_log_post_ids = $post_ids; + } + + /** + * 1. Reap succeeds via post_meta primary lookup. + * + * Orphan row is >1h old, `_prautoblogger_run_id` meta returns two + * post IDs, amortize inserts two attributed rows and deletes the + * original orphan. + */ + public function test_reaps_orphan_with_matching_run_id_posts(): void { + $old_ts = gmdate( 'Y-m-d H:i:s', time() - ( 2 * HOUR_IN_SECONDS ) ); + $this->seed_orphans( [ [ 'id' => 99, 'run_id' => 'run-abc', 'created_at' => $old_ts, 'estimated_cost' => 0.40 ] ] ); + + // In the v0.8.1 world both sources agree. Meta is the reaper's gate; + // gen_log also has rows so `amortize_research_costs()` can do its + // own internal post-count query. + Functions\when( 'get_posts' )->alias( + static fn( $args ) => ( '_prautoblogger_run_id' === ( $args['meta_key'] ?? '' ) && 'run-abc' === ( $args['meta_value'] ?? '' ) ) + ? [ 101, 102 ] + : [] + ); + $this->seed_gen_log_posts_for_run( [ 101, 102 ] ); + + $stats = \PRAutoBlogger_Research_Reaper::reap(); + + $this->assertSame( 1, $stats['reaped'] ); + $this->assertSame( 0, $stats['deleted'] ); + $this->assertSame( 0, $stats['skipped'] ); + $this->assertCount( 2, $this->inserted_rows, 'One amortized row per post should be inserted.' ); + // Original orphan deleted by amortize_research_costs. + $this->assertNotEmpty( array_filter( $this->deleted_rows, static fn( $d ) => ( $d[1]['id'] ?? null ) === 99 ) ); + } + + /** + * 2. Orphan within the 1-hour grace window is left alone — a live + * pipeline may still be in the middle of its own amortize step. + */ + public function test_skips_orphan_within_grace_period(): void { + // The primary SELECT filters on `created_at < (now - 1h)`, so a + // fresh orphan is excluded from the result set at the DB boundary. + // We simulate that by returning an empty orphan list. + $this->seed_orphans( [] ); + + Functions\when( 'get_posts' )->justReturn( [ 101, 102 ] ); + + $stats = \PRAutoBlogger_Research_Reaper::reap(); + + $this->assertSame( 0, $stats['reaped'] ); + $this->assertSame( 0, $stats['deleted'] ); + $this->assertSame( 0, $stats['skipped'] ); + $this->assertEmpty( $this->inserted_rows ); + $this->assertEmpty( $this->deleted_rows ); + } + + /** + * 3. Orphan older than 7 days with zero matching posts is deleted + * outright — research cost is sunk with nothing to attribute to. + */ + public function test_deletes_orphan_with_no_articles_after_7_days(): void { + $stale_ts = gmdate( 'Y-m-d H:i:s', time() - ( 8 * DAY_IN_SECONDS ) ); + $this->seed_orphans( [ [ 'id' => 77, 'run_id' => 'run-dead', 'created_at' => $stale_ts ] ] ); + + // No posts via meta, no posts via gen_log. + Functions\when( 'get_posts' )->justReturn( [] ); + $this->seed_gen_log_posts_for_run( [] ); + + $stats = \PRAutoBlogger_Research_Reaper::reap(); + + $this->assertSame( 0, $stats['reaped'] ); + $this->assertSame( 1, $stats['deleted'] ); + $this->assertNotEmpty( array_filter( $this->deleted_rows, static fn( $d ) => ( $d[1]['id'] ?? null ) === 77 ) ); + } + + /** + * 4. When `_prautoblogger_run_id` post_meta is absent (legacy posts + * predating v0.8.1), the reaper falls back to querying gen_log for + * distinct post_ids carrying the same run_id. + */ + public function test_falls_back_to_gen_log_when_post_meta_missing(): void { + $old_ts = gmdate( 'Y-m-d H:i:s', time() - ( 2 * HOUR_IN_SECONDS ) ); + $this->seed_orphans( [ [ 'id' => 55, 'run_id' => 'run-legacy', 'created_at' => $old_ts, 'estimated_cost' => 0.30 ] ] ); + + // Meta lookup returns nothing. + Functions\when( 'get_posts' )->justReturn( [] ); + // But gen_log has two posts with this run_id. + $this->seed_gen_log_posts_for_run( [ 201, 202 ] ); + + $stats = \PRAutoBlogger_Research_Reaper::reap(); + + $this->assertSame( 1, $stats['reaped'] ); + $this->assertCount( 2, $this->inserted_rows ); + } + + /** + * 5. A second reap run is a no-op — the first run deleted the orphan + * and inserted amortized per-article rows, so the scan returns empty. + */ + public function test_idempotent_on_repeat_run(): void { + // Simulate "already reaped" state: scan returns no orphans. + $this->seed_orphans( [] ); + + $stats_1 = \PRAutoBlogger_Research_Reaper::reap(); + $stats_2 = \PRAutoBlogger_Research_Reaper::reap(); + + $this->assertSame( 0, $stats_1['reaped'] ); + $this->assertSame( 0, $stats_2['reaped'] ); + $this->assertEmpty( $this->inserted_rows ); + $this->assertEmpty( $this->deleted_rows ); + } +}