Files
dpl/tests/Feature/MailFlow/TeleHubMailReportTest.php
T

88 lines
9.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Tests\Feature\MailFlow;
use App\Models\{MailDailyReport,MailMessage,MailQuotaBucket};
use App\Services\MailFlow\{DailyReportService,Settings};
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\{Cache,DB,Http,Schema};
use Tests\TestCase;
class TeleHubMailReportTest extends TestCase
{
private const UUID='12345678-1234-1234-1234-123456789abc';
protected function setUp():void
{
parent::setUp();
config(['database.default'=>'sqlite','database.connections.sqlite.database'=>':memory:','cache.default'=>'array','cache.stores.redis'=>['driver'=>'array'],'app.key'=>'base64:'.base64_encode(str_repeat('a',32)),'queue.default'=>'sync','app.env'=>'production']);
DB::purge('sqlite');Cache::forgetDriver(['redis','array']);$this->app->forgetInstance(\App\Support\Setting::class);
Schema::create('v2_settings',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->text('value')->nullable(),$t->timestamps()]);
(require base_path('database/migrations/2026_10_09_170000_create_mail_flow_tables.php'))->up();Cache::flush();
config(['mailflow.enabled'=>true,'mailflow.resend_enabled'=>false,'mailflow.report_enabled'=>true,'mail_report.enabled'=>true,'mail_report.project'=>'DPL','mail_report.telehub_url'=>'https://telehub.example.test','mail_report.telehub_key'=>'private-report-key','mail_report.start_date'=>'2026-10-30','mail_report.retry_seconds'=>300]);
$this->travelTo(Carbon::parse('2026-10-31 08:00:00','Asia/Shanghai'));Http::preventStrayRequests();
}
private function report():MailDailyReport {return app(DailyReportService::class)->snapshot(now()->utc()->startOfDay());}
private function fake(string $status='queued',int $code=202):void {Http::fake(['*/api/v1/messages'=>Http::response(['data'=>['id'=>self::UUID,'status'=>$status]],$code)]);}
private function message(string $key,string $time):void {MailMessage::create(['message_key'=>$key,'email'=>'[email protected]','subject'=>'private-subject','purpose'=>'verification','channel'=>'resend','status'=>'delivered','created_at'=>Carbon::parse($time,'Asia/Shanghai')]);}
public function test_counts_usage_and_quota_are_reported_without_email_or_secrets():void
{
$this->message('mail','2026-10-30 10:00');$r=$this->report();$s=$r->summary;$s['resend_usage']=['daily'=>['used'=>3,'limit'=>100],'monthly'=>['used'=>9,'limit'=>3000]];$s['quota']=[['period'=>'daily','limit'=>100,'used'=>3,'reserved'=>2]];$r->update(['summary'=>$s]);$this->fake();app(DailyReportService::class)->send($r);
$text=$r->refresh()->summary['_telehub']['text'];$this->assertStringContainsString('2026-10-30 08:00–2026-10-31 08:00',$text);$this->assertStringContainsString('发送 / Resend / 已投递:1',$text);$this->assertStringContainsString('官方本月已用:9 / 3000',$text);$this->assertStringContainsString('日保守剩余额度:95',$text);$this->assertStringNotContainsString('private-user',$text);$this->assertStringNotContainsString('private-subject',$text);$this->assertStringNotContainsString('private-report-key',$text);
}
public function test_queued_receipt_is_polled_and_sent_is_terminal():void
{
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->assertSame('queued',$r->refresh()->status);$this->travel(6)->minutes();Http::fake(['*/api/v1/messages/'.self::UUID=>Http::response(['data'=>['id'=>self::UUID,'status'=>'sent']],200)]);$s->send($r);$s->send($r);$this->assertSame('sent',$r->refresh()->status);Http::assertSent(fn($q)=>$q->method()==='GET');Http::assertNotSent(fn($q)=>$q->method()==='POST');
}
public function test_lost_post_response_reuses_body_and_key_even_after_summary_changes():void
{
$fail=true;Http::fake(['*/api/v1/messages'=>function()use(&$fail){if($fail)throw new \Illuminate\Http\Client\ConnectionException('simulated');return Http::response(['data'=>['id'=>self::UUID,'status'=>'queued']],202);}]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$event=$r->refresh()->summary['_telehub'];$summary=$r->summary;$summary['counts']=['out/resend/delivered'=>999];$r->update(['summary'=>$summary]);$this->travel(6)->minutes();$fail=false;$s->send($r);Http::assertSent(fn($q)=>$q->hasHeader('Idempotency-Key',$event['key'])&&$q['text']===$event['text']);$this->assertSame('queued',$r->refresh()->status);
}
public function test_all_legacy_attempted_or_unknown_reports_are_preserved_without_http():void
{
$r=$this->report();foreach(['submitted','unknown','sending','failed'] as $status){$r->update(['status'=>$status,'attempts'=>1]);app(DailyReportService::class)->send($r);$this->assertSame($status,$r->refresh()->status);$this->assertArrayNotHasKey('_telehub',$r->summary);}$r->update(['status'=>'pending','attempts'=>1]);app(DailyReportService::class)->send($r);$this->assertArrayNotHasKey('_telehub',$r->refresh()->summary);Http::assertNothingSent();
}
public function test_legacy_submitted_current_day_is_not_replaced_by_command():void
{
$r=$this->report();$r->update(['status'=>'submitted','attempts'=>1]);$this->artisan('mail:report-usage')->assertExitCode(0);$this->assertSame(1,MailDailyReport::count());$this->assertSame('submitted',$r->refresh()->status);Http::assertNothingSent();
}
public function test_early_retry_uses_last_completed_eight_to_eight_period():void
{
$this->travelTo(Carbon::parse('2026-11-02 07:55:00','Asia/Shanghai'));
foreach(['before'=>'2026-10-31 07:59:59','start'=>'2026-10-31 08:00:00','inside'=>'2026-11-01 07:59:59','end'=>'2026-11-01 08:00:00'] as $key=>$time)$this->message($key,$time);
$this->fake();$this->artisan('mail:report-usage')->assertExitCode(0);$r=MailDailyReport::first();$this->assertSame('2026-10-31',$r->report_date);$this->assertSame(['out/resend/delivered'=>2],$r->summary['counts']);$this->assertStringContainsString('2026-10-31 08:00–2026-11-01 08:00',$r->summary['_telehub']['text']);
}
public function test_future_start_date_prevents_historical_snapshot_or_send():void
{
config(['mail_report.start_date'=>'2026-11-01']);$this->artisan('mail:report-usage')->assertExitCode(0);$this->assertSame(0,MailDailyReport::count());Http::assertNothingSent();
}
public function test_disabled_local_and_missing_key_do_not_call_telehub():void
{
$r=$this->report();$s=app(DailyReportService::class);config(['mail_report.enabled'=>false]);$s->send($r);config(['mail_report.enabled'=>true,'app.env'=>'local']);$s->send($r);config(['app.env'=>'production','mail_report.telehub_key'=>'']);$s->send($r);$this->assertSame('telehub_configuration_required',$r->refresh()->error_code);$this->assertSame(0,(int)$r->attempts);Http::assertNothingSent();
}
public function test_authorization_failure_does_not_fallback_or_blindly_retry():void
{
Http::fake(['*/api/v1/messages'=>Http::response([],403)]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(1)->hours();$s->send($r);$this->assertSame('failed',$r->refresh()->status);$this->assertSame('telehub_http_403',$r->error_code);Http::assertSentCount(1);
}
public function test_uncertain_receipt_is_terminal_and_never_reposted():void
{
$this->fake('uncertain');$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(1)->hours();$s->send($r);$this->assertSame('uncertain',$r->refresh()->status);Http::assertSentCount(1);
}
public function test_rate_limit_retains_key_and_obeys_retry_after():void
{
Http::fake(['*/api/v1/messages'=>Http::sequence()->push([],429,['Retry-After'=>'900'])->push(['data'=>['id'=>self::UUID,'status'=>'queued']],202)]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$key=$r->refresh()->summary['_telehub']['key'];$this->travel(6)->minutes();$s->send($r);Http::assertSentCount(1);$this->travel(10)->minutes();$s->send($r);$this->assertSame('queued',$r->refresh()->status);Http::assertSent(fn($q)=>$q->hasHeader('Idempotency-Key',$key));
}
public function test_receipt_id_mismatch_keeps_original_receipt():void
{
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(6)->minutes();Http::fake(['*/api/v1/messages*'=>Http::response(['data'=>['id'=>'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','status'=>'sent']],200)]);$s->send($r);$this->assertSame(self::UUID,$r->refresh()->summary['_telehub']['receipt_id']);$this->assertSame('queued',$r->status);$this->assertSame('telehub_response_invalid',$r->error_code);
}
public function test_cross_instance_state_cannot_be_reused():void
{
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);config(['mail_report.project'=>'HN']);$this->expectException(\RuntimeException::class);$s->send($r);
}
public function test_reporting_credentials_are_not_in_mailflow_public_settings():void
{
$settings=Settings::publicSettings();$this->assertArrayNotHasKey('telehub_key',$settings);$this->assertStringNotContainsString('private-report-key',json_encode($settings));
}
}