LoginFormTest.php 1.82 KB
Newer Older
Mark committed
1 2 3 4
<?php

namespace tests\unit\models;

5
use Yii;
6
use yii\codeception\TestCase;
7
use app\models\User;
Mark committed
8

9 10
class LoginFormTest extends TestCase
{
11 12
	use \Codeception\Specify;

Mark committed
13
	protected function tearDown()
Mark committed
14 15 16 17 18
	{
		Yii::$app->user->logout();
		parent::tearDown();
	}

19 20
	public function testLoginNoUser()
	{
21
		$model = $this->mockUser(null);
22 23 24 25

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

MaximAL committed
26
		$this->specify('user should not be able to login, when there is no identity', function () use ($model) {
Mark committed
27 28
			expect('model should not login user', $model->login())->false();
			expect('user should not be logged in', Yii::$app->user->isGuest)->true();
29 30 31 32 33
		});
	}

	public function testLoginWrongPassword()
	{
34
		$model = $this->mockUser(new User);
35 36 37 38

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

39
		$this->specify('user should not be able to login with wrong password', function () use ($model) {
Mark committed
40 41 42
			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();
43 44 45 46 47
		});
	}

	public function testLoginCorrect()
	{
48
		$model = $this->mockUser(new User(['password' => 'demo']));
49 50 51 52

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

MaximAL committed
53
		$this->specify('user should be able to login with correct credentials', function () use ($model) {
Mark committed
54 55 56
			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();
57 58 59 60 61
		});
	}

	private function mockUser($user)
	{
MaximAL committed
62
		$loginForm = $this->getMock('app\models\LoginForm', ['getUser']);
63 64
		$loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
		return $loginForm;
65
	}
Luciano Baraglia committed
66
}