mirror of
https://github.com/elyby/accounts.git
synced 2024-12-27 15:40:21 +05:30
Реорганизованы зависимости для ReCaptcha\Validator
Новый способ отключения проверки капчи для функциональных тестов
This commit is contained in:
parent
b9df9ff2a7
commit
0cf68a6360
@ -2,14 +2,14 @@
|
||||
namespace api\components\ReCaptcha;
|
||||
|
||||
use common\helpers\Error as E;
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use Yii;
|
||||
use yii\base\Exception;
|
||||
use yii\base\InvalidConfigException;
|
||||
use yii\di\Instance;
|
||||
|
||||
class Validator extends \yii\validators\Validator {
|
||||
|
||||
const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
||||
protected const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
||||
|
||||
public $skipOnEmpty = false;
|
||||
|
||||
@ -17,15 +17,21 @@ class Validator extends \yii\validators\Validator {
|
||||
|
||||
public $requiredMessage = E::CAPTCHA_REQUIRED;
|
||||
|
||||
/**
|
||||
* @var Component|string
|
||||
*/
|
||||
public $component = 'reCaptcha';
|
||||
|
||||
private $client;
|
||||
|
||||
public function __construct(ClientInterface $client, array $config = []) {
|
||||
parent::__construct($config);
|
||||
$this->client = $client;
|
||||
}
|
||||
|
||||
public function init() {
|
||||
parent::init();
|
||||
if ($this->getComponent() === null) {
|
||||
throw new InvalidConfigException('Required "reCaptcha" component as instance of ' . Component::class . '.');
|
||||
}
|
||||
|
||||
$this->when = function() {
|
||||
return !YII_ENV_TEST;
|
||||
};
|
||||
$this->component = Instance::ensure($this->component, Component::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -36,9 +42,9 @@ class Validator extends \yii\validators\Validator {
|
||||
return [$this->requiredMessage, []];
|
||||
}
|
||||
|
||||
$response = $this->createClient()->post(self::SITE_VERIFY_URL, [
|
||||
$response = $this->client->request('POST', self::SITE_VERIFY_URL, [
|
||||
'form_params' => [
|
||||
'secret' => $this->getComponent()->secret,
|
||||
'secret' => $this->component->secret,
|
||||
'response' => $value,
|
||||
'remoteip' => Yii::$app->getRequest()->getUserIP(),
|
||||
],
|
||||
@ -52,15 +58,4 @@ class Validator extends \yii\validators\Validator {
|
||||
return $data['success'] ? null : [$this->message, []];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Component
|
||||
*/
|
||||
protected function getComponent() {
|
||||
return Yii::$app->reCaptcha;
|
||||
}
|
||||
|
||||
protected function createClient() {
|
||||
return new GuzzleClient();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -79,6 +79,11 @@ return [
|
||||
],
|
||||
],
|
||||
],
|
||||
'container' => [
|
||||
'definitions' => [
|
||||
GuzzleHttp\ClientInterface::class => GuzzleHttp\Client::class,
|
||||
],
|
||||
],
|
||||
'aliases' => [
|
||||
'@bower' => '@vendor/bower-asset',
|
||||
'@npm' => '@vendor/npm-asset',
|
||||
|
@ -2,64 +2,36 @@
|
||||
namespace codeception\api\unit\components\ReCaptcha;
|
||||
|
||||
use api\components\ReCaptcha\Validator;
|
||||
use Codeception\Specify;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use tests\codeception\api\unit\TestCase;
|
||||
|
||||
class ValidatorTest extends TestCase {
|
||||
use Specify;
|
||||
|
||||
public function testValidateValue() {
|
||||
$this->specify('Get error.captcha_required, if passed empty value', function() {
|
||||
$validator = new Validator();
|
||||
expect($validator->validate('', $error))->false();
|
||||
expect($error)->equals('error.captcha_required');
|
||||
});
|
||||
$validator = new Validator(mock(ClientInterface::class));
|
||||
$this->assertFalse($validator->validate('', $error));
|
||||
$this->assertEquals('error.captcha_required', $error, 'Get error.captcha_required, if passed empty value');
|
||||
|
||||
$this->specify('Get error.captcha_invalid, if passed wrong value', function() {
|
||||
/** @var \PHPUnit_Framework_MockObject_MockObject|Validator $validator */
|
||||
$validator = $this->getMockBuilder(Validator::class)
|
||||
->setMethods(['createClient'])
|
||||
->getMock();
|
||||
$mockClient = mock(ClientInterface::class);
|
||||
$mockClient->shouldReceive('request')->andReturn(new Response(200, [], json_encode([
|
||||
'success' => false,
|
||||
'error-codes' => [
|
||||
'invalid-input-response', // The response parameter is invalid or malformed.
|
||||
],
|
||||
])));
|
||||
$validator = new Validator($mockClient);
|
||||
$this->assertFalse($validator->validate('12341234', $error));
|
||||
$this->assertEquals('error.captcha_invalid', $error, 'Get error.captcha_invalid, if passed wrong value');
|
||||
unset($error);
|
||||
|
||||
$validator->expects($this->once())
|
||||
->method('createClient')
|
||||
->will($this->returnValue($this->createMockGuzzleClient([
|
||||
'success' => false,
|
||||
'error-codes' => [
|
||||
'invalid-input-response', // The response parameter is invalid or malformed.
|
||||
],
|
||||
])));
|
||||
|
||||
expect($validator->validate('12341234', $error))->false();
|
||||
expect($error)->equals('error.captcha_invalid');
|
||||
});
|
||||
|
||||
$this->specify('Get error.captcha_invalid, if passed wrong value', function() {
|
||||
/** @var \PHPUnit_Framework_MockObject_MockObject|Validator $validator */
|
||||
$validator = $this->getMockBuilder(Validator::class)
|
||||
->setMethods(['createClient'])
|
||||
->getMock();
|
||||
|
||||
$validator->expects($this->once())
|
||||
->method('createClient')
|
||||
->will($this->returnValue($this->createMockGuzzleClient(['success' => true])));
|
||||
|
||||
expect($validator->validate('12341234', $error))->true();
|
||||
expect($error)->null();
|
||||
});
|
||||
}
|
||||
|
||||
private function createMockGuzzleClient(array $response) {
|
||||
$mock = new MockHandler([
|
||||
new Response(200, [], json_encode($response)),
|
||||
]);
|
||||
$handler = HandlerStack::create($mock);
|
||||
|
||||
return new Client(['handler' => $handler]);
|
||||
$mockClient = mock(ClientInterface::class);
|
||||
$mockClient->shouldReceive('request')->andReturn(new Response(200, [], json_encode([
|
||||
'success' => true,
|
||||
])));
|
||||
$validator = new Validator($mockClient);
|
||||
$this->assertTrue($validator->validate('12341234', $error));
|
||||
$this->assertNull($error);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ use api\components\ReCaptcha\Validator as ReCaptchaValidator;
|
||||
use api\models\authentication\ForgotPasswordForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\EmailActivation;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use OTPHP\TOTP;
|
||||
use tests\codeception\api\unit\TestCase;
|
||||
use tests\codeception\common\fixtures\AccountFixture;
|
||||
@ -16,7 +17,7 @@ class ForgotPasswordFormTest extends TestCase {
|
||||
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class extends ReCaptchaValidator {
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator {
|
||||
public function validateValue($value) {
|
||||
return null;
|
||||
}
|
||||
@ -31,17 +32,13 @@ class ForgotPasswordFormTest extends TestCase {
|
||||
}
|
||||
|
||||
public function testValidateLogin() {
|
||||
$this->specify('error.login_not_exist if login is invalid', function() {
|
||||
$model = new ForgotPasswordForm(['login' => 'unexist']);
|
||||
$model->validateLogin('login');
|
||||
expect($model->getErrors('login'))->equals(['error.login_not_exist']);
|
||||
});
|
||||
$model = new ForgotPasswordForm(['login' => 'unexist']);
|
||||
$model->validateLogin('login');
|
||||
$this->assertEquals(['error.login_not_exist'], $model->getErrors('login'), 'error.login_not_exist if login is invalid');
|
||||
|
||||
$this->specify('empty errors if login is exists', function() {
|
||||
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
|
||||
$model->validateLogin('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
});
|
||||
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
|
||||
$model->validateLogin('login');
|
||||
$this->assertEmpty($model->getErrors('login'), 'empty errors if login is exists');
|
||||
}
|
||||
|
||||
public function testValidateTotpToken() {
|
||||
@ -60,77 +57,60 @@ class ForgotPasswordFormTest extends TestCase {
|
||||
}
|
||||
|
||||
public function testValidateActivity() {
|
||||
$this->specify('error.account_not_activated if account is not confirmed', function() {
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $this->tester->grabFixture('accounts', 'not-activated-account')['username'],
|
||||
]);
|
||||
$model->validateActivity('login');
|
||||
expect($model->getErrors('login'))->equals(['error.account_not_activated']);
|
||||
});
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $this->tester->grabFixture('accounts', 'not-activated-account')['username'],
|
||||
]);
|
||||
$model->validateActivity('login');
|
||||
$this->assertEquals(['error.account_not_activated'], $model->getErrors('login'), 'expected error if account is not confirmed');
|
||||
|
||||
$this->specify('empty errors if login is exists', function() {
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
]);
|
||||
$model->validateLogin('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
});
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
]);
|
||||
$model->validateLogin('login');
|
||||
$this->assertEmpty($model->getErrors('login'), 'empty errors if login is exists');
|
||||
}
|
||||
|
||||
public function testValidateFrequency() {
|
||||
$this->specify('error.account_not_activated if recently was message', function() {
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => $this->tester->grabFixture('emailActivations', 'freshPasswordRecovery')['key'],
|
||||
]);
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => $this->tester->grabFixture('emailActivations', 'freshPasswordRecovery')['key'],
|
||||
]);
|
||||
$model->validateFrequency('login');
|
||||
$this->assertEquals(['error.recently_sent_message'], $model->getErrors('login'), 'error.account_not_activated if recently was message');
|
||||
|
||||
$model->validateFrequency('login');
|
||||
expect($model->getErrors('login'))->equals(['error.recently_sent_message']);
|
||||
});
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => $this->tester->grabFixture('emailActivations', 'oldPasswordRecovery')['key'],
|
||||
]);
|
||||
$model->validateFrequency('login');
|
||||
$this->assertEmpty($model->getErrors('login'), 'empty errors if email was sent a long time ago');
|
||||
|
||||
$this->specify('empty errors if email was sent a long time ago', function() {
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => $this->tester->grabFixture('emailActivations', 'oldPasswordRecovery')['key'],
|
||||
]);
|
||||
|
||||
$model->validateFrequency('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
});
|
||||
|
||||
$this->specify('empty errors if previous confirmation model not founded', function() {
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => 'invalid-key',
|
||||
]);
|
||||
|
||||
$model->validateFrequency('login');
|
||||
expect($model->getErrors('login'))->isEmpty();
|
||||
});
|
||||
$model = $this->createModel([
|
||||
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
|
||||
'key' => 'invalid-key',
|
||||
]);
|
||||
$model->validateFrequency('login');
|
||||
$this->assertEmpty($model->getErrors('login'), 'empty errors if previous confirmation model not founded');
|
||||
}
|
||||
|
||||
public function testForgotPassword() {
|
||||
$this->specify('successfully send message with restore password key', function() {
|
||||
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
|
||||
expect($model->forgotPassword())->true();
|
||||
expect($model->getEmailActivation())->notNull();
|
||||
$this->tester->canSeeEmailIsSent(1);
|
||||
});
|
||||
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
|
||||
$this->assertTrue($model->forgotPassword(), 'form should be successfully processed');
|
||||
$this->assertInstanceOf(EmailActivation::class, $model->getEmailActivation(), 'getEmailActivation should return valid object instance');
|
||||
$this->tester->canSeeEmailIsSent(1);
|
||||
}
|
||||
|
||||
public function testForgotPasswordResend() {
|
||||
$this->specify('successfully renew and send message with restore password key', function() {
|
||||
$fixture = $this->tester->grabFixture('accounts', 'account-with-expired-forgot-password-message');
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $fixture['username'],
|
||||
]);
|
||||
$callTime = time();
|
||||
expect($model->forgotPassword())->true();
|
||||
$emailActivation = $model->getEmailActivation();
|
||||
expect($emailActivation)->notNull();
|
||||
expect($emailActivation->created_at)->greaterOrEquals($callTime);
|
||||
$this->tester->canSeeEmailIsSent(1);
|
||||
});
|
||||
$fixture = $this->tester->grabFixture('accounts', 'account-with-expired-forgot-password-message');
|
||||
$model = new ForgotPasswordForm([
|
||||
'login' => $fixture['username'],
|
||||
]);
|
||||
$callTime = time();
|
||||
$this->assertTrue($model->forgotPassword(), 'form should be successfully processed');
|
||||
$emailActivation = $model->getEmailActivation();
|
||||
$this->assertInstanceOf(EmailActivation::class, $emailActivation);
|
||||
$this->assertGreaterThanOrEqual($callTime, $emailActivation->created_at);
|
||||
$this->tester->canSeeEmailIsSent(1);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -7,6 +7,7 @@ use Codeception\Specify;
|
||||
use common\models\Account;
|
||||
use common\models\EmailActivation;
|
||||
use common\models\UsernameHistory;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use tests\codeception\api\unit\TestCase;
|
||||
use tests\codeception\common\fixtures\AccountFixture;
|
||||
use Yii;
|
||||
@ -19,7 +20,7 @@ class RegistrationFormTest extends TestCase {
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
$this->mockRequest();
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class extends ReCaptchaValidator {
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator {
|
||||
public function validateValue($value) {
|
||||
return null;
|
||||
}
|
||||
@ -108,8 +109,6 @@ class RegistrationFormTest extends TestCase {
|
||||
$this->tester->canSeeEmailIsSent(1);
|
||||
}
|
||||
|
||||
// TODO: там в самой форме есть метод sendMail(), который рано или поздно должен переехать. К нему нужны будут тоже тесты
|
||||
|
||||
private function mockRequest($ip = '88.225.20.236') {
|
||||
$request = $this->getMockBuilder(Request::class)
|
||||
->setMethods(['getUserIP'])
|
||||
|
@ -5,6 +5,7 @@ use api\components\ReCaptcha\Validator as ReCaptchaValidator;
|
||||
use api\models\authentication\RepeatAccountActivationForm;
|
||||
use Codeception\Specify;
|
||||
use common\models\EmailActivation;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use tests\codeception\api\unit\TestCase;
|
||||
use tests\codeception\common\fixtures\AccountFixture;
|
||||
use tests\codeception\common\fixtures\EmailActivationFixture;
|
||||
@ -15,7 +16,7 @@ class RepeatAccountActivationFormTest extends TestCase {
|
||||
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class extends ReCaptchaValidator {
|
||||
Yii::$container->set(ReCaptchaValidator::class, new class(mock(ClientInterface::class)) extends ReCaptchaValidator {
|
||||
public function validateValue($value) {
|
||||
return null;
|
||||
}
|
||||
|
@ -1,4 +1,7 @@
|
||||
<?php
|
||||
use api\components\ReCaptcha\Validator;
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
return [
|
||||
'components' => [
|
||||
'user' => [
|
||||
@ -17,4 +20,15 @@ return [
|
||||
'params' => [
|
||||
'authserverHost' => 'authserver.ely.by',
|
||||
],
|
||||
'container' => [
|
||||
'definitions' => [
|
||||
Validator::class => function() {
|
||||
return new class(new Client()) extends Validator {
|
||||
protected function validateValue($value) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
},
|
||||
],
|
||||
],
|
||||
];
|
||||
|
Loading…
Reference in New Issue
Block a user