Rework tests structure. Upgrade codeception to 2.5.3. Merge params configuration into app configuration.

This commit is contained in:
ErickSkrauch
2019-02-20 22:58:52 +03:00
parent 2eacc581be
commit b05dc6816e
248 changed files with 1503 additions and 1339 deletions

View File

@@ -0,0 +1,22 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\AcceptRulesForm;
use common\models\Account;
use api\tests\unit\TestCase;
use const common\LATEST_RULES_VERSION;
class AcceptRulesFormTest extends TestCase {
public function testAgreeWithLatestRules() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->rules_agreement_version = LATEST_RULES_VERSION - 1;
$model = new AcceptRulesForm($account);
$this->assertTrue($model->performAction());
$this->assertEquals(LATEST_RULES_VERSION, $account->rules_agreement_version);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\ChangeEmailForm;
use common\models\Account;
use common\models\EmailActivation;
use api\tests\unit\TestCase;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\EmailActivationFixture;
class ChangeEmailFormTest extends TestCase {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testChangeEmail() {
/** @var Account $account */
$account = Account::findOne($this->getAccountId());
$newEmailConfirmationFixture = $this->tester->grabFixture('emailActivations', 'newEmailConfirmation');
$model = new ChangeEmailForm($account, [
'key' => $newEmailConfirmationFixture['key'],
]);
$this->assertTrue($model->performAction());
$this->assertNull(EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]));
/** @noinspection UnserializeExploitsInspection */
$data = unserialize($newEmailConfirmationFixture['_data']);
$this->assertEquals($data['newEmail'], $account->email);
}
private function getAccountId() {
return $this->tester->grabFixture('accounts', 'account-with-change-email-finish-state')['id'];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\ChangeLanguageForm;
use common\models\Account;
use api\tests\unit\TestCase;
class ChangeLanguageFormTest extends TestCase {
public function testApplyLanguage() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$model = new ChangeLanguageForm($account);
$model->lang = 'ru';
$this->assertTrue($model->performAction());
$this->assertEquals('ru', $account->lang);
}
}

View File

@@ -0,0 +1,139 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\modules\accounts\models\ChangePasswordForm;
use common\components\UserPass;
use common\helpers\Error as E;
use common\models\Account;
use api\tests\unit\TestCase;
use Yii;
use yii\db\Transaction;
class ChangePasswordFormTest extends TestCase {
public function testValidatePasswordAndRePasswordMatch() {
$account = new Account();
$account->setPassword('12345678');
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
'newRePassword' => 'another-password',
]);
$model->validatePasswordAndRePasswordMatch('newRePassword');
$this->assertEquals(
[E::NEW_RE_PASSWORD_DOES_NOT_MATCH],
$model->getErrors('newRePassword'),
'error.rePassword_does_not_match expected if passwords not match'
);
$account = new Account();
$account->setPassword('12345678');
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$model->validatePasswordAndRePasswordMatch('newRePassword');
$this->assertEmpty($model->getErrors('newRePassword'), 'no errors expected if passwords are valid');
// this is very important, because password change flow may be combined of two steps
// therefore we need to validate password sameness before we will validate current account password
$account = new Account();
$account->setPassword('12345678');
$model = new ChangePasswordForm($account, [
'newPassword' => 'my-new-password',
'newRePassword' => 'another-password',
]);
$model->validate();
$this->assertEquals(
[E::NEW_RE_PASSWORD_DOES_NOT_MATCH],
$model->getErrors('newRePassword'),
'error.rePassword_does_not_match expected even if there are errors on other attributes'
);
$this->assertEmpty($model->getErrors('password'));
}
public function testPerformAction() {
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component->shouldNotReceive('terminateSessions');
Yii::$app->set('user', $component);
$transaction = mock(Transaction::class . '[commit]');
$transaction->shouldReceive('commit');
$connection = mock(Yii::$app->db);
$connection->shouldReceive('beginTransaction')->andReturn($transaction);
Yii::$app->set('db', $connection);
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->setPassword('password_0');
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$callTime = time();
$this->assertTrue($model->performAction(), 'successfully change password with modern hash strategy');
$this->assertTrue($account->validatePassword('my-new-password'), 'new password should be successfully stored into account');
$this->assertGreaterThanOrEqual($callTime, $account->password_changed_at, 'password change time updated');
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->email = 'mock@ely.by';
$account->password_hash_strategy = Account::PASS_HASH_STRATEGY_OLD_ELY;
$account->password_hash = UserPass::make($account->email, '12345678');
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
]);
$callTime = time();
$this->assertTrue($model->performAction(), 'successfully change password with legacy hash strategy');
$this->assertTrue($account->validatePassword('my-new-password'));
$this->assertGreaterThanOrEqual($callTime, $account->password_changed_at);
$this->assertEquals(Account::PASS_HASH_STRATEGY_YII2, $account->password_hash_strategy);
}
public function testPerformActionWithLogout() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->setPassword('password_0');
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component->shouldReceive('terminateSessions')->once()->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
'newRePassword' => 'my-new-password',
'logoutAll' => true,
]);
$this->assertTrue($model->performAction());
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\ChangeUsernameForm;
use common\models\Account;
use common\models\UsernameHistory;
use common\tasks\PullMojangUsername;
use api\tests\unit\TestCase;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\UsernameHistoryFixture;
class ChangeUsernameFormTest extends TestCase {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'history' => UsernameHistoryFixture::class,
];
}
public function testPerformAction() {
$model = new ChangeUsernameForm($this->getAccount(), [
'password' => 'password_0',
'username' => 'my_new_nickname',
]);
$this->assertTrue($model->performAction());
$this->assertEquals('my_new_nickname', Account::findOne($this->getAccountId())->username);
$this->assertInstanceOf(UsernameHistory::class, UsernameHistory::findOne(['username' => 'my_new_nickname']));
/** @var PullMojangUsername $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(PullMojangUsername::class, $job);
$this->assertSame($job->username, 'my_new_nickname');
}
public function testPerformActionWithTheSameUsername() {
$account = $this->getAccount();
$username = $account->username;
$model = new ChangeUsernameForm($account, [
'password' => 'password_0',
'username' => $username,
]);
$callTime = time();
$this->assertTrue($model->performAction());
$this->assertNull(UsernameHistory::findOne([
'AND',
'username' => $username,
['>=', 'applied_in', $callTime],
]), 'no new UsernameHistory record, if we don\'t change username');
$this->assertNull($this->tester->grabLastQueuedJob());
}
public function testPerformActionWithChangeCase() {
$newUsername = mb_strtoupper($this->tester->grabFixture('accounts', 'admin')['username']);
$model = new ChangeUsernameForm($this->getAccount(), [
'password' => 'password_0',
'username' => $newUsername,
]);
$this->assertTrue($model->performAction());
$this->assertEquals($newUsername, Account::findOne($this->getAccountId())->username);
$this->assertInstanceOf(
UsernameHistory::class,
UsernameHistory::findOne(['username' => $newUsername]),
'username should change, if we change case of some letters'
);
/** @var PullMojangUsername $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(PullMojangUsername::class, $job);
$this->assertSame($job->username, $newUsername);
}
private function getAccount(): Account {
return $this->tester->grabFixture('accounts', 'admin');
}
private function getAccountId() {
return $this->getAccount()->id;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\DisableTwoFactorAuthForm;
use common\helpers\Error as E;
use common\models\Account;
use api\tests\unit\TestCase;
class DisableTwoFactorAuthFormTest extends TestCase {
public function testPerformAction() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class)->makePartial();
$account->shouldReceive('save')->once()->andReturn(true);
$account->is_otp_enabled = true;
$account->otp_secret = 'mock secret';
/** @var DisableTwoFactorAuthForm|\Mockery\MockInterface $model */
$model = mock(DisableTwoFactorAuthForm::class . '[validate]', [$account]);
$model->shouldReceive('validate')->once()->andReturn(true);
$this->assertTrue($model->performAction());
$this->assertNull($account->otp_secret);
$this->assertFalse($account->is_otp_enabled);
}
public function testValidateOtpEnabled() {
$account = new Account();
$account->is_otp_enabled = false;
$model = new DisableTwoFactorAuthForm($account);
$model->validateOtpEnabled('account');
$this->assertEquals([E::OTP_NOT_ENABLED], $model->getErrors('account'));
$account = new Account();
$account->is_otp_enabled = true;
$model = new DisableTwoFactorAuthForm($account);
$model->validateOtpEnabled('account');
$this->assertEmpty($model->getErrors('account'));
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\modules\accounts\models\EnableTwoFactorAuthForm;
use common\helpers\Error as E;
use common\models\Account;
use api\tests\unit\TestCase;
use Yii;
class EnableTwoFactorAuthFormTest extends TestCase {
public function testPerformAction() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->is_otp_enabled = false;
$account->otp_secret = 'mock secret';
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
]]);
$component->shouldReceive('terminateSessions')->withArgs([$account, Component::KEEP_CURRENT_SESSION]);
Yii::$app->set('user', $component);
/** @var EnableTwoFactorAuthForm|\Mockery\MockInterface $model */
$model = mock(EnableTwoFactorAuthForm::class . '[validate]', [$account]);
$model->shouldReceive('validate')->andReturn(true);
$this->assertTrue($model->performAction());
$this->assertTrue($account->is_otp_enabled);
}
public function testValidateOtpDisabled() {
$account = new Account();
$account->is_otp_enabled = true;
$model = new EnableTwoFactorAuthForm($account);
$model->validateOtpDisabled('account');
$this->assertEquals([E::OTP_ALREADY_ENABLED], $model->getErrors('account'));
$account = new Account();
$account->is_otp_enabled = false;
$model = new EnableTwoFactorAuthForm($account);
$model->validateOtpDisabled('account');
$this->assertEmpty($model->getErrors('account'));
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\SendEmailVerificationForm;
use common\models\Account;
use common\models\confirmations\CurrentEmailConfirmation;
use common\models\EmailActivation;
use common\tasks\SendCurrentEmailConfirmation;
use api\tests\unit\TestCase;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\EmailActivationFixture;
class SendEmailVerificationFormTest extends TestCase {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testCreateCode() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new SendEmailVerificationForm($account);
$activationModel = $model->createCode();
$this->assertInstanceOf(CurrentEmailConfirmation::class, $activationModel);
$this->assertEquals($account->id, $activationModel->account_id);
$this->assertNotNull(EmailActivation::findOne($activationModel->key));
}
public function testSendCurrentEmailConfirmation() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new SendEmailVerificationForm($account, [
'password' => 'password_0',
]);
$this->assertTrue($model->performAction());
/** @var EmailActivation $activation */
$activation = EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION,
]);
$this->assertInstanceOf(EmailActivation::class, $activation);
/** @var SendCurrentEmailConfirmation $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(SendCurrentEmailConfirmation::class, $job);
$this->assertSame($account->username, $job->username);
$this->assertSame($account->email, $job->email);
$this->assertSame($activation->key, $job->code);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\SendNewEmailVerificationForm;
use common\models\Account;
use common\models\confirmations\NewEmailConfirmation;
use common\models\EmailActivation;
use common\tasks\SendNewEmailConfirmation;
use api\tests\unit\TestCase;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\EmailActivationFixture;
use common\tests\helpers\Mock;
use yii\validators\EmailValidator;
class SendNewEmailVerificationFormTest extends TestCase {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testCreateCode() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new SendNewEmailVerificationForm($account);
$model->email = 'my-new-email@ely.by';
$activationModel = $model->createCode();
$this->assertInstanceOf(NewEmailConfirmation::class, $activationModel);
$this->assertEquals($account->id, $activationModel->account_id);
$this->assertEquals($model->email, $activationModel->newEmail);
$this->assertNotNull(EmailActivation::findOne($activationModel->key));
}
public function testSendNewEmailConfirmation() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'account-with-change-email-init-state');
/** @var SendNewEmailVerificationForm $model */
$key = $this->tester->grabFixture('emailActivations', 'currentChangeEmailConfirmation')['key'];
$model = new SendNewEmailVerificationForm($account, [
'key' => $key,
'email' => 'my-new-email@ely.by',
]);
Mock::func(EmailValidator::class, 'checkdnsrr')->andReturn(true);
$this->assertTrue($model->performAction());
$this->assertNull(EmailActivation::findOne($key));
/** @var EmailActivation $activation */
$activation = EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]);
$this->assertNotNull(EmailActivation::class, $activation);
/** @var SendNewEmailConfirmation $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(SendNewEmailConfirmation::class, $job);
$this->assertSame($account->username, $job->username);
$this->assertSame('my-new-email@ely.by', $job->email);
$this->assertSame($activation->key, $job->code);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace api\tests\unit\modules\accounts\models;
use api\modules\accounts\models\TwoFactorAuthInfo;
use common\models\Account;
use api\tests\unit\TestCase;
class TwoFactorAuthInfoTest extends TestCase {
public function testGetCredentials() {
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->email = 'mock@email.com';
$account->otp_secret = null;
$model = new TwoFactorAuthInfo($account);
$result = $model->getCredentials();
$this->assertTrue(is_array($result));
$this->assertArrayHasKey('qr', $result);
$this->assertArrayHasKey('uri', $result);
$this->assertArrayHasKey('secret', $result);
$this->assertSame($account->otp_secret, $result['secret']);
$this->assertSame(strtoupper($account->otp_secret), $account->otp_secret);
$this->assertStringStartsWith('data:image/svg+xml,<?xml', $result['qr']);
$previous = libxml_use_internal_errors(true);
simplexml_load_string(base64_decode($result['qr']));
libxml_use_internal_errors($previous);
$this->assertEmpty(libxml_get_errors());
/** @var Account|\Mockery\MockInterface $account */
$account = mock(Account::class . '[save]');
$account->shouldReceive('save')->andReturn(true);
$account->email = 'mock@email.com';
$account->otp_secret = 'AAAA';
$model = new TwoFactorAuthInfo($account);
$result = $model->getCredentials();
$this->assertEquals('AAAA', $result['secret']);
}
}

View File

@@ -0,0 +1,141 @@
<?php
namespace codeception\api\unit\modules\authserver\models;
use api\models\authentication\LoginForm;
use api\modules\authserver\models\AuthenticateData;
use api\modules\authserver\models\AuthenticationForm;
use common\models\Account;
use common\models\MinecraftAccessKey;
use Ramsey\Uuid\Uuid;
use api\tests\unit\TestCase;
use common\tests\_support\ProtectedCaller;
use common\tests\fixtures\AccountFixture;
use common\tests\fixtures\MinecraftAccessKeyFixture;
class AuthenticationFormTest extends TestCase {
use ProtectedCaller;
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'minecraftAccessKeys' => MinecraftAccessKeyFixture::class,
];
}
/**
* @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException
* @expectedExceptionMessage Invalid credentials. Invalid nickname or password.
*/
public function testAuthenticateByWrongNicknamePass() {
$authForm = $this->createAuthForm();
$authForm->username = 'wrong-username';
$authForm->password = 'wrong-password';
$authForm->clientToken = Uuid::uuid4();
$authForm->authenticate();
}
/**
* @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException
* @expectedExceptionMessage Invalid credentials. Invalid email or password.
*/
public function testAuthenticateByWrongEmailPass() {
$authForm = $this->createAuthForm();
$authForm->username = 'wrong-email@ely.by';
$authForm->password = 'wrong-password';
$authForm->clientToken = Uuid::uuid4();
$authForm->authenticate();
}
/**
* @expectedException \api\modules\authserver\exceptions\ForbiddenOperationException
* @expectedExceptionMessage This account has been suspended.
*/
public function testAuthenticateByValidCredentialsIntoBlockedAccount() {
$authForm = $this->createAuthForm(Account::STATUS_BANNED);
$authForm->username = 'dummy';
$authForm->password = 'password_0';
$authForm->clientToken = Uuid::uuid4();
$authForm->authenticate();
}
public function testAuthenticateByValidCredentials() {
$authForm = $this->createAuthForm();
$minecraftAccessKey = new MinecraftAccessKey();
$minecraftAccessKey->access_token = Uuid::uuid4();
$authForm->expects($this->once())
->method('createMinecraftAccessToken')
->will($this->returnValue($minecraftAccessKey));
$authForm->username = 'dummy';
$authForm->password = 'password_0';
$authForm->clientToken = Uuid::uuid4();
$result = $authForm->authenticate();
$this->assertInstanceOf(AuthenticateData::class, $result);
$this->assertEquals($minecraftAccessKey->access_token, $result->getMinecraftAccessKey()->access_token);
}
public function testCreateMinecraftAccessToken() {
$authForm = new AuthenticationForm();
$authForm->clientToken = Uuid::uuid4();
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
/** @var MinecraftAccessKey $result */
$result = $this->callProtected($authForm, 'createMinecraftAccessToken', $account);
$this->assertInstanceOf(MinecraftAccessKey::class, $result);
$this->assertEquals($account->id, $result->account_id);
$this->assertEquals($authForm->clientToken, $result->client_token);
$this->assertInstanceOf(MinecraftAccessKey::class, MinecraftAccessKey::findOne($result->access_token));
}
public function testCreateMinecraftAccessTokenWithExistsClientId() {
$authForm = new AuthenticationForm();
$minecraftFixture = $this->tester->grabFixture('minecraftAccessKeys', 'admin-token');
$authForm->clientToken = $minecraftFixture['client_token'];
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
/** @var MinecraftAccessKey $result */
$result = $this->callProtected($authForm, 'createMinecraftAccessToken', $account);
$this->assertInstanceOf(MinecraftAccessKey::class, $result);
$this->assertEquals($account->id, $result->account_id);
$this->assertEquals($authForm->clientToken, $result->client_token);
$this->assertNull(MinecraftAccessKey::findOne($minecraftFixture['access_token']));
$this->assertInstanceOf(MinecraftAccessKey::class, MinecraftAccessKey::findOne($result->access_token));
}
private function createAuthForm($status = Account::STATUS_ACTIVE) {
/** @var LoginForm|\PHPUnit_Framework_MockObject_MockObject $loginForm */
$loginForm = $this->getMockBuilder(LoginForm::class)
->setMethods(['getAccount'])
->getMock();
$account = new Account();
$account->username = 'dummy';
$account->email = 'dummy@ely.by';
$account->status = $status;
$account->setPassword('password_0');
$loginForm->expects($this->any())
->method('getAccount')
->will($this->returnValue($account));
/** @var AuthenticationForm|\PHPUnit_Framework_MockObject_MockObject $authForm */
$authForm = $this->getMockBuilder(AuthenticationForm::class)
->setMethods(['createLoginForm', 'createMinecraftAccessToken'])
->getMock();
$authForm->expects($this->any())
->method('createLoginForm')
->will($this->returnValue($loginForm));
return $authForm;
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace codeception\api\unit\modules\authserver\validators;
use api\modules\authserver\validators\RequiredValidator;
use api\tests\unit\TestCase;
use common\tests\_support\ProtectedCaller;
class RequiredValidatorTest extends TestCase {
use ProtectedCaller;
public function testValidateValueNormal() {
$validator = new RequiredValidator();
$this->assertNull($this->callProtected($validator, 'validateValue', 'dummy'));
}
/**
* @expectedException \api\modules\authserver\exceptions\IllegalArgumentException
*/
public function testValidateValueEmpty() {
$validator = new RequiredValidator();
$this->assertNull($this->callProtected($validator, 'validateValue', ''));
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace api\tests\unit\modules\internal\models;
use api\modules\accounts\models\BanAccountForm;
use api\modules\internal\helpers\Error as E;
use common\models\Account;
use common\tasks\ClearAccountSessions;
use api\tests\unit\TestCase;
class BanFormTest extends TestCase {
public function testValidateAccountActivity() {
$account = new Account();
$account->status = Account::STATUS_ACTIVE;
$form = new BanAccountForm($account);
$form->validateAccountActivity();
$this->assertEmpty($form->getErrors('account'));
$account = new Account();
$account->status = Account::STATUS_BANNED;
$form = new BanAccountForm($account);
$form->validateAccountActivity();
$this->assertEquals([E::ACCOUNT_ALREADY_BANNED], $form->getErrors('account'));
}
public function testBan() {
/** @var Account|\PHPUnit_Framework_MockObject_MockObject $account */
$account = $this->getMockBuilder(Account::class)
->setMethods(['save'])
->getMock();
$account->expects($this->once())
->method('save')
->willReturn(true);
$model = new BanAccountForm($account);
$this->assertTrue($model->performAction());
$this->assertEquals(Account::STATUS_BANNED, $account->status);
/** @var ClearAccountSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearAccountSessions::class, $job);
$this->assertSame($job->accountId, $account->id);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace api\tests\unit\modules\internal\models;
use api\modules\accounts\models\PardonAccountForm;
use api\modules\internal\helpers\Error as E;
use common\models\Account;
use api\tests\unit\TestCase;
class PardonFormTest extends TestCase {
public function testValidateAccountBanned() {
$account = new Account();
$account->status = Account::STATUS_BANNED;
$form = new PardonAccountForm($account);
$form->validateAccountBanned();
$this->assertEmpty($form->getErrors('account'));
$account = new Account();
$account->status = Account::STATUS_ACTIVE;
$form = new PardonAccountForm($account);
$form->validateAccountBanned();
$this->assertEquals([E::ACCOUNT_NOT_BANNED], $form->getErrors('account'));
}
public function testPardon() {
/** @var Account|\PHPUnit_Framework_MockObject_MockObject $account */
$account = $this->getMockBuilder(Account::class)
->setMethods(['save'])
->getMock();
$account->expects($this->once())
->method('save')
->willReturn(true);
$account->status = Account::STATUS_BANNED;
$model = new PardonAccountForm($account);
$this->assertTrue($model->performAction());
$this->assertEquals(Account::STATUS_ACTIVE, $account->status);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\models\ApplicationType;
use common\models\OauthClient;
use api\tests\unit\TestCase;
class ApplicationTypeTest extends TestCase {
public function testApplyToClient(): void {
$model = new ApplicationType();
$model->name = 'Application name';
$model->websiteUrl = 'http://example.com';
$model->redirectUri = 'http://example.com/oauth/ely';
$model->description = 'Application description.';
$client = new OauthClient();
$model->applyToClient($client);
$this->assertSame('Application name', $client->name);
$this->assertSame('Application description.', $client->description);
$this->assertSame('http://example.com/oauth/ely', $client->redirect_uri);
$this->assertSame('http://example.com', $client->website_url);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\models\BaseOauthClientType;
use common\models\OauthClient;
use api\tests\unit\TestCase;
class BaseOauthClientTypeTest extends TestCase {
public function testApplyTyClient(): void {
$client = new OauthClient();
/** @var BaseOauthClientType|\Mockery\MockInterface $form */
$form = mock(BaseOauthClientType::class);
$form->makePartial();
$form->name = 'Application name';
$form->websiteUrl = 'http://example.com';
$form->applyToClient($client);
$this->assertSame('Application name', $client->name);
$this->assertSame('http://example.com', $client->website_url);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\models\MinecraftServerType;
use common\models\OauthClient;
use api\tests\unit\TestCase;
class MinecraftServerTypeTest extends TestCase {
public function testApplyToClient(): void {
$model = new MinecraftServerType();
$model->name = 'Server name';
$model->websiteUrl = 'http://example.com';
$model->minecraftServerIp = 'localhost:12345';
$client = new OauthClient();
$model->applyToClient($client);
$this->assertSame('Server name', $client->name);
$this->assertSame('http://example.com', $client->website_url);
$this->assertSame('localhost:12345', $client->minecraft_server_ip);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\models\ApplicationType;
use api\modules\oauth\models\MinecraftServerType;
use api\modules\oauth\models\OauthClientFormFactory;
use common\models\OauthClient;
use api\tests\unit\TestCase;
class OauthClientFormFactoryTest extends TestCase {
public function testCreate() {
$client = new OauthClient();
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Application name';
$client->description = 'Application description.';
$client->website_url = 'http://example.com';
$client->redirect_uri = 'http://example.com/oauth/ely';
/** @var ApplicationType $requestForm */
$requestForm = OauthClientFormFactory::create($client);
$this->assertInstanceOf(ApplicationType::class, $requestForm);
$this->assertSame('Application name', $requestForm->name);
$this->assertSame('Application description.', $requestForm->description);
$this->assertSame('http://example.com', $requestForm->websiteUrl);
$this->assertSame('http://example.com/oauth/ely', $requestForm->redirectUri);
$client = new OauthClient();
$client->type = OauthClient::TYPE_MINECRAFT_SERVER;
$client->name = 'Server name';
$client->website_url = 'http://example.com';
$client->minecraft_server_ip = 'localhost:12345';
/** @var MinecraftServerType $requestForm */
$requestForm = OauthClientFormFactory::create($client);
$this->assertInstanceOf(MinecraftServerType::class, $requestForm);
$this->assertSame('Server name', $requestForm->name);
$this->assertSame('http://example.com', $requestForm->websiteUrl);
$this->assertSame('localhost:12345', $requestForm->minecraftServerIp);
}
/**
* @expectedException \api\modules\oauth\exceptions\UnsupportedOauthClientType
*/
public function testCreateUnknownType() {
$client = new OauthClient();
$client->type = 'unknown-type';
OauthClientFormFactory::create($client);
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace api\tests\unit\modules\oauth\models;
use api\modules\oauth\models\OauthClientForm;
use api\modules\oauth\models\OauthClientTypeForm;
use common\models\OauthClient;
use common\tasks\ClearOauthSessions;
use api\tests\unit\TestCase;
class OauthClientFormTest extends TestCase {
public function testSave() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->shouldReceive('save')->andReturn(true);
$client->account_id = 1;
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Test application';
/** @var OauthClientForm|\Mockery\MockInterface $form */
$form = mock(OauthClientForm::class . '[isClientExists]', [$client]);
$form->shouldAllowMockingProtectedMethods();
$form->shouldReceive('isClientExists')
->times(3)
->andReturnValues([true, true, false]);
/** @var OauthClientTypeForm|\Mockery\MockInterface $requestType */
$requestType = mock(OauthClientTypeForm::class);
$requestType->shouldReceive('validate')->once()->andReturn(true);
$requestType->shouldReceive('applyToClient')->once()->withArgs([$client]);
$this->assertTrue($form->save($requestType));
$this->assertSame('test-application2', $client->id);
$this->assertNotNull($client->secret);
$this->assertSame(64, mb_strlen($client->secret));
}
public function testSaveUpdateExistsModel() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->shouldReceive('save')->andReturn(true);
$client->setIsNewRecord(false);
$client->id = 'application-id';
$client->secret = 'application_secret';
$client->account_id = 1;
$client->type = OauthClient::TYPE_APPLICATION;
$client->name = 'Application name';
$client->description = 'Application description';
$client->redirect_uri = 'http://example.com/oauth/ely';
$client->website_url = 'http://example.com';
/** @var OauthClientForm|\Mockery\MockInterface $form */
$form = mock(OauthClientForm::class . '[isClientExists]', [$client]);
$form->shouldAllowMockingProtectedMethods();
$form->shouldReceive('isClientExists')->andReturn(false);
$request = new class implements OauthClientTypeForm {
public function load($data): bool {
return true;
}
public function validate(): bool {
return true;
}
public function getValidationErrors(): array {
return [];
}
public function applyToClient(OauthClient $client): void {
$client->name = 'New name';
$client->description = 'New description.';
}
};
$this->assertTrue($form->save($request));
$this->assertSame('application-id', $client->id);
$this->assertSame('application_secret', $client->secret);
$this->assertSame('New name', $client->name);
$this->assertSame('New description.', $client->description);
$this->assertSame('http://example.com/oauth/ely', $client->redirect_uri);
$this->assertSame('http://example.com', $client->website_url);
}
public function testDelete() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->delete());
$this->assertTrue($form->getClient()->is_deleted);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertNull($job->notSince);
}
public function testReset() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->secret = 'initial_secret';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->reset());
$this->assertSame('initial_secret', $form->getClient()->secret);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertEquals(time(), $job->notSince, '', 2);
}
public function testResetWithSecret() {
/** @var OauthClient|\Mockery\MockInterface $client */
$client = mock(OauthClient::class . '[save]');
$client->id = 'mocked-id';
$client->secret = 'initial_secret';
$client->type = OauthClient::TYPE_APPLICATION;
$client->shouldReceive('save')->andReturn(true);
$form = new OauthClientForm($client);
$this->assertTrue($form->reset(true));
$this->assertNotSame('initial_secret', $form->getClient()->secret);
/** @var ClearOauthSessions $job */
$job = $this->tester->grabLastQueuedJob();
$this->assertInstanceOf(ClearOauthSessions::class, $job);
$this->assertSame('mocked-id', $job->clientId);
$this->assertEquals(time(), $job->notSince, '', 2);
}
}

View File

@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\modules\session\filters;
use api\modules\session\filters\RateLimiter;
use common\models\OauthClient;
use Faker\Provider\Internet;
use api\tests\unit\TestCase;
use Yii;
use yii\redis\Connection;
use yii\web\Request;
class RateLimiterTest extends TestCase {
public function testCheckRateLimiterWithOldAuthserver() {
/** @var Connection|\PHPUnit\Framework\MockObject\MockObject $redis */
$redis = $this->getMockBuilder(Connection::class)
->setMethods(['executeCommand'])
->getMock();
$redis->expects($this->never())
->method('executeCommand');
Yii::$app->set('redis', $redis);
/** @var RateLimiter|\PHPUnit\Framework\MockObject\MockObject $filter */
$filter = $this->getMockBuilder(RateLimiter::class)
->setConstructorArgs([[
'authserverDomain' => 'authserver.ely.by',
]])
->setMethods(['getServer'])
->getMock();
$filter->method('getServer')
->willReturn(new OauthClient());
$filter->checkRateLimit(null, new Request(), null, null);
}
public function testCheckRateLimiterWithValidServerId() {
/** @var Connection|\PHPUnit\Framework\MockObject\MockObject $redis */
$redis = $this->getMockBuilder(Connection::class)
->setMethods(['executeCommand'])
->getMock();
$redis->expects($this->never())
->method('executeCommand');
Yii::$app->set('redis', $redis);
/** @var Request|\PHPUnit\Framework\MockObject\MockObject $request */
$request = $this->getMockBuilder(Request::class)
->setMethods(['getHostInfo'])
->getMock();
$request->method('getHostInfo')
->willReturn('http://authserver.ely.by');
$filter = new RateLimiter([
'authserverDomain' => 'authserver.ely.by',
]);
$filter->checkRateLimit(null, $request, null, null);
}
/**
* @expectedException \yii\web\TooManyRequestsHttpException
*/
public function testCheckRateLimiter() {
/** @var Connection|\PHPUnit\Framework\MockObject\MockObject $redis */
$redis = $this->getMockBuilder(Connection::class)
->setMethods(['executeCommand'])
->getMock();
$redis->expects($this->exactly(5))
->method('executeCommand')
->will($this->onConsecutiveCalls('1', '1', '2', '3', '4'));
Yii::$app->set('redis', $redis);
/** @var Request|\PHPUnit\Framework\MockObject\MockObject $request */
$request = $this->getMockBuilder(Request::class)
->setMethods(['getUserIP'])
->getMock();
$request->method('getUserIp')
->willReturn(Internet::localIpv4());
/** @var RateLimiter|\PHPUnit\Framework\MockObject\MockObject $filter */
$filter = $this->getMockBuilder(RateLimiter::class)
->setConstructorArgs([[
'limit' => 3,
'authserverDomain' => 'authserver.ely.by',
]])
->setMethods(['getServer'])
->getMock();
$filter->method('getServer')
->willReturn(null);
for ($i = 0; $i < 5; $i++) {
$filter->checkRateLimit(null, $request, null, null);
}
}
}