Add unit test suite: 54 tests across models, core, and providers
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
166
tests/unit/Core/ContentAnalyzerTest.php
Normal file
166
tests/unit/Core/ContentAnalyzerTest.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Content_Analyzer.
|
||||
*
|
||||
* Validates the LLM analysis pipeline: prompt construction,
|
||||
* response parsing, cost tracking integration, and error handling.
|
||||
* All LLM API calls are mocked.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class ContentAnalyzerTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock LLM provider.
|
||||
*/
|
||||
private $mock_provider;
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock cost tracker.
|
||||
*/
|
||||
private $mock_cost_tracker;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/models/class-prab-source-data.php';
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/models/class-prab-analysis-result.php';
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/core/class-prab-content-analyzer.php';
|
||||
|
||||
// Mock the LLM provider interface.
|
||||
$this->mock_provider = $this->createMock( \PRAutoBlogger_LLM_Provider::class );
|
||||
|
||||
// Mock the cost tracker.
|
||||
$this->mock_cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test analyze returns AnalysisResult on successful LLM response.
|
||||
*/
|
||||
public function test_analyze_returns_analysis_result_on_success(): void {
|
||||
$source = new \PRAutoBlogger_Source_Data(
|
||||
'BPC-157 Shows Promise in Gut Healing',
|
||||
'https://example.com/bpc157',
|
||||
'BPC-157 is a synthetic peptide that has shown remarkable healing properties...',
|
||||
'rss'
|
||||
);
|
||||
|
||||
$llm_response = [
|
||||
'content' => json_encode( [
|
||||
'category' => 'peptide-research',
|
||||
'keywords' => [ 'BPC-157', 'gut healing', 'peptide therapy' ],
|
||||
'relevance_score' => 9,
|
||||
'summary' => 'Article discusses BPC-157 healing properties for gut issues.',
|
||||
'topics' => [ 'regenerative medicine', 'gastrointestinal health' ],
|
||||
] ),
|
||||
'usage' => [
|
||||
'prompt_tokens' => 200,
|
||||
'completion_tokens' => 150,
|
||||
],
|
||||
];
|
||||
|
||||
$this->mock_provider->expects( $this->once() )
|
||||
->method( 'chat_completion' )
|
||||
->willReturn( $llm_response );
|
||||
|
||||
$this->mock_cost_tracker->expects( $this->once() )
|
||||
->method( 'log_api_call' );
|
||||
|
||||
$analyzer = new \PRAutoBlogger_Content_Analyzer(
|
||||
$this->mock_provider,
|
||||
$this->mock_cost_tracker
|
||||
);
|
||||
|
||||
$result = $analyzer->analyze( $source );
|
||||
|
||||
$this->assertInstanceOf( \PRAutoBlogger_Analysis_Result::class, $result );
|
||||
$this->assertSame( 'peptide-research', $result->get_category() );
|
||||
$this->assertSame( 9, $result->get_relevance_score() );
|
||||
$this->assertContains( 'BPC-157', $result->get_keywords() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test analyze handles LLM error response gracefully.
|
||||
*/
|
||||
public function test_analyze_handles_llm_error(): void {
|
||||
$source = new \PRAutoBlogger_Source_Data(
|
||||
'Test Article',
|
||||
'https://example.com',
|
||||
'Content.',
|
||||
'rss'
|
||||
);
|
||||
|
||||
$this->mock_provider->expects( $this->once() )
|
||||
->method( 'chat_completion' )
|
||||
->willReturn( [ 'error' => 'Rate limit exceeded' ] );
|
||||
|
||||
$this->mock_cost_tracker->expects( $this->once() )
|
||||
->method( 'log_api_call' )
|
||||
->with( $this->callback( function ( $data ) {
|
||||
return false === $data['success'];
|
||||
} ) );
|
||||
|
||||
$analyzer = new \PRAutoBlogger_Content_Analyzer(
|
||||
$this->mock_provider,
|
||||
$this->mock_cost_tracker
|
||||
);
|
||||
|
||||
$result = $analyzer->analyze( $source );
|
||||
|
||||
$this->assertNull( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test analyze handles malformed JSON in LLM content.
|
||||
*/
|
||||
public function test_analyze_handles_malformed_llm_json(): void {
|
||||
$source = new \PRAutoBlogger_Source_Data(
|
||||
'Test', 'https://example.com', 'Content.', 'rss'
|
||||
);
|
||||
|
||||
$this->mock_provider->method( 'chat_completion' )
|
||||
->willReturn( [
|
||||
'content' => 'This is not valid JSON {{{',
|
||||
'usage' => [ 'prompt_tokens' => 100, 'completion_tokens' => 50 ],
|
||||
] );
|
||||
|
||||
$analyzer = new \PRAutoBlogger_Content_Analyzer(
|
||||
$this->mock_provider,
|
||||
$this->mock_cost_tracker
|
||||
);
|
||||
|
||||
$result = $analyzer->analyze( $source );
|
||||
|
||||
$this->assertNull( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test analyze respects budget check before calling LLM.
|
||||
*/
|
||||
public function test_analyze_skips_when_budget_exceeded(): void {
|
||||
$source = new \PRAutoBlogger_Source_Data(
|
||||
'Test', 'https://example.com', 'Content.', 'rss'
|
||||
);
|
||||
|
||||
$this->mock_cost_tracker->method( 'is_budget_exceeded' )->willReturn( true );
|
||||
|
||||
// Provider should never be called if budget is exceeded.
|
||||
$this->mock_provider->expects( $this->never() )
|
||||
->method( 'chat_completion' );
|
||||
|
||||
$analyzer = new \PRAutoBlogger_Content_Analyzer(
|
||||
$this->mock_provider,
|
||||
$this->mock_cost_tracker
|
||||
);
|
||||
|
||||
$result = $analyzer->analyze( $source );
|
||||
|
||||
$this->assertNull( $result );
|
||||
}
|
||||
}
|
||||
275
tests/unit/Core/CostTrackerTest.php
Normal file
275
tests/unit/Core/CostTrackerTest.php
Normal file
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Cost_Tracker.
|
||||
*
|
||||
* Validates API call logging, monthly spend aggregation,
|
||||
* budget enforcement, and cost estimation.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class CostTrackerTest extends BaseTestCase {
|
||||
|
||||
/**
|
||||
* @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb instance.
|
||||
*/
|
||||
private $wpdb;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/core/class-prab-cost-tracker.php';
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// log_api_call
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Test log_api_call inserts a row with all required fields.
|
||||
*/
|
||||
public function test_log_api_call_inserts_complete_row(): void {
|
||||
$this->stub_current_time( '2026-04-11 14:30:00' );
|
||||
|
||||
$data = [
|
||||
'model' => 'google/gemini-2.0-flash-001',
|
||||
'step' => 'content_generation',
|
||||
'prompt_tokens' => 500,
|
||||
'completion_tokens' => 1200,
|
||||
'cost' => 0.0034,
|
||||
'duration' => 2.45,
|
||||
'success' => true,
|
||||
'error' => '',
|
||||
];
|
||||
|
||||
$this->wpdb->expects( $this->once() )
|
||||
->method( 'insert' )
|
||||
->with(
|
||||
'wp_prab_cost_logs',
|
||||
$this->callback( function ( $row ) use ( $data ) {
|
||||
return $row['model'] === $data['model']
|
||||
&& $row['prompt_tokens'] === $data['prompt_tokens']
|
||||
&& $row['completion_tokens'] === $data['completion_tokens']
|
||||
&& abs( $row['cost'] - $data['cost'] ) < 0.0001
|
||||
&& $row['step'] === $data['step'];
|
||||
} )
|
||||
)
|
||||
->willReturn( 1 );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$result = $tracker->log_api_call( $data );
|
||||
|
||||
$this->assertTrue( $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test log_api_call returns false on DB insert failure.
|
||||
*/
|
||||
public function test_log_api_call_returns_false_on_db_failure(): void {
|
||||
$this->stub_current_time( '2026-04-11 14:30:00' );
|
||||
|
||||
$this->wpdb->expects( $this->once() )
|
||||
->method( 'insert' )
|
||||
->willReturn( false );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$result = $tracker->log_api_call( [
|
||||
'model' => 'test/model',
|
||||
'step' => 'test',
|
||||
'prompt_tokens' => 100,
|
||||
'completion_tokens' => 200,
|
||||
'cost' => 0.001,
|
||||
'duration' => 1.0,
|
||||
'success' => true,
|
||||
'error' => '',
|
||||
] );
|
||||
|
||||
$this->assertFalse( $result );
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// get_monthly_spend
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Test get_monthly_spend returns aggregated cost for given month.
|
||||
*/
|
||||
public function test_get_monthly_spend_returns_sum(): void {
|
||||
$this->wpdb->expects( $this->once() )
|
||||
->method( 'prepare' )
|
||||
->willReturn( "SELECT SUM(cost) FROM wp_prab_cost_logs WHERE YEAR(created_at) = 2026 AND MONTH(created_at) = 4" );
|
||||
|
||||
$this->wpdb->expects( $this->once() )
|
||||
->method( 'get_var' )
|
||||
->willReturn( '12.5600' );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$spend = $tracker->get_monthly_spend( 2026, 4 );
|
||||
|
||||
$this->assertSame( 12.56, round( $spend, 2 ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test get_monthly_spend returns zero when no rows exist.
|
||||
*/
|
||||
public function test_get_monthly_spend_returns_zero_when_empty(): void {
|
||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared query' );
|
||||
$this->wpdb->method( 'get_var' )->willReturn( null );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$spend = $tracker->get_monthly_spend( 2026, 1 );
|
||||
|
||||
$this->assertSame( 0.0, (float) $spend );
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// is_budget_exceeded
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Test is_budget_exceeded returns false when budget is unlimited (0).
|
||||
*/
|
||||
public function test_is_budget_exceeded_returns_false_when_unlimited(): void {
|
||||
$this->stub_get_option( [
|
||||
'prab_settings' => [ 'monthly_budget' => 0 ],
|
||||
] );
|
||||
|
||||
// Should not even query the DB when budget is unlimited.
|
||||
$this->wpdb->expects( $this->never() )
|
||||
->method( 'get_var' );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$this->assertFalse( $tracker->is_budget_exceeded() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test is_budget_exceeded returns true when spend exceeds budget.
|
||||
*/
|
||||
public function test_is_budget_exceeded_returns_true_when_over(): void {
|
||||
$this->stub_get_option( [
|
||||
'prab_settings' => [ 'monthly_budget' => 10.00 ],
|
||||
] );
|
||||
|
||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||
$this->wpdb->method( 'get_var' )->willReturn( '15.75' );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$this->assertTrue( $tracker->is_budget_exceeded() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test is_budget_exceeded returns false when under budget.
|
||||
*/
|
||||
public function test_is_budget_exceeded_returns_false_when_under(): void {
|
||||
$this->stub_get_option( [
|
||||
'prab_settings' => [ 'monthly_budget' => 50.00 ],
|
||||
] );
|
||||
|
||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||
$this->wpdb->method( 'get_var' )->willReturn( '23.40' );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$this->assertFalse( $tracker->is_budget_exceeded() );
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// estimate_cost
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Test estimate_cost calculates based on model pricing.
|
||||
*/
|
||||
public function test_estimate_cost_calculates_correctly(): void {
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
|
||||
// Using a known model — the exact price depends on the pricing table,
|
||||
// but the structure should be: (prompt_tokens * input_price + completion_tokens * output_price) / 1_000_000
|
||||
$cost = $tracker->estimate_cost( 'google/gemini-2.0-flash-001', 1000, 2000 );
|
||||
|
||||
$this->assertIsFloat( $cost );
|
||||
$this->assertGreaterThanOrEqual( 0.0, $cost );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test estimate_cost returns zero for unknown model.
|
||||
*/
|
||||
public function test_estimate_cost_returns_zero_for_unknown_model(): void {
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
|
||||
$cost = $tracker->estimate_cost( 'nonexistent/model-xyz', 1000, 2000 );
|
||||
|
||||
$this->assertSame( 0.0, $cost );
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// get_recent_logs
|
||||
// ---------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Test get_recent_logs returns array of recent entries.
|
||||
*/
|
||||
public function test_get_recent_logs_returns_limited_results(): void {
|
||||
$mock_rows = [
|
||||
(object) [
|
||||
'id' => 1,
|
||||
'model' => 'model/a',
|
||||
'step' => 'analysis',
|
||||
'prompt_tokens' => 100,
|
||||
'completion_tokens' => 200,
|
||||
'cost' => 0.001,
|
||||
'duration' => 0.5,
|
||||
'success' => 1,
|
||||
'error' => '',
|
||||
'created_at' => '2026-04-11 14:00:00',
|
||||
],
|
||||
(object) [
|
||||
'id' => 2,
|
||||
'model' => 'model/b',
|
||||
'step' => 'generation',
|
||||
'prompt_tokens' => 500,
|
||||
'completion_tokens' => 1000,
|
||||
'cost' => 0.005,
|
||||
'duration' => 2.1,
|
||||
'success' => 1,
|
||||
'error' => '',
|
||||
'created_at' => '2026-04-11 14:05:00',
|
||||
],
|
||||
];
|
||||
|
||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||
$this->wpdb->method( 'get_results' )->willReturn( $mock_rows );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$logs = $tracker->get_recent_logs( 10 );
|
||||
|
||||
$this->assertIsArray( $logs );
|
||||
$this->assertCount( 2, $logs );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test get_recent_logs returns empty array when no logs exist.
|
||||
*/
|
||||
public function test_get_recent_logs_returns_empty_when_no_rows(): void {
|
||||
$this->wpdb->method( 'prepare' )->willReturn( 'prepared' );
|
||||
$this->wpdb->method( 'get_results' )->willReturn( [] );
|
||||
|
||||
$tracker = new \PRAutoBlogger_Cost_Tracker();
|
||||
$logs = $tracker->get_recent_logs( 10 );
|
||||
|
||||
$this->assertIsArray( $logs );
|
||||
$this->assertEmpty( $logs );
|
||||
}
|
||||
}
|
||||
117
tests/unit/Core/IdeaScorerTest.php
Normal file
117
tests/unit/Core/IdeaScorerTest.php
Normal file
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Idea_Scorer.
|
||||
*
|
||||
* Validates idea ranking, deduplication, and score normalization.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class IdeaScorerTest extends BaseTestCase {
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/models/class-prab-article-idea.php';
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/core/class-prab-idea-scorer.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Test rank_ideas returns ideas sorted by score descending.
|
||||
*/
|
||||
public function test_rank_ideas_sorts_by_score_descending(): void {
|
||||
$ideas = [
|
||||
new \PRAutoBlogger_Article_Idea( 'Low Score', 'Desc', [], 'cat', 30.0 ),
|
||||
new \PRAutoBlogger_Article_Idea( 'High Score', 'Desc', [], 'cat', 90.0 ),
|
||||
new \PRAutoBlogger_Article_Idea( 'Mid Score', 'Desc', [], 'cat', 60.0 ),
|
||||
];
|
||||
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$ranked = $scorer->rank_ideas( $ideas );
|
||||
|
||||
$this->assertSame( 'High Score', $ranked[0]->get_title() );
|
||||
$this->assertSame( 'Mid Score', $ranked[1]->get_title() );
|
||||
$this->assertSame( 'Low Score', $ranked[2]->get_title() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test rank_ideas limits output to requested count.
|
||||
*/
|
||||
public function test_rank_ideas_limits_results(): void {
|
||||
$ideas = [];
|
||||
for ( $i = 0; $i < 20; $i++ ) {
|
||||
$ideas[] = new \PRAutoBlogger_Article_Idea(
|
||||
"Idea {$i}", 'Description', [], 'cat', (float) $i
|
||||
);
|
||||
}
|
||||
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$ranked = $scorer->rank_ideas( $ideas, 5 );
|
||||
|
||||
$this->assertCount( 5, $ranked );
|
||||
// Should be the top 5 by score.
|
||||
$this->assertSame( 'Idea 19', $ranked[0]->get_title() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test deduplicate removes ideas with similar titles.
|
||||
*/
|
||||
public function test_deduplicate_removes_similar_titles(): void {
|
||||
$ideas = [
|
||||
new \PRAutoBlogger_Article_Idea( 'BPC-157 Benefits for Gut Health', 'Desc', [], 'cat', 80.0 ),
|
||||
new \PRAutoBlogger_Article_Idea( 'BPC-157 Benefits for Gut Health', 'Different desc', [], 'cat', 75.0 ),
|
||||
new \PRAutoBlogger_Article_Idea( 'Thymosin Beta-4 Research Update', 'Desc', [], 'cat', 70.0 ),
|
||||
];
|
||||
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$deduplicated = $scorer->deduplicate( $ideas );
|
||||
|
||||
$this->assertCount( 2, $deduplicated );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test deduplicate keeps the higher-scored duplicate.
|
||||
*/
|
||||
public function test_deduplicate_keeps_higher_score(): void {
|
||||
$ideas = [
|
||||
new \PRAutoBlogger_Article_Idea( 'Same Title Here', 'Low version', [], 'cat', 40.0 ),
|
||||
new \PRAutoBlogger_Article_Idea( 'Same Title Here', 'High version', [], 'cat', 90.0 ),
|
||||
];
|
||||
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$deduplicated = $scorer->deduplicate( $ideas );
|
||||
|
||||
$this->assertCount( 1, $deduplicated );
|
||||
$this->assertSame( 90.0, $deduplicated[0]->get_score() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test rank_ideas handles empty input.
|
||||
*/
|
||||
public function test_rank_ideas_handles_empty_input(): void {
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$ranked = $scorer->rank_ideas( [] );
|
||||
|
||||
$this->assertIsArray( $ranked );
|
||||
$this->assertEmpty( $ranked );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test rank_ideas handles single idea.
|
||||
*/
|
||||
public function test_rank_ideas_handles_single_idea(): void {
|
||||
$ideas = [
|
||||
new \PRAutoBlogger_Article_Idea( 'Only Idea', 'Desc', [], 'cat', 50.0 ),
|
||||
];
|
||||
|
||||
$scorer = new \PRAutoBlogger_Idea_Scorer();
|
||||
$ranked = $scorer->rank_ideas( $ideas );
|
||||
|
||||
$this->assertCount( 1, $ranked );
|
||||
$this->assertSame( 'Only Idea', $ranked[0]->get_title() );
|
||||
}
|
||||
}
|
||||
159
tests/unit/Core/PublisherTest.php
Normal file
159
tests/unit/Core/PublisherTest.php
Normal file
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Publisher.
|
||||
*
|
||||
* Validates WordPress post creation with metadata,
|
||||
* generation log attachment, and error handling.
|
||||
* All WordPress functions are mocked.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class PublisherTest extends BaseTestCase {
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
require_once PRAB_PLUGIN_DIR . 'includes/core/class-prab-publisher.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Test publish creates a draft post with correct data.
|
||||
*/
|
||||
public function test_publish_creates_draft_post(): void {
|
||||
$post_data = [
|
||||
'title' => 'BPC-157: A Complete Guide',
|
||||
'content' => '<p>BPC-157 is a synthetic peptide...</p>',
|
||||
'excerpt' => 'An overview of BPC-157 benefits.',
|
||||
'category' => 'peptide-research',
|
||||
];
|
||||
|
||||
$generation_meta = [
|
||||
'model' => 'google/gemini-2.0-flash-001',
|
||||
'pipeline_mode' => 'single_pass',
|
||||
'total_cost' => 0.0045,
|
||||
'prompt_tokens' => 800,
|
||||
'completion_tokens' => 2000,
|
||||
'generation_logs' => [],
|
||||
];
|
||||
|
||||
// wp_insert_post should be called with post_status = 'draft'.
|
||||
Functions\expect( 'wp_insert_post' )
|
||||
->once()
|
||||
->with( \Mockery::on( function ( $args ) {
|
||||
return 'draft' === $args['post_status']
|
||||
&& 'BPC-157: A Complete Guide' === $args['post_title']
|
||||
&& false !== strpos( $args['post_content'], 'BPC-157' );
|
||||
} ) )
|
||||
->andReturn( 42 );
|
||||
|
||||
// Metadata should be saved.
|
||||
Functions\expect( 'update_post_meta' )
|
||||
->atLeast()
|
||||
->once();
|
||||
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
Functions\when( 'wp_slash' )->returnArg();
|
||||
Functions\when( 'sanitize_title' )->alias( function ( $title ) {
|
||||
return strtolower( str_replace( ' ', '-', $title ) );
|
||||
} );
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$post_id = $publisher->publish( $post_data, $generation_meta );
|
||||
|
||||
$this->assertSame( 42, $post_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test publish returns WP_Error when wp_insert_post fails.
|
||||
*/
|
||||
public function test_publish_returns_error_on_insert_failure(): void {
|
||||
$wp_error = new \stdClass();
|
||||
$wp_error->errors = [ 'db_insert_error' => [ 'Could not insert post' ] ];
|
||||
|
||||
Functions\when( 'wp_insert_post' )->justReturn( $wp_error );
|
||||
Functions\when( 'is_wp_error' )->justReturn( true );
|
||||
Functions\when( 'wp_slash' )->returnArg();
|
||||
Functions\when( 'sanitize_title' )->returnArg();
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$result = $publisher->publish(
|
||||
[ 'title' => 'Test', 'content' => 'Test content', 'excerpt' => '', 'category' => '' ],
|
||||
[]
|
||||
);
|
||||
|
||||
// Should propagate the error, not the post ID.
|
||||
$this->assertNotSame( 42, $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test publish sanitizes title and content.
|
||||
*/
|
||||
public function test_publish_calls_sanitization(): void {
|
||||
Functions\expect( 'wp_slash' )
|
||||
->atLeast()
|
||||
->once()
|
||||
->andReturnFirstArg();
|
||||
|
||||
Functions\expect( 'sanitize_title' )
|
||||
->once()
|
||||
->andReturnUsing( function ( $title ) {
|
||||
return strtolower( str_replace( ' ', '-', $title ) );
|
||||
} );
|
||||
|
||||
Functions\when( 'wp_insert_post' )->justReturn( 1 );
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
Functions\when( 'update_post_meta' )->justReturn( true );
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$publisher->publish(
|
||||
[
|
||||
'title' => 'Test <script>alert(1)</script>',
|
||||
'content' => '<p>Safe content</p>',
|
||||
'excerpt' => 'Excerpt',
|
||||
'category' => 'general',
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
// If we get here without error, sanitization was called.
|
||||
$this->assertTrue( true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Test publish stores generation metadata as post meta.
|
||||
*/
|
||||
public function test_publish_stores_generation_metadata(): void {
|
||||
$generation_meta = [
|
||||
'model' => 'test/model',
|
||||
'pipeline_mode' => 'multi_step',
|
||||
'total_cost' => 0.01,
|
||||
];
|
||||
|
||||
Functions\when( 'wp_insert_post' )->justReturn( 99 );
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
Functions\when( 'wp_slash' )->returnArg();
|
||||
Functions\when( 'sanitize_title' )->returnArg();
|
||||
|
||||
$meta_saved = [];
|
||||
Functions\when( 'update_post_meta' )->alias(
|
||||
function ( $post_id, $key, $value ) use ( &$meta_saved ) {
|
||||
$meta_saved[ $key ] = $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
$publisher = new \PRAutoBlogger_Publisher();
|
||||
$publisher->publish(
|
||||
[ 'title' => 'T', 'content' => 'C', 'excerpt' => '', 'category' => '' ],
|
||||
$generation_meta
|
||||
);
|
||||
|
||||
// Verify generation metadata was stored.
|
||||
$this->assertNotEmpty( $meta_saved );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user