def bible( self, request: pytest.FixtureRequest, default_version: str, default_abbr: str, MockBible: type[Any], ) -> Any: name = cast(Callable[..., Any], cast(Any, request).function).__name__ data: dict[str, Any] if name == 'test_search': data = request.getfixturevalue('search_data') elif name == 'test_get_passage': data = request.getfixturevalue('passage_data') else: data = {} return MockBible( command='bib', name='The Bible', abbr=data.get('abbr', default_abbr), service='MyService', service_version=data.get('version', default_version), rtl=False, )
def test_change_container_pass(happi_client: Client, item: str, target: str, request: pytest.FixtureRequest): i = request.getfixturevalue(item) t = request.getfixturevalue(target) kw = happi_client.change_container(i, t) for k in kw: assert i.post()[k] == kw[k]
def test_setup_test_db_creates_db(request: FixtureRequest, db_dsn): server_dsn, dsn, db_name = db_dsn request.getfixturevalue("setup_test_db") with create_db_client(dsn) as db_client: assert len(db_client.query("SELECT File")) == 0 with create_db_client(server_dsn) as db_client: db_client.execute(f"DROP DATABASE {db_name};")
def test_recreates_db_and_applies_migration(request: FixtureRequest, db_dsn): server_dsn, dsn, db_name = db_dsn with create_db_client(server_dsn) as db_client: db_client.execute(f"CREATE DATABASE {db_name};") request.getfixturevalue("setup_test_db") with create_db_client(dsn) as db_client: assert len(db_client.query("SELECT File")) == 0 with create_db_client(server_dsn) as db_client: db_client.execute(f"DROP DATABASE {db_name};")
def db_client_or_tx(request: FixtureRequest): """ Yield either a `tx` or a `db_client` fixture depending on `pytest.mark.database` params. """ marker = request.node.get_closest_marker("database") if not marker: raise RuntimeError("Access to database without `database` marker!") if marker.kwargs.get("transaction", False): yield request.getfixturevalue("db_client") else: yield request.getfixturevalue("tx")
def _config(request: FixtureRequest): """Fixture that parametrizes the configuration used in the tests below.""" test_name = request.function.__name__ model_name: str = request.param # type: ignore model_type = ng.optimizers.registry[model_name] if model_name in NOT_WORKING: pytest.skip(reason=f"Model {model_name} is not supported.") tweaks = MODEL_NAMES[model_name] if model_type.no_parallelization: num_workers = 1 else: num_workers = 10 TestNevergradOptimizer.config["model_name"] = model_name TestNevergradOptimizer.config["num_workers"] = num_workers mark = tweaks.get(test_name, None) current_phase: TestPhase = request.getfixturevalue("phase") if (mark and test_name == "test_seed_rng_init" and request.getfixturevalue("phase").n_trials > 0 and mark in _deterministic_first_point.values()): # Remove the mark, because The algo always gives back the same first trial, regardless of # the seed. This means that since `test_seed_rng_init` expects different seeds to give # different results, the test will fail if we're at the first phase, but pass in other # phases. mark = None if model_name == "MultiScaleCMA" and test_name == "test_state_dict": # NOTE: Only fails at the optimization phase. if current_phase.n_trials == 0: mark = None if mark == "skip": pytest.skip(reason="Skipping test") elif mark: request.node.add_marker(mark) start = TestNevergradOptimizer.max_trials if model_name == "MultiScaleCMA" and test_name == "test_state_dict": TestNevergradOptimizer.max_trials = 20 yield TestNevergradOptimizer.max_trials = start
def test_recreates_db(request: FixtureRequest, db_dsn): server_dsn, dsn, db_name = db_dsn with create_db_client(server_dsn) as db_client: db_client.execute(f"CREATE DATABASE {db_name};") request.getfixturevalue("setup_test_db") with create_db_client(dsn) as db_client: with pytest.raises(edgedb.InvalidReferenceError) as excinfo: assert len(db_client.query("SELECT File")) == 0 assert str(excinfo.value) == "object type or alias 'default::File' does not exist" with create_db_client(server_dsn) as db_client: db_client.execute(f"DROP DATABASE {db_name};")
def postgresql_factory(request: FixtureRequest) -> Iterator[connection]: """ Fixture factory for PostgreSQL. :param request: fixture request object :returns: postgresql client """ check_for_psycopg() proc_fixture: Union[PostgreSQLExecutor, NoopExecutor] = request.getfixturevalue( process_fixture_name) pg_host = proc_fixture.host pg_port = proc_fixture.port pg_user = proc_fixture.user pg_password = proc_fixture.password pg_options = proc_fixture.options pg_db = dbname or proc_fixture.dbname pg_load = load or [] with DatabaseJanitor(pg_user, pg_host, pg_port, pg_db, proc_fixture.version, pg_password, isolation_level) as janitor: db_connection: connection = psycopg.connect( dbname=pg_db, user=pg_user, password=pg_password, host=pg_host, port=pg_port, options=pg_options, ) for load_element in pg_load: janitor.load(load_element) yield db_connection db_connection.close()
def _push_request_context(request: pytest.FixtureRequest): """During tests execution request context has been pushed, e.g. `url_for`, `session`, etc. can be used in tests as is:: def test_app(app, client): assert client.get(url_for('myview')).status_code == 200 """ if "app" not in request.fixturenames: return app = request.getfixturevalue("app") ctx = app.test_request_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown)
def update_parameterized(cls, request: pytest.FixtureRequest, config: BaseConfig): """Update the given configuration object with parameterized values if the key is present""" config_type = config.__class__.__name__ parameterized_keys = cls._get_parameterized_keys(request) for fixture_name in parameterized_keys: with suppress(pytest.FixtureLookupError, AttributeError): if hasattr(config, fixture_name): value = request.getfixturevalue(fixture_name) config.set_value(fixture_name, value) log.debug( f"{config_type}.{fixture_name} value updated from parameterized value to {value}" ) else: raise AttributeError( f"No attribute name {fixture_name} in {config_type} object type" )
async def flush_db_if_needed(request: FixtureRequest): """Flush database after each tests.""" try: yield finally: marker = request.node.get_closest_marker("database") if not marker: return if not marker.kwargs.get("transaction", False): return session_db_client: DBClient = request.getfixturevalue( "session_db_client") await session_db_client.execute(""" DELETE Account; DELETE File; DELETE MediaType; DELETE Namespace; DELETE User; """)
def test_change_container_fail(happi_client: Client, item: str, target: str, request: pytest.FixtureRequest): i = request.getfixturevalue(item) t = request.getfixturevalue(target) with pytest.raises(TransferError): happi_client.change_container(i, t)
def cfg_all(request: FixtureRequest): return request.getfixturevalue(request.param)
def test_automatic_mock_event_emission( server_url_fixture: str, mock_client_wait_timeout: float, mock_client_wait_interval: float, client: socketio.Client, request: pytest.FixtureRequest, ): server_url: str = request.getfixturevalue(server_url_fixture) new_message_event = "new message" new_message_mock_ack = Mock() @client.on(new_message_event) def _new_message_handler(data): jsonschema.validate(data, { "username": { "type": "string" }, "message": { "type": "string" } }) # Assert that message is of sentence format: assert data["message"].endswith(".") assert " " in data["message"] # Assert that username is a first name: assert data["username"].istitle() new_message_mock_ack(new_message_event) typing_event = "typing" typing_mock_ack = Mock() @client.on(typing_event) def _typing_handler(data): jsonschema.validate(data, {"username": {"type": "string"}}) # Assert that username is a first name: assert data["username"].istitle() typing_mock_ack(typing_event) user_joined_event = "user joined" user_joined_mock_ack = Mock() @client.on(user_joined_event) def _user_joined_handler(data): jsonschema.validate(data, { "username": { "type": "string" }, "numUsers": { "type": "integer" } }) # Assert that username is a first name: assert data["username"].istitle() user_joined_mock_ack(user_joined_event) client.connect(server_url, wait_timeout=mock_client_wait_timeout) # Wait for all messages to arrive: client.sleep(mock_client_wait_interval) new_message_mock_ack.assert_called_with(new_message_event) typing_mock_ack.assert_called_with(typing_event) user_joined_mock_ack.assert_called_with(user_joined_event)
def get_fixture_value(request: pytest.FixtureRequest, v: Any) -> Any: """Get the fixture value if it is a fixture, else v.""" try: return request.getfixturevalue(v) except (pytest.FixtureLookupError, TypeError): return v