Codeception DB cleanup on functional tests

Goodnight all,

I am writing functional tests (at last!) and they are functioning satisfactorily, except for a reason. The test fills a certain form and send it and then makes some confirmations to see if everything worked well. However, as each test runs, a new registry linked to form (News) is generated in the DB. Ie, 10 tests performed, 10 new records.

I need BD to be cleaned up on each functional testing, either by deleting and recreating or truncate the tables.

I’ve read almost all the codeception manual, already searched in all that can be called internet, already swept the world and nothing, I have not found solution. I’ve tried using the solution offered in Codeception (see below) but I have already included the configuration into multiple files * .yml to figure out which correct (always remaking the codecept build) and I could not.

I tried setting in many codeceptions*.yml:




modules:

	config:

    	Db:

        	dns: 'mysql:host=localhost;dbname=banco_testes'

        	user: 'root'

        	password: 'secret'

        	dump: dump-de-dados.sql



Anyone that works with tests or know how to solve it could give that BIG help, please?

Would greatly appreciate it!

Sidney Lins

I received an idea "not oficial" in the yii-framework-brazil list:




'db' => [

		+	'class' => 'yii\db\Connection',

		+	// ...

		+	'on afterOpen' => function($event) {

                   	//do something to delete/truncate tables here

                   	//(just workaround)

		+	}

],



(posting here to help someone more in that same situation)

I will try… but, anymore ideas here?

Thank you.

Partially solved !!

As promised here is my code (perhaps it can be useful to others) based on onAfterOpen event of the connection:




// In my file tests / codeception / config / config.php


     	'db' => [

        	'dsn' => '...',

        	'on afterOpen' => function ($event) {

            	$path = dirname(__DIR__) . '/path/to/dumpfile.sql';

            	$sql = file_get_contents($path);

            	$event->sender->pdo->exec($sql);

        	},

    	],



My dumpfile has several instructions in, including TRUNCATE tables and insertion of records. It was necessary to use the PDO because the Command::execute() only executes one sql command for calling, ignoring the others.

I will still try to solve this by using the "codeception way" to do so. Still accepting suggestions. But for now it is a considerable progress!

Sidney Lins

Hi

Here is what I use




	public static function setUpBeforeClass()

	{

		// store as class property so it is still available in tearDown method

		self::$app = new yii\web\Application(require(dirname(dirname(__DIR__)) . '/config/frontend/functional.php'));

		$db = self::$app->db;

		list($dbData, $dbName) = explode(';', $db->dsn);

		$dbName = str_replace('dbname=', '', $dbName);

		$dbFile = __DIR__ . '/fixtures/data/db.sql.gz';

		if (file_exists($dbFile) === false) {

			throw new \Exception('Unable to find dbfile');

		}

		$command = "gunzip -cf $dbFile | " . sprintf('mysql -u %s -p%s %s', $db->username, $db->password, $dbName);

		exec($command, $output, $retVar);

	}


	public static function tearDownAfterClass()

	{

		$db = self::$app->db;

		$command = $db->createCommand('SET FOREIGN_KEY_CHECKS=0')->execute();

		$command = $db->createCommand("SHOW FULL TABLES WHERE TABLE_TYPE LIKE '%TABLE'");

		$res = $command->queryAll();

		foreach ($res as $row) {

			$command = $db->createCommand('TRUNCATE TABLE `' . $row['Tables_in_test'] . '`')->execute();

		}

		$command = $db->createCommand('SET FOREIGN_KEY_CHECKS=1')->execute();

	}



Hi Flarpy,

Thank you for your answer but where do you use your methods, I mean, which class? I think it would be useful for unit tests, but maybe not in functional tests. Can you give some more details? Thanks.

Bye the way, i am being able to use my solution/workaround temporarily.

I think there are no much information about tests on yii2. If we read codeception instructions they dont work with yii2 (in this case, at least). But in the guide, we dont have enough info. The same in tests/README.md. So, we have to "crack" the things, unfortunately. I feel tempted to make a "direct" codeception installation, without yii2 plugin, just to see what happens, but I know it could be very hard.