首先,你提供的测试用例不是单元测试,它叫集成测试,因为它依赖于环境中可用的MySQL服务器。
然后,我们将进行集成测试。没有深入研究使用 PHPUnit 进行正确 DB 测试的复杂性以使事情变得足够简单,这是示例测试用例类,在编写时考虑到了可用性:
测试.php
<?php
require_once(__DIR__.'/code.php');
class BruteForceTests extends PHPUnit_Framework_TestCase
{
/** @test */
public function NoLoginAttemptsNoBruteforce()
{
// Given empty dataset any random time will do
$any_random_time = date('H:i');
$this->assertFalse(
$this->isUserTriedToBruteForce($any_random_time)
);
}
/** @test */
public function DoNotDetectBruteforceIfLessThanFiveLoginAttemptsInLastTwoHours()
{
$this->userLogged('5:34');
$this->userLogged('4:05');
$this->assertFalse(
$this->isUserTriedToBruteForce('6:00')
);
}
/** @test */
public function DetectBruteforceIfMoreThanFiveLoginAttemptsInLastTwoHours()
{
$this->userLogged('4:36');
$this->userLogged('4:23');
$this->userLogged('4:00');
$this->userLogged('3:40');
$this->userLogged('3:15');
$this->userLogged('3:01'); // ping! 6th login, just in time
$this->assertTrue(
$this->isUserTriedToBruteForce('5:00')
);
}
//==================================================================== SETUP
/** @var PDO */
private $connection;
/** @var PDOStatement */
private $inserter;
const DBNAME = 'test';
const DBUSER = 'tester';
const DBPASS = 'secret';
const DBHOST = 'localhost';
public function setUp()
{
$this->connection = new PDO(
sprintf('mysql:host=%s;dbname=%s', self::DBHOST, self::DBNAME),
self::DBUSER,
self::DBPASS
);
$this->assertInstanceOf('PDO', $this->connection);
// Cleaning after possible previous launch
$this->connection->exec('delete from login_attempts');
// Caching the insert statement for perfomance
$this->inserter = $this->connection->prepare(
'insert into login_attempts (`user_id`, `time`) values(:user_id, :timestamp)'
);
$this->assertInstanceOf('PDOStatement', $this->inserter);
}
//================================================================= FIXTURES
// User ID of user we care about
const USER_UNDER_TEST = 1;
// User ID of user who is just the noise in the DB, and should be skipped by tests
const SOME_OTHER_USER = 2;
/**
* Use this method to record login attempts of the user we care about
*
* @param string $datetime Any date & time definition which `strtotime()` understands.
*/
private function userLogged($datetime)
{
$this->logUserLogin(self::USER_UNDER_TEST, $datetime);
}
/**
* Use this method to record login attempts of the user we do not care about,
* to provide fuzziness to our tests
*
* @param string $datetime Any date & time definition which `strtotime()` understands.
*/
private function anotherUserLogged($datetime)
{
$this->logUserLogin(self::SOME_OTHER_USER, $datetime);
}
/**
* @param int $userid
* @param string $datetime Human-readable representation of login time (and possibly date)
*/
private function logUserLogin($userid, $datetime)
{
$mysql_timestamp = date('Y-m-d H:i:s', strtotime($datetime));
$this->inserter->execute(
array(
':user_id' => $userid,
':timestamp' => $mysql_timestamp
)
);
$this->inserter->closeCursor();
}
//=================================================================== HELPERS
/**
* Helper to quickly imitate calling of our function under test
* with the ID of user we care about, clean connection of correct type and provided testing datetime.
* You can call this helper with the human-readable datetime value, although function under test
* expects the integer timestamp as an origin date.
*
* @param string $datetime Any human-readable datetime value
* @return bool The value of called function under test.
*/
private function isUserTriedToBruteForce($datetime)
{
$connection = $this->tryGetMysqliConnection();
$timestamp = strtotime($datetime);
return wasTryingToBruteForce(self::USER_UNDER_TEST, $connection, $timestamp);
}
private function tryGetMysqliConnection()
{
$connection = new mysqli(self::DBHOST, self::DBUSER, self::DBPASS, self::DBNAME);
$this->assertSame(0, $connection->connect_errno);
$this->assertEquals("", $connection->connect_error);
return $connection;
}
}
该测试套件是自包含的,具有三个测试用例:当没有登录尝试记录时,当检查时两小时内有六次登录尝试记录时,以及同一时间段内只有两次登录尝试记录时.
这是测试套件的不足,例如,您需要测试暴力检查是否真的只对我们感兴趣的用户有效,而忽略其他用户的登录尝试。另一个例子是,您的函数应该真正选择以检查时间结束的两小时间隔内的记录,而不是在检查时间减去两小时后存储的所有记录(就像现在一样)。您可以自己编写所有剩余的测试。
该测试套件使用 连接到数据库PDO
,这绝对优于mysqli
接口,但针对被测功能的需要,它会创建适当的连接对象。
应该注意一个非常重要的注意事项:由于静态依赖于此处的不可控库函数,因此您的函数是不可测试的:
// Get timestamp of current time
$now = time();
检查时间应提取到函数参数中,以便通过自动方式测试函数,如下所示:
function wasTryingToBruteForce($user_id, $connection, $now)
{
if (!$now)
$now = time();
//... rest of code ...
}
如您所见,我已将您的函数重命名为更清晰的名称。
除此之外,我想你在使用 MySQL 和 PHP 之间的 datetime 值时应该非常小心,并且永远不要通过连接字符串来构造 SQL 查询,而是使用参数绑定。因此,您的初始代码的稍微清理过的版本如下(请注意,测试套件在第一行就需要它):
代码.php
<?php
/**
* Checks whether user was trying to bruteforce the login.
* Bruteforce is defined as 6 or more login attempts in last 2 hours from $now.
* Default for $now is current time.
*
* @param int $user_id ID of user in the DB
* @param mysqli $connection Result of calling `new mysqli`
* @param timestamp $now Base timestamp to count two hours from
* @return bool Whether the $user_id tried to bruteforce login or not.
*/
function wasTryingToBruteForce($user_id, $connection, $now)
{
if (!$now)
$now = time();
$two_hours_ago = $now - (2 * 60 * 60);
$since = date('Y-m-d H:i:s', $two_hours_ago); // Checking records of login attempts for last 2 hours
$stmt = $connection->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > ?");
if ($stmt) {
$stmt->bind_param('is', $user_id, $since);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if ($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
就我个人的口味而言,这种检查方法效率很低,您可能真的想进行以下查询:
select count(time)
from login_attempts
where
user_id=:user_id
and time between :two_hours_ago and :now
由于这是集成测试,因此它需要工作的可访问 MySQL 实例,其中包含数据库并定义了下表:
mysql> describe login_attempts;
+---------+------------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+-------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | YES | | NULL | |
| time | timestamp | NO | | CURRENT_TIMESTAMP | |
+---------+------------------+------+-----+-------------------+----------------+
3 rows in set (0.00 sec)
考虑到被测函数的工作原理,这只是我个人的猜测,但我想你确实有这样的表格。
在运行测试之前,您必须DB*
在文件的“SETUP”部分中配置常量tests.php
。