|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tests\Unit; |
| 4 | + |
| 5 | +use Domain\Captcha\GoogleRecaptchaV3CaptchaProvider; |
| 6 | +use Domain\Setting\Models\Setting; |
| 7 | +use Illuminate\Support\Facades\App; |
| 8 | +use Illuminate\Support\Facades\Config; |
| 9 | +use Illuminate\Support\Facades\Http; |
| 10 | +use Tests\TestCase; |
| 11 | + |
| 12 | +class CaptchaServiceTest extends TestCase |
| 13 | +{ |
| 14 | + public function setUp(): void |
| 15 | + { |
| 16 | + parent::setUp(); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * @dataProvider captchaDataProvider |
| 21 | + */ |
| 22 | + public function testValidateTokenLogic( |
| 23 | + float $google_score, |
| 24 | + string $db_min_score, |
| 25 | + bool $expected_result |
| 26 | + ): void { |
| 27 | + Config::set('captcha.google_recaptcha_url', 'www.google.com/recaptcha/api/siteverify'); |
| 28 | + Config::set('captcha.google_recaptcha_secret', 'secret'); |
| 29 | + |
| 30 | + Setting::query()->where('name', 'google_recaptcha_min_score') |
| 31 | + ->firstOrCreate([ |
| 32 | + 'name' => 'google_recaptcha_min_score', |
| 33 | + 'value' => $db_min_score, |
| 34 | + 'public' => false, |
| 35 | + ]); |
| 36 | + |
| 37 | + Http::fake([ |
| 38 | + 'www.google.com/recaptcha/api/siteverify' => Http::response([ |
| 39 | + 'success' => true, |
| 40 | + 'action' => 'login', |
| 41 | + 'score' => $google_score, |
| 42 | + ], 200), |
| 43 | + ]); |
| 44 | + |
| 45 | + /** @var GoogleRecaptchaV3CaptchaProvider $captchaProvider */ |
| 46 | + $captchaProvider = App::make(GoogleRecaptchaV3CaptchaProvider::class); |
| 47 | + |
| 48 | + $result = $captchaProvider->validate_token('test-token', 'login'); |
| 49 | + |
| 50 | + $this->assertEquals($expected_result, $result); |
| 51 | + } |
| 52 | + |
| 53 | + public static function captchaDataProvider(): array |
| 54 | + { |
| 55 | + return [ |
| 56 | + ['google_score' => 0.9, 'db_min_score' => '0.5', 'expected' => true], |
| 57 | + ['google_score' => 0.1, 'db_min_score' => '0.5', 'expected' => false], |
| 58 | + ['google_score' => 0.5, 'db_min_score' => '0.5', 'expected' => true], |
| 59 | + |
| 60 | + ['google_score' => 0.3, 'db_min_score' => '0,5', 'expected' => false], |
| 61 | + |
| 62 | + ['google_score' => 0.0, 'db_min_score' => '', 'expected' => false], |
| 63 | + // Default value is 0.1 |
| 64 | + ['google_score' => 0.2, 'db_min_score' => '', 'expected' => true], |
| 65 | + ]; |
| 66 | + } |
| 67 | +} |
0 commit comments