def test_consistent_read_true(mocker): boto_mock = mocker.patch('flask_dynamodb_sessions.boto3.client') boto_mock_instance = boto_mock() boto_mock_instance.get_item.return_value = {'Item': {'data': ''}} app = create_test_app(SESSION_DYNAMODB_USE_HEADER=True, SESSION_DYNAMODB_CONSISTENT_READ=True) mocker.spy(boto_mock, 'get_item') response = app.test_client().get('/test_route', headers={'X-SessionId': 'foo'}) # Validate ConsistentRead setting assert 'ConsistentRead=True' in str(boto_mock_instance.get_item.call_args)
def test_free_money_request_success(mocker): fake_address = "fake-address" amount = 10 client = MockApiClient() mocker.spy(client, 'broadcast_transform') init_free_money(client, fake_address, amount) client.broadcast_transform.assert_called_once() broadcasted_transform = client.broadcast_transform.call_args[0][0] assert type(broadcasted_transform) is FreeMoney assert broadcasted_transform.amount == amount assert broadcasted_transform.receiver == fake_address
def test_get_saml_assertion_uses_listen_port(mocker): bacp: BrowserAzureCredentialsProvider = make_valid_browser_azure_credential_provider( ) mocked_token: str = "test_token" mocked_saml_assertion: str = "test_saml_assertion" mocked_socket = MockSocket() mocker.patch( "redshift_connector.plugin.BrowserAzureCredentialsProvider.get_listen_socket", return_value=mocked_socket) mocker.patch( "redshift_connector.plugin.BrowserAzureCredentialsProvider.fetch_authorization_token", return_value=mocked_token) mocker.patch( "redshift_connector.plugin.BrowserAzureCredentialsProvider.fetch_saml_response", return_value=mocked_saml_assertion, ) mocker.patch( "redshift_connector.plugin.BrowserAzureCredentialsProvider.wrap_and_encode_assertion", return_value=None) get_listen_socket_spy = mocker.spy(BrowserAzureCredentialsProvider, "get_listen_socket") fetch_auth_spy = mocker.spy(BrowserAzureCredentialsProvider, "fetch_authorization_token") fetch_saml_spy = mocker.spy(BrowserAzureCredentialsProvider, "fetch_saml_response") wrap_and_encode_spy = mocker.spy(BrowserAzureCredentialsProvider, "wrap_and_encode_assertion") bacp.get_saml_assertion() assert bacp.redirectUri == "http://localhost:{port}/redshift/".format( port=bacp.listen_port) assert get_listen_socket_spy.called assert get_listen_socket_spy.call_count == 1 assert fetch_auth_spy.called assert fetch_auth_spy.call_count == 1 assert fetch_auth_spy.call_args[0][0] == mocked_socket assert fetch_saml_spy.called assert fetch_saml_spy.call_count == 1 assert fetch_saml_spy.call_args[0][0] == mocked_token assert wrap_and_encode_spy.called assert wrap_and_encode_spy.call_count == 1 assert wrap_and_encode_spy.call_args[0][0] == mocked_saml_assertion
def test_get_columns(mocker, _input, db_kwargs): database_metadata_current_db_only_val, _args = _input db_kwargs[ "database_metadata_current_db_only"] = database_metadata_current_db_only_val with redshift_connector.connect(**db_kwargs) as conn: assert conn.is_single_database_metadata is database_metadata_current_db_only_val with conn.cursor() as cursor: spy = mocker.spy(cursor, "execute") result: typing.Tuple = cursor.get_columns(**_args) # ensure query was executed with arguments passed to get_schemas assert spy.called if _args[ "schema_pattern"] is not None and database_metadata_current_db_only_val: assert spy.call_count == 2 # call in __schema_pattern_match(), get_columns() else: assert spy.call_count == 1 for arg in ( _args["catalog"], _args["schema_pattern"], _args["tablename_pattern"], _args["columnname_pattern"], ): if arg is not None: assert arg in spy.call_args[0][0] assert len(result) > 0, print(spy.call_args, "\n", result) assert len(result[0]) == 24
def test_multi_step_three(mocker): ''' Use mocked randint to test that player makes multiple moves of given length. ''' n_steps = 5 randint_value = 3 # Patch random.randint to always return randint_value mocker.patch('random.randint', return_value=randint_value) # Wrap a "spy" around random.randint to collect information about # how often and with which arguments it is called. randint_spy = mocker.spy(random, 'randint') b = Board(chutes=[], ladders=[]) pl = Player(b) for _ in range(n_steps): pl.move() # Check that player is in correct position assert pl.position == n_steps * randint_value # Check that random.randint was called once per call to move() assert randint_spy.call_count == n_steps # Check that random.randint was always called with arguments 1, 6 randint_spy.assert_has_calls(n_steps * [mocker.call(1, 6)])
def test_create_q_matrices_all_zeros_files_if_wrong_data(mocker, deactivate_open_files): mocker.spy(functions, "newton_cotes") mocked_file = deactivate_open_files mocker.spy(numpy, "savetxt") model = Model(settings.default) model.total_time_steps = 2 model.mass_intervals = [[0., 0.1], [8., 2.]] model.energies = [1e-8, -1e-4] model.create_q_matrices() calls = [mocker.call(f"{settings.default['output_dir']}/imf_supernova_rates", "w+"), mocker.call(f"{settings.default['output_dir']}/qm-matrices", "w+")] mocked_file.assert_has_calls(calls) assert functions.newton_cotes.call_count == 0 assert numpy.savetxt.call_count == model.total_time_steps
def test_set_iam_credentials_for_serverless_calls_get_credentials( mock_boto_client, mocker, serverless_iam_db_kwargs): rp: RedshiftProperty = RedshiftProperty() for k, v in serverless_iam_db_kwargs.items(): rp.put(k, v) mock_cred_provider = MagicMock() mock_cred_holder = MagicMock() mock_cred_provider.get_credentials.return_value = mock_cred_holder mock_cred_holder.has_associated_session = False spy = mocker.spy(rp, "put") IamHelper.set_cluster_credentials(mock_cred_provider, rp) # ensure describe_configuration is called mock_boto_client.assert_has_calls( [call().get_credentials(dbName=rp.db_name)]) # ensure host, port values were set assert spy.called # ensure RedshiftProperty.put method was called assert "user_name" in [c[0][0] for c in spy.call_args_list] assert "password" in [c[0][0] for c in spy.call_args_list]
def test_get_schemas_considers_args(_input, is_single_database_metadata_val, mocker): catalog, schema_pattern = _input mocker.patch("redshift_connector.Cursor.execute", return_value=None) mocker.patch("redshift_connector.Cursor.fetchall", return_value=None) mock_cursor: Cursor = Cursor.__new__(Cursor) mock_cursor.paramstyle = "mocked" mock_connection: Cursor = Connection.__new__(Connection) mock_cursor._c = mock_connection spy = mocker.spy(mock_cursor, "execute") with patch( "redshift_connector.Connection.is_single_database_metadata", new_callable=PropertyMock()) as mock_is_single_database_metadata: mock_is_single_database_metadata.__get__ = Mock( return_value=is_single_database_metadata_val) mock_cursor.get_schemas(catalog, schema_pattern) assert spy.called assert spy.call_count == 1 if schema_pattern is not None: # should be in parameterized portion assert schema_pattern in spy.call_args[0][1] if catalog is not None: assert catalog in spy.call_args[0][0]
def test_get_catalogs_considers_args(is_single_database_metadata_val, mocker): mocker.patch("redshift_connector.Cursor.execute", return_value=None) mocker.patch("redshift_connector.Cursor.fetchall", return_value=None) mock_cursor: Cursor = Cursor.__new__(Cursor) mock_cursor.paramstyle = "mocked" mock_connection: Cursor = Connection.__new__(Connection) mock_cursor._c = mock_connection spy = mocker.spy(mock_cursor, "execute") with patch( "redshift_connector.Connection.is_single_database_metadata", new_callable=PropertyMock()) as mock_is_single_database_metadata: mock_is_single_database_metadata.__get__ = Mock( return_value=is_single_database_metadata_val) mock_cursor.get_catalogs() assert spy.called assert spy.call_count == 1 if is_single_database_metadata_val: assert "select current_database as TABLE_CAT FROM current_database()" in spy.call_args[ 0][0] else: assert ( "SELECT CAST(database_name AS varchar(124)) AS TABLE_CAT FROM PG_CATALOG.SVV_REDSHIFT_DATABASES " in spy.call_args[0][0])
def test_get_initial_coords(mocker, graphic_settings): dimensions = {"header": [797.0, 194.0], "text": [1045, 111.0]} return_coords = (377, 732) spy = mocker.spy(src, "__get_initial_coordinates") src.__get_initial_coordinates(graphic_settings, dimensions) assert spy.spy_return == return_coords
def test_create_q_matrices(mocker, deactivate_open_files): mocker.spy(functions, "newton_cotes") mocked_file = deactivate_open_files mocker.spy(numpy, "savetxt") model = Model(settings.default) model.total_time_steps = 2 model.mass_intervals = [[1., 8.], [8., 33.]] model.sn_Ia_rates = [2e-4, 1e-4] model.energies = [3e-4, 1.2e-4] model.create_q_matrices() calls = [mocker.call(f"{settings.default['output_dir']}/imf_supernova_rates", "w+"), mocker.call(f"{settings.default['output_dir']}/qm-matrices", "w+")] mocked_file.assert_has_calls(calls) functions.newton_cotes.assert_has_calls assert numpy.savetxt.call_count == model.total_time_steps
def test_result_add(populated_db, mocker): assert not Team.objects.filter(present=True).exists() mocker.spy(Ranking, 'compute') assert Ranking.compute.call_count == 0 # adding a result to a team should update it as automatically present team = Team.objects.get(num=1) assert not hasattr(team, 'robotics1') referee = User.objects.get(username='******') Robotics1.objects.create(team=team, referee=referee, trips=5, variants=1) assert hasattr(team, 'robotics1') assert team.present # it should also have triggered the global ranking update assert Ranking.compute.call_count == 1
def test_transaction_request_success(mocker): sender_address = "fake-sender" receiver_address = "fake-receiver" amount = 100 client = MockApiClient() mocker.spy(client, 'broadcast_transform') init_transaction(client, sender_address, receiver_address, amount) client.broadcast_transform.assert_called_once() broadcasted_transform = client.broadcast_transform.call_args[0][0] assert type(broadcasted_transform) is BalanceTransfer assert broadcasted_transform.amount == amount assert broadcasted_transform.receiver == receiver_address assert broadcasted_transform.sender == sender_address
def test_scale_array_convert_array_type_called(self, mocker): """Test the convert_array_type method is called during scale_array.""" mocked_method = mocker.spy(scale.Scaler, "convert_array_type") min_max_scaler = scale.MinMaxScaler(array_like=[1, 2, 3]) min_max_scaler.scale_array() mocked_method.assert_called()
def test_scale_array_min_max_called_times(self, mocker): """Test the number of times min_max_scaling is called in scale_array.""" mocked_method = mocker.spy(scale.MinMaxScaler, "min_max_scaling") min_max_scaler = scale.MinMaxScaler(array_like=[1, 2, 3]) min_max_scaler.scale_array() assert mocked_method.call_count == 3
def test_get_min_max_values_called(self, mocker): """Test the get_min_max_values method from parent class is called.""" mocked_method = mocker.spy(scale.Scaler, "get_min_max_values") min_max_scaler = scale.MinMaxScaler(array_like=[1, 2, 3]) mocked_method.assert_called() assert min_max_scaler.min_max_val == (1, 3)
def test_super_init_called(self, mocker): """Test the super init is called when the object is initialised.""" mocked_method = mocker.spy(scale.Scaler, "__init__") min_max_scaler = scale.MinMaxScaler(array_like=[1, 2, 3]) mocked_method.assert_called() assert min_max_scaler.array_like == [1, 2, 3]
def test_return_fractions(mocker, deactivate_open_files): mocker.spy(functions, "return_fraction") mocked_file = deactivate_open_files model = Model({**settings.default, **{"return_fractions": True}}) model.total_time_steps = 2 model.mass_intervals = [[1., 8.], [8., 33.]] model.sn_Ia_rates = [2e-4, 1e-4] model.energies = [3e-4, 1.2e-4] model.create_q_matrices() assert model.context["return_fractions"] is True calls = [mocker.call(f"{settings.default['output_dir']}/imf_supernova_rates", "w+"), mocker.call(f"{settings.default['output_dir']}/qm-matrices", "w+"), mocker.call(f"{settings.default['output_dir']}/return_fractions", "w+")] mocked_file.assert_has_calls(calls) functions.return_fraction.assert_has_calls
def test_get_initial_coords(mocker): size = [1800, 1800] dimensions = {'header': [770, 48.0], 'text': [1406, 548]} return_coords = (197, 602) spy = mocker.spy(src, "__get_initial_coordinates") src.__get_initial_coordinates(size, dimensions) assert spy.spy_return == return_coords
def test_scale_array_convert_array_type_arguments(self, mocker): """Test the convert_array_type method is called with the correct arguments.""" mocked_method = mocker.spy(scale.Scaler, "convert_array_type") min_max_scaler = scale.MinMaxScaler(array_like=[1, 2, 3]) min_max_scaler.scale_array() assert mocked_method.call_args_list[0][0][1] == [0.0, 0.5, 1.0] assert mocked_method.call_args_list[0][0][2] == list
def test_set_iam_properties_redshift_auth_profile_does_override(mocker): mock_contents: typing.Dict[str, str] = { "password": "******", } mock_auth_profile_contents: RedshiftProperty = RedshiftProperty( **mock_contents) mocker.patch( "redshift_connector.idp_auth_helper.IdpAuthHelper.read_auth_profile", return_value=mock_auth_profile_contents) mocker.patch("redshift_connector.iam_helper.IamHelper.set_iam_credentials", return_value=None) redshift_auth_profile_spy = mocker.spy(IdpAuthHelper, "read_auth_profile") set_iam_crednetials_spy = mocker.spy(IamHelper, "set_iam_credentials") exp_call_arg: typing.Dict[str, str] = { "auth_profile": "someTestProfile", "access_key_id": "someAccessKeyIdValue", "session_token": "someSessionTokenValue", "secret_access_key": "someSecretAccessValue", "region": "someRegion", "endpoint_url": "someEndpointUrl", } rp: RedshiftProperty = make_basic_redshift_property( **{ **{ "iam": True, "ssl": True, "cluster_identifier": "someCluster" }, **exp_call_arg, }) res = IamHelper.set_iam_properties(rp) assert rp.password == mock_auth_profile_contents.password assert redshift_auth_profile_spy.called is True assert redshift_auth_profile_spy.call_count == 1 assert res.password == mock_auth_profile_contents.password assert set_iam_crednetials_spy.called is True assert set_iam_crednetials_spy.call_count == 1 assert set_iam_crednetials_spy.call_args[0][ 0].password == mock_auth_profile_contents.password
def test_cri_lim_exception(mocker): test_settings = { "z": 0.03, "abundances": abundances.select_abundances(np.random.choice(settings.valid_values["sol_ab"]), 0.03), "expelled": elements.Expelled(settings.default["expelled_elements_filename"]), } mocker.spy(abundances.Abundances, "abundance") mocker.spy(abundances.Abundances, "corrected_abundance_CRI_LIM") q = matrix.q(4, test_settings) abundances.Abundances.abundance.assert_called_once() abundances.Abundances.corrected_abundance_CRI_LIM.assert_not_called() test_settings["expelled"].cri_lim_yields = True q = matrix.q(4, test_settings) abundances.Abundances.corrected_abundance_CRI_LIM.assert_called_once()
def test_save_uses_header(mocker): boto_mock = mocker.patch('flask_dynamodb_sessions.boto3.client') boto_mock_instance = boto_mock() app = create_test_app(SESSION_DYNAMODB_USE_HEADER=True) mocker.spy(boto_mock, 'update_item') response = app.test_client().get('/test_route') # Find the session ID that was passed to update_item() session_id = None match = re.search("Key={'id': {'S': '(.+?)'}}", str(boto_mock_instance.update_item.call_args)) if match: session_id = match.group(1) assert 'X-SessionId' in response.headers assert response.headers['X-SessionId'] == session_id assert 'Set-Cookie' not in response.headers
def test_explosive_nucleosynthesis_with_two_steps_t(mocker, deactivate_open_files): mocker.spy(Model, "explosive_nucleosynthesis_step_t") mocker.spy(Model, "explosive_nucleosynthesis_step_logt") mocker.spy(Model, "explosive_nucleosynthesis_two_steps_t") mocker.spy(Model, "explosive_nucleosynthesis_fixed_n_steps") model = Model(settings.validate({"integration_step": "two_steps_t"})) model.explosive_nucleosynthesis() Model.explosive_nucleosynthesis_two_steps_t.assert_called_once() Model.explosive_nucleosynthesis_step_t.assert_not_called() Model.explosive_nucleosynthesis_step_logt.assert_not_called() Model.explosive_nucleosynthesis_fixed_n_steps.assert_not_called()
def test_draw_header(mocker): coords = (197, 602) return_y = 837 dummy_img = Image.new("RGB", (0, 0), color="black") draw = ImageDraw.Draw(dummy_img) font_header = ImageFont.truetype("arial.ttf", 80, encoding="utf-8") spy = mocker.spy(src, "__draw_header") src.__draw_header("test", "@test", "", [1800, 1800], dummy_img, draw, coords, 30, font_header, "black") assert spy.spy_return == return_y
def test_read_uses_header(mocker): expected_session_id = 'foobar' boto_mock = mocker.patch('flask_dynamodb_sessions.boto3.client') boto_mock_instance = boto_mock() boto_mock_instance.get_item.return_value = {'Item': {'data': ''}} app = create_test_app(SESSION_DYNAMODB_USE_HEADER=True) mocker.spy(boto_mock, 'get_item') response = app.test_client().get( '/test_route', headers={'X-SessionId': expected_session_id}) # Find the session ID that was passed to get_item() actual_session_id = None match = re.search("Key={'id': {'S': '(.+?)'}}", str(boto_mock_instance.get_item.call_args)) if match: actual_session_id = match.group(1) assert actual_session_id == expected_session_id
def test_session_reminder(self, test_user, test_session, client, mocker): test_session.bakers.append(test_user) reminders.send_email = mocker.stub() email_spy = mocker.spy(reminders, "send_session_reminder_email") token = TestingConfig.ADMIN_KEY response = client.get(f"/api/sessionreminder/{token}") assert "1" in str(response.data) email_spy.assert_called_once() reminders.send_email.assert_called_once()
def test_explosive_nucleosynthesis_with_invalid_step(mocker, deactivate_open_files): mocker.spy(Model, "explosive_nucleosynthesis_step_t") mocker.spy(Model, "explosive_nucleosynthesis_step_logt") mocker.spy(Model, "explosive_nucleosynthesis_two_steps_t") mocker.spy(Model, "explosive_nucleosynthesis_fixed_n_steps") model = Model({**settings.default, **{"integration_step": "t2"}}) with pytest.raises(ValueError): model.explosive_nucleosynthesis() Model.explosive_nucleosynthesis_step_t.assert_not_called() Model.explosive_nucleosynthesis_step_logt.assert_not_called() Model.explosive_nucleosynthesis_two_steps_t.assert_not_called() Model.explosive_nucleosynthesis_fixed_n_steps.assert_not_called()
def test_get_jwt_assertion_fetches_and_extracts(mocker): mock_token: str = "mock_token" mock_content: str = "mock_content" mock_jwt_assertion: str = "mock_jwt_assertion" mocker.patch( "redshift_connector.plugin.browser_azure_oauth2_credentials_provider." "BrowserAzureOAuth2CredentialsProvider.fetch_authorization_token", return_value=mock_token, ) mocker.patch( "redshift_connector.plugin.browser_azure_oauth2_credentials_provider." "BrowserAzureOAuth2CredentialsProvider.fetch_jwt_response", return_value=mock_content, ) mocker.patch( "redshift_connector.plugin.browser_azure_oauth2_credentials_provider." "BrowserAzureOAuth2CredentialsProvider.extract_jwt_assertion", return_value=mock_jwt_assertion, ) acp, rp = make_valid_azure_oauth2_provider() fetch_token_spy = mocker.spy(acp, "fetch_authorization_token") fetch_jwt_spy = mocker.spy(acp, "fetch_jwt_response") extract_jwt_spy = mocker.spy(acp, "extract_jwt_assertion") jwt_assertion: str = acp.get_jwt_assertion() assert fetch_token_spy.called is True assert fetch_token_spy.call_count == 1 assert fetch_jwt_spy.called is True assert fetch_jwt_spy.call_count == 1 assert fetch_jwt_spy.call_args[0][0] == mock_token assert extract_jwt_spy.called is True assert extract_jwt_spy.call_count == 1 assert extract_jwt_spy.call_args[0][0] == mock_content assert jwt_assertion == mock_jwt_assertion
def test_set_iam_properties_calls_set_auth_props(mocker): mocker.patch( "redshift_connector.iam_helper.IdpAuthHelper.set_auth_properties", return_value=None) spy = mocker.spy(IdpAuthHelper, "set_auth_properties") mock_rp: MagicMock = MagicMock() mock_rp.credentials_provider = None mock_rp.is_serverless_host = False IamHelper.set_iam_properties(mock_rp) assert spy.called is True assert spy.call_count == 1 assert spy.call_args[0][0] == mock_rp