Merge branch 'tests_refactoring' into develop

This commit is contained in:
ErickSkrauch 2016-11-01 19:49:14 +03:00
commit 91db572411
64 changed files with 689 additions and 852 deletions

View File

@ -17,7 +17,7 @@ class ConfirmEmailForm extends KeyConfirmationForm {
}
$confirmModel = $this->getActivationCodeModel();
if ($confirmModel->type != EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION) {
if ($confirmModel->type !== EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION) {
$confirmModel->delete();
// TODO: вот где-то здесь нужно ещё попутно сгенерировать соответствующую ошибку
return false;
@ -31,7 +31,7 @@ class ConfirmEmailForm extends KeyConfirmationForm {
throw new ErrorException('Unable remove activation key.');
}
if (!$account->save()) {
if (!$account->save(false)) {
throw new ErrorException('Unable activate user account.');
}

View File

@ -77,7 +77,7 @@ class ChangePasswordForm extends ApiForm {
}
}
if (!$account->save()) {
if (!$account->save(false)) {
throw new ErrorException('Cannot save user model');
}

View File

@ -32,7 +32,7 @@ class ApiController extends Controller {
// ник пользователь не сменил его на нечто иное
$account = null;
if ($record !== null) {
if ($record->findNext($at) !== null || $record->account->username === $record->username) {
if ($record->account->username === $record->username || $record->findNext($at) !== null) {
$account = $record->account;
}
}

View File

@ -4,7 +4,7 @@ namespace common\components\Mojang;
use common\components\Mojang\exceptions\MojangApiException;
use common\components\Mojang\exceptions\NoContentException;
use common\components\Mojang\response\UsernameToUUIDResponse;
use GuzzleHttp\Client as GuzzleClient;
use Yii;
class Api {
@ -23,7 +23,7 @@ class Api {
$query['atTime'] = $atTime;
}
$response = $this->createClient()->get($this->buildUsernameToUUIDRoute($username), $query);
$response = $this->getClient()->get($this->buildUsernameToUUIDRoute($username), $query);
if ($response->getStatusCode() === 204) {
throw new NoContentException('Username not found');
} elseif ($response->getStatusCode() !== 200) {
@ -40,8 +40,11 @@ class Api {
return $responseObj;
}
protected function createClient() {
return new GuzzleClient();
/**
* @return \GuzzleHttp\Client
*/
protected function getClient() {
return Yii::$app->guzzle;
}
protected function buildUsernameToUUIDRoute($username) {

View File

@ -9,7 +9,7 @@ class UserFriendlyRandomKey {
$numChars = strlen($chars);
$key = '';
for ($i = 0; $i < $length; $i++) {
$key .= substr($chars, rand(1, $numChars) - 1, 1);
$key .= $chars[random_int(0, $numChars - 1)];
}
return $key;

View File

@ -54,7 +54,7 @@ class AuthCodeStorage extends AbstractStorage implements AuthCodeInterface {
* @inheritdoc
*/
public function getScopes(OriginalAuthCodeEntity $token) {
$result = (new Set($this->dataTable, $token->getId(), 'scopes'));
$result = new Set($this->dataTable, $token->getId(), 'scopes');
$response = [];
foreach ($result as $scope) {
// TODO: нужно проверить все выданные скоупы на их существование

View File

@ -2,10 +2,9 @@
namespace common\components\oauth\Util\KeyAlgorithm;
use League\OAuth2\Server\Util\KeyAlgorithm\DefaultAlgorithm;
use League\OAuth2\Server\Util\KeyAlgorithm\KeyAlgorithmInterface;
use Ramsey\Uuid\Uuid;
class UuidAlgorithm extends DefaultAlgorithm implements KeyAlgorithmInterface {
class UuidAlgorithm extends DefaultAlgorithm {
/**
* @inheritdoc

View File

@ -2,7 +2,6 @@
namespace common\helpers;
use common\components\RabbitMQ\Helper;
use Yii;
class Amqp extends Helper {

View File

@ -1,9 +1,10 @@
<?php
use yii\helpers\Html;
/**
* @var $this \yii\web\View view component instance
* @var $message \yii\mail\MessageInterface the message being composed
* @var $content string main view render result
*/
/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<?php $this->beginBody() ?>

View File

@ -1,7 +1,6 @@
<?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
/**

View File

@ -2,7 +2,6 @@
namespace common\models;
use common\components\redis\Set;
use Yii;
use yii\db\ActiveRecord;
/**
@ -38,7 +37,7 @@ class OauthSession extends ActiveRecord {
}
public function getScopes() {
return new Set($this->getDb()->getSchema()->getRawTableName($this->tableName()), $this->id, 'scopes');
return new Set(static::getDb()->getSchema()->getRawTableName(static::tableName()), $this->id, 'scopes');
}
public function beforeDelete() {

View File

@ -2,6 +2,8 @@
namespace common\models;
use common\components\SkinSystem\Api as SkinSystemApi;
use DateInterval;
use DateTime;
class Textures {
@ -38,7 +40,7 @@ class Textures {
public function getTexturesValue($encrypted = true) {
$array = [
'timestamp' => time() + 60 * 60 * 24 * 2,
'timestamp' => (new DateTime())->add(new DateInterval('P2D'))->getTimestamp(),
'profileId' => str_replace('-', '', $this->account->uuid),
'profileName' => $this->account->username,
'textures' => $this->getTextures(),
@ -51,7 +53,7 @@ class Textures {
if (!$encrypted) {
return $array;
} else {
return $this->encrypt($array);
return static::encrypt($array);
}
}

View File

@ -37,7 +37,7 @@ class AccountQueueController extends AmqpController {
}
public function routeUsernameChanged(UsernameChanged $body) {
$mojangApi = new MojangApi();
$mojangApi = $this->createMojangApi();
try {
$response = $mojangApi->usernameToUUID($body->newUsername);
} catch (NoContentException $e) {
@ -68,4 +68,11 @@ class AccountQueueController extends AmqpController {
return true;
}
/**
* @return MojangApi
*/
protected function createMojangApi() : MojangApi {
return new MojangApi();
}
}

View File

@ -12,6 +12,7 @@ modules:
config:
Yii2:
configFile: '../config/api/functional.php'
cleanup: true
Redis:
host: testredis
port: 6379

View File

@ -1,7 +1,6 @@
<?php
namespace tests\codeception\api\functional;
use Codeception\Specify;
use tests\codeception\api\_pages\AccountsRoute;
use tests\codeception\api\FunctionalTester;

View File

@ -1,4 +1 @@
<?php
new yii\web\Application(require __DIR__ . '/../../config/api/functional.php');
\Codeception\Util\Autoload::registerSuffix('Steps', __DIR__ . DIRECTORY_SEPARATOR);

View File

@ -1 +1,8 @@
class_name: UnitTester
modules:
enabled:
- Yii2:
part: [orm, email, fixtures]
config:
Yii2:
configFile: '../config/api/unit.php'

View File

@ -1,9 +0,0 @@
<?php
namespace tests\codeception\api\unit;
class DbTestCase extends \yii\codeception\DbTestCase {
public $appConfig = '@tests/codeception/config/api/unit.php';
}

View File

@ -1,9 +1,22 @@
<?php
namespace tests\codeception\api\unit;
class TestCase extends \Codeception\Test\Unit {
class TestCase extends \yii\codeception\TestCase {
/**
* @var \tests\codeception\api\UnitTester
*/
protected $tester;
public $appConfig = '@tests/codeception/config/api/unit.php';
/**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
*
* @url http://codeception.com/docs/modules/Yii2#fixtures
*
* @return array
*/
public function _fixtures() {
return [];
}
}

View File

@ -11,7 +11,7 @@ use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Claim\ClaimInterface;
use Emarref\Jwt\Claim\Expiration;
use Emarref\Jwt\Token;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
@ -19,11 +19,7 @@ use Yii;
use yii\web\HeaderCollection;
use yii\web\Request;
/**
* @property AccountFixture $accounts
* @property AccountSessionFixture $sessions
*/
class ComponentTest extends DbTestCase {
class ComponentTest extends TestCase {
use Specify;
use ProtectedCaller;
@ -37,7 +33,7 @@ class ComponentTest extends DbTestCase {
$this->component = new Component($this->getComponentArguments());
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'sessions' => AccountSessionFixture::class,
@ -62,7 +58,7 @@ class ComponentTest extends DbTestCase {
$this->specify('success get LoginResult object with session value if rememberMe is true', function() {
/** @var AccountIdentity $account */
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
$account = AccountIdentity::findOne($this->tester->grabFixture('accounts', 'admin')['id']);
$result = $this->component->login($account, true);
expect($result)->isInstanceOf(LoginResult::class);
expect($result->getSession())->isInstanceOf(AccountSession::class);
@ -82,7 +78,7 @@ class ComponentTest extends DbTestCase {
$userIP = '192.168.0.1';
$this->mockRequest($userIP);
/** @var AccountSession $session */
$session = AccountSession::findOne($this->sessions['admin']['id']);
$session = AccountSession::findOne($this->tester->grabFixture('sessions', 'admin')['id']);
$callTime = time();
$result = $this->component->renew($session);
expect($result)->isInstanceOf(RenewResult::class);
@ -108,7 +104,7 @@ class ComponentTest extends DbTestCase {
public function testGetActiveSession() {
$this->specify('get used account session', function() {
/** @var AccountIdentity $identity */
$identity = AccountIdentity::findOne($this->accounts['admin']['id']);
$identity = AccountIdentity::findOne($this->tester->grabFixture('accounts', 'admin')['id']);
$result = $this->component->login($identity, true);
$this->component->logout();
@ -184,6 +180,7 @@ class ComponentTest extends DbTestCase {
}
/**
* @param string $userIP
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function mockRequest($userIP = '127.0.0.1') {

View File

@ -7,8 +7,8 @@ use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use const common\LATEST_RULES_VERSION;
use yii\base\Action;
use const common\LATEST_RULES_VERSION;
class ActiveUserRuleTest extends TestCase {
use Specify;

View File

@ -7,7 +7,7 @@ use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
use Yii;
@ -16,11 +16,11 @@ use yii\web\IdentityInterface;
/**
* @property AccountIdentity $accounts
*/
class AccountIdentityTest extends DbTestCase {
class AccountIdentityTest extends TestCase {
use Specify;
use ProtectedCaller;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
];
@ -29,7 +29,7 @@ class AccountIdentityTest extends DbTestCase {
public function testFindIdentityByAccessToken() {
$identity = AccountIdentity::findIdentityByAccessToken($this->generateToken());
$this->assertInstanceOf(IdentityInterface::class, $identity);
$this->assertEquals($this->accounts['admin']['id'], $identity->getId());
$this->assertEquals($this->tester->grabFixture('accounts', 'admin')['id'], $identity->getId());
}
/**
@ -42,7 +42,7 @@ class AccountIdentityTest extends DbTestCase {
$token->addClaim(new Claim\Issuer('http://localhost'));
$token->addClaim(new Claim\IssuedAt(1464593193));
$token->addClaim(new Claim\Expiration(1464596793));
$token->addClaim(new Claim\JwtId($this->accounts['admin']['id']));
$token->addClaim(new Claim\JwtId($this->tester->grabFixture('accounts', 'admin')['id']));
$expiredToken = (new Jwt())->serialize($token, EncryptionFactory::create(Yii::$app->user->getAlgorithm()));
AccountIdentity::findIdentityByAccessToken($expiredToken);
@ -60,7 +60,7 @@ class AccountIdentityTest extends DbTestCase {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
/** @var AccountIdentity $account */
$account = AccountIdentity::findOne($this->accounts['admin']['id']);
$account = AccountIdentity::findOne($this->tester->grabFixture('accounts', 'admin')['id']);
$token = $this->callProtected($component, 'createToken', $account);

View File

@ -2,76 +2,48 @@
namespace codeception\api\unit\models;
use api\models\FeedbackForm;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\TestCase;
use Yii;
use yii\swiftmailer\Message;
class FeedbackFormTest extends TestCase {
use Specify;
const FILE_NAME = 'testing_message.eml';
public function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function() {
return self::FILE_NAME;
};
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function testSendMessage() {
$this->specify('send email', function() {
$model = new FeedbackForm([
$model = new FeedbackForm([
'subject' => 'Тема обращения',
'email' => 'erickskrauch@ely.by',
'message' => 'Привет мир!',
]);
$this->assertTrue($model->sendMessage());
$this->tester->seeEmailIsSent(1, 'message file exists');
}
public function testSendMessageWithEmail() {
/** @var FeedbackForm|\PHPUnit_Framework_MockObject_MockObject $model */
$model = $this->getMockBuilder(FeedbackForm::class)
->setMethods(['getAccount'])
->setConstructorArgs([[
'subject' => 'Тема обращения',
'email' => 'erickskrauch@ely.by',
'message' => 'Привет мир!',
]);
expect($model->sendMessage())->true();
expect_file('message file exists', $this->getMessageFile())->exists();
});
]])
->getMock();
$this->specify('send email with user info', function() {
/** @var FeedbackForm|\PHPUnit_Framework_MockObject_MockObject $model */
$model = $this->getMockBuilder(FeedbackForm::class)
->setMethods(['getAccount'])
->setConstructorArgs([[
'subject' => 'Тема обращения',
'email' => 'erickskrauch@ely.by',
'message' => 'Привет мир!',
]])
->getMock();
$model
->expects($this->any())
->method('getAccount')
->will($this->returnValue(new Account([
'id' => '123',
'username' => 'Erick',
'email' => 'find-this@email.net',
'created_at' => time() - 86400,
])));
expect($model->sendMessage())->true();
expect_file('message file exists', $this->getMessageFile())->exists();
$data = file_get_contents($this->getMessageFile());
expect(strpos($data, 'find-this@email.net'))->notEquals(false);
});
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/' . self::FILE_NAME;
$model
->expects($this->any())
->method('getAccount')
->will($this->returnValue(new Account([
'id' => '123',
'username' => 'Erick',
'email' => 'find-this@email.net',
'created_at' => time() - 86400,
])));
$this->assertTrue($model->sendMessage());
/** @var Message $message */
$message = $this->tester->grabLastSentEmail();
$this->assertInstanceOf(Message::class, $message);
$data = (string)$message;
$this->assertContains('find-this@email.net', $data);
}
}

View File

@ -3,45 +3,37 @@ namespace tests\codeception\api\models\authentication;
use api\components\User\LoginResult;
use api\models\authentication\ConfirmEmailForm;
use Codeception\Specify;
use common\models\Account;
use common\models\AccountSession;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property EmailActivationFixture $emailActivations
*/
class ConfirmEmailFormTest extends DbTestCase {
use Specify;
class ConfirmEmailFormTest extends TestCase {
public function fixtures() {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
];
}
protected function createModel($key) {
public function testConfirm() {
$fixture = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation');
$model = $this->createModel($fixture['key']);
$result = $model->confirm();
$this->assertInstanceOf(LoginResult::class, $result);
$this->assertInstanceOf(AccountSession::class, $result->getSession(), 'session was generated');
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
$this->assertFalse($activationExists, 'email activation key is not exist');
/** @var Account $user */
$user = Account::findOne($fixture['account_id']);
$this->assertEquals(Account::STATUS_ACTIVE, $user->status, 'user status changed to active');
}
private function createModel($key) {
return new ConfirmEmailForm([
'key' => $key,
]);
}
public function testConfirm() {
$fixture = $this->emailActivations['freshRegistrationConfirmation'];
$model = $this->createModel($fixture['key']);
$this->specify('expect true result', function() use ($model, $fixture) {
$result = $model->confirm();
expect($result)->isInstanceOf(LoginResult::class);
expect('session was generated', $result->getSession())->isInstanceOf(AccountSession::class);
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
expect('email activation key is not exist', $activationExists)->false();
/** @var Account $user */
$user = Account::findOne($fixture['account_id']);
expect('user status changed to active', $user->status)->equals(Account::STATUS_ACTIVE);
});
}
}

View File

@ -4,41 +4,16 @@ namespace codeception\api\unit\models\authentication;
use api\models\authentication\ForgotPasswordForm;
use Codeception\Specify;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property EmailActivationFixture $emailActivations
*/
class ForgotPasswordFormTest extends DbTestCase {
class ForgotPasswordFormTest extends TestCase {
use Specify;
protected function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
@ -51,7 +26,7 @@ class ForgotPasswordFormTest extends DbTestCase {
});
$this->specify('empty errors if login is exists', function() {
$model = new ForgotPasswordForm(['login' => $this->accounts['admin']['username']]);
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
$model->validateLogin('login');
expect($model->getErrors('login'))->isEmpty();
});
@ -59,13 +34,17 @@ class ForgotPasswordFormTest extends DbTestCase {
public function testValidateActivity() {
$this->specify('error.account_not_activated if account is not confirmed', function() {
$model = new ForgotPasswordForm(['login' => $this->accounts['not-activated-account']['username']]);
$model = new ForgotPasswordForm([
'login' => $this->tester->grabFixture('accounts', 'not-activated-account')['username'],
]);
$model->validateActivity('login');
expect($model->getErrors('login'))->equals(['error.account_not_activated']);
});
$this->specify('empty errors if login is exists', function() {
$model = new ForgotPasswordForm(['login' => $this->accounts['admin']['username']]);
$model = new ForgotPasswordForm([
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
]);
$model->validateLogin('login');
expect($model->getErrors('login'))->isEmpty();
});
@ -74,8 +53,8 @@ class ForgotPasswordFormTest extends DbTestCase {
public function testValidateFrequency() {
$this->specify('error.account_not_activated if recently was message', function() {
$model = $this->createModel([
'login' => $this->accounts['admin']['username'],
'key' => $this->emailActivations['freshPasswordRecovery']['key'],
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
'key' => $this->tester->grabFixture('emailActivations', 'freshPasswordRecovery')['key'],
]);
$model->validateFrequency('login');
@ -84,8 +63,8 @@ class ForgotPasswordFormTest extends DbTestCase {
$this->specify('empty errors if email was sent a long time ago', function() {
$model = $this->createModel([
'login' => $this->accounts['admin']['username'],
'key' => $this->emailActivations['oldPasswordRecovery']['key'],
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
'key' => $this->tester->grabFixture('emailActivations', 'oldPasswordRecovery')['key'],
]);
$model->validateFrequency('login');
@ -94,7 +73,7 @@ class ForgotPasswordFormTest extends DbTestCase {
$this->specify('empty errors if previous confirmation model not founded', function() {
$model = $this->createModel([
'login' => $this->accounts['admin']['username'],
'login' => $this->tester->grabFixture('accounts', 'admin')['username'],
'key' => 'invalid-key',
]);
@ -105,34 +84,28 @@ class ForgotPasswordFormTest extends DbTestCase {
public function testForgotPassword() {
$this->specify('successfully send message with restore password key', function() {
$model = new ForgotPasswordForm(['login' => $this->accounts['admin']['username']]);
$model = new ForgotPasswordForm(['login' => $this->tester->grabFixture('accounts', 'admin')['username']]);
expect($model->forgotPassword())->true();
expect($model->getEmailActivation())->notNull();
expect_file($this->getMessageFile())->exists();
$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' => $this->accounts['account-with-expired-forgot-password-message']['username'],
'login' => $fixture['username'],
]);
$callTime = time();
expect($model->forgotPassword())->true();
$emailActivation = $model->getEmailActivation();
expect($emailActivation)->notNull();
expect($emailActivation->created_at)->greaterOrEquals($callTime);
expect_file($this->getMessageFile())->exists();
$this->tester->canSeeEmailIsSent(1);
});
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/testing_message.eml';
}
/**
* @param array $params
* @return ForgotPasswordForm

View File

@ -6,13 +6,10 @@ use api\models\AccountIdentity;
use api\models\authentication\LoginForm;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
/**
* @property AccountFixture $accounts
*/
class LoginFormTest extends DbTestCase {
class LoginFormTest extends TestCase {
use Specify;
private $originalRemoteAddr;
@ -28,7 +25,7 @@ class LoginFormTest extends DbTestCase {
$_SERVER['REMOTE_ADDR'] = $this->originalRemoteAddr;
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
];
@ -119,7 +116,7 @@ class LoginFormTest extends DbTestCase {
public function testLoginWithRehashing() {
$this->specify('user, that login using account with old pass hash strategy should update it automatically', function () {
$model = new LoginForm([
'login' => $this->accounts['user-with-old-password-type']['username'],
'login' => $this->tester->grabFixture('accounts', 'user-with-old-password-type')['username'],
'password' => '12345678',
]);
expect($model->login())->isInstanceOf(LoginResult::class);

View File

@ -6,10 +6,10 @@ use api\models\AccountIdentity;
use api\models\authentication\LogoutForm;
use Codeception\Specify;
use common\models\AccountSession;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use Yii;
class LogoutFormTest extends DbTestCase {
class LogoutFormTest extends TestCase {
use Specify;
public function testValidateLogout() {

View File

@ -6,39 +6,32 @@ use api\models\authentication\RecoverPasswordForm;
use Codeception\Specify;
use common\models\Account;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property EmailActivationFixture $emailActivations
*/
class RecoverPasswordFormTest extends DbTestCase {
class RecoverPasswordFormTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
];
}
public function testRecoverPassword() {
$fixture = $this->emailActivations['freshPasswordRecovery'];
$this->specify('change user account password by email confirmation key', function() use ($fixture) {
$model = new RecoverPasswordForm([
'key' => $fixture['key'],
'newPassword' => '12345678',
'newRePassword' => '12345678',
]);
$result = $model->recoverPassword();
expect($result)->isInstanceOf(LoginResult::class);
expect('session was not generated', $result->getSession())->null();
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
expect($activationExists)->false();
/** @var Account $account */
$account = Account::findOne($fixture['account_id']);
expect($account->validatePassword('12345678'))->true();
});
$fixture = $this->tester->grabFixture('emailActivations', 'freshPasswordRecovery');
$model = new RecoverPasswordForm([
'key' => $fixture['key'],
'newPassword' => '12345678',
'newRePassword' => '12345678',
]);
$result = $model->recoverPassword();
$this->assertInstanceOf(LoginResult::class, $result);
$this->assertNull($result->getSession(), 'session was not generated');
$this->assertFalse(EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists());
/** @var Account $account */
$account = Account::findOne($fixture['account_id']);
$this->assertTrue($account->validatePassword('12345678'));
}
}

View File

@ -5,16 +5,13 @@ use api\components\User\RenewResult;
use api\models\authentication\RefreshTokenForm;
use Codeception\Specify;
use common\models\AccountSession;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountSessionFixture;
/**
* @property AccountSessionFixture $sessions
*/
class RefreshTokenFormTest extends DbTestCase {
class RefreshTokenFormTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'sessions' => AccountSessionFixture::class,
];
@ -45,11 +42,9 @@ class RefreshTokenFormTest extends DbTestCase {
}
public function testRenew() {
$this->specify('success renew token', function() {
$model = new RefreshTokenForm();
$model->refresh_token = $this->sessions['admin']['refresh_token'];
expect($model->renew())->isInstanceOf(RenewResult::class);
});
$model = new RefreshTokenForm();
$model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token'];
$this->assertInstanceOf(RenewResult::class, $model->renew());
}
}

View File

@ -1,53 +1,34 @@
<?php
namespace tests\codeception\api\models\authentication;
use api\components\ReCaptcha\Validator;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\models\authentication\RegistrationForm;
use Codeception\Specify;
use common\models\Account;
use common\models\EmailActivation;
use common\models\UsernameHistory;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use Yii;
use const common\LATEST_RULES_VERSION;
use yii\web\Request;
use const common\LATEST_RULES_VERSION;
/**
* @property array $accounts
*/
class RegistrationFormTest extends DbTestCase {
class RegistrationFormTest extends TestCase {
use Specify;
public function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
$this->mockRequest();
Yii::$container->set(Validator::class, new class extends Validator {
Yii::$container->set(ReCaptchaValidator::class, new class extends ReCaptchaValidator {
public function validateValue($value) {
return null;
}
});
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
];
}
@ -84,7 +65,7 @@ class RegistrationFormTest extends DbTestCase {
$account = $model->signup();
$this->expectSuccessRegistration($account);
expect('lang is set', $account->lang)->equals('ru');
$this->assertEquals('ru', $account->lang, 'lang is set');
}
public function testSignupWithDefaultLanguage() {
@ -99,32 +80,32 @@ class RegistrationFormTest extends DbTestCase {
$account = $model->signup();
$this->expectSuccessRegistration($account);
expect('lang is set', $account->lang)->equals('en');
$this->assertEquals('en', $account->lang, 'lang is set');
}
/**
* @param Account|null $account
*/
private function expectSuccessRegistration($account) {
expect('user should be valid', $account)->isInstanceOf(Account::class);
expect('password should be correct', $account->validatePassword('some_password'))->true();
expect('uuid is set', $account->uuid)->notEmpty();
expect('registration_ip is set', $account->registration_ip)->notNull();
expect('actual rules version is set', $account->rules_agreement_version)->equals(LATEST_RULES_VERSION);
expect('user model exists in database', Account::find()->andWhere([
$this->assertInstanceOf(Account::class, $account, 'user should be valid');
$this->assertTrue($account->validatePassword('some_password'), 'password should be correct');
$this->assertNotEmpty($account->uuid, 'uuid is set');
$this->assertNotNull($account->registration_ip, 'registration_ip is set');
$this->assertEquals(LATEST_RULES_VERSION, $account->rules_agreement_version, 'actual rules version is set');
$this->assertTrue(Account::find()->andWhere([
'username' => 'some_username',
'email' => 'some_email@example.com',
])->exists())->true();
expect('email activation code exists in database', EmailActivation::find()->andWhere([
])->exists(), 'user model exists in database');
$this->assertTrue(EmailActivation::find()->andWhere([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION,
])->exists())->true();
expect('username history record exists in database', UsernameHistory::find()->andWhere([
])->exists(), 'email activation code exists in database');
$this->assertTrue(UsernameHistory::find()->andWhere([
'username' => $account->username,
'account_id' => $account->id,
'applied_in' => $account->created_at,
])->exists())->true();
expect_file('message file exists', $this->getMessageFile())->exists();
])->exists(), 'username history record exists in database');
$this->tester->canSeeEmailIsSent(1);
}
// TODO: там в самой форме есть метод sendMail(), который рано или поздно должен переехать. К нему нужны будут тоже тесты
@ -144,11 +125,4 @@ class RegistrationFormTest extends DbTestCase {
return $request;
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/testing_message.eml';
}
}

View File

@ -1,50 +1,30 @@
<?php
namespace tests\codeception\api\models\authentication;
use api\components\ReCaptcha\Validator;
use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\models\authentication\RepeatAccountActivationForm;
use Codeception\Specify;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property array $accounts
* @property array $activations
*/
class RepeatAccountActivationFormTest extends DbTestCase {
class RepeatAccountActivationFormTest extends TestCase {
use Specify;
public function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
Yii::$container->set(Validator::class, new class extends Validator {
Yii::$container->set(ReCaptchaValidator::class, new class extends ReCaptchaValidator {
public function validateValue($value) {
return null;
}
});
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'activations' => EmailActivationFixture::class,
];
}
@ -57,13 +37,15 @@ class RepeatAccountActivationFormTest extends DbTestCase {
});
$this->specify('error.account_already_activated if passed valid email, but account already activated', function() {
$model = new RepeatAccountActivationForm(['email' => $this->accounts['admin']['email']]);
$fixture = $this->tester->grabFixture('accounts', 'admin');
$model = new RepeatAccountActivationForm(['email' => $fixture['email']]);
$model->validateEmailForAccount('email');
expect($model->getErrors('email'))->equals(['error.account_already_activated']);
});
$this->specify('no errors if passed valid email for not activated account', function() {
$model = new RepeatAccountActivationForm(['email' => $this->accounts['not-activated-account']['email']]);
$fixture = $this->tester->grabFixture('accounts', 'not-activated-account');
$model = new RepeatAccountActivationForm(['email' => $fixture['email']]);
$model->validateEmailForAccount('email');
expect($model->getErrors('email'))->isEmpty();
});
@ -71,17 +53,15 @@ class RepeatAccountActivationFormTest extends DbTestCase {
public function testValidateExistsActivation() {
$this->specify('error.recently_sent_message if passed email has recently sent message', function() {
$model = $this->createModel([
'emailKey' => $this->activations['freshRegistrationConfirmation']['key'],
]);
$fixture = $this->tester->grabFixture('activations', 'freshRegistrationConfirmation');
$model = $this->createModel(['emailKey' => $fixture['key']]);
$model->validateExistsActivation('email');
expect($model->getErrors('email'))->equals(['error.recently_sent_message']);
});
$this->specify('no errors if passed email has expired activation message', function() {
$model = $this->createModel([
'emailKey' => $this->activations['oldRegistrationConfirmation']['key'],
]);
$fixture = $this->tester->grabFixture('activations', 'oldRegistrationConfirmation');
$model = $this->createModel(['emailKey' => $fixture['key']]);
$model->validateExistsActivation('email');
expect($model->getErrors('email'))->isEmpty();
});
@ -91,25 +71,18 @@ class RepeatAccountActivationFormTest extends DbTestCase {
$this->specify('no magic if we don\'t pass validation', function() {
$model = new RepeatAccountActivationForm();
expect($model->sendRepeatMessage())->false();
expect_file($this->getMessageFile())->notExists();
$this->tester->cantSeeEmailIsSent();
});
$this->specify('successfully send new message if previous message has expired', function() {
$email = $this->accounts['not-activated-account-with-expired-message']['email'];
$email = $this->tester->grabFixture('accounts', 'not-activated-account-with-expired-message')['email'];
$model = new RepeatAccountActivationForm(['email' => $email]);
expect($model->sendRepeatMessage())->true();
expect($model->getActivation())->notNull();
expect_file($this->getMessageFile())->exists();
$this->tester->canSeeEmailIsSent(1);
});
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/testing_message.eml';
}
/**
* @param array $params
* @return RepeatAccountActivationForm

View File

@ -2,19 +2,14 @@
namespace tests\codeception\api\models\base;
use api\models\base\ApiForm;
use Codeception\Specify;
use tests\codeception\api\unit\TestCase;
class ApiFormTest extends TestCase {
use Specify;
public function testLoad() {
$model = new DummyApiForm();
$this->specify('model should load data without ModelName array scope', function () use ($model) {
expect('model successful load data without prefix', $model->load(['field' => 'test-data']))->true();
expect('field is set as passed data', $model->field)->equals('test-data');
});
$this->assertTrue($model->load(['field' => 'test-data']), 'model successful load data without prefix');
$this->assertEquals('test-data', $model->field, 'field is set as passed data');
}
}

View File

@ -4,34 +4,26 @@ namespace tests\codeception\api\models\base;
use api\models\base\KeyConfirmationForm;
use Codeception\Specify;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property EmailActivationFixture $emailActivations
*/
class KeyConfirmationFormTest extends DbTestCase {
class KeyConfirmationFormTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
];
}
public function testGetActivationCodeModel() {
$this->specify('should return model, based on passed key', function() {
$model = new KeyConfirmationForm();
$model->key = array_values($this->emailActivations->data)[0]['key'];
expect($model->getActivationCodeModel())->isInstanceOf(EmailActivation::class);
});
$model = new KeyConfirmationForm();
$model->key = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation')['key'];
$this->assertInstanceOf(EmailActivation::class, $model->getActivationCodeModel());
$this->specify('should return null, if passed key is invalid', function() {
$model = new KeyConfirmationForm();
$model->key = 'this-is-invalid-key';
expect($model->getActivationCodeModel())->null();
});
$model = new KeyConfirmationForm();
$model->key = 'this-is-invalid-key';
$this->assertNull($model->getActivationCodeModel());
}
}

View File

@ -2,32 +2,25 @@
namespace codeception\api\unit\models\profile;
use api\models\profile\AcceptRulesForm;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use const common\LATEST_RULES_VERSION;
/**
* @property AccountFixture $accounts
*/
class AcceptRulesFormTest extends DbTestCase {
use Specify;
class AcceptRulesFormTest extends TestCase {
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
];
}
public function testApplyLanguage() {
$this->specify('rules version bumped to latest', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['account-with-old-rules-version']);
$model = new AcceptRulesForm($account);
expect($model->agreeWithLatestRules())->true();
expect($account->rules_agreement_version)->equals(LATEST_RULES_VERSION);
});
public function testAgreeWithLatestRules() {
/** @var Account $account */
$account = Account::findOne($this->tester->grabFixture('accounts', 'account-with-old-rules-version'));
$model = new AcceptRulesForm($account);
$this->assertTrue($model->agreeWithLatestRules());
$this->assertEquals(LATEST_RULES_VERSION, $account->rules_agreement_version);
}
}

View File

@ -2,46 +2,36 @@
namespace codeception\api\unit\models\profile\ChangeEmail;
use api\models\profile\ChangeEmail\ConfirmNewEmailForm;
use Codeception\Specify;
use common\models\Account;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property EmailActivationFixture $emailActivations
*/
class ConfirmNewEmailFormTest extends DbTestCase {
use Specify;
class ConfirmNewEmailFormTest extends TestCase {
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testChangeEmail() {
$this->specify('successfully change account email', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['account-with-change-email-finish-state']['id']);
$model = new ConfirmNewEmailForm($account, [
'key' => $this->emailActivations['newEmailConfirmation']['key'],
]);
expect($model->changeEmail())->true();
expect(EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]))->null();
$data = unserialize($this->emailActivations['newEmailConfirmation']['_data']);
expect($account->email)->equals($data['newEmail']);
});
$accountId = $this->tester->grabFixture('accounts', 'account-with-change-email-finish-state')['id'];
/** @var Account $account */
$account = Account::findOne($accountId);
$newEmailConfirmationFixture = $this->tester->grabFixture('emailActivations', 'newEmailConfirmation');
$model = new ConfirmNewEmailForm($account, [
'key' => $newEmailConfirmationFixture['key'],
]);
$this->assertTrue($model->changeEmail());
$this->assertNull(EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]));
$data = unserialize($newEmailConfirmationFixture['_data']);
$this->assertEquals($data['newEmail'], $account->email);
}
}

View File

@ -2,82 +2,44 @@
namespace codeception\api\unit\models\profile\ChangeEmail;
use api\models\profile\ChangeEmail\InitStateForm;
use Codeception\Specify;
use common\models\Account;
use common\models\confirmations\CurrentEmailConfirmation;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property EmailActivationFixture $emailActivations
*/
class InitStateFormTest extends DbTestCase {
use Specify;
class InitStateFormTest extends TestCase {
public function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testCreateCode() {
$this->specify('create valid code and store it to database', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new InitStateForm($account);
$activationModel = $model->createCode();
expect($activationModel)->isInstanceOf(CurrentEmailConfirmation::class);
expect($activationModel->account_id)->equals($account->id);
expect(EmailActivation::findOne($activationModel->key))->notNull();
});
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new InitStateForm($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() {
$this->specify('send email', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new InitStateForm($account, [
'password' => 'password_0',
]);
expect($model->sendCurrentEmailConfirmation())->true();
expect(EmailActivation::find()->andWhere([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION,
])->exists())->true();
expect_file($this->getMessageFile())->exists();
});
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/testing_message.eml';
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new InitStateForm($account, [
'password' => 'password_0',
]);
$this->assertTrue($model->sendCurrentEmailConfirmation());
$this->assertTrue(EmailActivation::find()->andWhere([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION,
])->exists());
$this->tester->canSeeEmailIsSent();
}
}

View File

@ -2,87 +2,50 @@
namespace codeception\api\unit\models\profile\ChangeEmail;
use api\models\profile\ChangeEmail\NewEmailForm;
use Codeception\Specify;
use common\models\Account;
use common\models\confirmations\NewEmailConfirmation;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\EmailActivationFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property EmailActivationFixture $emailActivations
*/
class NewEmailFormTest extends DbTestCase {
use Specify;
class NewEmailFormTest extends TestCase {
public function setUp() {
parent::setUp();
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
$mailer->fileTransportCallback = function () {
return 'testing_message.eml';
};
}
protected function tearDown() {
if (file_exists($this->getMessageFile())) {
unlink($this->getMessageFile());
}
parent::tearDown();
}
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
'emailActivations' => EmailActivationFixture::class,
];
}
public function testCreateCode() {
$this->specify('create valid code and store it to database', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$model = new NewEmailForm($account);
$model->email = 'my-new-email@ely.by';
$activationModel = $model->createCode();
expect($activationModel)->isInstanceOf(NewEmailConfirmation::class);
expect($activationModel->account_id)->equals($account->id);
expect($activationModel->newEmail)->equals($model->email);
expect(EmailActivation::findOne($activationModel->key))->notNull();
});
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new NewEmailForm($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() {
$this->specify('send email', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['account-with-change-email-init-state']['id']);
/** @var NewEmailForm $model */
$key = $this->emailActivations['currentChangeEmailConfirmation']['key'];
$model = new NewEmailForm($account, [
'key' => $key,
'email' => 'my-new-email@ely.by',
]);
expect($model->sendNewEmailConfirmation())->true();
expect(EmailActivation::findOne($key))->null();
expect(EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]))->notNull();
expect_file($this->getMessageFile())->exists();
});
}
private function getMessageFile() {
/** @var \yii\swiftmailer\Mailer $mailer */
$mailer = Yii::$app->mailer;
return Yii::getAlias($mailer->fileTransportPath) . '/testing_message.eml';
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'account-with-change-email-init-state');
/** @var NewEmailForm $model */
$key = $this->tester->grabFixture('emailActivations', 'currentChangeEmailConfirmation')['key'];
$model = new NewEmailForm($account, [
'key' => $key,
'email' => 'my-new-email@ely.by',
]);
$this->assertTrue($model->sendNewEmailConfirmation());
$this->assertNull(EmailActivation::findOne($key));
$this->assertNotNull(EmailActivation::findOne([
'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]));
$this->tester->canSeeEmailIsSent();
}
}

View File

@ -2,35 +2,25 @@
namespace codeception\api\unit\models\profile;
use api\models\profile\ChangeLanguageForm;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
/**
* @property AccountFixture $accounts
*/
class ChangeLanguageFormTest extends DbTestCase {
use Specify;
class ChangeLanguageFormTest extends TestCase {
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class
];
}
public function testApplyLanguage() {
$this->specify('language changed', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']);
$model = new ChangeLanguageForm($account);
$model->lang = 'ru';
expect($model->applyLanguage())->true();
expect($account->lang)->equals('ru');
});
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model = new ChangeLanguageForm($account);
$model->lang = 'ru';
$this->assertTrue($model->applyLanguage());
$this->assertEquals('ru', $account->lang);
}
}

View File

@ -7,19 +7,15 @@ use api\models\profile\ChangePasswordForm;
use Codeception\Specify;
use common\models\Account;
use common\models\AccountSession;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\AccountSessionFixture;
use Yii;
/**
* @property AccountFixture $accounts
* @property AccountSessionFixture $accountSessions
*/
class ChangePasswordFormTest extends DbTestCase {
class ChangePasswordFormTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'accountSessions' => AccountSessionFixture::class,
@ -68,7 +64,7 @@ class ChangePasswordFormTest extends DbTestCase {
public function testChangePassword() {
$this->specify('successfully change password with modern hash strategy', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$account = Account::findOne($this->tester->grabFixture('accounts', 'admin')['id']);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',
'newPassword' => 'my-new-password',
@ -83,7 +79,7 @@ class ChangePasswordFormTest extends DbTestCase {
$this->specify('successfully change password with legacy hash strategy', function() {
/** @var Account $account */
$account = Account::findOne($this->accounts['user-with-old-password-type']['id']);
$account = Account::findOne($this->tester->grabFixture('accounts', 'user-with-old-password-type')['id']);
$model = new ChangePasswordForm($account, [
'password' => '12345678',
'newPassword' => 'my-new-password',
@ -111,7 +107,7 @@ class ChangePasswordFormTest extends DbTestCase {
->getMock();
/** @var AccountSession $session */
$session = AccountSession::findOne($this->accountSessions['admin2']['id']);
$session = AccountSession::findOne($this->tester->grabFixture('accountSessions', 'admin2')['id']);
$component
->expects($this->any())
@ -122,7 +118,7 @@ class ChangePasswordFormTest extends DbTestCase {
$this->specify('change password with removing all session, except current', function() use ($session) {
/** @var Account $account */
$account = Account::findOne($this->accounts['admin']['id']);
$account = Account::findOne($this->tester->grabFixture('accounts', 'admin')['id']);
$model = new ChangePasswordForm($account, [
'password' => 'password_0',

View File

@ -6,18 +6,15 @@ use api\models\profile\ChangeUsernameForm;
use Codeception\Specify;
use common\models\Account;
use common\models\UsernameHistory;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\UsernameHistoryFixture;
use Yii;
/**
* @property AccountFixture $accounts
*/
class ChangeUsernameFormTest extends DbTestCase {
class ChangeUsernameFormTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'history' => UsernameHistoryFixture::class,
@ -31,44 +28,43 @@ class ChangeUsernameFormTest extends DbTestCase {
}
public function testChange() {
$this->specify('successfully change username to new one', function() {
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => 'my_new_nickname',
]);
expect($model->change())->true();
expect(Account::findOne($this->getAccountId())->username)->equals('my_new_nickname');
expect(UsernameHistory::findOne(['username' => 'my_new_nickname']))->isInstanceOf(UsernameHistory::class);
});
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => 'my_new_nickname',
]);
$this->assertTrue($model->change());
$this->assertEquals('my_new_nickname', Account::findOne($this->getAccountId())->username);
$this->assertInstanceOf(UsernameHistory::class, UsernameHistory::findOne(['username' => 'my_new_nickname']));
}
public function testChangeWithoutChange() {
$this->specify('no new UsernameHistory record, if we don\'t change nickname', function() {
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => $this->accounts['admin']['username'],
]);
$callTime = time();
expect($model->change())->true();
expect(UsernameHistory::findOne([
'AND',
'username' => $this->accounts['admin']['username'],
['>=', 'applied_in', $callTime],
]))->null();
});
$username = $this->tester->grabFixture('accounts', 'admin')['username'];
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => $username,
]);
$callTime = time();
$this->assertTrue($model->change());
$this->assertNull(UsernameHistory::findOne([
'AND',
'username' => $username,
['>=', 'applied_in', $callTime],
]), 'no new UsernameHistory record, if we don\'t change nickname');
}
public function testChangeCase() {
$this->specify('username should change, if we change case of some letters', function() {
$newUsername = mb_strtoupper($this->accounts['admin']['username']);
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => $newUsername,
]);
expect($model->change())->true();
expect(Account::findOne($this->getAccountId())->username)->equals($newUsername);
expect(UsernameHistory::findOne(['username' => $newUsername]))->isInstanceOf(UsernameHistory::class);
});
$newUsername = mb_strtoupper($this->tester->grabFixture('accounts', 'admin')['username']);
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => $newUsername,
]);
$this->assertTrue($model->change());
$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'
);
}
public function testValidateUsername() {
@ -84,7 +80,7 @@ class ChangeUsernameFormTest extends DbTestCase {
$this->specify('error.username_not_available is NOT expected if username is already taken by CURRENT user', function() {
$model = new ChangeUsernameForm([
'password' => 'password_0',
'username' => $this->accounts['admin']['username'],
'username' => $this->tester->grabFixture('accounts', 'admin')['username'],
]);
$model->validateUsername('username');
expect($model->getErrors('username'))->isEmpty();
@ -99,7 +95,7 @@ class ChangeUsernameFormTest extends DbTestCase {
}
private function getAccountId() {
return $this->accounts['admin']['id'];
return $this->tester->grabFixture('accounts', 'admin')['id'];
}
}

View File

@ -8,19 +8,15 @@ use api\modules\authserver\models\AuthenticationForm;
use common\models\Account;
use common\models\MinecraftAccessKey;
use Ramsey\Uuid\Uuid;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\MinecraftAccessKeyFixture;
/**
* @property AccountFixture $accounts
* @property MinecraftAccessKeyFixture $minecraftAccessKeys
*/
class AuthenticationFormTest extends DbTestCase {
class AuthenticationFormTest extends TestCase {
use ProtectedCaller;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => AccountFixture::class,
'minecraftAccessKeys' => MinecraftAccessKeyFixture::class,
@ -91,7 +87,7 @@ class AuthenticationFormTest extends DbTestCase {
$authForm = new AuthenticationForm();
$authForm->clientToken = Uuid::uuid4();
/** @var Account $account */
$account = $this->accounts->getModel('admin');
$account = $this->tester->grabFixture('accounts', 'admin');
/** @var MinecraftAccessKey $result */
$result = $this->callProtected($authForm, 'createMinecraftAccessToken', $account);
$this->assertInstanceOf(MinecraftAccessKey::class, $result);
@ -102,15 +98,16 @@ class AuthenticationFormTest extends DbTestCase {
public function testCreateMinecraftAccessTokenWithExistsClientId() {
$authForm = new AuthenticationForm();
$authForm->clientToken = $this->minecraftAccessKeys['admin-token']['client_token'];
$minecraftFixture = $this->tester->grabFixture('minecraftAccessKeys', 'admin-token');
$authForm->clientToken = $minecraftFixture['client_token'];
/** @var Account $account */
$account = $this->accounts->getModel('admin');
$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($this->minecraftAccessKeys['admin-token']['access_token']));
$this->assertNull(MinecraftAccessKey::findOne($minecraftFixture['access_token']));
$this->assertInstanceOf(MinecraftAccessKey::class, MinecraftAccessKey::findOne($result->access_token));
}

View File

@ -5,32 +5,27 @@ use api\models\AccountIdentity;
use api\traits\AccountFinder;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\fixtures\AccountFixture;
/**
* @property \tests\codeception\api\UnitTester $actor
* @property array $accounts
*/
class AccountFinderTest extends DbTestCase {
class AccountFinderTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'accounts' => AccountFixture::class,
];
}
public function testGetAccount() {
$this->specify('founded account for passed login data', function() {
$model = new AccountFinderTestTestClass();
$model->login = $this->accounts['admin']['email'];
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model->login = $account->email;
$account = $model->getAccount();
expect($account)->isInstanceOf(Account::class);
expect($account->id)->equals($this->accounts['admin']['id']);
expect($account->id)->equals($account->id);
});
$this->specify('founded account for passed login data with changed account model class name', function() {
@ -40,10 +35,12 @@ class AccountFinderTest extends DbTestCase {
return AccountIdentity::class;
}
};
$model->login = $this->accounts['admin']['email'];
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
$model->login = $account->email;
$account = $model->getAccount();
expect($account)->isInstanceOf(AccountIdentity::class);
expect($account->id)->equals($this->accounts['admin']['id']);
expect($account->id)->equals($account->id);
});
$this->specify('null, if account not founded', function() {

View File

@ -2,41 +2,34 @@
namespace tests\codeception\api\traits;
use api\traits\ApiNormalize;
use Codeception\Specify;
use Codeception\TestCase\Test;
use tests\codeception\api\unit\TestCase;
class ApiNormalizeTestClass {
use ApiNormalize;
}
/**
* @property \tests\codeception\api\UnitTester $actor
*/
class ApiNormalizerTest extends Test {
use Specify;
class ApiNormalizerTest extends TestCase {
public function testNormalizeModelErrors() {
$object = new ApiNormalizeTestClass();
$this->specify('', function() use ($object) {
$normalized = $object->normalizeModelErrors([
'rulesAgreement' => [
'error.you_must_accept_rules',
],
'email' => [
'error.email_required',
],
'username' => [
'error.username_too_short',
'error.username_not_unique',
],
]);
$normalized = $object->normalizeModelErrors([
'rulesAgreement' => [
'error.you_must_accept_rules',
],
'email' => [
'error.email_required',
],
'username' => [
'error.username_too_short',
'error.username_not_unique',
],
]);
expect($normalized)->equals([
'rulesAgreement' => 'error.you_must_accept_rules',
'email' => 'error.email_required',
'username' => 'error.username_too_short',
]);
});
$this->assertEquals([
'rulesAgreement' => 'error.you_must_accept_rules',
'email' => 'error.email_required',
'username' => 'error.username_too_short',
], $normalized);
}
}

View File

@ -5,18 +5,15 @@ use api\validators\EmailActivationKeyValidator;
use Codeception\Specify;
use common\models\confirmations\ForgotPassword;
use common\models\EmailActivation;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use tests\codeception\common\fixtures\EmailActivationFixture;
/**
* @property EmailActivationFixture $emailActivations
*/
class EmailActivationKeyValidatorTest extends DbTestCase {
class EmailActivationKeyValidatorTest extends TestCase {
use Specify;
use ProtectedCaller;
public function fixtures() {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
];
@ -24,7 +21,7 @@ class EmailActivationKeyValidatorTest extends DbTestCase {
public function testFindEmailActivationModel() {
$this->specify('get EmailActivation model for exists key', function() {
$key = array_values($this->emailActivations->data)[0]['key'];
$key = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation')['key'];
$model = new EmailActivationKeyValidator();
/** @var EmailActivation $result */
$result = $this->callProtected($model, 'findEmailActivationModel', $key);

View File

@ -4,11 +4,11 @@ namespace codeception\api\unit\validators;
use api\validators\PasswordRequiredValidator;
use Codeception\Specify;
use common\models\Account;
use tests\codeception\api\unit\DbTestCase;
use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller;
use common\helpers\Error as E;
class PasswordRequiredValidatorTest extends DbTestCase {
class PasswordRequiredValidatorTest extends TestCase {
use Specify;
use ProtectedCaller;

View File

@ -16,6 +16,8 @@ use yii\test\InitDbFixture;
/**
* This helper is used to populate the database with needed fixtures before any tests are run.
* All fixtures will be loaded before the suite is started and unloaded after it completes.
*
* TODO: try to remove
*/
class FixtureHelper extends Module {
@ -52,14 +54,8 @@ class FixtureHelper extends Module {
'accountSessions' => AccountSessionFixture::class,
'emailActivations' => EmailActivationFixture::class,
'usernamesHistory' => UsernameHistoryFixture::class,
'oauthClients' => [
'class' => OauthClientFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/oauth-clients.php',
],
'oauthSessions' => [
'class' => OauthSessionFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/oauth-sessions.php',
],
'oauthClients' => OauthClientFixture::class,
'oauthSessions' => OauthSessionFixture::class,
'minecraftAccessKeys' => MinecraftAccessKeyFixture::class,
];
}

View File

@ -8,4 +8,6 @@ class MojangUsernameFixture extends ActiveFixture {
public $modelClass = MojangUsername::class;
public $dataFile = '@tests/codeception/common/fixtures/data/mojang-usernames.php';
}

View File

@ -8,6 +8,8 @@ class OauthClientFixture extends ActiveFixture {
public $modelClass = OauthClient::class;
public $dataFile = '@tests/codeception/common/fixtures/data/oauth-clients.php';
public $depends = [
AccountFixture::class,
];

View File

@ -9,6 +9,8 @@ class OauthSessionFixture extends ActiveFixture {
public $modelClass = OauthSession::class;
public $dataFile = '@tests/codeception/common/fixtures/data/oauth-sessions.php';
public $depends = [
OauthClientFixture::class,
AccountFixture::class,

View File

@ -1,6 +1,8 @@
# Codeception Test Suite Configuration
# suite for unit (internal) tests.
# RUN `build` COMMAND AFTER ADDING/REMOVING MODULES.
class_name: UnitTester
modules:
enabled:
- Yii2:
part: [orm, email, fixtures]
config:
Yii2:
configFile: '../config/api/unit.php'

View File

@ -1,11 +0,0 @@
<?php
namespace tests\codeception\common\unit;
/**
* @inheritdoc
*/
class DbTestCase extends \yii\codeception\DbTestCase
{
public $appConfig = '@tests/codeception/config/common/unit.php';
}

View File

@ -1,8 +1,22 @@
<?php
namespace tests\codeception\common\unit;
class TestCase extends \yii\codeception\TestCase {
class TestCase extends \Codeception\Test\Unit {
public $appConfig = '@tests/codeception/config/common/unit.php';
/**
* @var \tests\codeception\common\UnitTester
*/
protected $tester;
/**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
*
* @url http://codeception.com/docs/modules/Yii2#fixtures
*
* @return array
*/
public function _fixtures() {
return [];
}
}

View File

@ -13,23 +13,19 @@ class DataBehaviorTest extends TestCase {
use ProtectedCaller;
public function testSetKey() {
$this->specify('setting value should change model data field', function() {
$model = $this->createModel();
/** @var DataBehavior $behavior */
$behavior = $model->behaviors['dataBehavior'];
$this->callProtected($behavior, 'setKey', 'my-key', 'my-value');
expect($model->_data)->equals(serialize(['my-key' => 'my-value']));
});
$model = $this->createModel();
/** @var DataBehavior $behavior */
$behavior = $model->behaviors['dataBehavior'];
$this->callProtected($behavior, 'setKey', 'my-key', 'my-value');
$this->assertEquals(serialize(['my-key' => 'my-value']), $model->_data);
}
public function testGetKey() {
$this->specify('getting value from exists data should work', function() {
$model = $this->createModel();
$model->_data = serialize(['some-key' => 'some-value']);
/** @var DataBehavior $behavior */
$behavior = $model->behaviors['dataBehavior'];
expect($this->callProtected($behavior, 'getKey', 'some-key'))->equals('some-value');
});
$model = $this->createModel();
$model->_data = serialize(['some-key' => 'some-value']);
/** @var DataBehavior $behavior */
$behavior = $model->behaviors['dataBehavior'];
$this->assertEquals('some-value', $this->callProtected($behavior, 'getKey', 'some-key'));
}
public function testGetData() {

View File

@ -12,12 +12,10 @@ class EmailActivationExpirationBehaviorTest extends TestCase {
use ProtectedCaller;
public function testCalculateTime() {
$this->specify('just use create_time and plus passed time', function() {
$behavior = $this->createBehavior();
$time = time();
$behavior->owner->created_at = $time;
expect($this->callProtected($behavior, 'calculateTime', 10))->equals($time + 10);
});
$behavior = $this->createBehavior();
$time = time();
$behavior->owner->created_at = $time;
$this->assertEquals($time + 10, $this->callProtected($behavior, 'calculateTime', 10));
}
public function testCompareTime() {

View File

@ -0,0 +1,54 @@
<?php
namespace codeception\common\unit\components\Mojang;
use common\components\Mojang\Api;
use common\components\Mojang\response\UsernameToUUIDResponse;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use tests\codeception\common\unit\TestCase;
use Yii;
class ApiTest extends TestCase {
/**
* @var MockHandler
*/
private $handler;
public function _before() {
parent::_before();
$this->handler = new MockHandler();
$handler = HandlerStack::create($this->handler);
Yii::$app->set('guzzle', new GuzzleClient([
'handler' => $handler,
]));
}
public function testUsernameToUUID() {
$this->handler->append(new Response(200, [], '{"id": "7125ba8b1c864508b92bb5c042ccfe2b","name": "KrisJelbring"}'));
$response = (new Api())->usernameToUUID('KrisJelbring');
$this->assertInstanceOf(UsernameToUUIDResponse::class, $response);
$this->assertEquals('7125ba8b1c864508b92bb5c042ccfe2b', $response->id);
$this->assertEquals('KrisJelbring', $response->name);
}
/**
* @expectedException \common\components\Mojang\exceptions\NoContentException
*/
public function testUsernameToUUIDNoContent() {
$this->handler->append(new Response(204));
(new Api())->usernameToUUID('some-non-exists-user');
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
*/
public function testUsernameToUUID404() {
$this->handler->append(new Response(404, [], '{"error":"Not Found","errorMessage":"The server has not found anything matching the request URI"}'));
(new Api())->usernameToUUID('#hashedNickname');
}
}

View File

@ -1,35 +1,27 @@
<?php
namespace codeception\common\unit\models;
use Codeception\Specify;
use common\models\AccountSession;
use tests\codeception\common\unit\TestCase;
class AccountSessionTest extends TestCase {
use Specify;
public function testGenerateRefreshToken() {
$this->specify('method call will set refresh_token value', function() {
$model = new AccountSession();
$model->generateRefreshToken();
expect($model->refresh_token)->notNull();
});
$model = new AccountSession();
$model->generateRefreshToken();
$this->assertNotNull($model->refresh_token, 'method call will set refresh_token value');
}
public function testSetIp() {
$this->specify('method should convert passed ip string to long', function() {
$model = new AccountSession();
$model->setIp('127.0.0.1');
expect($model->last_used_ip)->equals(2130706433);
});
$model = new AccountSession();
$model->setIp('127.0.0.1');
$this->assertEquals(2130706433, $model->last_used_ip, 'method should convert passed ip string to long');
}
public function testGetReadableIp() {
$this->specify('method should convert stored ip long into readable ip string', function() {
$model = new AccountSession();
$model->last_used_ip = 2130706433;
expect($model->getReadableIp())->equals('127.0.0.1');
});
$model = new AccountSession();
$model->last_used_ip = 2130706433;
$this->assertEquals('127.0.0.1', $model->getReadableIp(), 'method should convert stored long into readable ip');
}
}

View File

@ -6,27 +6,17 @@ use common\components\UserPass;
use common\models\Account;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\MojangUsernameFixture;
use tests\codeception\common\unit\DbTestCase;
use tests\codeception\common\unit\TestCase;
use Yii;
use const common\LATEST_RULES_VERSION;
/**
* @property array $accounts
* @property array $mojangAccounts
*/
class AccountTest extends DbTestCase {
class AccountTest extends TestCase {
use Specify;
public function fixtures() {
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'mojangAccounts' => [
'class' => MojangUsernameFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/mojang-usernames.php',
],
'accounts' => AccountFixture::class,
'mojangAccounts' => MojangUsernameFixture::class,
];
}
@ -73,7 +63,8 @@ class AccountTest extends DbTestCase {
});
$this->specify('username should be unique', function() {
$model = new Account(['username' => $this->accounts['admin']['username']]);
$model = new Account();
$model->username = $this->tester->grabFixture('accounts', 'admin')['username'];
expect($model->validate('username'))->false();
expect($model->getErrors('username'))->equals(['error.username_not_available']);
});
@ -111,7 +102,7 @@ class AccountTest extends DbTestCase {
});
$this->specify('email should be unique', function() {
$model = new Account(['email' => $this->accounts['admin']['email']]);
$model = new Account(['email' => $this->tester->grabFixture('accounts', 'admin')['email']]);
expect($model->validate('email'))->false();
expect($model->getErrors('email'))->equals(['error.email_not_available']);
});

View File

@ -1,31 +1,35 @@
<?php
namespace codeception\common\unit\models;
use Codeception\Specify;
use common\models\confirmations\ForgotPassword;
use common\models\confirmations\RegistrationConfirmation;
use common\models\confirmations;
use common\models\EmailActivation;
use tests\codeception\common\fixtures\EmailActivationFixture;
use tests\codeception\common\unit\DbTestCase;
use tests\codeception\common\unit\TestCase;
class EmailActivationTest extends DbTestCase {
use Specify;
class EmailActivationTest extends TestCase {
public function fixtures() {
public function _fixtures() {
return [
'emailActivations' => EmailActivationFixture::class,
];
}
public function testInstantiate() {
$this->specify('return valid model type', function() {
expect(EmailActivation::findOne([
'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION,
]))->isInstanceOf(RegistrationConfirmation::class);
expect(EmailActivation::findOne([
'type' => EmailActivation::TYPE_FORGOT_PASSWORD_KEY,
]))->isInstanceOf(ForgotPassword::class);
});
$this->assertInstanceOf(confirmations\RegistrationConfirmation::class, EmailActivation::findOne([
'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION,
]));
$this->assertInstanceOf(confirmations\ForgotPassword::class, EmailActivation::findOne([
'type' => EmailActivation::TYPE_FORGOT_PASSWORD_KEY,
]));
$this->assertInstanceOf(confirmations\CurrentEmailConfirmation::class, EmailActivation::findOne([
'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION,
]));
$this->assertInstanceOf(confirmations\NewEmailConfirmation::class, EmailActivation::findOne([
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
]));
}
}

View File

@ -11,25 +11,18 @@ class LanguageValidatorTest extends TestCase {
use ProtectedCaller;
public function testGetFilesNames() {
$this->specify('get list of 2 languages: ru and en', function() {
$model = $this->createModelWithFixturePath();
expect($this->callProtected($model, 'getFilesNames'))->equals(['en', 'ru']);
});
$model = $this->createModelWithFixturePath();
$this->assertEquals(['en', 'ru'], $this->callProtected($model, 'getFilesNames'));
}
public function testValidateValue() {
$this->specify('get null, because language is supported', function() {
$model = $this->createModelWithFixturePath();
expect($this->callProtected($model, 'validateValue', 'ru'))->null();
});
public function testValidateValueSupportedLanguage() {
$model = $this->createModelWithFixturePath();
$this->assertNull($this->callProtected($model, 'validateValue', 'ru'));
}
$this->specify('get error message, because language is unsupported', function() {
$model = $this->createModelWithFixturePath();
expect($this->callProtected($model, 'validateValue', 'by'))->equals([
$model->message,
[],
]);
});
public function testValidateNotSupportedLanguage() {
$model = $this->createModelWithFixturePath();
$this->assertEquals([$model->message, []], $this->callProtected($model, 'validateValue', 'by'));
}
/**

View File

@ -1,6 +1,8 @@
# Codeception Test Suite Configuration
# suite for unit (internal) tests.
# RUN `build` COMMAND AFTER ADDING/REMOVING MODULES.
class_name: UnitTester
modules:
enabled:
- Yii2:
part: [orm, email, fixtures]
config:
Yii2:
configFile: '../config/console/unit.php'

View File

@ -1,8 +0,0 @@
<?php
namespace tests\codeception\console\unit;
class DbTestCase extends \yii\codeception\DbTestCase {
public $appConfig = '@tests/codeception/config/console/unit.php';
}

View File

@ -1,11 +1,24 @@
<?php
namespace tests\codeception\console\unit;
/**
* @inheritdoc
*/
class TestCase extends \yii\codeception\TestCase
{
public $appConfig = '@tests/codeception/config/console/config.php';
use Codeception\Test\Unit;
class TestCase extends Unit {
/**
* @var \tests\codeception\console\UnitTester
*/
protected $tester;
/**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
*
* @url http://codeception.com/docs/modules/Yii2#fixtures
*
* @return array
*/
public function _fixtures() {
return [];
}
}

View File

@ -1,95 +1,146 @@
<?php
namespace codeception\console\unit\controllers;
use Codeception\Specify;
use common\components\Mojang\Api;
use common\components\Mojang\exceptions\NoContentException;
use common\components\Mojang\response\UsernameToUUIDResponse;
use common\models\amqp\UsernameChanged;
use common\models\MojangUsername;
use console\controllers\AccountQueueController;
use tests\codeception\common\fixtures\AccountFixture;
use tests\codeception\common\fixtures\MojangUsernameFixture;
use tests\codeception\console\unit\DbTestCase;
use tests\codeception\console\unit\TestCase;
use Yii;
/**
* @property array $accounts
* @property array $mojangUsernames
*/
class AccountQueueControllerTest extends DbTestCase {
use Specify;
class AccountQueueControllerTest extends TestCase {
public function fixtures() {
/**
* @var AccountQueueController
*/
private $controller;
private $expectedResponse;
public function _fixtures() {
return [
'accounts' => [
'class' => AccountFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/accounts.php',
],
'mojangUsernames' => [
'class' => MojangUsernameFixture::class,
'dataFile' => '@tests/codeception/common/fixtures/data/mojang-usernames.php',
],
'accounts' => AccountFixture::class,
'mojangUsernames' => MojangUsernameFixture::class,
];
}
public function testRouteUsernameChanged() {
// TODO: пропустить тест, если у нас нету интернета
$controller = new AccountQueueController('account-queue', Yii::$app);
$this->specify('Update last_pulled_at time if username exists', function() use ($controller) {
$accountInfo = $this->accounts['admin'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => 'Notch',
]);
$controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne('Notch');
expect($mojangUsername)->isInstanceOf(MojangUsername::class);
expect($mojangUsername->last_pulled_at)->greaterThan($this->mojangUsernames['Notch']['last_pulled_at']);
expect($mojangUsername->last_pulled_at)->lessOrEquals(time());
});
public function _before() {
parent::_before();
$this->specify('Add new MojangUsername if don\'t exists', function() use ($controller) {
$accountInfo = $this->accounts['admin'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => 'Chest',
]);
$controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne('Chest');
expect($mojangUsername)->isInstanceOf(MojangUsername::class);
});
/** @var AccountQueueController|\PHPUnit_Framework_MockObject_MockObject $controller */
$controller = $this->getMockBuilder(AccountQueueController::class)
->setMethods(['createMojangApi'])
->setConstructorArgs(['account-queue', Yii::$app])
->getMock();
$this->specify('Remove MojangUsername, if now it\'s does\'t exists', function() use ($controller) {
$accountInfo = $this->accounts['admin'];
$username = $this->mojangUsernames['not-exists']['username'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => $username,
]);
$controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne($username);
expect($mojangUsername)->null();
});
/** @var Api|\PHPUnit_Framework_MockObject_MockObject $apiMock */
$apiMock = $this->getMockBuilder(Api::class)
->setMethods(['usernameToUUID'])
->getMock();
$this->specify('Update uuid if username for now owned by other player', function() use ($controller) {
$accountInfo = $this->accounts['admin'];
$mojangInfo = $this->mojangUsernames['uuid-changed'];
$username = $mojangInfo['username'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => $username,
]);
$controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne($username);
expect($mojangUsername)->isInstanceOf(MojangUsername::class);
expect($mojangUsername->uuid)->notEquals($mojangInfo['uuid']);
});
$apiMock
->expects($this->any())
->method('usernameToUUID')
->willReturnCallback(function() {
if ($this->expectedResponse === false) {
throw new NoContentException();
} else {
return $this->expectedResponse;
}
});
$controller
->expects($this->any())
->method('createMojangApi')
->willReturn($apiMock);
$this->controller = $controller;
}
public function testRouteUsernameChangedUsernameExists() {
$expectedResponse = new UsernameToUUIDResponse();
$expectedResponse->id = '069a79f444e94726a5befca90e38aaf5';
$expectedResponse->name = 'Notch';
$this->expectedResponse = $expectedResponse;
/** @var \common\models\Account $accountInfo */
$accountInfo = $this->tester->grabFixture('accounts', 'admin');
/** @var MojangUsername $mojangUsernameFixture */
$mojangUsernameFixture = $this->tester->grabFixture('mojangUsernames', 'Notch');
$body = new UsernameChanged([
'accountId' => $accountInfo->id,
'oldUsername' => $accountInfo->username,
'newUsername' => 'Notch',
]);
$this->controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne('Notch');
$this->assertInstanceOf(MojangUsername::class, $mojangUsername);
$this->assertGreaterThan($mojangUsernameFixture->last_pulled_at, $mojangUsername->last_pulled_at);
$this->assertLessThanOrEqual(time(), $mojangUsername->last_pulled_at);
}
public function testRouteUsernameChangedUsernameNotExists() {
$expectedResponse = new UsernameToUUIDResponse();
$expectedResponse->id = '607153852b8c4909811f507ed8ee737f';
$expectedResponse->name = 'Chest';
$this->expectedResponse = $expectedResponse;
/** @var \common\models\Account $accountInfo */
$accountInfo = $this->tester->grabFixture('accounts', 'admin');
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => 'Chest',
]);
$this->controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne('Chest');
$this->assertInstanceOf(MojangUsername::class, $mojangUsername);
}
public function testRouteUsernameChangedRemoveIfExistsNoMore() {
$this->expectedResponse = false;
/** @var \common\models\Account $accountInfo */
$accountInfo = $this->tester->grabFixture('accounts', 'admin');
$username = $this->tester->grabFixture('mojangUsernames', 'not-exists')['username'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => $username,
]);
$this->controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne($username);
$this->assertNull($mojangUsername);
}
public function testRouteUsernameChangedUuidUpdated() {
$expectedResponse = new UsernameToUUIDResponse();
$expectedResponse->id = 'f498513ce8c84773be26ecfc7ed5185d';
$expectedResponse->name = 'jeb';
$this->expectedResponse = $expectedResponse;
/** @var \common\models\Account $accountInfo */
$accountInfo = $this->tester->grabFixture('accounts', 'admin');
/** @var MojangUsername $mojangInfo */
$mojangInfo = $this->tester->grabFixture('mojangUsernames', 'uuid-changed');
$username = $mojangInfo['username'];
$body = new UsernameChanged([
'accountId' => $accountInfo['id'],
'oldUsername' => $accountInfo['username'],
'newUsername' => $username,
]);
$this->controller->routeUsernameChanged($body);
/** @var MojangUsername|null $mojangUsername */
$mojangUsername = MojangUsername::findOne($username);
$this->assertInstanceOf(MojangUsername::class, $mojangUsername);
$this->assertNotEquals($mojangInfo->uuid, $mojangUsername->uuid);
}
}