LoginFormTest.php 1.97 KB
Newer Older
Mark committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<?php

namespace common\tests\unit\models;

use Yii;
use frontend\tests\unit\TestCase;
use common\models\User;
use yii\helpers\Security;

class LoginFormTest extends TestCase
{
	
	use \Codeception\Specify;

	protected function tearDown()
	{
		Yii::$app->user->logout();
		parent::tearDown();
	}

	public function testLoginNoUser()
	{
		$model = $this->mockUser(null);

		$model->username = 'some_username';
		$model->password = 'some_password';

AlexGx committed
28
		$this->specify('user should not be able to login, when there is no identity', function () use ($model) {
Mark committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
			expect('model should not login user', $model->login())->false();
			expect('user should not be logged in', Yii::$app->user->isGuest)->true();
		});
	}

	public function testLoginWrongPassword()
	{
		$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('will-not-match')]));

		$model->username = 'demo';
		$model->password = 'wrong-password';

		$this->specify('user should not be able to login with wrong password', function () use ($model) {
			expect('model should not login user', $model->login())->false();
			expect('error message should be set', $model->errors)->hasKey('password');
			expect('user should not be logged in', Yii::$app->user->isGuest)->true();
		});
	}

	public function testLoginCorrect()
	{
		$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('demo')]));

		$model->username = 'demo';
		$model->password = 'demo';

AlexGx committed
55
		$this->specify('user should be able to login with correct credentials', function () use ($model) {
Mark committed
56 57 58 59 60 61 62 63
			expect('model should login user', $model->login())->true();
			expect('error message should not be set', $model->errors)->hasntKey('password');
			expect('user should be logged in', Yii::$app->user->isGuest)->false();
		});
	}

	private function mockUser($user)
	{
AlexGx committed
64
		$loginForm = $this->getMock('common\models\LoginForm', ['getUser']);
Mark committed
65 66 67 68
		$loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
		return $loginForm;
	}
}