Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Codeception\Configuration;
- use Codeception\Exception\ModuleConfigException;
- /**
- * Use Codeception event hooks to modify setup an existing database (e.g copy of live or a development database) for tests
- * rather than rather than dumping and reloading a test database using the DB module
- *
- * 1. Add this file to the /_support/ directory
- * 2. Add your SQL files to the /_data/ directory
- * 3. Modify Codecption.yml to enable the extension and add DSN details e.g.
- *
- * extensions:
- * enabled:
- * - Codeception\Extension\RunFailed
- * - SetupDatabaseExtension
- * modules:
- * config:
- * Db:
- * dsn: 'mysql:host=localhost;dbname=uyls5'
- * user: 'root'
- * password: '123456'
- * dump: tests/_data/dump.sql
- * populate: false
- * cleanup: false
- *
- *
- */
- class SetupDatabaseExtension extends \Codeception\Extension
- {
- /**
- * Events to listen to
- * @var array
- */
- public static $events = array(
- 'suite.after' => 'afterSuite',
- 'suite.before' => 'beforeSuite'
- );
- /**
- * @var \Codeception\Module\Db
- */
- protected $db = null;
- /**
- *
- * @param \Codeception\Event\SuiteEvent $e
- */
- public function beforeSuite(\Codeception\Event\SuiteEvent $e)
- {
- print 'Running beforeSuite()...' . PHP_EOL;
- $this->db = $this->getModule('Db')->dbh;
- $this->setupExample();
- // $this->setupSomethingElse();
- // etc.
- }
- /**
- *
- * @param \Codeception\Event\SuiteEvent $e
- */
- public function afterSuite(\Codeception\Event\SuiteEvent $e)
- {
- print 'Running afterSuite()...' . PHP_EOL;
- $this->db = $this->getModule('Db')->dbh;
- $this->cleanupExample();
- // $this->cleanupSomethingElse();
- // etc.
- }
- /**
- *
- */
- protected function setupExample()
- {
- print 'Running setupExample()...' . PHP_EOL;
- $query = $this->load('example_before');
- $sth = $this->db->prepare($query);
- $sth->execute();
- }
- /**
- * Load an SQL query from a file to reset the database after the test suite has run
- */
- protected function cleanupExample()
- {
- print 'Running cleanupExample()...' . PHP_EOL;
- $query = $this->load('example_after');
- $sth = $this->db->prepare($query);
- $sth->execute();
- }
- /**
- * Load an sqlstring from a file stored in the _data directory
- * @param unknown $file
- * @throws ModuleConfigException
- * @return string sqlstring
- */
- protected function load($file)
- {
- $path = Configuration::dataDir() . $file . '.sql';
- if (!file_exists($path)) {
- throw new ModuleConfigException(
- __CLASS__,
- "\nFile with dump doesn't exist.\n"
- . "Please, check path for sql file: "
- . $path
- );
- }
- $sqlstring = file_get_contents($path);
- return $sqlstring;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement