Handle SUITE_BEFORE event.

Create a full standalone TYPO3 instance within typo3temp/var/tests/acceptance,
create a database and create database schema.
431693
public function bootstrapTypo3Environment(TestEvent $event)
    {
        $testbase = new Testbase();
        $testbase->enableDisplayErrors();
        $testbase->defineBaseConstants();
        $testbase->defineOriginalRootPath();
        $testbase->setTypo3TestingContext();

        $instancePath = ORIGINAL_ROOT . 'typo3temp/var/tests/acceptance';
        $testbase->removeOldInstanceIfExists($instancePath);
        putenv('TYPO3_PATH_ROOT=' . $instancePath);
        putenv('TYPO3_PATH_APP=' . $instancePath);

        // Drop db from a previous run if exists
        $connectionParameters = [
            'driver' => 'mysqli',
            'host' => $this->config['typo3InstallMysqlDatabaseHost'],
            'port' => 3306,
            'password' => $this->config['typo3InstallMysqlDatabasePassword'],
            'user' => $this->config['typo3InstallMysqlDatabaseUsername'],
        ];
        $this->output->debug("Connecting to MySQL: " . json_encode($connectionParameters));
        $databaseName = $this->config['typo3InstallMysqlDatabaseName'];
        $schemaManager = DriverManager::getConnection($connectionParameters)->getSchemaManager();
        $this->output->debug("Database: $databaseName");
        if (in_array($databaseName, $schemaManager->listDatabases(), true)) {
            $this->output->debug("Dropping database $databaseName");
            $schemaManager->dropDatabase($databaseName);
        }

        $testbase->createDirectory($instancePath);
        $testbase->setUpInstanceCoreLinks($instancePath);
        touch($instancePath . '/FIRST_INSTALL');

        // Have config available in test
        $event->getTest()->getMetadata()->setCurrent($this->config);
    }
861207
def create_schema(self, check_if_exists=False, sync_schema=True,
                      verbosity=1):
        

        # safety check
        connection = connections[get_tenant_database_alias()]
        _check_schema_name(self.schema_name)
        cursor = connection.cursor()

        if check_if_exists and schema_exists(self.schema_name):
            return False

        fake_migrations = get_creation_fakes_migrations()

        if sync_schema:
            if fake_migrations:
                # copy tables and data from provided model schema
                base_schema = get_tenant_base_schema()
                clone_schema = CloneSchema()
                clone_schema.clone_schema(base_schema, self.schema_name)

                call_command('migrate_schemas',
                             tenant=True,
                             fake=True,
                             schema_name=self.schema_name,
                             interactive=False,
                             verbosity=verbosity)
            else:
                # create the schema
                cursor.execute('CREATE SCHEMA %s' % self.schema_name)
                call_command('migrate_schemas',
                             tenant=True,
                             schema_name=self.schema_name,
                             interactive=False,
                             verbosity=verbosity)

        connection.set_schema_to_public()
50223
def before_insert(mapper, conn, target):
        """"""
        from sqlalchemy import text

        if not target.id:
            sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did')

            target.id, = conn.execute(sql, did=target.d_vid).fetchone()

            if not target.id:
                target.id = 1

        if target.contents and isinstance(target.contents, six.text_type):
            target.contents = target.contents.encode('utf-8')

        File.before_update(mapper, conn, target)
171821
public void beforeSuite(String suiteName, String ... testGroups) {
        testSuiteListener.onStart();

        if (!CollectionUtils.isEmpty(beforeSuite)) {
            for (SequenceBeforeSuite sequenceBeforeSuite : beforeSuite) {
                try {
                    if (sequenceBeforeSuite.shouldExecute(suiteName, testGroups)) {
                        sequenceBeforeSuite.execute(createTestContext());
                    }
                } catch (Exception e) {
                    testSuiteListener.onStartFailure(e);
                    afterSuite(suiteName, testGroups);

                    throw new AssertionError("Before suite failed with errors", e);
                }
            }

            testSuiteListener.onStartSuccess();
        } else {
            testSuiteListener.onStartSuccess();
        }
    }
634925
def create_app(test_config=None):
    """"""
    app = Flask(__name__, instance_relative_config=True)

    # some deploy systems set the database url in the environ
    db_url = os.environ.get("DATABASE_URL")

    if db_url is None:
        # default to a sqlite database in the instance folder
        db_url = "sqlite:///" + os.path.join(app.instance_path, "flaskr.sqlite")
        # ensure the instance folder exists
        os.makedirs(app.instance_path, exist_ok=True)

    app.config.from_mapping(
        # default secret that should be overridden in environ or config
        SECRET_KEY=os.environ.get("SECRET_KEY", "dev"),
        SQLALCHEMY_DATABASE_URI=db_url,
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.update(test_config)

    # initialize Flask-SQLAlchemy and the init-db command
    db.init_app(app)
    app.cli.add_command(init_db_command)

    # apply the blueprints to the app
    from flaskr import auth, blog

    app.register_blueprint(auth.bp)
    app.register_blueprint(blog.bp)

    # make "index" point at "/", which is handled by "blog.index"
    app.add_url_rule("/", endpoint="index")

    return app
633217
def session_prepare(self, session, _):
        
        if not hasattr(session, 'meepo_unique_id'):
            self._session_init(session)

        evt = collections.defaultdict(set)
        for action in ("write", "update", "delete"):
            objs = getattr(session, "pending_%s" % action)
            # filter tables if possible
            if self.tables:
                objs = [o for o in objs
                        if o.__table__.fullname in self.tables]
            for obj in objs:
                evt_name = "%s_%s" % (obj.__table__.fullname, action)
                evt[evt_name].add(obj)
                self.logger.debug("%s - session_prepare: %s -> %s" % (
                    session.meepo_unique_id, evt_name, evt))

        # only trigger signal when event exists
        if evt:
            signal("session_prepare").send(session, event=evt)
732471
public function main()
    {
        if ($this->codecoverage && !extension_loaded('xdebug')) {
            throw new Exception("PHPUnitTask depends on Xdebug being installed to gather code coverage information.");
        }

        $this->loadPHPUnit();

        if (class_exists('\PHPUnit_Framework_TestSuite')) {
            $suite = new PHPUnit_Framework_TestSuite('AllTests');
        } else {
            $suite = new \PHPUnit\Framework\TestSuite('AllTests');
        }

        $autoloadSave = spl_autoload_functions();

        if ($this->bootstrap) {
            include $this->bootstrap;
        }

        if ($this->configuration) {
            $arguments = $this->handlePHPUnitConfiguration($this->configuration);

            if ($arguments['backupGlobals'] === false) {
                $suite->setBackupGlobals(false);
            }

            if ($arguments['backupStaticAttributes'] === true) {
                $suite->setBackupStaticAttributes(true);
            }
        }

        if ($this->printsummary) {
            $fe = new FormatterElement();
            $fe->setParent($this);
            $fe->setType("summary");
            $fe->setUseFile(false);
            $this->formatters[] = $fe;
        }

        foreach ($this->batchtests as $batchTest) {
            $this->appendBatchTestToTestSuite($batchTest, $suite);
        }

        $this->execute($suite);

        if ($this->testfailed) {
            throw new BuildException($this->testfailuremessage);
        }

        $autoloadNew = spl_autoload_functions();
        if (is_array($autoloadNew)) {
            foreach ($autoloadNew as $autoload) {
                spl_autoload_unregister($autoload);
            }
        }

        if (is_array($autoloadSave)) {
            foreach ($autoloadSave as $autoload) {
                spl_autoload_register($autoload);
            }
        }
    }
847601
function Suite(options) {
	Emitter.call(this);
	// Suite extensions
	this.plugins = {};

	// Raw tests
	this.tests = [];

	// API
	this.api = api;

	// Parse options
	this.options = this._parseOptions(options);

	// Logger
	this.log = bunyan.createLogger({
		name: 'picky',
		streams: this.options.log
	});

	// Load the plugins
	this.options.plugins.forEach(function (name) {
		this.usePlugin(name);
	}, this);
}
165830
protected function before() {
		if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
			$this->connection->executeUpdate('EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"');
		} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
			$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=0');
		} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
			$this->connection->executeUpdate('PRAGMA foreign_keys = OFF');
		}
	}
443166
private void beforeSessionEvent() throws NewSessionException {
    RemoteProxy p = session.getSlot().getProxy();
    if (p instanceof TestSessionListener) {
      try {
        ((TestSessionListener) p).beforeSession(session);
      } catch (Exception e) {
        log.severe("Error running the beforeSessionListener : " + e.getMessage());
        e.printStackTrace();
        throw new NewSessionException("The listener threw an exception ( listener bug )", e);
      }
    }
  }
248506
function _suite(description, cb) {
            var test = new this(description, {});
            var it = test._addAction;
            _(["suite", "test", "timeout", "getAction", "beforeAll", "beforeEach",
                "afterAll", "afterEach", "context", "get", "set", "skip"]).forEach(function (key) {
                    it[key] = test[key];
                });
            cb(test);
            return test;
        }
505521
def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True,
           accept_context=False):
    """"""
    extend = extend if type(extend) == type else type(extend)

    def new_type_handler(function):
        class NewType(extend):
            __slots__ = ()
            _accept_context = accept_context

            if chain and extend != Type:
                if error_text or exception_handlers:
                    if not accept_context:
                        def __call__(self, value):
                            try:
                                value = super(NewType, self).__call__(value)
                                return function(value)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        if extend._accept_context:
                            def __call__(self, value, context):
                                try:
                                    value = super(NewType, self).__call__(value, context)
                                    return function(value, context)
                                except Exception as exception:
                                    for take_exception, rewrite in exception_handlers.items():
                                        if isinstance(exception, take_exception):
                                            if isinstance(rewrite, str):
                                                raise ValueError(rewrite)
                                            else:
                                                raise rewrite(value)
                                    if error_text:
                                        raise ValueError(error_text)
                                    raise exception
                        else:
                            def __call__(self, value, context):
                                try:
                                    value = super(NewType, self).__call__(value)
                                    return function(value, context)
                                except Exception as exception:
                                    for take_exception, rewrite in exception_handlers.items():
                                        if isinstance(exception, take_exception):
                                            if isinstance(rewrite, str):
                                                raise ValueError(rewrite)
                                            else:
                                                raise rewrite(value)
                                    if error_text:
                                        raise ValueError(error_text)
                                    raise exception
                else:
                    if not accept_context:
                        def __call__(self, value):
                            value = super(NewType, self).__call__(value)
                            return function(value)
                    else:
                        if extend._accept_context:
                            def __call__(self, value, context):
                                value = super(NewType, self).__call__(value, context)
                                return function(value, context)
                        else:
                            def __call__(self, value, context):
                                value = super(NewType, self).__call__(value)
                                return function(value, context)
            else:
                if not accept_context:
                    if error_text or exception_handlers:
                        def __call__(self, value):
                            try:
                                return function(value)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        def __call__(self, value):
                            return function(value)
                else:
                    if error_text or exception_handlers:
                        def __call__(self, value, context):
                            try:
                                return function(value, context)
                            except Exception as exception:
                                for take_exception, rewrite in exception_handlers.items():
                                    if isinstance(exception, take_exception):
                                        if isinstance(rewrite, str):
                                            raise ValueError(rewrite)
                                        else:
                                            raise rewrite(value)
                                if error_text:
                                    raise ValueError(error_text)
                                raise exception
                    else:
                        def __call__(self, value, context):
                            return function(value, context)

        NewType.__doc__ = function.__doc__ if doc is None else doc
        if auto_instance and not (introspect.arguments(NewType.__init__, -1) or
                                  introspect.takes_kwargs(NewType.__init__) or
                                  introspect.takes_args(NewType.__init__)):
            return NewType()
        return NewType

    return new_type_handler
268015
def before_all(context):
    
    lf = LoggerFactory(config_file='../features/resources/test_config.yaml')
    lf.initialize()
    ll = lf.get_instance('environment')
    ll.info('Logger initialized: {}'.format(lf.config))
    ll.info('Initial test context: {}'.format(context))
1309275
function createDatabase(tx) {
    var schema = "clicks (id integer primary key, date text)"
    var sql = "create table if not exists " + schema

    tx.executeSql(sql, null, clearDatabase, sqlError);
}
1356212
def before_scenario(context, scenario):
    """"""

    # Prepare a new temporary directory.
    context.directory = testfixtures.TempDirectory(create=True)
    context.old_cwd = os.getcwd()
    context.new_cwd = context.directory.path

    # Move into our new working directory.
    os.chdir(context.new_cwd)
635526
function SuiteModel (name) {
  this.className = 'js.' + name
  this.scenarios = []
  this.tagMap = {}
  this.tagMap.JS = new TagModel('JS')

  log('Creating new model ' + this.className)
}
554880
public function beforeSuite(SuiteEvent $e)
    {
        $this->namespace = "";
        $settings = $e->getSettings();
        if (isset($settings['namespace'])) {
            $this->namespace = $settings['namespace'];
        }
        $this->message("%s Tests (%d) ")
            ->with(ucfirst($e->getSuite()->getName()), $e->getSuite()->count())
            ->style('bold')
            ->width($this->width, '-')
            ->prepend("\n")
            ->writeln();

        if ($e->getSuite() instanceof Suite) {
            $message = $this->message(
                implode(
                    ', ',
                    array_map(
                        function ($module) {
                            return $module->_getName();
                        },
                        $e->getSuite()->getModules()
                    )
                )
            );

            $message->style('info')
                ->prepend('Modules: ')
                ->writeln(OutputInterface::VERBOSITY_VERBOSE);
        }

        $this->message('')->width($this->width, '-')->writeln(OutputInterface::VERBOSITY_VERBOSE);
    }