From 88175fea48c1bbe8168735c9f2deb544880ab497 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Sun, 26 Nov 2017 04:44:41 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9E=D1=82=D0=BF=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B2=D1=81=D0=B5=D1=85=20email=20=D0=B2=D1=8B=D0=BD?= =?UTF-8?q?=D0=B5=D1=81=D0=B5=D0=BD=D0=B0=20=D0=B2=20=D0=BE=D1=87=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env-dist | 1 + .../authentication/ForgotPasswordForm.php | 5 +- .../authentication/RegistrationForm.php | 4 +- .../RepeatAccountActivationForm.php | 35 +++++------- .../models/SendEmailVerificationForm.php | 4 +- .../models/SendNewEmailVerificationForm.php | 4 +- autocompletion.php | 1 + common/components/EmailRenderer.php | 8 +-- common/config/config.php | 10 ++++ common/emails/EmailHelper.php | 50 +---------------- common/tasks/SendCurrentEmailConfirmation.php | 43 +++++++++++++++ common/tasks/SendNewEmailConfirmation.php | 43 +++++++++++++++ common/tasks/SendPasswordRecoveryEmail.php | 55 +++++++++++++++++++ common/tasks/SendRegistrationEmail.php | 55 +++++++++++++++++++ composer.json | 3 +- console/config/config.php | 11 ++-- docker/supervisor/worker-queue.conf | 6 ++ 17 files changed, 253 insertions(+), 85 deletions(-) create mode 100644 common/tasks/SendCurrentEmailConfirmation.php create mode 100644 common/tasks/SendNewEmailConfirmation.php create mode 100644 common/tasks/SendPasswordRecoveryEmail.php create mode 100644 common/tasks/SendRegistrationEmail.php create mode 100644 docker/supervisor/worker-queue.conf diff --git a/.env-dist b/.env-dist index b9dd499..a4fcd1c 100644 --- a/.env-dist +++ b/.env-dist @@ -2,6 +2,7 @@ ## Env приложения YII_DEBUG=true YII_ENV=dev +DOMAIN=https://account.ely.by ## Параметры, отвечающие за безопасность JWT_USER_SECRET= diff --git a/api/models/authentication/ForgotPasswordForm.php b/api/models/authentication/ForgotPasswordForm.php index 8b2f52b..45cf5cc 100644 --- a/api/models/authentication/ForgotPasswordForm.php +++ b/api/models/authentication/ForgotPasswordForm.php @@ -4,13 +4,14 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\models\base\ApiForm; -use common\emails\EmailHelper; use common\helpers\Error as E; use api\traits\AccountFinder; use common\components\UserFriendlyRandomKey; use common\models\Account; use common\models\confirmations\ForgotPassword; use common\models\EmailActivation; +use common\tasks\SendPasswordRecoveryEmail; +use Yii; use yii\base\ErrorException; class ForgotPasswordForm extends ApiForm { @@ -80,7 +81,7 @@ class ForgotPasswordForm extends ApiForm { throw new ErrorException('Cannot create email activation for forgot password form'); } - EmailHelper::forgotPassword($emailActivation); + Yii::$app->queue->push(SendPasswordRecoveryEmail::createFromConfirmation($emailActivation)); return true; } diff --git a/api/models/authentication/RegistrationForm.php b/api/models/authentication/RegistrationForm.php index 743b1e4..2382fd5 100644 --- a/api/models/authentication/RegistrationForm.php +++ b/api/models/authentication/RegistrationForm.php @@ -3,13 +3,13 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; -use common\emails\EmailHelper; use api\models\base\ApiForm; use common\helpers\Error as E; use common\components\UserFriendlyRandomKey; use common\models\Account; use common\models\confirmations\RegistrationConfirmation; use common\models\UsernameHistory; +use common\tasks\SendRegistrationEmail; use common\validators\EmailValidator; use common\validators\LanguageValidator; use common\validators\PasswordValidator; @@ -104,7 +104,7 @@ class RegistrationForm extends ApiForm { throw new ErrorException('Cannot save username history record'); } - EmailHelper::registration($emailActivation); + Yii::$app->queue->push(SendRegistrationEmail::createFromConfirmation($emailActivation)); $transaction->commit(); } catch (Exception $e) { diff --git a/api/models/authentication/RepeatAccountActivationForm.php b/api/models/authentication/RepeatAccountActivationForm.php index 58d6c35..a56d226 100644 --- a/api/models/authentication/RepeatAccountActivationForm.php +++ b/api/models/authentication/RepeatAccountActivationForm.php @@ -3,15 +3,15 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; -use common\emails\EmailHelper; +use api\exceptions\ThisShouldNotHappenException; use api\models\base\ApiForm; use common\helpers\Error as E; use common\components\UserFriendlyRandomKey; use common\models\Account; use common\models\confirmations\RegistrationConfirmation; use common\models\EmailActivation; +use common\tasks\SendRegistrationEmail; use Yii; -use yii\base\ErrorException; class RepeatAccountActivationForm extends ApiForm { @@ -57,7 +57,6 @@ class RepeatAccountActivationForm extends ApiForm { /** * @CollectModelMetrics(prefix="signup.repeatEmail") * @return bool - * @throws ErrorException */ public function sendRepeatMessage() { if (!$this->validate()) { @@ -66,27 +65,23 @@ class RepeatAccountActivationForm extends ApiForm { $account = $this->getAccount(); $transaction = Yii::$app->db->beginTransaction(); - try { - EmailActivation::deleteAll([ - 'account_id' => $account->id, - 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION, - ]); - $activation = new RegistrationConfirmation(); - $activation->account_id = $account->id; - $activation->key = UserFriendlyRandomKey::make(); - if (!$activation->save()) { - throw new ErrorException('Unable save email-activation model.'); - } + EmailActivation::deleteAll([ + 'account_id' => $account->id, + 'type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION, + ]); - EmailHelper::registration($activation); - - $transaction->commit(); - } catch (ErrorException $e) { - $transaction->rollBack(); - throw $e; + $activation = new RegistrationConfirmation(); + $activation->account_id = $account->id; + $activation->key = UserFriendlyRandomKey::make(); + if (!$activation->save()) { + throw new ThisShouldNotHappenException('Unable save email-activation model.'); } + Yii::$app->queue->push(SendRegistrationEmail::createFromConfirmation($activation)); + + $transaction->commit(); + return true; } diff --git a/api/modules/accounts/models/SendEmailVerificationForm.php b/api/modules/accounts/models/SendEmailVerificationForm.php index 593215f..cd680da 100644 --- a/api/modules/accounts/models/SendEmailVerificationForm.php +++ b/api/modules/accounts/models/SendEmailVerificationForm.php @@ -3,11 +3,11 @@ namespace api\modules\accounts\models; use api\aop\annotations\CollectModelMetrics; use api\exceptions\ThisShouldNotHappenException; -use common\emails\EmailHelper; use api\validators\PasswordRequiredValidator; use common\helpers\Error as E; use common\models\confirmations\CurrentEmailConfirmation; use common\models\EmailActivation; +use common\tasks\SendCurrentEmailConfirmation; use Yii; class SendEmailVerificationForm extends AccountActionForm { @@ -48,7 +48,7 @@ class SendEmailVerificationForm extends AccountActionForm { $this->removeOldCode(); $activation = $this->createCode(); - EmailHelper::changeEmailConfirmCurrent($activation); + Yii::$app->queue->push(SendCurrentEmailConfirmation::createFromConfirmation($activation)); $transaction->commit(); diff --git a/api/modules/accounts/models/SendNewEmailVerificationForm.php b/api/modules/accounts/models/SendNewEmailVerificationForm.php index 100c09b..1c9470a 100644 --- a/api/modules/accounts/models/SendNewEmailVerificationForm.php +++ b/api/modules/accounts/models/SendNewEmailVerificationForm.php @@ -3,10 +3,10 @@ namespace api\modules\accounts\models; use api\aop\annotations\CollectModelMetrics; use api\exceptions\ThisShouldNotHappenException; -use common\emails\EmailHelper; use api\validators\EmailActivationKeyValidator; use common\models\confirmations\NewEmailConfirmation; use common\models\EmailActivation; +use common\tasks\SendNewEmailConfirmation; use common\validators\EmailValidator; use Yii; @@ -39,7 +39,7 @@ class SendNewEmailVerificationForm extends AccountActionForm { $activation = $this->createCode(); - EmailHelper::changeEmailConfirmNew($activation); + Yii::$app->queue->push(SendNewEmailConfirmation::createFromConfirmation($activation)); $transaction->commit(); diff --git a/autocompletion.php b/autocompletion.php index 1d5fd81..07b6667 100644 --- a/autocompletion.php +++ b/autocompletion.php @@ -25,6 +25,7 @@ class Yii extends \yii\BaseYii { * @property \mito\sentry\Component $sentry * @property \api\components\OAuth2\Component $oauth * @property \common\components\StatsD $statsd + * @property \yii\queue\Queue $queue */ abstract class BaseApplication extends yii\base\Application { } diff --git a/common/components/EmailRenderer.php b/common/components/EmailRenderer.php index 3c493ca..ce0e3e7 100644 --- a/common/components/EmailRenderer.php +++ b/common/components/EmailRenderer.php @@ -29,7 +29,7 @@ class EmailRenderer extends Component { parent::__construct($config); if ($this->_baseDomain === null) { - $this->_baseDomain = Yii::$app->request->getHostInfo(); + $this->_baseDomain = Yii::$app->urlManager->getHostInfo(); if ($this->_baseDomain === null) { throw new InvalidConfigException('Cannot automatically obtain base domain'); } @@ -51,7 +51,7 @@ class EmailRenderer extends Component { * @param string $templateName * @return TemplateBuilder */ - public function getTemplate(string $templateName) : TemplateBuilder { + public function getTemplate(string $templateName): TemplateBuilder { return $this->renderer->getTemplate($templateName); } @@ -60,11 +60,11 @@ class EmailRenderer extends Component { * @throws \Ely\Email\RendererException * @return string */ - public function render(TemplateBuilder $template) : string { + public function render(TemplateBuilder $template): string { return $this->renderer->render($template); } - private function buildBasePath() : string { + private function buildBasePath(): string { return $this->_baseDomain . $this->basePath; } diff --git a/common/config/config.php b/common/config/config.php index c1e886b..692fbed 100644 --- a/common/config/config.php +++ b/common/config/config.php @@ -96,6 +96,16 @@ return [ 'port' => getenv('STATSD_PORT') ?: 8125, 'namespace' => getenv('STATSD_NAMESPACE') ?: 'ely.accounts.' . gethostname() . '.app', ], + 'queue' => [ + 'class' => yii\queue\amqp\Queue::class, + 'host' => getenv('RABBITMQ_HOST') ?: 'rabbitmq', + 'port' => getenv('RABBITMQ_PORT') ?: 5672, + 'user' => getenv('RABBITMQ_USER'), + 'password' => getenv('RABBITMQ_PASS'), + 'vhost' => getenv('RABBITMQ_VHOST'), + 'queueName' => 'worker', + 'exchangeName' => 'tasks', + ], ], 'container' => [ 'definitions' => [ diff --git a/common/emails/EmailHelper.php b/common/emails/EmailHelper.php index 2d40cb3..3b0d5e3 100644 --- a/common/emails/EmailHelper.php +++ b/common/emails/EmailHelper.php @@ -1,56 +1,10 @@ account; - $locale = $account->lang; - $params = new RegistrationEmailParams( - $account->username, - $emailActivation->key, - Yii::$app->request->getHostInfo() . '/activation/' . $emailActivation->key - ); - - (new RegistrationEmail(self::buildTo($account), $locale, $params))->send(); - } - - public static function forgotPassword(ForgotPassword $emailActivation): void { - $account = $emailActivation->account; - $locale = $account->lang; - $params = new ForgotPasswordParams( - $account->username, - $emailActivation->key, - Yii::$app->request->getHostInfo() . '/recover-password/' . $emailActivation->key - ); - - (new ForgotPasswordEmail(self::buildTo($account), $locale, $params))->send(); - } - - public static function changeEmailConfirmCurrent(CurrentEmailConfirmation $emailActivation): void { - (new ChangeEmailConfirmCurrentEmail(self::buildTo($emailActivation->account), $emailActivation->key))->send(); - } - - public static function changeEmailConfirmNew(NewEmailConfirmation $emailActivation): void { - $account = $emailActivation->account; - (new ChangeEmailConfirmNewEmail(self::buildTo($account), $account->username, $emailActivation->key))->send(); - } - - public static function buildTo(Account $account): array { - return [$account->email => $account->username]; + public static function buildTo(string $username, string $email): array { + return [$email => $username]; } } diff --git a/common/tasks/SendCurrentEmailConfirmation.php b/common/tasks/SendCurrentEmailConfirmation.php new file mode 100644 index 0000000..3f5362a --- /dev/null +++ b/common/tasks/SendCurrentEmailConfirmation.php @@ -0,0 +1,43 @@ +email = $confirmation->account->email; + $result->username = $confirmation->account->username; + $result->code = $confirmation->key; + + return $result; + } + + public function getTtr() { + return 30; + } + + public function canRetry($attempt, $error) { + return true; + } + + /** + * @param \yii\queue\Queue $queue + */ + public function execute($queue) { + $to = EmailHelper::buildTo($this->username, $this->email); + $template = new ChangeEmailConfirmCurrentEmail($to, $this->code); + $template->send(); + } + +} diff --git a/common/tasks/SendNewEmailConfirmation.php b/common/tasks/SendNewEmailConfirmation.php new file mode 100644 index 0000000..1d09f42 --- /dev/null +++ b/common/tasks/SendNewEmailConfirmation.php @@ -0,0 +1,43 @@ +email = $confirmation->getNewEmail(); + $result->username = $confirmation->account->username; + $result->code = $confirmation->key; + + return $result; + } + + public function getTtr() { + return 30; + } + + public function canRetry($attempt, $error) { + return true; + } + + /** + * @param \yii\queue\Queue $queue + */ + public function execute($queue) { + $to = EmailHelper::buildTo($this->username, $this->email); + $template = new ChangeEmailConfirmNewEmail($to, $this->username, $this->code); + $template->send(); + } + +} diff --git a/common/tasks/SendPasswordRecoveryEmail.php b/common/tasks/SendPasswordRecoveryEmail.php new file mode 100644 index 0000000..fe39b9a --- /dev/null +++ b/common/tasks/SendPasswordRecoveryEmail.php @@ -0,0 +1,55 @@ +account; + + $result = new self(); + $result->username = $account->username; + $result->email = $account->email; + $result->code = $confirmation->key; + $result->link = Yii::$app->request->getHostInfo() . '/recover-password/' . $confirmation->key; + $result->locale = $account->lang; + + return $result; + } + + public function getTtr() { + return 30; + } + + public function canRetry($attempt, $error) { + return true; + } + + /** + * @param \yii\queue\Queue $queue + * @throws \common\emails\exceptions\CannotSendEmailException + */ + public function execute($queue) { + $params = new ForgotPasswordParams($this->username, $this->code, $this->link); + $to = EmailHelper::buildTo($this->username, $this->email); + $template = new ForgotPasswordEmail($to, $this->locale, $params); + $template->send(); + } + +} diff --git a/common/tasks/SendRegistrationEmail.php b/common/tasks/SendRegistrationEmail.php new file mode 100644 index 0000000..ec80050 --- /dev/null +++ b/common/tasks/SendRegistrationEmail.php @@ -0,0 +1,55 @@ +account; + + $result = new self(); + $result->username = $account->username; + $result->email = $account->email; + $result->code = $confirmation->key; + $result->link = Yii::$app->request->getHostInfo() . '/activation/' . $confirmation->key; + $result->locale = $account->lang; + + return $result; + } + + public function getTtr() { + return 30; + } + + public function canRetry($attempt, $error) { + return true; + } + + /** + * @param \yii\queue\Queue $queue + * @throws \common\emails\exceptions\CannotSendEmailException + */ + public function execute($queue) { + $params = new RegistrationEmailParams($this->username, $this->code, $this->link); + $to = EmailHelper::buildTo($this->username, $this->email); + $template = new RegistrationEmail($to, $this->locale, $params); + $template->send(); + } + +} diff --git a/composer.json b/composer.json index af98768..f37adb5 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,8 @@ "paragonie/constant_time_encoding": "^2.0", "webmozart/assert": "^1.2.0", "goaop/framework": "~2.1.2", - "domnikl/statsd": "^2.6" + "domnikl/statsd": "^2.6", + "yiisoft/yii2-queue": "~2.0.1" }, "require-dev": { "yiisoft/yii2-debug": "*", diff --git a/console/config/config.php b/console/config/config.php index 748acc4..7b5d94d 100644 --- a/console/config/config.php +++ b/console/config/config.php @@ -1,13 +1,13 @@ 'accounts-console', 'basePath' => dirname(__DIR__), - 'bootstrap' => ['log'], + 'bootstrap' => ['log', 'queue'], 'controllerNamespace' => 'console\controllers', 'params' => $params, 'components' => [ @@ -23,10 +23,13 @@ return [ ], ], ], + 'urlManager' => [ + 'hostInfo' => getenv('DOMAIN') ?: 'https://account.ely.by', + ], ], 'controllerMap' => [ 'migrate' => [ - 'class' => yii\console\controllers\MigrateController::class, + 'class' => yii\console\controllers\MigrateController::class, 'templateFile' => '@console/views/migration.php', ], ], diff --git a/docker/supervisor/worker-queue.conf b/docker/supervisor/worker-queue.conf new file mode 100644 index 0000000..b7d715f --- /dev/null +++ b/docker/supervisor/worker-queue.conf @@ -0,0 +1,6 @@ +[program:account-queue-worker] +directory=/var/www/html +command=wait-for-it rabbitmq:5672 -- php yii queue/listen +autostart=true +autorestart=true +priority=10 From b8049e88996efdbe35e25056e83743cad7bfb1f5 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Mon, 27 Nov 2017 02:29:15 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B2=D1=81=D0=B5=D1=85=20=D1=84=D0=BE=D1=80=D0=BC,?= =?UTF-8?q?=20=D1=87=D1=82=D0=BE=20=D0=BE=D1=82=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D1=8F=D0=BB=D0=B8=20=D0=BF=D0=B8=D1=81=D1=8C=D0=BC=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RepeatAccountActivationForm.php | 2 + common/tasks/SendCurrentEmailConfirmation.php | 1 + common/tasks/SendNewEmailConfirmation.php | 1 + common/tasks/SendPasswordRecoveryEmail.php | 1 + common/tasks/SendRegistrationEmail.php | 1 + tests/codeception/api/unit.suite.yml | 1 + .../authentication/ForgotPasswordFormTest.php | 38 ++++++++----- .../authentication/RegistrationFormTest.php | 44 +++++++-------- .../RepeatAccountActivationFormTest.php | 30 ++++++----- .../models/SendEmailVerificationFormTest.php | 15 ++++-- .../SendNewEmailVerificationFormTest.php | 15 ++++-- .../_support/queue/CodeceptionQueueHelper.php | 51 ++++++++++++++++++ .../common/_support/queue/Queue.php | 32 +++++++++++ .../common/unit/emails/EmailHelperTest.php | 7 +-- .../SendCurrentEmailConfirmationTest.php | 47 ++++++++++++++++ .../tasks/SendNewEmailConfirmationTest.php | 47 ++++++++++++++++ .../tasks/SendPasswordRecoveryEmailTest.php | 53 +++++++++++++++++++ .../unit/tasks/SendRegistrationEmailTest.php | 53 +++++++++++++++++++ tests/codeception/config/config.php | 6 +++ 19 files changed, 387 insertions(+), 58 deletions(-) create mode 100644 tests/codeception/common/_support/queue/CodeceptionQueueHelper.php create mode 100644 tests/codeception/common/_support/queue/Queue.php create mode 100644 tests/codeception/common/unit/tasks/SendCurrentEmailConfirmationTest.php create mode 100644 tests/codeception/common/unit/tasks/SendNewEmailConfirmationTest.php create mode 100644 tests/codeception/common/unit/tasks/SendPasswordRecoveryEmailTest.php create mode 100644 tests/codeception/common/unit/tasks/SendRegistrationEmailTest.php diff --git a/api/models/authentication/RepeatAccountActivationForm.php b/api/models/authentication/RepeatAccountActivationForm.php index a56d226..9cbec46 100644 --- a/api/models/authentication/RepeatAccountActivationForm.php +++ b/api/models/authentication/RepeatAccountActivationForm.php @@ -78,6 +78,8 @@ class RepeatAccountActivationForm extends ApiForm { throw new ThisShouldNotHappenException('Unable save email-activation model.'); } + $this->emailActivation = $activation; + Yii::$app->queue->push(SendRegistrationEmail::createFromConfirmation($activation)); $transaction->commit(); diff --git a/common/tasks/SendCurrentEmailConfirmation.php b/common/tasks/SendCurrentEmailConfirmation.php index 3f5362a..55e96ef 100644 --- a/common/tasks/SendCurrentEmailConfirmation.php +++ b/common/tasks/SendCurrentEmailConfirmation.php @@ -1,4 +1,5 @@ $this->tester->grabFixture('accounts', 'admin')['username']]); + /** @var Account $account */ + $account = $this->tester->grabFixture('accounts', 'admin'); + $model = new ForgotPasswordForm(['login' => $account->username]); $this->assertTrue($model->forgotPassword(), 'form should be successfully processed'); $activation = $model->getEmailActivation(); $this->assertInstanceOf(EmailActivation::class, $activation, 'getEmailActivation should return valid object instance'); - $this->tester->canSeeEmailIsSent(1); - /** @var \yii\swiftmailer\Message $email */ - $email = $this->tester->grabSentEmails()[0]; - $body = $email->getSwiftMessage()->getBody(); - $this->assertContains($activation->key, $body); - $this->assertContains('/recover-password/' . $activation->key, $body); + + $this->assertTaskCreated($this->tester->grabLastQueuedJob(), $account, $activation); } public function testForgotPasswordResend() { - $fixture = $this->tester->grabFixture('accounts', 'account-with-expired-forgot-password-message'); - $model = new ForgotPasswordForm([ - 'login' => $fixture['username'], - ]); + /** @var Account $account */ + $account = $this->tester->grabFixture('accounts', 'account-with-expired-forgot-password-message'); + $model = new ForgotPasswordForm(['login' => $account->username]); $callTime = time(); $this->assertTrue($model->forgotPassword(), 'form should be successfully processed'); $emailActivation = $model->getEmailActivation(); $this->assertInstanceOf(EmailActivation::class, $emailActivation); $this->assertGreaterThanOrEqual($callTime, $emailActivation->created_at); - $this->tester->canSeeEmailIsSent(1); + + $this->assertTaskCreated($this->tester->grabLastQueuedJob(), $account, $emailActivation); + } + + /** + * @param SendPasswordRecoveryEmail $job + * @param Account $account + * @param EmailActivation $activation + */ + private function assertTaskCreated($job, Account $account, EmailActivation $activation) { + $this->assertInstanceOf(SendPasswordRecoveryEmail::class, $job); + $this->assertSame($account->username, $job->username); + $this->assertSame($account->email, $job->email); + $this->assertSame($account->lang, $job->locale); + $this->assertSame($activation->key, $job->code); + $this->assertSame('http://localhost/recover-password/' . $activation->key, $job->link); } /** diff --git a/tests/codeception/api/unit/models/authentication/RegistrationFormTest.php b/tests/codeception/api/unit/models/authentication/RegistrationFormTest.php index e957e74..bd76a40 100644 --- a/tests/codeception/api/unit/models/authentication/RegistrationFormTest.php +++ b/tests/codeception/api/unit/models/authentication/RegistrationFormTest.php @@ -7,6 +7,7 @@ use Codeception\Specify; use common\models\Account; use common\models\EmailActivation; use common\models\UsernameHistory; +use common\tasks\SendRegistrationEmail; use GuzzleHttp\ClientInterface; use tests\codeception\api\unit\TestCase; use tests\codeception\common\fixtures\AccountFixture; @@ -40,23 +41,19 @@ class RegistrationFormTest extends TestCase { } public function testValidatePasswordAndRePasswordMatch() { - $this->specify('error.rePassword_does_not_match if password and rePassword not match', function() { - $model = new RegistrationForm([ - 'password' => 'enough-length', - 'rePassword' => 'password', - ]); - expect($model->validate(['rePassword']))->false(); - expect($model->getErrors('rePassword'))->equals(['error.rePassword_does_not_match']); - }); + $model = new RegistrationForm([ + 'password' => 'enough-length', + 'rePassword' => 'but-mismatch', + ]); + $this->assertFalse($model->validate(['rePassword'])); + $this->assertSame(['error.rePassword_does_not_match'], $model->getErrors('rePassword')); - $this->specify('no errors if password and rePassword match', function() { - $model = new RegistrationForm([ - 'password' => 'enough-length', - 'rePassword' => 'enough-length', - ]); - expect($model->validate(['rePassword']))->true(); - expect($model->getErrors('rePassword'))->isEmpty(); - }); + $model = new RegistrationForm([ + 'password' => 'enough-length', + 'rePassword' => 'enough-length', + ]); + $this->assertTrue($model->validate(['rePassword'])); + $this->assertEmpty($model->getErrors('rePassword')); } public function testSignup() { @@ -118,12 +115,15 @@ class RegistrationFormTest extends TestCase { 'account_id' => $account->id, 'applied_in' => $account->created_at, ])->exists(), 'username history record exists in database'); - $this->tester->canSeeEmailIsSent(1); - /** @var \yii\swiftmailer\Message $email */ - $email = $this->tester->grabSentEmails()[0]; - $body = $email->getSwiftMessage()->getBody(); - $this->assertContains($activation->key, $body); - $this->assertContains('/activation/' . $activation->key, $body); + + /** @var SendRegistrationEmail $job */ + $job = $this->tester->grabLastQueuedJob(); + $this->assertInstanceOf(SendRegistrationEmail::class, $job); + $this->assertSame($account->username, $job->username); + $this->assertSame($account->email, $job->email); + $this->assertSame($account->lang, $job->locale); + $this->assertSame($activation->key, $job->code); + $this->assertSame('http://localhost/activation/' . $activation->key, $job->link); } private function mockRequest($ip = '88.225.20.236') { diff --git a/tests/codeception/api/unit/models/authentication/RepeatAccountActivationFormTest.php b/tests/codeception/api/unit/models/authentication/RepeatAccountActivationFormTest.php index 23acf22..6dbebb1 100644 --- a/tests/codeception/api/unit/models/authentication/RepeatAccountActivationFormTest.php +++ b/tests/codeception/api/unit/models/authentication/RepeatAccountActivationFormTest.php @@ -5,6 +5,7 @@ use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\models\authentication\RepeatAccountActivationForm; use Codeception\Specify; use common\models\EmailActivation; +use common\tasks\SendRegistrationEmail; use GuzzleHttp\ClientInterface; use tests\codeception\api\unit\TestCase; use tests\codeception\common\fixtures\AccountFixture; @@ -69,19 +70,24 @@ class RepeatAccountActivationFormTest extends TestCase { } public function testSendRepeatMessage() { - $this->specify('no magic if we don\'t pass validation', function() { - $model = new RepeatAccountActivationForm(); - expect($model->sendRepeatMessage())->false(); - $this->tester->cantSeeEmailIsSent(); - }); + $model = new RepeatAccountActivationForm(); + $this->assertFalse($model->sendRepeatMessage(), 'no magic if we don\'t pass validation'); + $this->assertEmpty($this->tester->grabQueueJobs()); - $this->specify('successfully send new message if previous message has expired', function() { - $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(); - $this->tester->canSeeEmailIsSent(1); - }); + /** @var \common\models\Account $account */ + $account = $this->tester->grabFixture('accounts', 'not-activated-account-with-expired-message'); + $model = new RepeatAccountActivationForm(['email' => $account->email]); + $this->assertTrue($model->sendRepeatMessage()); + $activation = $model->getActivation(); + $this->assertNotNull($activation); + /** @var SendRegistrationEmail $job */ + $job = $this->tester->grabLastQueuedJob(); + $this->assertInstanceOf(SendRegistrationEmail::class, $job); + $this->assertSame($account->username, $job->username); + $this->assertSame($account->email, $job->email); + $this->assertSame($account->lang, $job->locale); + $this->assertSame($activation->key, $job->code); + $this->assertSame('http://localhost/activation/' . $activation->key, $job->link); } /** diff --git a/tests/codeception/api/unit/modules/accounts/models/SendEmailVerificationFormTest.php b/tests/codeception/api/unit/modules/accounts/models/SendEmailVerificationFormTest.php index 4a34e36..dbee640 100644 --- a/tests/codeception/api/unit/modules/accounts/models/SendEmailVerificationFormTest.php +++ b/tests/codeception/api/unit/modules/accounts/models/SendEmailVerificationFormTest.php @@ -5,6 +5,7 @@ use api\modules\accounts\models\SendEmailVerificationForm; use common\models\Account; use common\models\confirmations\CurrentEmailConfirmation; use common\models\EmailActivation; +use common\tasks\SendCurrentEmailConfirmation; use tests\codeception\api\unit\TestCase; use tests\codeception\common\fixtures\AccountFixture; use tests\codeception\common\fixtures\EmailActivationFixture; @@ -35,11 +36,19 @@ class SendEmailVerificationFormTest extends TestCase { 'password' => 'password_0', ]); $this->assertTrue($model->performAction()); - $this->assertTrue(EmailActivation::find()->andWhere([ + /** @var EmailActivation $activation */ + $activation = EmailActivation::findOne([ 'account_id' => $account->id, 'type' => EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION, - ])->exists()); - $this->tester->canSeeEmailIsSent(); + ]); + $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); } } diff --git a/tests/codeception/api/unit/modules/accounts/models/SendNewEmailVerificationFormTest.php b/tests/codeception/api/unit/modules/accounts/models/SendNewEmailVerificationFormTest.php index 0802019..addee2c 100644 --- a/tests/codeception/api/unit/modules/accounts/models/SendNewEmailVerificationFormTest.php +++ b/tests/codeception/api/unit/modules/accounts/models/SendNewEmailVerificationFormTest.php @@ -5,6 +5,7 @@ use api\modules\accounts\models\SendNewEmailVerificationForm; use common\models\Account; use common\models\confirmations\NewEmailConfirmation; use common\models\EmailActivation; +use common\tasks\SendNewEmailConfirmation; use tests\codeception\api\unit\TestCase; use tests\codeception\common\fixtures\AccountFixture; use tests\codeception\common\fixtures\EmailActivationFixture; @@ -44,11 +45,19 @@ class SendNewEmailVerificationFormTest extends TestCase { Mock::func(EmailValidator::class, 'checkdnsrr')->andReturn(true); $this->assertTrue($model->performAction()); $this->assertNull(EmailActivation::findOne($key)); - $this->assertNotNull(EmailActivation::findOne([ + /** @var EmailActivation $activation */ + $activation = EmailActivation::findOne([ 'account_id' => $account->id, 'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION, - ])); - $this->tester->canSeeEmailIsSent(); + ]); + $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); } } diff --git a/tests/codeception/common/_support/queue/CodeceptionQueueHelper.php b/tests/codeception/common/_support/queue/CodeceptionQueueHelper.php new file mode 100644 index 0000000..8878ea3 --- /dev/null +++ b/tests/codeception/common/_support/queue/CodeceptionQueueHelper.php @@ -0,0 +1,51 @@ +grabQueueJobs(); + return end($messages); + } + + /** + * Returns array of all sent amqp messages. + * Each message is `\PhpAmqpLib\Message\AMQPMessage` instance. + * Useful to perform additional checks using `Asserts` module. + * + * @param string|null $exchange + * @return \yii\queue\JobInterface[] + * @throws ModuleException + */ + public function grabQueueJobs() { + $amqp = $this->grabComponent('queue'); + if (!$amqp instanceof Queue) { + throw new ModuleException($this, 'AMQP module is not mocked, can\'t test messages'); + } + + return $amqp->getMessages(); + } + + private function grabComponent(string $component) { + return $this->getYii2()->grabComponent($component); + } + + private function getYii2(): Yii2 { + $yii2 = $this->getModule('Yii2'); + if (!$yii2 instanceof Yii2) { + throw new ModuleException($this, 'Yii2 module must be configured'); + } + + return $yii2; + } + +} diff --git a/tests/codeception/common/_support/queue/Queue.php b/tests/codeception/common/_support/queue/Queue.php new file mode 100644 index 0000000..169da26 --- /dev/null +++ b/tests/codeception/common/_support/queue/Queue.php @@ -0,0 +1,32 @@ +messages[] = $job; + } + + public function status($id) { + throw new NotSupportedException('Status is not supported in the driver.'); + } + + public function getMessages() { + return $this->messages; + } + + protected function pushMessage($message, $ttr, $delay, $priority) { + // This function is abstract, but will be not called + } + + public function __set($name, $value) { + // Yii2 components may contains some configuration + // But we just ignore it for this mock component + } + +} diff --git a/tests/codeception/common/unit/emails/EmailHelperTest.php b/tests/codeception/common/unit/emails/EmailHelperTest.php index 9b9d011..0f1f62d 100644 --- a/tests/codeception/common/unit/emails/EmailHelperTest.php +++ b/tests/codeception/common/unit/emails/EmailHelperTest.php @@ -2,17 +2,12 @@ namespace tests\codeception\common\unit\emails; use common\emails\EmailHelper; -use common\models\Account; use tests\codeception\common\unit\TestCase; class EmailHelperTest extends TestCase { public function testBuildTo() { - /** @var Account|\Mockery\MockInterface $account */ - $account = mock(Account::class)->makePartial(); - $account->username = 'mock-username'; - $account->email = 'mock@ely.by'; - $this->assertEquals(['mock@ely.by' => 'mock-username'], EmailHelper::buildTo($account)); + $this->assertSame(['mock@ely.by' => 'username'], EmailHelper::buildTo('username', 'mock@ely.by')); } } diff --git a/tests/codeception/common/unit/tasks/SendCurrentEmailConfirmationTest.php b/tests/codeception/common/unit/tasks/SendCurrentEmailConfirmationTest.php new file mode 100644 index 0000000..eb81b0a --- /dev/null +++ b/tests/codeception/common/unit/tasks/SendCurrentEmailConfirmationTest.php @@ -0,0 +1,47 @@ +username = 'mock-username'; + $account->email = 'mock@ely.by'; + $account->lang = 'id'; + + /** @var \Mockery\Mock|CurrentEmailConfirmation $confirmation */ + $confirmation = mock(CurrentEmailConfirmation::class)->makePartial(); + $confirmation->key = 'ABCDEFG'; + $confirmation->shouldReceive('getAccount')->andReturn($account); + + $result = SendCurrentEmailConfirmation::createFromConfirmation($confirmation); + $this->assertInstanceOf(SendCurrentEmailConfirmation::class, $result); + $this->assertSame('mock-username', $result->username); + $this->assertSame('mock@ely.by', $result->email); + $this->assertSame('ABCDEFG', $result->code); + } + + public function testExecute() { + $task = new SendCurrentEmailConfirmation(); + $task->username = 'mock-username'; + $task->email = 'mock@ely.by'; + $task->code = 'GFEDCBA'; + + $task->execute(mock(Queue::class)); + + $this->tester->canSeeEmailIsSent(1); + /** @var \yii\swiftmailer\Message $email */ + $email = $this->tester->grabSentEmails()[0]; + $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); + $this->assertSame('Ely.by Account change E-mail confirmation', $email->getSubject()); + $children = $email->getSwiftMessage()->getChildren()[0]; + $this->assertContains('GFEDCBA', $children->getBody()); + } + +} diff --git a/tests/codeception/common/unit/tasks/SendNewEmailConfirmationTest.php b/tests/codeception/common/unit/tasks/SendNewEmailConfirmationTest.php new file mode 100644 index 0000000..a0fcb12 --- /dev/null +++ b/tests/codeception/common/unit/tasks/SendNewEmailConfirmationTest.php @@ -0,0 +1,47 @@ +username = 'mock-username'; + $account->lang = 'id'; + + /** @var \Mockery\Mock|NewEmailConfirmation $confirmation */ + $confirmation = mock(NewEmailConfirmation::class)->makePartial(); + $confirmation->key = 'ABCDEFG'; + $confirmation->shouldReceive('getAccount')->andReturn($account); + $confirmation->shouldReceive('getNewEmail')->andReturn('new-email@ely.by'); + + $result = SendNewEmailConfirmation::createFromConfirmation($confirmation); + $this->assertInstanceOf(SendNewEmailConfirmation::class, $result); + $this->assertSame('mock-username', $result->username); + $this->assertSame('new-email@ely.by', $result->email); + $this->assertSame('ABCDEFG', $result->code); + } + + public function testExecute() { + $task = new SendNewEmailConfirmation(); + $task->username = 'mock-username'; + $task->email = 'mock@ely.by'; + $task->code = 'GFEDCBA'; + + $task->execute(mock(Queue::class)); + + $this->tester->canSeeEmailIsSent(1); + /** @var \yii\swiftmailer\Message $email */ + $email = $this->tester->grabSentEmails()[0]; + $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); + $this->assertSame('Ely.by Account new E-mail confirmation', $email->getSubject()); + $children = $email->getSwiftMessage()->getChildren()[0]; + $this->assertContains('GFEDCBA', $children->getBody()); + } + +} diff --git a/tests/codeception/common/unit/tasks/SendPasswordRecoveryEmailTest.php b/tests/codeception/common/unit/tasks/SendPasswordRecoveryEmailTest.php new file mode 100644 index 0000000..b7c887b --- /dev/null +++ b/tests/codeception/common/unit/tasks/SendPasswordRecoveryEmailTest.php @@ -0,0 +1,53 @@ +username = 'mock-username'; + $account->email = 'mock@ely.by'; + $account->lang = 'id'; + + /** @var \Mockery\Mock|ForgotPassword $confirmation */ + $confirmation = mock(ForgotPassword::class)->makePartial(); + $confirmation->key = 'ABCDEFG'; + $confirmation->shouldReceive('getAccount')->andReturn($account); + + $result = SendPasswordRecoveryEmail::createFromConfirmation($confirmation); + $this->assertInstanceOf(SendPasswordRecoveryEmail::class, $result); + $this->assertSame('mock-username', $result->username); + $this->assertSame('mock@ely.by', $result->email); + $this->assertSame('ABCDEFG', $result->code); + $this->assertSame('http://localhost/recover-password/ABCDEFG', $result->link); + $this->assertSame('id', $result->locale); + } + + public function testExecute() { + $task = new SendPasswordRecoveryEmail(); + $task->username = 'mock-username'; + $task->email = 'mock@ely.by'; + $task->code = 'GFEDCBA'; + $task->link = 'https://account.ely.by/recover-password/ABCDEFG'; + $task->locale = 'ru'; + + $task->execute(mock(Queue::class)); + + $this->tester->canSeeEmailIsSent(1); + /** @var \yii\swiftmailer\Message $email */ + $email = $this->tester->grabSentEmails()[0]; + $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); + $this->assertSame('Ely.by Account forgot password', $email->getSubject()); + $body = $email->getSwiftMessage()->getBody(); + $this->assertContains('Привет, mock-username', $body); + $this->assertContains('GFEDCBA', $body); + $this->assertContains('https://account.ely.by/recover-password/ABCDEFG', $body); + } + +} diff --git a/tests/codeception/common/unit/tasks/SendRegistrationEmailTest.php b/tests/codeception/common/unit/tasks/SendRegistrationEmailTest.php new file mode 100644 index 0000000..41ace9b --- /dev/null +++ b/tests/codeception/common/unit/tasks/SendRegistrationEmailTest.php @@ -0,0 +1,53 @@ +username = 'mock-username'; + $account->email = 'mock@ely.by'; + $account->lang = 'ru'; + + /** @var \Mockery\Mock|RegistrationConfirmation $confirmation */ + $confirmation = mock(RegistrationConfirmation::class)->makePartial(); + $confirmation->key = 'ABCDEFG'; + $confirmation->shouldReceive('getAccount')->andReturn($account); + + $result = SendRegistrationEmail::createFromConfirmation($confirmation); + $this->assertInstanceOf(SendRegistrationEmail::class, $result); + $this->assertSame('mock-username', $result->username); + $this->assertSame('mock@ely.by', $result->email); + $this->assertSame('ABCDEFG', $result->code); + $this->assertSame('http://localhost/activation/ABCDEFG', $result->link); + $this->assertSame('ru', $result->locale); + } + + public function testExecute() { + $task = new SendRegistrationEmail(); + $task->username = 'mock-username'; + $task->email = 'mock@ely.by'; + $task->code = 'GFEDCBA'; + $task->link = 'https://account.ely.by/activation/ABCDEFG'; + $task->locale = 'ru'; + + $task->execute(mock(Queue::class)); + + $this->tester->canSeeEmailIsSent(1); + /** @var \yii\swiftmailer\Message $email */ + $email = $this->tester->grabSentEmails()[0]; + $this->assertSame(['mock@ely.by' => 'mock-username'], $email->getTo()); + $this->assertSame('Ely.by Account registration', $email->getSubject()); + $body = $email->getSwiftMessage()->getBody(); + $this->assertContains('Привет, mock-username', $body); + $this->assertContains('GFEDCBA', $body); + $this->assertContains('https://account.ely.by/activation/ABCDEFG', $body); + } + +} diff --git a/tests/codeception/config/config.php b/tests/codeception/config/config.php index edd34d4..78b097c 100644 --- a/tests/codeception/config/config.php +++ b/tests/codeception/config/config.php @@ -9,6 +9,9 @@ return [ 'namespace' => 'tests\codeception\common\fixtures', ], ], + 'params' => [ + 'fromEmail' => 'ely@ely.by', + ], 'components' => [ 'urlManager' => [ 'showScriptName' => true, @@ -20,6 +23,9 @@ return [ 'amqp' => [ 'class' => tests\codeception\common\_support\amqp\TestComponent::class, ], + 'queue' => [ + 'class' => tests\codeception\common\_support\queue\Queue::class, + ], 'sentry' => [ 'enabled' => false, ],