Codeception/module-db

Suggestion: Add a function that waits for a value to appear in database

dimitris-am opened this issue · 1 comments

This is a suggestion for a new function that waits for a value to appear in the database.
That would be helpful for many engineers in order to reduce actual needs of using explicit waiting when running tests.

In the example below, the actual waiting time (0.5 seconds) could also be an argument and many more improvements that you guys could think of :)

Thanks for reading and for your great work!

Proof of concept:

/**
* Waits for a certain value to appear in the database.
 *
 * @param string $expectedValue      Expected value to be used in assertion.
 * @param string $table              DB Table.
 * @param string $field              Field of db table.
 * @param array  $criteria           Criteria for db query.
 * @param int    $maxNumberOfRetries Maximum number of retries.
 *
 * @throws Exception
 */
public function waitForValueInDb( $expectedValue, $table, $field, $criteria, $maxNumberOfRetries = 10 ) {

	$actualValue = null;

	for ( $i = 0; $i <= $maxNumberOfRetries; $i++ ) {
		$actualValue = $this->grabFromDatabase( $table, $field, $criteria );

		if ( $actualValue !== false ) {
			continue;
		}
		$this->wait( 0.5 );
	}
	$this->assertEquals( $expectedValue, $actualValue, "Expected value wasn't matched with the actual one fetched from db." );
}

You can use existing retry functionality as documented in https://codeception.com/docs/03-AcceptanceTests#Retry

  1. Enable step decorator by adding this section to codeception.yaml or acceptance.suite.yaml (or any other suite.yaml file)
step_decorators:
  - \Codeception\Step\Retry
  1. Add \Codeception\Lib\Actor\Shared\Retry trait into AcceptanceTester class
  2. Use retrySeeInDatabase action in your test.