feat: M3 edit + single-step re-run — input versioning, human-modified audit, staged re-run (v0.20.0) (#161)
QA: REJECT@6ed639d (CTO rebase header P1) -> APPROVE@6727e07 (qa-reviews/prautoblogger/2026-06-12-6727e07.md) CPO guardrails 1-5 verified hard-AC. CEO conditional greenlight 2026-06-12 in chat (QA-APPROVE condition met). Agent-Session: cto-m3-merge-20260612
This commit is contained in:
120
tests/unit/Admin/BoardHumanModifiedFlagTest.php
Normal file
120
tests/unit/Admin/BoardHumanModifiedFlagTest.php
Normal file
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for the v0.20.0 board-card human_modified flag (CPO product AC:
|
||||
* human-modified runs are visually distinct at the run-list level).
|
||||
*
|
||||
* Locks: ONE batched query flags all cards (no N+1), unflagged runs and
|
||||
* missing-table sites degrade to false.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Admin
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Admin;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class BoardHumanModifiedFlagTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* Number of get_col calls (N+1 guard).
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private int $col_queries = 0;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->col_queries = 0;
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
Functions\when( 'get_post_meta' )->alias(
|
||||
static function ( $post_id, $key ) {
|
||||
if ( '_prautoblogger_run_id' === $key ) {
|
||||
return 'run-' . $post_id;
|
||||
}
|
||||
if ( '_prautoblogger_total_cost' === $key ) {
|
||||
return '0.05';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
);
|
||||
Functions\when( 'get_edit_post_link' )->justReturn( 'https://example.com/edit' );
|
||||
Functions\when( 'admin_url' )->alias( static fn( $p = '' ) => 'https://example.com/wp-admin/' . $p );
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\WP_Query::$_test_posts_queue = array();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Build a WP_Post for the queue. */
|
||||
private function make_post( int $id ): \WP_Post {
|
||||
$post = new \WP_Post();
|
||||
$post->ID = $id;
|
||||
$post->post_title = 'Post ' . $id;
|
||||
$post->post_date_gmt = '2026-06-12 00:00:00';
|
||||
return $post;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cards whose runs carry human_modified rows get the flag; others
|
||||
* stay false; exactly ONE batched query runs for the whole column.
|
||||
*/
|
||||
public function test_cards_flagged_in_one_batched_query(): void {
|
||||
\WP_Query::$_test_posts_queue[] = array( $this->make_post( 1 ), $this->make_post( 2 ), $this->make_post( 3 ) );
|
||||
|
||||
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
|
||||
$this->wpdb->method( 'get_col' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
++$this->col_queries;
|
||||
$this->assertStringContainsString( 'human_modified = 1', (string) $sql );
|
||||
return array( 'run-2' ); // Only post 2's run was edited.
|
||||
}
|
||||
);
|
||||
|
||||
$cards = ( new \PRAutoBlogger_Board_Data_Provider() )->get_in_review_cards();
|
||||
|
||||
$this->assertCount( 3, $cards );
|
||||
$this->assertFalse( $cards[0]['human_modified'] );
|
||||
$this->assertTrue( $cards[1]['human_modified'] );
|
||||
$this->assertFalse( $cards[2]['human_modified'] );
|
||||
$this->assertSame( 1, $this->col_queries, 'one batched query, never per-card' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Missing substrate table: flags default false, zero flag queries.
|
||||
*/
|
||||
public function test_missing_table_degrades_to_false(): void {
|
||||
\WP_Query::$_test_posts_queue[] = array( $this->make_post( 1 ) );
|
||||
|
||||
$this->wpdb->method( 'get_var' )->willReturn( null );
|
||||
$this->wpdb->method( 'get_col' )->willReturnCallback(
|
||||
function () {
|
||||
++$this->col_queries;
|
||||
return array();
|
||||
}
|
||||
);
|
||||
|
||||
$cards = ( new \PRAutoBlogger_Board_Data_Provider() )->get_in_review_cards();
|
||||
|
||||
$this->assertFalse( $cards[0]['human_modified'] );
|
||||
$this->assertSame( 0, $this->col_queries );
|
||||
}
|
||||
}
|
||||
103
tests/unit/Admin/DossierActionsRerunTest.php
Normal file
103
tests/unit/Admin/DossierActionsRerunTest.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
/**
|
||||
* Dossier_Actions: rerun + status endpoint tests (v0.20.0, M3).
|
||||
*
|
||||
* Locks the chained-cron contract (queue only — ZERO state mutations in
|
||||
* the AJAX layer) and the read-only stage-status poll shape.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Admin
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Admin;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class DossierActionsRerunTest extends DossierActionsTestCase {
|
||||
|
||||
/**
|
||||
* Chained-cron contract: rerun_stage only schedules — no run/stage
|
||||
* state is mutated by the AJAX layer, and the response says queued.
|
||||
*/
|
||||
public function test_rerun_stage_queues_without_any_state_mutation(): void {
|
||||
$this->wire_eligible_context();
|
||||
// A saved fork exists for the replay check.
|
||||
$wpdb_get_row_fork = array(
|
||||
'version' => '1',
|
||||
'request_json' => '{"model":"m","messages":[{"role":"user","content":"edited"}]}',
|
||||
);
|
||||
// Rebuild get_row: forks resolve, run row terminal.
|
||||
$_POST = array(
|
||||
'post_id' => '99',
|
||||
'stage' => 'draft',
|
||||
'agent_role' => 'writer',
|
||||
);
|
||||
// Replace the get_row wiring (fork now exists).
|
||||
$wpdb = $this->create_mock_wpdb();
|
||||
$wpdb->options = 'wp_options';
|
||||
$wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
$wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
if ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) {
|
||||
return ( false !== strpos( (string) $sql, 'stage_inputs' ) ) ? 'wp_prautoblogger_stage_inputs' : 'wp_prautoblogger_runs';
|
||||
}
|
||||
return null; // Lock free.
|
||||
}
|
||||
);
|
||||
$wpdb->method( 'get_row' )->willReturnCallback(
|
||||
static function ( $sql ) use ( $wpdb_get_row_fork ) {
|
||||
if ( false !== strpos( (string) $sql, 'stage_inputs' ) ) {
|
||||
return $wpdb_get_row_fork;
|
||||
}
|
||||
return array(
|
||||
'run_id' => 'run-1',
|
||||
'status' => 'done',
|
||||
);
|
||||
}
|
||||
);
|
||||
$wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
$GLOBALS['wpdb'] = $wpdb;
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
|
||||
$actions = new \PRAutoBlogger_Dossier_Actions();
|
||||
$this->dispatch( array( $actions, 'on_rerun_stage' ) );
|
||||
|
||||
$this->assertTrue( $this->json['ok'] );
|
||||
$this->assertTrue( $this->json['data']['queued'] );
|
||||
$this->assertCount( 1, $this->scheduled );
|
||||
$this->assertSame( \PRAutoBlogger_Rerun_Executor::REPLAY_ACTION, $this->scheduled[0]['hook'] );
|
||||
$this->assertSame( array( 'run-1', 99, 'draft', 'writer', 'idea:abc123' ), array_slice( $this->scheduled[0]['args'], 0, 5 ) );
|
||||
foreach ( $this->queries as $sql ) {
|
||||
$this->assertStringNotContainsString( 'UPDATE', $sql, 'the AJAX layer must not mutate state' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* stage_status: read-only poll returns run status + per-stage state
|
||||
* with stale/human_modified flags.
|
||||
*/
|
||||
public function test_stage_status_returns_stage_states(): void {
|
||||
$this->wire_eligible_context();
|
||||
$this->wpdb->method( 'get_results' )->willReturn( array() );
|
||||
$_POST = array( 'post_id' => '99' );
|
||||
|
||||
$actions = new \PRAutoBlogger_Dossier_Actions();
|
||||
$this->dispatch( array( $actions, 'on_stage_status' ) );
|
||||
|
||||
$this->assertTrue( $this->json['ok'] );
|
||||
$this->assertArrayHasKey( 'run_status', $this->json['data'] );
|
||||
$this->assertArrayHasKey( 'stages', $this->json['data'] );
|
||||
}
|
||||
}
|
||||
87
tests/unit/Admin/DossierActionsSaveInputTest.php
Normal file
87
tests/unit/Admin/DossierActionsSaveInputTest.php
Normal file
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
/**
|
||||
* Dossier_Actions: save_input endpoint tests (v0.20.0, M3).
|
||||
*
|
||||
* Locks: published-post rejection (guardrail 5 server-side), fork
|
||||
* structure validation (count/roles locked, contents non-empty), and
|
||||
* the merged-fork save (model/options from the base, never the client).
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Admin
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Admin;
|
||||
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class DossierActionsSaveInputTest extends DossierActionsTestCase {
|
||||
|
||||
/**
|
||||
* Frozen post: save_input rejects server-side with 400 and inserts
|
||||
* nothing (guardrail 5 is not just hidden UI).
|
||||
*/
|
||||
public function test_save_input_rejects_published_post(): void {
|
||||
$this->wire_eligible_context( 'publish' );
|
||||
$_POST = array(
|
||||
'post_id' => '99',
|
||||
'stage' => 'draft',
|
||||
'agent_role' => 'writer',
|
||||
'messages' => '[]',
|
||||
);
|
||||
|
||||
$actions = new \PRAutoBlogger_Dossier_Actions();
|
||||
$this->dispatch( array( $actions, 'on_save_input' ) );
|
||||
|
||||
$this->assertFalse( $this->json['ok'] );
|
||||
$this->assertSame( 400, $this->json['status'] );
|
||||
$this->assertCount( 0, $this->inserted );
|
||||
}
|
||||
|
||||
/**
|
||||
* Structure lock: changing a message ROLE (or count, or emptying a
|
||||
* content) is rejected — forks are always replayable chat bodies.
|
||||
*/
|
||||
public function test_save_input_rejects_structure_mismatch(): void {
|
||||
$this->wire_eligible_context();
|
||||
$_POST = array(
|
||||
'post_id' => '99',
|
||||
'stage' => 'draft',
|
||||
'agent_role' => 'writer',
|
||||
// Role flipped user->assistant vs the base body.
|
||||
'messages' => '[{"role":"system","content":"sys"},{"role":"assistant","content":"edited"}]',
|
||||
);
|
||||
|
||||
$actions = new \PRAutoBlogger_Dossier_Actions();
|
||||
$this->dispatch( array( $actions, 'on_save_input' ) );
|
||||
|
||||
$this->assertFalse( $this->json['ok'] );
|
||||
$this->assertCount( 0, $this->inserted );
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid edit: fork v1 saved with the edited content merged into the
|
||||
* base body; model/options come from the base, not the client.
|
||||
*/
|
||||
public function test_save_input_saves_merged_fork(): void {
|
||||
$this->wire_eligible_context();
|
||||
$_POST = array(
|
||||
'post_id' => '99',
|
||||
'stage' => 'draft',
|
||||
'agent_role' => 'writer',
|
||||
'messages' => '[{"role":"system","content":"sys"},{"role":"user","content":"EDITED PROMPT"}]',
|
||||
);
|
||||
|
||||
$actions = new \PRAutoBlogger_Dossier_Actions();
|
||||
$this->dispatch( array( $actions, 'on_save_input' ) );
|
||||
|
||||
$this->assertTrue( $this->json['ok'] );
|
||||
$this->assertSame( 1, $this->json['data']['version'] );
|
||||
$this->assertCount( 1, $this->inserted );
|
||||
$row = $this->inserted[0];
|
||||
$this->assertSame( 'human', $row['source'] );
|
||||
$this->assertSame( 'rhys', $row['author'] );
|
||||
$this->assertSame( 'idea:abc123', $row['item_key'] );
|
||||
$body = json_decode( (string) $row['request_json'], true );
|
||||
$this->assertSame( 'EDITED PROMPT', $body['messages'][1]['content'] );
|
||||
$this->assertSame( 'm', $body['model'] ); // From the base, not the client.
|
||||
}
|
||||
}
|
||||
212
tests/unit/Admin/DossierActionsTestCase.php
Normal file
212
tests/unit/Admin/DossierActionsTestCase.php
Normal file
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
/**
|
||||
* Shared harness for the Dossier_Actions endpoint tests (v0.20.0, M3).
|
||||
*
|
||||
* Provides: mock wpdb with SQL-pattern wiring, JSON-response capture
|
||||
* (wp_send_json_* throw a sentinel), cron-schedule capture, and the
|
||||
* eligible-context fixture (draft post, terminal run, free lock).
|
||||
* Split across two test classes for the 300-line file cap (the M2
|
||||
* split-precedent applies to test files too).
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Admin
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Admin;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
abstract class DossierActionsTestCase extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
protected $wpdb;
|
||||
|
||||
/**
|
||||
* Captured JSON response (success/error + payload + status).
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
protected $json = null;
|
||||
|
||||
/**
|
||||
* SQL captured from $wpdb->query().
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected array $queries = array();
|
||||
|
||||
/**
|
||||
* Rows captured from $wpdb->insert().
|
||||
*
|
||||
* @var array<int, array>
|
||||
*/
|
||||
protected array $inserted = array();
|
||||
|
||||
/**
|
||||
* Cron events captured from wp_schedule_single_event().
|
||||
*
|
||||
* @var array<int, array>
|
||||
*/
|
||||
protected array $scheduled = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->json = null;
|
||||
$this->queries = array();
|
||||
$this->inserted = array();
|
||||
$this->scheduled = array();
|
||||
$_POST = array();
|
||||
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$this->wpdb->options = 'wp_options';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'insert' )->willReturnCallback(
|
||||
function ( $table, $row ) {
|
||||
$this->inserted[] = (array) $row;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
|
||||
Functions\when( 'check_ajax_referer' )->justReturn( true );
|
||||
Functions\when( 'current_user_can' )->justReturn( true );
|
||||
Functions\when( 'absint' )->alias( static function ( $val ) { return abs( (int) $val ); } );
|
||||
Functions\when( 'sanitize_key' )->alias( static function ( $val ) { return preg_replace( '/[^a-z0-9_\-]/', '', strtolower( (string) $val ) ); } );
|
||||
Functions\when( 'wp_unslash' )->returnArg();
|
||||
Functions\when( 'wp_schedule_single_event' )->alias(
|
||||
function ( $ts, $hook, $args ) {
|
||||
$this->scheduled[] = array(
|
||||
'hook' => $hook,
|
||||
'args' => $args,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
Functions\when( 'spawn_cron' )->justReturn( true );
|
||||
Functions\when( 'wp_remote_post' )->justReturn( array() );
|
||||
Functions\when( 'site_url' )->justReturn( 'https://example.com' );
|
||||
Functions\when( 'wp_send_json_success' )->alias(
|
||||
function ( $data = null ) {
|
||||
$this->json = array(
|
||||
'ok' => true,
|
||||
'data' => $data,
|
||||
);
|
||||
throw new \RuntimeException( 'json_sent' );
|
||||
}
|
||||
);
|
||||
Functions\when( 'wp_send_json_error' )->alias(
|
||||
function ( $data = null, $status = 0 ) {
|
||||
$this->json = array(
|
||||
'ok' => false,
|
||||
'data' => $data,
|
||||
'status' => $status,
|
||||
);
|
||||
throw new \RuntimeException( 'json_sent' );
|
||||
}
|
||||
);
|
||||
$user = new \stdClass();
|
||||
$user->user_login = 'rhys';
|
||||
Functions\when( 'wp_get_current_user' )->justReturn( $user );
|
||||
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
$_POST = array();
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Run an endpoint, swallowing the wp_send_json sentinel. */
|
||||
protected function dispatch( callable $endpoint ): void {
|
||||
try {
|
||||
$endpoint();
|
||||
} catch ( \RuntimeException $e ) {
|
||||
if ( 'json_sent' !== $e->getMessage() ) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Wire post meta + a draft post + a terminal run + free lock. */
|
||||
protected function wire_eligible_context( string $post_status = 'draft', string $run_status = 'done' ): void {
|
||||
Functions\when( 'get_post_meta' )->alias(
|
||||
static function ( $post_id, $key ) {
|
||||
if ( '_prautoblogger_run_id' === $key ) {
|
||||
return 'run-1';
|
||||
}
|
||||
if ( '_prautoblogger_idea_hash' === $key ) {
|
||||
return 'abc123';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
);
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 99;
|
||||
$post->post_status = $post_status;
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) use ( $run_status ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'SHOW TABLES' ) ) {
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
if ( false !== strpos( $sql, 'run_stages' ) ) {
|
||||
return 'wp_prautoblogger_run_stages';
|
||||
}
|
||||
return 'wp_prautoblogger_runs';
|
||||
}
|
||||
if ( false !== strpos( $sql, 'MAX(version)' ) ) {
|
||||
return null; // First fork version.
|
||||
}
|
||||
return null; // Lock free; no seed.
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturnCallback(
|
||||
static function ( $sql ) use ( $run_status ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return null; // No fork yet.
|
||||
}
|
||||
return array(
|
||||
'run_id' => 'run-1',
|
||||
'status' => $run_status,
|
||||
'ceiling_usd' => '0.50',
|
||||
);
|
||||
}
|
||||
);
|
||||
// resolve_base_body falls through to the gen_log query.
|
||||
$this->wpdb->method( 'get_results' )->willReturn(
|
||||
array(
|
||||
array(
|
||||
'id' => '11',
|
||||
'stage' => 'draft',
|
||||
'request_json' => '{"model":"m","messages":[{"role":"system","content":"sys"},{"role":"user","content":"orig"}]}',
|
||||
'response_status' => 'success',
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
236
tests/unit/Admin/DossierAssemblerRerunDataTest.php
Normal file
236
tests/unit/Admin/DossierAssemblerRerunDataTest.php
Normal file
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for the v0.20.0 dossier view-model additions (M3 + F2/F3).
|
||||
*
|
||||
* Locks: item-scoped stage filtering (multi-article runs no longer
|
||||
* collide), other-post gen_log row exclusion, per-stage rerun panel
|
||||
* data (policy reasons on non-editable stages; editable writer stage
|
||||
* with recorded input), log-only stage exposure (F3) and the spend
|
||||
* strip shape (guardrail 4 visibility).
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Admin
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Admin;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class DossierAssemblerRerunDataTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$this->wpdb->options = 'wp_options';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
Functions\when( 'get_post_thumbnail_id' )->justReturn( 0 );
|
||||
Functions\when( 'get_children' )->justReturn( array() );
|
||||
Functions\when( 'wp_get_attachment_image_url' )->justReturn( '' );
|
||||
Functions\when( 'apply_filters' )->returnArg( 2 );
|
||||
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Build the standard post + meta wiring. */
|
||||
private function wire_post(): void {
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 99;
|
||||
$post->post_title = 'Test Article';
|
||||
$post->post_status = 'draft';
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
Functions\when( 'get_post_meta' )->alias(
|
||||
static function ( $post_id, $key ) {
|
||||
$map = array(
|
||||
'_prautoblogger_run_id' => 'run-1',
|
||||
'_prautoblogger_idea_hash' => 'abc123',
|
||||
'_prautoblogger_editor_verdict' => 'approved',
|
||||
'_prautoblogger_article_type' => 'guide',
|
||||
);
|
||||
return $map[ $key ] ?? '';
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/** Wire wpdb for: tables exist, run row, stage rows, gen_log rows, lock free. */
|
||||
private function wire_data( array $stage_rows, array $log_rows ): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'SHOW TABLES' ) ) {
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
if ( false !== strpos( $sql, 'run_stages' ) ) {
|
||||
return 'wp_prautoblogger_run_stages';
|
||||
}
|
||||
return 'wp_prautoblogger_runs';
|
||||
}
|
||||
return null; // Lock free.
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
if ( false !== strpos( (string) $sql, 'stage_inputs' ) ) {
|
||||
return null; // No forks saved.
|
||||
}
|
||||
return array(
|
||||
'run_id' => 'run-1',
|
||||
'status' => 'done',
|
||||
'ceiling_usd' => '0.50',
|
||||
'settled_usd' => '0.30',
|
||||
'reserved_usd' => '0.15',
|
||||
);
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_results' )->willReturnCallback(
|
||||
static function ( $sql ) use ( $stage_rows, $log_rows ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'run_stages' ) ) {
|
||||
return $stage_rows;
|
||||
}
|
||||
if ( false !== strpos( $sql, 'generation_log' ) ) {
|
||||
return $log_rows;
|
||||
}
|
||||
return array(); // run_decisions.
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stage query is item-scoped (idea hash -> item_key IN (item, ''))
|
||||
* and gen_log rows belonging to OTHER posts are dropped while
|
||||
* unlinked (post_id NULL/0) rows are kept.
|
||||
*/
|
||||
public function test_item_scoping_and_other_post_log_exclusion(): void {
|
||||
$this->wire_post();
|
||||
$captured_stage_sql = null;
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
if ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) {
|
||||
return false !== strpos( (string) $sql, 'stage_inputs' ) ? 'wp_prautoblogger_stage_inputs'
|
||||
: ( false !== strpos( (string) $sql, 'run_stages' ) ? 'wp_prautoblogger_run_stages' : 'wp_prautoblogger_runs' );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturn( array( 'run_id' => 'run-1', 'status' => 'done', 'ceiling_usd' => '0' ) );
|
||||
$this->wpdb->method( 'get_results' )->willReturnCallback(
|
||||
static function ( $sql ) use ( &$captured_stage_sql ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'run_stages' ) ) {
|
||||
$captured_stage_sql = $sql;
|
||||
return array();
|
||||
}
|
||||
if ( false !== strpos( $sql, 'generation_log' ) ) {
|
||||
return array(
|
||||
array( 'id' => '1', 'stage' => 'draft', 'post_id' => '99', 'model' => 'm', 'request_json' => null ),
|
||||
array( 'id' => '2', 'stage' => 'draft', 'post_id' => '77', 'model' => 'm', 'request_json' => null ),
|
||||
array( 'id' => '3', 'stage' => 'llm_research', 'post_id' => null, 'model' => 'm', 'request_json' => null ),
|
||||
);
|
||||
}
|
||||
return array();
|
||||
}
|
||||
);
|
||||
|
||||
$dossier = ( new \PRAutoBlogger_Dossier_Data_Assembler() )->assemble( 99 );
|
||||
|
||||
$this->assertSame( 'idea:abc123', $dossier['item_key'] );
|
||||
$this->assertStringContainsString( "item_key IN (%s, '')", (string) $captured_stage_sql );
|
||||
// Post 77's draft row dropped; this post's row + unlinked research row kept.
|
||||
$this->assertCount( 1, $dossier['gen_log_index']['draft'] );
|
||||
$this->assertSame( '1', $dossier['gen_log_index']['draft'][0]['id'] );
|
||||
$this->assertCount( 1, $dossier['gen_log_index']['llm_research'] );
|
||||
// F3: llm_research has no run_stages row -> exposed as log-only.
|
||||
$this->assertContains( 'llm_research', $dossier['log_only_stages'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-stage rerun data: a writer stage with a recorded request is
|
||||
* editable with prefill; review carries a policy reason instead; the
|
||||
* spend strip reflects the ledger row (guardrail 4 visibility).
|
||||
*/
|
||||
public function test_stage_rerun_panel_data_and_spend(): void {
|
||||
$this->wire_post();
|
||||
$stage_rows = array(
|
||||
array(
|
||||
'id' => '1',
|
||||
'run_id' => 'run-1',
|
||||
'stage' => 'draft',
|
||||
'agent_role' => 'writer',
|
||||
'item_key' => 'idea:abc123',
|
||||
'status' => 'done',
|
||||
'attempt' => '1',
|
||||
'cost_usd' => '0.01',
|
||||
'meta_json' => '{"output":"text"}',
|
||||
'stale' => '0',
|
||||
'human_modified' => '1',
|
||||
),
|
||||
array(
|
||||
'id' => '2',
|
||||
'run_id' => 'run-1',
|
||||
'stage' => 'review',
|
||||
'agent_role' => 'editor',
|
||||
'item_key' => 'idea:abc123',
|
||||
'status' => 'done',
|
||||
'attempt' => '1',
|
||||
'cost_usd' => '0.005',
|
||||
'meta_json' => null,
|
||||
'stale' => '1',
|
||||
),
|
||||
);
|
||||
$log_rows = array(
|
||||
array(
|
||||
'id' => '10',
|
||||
'stage' => 'draft',
|
||||
'post_id' => '99',
|
||||
'model' => 'google/gemini-2.5-flash-lite',
|
||||
'request_json' => '{"model":"google/gemini-2.5-flash-lite","messages":[{"role":"user","content":"draft prompt"}]}',
|
||||
'response_status' => 'success',
|
||||
),
|
||||
);
|
||||
$this->wire_data( $stage_rows, $log_rows );
|
||||
|
||||
$dossier = ( new \PRAutoBlogger_Dossier_Data_Assembler() )->assemble( 99 );
|
||||
|
||||
$draft = $dossier['stages']['draft:writer']['rerun'];
|
||||
$this->assertTrue( $draft['editable'] );
|
||||
$this->assertSame( 'draft prompt', $draft['prefill']['messages'][0]['content'] );
|
||||
$this->assertTrue( $draft['human_modified'] );
|
||||
$this->assertTrue( $dossier['human_modified_any'] );
|
||||
|
||||
$review = $dossier['stages']['review:editor']['rerun'];
|
||||
$this->assertFalse( $review['editable'] );
|
||||
$this->assertStringContainsString( 'Re-run from here', $review['edit_reason'] );
|
||||
$this->assertTrue( $review['stale'] );
|
||||
$this->assertTrue( $review['rerun_from'] );
|
||||
$this->assertTrue( $dossier['stale_any'] );
|
||||
|
||||
$this->assertSame( 0.30, $dossier['spend']['settled'] );
|
||||
$this->assertSame( 0.15, $dossier['spend']['reserved'] );
|
||||
$this->assertSame( 0.50, $dossier['spend']['ceiling'] );
|
||||
$this->assertTrue( $dossier['spend']['warn'] ); // 0.45/0.50 = 90% >= 80%.
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,14 @@ class DossierDataAssemblerTest extends BaseTestCase {
|
||||
// Stub PRAutoBlogger_Run_Stage_State::is_available() to return true.
|
||||
// Static method -- stubbed via wpdb table check returning the table name.
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
|
||||
// v0.20.0 additions: image data + eligibility paths.
|
||||
Functions\when( 'get_post_thumbnail_id' )->justReturn( 0 );
|
||||
Functions\when( 'get_children' )->justReturn( array() );
|
||||
Functions\when( 'wp_get_attachment_image_url' )->justReturn( '' );
|
||||
Functions\when( 'apply_filters' )->returnArg( 2 );
|
||||
|
||||
// table_name returns wp_prautoblogger_run_stages.
|
||||
$this->wpdb->prefix = 'wp_';
|
||||
|
||||
@@ -51,6 +51,11 @@ abstract class DossierMenuRegistrationTestCase extends BaseTestCase {
|
||||
$this->captured_menu_slug = null;
|
||||
$this->registration_hookname = null;
|
||||
|
||||
// v0.20.0: the dossier enqueue path localizes the edit/re-run config.
|
||||
Functions\when( 'wp_localize_script' )->justReturn( true );
|
||||
Functions\when( 'wp_create_nonce' )->justReturn( 'test-nonce' );
|
||||
Functions\when( 'absint' )->alias( static function ( $val ) { return abs( (int) $val ); } );
|
||||
|
||||
// Spy stub: tracks call order, captures slugs, returns a hookname that
|
||||
// reflects how WordPress actually resolves it for known parents.
|
||||
Functions\when( 'add_menu_page' )->alias(
|
||||
|
||||
@@ -147,7 +147,7 @@ abstract class BaseTestCase extends TestCase {
|
||||
*/
|
||||
protected function create_mock_wpdb() {
|
||||
$wpdb = $this->getMockBuilder( \stdClass::class )
|
||||
->addMethods( [ 'prepare', 'get_var', 'get_results', 'insert', 'query', 'get_row', 'update' ] )
|
||||
->addMethods( [ 'prepare', 'get_var', 'get_results', 'insert', 'query', 'get_row', 'get_col', 'update' ] )
|
||||
->getMock();
|
||||
|
||||
$wpdb->prefix = 'wp_';
|
||||
|
||||
181
tests/unit/Core/CostTrackerRequestJsonTest.php
Normal file
181
tests/unit/Core/CostTrackerRequestJsonTest.php
Normal file
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for the v0.20.0 (B1) request_json persistence in
|
||||
* PRAutoBlogger_Cost_Tracker::log_api_call().
|
||||
*
|
||||
* Every chat call's request body must land on its generation_log row
|
||||
* (stage inputs exist for edit + re-run; the dossier raw-input trace is
|
||||
* no longer hollow — QA M2 F1), with consume-once isolation between rows.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class CostTrackerRequestJsonTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb instance.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* Rows captured from $wpdb->insert().
|
||||
*
|
||||
* @var array<int, array<string, mixed>>
|
||||
*/
|
||||
private array $inserted = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->inserted = array();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->insert_id = 7;
|
||||
$this->wpdb->method( 'insert' )->willReturnCallback(
|
||||
function ( $table, $row ) {
|
||||
// Capture generation_log rows only — the Logger also
|
||||
// inserts (event_log) when e.g. Pricing warns on an
|
||||
// unknown model; those rows are not under test.
|
||||
if ( false !== strpos( (string) $table, 'generation_log' ) ) {
|
||||
$this->inserted[] = (array) $row;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
$this->stub_get_option( array() );
|
||||
\PRAutoBlogger_Request_Recorder::clear();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Request_Recorder::clear();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* log_api_call() persists the recorder stash into request_json.
|
||||
*/
|
||||
public function test_log_api_call_persists_recorded_request_json(): void {
|
||||
\PRAutoBlogger_Request_Recorder::record(
|
||||
array(
|
||||
'model' => 'google/gemini-2.5-flash-lite',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'draft prompt' ) ),
|
||||
)
|
||||
);
|
||||
|
||||
( new \PRAutoBlogger_Cost_Tracker() )->log_api_call(
|
||||
null,
|
||||
'draft',
|
||||
'OpenRouter',
|
||||
'google/gemini-2.5-flash-lite',
|
||||
100,
|
||||
500
|
||||
);
|
||||
|
||||
$this->assertCount( 1, $this->inserted );
|
||||
$row = $this->inserted[0];
|
||||
$this->assertArrayHasKey( 'request_json', $row );
|
||||
$decoded = json_decode( (string) $row['request_json'], true );
|
||||
$this->assertSame( 'draft prompt', $decoded['messages'][0]['content'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume-once isolation: a second log row written with no new send
|
||||
* in between must get NULL, never the previous call's body.
|
||||
*/
|
||||
public function test_second_log_row_without_new_record_gets_null(): void {
|
||||
\PRAutoBlogger_Request_Recorder::record( array( 'model' => 'm1' ) );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$tracker->log_api_call( null, 'draft', 'OpenRouter', 'm1', 10, 10 );
|
||||
$tracker->log_api_call( null, 'polish', 'OpenRouter', 'm1', 10, 10 );
|
||||
|
||||
$this->assertCount( 2, $this->inserted );
|
||||
$this->assertNotNull( $this->inserted[0]['request_json'] );
|
||||
$this->assertNull( $this->inserted[1]['request_json'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Historical behavior preserved: nothing recorded -> request_json NULL.
|
||||
*/
|
||||
public function test_log_api_call_without_stash_writes_null(): void {
|
||||
( new \PRAutoBlogger_Cost_Tracker() )->log_api_call(
|
||||
null,
|
||||
'analysis',
|
||||
'OpenRouter',
|
||||
'google/gemini-2.5-flash-lite',
|
||||
10,
|
||||
10
|
||||
);
|
||||
|
||||
$this->assertCount( 1, $this->inserted );
|
||||
$this->assertNull( $this->inserted[0]['request_json'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* The persisted payload can never contain credential material — the
|
||||
* provider records only build_body() output (headers are separate).
|
||||
* Belt-and-braces audit on the exact column value.
|
||||
*/
|
||||
public function test_persisted_request_json_contains_no_auth_header(): void {
|
||||
$this->stub_get_option( array() );
|
||||
$builder = new \PRAutoBlogger_OpenRouter_Request_Builder();
|
||||
\PRAutoBlogger_Request_Recorder::record(
|
||||
$builder->build_body(
|
||||
array( array( 'role' => 'user', 'content' => 'x' ) ),
|
||||
'google/gemini-2.5-flash-lite',
|
||||
array( 'max_tokens' => 100 )
|
||||
)
|
||||
);
|
||||
|
||||
( new \PRAutoBlogger_Cost_Tracker() )->log_api_call(
|
||||
null,
|
||||
'draft',
|
||||
'OpenRouter',
|
||||
'google/gemini-2.5-flash-lite',
|
||||
10,
|
||||
10
|
||||
);
|
||||
|
||||
$json = (string) $this->inserted[0]['request_json'];
|
||||
$this->assertStringNotContainsString( 'Authorization', $json );
|
||||
$this->assertStringNotContainsString( 'Bearer', $json );
|
||||
$this->assertStringNotContainsString( 'sk-or-', $json );
|
||||
}
|
||||
|
||||
/**
|
||||
* The half-migrated-schema legacy retry (v0.18.0 pattern) keeps
|
||||
* request_json — the column predates the audit columns (v1.1.0
|
||||
* schema) and exists on every site.
|
||||
*/
|
||||
public function test_legacy_schema_retry_keeps_request_json(): void {
|
||||
$this->inserted = array();
|
||||
$wpdb = $this->create_mock_wpdb();
|
||||
$wpdb->insert_id = 7;
|
||||
$calls = 0;
|
||||
$wpdb->method( 'insert' )->willReturnCallback(
|
||||
function ( $table, $row ) use ( &$calls ) {
|
||||
if ( false === strpos( (string) $table, 'generation_log' ) ) {
|
||||
return 1; // Logger/event_log noise — not under test.
|
||||
}
|
||||
++$calls;
|
||||
$this->inserted[] = (array) $row;
|
||||
return 1 === $calls ? false : 1; // First insert fails (missing v0.18.0 columns).
|
||||
}
|
||||
);
|
||||
$GLOBALS['wpdb'] = $wpdb;
|
||||
|
||||
\PRAutoBlogger_Request_Recorder::record( array( 'model' => 'm1' ) );
|
||||
( new \PRAutoBlogger_Cost_Tracker() )->log_api_call( null, 'draft', 'OpenRouter', 'm1', 10, 10 );
|
||||
|
||||
$this->assertCount( 2, $this->inserted );
|
||||
$retry_row = $this->inserted[1];
|
||||
$this->assertArrayNotHasKey( 'agent_role', $retry_row );
|
||||
$this->assertArrayNotHasKey( 'prompt_version', $retry_row );
|
||||
$this->assertArrayHasKey( 'request_json', $retry_row );
|
||||
$this->assertNotNull( $retry_row['request_json'] );
|
||||
}
|
||||
}
|
||||
134
tests/unit/Core/PublisherRerunUpdateTest.php
Normal file
134
tests/unit/Core/PublisherRerunUpdateTest.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for the v0.20.0 Publisher refresh-unpublished behavior.
|
||||
*
|
||||
* A re-run's regenerated content must land on the existing UNPUBLISHED
|
||||
* post (idempotency previously skip-returned and silently discarded
|
||||
* re-run output); published posts remain frozen and untouched (CPO
|
||||
* guardrail 5 enforced at the data layer).
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class PublisherRerunUpdateTest extends BaseTestCase {
|
||||
|
||||
private \PRAutoBlogger_Article_Idea $idea;
|
||||
private \PRAutoBlogger_Editorial_Review $review;
|
||||
|
||||
/**
|
||||
* Args captured from wp_update_post().
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
private $updated_args = null;
|
||||
|
||||
/**
|
||||
* Meta captured from update_post_meta().
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $updated_meta = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->idea = new \PRAutoBlogger_Article_Idea( $this->get_article_idea_fixture() );
|
||||
$this->review = new \PRAutoBlogger_Editorial_Review( $this->get_editorial_review_fixture() );
|
||||
|
||||
$this->stub_get_option( array() );
|
||||
Functions\when( 'sanitize_text_field' )->returnArg();
|
||||
Functions\when( 'wp_kses_post' )->returnArg();
|
||||
Functions\when( 'wp_strip_all_tags' )->alias(
|
||||
static function ( $text ) {
|
||||
return trim( strip_tags( (string) $text ) );
|
||||
}
|
||||
);
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
Functions\when( 'apply_filters' )->returnArg( 2 );
|
||||
|
||||
$this->updated_args = null;
|
||||
$this->updated_meta = array();
|
||||
Functions\when( 'wp_update_post' )->alias(
|
||||
function ( $args ) {
|
||||
$this->updated_args = (array) $args;
|
||||
return $args['ID'] ?? 0;
|
||||
}
|
||||
);
|
||||
Functions\when( 'update_post_meta' )->alias(
|
||||
function ( $post_id, $key, $value ) {
|
||||
$this->updated_meta[ (string) $key ] = $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
// find_existing_post() resolves post 55 for this (run, idea).
|
||||
$wpdb = $this->create_mock_wpdb();
|
||||
$wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||
$wpdb->method( 'get_var' )->willReturn( '55' );
|
||||
$GLOBALS['wpdb'] = $wpdb;
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Stub get_post for post 55 with a status. */
|
||||
private function stub_existing_post( string $status ): void {
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 55;
|
||||
$post->post_status = $status;
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-run output refreshes the existing draft: content + title are
|
||||
* updated, verdict meta refreshed — and the post status is NEVER
|
||||
* touched (a re-run must not publish; publication stays an explicit
|
||||
* operator action).
|
||||
*/
|
||||
public function test_rerun_refreshes_existing_draft_without_status_change(): void {
|
||||
$this->stub_existing_post( 'draft' );
|
||||
Functions\when( 'wp_insert_post' )->alias(
|
||||
static function () {
|
||||
throw new \RuntimeException( 'wp_insert_post must not be called for an existing post' );
|
||||
}
|
||||
);
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$post_id = $publisher->save_as_draft( '<p>Regenerated content</p>', $this->idea, $this->review, 'run-1' );
|
||||
|
||||
$this->assertSame( 55, $post_id );
|
||||
$this->assertIsArray( $this->updated_args );
|
||||
$this->assertSame( 55, $this->updated_args['ID'] );
|
||||
$this->assertStringContainsString( 'Regenerated content', (string) $this->updated_args['post_content'] );
|
||||
$this->assertArrayNotHasKey( 'post_status', $this->updated_args );
|
||||
$this->assertSame( $this->review->get_verdict(), $this->updated_meta['_prautoblogger_editor_verdict'] );
|
||||
$this->assertArrayHasKey( '_prautoblogger_generated_at', $this->updated_meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Published post: frozen — returned untouched, no wp_update_post, no
|
||||
* meta writes, no duplicate insert (guardrail 5 at the data layer).
|
||||
*/
|
||||
public function test_published_post_is_never_updated(): void {
|
||||
$this->stub_existing_post( 'publish' );
|
||||
Functions\when( 'wp_insert_post' )->alias(
|
||||
static function () {
|
||||
throw new \RuntimeException( 'wp_insert_post must not be called for an existing post' );
|
||||
}
|
||||
);
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$post_id = $publisher->save_as_draft( '<p>Regenerated content</p>', $this->idea, $this->review, 'run-1' );
|
||||
|
||||
$this->assertSame( 55, $post_id );
|
||||
$this->assertNull( $this->updated_args );
|
||||
$this->assertSame( array(), $this->updated_meta );
|
||||
}
|
||||
}
|
||||
120
tests/unit/Core/RequestRecorderTest.php
Normal file
120
tests/unit/Core/RequestRecorderTest.php
Normal file
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Request_Recorder (v0.20.0 / B1).
|
||||
*
|
||||
* Locks the consume-once + overwrite-on-record semantics that make it
|
||||
* impossible for a stale request body to attach to an unrelated log row,
|
||||
* and the no-Authorization guarantee of the record path.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class RequestRecorderTest extends BaseTestCase {
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
\PRAutoBlogger_Request_Recorder::clear();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Request_Recorder::clear();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* consume() returns the recorded body exactly once, then null.
|
||||
*/
|
||||
public function test_consume_returns_recorded_body_exactly_once(): void {
|
||||
\PRAutoBlogger_Request_Recorder::record(
|
||||
array(
|
||||
'model' => 'google/gemini-2.5-flash-lite',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'hi' ) ),
|
||||
)
|
||||
);
|
||||
|
||||
$first = \PRAutoBlogger_Request_Recorder::consume();
|
||||
$this->assertIsString( $first );
|
||||
$decoded = json_decode( $first, true );
|
||||
$this->assertSame( 'google/gemini-2.5-flash-lite', $decoded['model'] );
|
||||
$this->assertSame( 'hi', $decoded['messages'][0]['content'] );
|
||||
|
||||
// Consume-once: the slot is cleared by the first read.
|
||||
$this->assertNull( \PRAutoBlogger_Request_Recorder::consume() );
|
||||
}
|
||||
|
||||
/**
|
||||
* record() overwrites the previous stash — a stale body from an
|
||||
* unlogged earlier call can never survive into the next dispatch.
|
||||
*/
|
||||
public function test_record_overwrites_previous_stash(): void {
|
||||
\PRAutoBlogger_Request_Recorder::record( array( 'model' => 'first/model' ) );
|
||||
\PRAutoBlogger_Request_Recorder::record( array( 'model' => 'second/model' ) );
|
||||
|
||||
$decoded = json_decode( (string) \PRAutoBlogger_Request_Recorder::consume(), true );
|
||||
$this->assertSame( 'second/model', $decoded['model'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* consume() with nothing recorded returns null (historical rows /
|
||||
* non-chat log writes keep request_json NULL).
|
||||
*/
|
||||
public function test_consume_without_record_returns_null(): void {
|
||||
$this->assertNull( \PRAutoBlogger_Request_Recorder::consume() );
|
||||
}
|
||||
|
||||
/**
|
||||
* clear() empties the slot.
|
||||
*/
|
||||
public function test_clear_empties_slot(): void {
|
||||
\PRAutoBlogger_Request_Recorder::record( array( 'model' => 'm' ) );
|
||||
\PRAutoBlogger_Request_Recorder::clear();
|
||||
$this->assertNull( \PRAutoBlogger_Request_Recorder::consume() );
|
||||
}
|
||||
|
||||
/**
|
||||
* The full record path for a body built by the real Request_Builder
|
||||
* from poisoned options can never contain credential material:
|
||||
* build_body() copies only whitelisted keys and headers are built
|
||||
* separately, so the recorder's JSON has no Authorization shape.
|
||||
*/
|
||||
public function test_recorded_builder_body_never_contains_auth_material(): void {
|
||||
$this->stub_get_option( array() );
|
||||
|
||||
$builder = new \PRAutoBlogger_OpenRouter_Request_Builder();
|
||||
$body = $builder->build_body(
|
||||
array( array( 'role' => 'user', 'content' => 'write about BPC-157' ) ),
|
||||
'google/gemini-2.5-flash-lite',
|
||||
array(
|
||||
'temperature' => 0.7,
|
||||
'max_tokens' => 4000,
|
||||
// Hostile/accidental injection attempts — must all be dropped.
|
||||
'Authorization' => 'Bearer sk-or-secret-key-123',
|
||||
'headers' => array( 'Authorization' => 'Bearer sk-or-secret-key-123' ),
|
||||
'api_key' => 'sk-or-secret-key-123',
|
||||
// Caller metadata — never sent upstream, never recorded.
|
||||
'stage' => 'draft',
|
||||
'prompt_key' => 'content.draft',
|
||||
'empty_retry' => true,
|
||||
)
|
||||
);
|
||||
\PRAutoBlogger_Request_Recorder::record( $body );
|
||||
|
||||
$json = (string) \PRAutoBlogger_Request_Recorder::consume();
|
||||
$this->assertStringNotContainsString( 'Authorization', $json );
|
||||
$this->assertStringNotContainsString( 'Bearer', $json );
|
||||
$this->assertStringNotContainsString( 'sk-or-', $json );
|
||||
$this->assertStringNotContainsString( 'api_key', $json );
|
||||
$this->assertStringNotContainsString( 'empty_retry', $json );
|
||||
$this->assertStringNotContainsString( 'prompt_key', $json );
|
||||
|
||||
$decoded = json_decode( $json, true );
|
||||
$this->assertSame(
|
||||
array( 'model', 'messages', 'temperature', 'max_tokens' ),
|
||||
array_keys( $decoded )
|
||||
);
|
||||
}
|
||||
}
|
||||
182
tests/unit/Core/RerunEligibilityTest.php
Normal file
182
tests/unit/Core/RerunEligibilityTest.php
Normal file
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Rerun_Eligibility (v0.20.0, M3).
|
||||
*
|
||||
* Locks the published-post lockout (CPO guardrail 5 incl. future/private),
|
||||
* the actively-executing-run block, the editable-stage policy, and the
|
||||
* downstream/rebuild set computation that drives stale marking.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class RerunEligibilityTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$this->wpdb->options = 'wp_options';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', array_filter( $args, 'is_scalar' ) ) ) . ' */';
|
||||
}
|
||||
);
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the mock for: runs table exists, run row with given status,
|
||||
* generation lock free.
|
||||
*/
|
||||
private function wire_run( string $run_status ): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'SHOW TABLES' ) ) {
|
||||
// Both runs + stage_inputs probes succeed.
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
return 'wp_prautoblogger_runs';
|
||||
}
|
||||
return null; // Lock option absent -> lock free; seed absent.
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_row' )->willReturn(
|
||||
array(
|
||||
'run_id' => 'run-1',
|
||||
'status' => $run_status,
|
||||
'ceiling_usd' => '0.50',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Stub get_post to return a post with the given status. */
|
||||
private function stub_post( string $status ): void {
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 99;
|
||||
$post->post_status = $status;
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
}
|
||||
|
||||
/**
|
||||
* Published, scheduled, and private posts are all frozen — no
|
||||
* edit+rerun (CPO guardrail 5). Draft and pending are not.
|
||||
*/
|
||||
public function test_published_post_lockout_covers_all_frozen_statuses(): void {
|
||||
foreach ( array( 'publish', 'future', 'private' ) as $frozen ) {
|
||||
$post = new \WP_Post();
|
||||
$post->post_status = $frozen;
|
||||
$this->assertTrue( \PRAutoBlogger_Rerun_Eligibility::post_frozen( $post ), "status {$frozen} must freeze" );
|
||||
}
|
||||
foreach ( array( 'draft', 'pending' ) as $open ) {
|
||||
$post = new \WP_Post();
|
||||
$post->post_status = $open;
|
||||
$this->assertFalse( \PRAutoBlogger_Rerun_Eligibility::post_frozen( $post ), "status {$open} must not freeze" );
|
||||
}
|
||||
// A run with no post yet is not frozen.
|
||||
$this->assertFalse( \PRAutoBlogger_Rerun_Eligibility::post_frozen( null ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* check() rejects a published post with the WP-editor redirect copy
|
||||
* (server-side enforcement, not just hidden UI).
|
||||
*/
|
||||
public function test_check_rejects_published_post(): void {
|
||||
$this->wire_run( 'done' );
|
||||
$this->stub_post( 'publish' );
|
||||
|
||||
$verdict = \PRAutoBlogger_Rerun_Eligibility::check( 'run-1', 99 );
|
||||
|
||||
$this->assertFalse( $verdict['ok'] );
|
||||
$this->assertStringContainsString( 'published', $verdict['reason'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* check() rejects an actively executing run — "in progress" in the
|
||||
* CPO sense means unpublished workflow state, not mid-execution.
|
||||
*/
|
||||
public function test_check_rejects_actively_executing_run(): void {
|
||||
$this->wire_run( 'running' );
|
||||
$this->stub_post( 'draft' );
|
||||
|
||||
$verdict = \PRAutoBlogger_Rerun_Eligibility::check( 'run-1', 99 );
|
||||
|
||||
$this->assertFalse( $verdict['ok'] );
|
||||
$this->assertStringContainsString( 'currently executing', $verdict['reason'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* A terminal run on an unpublished post is eligible: done, failed
|
||||
* and halted (held) runs can all be re-run.
|
||||
*/
|
||||
public function test_check_accepts_terminal_runs_on_unpublished_posts(): void {
|
||||
foreach ( array( 'done', 'failed', 'halted' ) as $status ) {
|
||||
$wpdb = $this->create_mock_wpdb();
|
||||
$wpdb->options = 'wp_options';
|
||||
$wpdb->method( 'prepare' )->willReturnCallback( static fn( $sql, ...$a ) => (string) $sql );
|
||||
$wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
return ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) ? 'wp_prautoblogger_runs' : null;
|
||||
}
|
||||
);
|
||||
$wpdb->method( 'get_row' )->willReturn( array( 'status' => $status ) );
|
||||
$GLOBALS['wpdb'] = $wpdb;
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
$this->stub_post( 'draft' );
|
||||
|
||||
$verdict = \PRAutoBlogger_Rerun_Eligibility::check( 'run-1', 99 );
|
||||
$this->assertTrue( $verdict['ok'], "run status {$status} must be eligible: {$verdict['reason']}" );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Editable-stage policy: writer chat stages only. review/analysis/
|
||||
* image stages get the replay affordance refused at the policy layer.
|
||||
*/
|
||||
public function test_editable_stage_policy(): void {
|
||||
foreach ( array( 'outline', 'draft', 'polish' ) as $stage ) {
|
||||
$this->assertTrue( \PRAutoBlogger_Rerun_Eligibility::is_editable_stage( $stage ) );
|
||||
}
|
||||
foreach ( array( 'review', 'publish', 'analysis', 'research', 'llm_research', 'image_a', 'image_b', 'curate' ) as $stage ) {
|
||||
$this->assertFalse( \PRAutoBlogger_Rerun_Eligibility::is_editable_stage( $stage ) );
|
||||
}
|
||||
|
||||
$verdict = \PRAutoBlogger_Rerun_Eligibility::check_replay( 'run-1', 99, 'review', 'editor', 'idea:abc' );
|
||||
$this->assertFalse( $verdict['ok'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Downstream/rebuild sets follow the canonical chain — these sets
|
||||
* drive stale marking and demotion, so order and bounds matter.
|
||||
*/
|
||||
public function test_downstream_and_rebuild_sets(): void {
|
||||
$this->assertSame( array( 'polish', 'review', 'publish' ), \PRAutoBlogger_Rerun_Eligibility::downstream_of( 'draft' ) );
|
||||
$this->assertSame( array( 'publish' ), \PRAutoBlogger_Rerun_Eligibility::downstream_of( 'review' ) );
|
||||
$this->assertSame( array(), \PRAutoBlogger_Rerun_Eligibility::downstream_of( 'publish' ) );
|
||||
$this->assertSame( array(), \PRAutoBlogger_Rerun_Eligibility::downstream_of( 'image_a' ) );
|
||||
$this->assertSame( array( 'review', 'publish' ), \PRAutoBlogger_Rerun_Eligibility::rebuild_set( 'review' ) );
|
||||
$this->assertSame(
|
||||
array( 'outline', 'draft', 'polish', 'review', 'publish' ),
|
||||
\PRAutoBlogger_Rerun_Eligibility::rebuild_set( 'outline' )
|
||||
);
|
||||
}
|
||||
}
|
||||
217
tests/unit/Core/RerunExecutorTest.php
Normal file
217
tests/unit/Core/RerunExecutorTest.php
Normal file
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Rerun_Executor + Job_Support (v0.20.0, M3).
|
||||
*
|
||||
* Locks the chained-cron contract (queue() schedules + writes the
|
||||
* queued transient — nothing executes synchronously), the under-lock
|
||||
* re-validation (a post published between click and pickup aborts the
|
||||
* job with ZERO stage mutations), and the terminal-status restore when
|
||||
* the stage demotion fails after the run was reopened.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class RerunExecutorTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* SQL captured from $wpdb->query().
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private array $queries = array();
|
||||
|
||||
/**
|
||||
* Transients captured from set_transient().
|
||||
*
|
||||
* @var array<int, array>
|
||||
*/
|
||||
private array $transients = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->queries = array();
|
||||
$this->transients = array();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$this->wpdb->options = 'wp_options';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
Functions\when( 'set_transient' )->alias(
|
||||
function ( $key, $value, $ttl = 0 ) {
|
||||
$this->transients[] = (array) $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
// Monthly budget 0 = no limit (fast false path).
|
||||
$this->stub_get_option( array( 'prautoblogger_monthly_budget_usd' => '0' ) );
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** SHOW TABLES probes succeed for every substrate table. */
|
||||
private function tables_exist(): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'SHOW TABLES' ) ) {
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
if ( false !== strpos( $sql, 'run_stages' ) ) {
|
||||
return 'wp_prautoblogger_run_stages';
|
||||
}
|
||||
return 'wp_prautoblogger_runs';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* queue() never executes anything: it schedules a single cron event
|
||||
* with a uniqueness token appended and broadcasts a 'running' status
|
||||
* transient so board/dossier polling shows the queued state
|
||||
* (chained-cron semantics — the CPO hard constraint).
|
||||
*/
|
||||
public function test_queue_schedules_cron_and_broadcasts_queued_state(): void {
|
||||
$scheduled = null;
|
||||
Functions\when( 'wp_schedule_single_event' )->alias(
|
||||
static function ( $ts, $hook, $args ) use ( &$scheduled ) {
|
||||
$scheduled = array(
|
||||
'hook' => $hook,
|
||||
'args' => $args,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
Functions\when( 'spawn_cron' )->justReturn( true );
|
||||
Functions\when( 'wp_remote_post' )->justReturn( array() );
|
||||
Functions\when( 'site_url' )->justReturn( 'https://example.com' );
|
||||
|
||||
\PRAutoBlogger_Rerun_Job_Support::queue(
|
||||
\PRAutoBlogger_Rerun_Executor::REPLAY_ACTION,
|
||||
array( 'run-1', 99, 'draft', 'writer', 'idea:abc' ),
|
||||
'Queued: re-running Draft…'
|
||||
);
|
||||
|
||||
$this->assertSame( \PRAutoBlogger_Rerun_Executor::REPLAY_ACTION, $scheduled['hook'] );
|
||||
$this->assertCount( 6, $scheduled['args'] ); // 5 args + uniqueness token.
|
||||
$this->assertSame( 'run-1', $scheduled['args'][0] );
|
||||
$this->assertCount( 1, $this->transients );
|
||||
$this->assertSame( 'running', $this->transients[0]['status'] );
|
||||
$this->assertSame( 'Queued: re-running Draft…', $this->transients[0]['stage'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Under-lock re-validation: a post published between click and cron
|
||||
* pickup aborts the replay with an error transient and ZERO
|
||||
* run_stages mutations (guardrail 5 cannot be raced).
|
||||
*/
|
||||
public function test_replay_job_aborts_on_frozen_post_without_mutations(): void {
|
||||
$this->tables_exist();
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1; // Lock cleanup + acquire succeed.
|
||||
}
|
||||
);
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 99;
|
||||
$post->post_status = 'publish';
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
|
||||
( new \PRAutoBlogger_Rerun_Executor() )->on_replay_job( 'run-1', 99, 'draft', 'writer', 'idea:abc' );
|
||||
|
||||
foreach ( $this->queries as $sql ) {
|
||||
$this->assertStringNotContainsString( 'run_stages', $sql, 'no stage mutation may happen on a frozen post' );
|
||||
$this->assertStringNotContainsString( 'run_id = %s AND status IN', $sql, 'the run must not be reopened' );
|
||||
}
|
||||
$last = end( $this->transients );
|
||||
$this->assertSame( 'error', $last['status'] );
|
||||
$this->assertStringContainsString( 'published', $last['message'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* When the stage demotion fails after the run was reopened (e.g. the
|
||||
* row is concurrently 'running'), the previous terminal status is
|
||||
* restored — the run cannot be left dangling in 'running' for the
|
||||
* reaper to misread.
|
||||
*/
|
||||
public function test_replay_job_restores_terminal_status_when_restart_fails(): void {
|
||||
$this->tables_exist();
|
||||
$this->wpdb->method( 'get_row' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
$sql = (string) $sql;
|
||||
if ( false !== strpos( $sql, 'stage_inputs' ) ) {
|
||||
return array(
|
||||
'version' => '2',
|
||||
'request_json' => '{"model":"m","messages":[{"role":"user","content":"edited"}]}',
|
||||
);
|
||||
}
|
||||
return array(
|
||||
'run_id' => 'run-1',
|
||||
'status' => 'done',
|
||||
'ceiling_usd' => '0.50',
|
||||
);
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$sql = (string) $sql;
|
||||
$this->queries[] = $sql;
|
||||
if ( false !== strpos( $sql, 'attempt = attempt + 1' ) ) {
|
||||
return 0; // restart() fails — row not demotable.
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
$post = new \WP_Post();
|
||||
$post->ID = 99;
|
||||
$post->post_status = 'draft';
|
||||
Functions\when( 'get_post' )->justReturn( $post );
|
||||
|
||||
( new \PRAutoBlogger_Rerun_Executor() )->on_replay_job( 'run-1', 99, 'draft', 'writer', 'idea:abc' );
|
||||
|
||||
$reopened = false;
|
||||
$restored = false;
|
||||
foreach ( $this->queries as $sql ) {
|
||||
if ( false !== strpos( $sql, "ceiling_usd = %f" ) ) {
|
||||
$reopened = true;
|
||||
}
|
||||
// restore_terminal -> mark_status('done') over the reopened 'running' row.
|
||||
if ( false !== strpos( $sql, 'SET status = %s' ) && false !== strpos( $sql, 'done' )
|
||||
&& false !== strpos( $sql, "status IN ('pending','running')" ) ) {
|
||||
$restored = true;
|
||||
}
|
||||
}
|
||||
$this->assertTrue( $reopened, 'run must have been reopened before restart' );
|
||||
$this->assertTrue( $restored, 'terminal status must be restored after the aborted demotion' );
|
||||
$last = end( $this->transients );
|
||||
$this->assertSame( 'error', $last['status'] );
|
||||
}
|
||||
}
|
||||
185
tests/unit/Core/RunStageRerunStateTest.php
Normal file
185
tests/unit/Core/RunStageRerunStateTest.php
Normal file
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Run_Stage_Writes (M3 done() delta) and
|
||||
* PRAutoBlogger_Run_Stage_Rerun_State (operator-action mutations).
|
||||
*
|
||||
* Locks: fresh done() clears stale but never touches human_modified;
|
||||
* the half-migrated-schema self-heal retry; restart() demotion rules
|
||||
* (never from 'running', human_modified is sticky); mark_stale() flags
|
||||
* only 'done' rows; demote_to_pending() preserves audit columns.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class RunStageRerunStateTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* SQL captured from $wpdb->query().
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private array $queries = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->queries = array();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_run_stages' );
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_Stage_State::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Capture queries, all succeeding. */
|
||||
private function capture_queries(): void {
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* done() writes stale = 0 on both INSERT and duplicate-key paths and
|
||||
* never references human_modified (sticky audit — set only by
|
||||
* Rerun_State::restart()).
|
||||
*/
|
||||
public function test_done_clears_stale_and_never_touches_human_modified(): void {
|
||||
$this->capture_queries();
|
||||
|
||||
\PRAutoBlogger_Run_Stage_State::done( 'run-1', 'draft', '', 'idea:abc', 'output text', 0.01 );
|
||||
|
||||
$this->assertCount( 1, $this->queries );
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( 'stale', $sql );
|
||||
$this->assertStringContainsString( 'stale = 0', $sql );
|
||||
$this->assertStringNotContainsString( 'human_modified', $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Half-migrated schema (no stale column yet): the failed write is
|
||||
* retried with the pre-v0.20.0 statement — the resume checkpoint is
|
||||
* never lost (Cost_Tracker v0.18.0 retry pattern).
|
||||
*/
|
||||
public function test_done_self_heals_on_missing_stale_column(): void {
|
||||
$calls = 0;
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) use ( &$calls ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
++$calls;
|
||||
return 1 === $calls ? false : 1; // First write fails (unknown column).
|
||||
}
|
||||
);
|
||||
|
||||
\PRAutoBlogger_Run_Stage_State::done( 'run-1', 'draft', '', 'idea:abc', 'output', 0.01 );
|
||||
|
||||
$this->assertCount( 2, $this->queries );
|
||||
$this->assertStringContainsString( 'stale', $this->queries[0] );
|
||||
$this->assertStringNotContainsString( 'stale', $this->queries[1] );
|
||||
$this->assertStringContainsString( "status = 'done'", $this->queries[1] );
|
||||
}
|
||||
|
||||
/**
|
||||
* restart() demotes terminal/pending rows only — a 'running' row can
|
||||
* never be restarted (the WHERE excludes it), the attempt counter is
|
||||
* bumped, stale clears, and human_modified can only be raised
|
||||
* (IF(...,1,human_modified)), never reset.
|
||||
*/
|
||||
public function test_restart_rules(): void {
|
||||
$this->capture_queries();
|
||||
|
||||
$ok = \PRAutoBlogger_Run_Stage_Rerun_State::restart( 'run-1', 'draft', 'writer', 'idea:abc', true );
|
||||
|
||||
$this->assertTrue( $ok );
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( "status = 'running'", $sql );
|
||||
$this->assertStringContainsString( 'attempt = attempt + 1', $sql );
|
||||
$this->assertStringContainsString( 'stale = 0', $sql );
|
||||
$this->assertStringContainsString( 'IF(%d = 1, 1, human_modified)', $sql );
|
||||
$this->assertStringContainsString( "IN ('done','failed','halted','pending')", $sql );
|
||||
$this->assertStringNotContainsString( "'running')", str_replace( "status = 'running'", '', $sql ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* restart() reports false when no row matched (e.g. concurrently
|
||||
* running stage) so the executor can abort cleanly.
|
||||
*/
|
||||
public function test_restart_returns_false_when_no_row_demoted(): void {
|
||||
$this->wpdb->method( 'query' )->willReturn( 0 );
|
||||
|
||||
$this->assertFalse(
|
||||
\PRAutoBlogger_Run_Stage_Rerun_State::restart( 'run-1', 'draft', 'writer', 'idea:abc', false )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* mark_stale() flags only 'done' rows of the given stages — pending/
|
||||
* failed rows are not "stale", they are simply not run. Nothing is
|
||||
* demoted (no status write): guardrail 3's no-silent-auto-rerun holds
|
||||
* by construction.
|
||||
*/
|
||||
public function test_mark_stale_targets_done_rows_only_and_never_demotes(): void {
|
||||
$this->capture_queries();
|
||||
|
||||
$count = \PRAutoBlogger_Run_Stage_Rerun_State::mark_stale( 'run-1', 'idea:abc', array( 'polish', 'review', 'publish' ) );
|
||||
|
||||
$this->assertSame( 1, $count );
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( 'SET stale = 1', $sql );
|
||||
$this->assertStringContainsString( "status = 'done'", $sql );
|
||||
$this->assertStringContainsString( 'IN (%s,%s,%s)', $sql );
|
||||
$this->assertStringNotContainsString( "SET status", $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* demote_to_pending() sets pending+stale, keeps meta_json/attempt/
|
||||
* human_modified untouched (audit survives), and never touches a
|
||||
* 'running' row.
|
||||
*/
|
||||
public function test_demote_to_pending_preserves_audit_columns(): void {
|
||||
$this->capture_queries();
|
||||
|
||||
\PRAutoBlogger_Run_Stage_Rerun_State::demote_to_pending( 'run-1', 'idea:abc', array( 'review', 'publish' ) );
|
||||
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( "SET status = 'pending', stale = 1", $sql );
|
||||
$this->assertStringContainsString( "status != 'running'", $sql );
|
||||
$this->assertStringNotContainsString( 'meta_json', $sql );
|
||||
$this->assertStringNotContainsString( 'attempt', $sql );
|
||||
$this->assertStringNotContainsString( 'human_modified', $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Empty stage lists and missing tables degrade to 0 / no queries.
|
||||
*/
|
||||
public function test_noop_paths(): void {
|
||||
$this->capture_queries();
|
||||
|
||||
$this->assertSame( 0, \PRAutoBlogger_Run_Stage_Rerun_State::mark_stale( 'run-1', 'i', array() ) );
|
||||
$this->assertSame( 0, \PRAutoBlogger_Run_Stage_Rerun_State::demote_to_pending( '', 'i', array( 'draft' ) ) );
|
||||
$this->assertCount( 0, $this->queries );
|
||||
}
|
||||
}
|
||||
102
tests/unit/Core/RunStateReopenTest.php
Normal file
102
tests/unit/Core/RunStateReopenTest.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Run_State::reopen() (v0.20.0, M3).
|
||||
*
|
||||
* Locks: terminal-only atomic gate, ceiling re-snapshot from the
|
||||
* CURRENT setting, and — critical for CPO guardrail 4 — that the
|
||||
* accumulated reserved/settled spend is never reset, so re-runs are
|
||||
* new spend on the same run ledger.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class RunStateReopenTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* SQL captured from $wpdb->query().
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private array $queries = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->queries = array();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'get_var' )->willReturn( 'wp_prautoblogger_runs' );
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
$this->stub_get_option( array( 'prautoblogger_per_run_cost_ceiling_usd' => '0.75' ) );
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* reopen() transitions ONLY terminal runs (atomic conditional UPDATE)
|
||||
* and re-snapshots the ceiling from the current setting.
|
||||
*/
|
||||
public function test_reopen_gates_on_terminal_status_and_resnapshots_ceiling(): void {
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
|
||||
$this->assertTrue( \PRAutoBlogger_Run_State::reopen( 'run-1' ) );
|
||||
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( "SET status = 'running'", $sql );
|
||||
$this->assertStringContainsString( "status IN ('done','failed','halted')", $sql );
|
||||
$this->assertStringContainsString( 'ceiling_usd = %f', $sql );
|
||||
$this->assertStringContainsString( '0.75', $sql ); // Current setting value.
|
||||
$this->assertStringContainsString( 'finished_at = NULL', $sql );
|
||||
// Guardrail 4: accumulated spend is NEVER reset by a reopen.
|
||||
$this->assertStringNotContainsString( 'reserved_usd', $sql );
|
||||
$this->assertStringNotContainsString( 'settled_usd', $sql );
|
||||
$this->assertStringNotContainsString( 'overage_usd', $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* No row matched (run is pending/running or absent) -> false, so the
|
||||
* executor aborts instead of replaying against a closed gate.
|
||||
*/
|
||||
public function test_reopen_returns_false_when_not_terminal(): void {
|
||||
$this->wpdb->method( 'query' )->willReturn( 0 );
|
||||
|
||||
$this->assertFalse( \PRAutoBlogger_Run_State::reopen( 'run-1' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-healing: missing table / empty run id -> false, no query.
|
||||
*/
|
||||
public function test_reopen_noop_paths(): void {
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
|
||||
$this->assertFalse( \PRAutoBlogger_Run_State::reopen( '' ) );
|
||||
$this->assertCount( 0, $this->queries );
|
||||
}
|
||||
}
|
||||
193
tests/unit/Core/StageInputStoreTest.php
Normal file
193
tests/unit/Core/StageInputStoreTest.php
Normal file
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Stage_Input_Store (v0.20.0, M3).
|
||||
*
|
||||
* Locks the INSERT-only immutability contract (fork saves create new
|
||||
* versions, nothing is ever updated), seed persist-once semantics, the
|
||||
* retention prune scope (human bodies only, seeds kept), and the
|
||||
* self-healing missing-table degradation.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class StageInputStoreTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
/**
|
||||
* Rows captured from $wpdb->insert().
|
||||
*
|
||||
* @var array<int, array<string, mixed>>
|
||||
*/
|
||||
private array $inserted = array();
|
||||
|
||||
/**
|
||||
* SQL captured from $wpdb->query().
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private array $queries = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->inserted = array();
|
||||
$this->queries = array();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
static function ( $sql, ...$args ) {
|
||||
if ( 1 === count( $args ) && is_array( $args[0] ) ) {
|
||||
$args = $args[0];
|
||||
}
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'insert' )->willReturnCallback(
|
||||
function ( $table, $row ) {
|
||||
$this->inserted[] = (array) $row;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'query' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
$this->queries[] = (string) $sql;
|
||||
return 1;
|
||||
}
|
||||
);
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Stage_Input_Store::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** Make the availability probe succeed. */
|
||||
private function table_exists(): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
if ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
return null; // MAX(version) on an empty scope.
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* First fork for a scope gets version 1 via INSERT — and the write
|
||||
* path is INSERT-only: no UPDATE statement may ever be issued.
|
||||
*/
|
||||
public function test_save_fork_inserts_version_one_and_never_updates(): void {
|
||||
$this->table_exists();
|
||||
|
||||
$version = \PRAutoBlogger_Stage_Input_Store::save_fork(
|
||||
'run-1',
|
||||
'draft',
|
||||
'writer',
|
||||
'idea:abc',
|
||||
'{"model":"m","messages":[]}',
|
||||
'rhys'
|
||||
);
|
||||
|
||||
$this->assertSame( 1, $version );
|
||||
$this->assertCount( 1, $this->inserted );
|
||||
$row = $this->inserted[0];
|
||||
$this->assertSame( 'human', $row['source'] );
|
||||
$this->assertSame( 1, $row['version'] );
|
||||
$this->assertSame( 'rhys', $row['author'] );
|
||||
// Immutability: the store issued no UPDATE of any kind.
|
||||
foreach ( $this->queries as $sql ) {
|
||||
$this->assertStringNotContainsString( 'UPDATE', $sql );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The next fork for the same scope gets MAX(version)+1 — the original
|
||||
* version row is never overwritten (CPO guardrail 1).
|
||||
*/
|
||||
public function test_save_fork_increments_version_from_existing_max(): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) {
|
||||
if ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
return '3'; // Existing max version.
|
||||
}
|
||||
);
|
||||
|
||||
$version = \PRAutoBlogger_Stage_Input_Store::save_fork( 'run-1', 'draft', 'writer', 'idea:abc', '{}', 'rhys' );
|
||||
|
||||
$this->assertSame( 4, $version );
|
||||
$this->assertSame( 4, $this->inserted[0]['version'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed persists once: a second save for the same item is a no-op
|
||||
* (idempotent worker resume).
|
||||
*/
|
||||
public function test_save_seed_is_insert_once(): void {
|
||||
$seeded = false;
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
static function ( $sql ) use ( &$seeded ) {
|
||||
if ( false !== strpos( (string) $sql, 'SHOW TABLES' ) ) {
|
||||
return 'wp_prautoblogger_stage_inputs';
|
||||
}
|
||||
if ( false !== strpos( (string) $sql, 'SELECT request_json' ) ) {
|
||||
return $seeded ? '{"topic":"t"}' : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
);
|
||||
|
||||
\PRAutoBlogger_Stage_Input_Store::save_seed( 'run-1', 'idea:abc', '{"topic":"t"}' );
|
||||
$seeded = true;
|
||||
\PRAutoBlogger_Stage_Input_Store::save_seed( 'run-1', 'idea:abc', '{"topic":"other"}' );
|
||||
|
||||
$this->assertCount( 1, $this->inserted );
|
||||
$this->assertSame( 'seed', $this->inserted[0]['source'] );
|
||||
$this->assertSame( '', $this->inserted[0]['stage'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retention prune targets ONLY human fork bodies — the WHERE clause
|
||||
* pins source='human', so seed rows survive (re-run-from-here keeps
|
||||
* working for the life of the run).
|
||||
*/
|
||||
public function test_prune_targets_human_bodies_only(): void {
|
||||
$this->table_exists();
|
||||
|
||||
\PRAutoBlogger_Stage_Input_Store::prune_human_bodies( '2026-05-29 00:00:00' );
|
||||
|
||||
$this->assertCount( 1, $this->queries );
|
||||
$sql = $this->queries[0];
|
||||
$this->assertStringContainsString( 'SET request_json = NULL', $sql );
|
||||
$this->assertStringContainsString( "source = %s", $sql );
|
||||
$this->assertStringContainsString( 'human', $sql );
|
||||
$this->assertStringNotContainsString( "seed", $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Missing table (half-migrated schema): every method degrades to a
|
||||
* silent no-op / null — never a query, never a notice.
|
||||
*/
|
||||
public function test_missing_table_degrades_to_noop(): void {
|
||||
$this->wpdb->method( 'get_var' )->willReturn( null );
|
||||
|
||||
$this->assertNull( \PRAutoBlogger_Stage_Input_Store::save_fork( 'r', 'draft', 'w', 'i', '{}', 'a' ) );
|
||||
\PRAutoBlogger_Stage_Input_Store::save_seed( 'r', 'i', '{}' );
|
||||
$this->assertNull( \PRAutoBlogger_Stage_Input_Store::get_seed( 'r', 'i' ) );
|
||||
$this->assertNull( \PRAutoBlogger_Stage_Input_Store::latest_fork( 'r', 'draft', 'w', 'i' ) );
|
||||
$this->assertSame( 0, \PRAutoBlogger_Stage_Input_Store::prune_human_bodies( '2026-05-29 00:00:00' ) );
|
||||
$this->assertCount( 0, $this->inserted );
|
||||
$this->assertCount( 0, $this->queries );
|
||||
}
|
||||
}
|
||||
157
tests/unit/Core/StageReplayTest.php
Normal file
157
tests/unit/Core/StageReplayTest.php
Normal file
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Stage_Replay (v0.20.0, M3).
|
||||
*
|
||||
* Locks the body -> options inverse transform (the replay must
|
||||
* round-trip through Request_Builder::build_body() to the SAME wire
|
||||
* shape, including the v0.18.1 reasoning headroom) and the decode
|
||||
* validation that guards the replay path against non-chat payloads.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
|
||||
class StageReplayTest extends BaseTestCase {
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
// Builder reads the global reasoning setting; pin it OFF here and
|
||||
// flip it in the drift test below.
|
||||
$this->stub_get_option( array( 'prautoblogger_reasoning_enabled' => '0' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Round-trip: a body WITHOUT reasoning replayed through build_body()
|
||||
* reproduces the original wire shape byte-for-byte.
|
||||
*/
|
||||
public function test_round_trip_without_reasoning(): void {
|
||||
$original = array(
|
||||
'model' => 'google/gemini-2.5-flash-lite',
|
||||
'messages' => array(
|
||||
array( 'role' => 'system', 'content' => 'sys' ),
|
||||
array( 'role' => 'user', 'content' => 'edited prompt' ),
|
||||
),
|
||||
'temperature' => 0.7,
|
||||
'max_tokens' => 4000,
|
||||
);
|
||||
|
||||
$options = \PRAutoBlogger_Stage_Replay::options_from_body( $original, 'draft' );
|
||||
$rebuilt = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )->build_body(
|
||||
$original['messages'],
|
||||
$original['model'],
|
||||
$options
|
||||
);
|
||||
|
||||
// The explicit reasoning-off pin is the only permitted delta
|
||||
// (same shape the empty-completion retry sends upstream).
|
||||
$this->assertSame( array( 'enabled' => false ), $rebuilt['reasoning'] );
|
||||
unset( $rebuilt['reasoning'] );
|
||||
$this->assertSame( $original, array_merge( array( 'model' => $original['model'], 'messages' => $original['messages'] ), $rebuilt ) );
|
||||
$this->assertSame( 4000, $rebuilt['max_tokens'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Round-trip WITH reasoning: the stored body's max_tokens carries the
|
||||
* builder's +cap headroom; the inverse subtracts it so the rebuilt
|
||||
* body is identical (headroom applied once, never compounded).
|
||||
*/
|
||||
public function test_round_trip_with_reasoning_headroom(): void {
|
||||
$original = array(
|
||||
'model' => 'deepseek/deepseek-v4-flash',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'p' ) ),
|
||||
'max_tokens' => 6048, // Caller asked 4000; builder added the 2048 cap.
|
||||
'reasoning' => array(
|
||||
'enabled' => true,
|
||||
'max_tokens' => 2048,
|
||||
),
|
||||
);
|
||||
|
||||
$options = \PRAutoBlogger_Stage_Replay::options_from_body( $original, 'draft' );
|
||||
$this->assertSame( 4000, $options['max_tokens'] );
|
||||
|
||||
$rebuilt = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )->build_body(
|
||||
$original['messages'],
|
||||
$original['model'],
|
||||
$options
|
||||
);
|
||||
|
||||
$this->assertSame( 6048, $rebuilt['max_tokens'] );
|
||||
$this->assertSame( $original['reasoning'], $rebuilt['reasoning'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Global-setting drift cannot reshape a replay: even with reasoning
|
||||
* globally ENABLED, a body stored without reasoning replays with the
|
||||
* explicit off-pin (build_body honours the per-call override).
|
||||
*/
|
||||
public function test_global_reasoning_drift_cannot_leak_into_replay(): void {
|
||||
$this->stub_get_option(
|
||||
array(
|
||||
'prautoblogger_reasoning_enabled' => '1',
|
||||
'prautoblogger_reasoning_effort' => 'high',
|
||||
)
|
||||
);
|
||||
|
||||
$body = array(
|
||||
'model' => 'google/gemini-2.5-flash-lite',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'p' ) ),
|
||||
'max_tokens' => 1000,
|
||||
);
|
||||
$options = \PRAutoBlogger_Stage_Replay::options_from_body( $body, 'polish' );
|
||||
$rebuilt = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )->build_body( $body['messages'], $body['model'], $options );
|
||||
|
||||
$this->assertSame( array( 'enabled' => false ), $rebuilt['reasoning'] );
|
||||
$this->assertSame( 1000, $rebuilt['max_tokens'] ); // No headroom added.
|
||||
}
|
||||
|
||||
/**
|
||||
* Caller metadata (stage/prompt_key) rides options for the guard's
|
||||
* audit rows but never reaches the wire body.
|
||||
*/
|
||||
public function test_options_carry_stage_metadata_not_sent_upstream(): void {
|
||||
$body = array(
|
||||
'model' => 'm',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'p' ) ),
|
||||
);
|
||||
$options = \PRAutoBlogger_Stage_Replay::options_from_body( $body, 'draft' );
|
||||
|
||||
$this->assertSame( 'draft', $options['stage'] );
|
||||
$this->assertSame( 'content.draft', $options['prompt_key'] );
|
||||
|
||||
$rebuilt = ( new \PRAutoBlogger_OpenRouter_Request_Builder() )->build_body( $body['messages'], $body['model'], $options );
|
||||
$this->assertArrayNotHasKey( 'stage', $rebuilt );
|
||||
$this->assertArrayNotHasKey( 'prompt_key', $rebuilt );
|
||||
}
|
||||
|
||||
/**
|
||||
* decode_body() accepts only well-formed chat bodies — model string +
|
||||
* non-empty role/content message list. Everything else returns null
|
||||
* (the executor aborts cleanly instead of replaying garbage).
|
||||
*/
|
||||
public function test_decode_body_validation(): void {
|
||||
$valid = wp_json_encode(
|
||||
array(
|
||||
'model' => 'm',
|
||||
'messages' => array( array( 'role' => 'user', 'content' => 'p' ) ),
|
||||
)
|
||||
);
|
||||
$this->assertIsArray( \PRAutoBlogger_Stage_Replay::decode_body( (string) $valid ) );
|
||||
|
||||
$invalid = array(
|
||||
'not json at all',
|
||||
'"just a string"',
|
||||
'{"messages":[{"role":"user","content":"p"}]}', // No model.
|
||||
'{"model":"m"}', // No messages.
|
||||
'{"model":"m","messages":[]}', // Empty messages.
|
||||
'{"model":"m","messages":["plain string"]}', // Malformed message.
|
||||
'{"model":"m","messages":[{"role":"user"}]}', // No content.
|
||||
'{"model":"m","messages":[{"role":1,"content":"p"}]}', // Non-string role.
|
||||
);
|
||||
foreach ( $invalid as $payload ) {
|
||||
$this->assertNull( \PRAutoBlogger_Stage_Replay::decode_body( $payload ), "must reject: {$payload}" );
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user