Files
dpl/tests/Feature/RegistrationReport/RegistrationReportTest.php

67 lines
8.5 KiB
PHP
Raw Permalink 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\RegistrationReport;
use App\Services\RegistrationReport\Reporter;
use Carbon\CarbonImmutable as Clock;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Bootstrap\RegisterProviders;
use Illuminate\Support\Facades\{Cache,DB,File,Http,Schema};
use Illuminate\Http\Client\ConnectionException;
use Tests\TestCase;
class RegistrationReportTest extends TestCase
{
private string $dir;
private const ID='530e8e2b-e4e8-4abc-9999-e263d245f812';
public function createApplication(){
$app=require dirname(__DIR__,3).'/bootstrap/app.php';
$app->beforeBootstrapping(RegisterProviders::class,function($app){$app['config']->set(['database.default'=>'sqlite','database.connections.sqlite.database'=>':memory:','cache.default'=>'array','cache.stores.redis'=>['driver'=>'array'],'queue.default'=>'sync','app.key'=>'base64:'.base64_encode(str_repeat('t',32)),'app.env'=>'production','app.url'=>'https://dpl.example.invalid']);});
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();return $app;
}
protected function setUp():void{
parent::setUp();Schema::create('v2_plugins',fn(Blueprint $t)=>[$t->id(),$t->boolean('is_enabled')->default(false)]);Schema::create('v2_user',fn(Blueprint $t)=>[$t->id(),$t->integer('created_at')]);$this->dir=sys_get_temp_dir().'/registration-report-'.bin2hex(random_bytes(6));mkdir($this->dir,0700);config(['registration_report.enabled'=>true,'registration_report.project'=>'DPL','registration_report.state_path'=>$this->dir.'/state.json','registration_report.telehub_url'=>'https://telehub.example.invalid','registration_report.telehub_key'=>'fake-local-test-key']);Http::preventStrayRequests();
}
protected function tearDown():void{File::deleteDirectory($this->dir);parent::tearDown();}
private function now(string $time='08:00:00'):Clock{return Clock::parse('2026-10-31 '.$time,'Asia/Shanghai');}
private function add(string $time):void{DB::table('v2_user')->insert(['created_at'=>Clock::parse($time,'Asia/Shanghai')->timestamp]);}
private function response(string $status='queued'):array{return ['data'=>['id'=>self::ID,'status'=>$status]];}
public function test_beijing_twenty_four_hour_window_and_eight_oclock_boundaries_match_integer_registration_timestamps():void{
foreach(['2026-10-30 07:59:59','2026-10-30 08:00:00','2026-10-30 23:59:59','2026-10-31 00:00:00','2026-10-31 07:59:59','2026-10-31 08:00:00','2026-10-31 09:00:00'] as $time)$this->add($time);
$s=(new Reporter)->run($this->now('12:00:00'),true)['report'];$this->assertSame(4,$s['count']);$this->assertSame($this->now()->timestamp,$s['end_at']);$this->assertStringContainsString('2026-10-30 08:00–2026-10-31 08:00',$s['text']);$this->assertStringStartsWith('【DPL/production - 注册量日报】',$s['text']);$this->assertFileDoesNotExist($this->dir.'/state.json');Http::assertNothingSent();
}
public function test_before_eight_does_not_send_or_create_a_daily_snapshot():void{Http::fake();$r=(new Reporter)->run($this->now('07:59:59'));$this->assertSame('not_due',$r['status']);$this->assertFileDoesNotExist($this->dir.'/state.json');Http::assertNothingSent();}
public function test_zero_is_reported_once_using_info_and_base_without_extra_api_fields():void{
Http::fake(['*'=>Http::response($this->response('sent'),202)]);$r=new Reporter;$r->run($this->now());$r->run($this->now('09:00:00'));Http::assertSentCount(1);Http::assertSent(fn($q)=>$q['bot']==='info'&&$q['target']==='base'&&str_contains($q['text'],'注册量:0 人')&&array_keys($q->data())===['bot','target','text']&&count($q->header('Idempotency-Key'))===1);$s=json_decode(file_get_contents($this->dir.'/state.json'),true);$this->assertSame('sent',$s['reports']['2026-10-31']['status']);
}
public function test_transport_retry_reuses_the_original_count_text_and_idempotency_key():void{
$this->add('2026-10-31 01:00:00');$captured=[];
Http::fake(function($q)use(&$captured){$captured[]=['key'=>$q->header('Idempotency-Key'),'data'=>$q->data()];if(count($captured)===1)throw new ConnectionException('must-not-log-secret');return Http::response($this->response(),202);});
$r=new Reporter;$r->run($this->now());$this->add('2026-10-31 02:00:00');$r->run($this->now('08:01:00'));$r->run($this->now('08:05:00'));$this->assertCount(2,$captured);$this->assertSame($captured[0],$captured[1]);$this->assertStringContainsString('注册量:1 人',$captured[1]['data']['text']);$this->assertStringNotContainsString('must-not-log-secret',file_get_contents($this->dir.'/state.json'));
}
public function test_accepted_message_is_polled_by_receipt_until_sent_and_never_posted_again():void{
Http::fake(['*/api/v1/messages/'.self::ID=>Http::response($this->response('sent'),200),'*/api/v1/messages'=>Http::response($this->response(),202)]);$r=new Reporter;$r->run($this->now());$r->run($this->now('08:05:00'));$r->run($this->now('08:10:00'));Http::assertSentCount(2);Http::assertSent(fn($q)=>$q->method()==='GET'&&str_ends_with($q->url(),self::ID));
}
public function test_uncertain_is_preserved_without_reposting_or_polling():void{
Http::fake(['*'=>Http::response($this->response('uncertain'),202)]);$r=new Reporter;$this->assertTrue($r->run($this->now())['needs_attention']);$this->assertTrue($r->run($this->now('09:00:00'))['needs_attention']);Http::assertSentCount(1);
}
public function test_unconfigured_disabled_and_nonproduction_instances_do_not_send():void{
Http::fake();config(['registration_report.telehub_key'=>'']);$this->assertTrue((new Reporter)->run($this->now())['needs_attention']);config(['registration_report.enabled'=>false]);$this->assertSame('disabled',(new Reporter)->run($this->now())['status']);config(['registration_report.enabled'=>true,'app.env'=>'local']);$this->assertSame('non_production',(new Reporter)->run($this->now())['status']);Http::assertNothingSent();
}
public function test_late_same_day_execution_still_counts_only_until_eight():void{
$this->add('2026-10-31 06:00:00');$this->add('2026-10-31 10:00:00');Http::fake(['*'=>Http::response($this->response('sent'),202)]);(new Reporter)->run($this->now('17:00:00'));Http::assertSent(fn($q)=>str_contains($q['text'],'注册量:1 人')&&str_contains($q['text'],'2026-10-30 08:00–2026-10-31 08:00'));
}
public function test_new_instances_inherit_enablement_and_have_distinct_event_identities():void{
$r=new Reporter;$first=$r->snapshot($this->now());config(['registration_report.project'=>'HN','app.url'=>'https://hn.example.invalid']);$second=$r->snapshot($this->now());$this->assertNotSame($first['key'],$second['key']);$this->assertStringStartsWith('【HN/production - 注册量日报】',$second['text']);$this->assertTrue((require base_path('config/registration_report.php'))['enabled']);
}
public function test_corrupt_state_fails_closed_without_external_calls():void{
file_put_contents($this->dir.'/state.json','corrupt');Http::fake();try{(new Reporter)->run($this->now());$this->fail('corrupt state must stop');}catch(\JsonException $e){Http::assertNothingSent();$this->assertSame('corrupt',file_get_contents($this->dir.'/state.json'));}
}
public function test_concurrent_run_does_not_send_when_the_instance_lock_is_held():void{
$h=fopen($this->dir.'/state.json.lock','c+');flock($h,LOCK_EX|LOCK_NB);try{$this->assertSame('locked',(new Reporter)->run($this->now())['status']);Http::assertNothingSent();}finally{flock($h,LOCK_UN);fclose($h);}
}
public function test_http_forbidden_does_not_fall_back_to_another_bot_or_caller():void{
Http::fake(['*'=>Http::response([],403)]);$r=new Reporter;$this->assertTrue($r->run($this->now())['needs_attention']);$r->run($this->now('08:05:00'));Http::assertSentCount(2);Http::assertSent(fn($q)=>$q['bot']==='info'&&$q['target']==='base');
}
public function test_schedule_contains_beijing_eight_and_bounded_recovery_with_instance_mutexes():void{
$schedule=new \Illuminate\Console\Scheduling\Schedule; $kernel=$this->app->make(\Illuminate\Contracts\Console\Kernel::class);$method=new \ReflectionMethod($kernel,'schedule');$method->invoke($kernel,$schedule);$events=array_values(array_filter($schedule->events(),fn($e)=>str_contains($e->command??'','report:registrations')));$this->assertCount(2,$events);$this->assertSame('0 8 * * *',$events[0]->expression);$this->assertSame('Asia/Shanghai',$events[0]->timezone);$this->assertSame('*/5 * * * *',$events[1]->expression);$this->assertNotSame($events[0]->mutexName(),$events[1]->mutexName());$this->assertTrue($events[0]->onOneServer);$this->assertTrue($events[0]->withoutOverlapping);config(['registration_report.enabled'=>false]);$this->assertFalse($events[0]->filtersPass($this->app));$this->assertFalse($events[1]->filtersPass($this->app));
}
}