How in codeception to make rollback a database if the test failed?

六月ゝ 毕业季﹏ 提交于 2019-12-24 19:27:39

问题


I need to test the feature in account. But for this need register an account. If the feature does not work correctly and the test fails, how do I can automatically delete an account from a database (account created during testing)?


回答1:


I think you have a few options.

You can do clean-up in your Cest class's _before or _after methods (if you use a framework you could use an ORM to delete all accounts for example).

Codeception's Db module (see https://codeception.com/docs/modules/Db) also has a cleanup flag which, when true, will load a user-defined database dump before each test (you could create a dump with no accounts).

There might be other options too. If you use Yii2 for example, the Yii2 module for Codeception has a cleanup flag that will wrap tests in a transaction if true (see https://codeception.com/for/yii).




回答2:


We are facing problems like this, too. If you insert the account with the DB module of codception you can use the cleanup flag and it will automaticly clean up the database after each run.

If you create the account by a test and you want to go sure that the account isn't existing before you start the test you can extend the DB module by a delete function (that has to used with care, we only allow that in testing environments).

<?php

namespace Helper\Shared;

class DbHelper extends \Codeception\Module {

    public function deleteFromDatabase($table, $criteria)
    {
        $dbh = $this->getModule('Db')->_getDbh();
        $query = "delete from `%s` where %s";
        $params = [];
        foreach ($criteria as $x => $y) {
            $params[] = "`$x` = '$y'";
        }
        $params = implode(' AND ', $params);
        $query = sprintf($query, $table, $params);
        codecept_debug($query);
        $this->debugSection('Query', $query, json_encode($criteria));
        $sth = $dbh->prepare($query);
        return $sth->execute(array_values($criteria));
    }
}

This can be used in the test code with ...

$I->deleteFromDatabase('account', ['id' => '123456']);

If it's possible the DB Module should be used to create the account and clean it up again. This method above is pretty dangerous dependend on the systems you are using it.



来源:https://stackoverflow.com/questions/54582326/how-in-codeception-to-make-rollback-a-database-if-the-test-failed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!