def test_check_opta_file_exists_file_does_not_exists_user_input( mocker: MockFixture, ) -> None: mock_config_path = "mock_config_path" mock_user_config_path = "mock_user_config_path" mock_os_path_exists = mocker.patch( "opta.utils.os.path.exists", side_effect=[False, True] ) mock_click_prompt = mocker.patch( "opta.utils.click.prompt", return_value=mock_user_config_path ) mock_system_exit = mocker.patch("opta.utils.sys.exit") config_path = check_opta_file_exists(mock_config_path) assert config_path == mock_user_config_path mock_os_path_exists.assert_has_calls( [mocker.call(mock_config_path), mocker.call(mock_user_config_path)] ) mock_click_prompt.assert_called_once_with( "Enter a Configuration Path (Empty String will exit)", default="", type=click.STRING, show_default=False, ) mock_system_exit.assert_not_called()
async def test_ok_filter_value_is_not_list( self, mocker: MockFixture, fake_model_data_provider: ModelDataProvider): fake_filters = dict(test=mocker.Mock()) mocked_hasattr = mocker.patch( 'aiohttp_baseapi.data_providers.model.hasattr', mocker.Mock(return_value=True)) mocked_get_table_field = mocker.patch.object(fake_model_data_provider, '_get_table_field') mocked_remove_comparison_suffix = mocker.patch.object( fake_model_data_provider, 'remove_comparison_suffix') mocked_get_filters = mocker.patch.object( fake_model_data_provider, 'get_filters', CoroutineMock(return_value=fake_filters)) compared_where_list = await fake_model_data_provider.get_where_list() expected_where_list = [ (mocked_get_table_field.return_value == filter_value) for filter_value in fake_filters.values() ] assert compared_where_list == expected_where_list mocked_get_table_field.has_calls( [mocker.call(filter_name) for filter_name in fake_filters.keys()]) mocked_remove_comparison_suffix.has_calls([ mocker.call(filter_value) for filter_value in fake_filters.values() ]) mocked_hasattr.has_calls([ mocker.call(fake_model_data_provider.model, mocked_remove_comparison_suffix.return_value) for _ in fake_filters.keys() ]) mocked_get_filters.assert_called_once()
def test_tail_module_log(self, mocker: MockFixture) -> None: base_start_time_timestamp = datetime.datetime.utcnow().timestamp() mocked_load_kube_config = mocker.patch( "opta.core.kubernetes.load_kube_config") mocked_core_v1_api = mocker.Mock(spec=CoreV1Api) mocked_core_v1_api_call = mocker.patch( "opta.core.kubernetes.CoreV1Api", return_value=mocked_core_v1_api) mocked_watch = mocker.Mock(spec=Watch) mocked_watch_call = mocker.patch("opta.core.kubernetes.Watch", return_value=mocked_watch) layer = mocker.Mock(spec=Layer) layer.name = "mocked_layer" layer.parent = None layer.providers = { "aws": { "region": "us-east-1", "account_id": "111111111111" } } mocked_pod_1 = mocker.Mock(spec=V1Pod) mocked_pod_1.metadata = mocker.Mock() mocked_pod_1.metadata.name = "pod1" mocked_pod_1.metadata.creation_timestamp = datetime.datetime.fromtimestamp( base_start_time_timestamp + 10000).replace(tzinfo=pytz.UTC) mocked_event_1 = {"object": mocked_pod_1} thread_1 = mocker.Mock() mocked_pod_2 = mocker.Mock(spec=V1Pod) mocked_pod_2.metadata = mocker.Mock() mocked_pod_2.metadata.name = "pod2" mocked_pod_2.metadata.creation_timestamp = datetime.datetime.fromtimestamp( base_start_time_timestamp + 10000).replace(tzinfo=pytz.UTC) mocked_event_2 = {"object": mocked_pod_2} thread_2 = mocker.Mock() mocked_watch.stream.return_value = [mocked_event_1, mocked_event_2] mocked_thread = mocker.patch("opta.core.kubernetes.Thread", side_effect=[thread_1, thread_2]) tail_module_log(layer, "mocked_module_name", since_seconds=3, start_color_idx=2) mocked_watch_call.assert_called_once_with() mocked_core_v1_api_call.assert_called_once_with() mocked_load_kube_config.assert_called_once_with(config_file=mocker.ANY) thread_1.start.assert_called_once_with() thread_2.start.assert_called_once_with() mocked_thread.assert_has_calls([ mocker.call( target=tail_pod_log, args=("mocked_layer", mocked_pod_1, 2, 3), daemon=True, ), mocker.call( target=tail_pod_log, args=("mocked_layer", mocked_pod_2, 3, 3), daemon=True, ), ])
def test_google_download_state(self, mocker: MockFixture) -> None: layer = mocker.Mock(spec=Layer) layer.gen_providers.return_value = { "terraform": { "backend": { "gcs": { "bucket": "opta-tf-state-test-dev1", "prefix": "dev1" } } }, "provider": { "google": { "region": "us-central1", "project": "dummy-project" } }, } layer.name = "blah" layer.cloud = "google" mocker.patch("opta.core.terraform.Terraform._gcp_verify_storage", return_value=True) patched_init = mocker.patch("opta.core.terraform.Terraform.init", return_value=True) mocked_credentials = mocker.Mock() mocked_gcp_credentials = mocker.patch( "opta.core.terraform.GCP.get_credentials", return_value=[mocked_credentials, "dummy-project"], ) mocked_storage_client = mocker.Mock() mocked_client_constructor = mocker.patch( "opta.core.terraform.storage.Client", return_value=mocked_storage_client) mocked_bucket_object = mocker.Mock() mocked_storage_client.get_bucket.return_value = mocked_bucket_object read_data = '{"a": 1}' mocked_file = mocker.mock_open(read_data=read_data) mocker.patch("opta.core.terraform.os.remove") mocked_open = mocker.patch("opta.core.terraform.open", mocked_file) assert Terraform.download_state(layer) patched_init.assert_not_called() mocked_gcp_credentials.assert_called_once_with() mocked_client_constructor.assert_called_once_with( project="dummy-project", credentials=mocked_credentials) mocked_storage_client.get_bucket.assert_called_once_with( "opta-tf-state-test-dev1") mocked_open.assert_has_calls( [ mocker.call("./tmp.tfstate", "wb"), mocker.call("./tmp.tfstate", "r") ], any_order=True, ) mocked_storage_client.download_blob_to_file.assert_called_once_with( mocker.ANY, mocker.ANY)
def test_no_tag_override(mocker: MockFixture) -> None: # Opta file check mocked_os_path_exists = mocker.patch("opta.utils.os.path.exists") mocked_os_path_exists.return_value = True nice_run_mock = mocker.patch("opta.commands.push.nice_run") gen_mock = mocker.patch("opta.commands.push.gen_all") layer_object_mock = mocker.patch("opta.commands.push.Layer") layer_mock = mocker.Mock(spec=Layer) layer_mock.cloud = "aws" layer_mock.org_name = "dummy_org_name" layer_mock.name = "dummy_name" layer_object_mock.load_from_yaml.return_value = layer_mock mocker.patch( "opta.commands.push.get_registry_url" ).return_value = "889760294590.dkr.ecr.us-east-1.amazonaws.com/github-runx-app" mocker.patch("opta.commands.push.get_ecr_auth_info").return_value = ( "username", "password", ) mocker.patch("opta.commands.push.get_image_digest") runner = CliRunner() result = runner.invoke(cli, ["push", "local_image:local_tag"]) assert result.exit_code == 0 layer_object_mock.load_from_yaml.assert_called_once_with( "opta.yaml", None, input_variables={} ) gen_mock.assert_called_once_with(layer_mock) nice_run_mock.assert_has_calls( [ mocker.call( [ "docker", "login", "889760294590.dkr.ecr.us-east-1.amazonaws.com/github-runx-app", "--username", "username", "--password-stdin", ], input=b"password", check=True, ), mocker.call( [ "docker", "tag", "local_image:local_tag", "889760294590.dkr.ecr.us-east-1.amazonaws.com/github-runx-app:local_tag", ], check=True, ), ] )
def test_chat_broadcast(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = ChatBot(send_message) bot.handle_message(10, 'hello') bot.handle_message(11, 'world') assert send_message.call_args_list == [ mocker.call(10, '#10: hello'), mocker.call(10, '#11: world'), mocker.call(11, '#11: world'), ]
def test_multiple_operations(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = CalculatorUserHandler(send_message) bot.handle_message('2 * 3') bot.handle_message('3 / 2') bot.handle_message('3 - 4') assert send_message.call_args_list == [ mocker.call('6'), mocker.call('1'), mocker.call('-1') ]
async def test_consume_messages( m_telebot: telebot.AsyncTeleBot, mocker: MockFixture, ) -> None: chat_id = 123456 messages = [ ExternalMessage( sender='@sender2', receiver='@receiver1', content='testing message 1', ), ExternalMessage( sender='@sender1', receiver='@receiver2', content='testing message 2', ), ] mocked_send_message = mocker.MagicMock() m_telebot.send_message.return_value = mocked_send_message mocked_send_message.wait.return_value = tb_types.Message( None, None, None, None, None, [], None, ) bot = TelegramGroupChat( bot_token=FAKE_TOKEN, chat_id=chat_id, ) await bot.consume_messages(messages) m_telebot.send_message.assert_has_calls( [ mocker.call( chat_id, f'From {messages[0].sender} ' f'to {messages[0].receiver}: ' f'{messages[0].content}', ), mocker.call( chat_id, f'From {messages[1].sender} ' f'to {messages[1].receiver}: ' f'{messages[1].content}', ), ], any_order=True, )
def test_tictactoe_wrong_arguments(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('X 0 0') bot.handle_message('X 1 0') bot.handle_message('O 0 0') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('X..\n...\n...'), mocker.call('Invalid turn'), mocker.call('Invalid turn'), ]
def test_game_many_starts(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('start') bot.handle_message('start') bot.handle_message('start') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('...\n...\n...'), mocker.call('...\n...\n...'), mocker.call('...\n...\n...') ]
def test_wrong_symbols(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('X 0 0') bot.handle_message('A 1 1') bot.handle_message('B 2 2') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('X..\n...\n...'), mocker.call('Invalid turn'), mocker.call('Invalid turn') ]
def test_list_secrets(self, mocker: MockFixture, mocked_layer: Any) -> None: mocked_os_path_exists = mocker.patch("opta.utils.os.path.exists") mocked_os_path_exists.return_value = os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_config1.yaml") mocked_print = mocker.patch("builtins.print") mocker.patch("opta.commands.secret.set_kube_config") mocked_create_namespace_if_not_exists = mocker.patch( "opta.commands.secret.create_namespace_if_not_exists") mocked_get_secret_name_and_namespace = mocker.patch( "opta.commands.secret.get_secret_name_and_namespace") mocked_get_secret_name_and_namespace.return_value = [ "manual-secrets", "dummy_layer", ] mocked_get_secrets = mocker.patch("opta.commands.secret.get_secrets") mocked_get_secrets.return_value = { "dummysecret": "1", "b": "2", "c": "3" } mocked_amplitude_client = mocker.patch( "opta.commands.secret.amplitude_client", spec=AmplitudeClient) mocked_amplitude_client.LIST_SECRETS_EVENT = amplitude_client.LIST_SECRETS_EVENT runner = CliRunner() result = runner.invoke( list_command, ["--env", "dummyenv", "--config", "dummyconfig"], ) assert result.exit_code == 0 mocked_create_namespace_if_not_exists.assert_called_once_with( "dummy_layer") mocked_get_secrets.assert_called_once_with("dummy_layer", "manual-secrets") mocked_layer.assert_called_once_with("dummyconfig", "dummyenv", input_variables={}, strict_input_variables=False) mocked_amplitude_client.send_event.assert_called_once_with( amplitude_client.LIST_SECRETS_EVENT) mocked_print.assert_has_calls([ mocker.call("dummysecret=1"), mocker.call("b=2"), mocker.call("c=3") ])
def test_add_admin_roles(self, mocker: MockFixture): layer = Layer.load_from_yaml( os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_config_parent.yaml" ), None, ) k8s_base_module = layer.get_module("k8sbase", 8) k8s_base_module.data["admin_arns"] = [ "arn:aws:iam::445935066876:user/live-example-dev-live-example-dev-deployeruser", "arn:aws:iam::445935066876:role/live-example-dev-live-example-dev-deployerrole", "arn:aws:iam::445935066876:role/silly-role", "arn:aws:iam::445935066876:user/silly-user", ] mocker.patch("modules.aws_k8s_base.aws_k8s_base.set_kube_config") mocker.patch("modules.aws_k8s_base.aws_k8s_base.load_opta_kube_config") mocked_core_v1_api = mocker.Mock() mocker.patch( "modules.aws_k8s_base.aws_k8s_base.CoreV1Api", return_value=mocked_core_v1_api, ) mocked_aws_auth_config_map = mocker.Mock() mocked_aws_auth_config_map.data = { "mapRoles": "- groups: ['system:bootstrappers', 'system:nodes']\n rolearn: arn:aws:iam::445935066876:role/opta-live-example-dev-eks-default-node-group\n username: system:node:{{EC2PrivateDNSName}}\n- groups: ['system:masters']\n rolearn: arn:aws:iam::445935066876:role/live-example-dev-live-example-dev-deployerrole\n username: opta-managed\n", "mapUsers": "- groups: ['system:masters']\n userarn: arn:aws:iam::445935066876:user/live-example-dev-live-example-dev-deployeruser\n username: opta-managed\n", } mocked_opta_arns_config_map = mocker.Mock() mocked_opta_arns_config_map.data = { "adminArns": '\n- "arn:aws:iam::445935066876:user/live-example-dev-live-example-dev-deployeruser"\n\n- "arn:aws:iam::445935066876:role/live-example-dev-live-example-dev-deployerrole"\n\n- "arn:aws:iam::445935066876:role/silly-role"\n\n- "arn:aws:iam::445935066876:user/silly-user"\n' } mocked_core_v1_api.read_namespaced_config_map.side_effect = [ mocked_aws_auth_config_map, mocked_opta_arns_config_map, ] AwsK8sBaseProcessor(k8s_base_module, layer).add_admin_roles() mocked_core_v1_api.read_namespaced_config_map.assert_has_calls( [mocker.call("aws-auth", "kube-system"), mocker.call("opta-arns", "default")] ) mocked_core_v1_api.replace_namespaced_config_map.assert_has_calls( [mocker.call("aws-auth", "kube-system", body=mocked_aws_auth_config_map)] ) assert mocked_aws_auth_config_map.data == { "mapRoles": "- groups: ['system:bootstrappers', 'system:nodes']\n rolearn: arn:aws:iam::445935066876:role/opta-live-example-dev-eks-default-node-group\n username: system:node:{{EC2PrivateDNSName}}\n- groups: ['system:masters']\n rolearn: arn:aws:iam::445935066876:role/live-example-dev-live-example-dev-deployerrole\n username: opta-managed\n- groups: ['system:masters']\n rolearn: arn:aws:iam::445935066876:role/silly-role\n username: opta-managed\n", "mapUsers": "- groups: ['system:masters']\n userarn: arn:aws:iam::445935066876:user/live-example-dev-live-example-dev-deployeruser\n username: opta-managed\n- groups: ['system:masters']\n userarn: arn:aws:iam::445935066876:user/silly-user\n username: opta-managed\n", }
def test_init_setup(with_scenarios, mocker: MockFixture): mock_resolve = mocker.patch("pydngconverter.compat.resolve_executable") mock_resolve.return_value = Path(""), "" dng = pydng.DNGConverter(*with_scenarios[0], **with_scenarios[-1]) dng_call = mocker.call(["Adobe DNG Converter", "dngconverter"], "PYDNG_DNG_CONVERTER") exif_call = mocker.call(["exiftool"], "PYDNG_EXIF_TOOL") if dng.parameters.jpeg_preview == flags.JPEGPreview.NONE: mock_resolve.assert_has_calls([dng_call]) mock_resolve.assert_called_once() if dng.parameters.jpeg_preview == flags.JPEGPreview.MEDIUM: mock_resolve.assert_has_calls([dng_call]) mock_resolve.assert_called_once() if dng.parameters.jpeg_preview == flags.JPEGPreview.EXTRACT: mock_resolve.assert_has_calls([dng_call, exif_call]) assert mock_resolve.call_count == 2
async def test_ok(self, fake_rows, model_manager: BaseModelManager, mocker: MockFixture): fake_where_list = mocker.Mock() fake_order_by = mocker.Mock() fake_offset = mocker.Mock() fake_limit = mocker.Mock() mocked_row_class = mocker.patch.object(model_manager, 'row_class') mocked_get_items = mocker.patch.object( model_manager, 'get_items', CoroutineMock(return_value=fake_rows) ) actual_result = await model_manager.get_instances( where_list=fake_where_list, limit=fake_limit, offset=fake_offset, order_by=fake_order_by ) expected_result = [mocked_row_class.return_value for _ in fake_rows] row_class_calls = [mocker.call(**row) for row in fake_rows] mocked_row_class.assert_has_calls(row_class_calls) mocked_get_items.assert_called_once_with( where_list=fake_where_list, limit=fake_limit, offset=fake_offset, order_by=fake_order_by ) assert actual_result == expected_result
def test_post_hook_error(self, mocker: MockFixture): layer = Layer.load_from_yaml( os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_config_parent.yaml" ), None, ) aws_email_module = layer.get_module("awsses", 8) patched_logger = mocker.patch("modules.aws_ses.aws_ses.logger") mocked_sesv2 = mocker.Mock() mocked_boto3 = mocker.patch("modules.aws_ses.aws_ses.boto3") mocked_boto3.client.return_value = mocked_sesv2 mocked_sesv2.get_account.return_value = { "ProductionAccessEnabled": False, "Details": {"ReviewDetails": {"Status": "FAILED", "CaseId": "123"}}, } aws_dns_modules = layer.get_module("awsdns", 8) aws_dns_modules.data["delegated"] = True mocked_state_storage = mocker.patch("opta.layer.Layer.state_storage") mocked_state_storage.return_value = "whatever" AwsEmailProcessor(aws_email_module, layer).post_hook(8, None) mocked_boto3.client.assert_called_once() mocked_sesv2.get_account.assert_called_once() patched_logger.warning.assert_has_calls([mocker.call(mocker.ANY)]) patched_logger.info.assert_not_called()
async def test_ok(self, model_manager: BaseModelManager, mocker: MockFixture): fake_values = [{'foo': 'bar'}] fake_fetchedall = [{'foo': 'bar'}] mocked_table = mocker.patch.object(model_manager, 'table', mocker.Mock(columns=[mocker.Mock(), mocker.Mock()])) mocked_set_sql = mocker.patch.object(model_manager, 'set_sql', return_value=model_manager) mocked_row_class = mocker.patch.object(model_manager, 'row_class') mocked_values = mocker.patch.object(model_manager, 'values', return_value=model_manager) mocked_returning = mocker.patch.object(model_manager, 'returning', return_value=model_manager) mocked_fetchall = mocker.patch.object( model_manager, 'fetchall', CoroutineMock(return_value=fake_fetchedall) ) compared_result = await model_manager.bulk_insert(fake_values) expected_result = [mocked_row_class.return_value for _ in fake_fetchedall] mocked_set_sql.assert_called_once_with(mocked_table.insert.return_value) mocked_table.insert.assert_called_once_with() mocked_values.assert_called_once_with(fake_values) mocked_returning.assert_called_once_with(*mocked_table.columns) mocked_fetchall.assert_called_once_with() row_class_calls = [mocker.call(**row) for row in fake_fetchedall] mocked_row_class.assert_has_calls(row_class_calls) assert compared_result == expected_result
def test_delete_persistent_volume_claims(self, mocker: MockFixture) -> None: mocked_core_v1_api = mocker.Mock(spec=CoreV1Api) mocker.patch("opta.core.kubernetes.CoreV1Api", return_value=mocked_core_v1_api) mocker.patch("opta.core.kubernetes.load_kube_config") mocked_claim_opta1 = mocker.Mock(spec=V1PersistentVolumeClaim) mocked_claim_opta1.metadata = mocker.Mock() mocked_claim_opta1.metadata.name = "opta-claim-1" mocked_claim_opta2 = mocker.Mock(spec=V1PersistentVolumeClaim) mocked_claim_opta2.metadata = mocker.Mock() mocked_claim_opta2.metadata.name = "opta-claim-2" mocked_list_persistent_volume_claims = mocker.patch( "opta.core.kubernetes.list_persistent_volume_claims", return_value=[mocked_claim_opta1, mocked_claim_opta2], ) # call with no parameter, expect list PVC method called and 2 delete PVC calls namespace = "hello" delete_persistent_volume_claims(namespace=namespace, opta_managed=True, async_req=True) mocked_list_persistent_volume_claims.assert_called_once_with( namespace="hello", opta_managed=True) mocked_core_v1_api.delete_collection_namespaced_persistent_volume_claim.assert_has_calls( [ mocker.call( namespace="hello", field_selector="metadata.name=opta-claim-1", async_req=True, body=mocker.ANY, ), mocker.call( namespace="hello", field_selector="metadata.name=opta-claim-2", async_req=True, body=mocker.ANY, ), ]) # pv are automatically deleted by k8s after deleting the claim, not by opta mocked_core_v1_api.assert_not_called()
def test_tictactoe_winner_x(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('X 0 0') bot.handle_message('O 1 0') bot.handle_message('X 1 1') bot.handle_message('O 2 0') bot.handle_message('X 2 2') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('X..\n...\n...'), mocker.call('XO.\n...\n...'), mocker.call('XO.\n.X.\n...'), mocker.call('XOO\n.X.\n...'), mocker.call('XOO\n.X.\n..X'), mocker.call('Game is finished, X wins'), ]
def test_game_not_started(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('O 2 1') bot.handle_message('Hello') assert send_message.call_args_list == [ mocker.call('Game is not started'), mocker.call('Game is not started') ]
def test_tail_pod_log(self, mocker: MockFixture) -> None: mocked_core_v1_api = mocker.Mock(spec=CoreV1Api) mocked_core_v1_api_call = mocker.patch( "opta.core.kubernetes.CoreV1Api", return_value=mocked_core_v1_api) mocked_watch = mocker.Mock(spec=Watch) mocked_watch_call = mocker.patch("opta.core.kubernetes.Watch", return_value=mocked_watch) mocked_watch.stream.side_effect = [ "hello_world", ApiException(status=400), ApiException(status=400), ApiException(status=400), Exception(), ApiException(status=400), ] mocked_pod = mocker.Mock(spec=V1Pod) mocked_pod.metadata = mocker.Mock() mocked_pod.metadata.name = "pod1" mocked_time = mocker.patch("opta.core.kubernetes.time") tail_pod_log("mocked_namespace", mocked_pod, 2, 3) mocked_watch_call.assert_called_once_with() mocked_core_v1_api_call.assert_called_once_with() mocked_time.sleep.assert_has_calls([ mocker.call(0), mocker.call(1), mocker.call(2), mocker.call(3), mocker.call(4), mocker.call(5), mocker.call(6), mocker.call(7), mocker.call(8), mocker.call(9), mocker.call(10), mocker.call(11), mocker.call(12), mocker.call(13), mocker.call(14), ]) assert mocked_time.sleep.call_count == 15 # Tailing should not retry upon encountering a 404 API exception. mocked_watch.stream.side_effect = [ "hello_world", ApiException(status=400), ApiException(status=404), ] mocked_time = mocker.patch("opta.core.kubernetes.time") tail_pod_log("mocked_namespace", mocked_pod, 2, 3) assert mocked_time.sleep.call_count == 1
def test_process_new(self, mocker: MockFixture): layer = Layer.load_from_yaml( os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_config_parent.yaml" ), None, ) dns_module = layer.get_module("awsdns", 6) mocked_ssm = mocker.Mock() mocked_boto3 = mocker.patch("modules.aws_dns.aws_dns.boto3") mocked_boto3.client.return_value = mocked_ssm mocked_ssm.get_parameters_by_path.return_value = {"Parameters": []} patched_prompt = mocker.patch("modules.aws_dns.aws_dns.prompt") patched_prompt.side_effect = [ os.path.join(os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_key.pem"), os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_cert.pem" ), "", ] mocked_state_storage = mocker.patch("opta.layer.Layer.state_storage") mocked_state_storage.return_value = "whatever" processor = AwsDnsProcessor(dns_module, layer) processor.process(2) mocked_boto3.client.assert_called_once_with("ssm", config=mocker.ANY) mocked_ssm.put_parameter.assert_has_calls( [ mocker.call( Name=mocker.ANY, Value=mocker.ANY, Type="SecureString", Overwrite=True, ), mocker.call( Name=mocker.ANY, Value=mocker.ANY, Type="SecureString", Overwrite=True, ), ] )
def test_run_configurations_async_mode(mocker: MockFixture, ) -> None: f_configurations = [mocker.MagicMock() for _ in range(2)] f_configuration_admin = ConfigurationAdmin(Configuration, AdminSite()) f_run_configuration = mocker.patch('configuration.admin.run_configuration') f_configuration_admin.run_configurations( mocker.MagicMock(), f_configurations, ) f_run_configuration.delay.assert_has_calls( [mocker.call(conf.id) for conf in f_configurations], )
def test_tictactoe_draw(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('X 1 1') bot.handle_message('O 2 2') bot.handle_message('X 0 0') bot.handle_message('O 1 0') bot.handle_message('X 1 2') bot.handle_message('O 2 1') bot.handle_message('X 2 0') bot.handle_message('O 0 2') bot.handle_message('X 0 1') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('...\n.X.\n...'), mocker.call('...\n.X.\n..O'), mocker.call('X..\n.X.\n..O'), mocker.call('XO.\n.X.\n..O'), mocker.call('XO.\n.X.\n.XO'), mocker.call('XO.\n.XO\n.XO'), mocker.call('XOX\n.XO\n.XO'), mocker.call('XOX\n.XO\nOXO'), mocker.call('XOX\nXXO\nOXO'), mocker.call('Game is finished, draw'), ]
def test_x_wins(mocker: pytest_mock.MockFixture) -> None: send_message = mocker.stub(name='send_message_stub') bot = TicTacToeUserHandler(send_message) bot.handle_message('start') bot.handle_message('X 1 1') bot.handle_message('O 1 2') bot.handle_message('X 0 0') bot.handle_message('O 2 2') bot.handle_message('X 0 2') bot.handle_message('O 2 0') bot.handle_message('X 0 1') assert send_message.call_args_list == [ mocker.call('...\n...\n...'), mocker.call('...\n.X.\n...'), mocker.call('...\n.X.\n.O.'), mocker.call('X..\n.X.\n.O.'), mocker.call('X..\n.X.\n.OO'), mocker.call('X..\n.X.\nXOO'), mocker.call('X.O\n.X.\nXOO'), mocker.call('X.O\nXX.\nXOO'), mocker.call('Game is finished, X wins') ]
def test_ok(self, mocker: MockFixture, fake_base_view_cls): fake_updated_value = 100 fake_object = mocker.Mock( **{ '_page.get.return_value': fake_updated_value, 'MAX_LIMIT': 1000, 'ITEMS_ON_PAGE': 100 }) mocker.patch.object(fake_object, '_page.update') fake_base_view_cls.validate_page(fake_object) fake_object._page.get.assert_has_calls([ mocker.call('limit', fake_object.DEFAULT_LIMIT), mocker.call('offset', fake_object.DEFAULT_OFFSET), ]) fake_object._page.update.assert_called_once_with({ 'limit': fake_updated_value, 'offset': fake_updated_value })
def test_valid_input(mocker: MockFixture) -> None: mocker.patch("opta.commands.push.get_image_digest") mocked_nice_run = mocker.patch("opta.commands.push.nice_run") push_to_docker( "username", "password", "local_image:local_tag", REGISTRY_URL, "image_tag_override", ) mocked_nice_run.assert_has_calls( [ mocker.call( [ "docker", "login", REGISTRY_URL, "--username", "username", "--password-stdin", ], input=b"password", check=True, ), mocker.call( [ "docker", "tag", "local_image:local_tag", f"{REGISTRY_URL}:image_tag_override", ], check=True, ), mocker.call( ["docker", "push", f"{REGISTRY_URL}:image_tag_override"], check=True, ), ] )
def test_post_hook_prompt(self, mocker: MockFixture): layer = Layer.load_from_yaml( os.path.join( os.getcwd(), "tests", "fixtures", "dummy_data", "dummy_config_parent.yaml" ), None, ) aws_email_module = layer.get_module("awsses", 8) patched_prompt = mocker.patch("modules.aws_ses.aws_ses.prompt") patched_prompt.side_effect = ["www.blah.com", "hello, world", "*****@*****.**"] patched_logger = mocker.patch("modules.aws_ses.aws_ses.logger") mocked_sesv2 = mocker.Mock() mocked_boto3 = mocker.patch("modules.aws_ses.aws_ses.boto3") mocked_boto3.client.return_value = mocked_sesv2 mocked_sesv2.get_account.return_value = { "ProductionAccessEnabled": False, } mocked_state_storage = mocker.patch("opta.layer.Layer.state_storage") mocked_state_storage.return_value = "whatever" aws_dns_modules = layer.get_module("awsdns", 8) aws_dns_modules.data["delegated"] = True AwsEmailProcessor(aws_email_module, layer).post_hook(8, None) mocked_boto3.client.assert_called_once() mocked_sesv2.get_account.assert_called_once() mocked_sesv2.put_account_details.assert_called_once_with( MailType="TRANSACTIONAL", WebsiteURL="https://www.blah.com", ContactLanguage="EN", UseCaseDescription="hello, world", AdditionalContactEmailAddresses=["*****@*****.**"], ProductionAccessEnabled=True, ) patched_logger.info.assert_has_calls( [mocker.call(mocker.ANY), mocker.call(mocker.ANY)] ) patched_logger.warning.assert_not_called()
def test_ok(self, fake_columns, fake_row_model, mocker: MockFixture): fake_values = {col.key: mocker.Mock() for col in fake_columns} fake_row_model.__table__.columns = fake_columns mocked_get_value = mocker.patch.object(fake_row_model, '_get_value') expected_calls = [] for col in fake_columns: setattr(fake_row_model, col.key, None) expected_calls.append(mocker.call(col.key)) fake_row_model._set_values(fake_values) mocked_get_value.assert_has_calls(expected_calls, any_order=True) for key, value in fake_values.items(): assert value == getattr(fake_row_model, key)
def test_ok_with_where_list(self, model_manager: BaseModelManager, mocker: MockFixture): fake_where_list = ['foo', 'bar'] mocked_get_sql = mocker.Mock() mocker.patch.object(model_manager, 'get_sql', mocked_get_sql) mocker.patch.object(model_manager, 'sql') model_manager.where(fake_where_list) compared_sql = model_manager.sql expected_sql = mocked_get_sql.return_value.where.return_value calls = [mocker.call(where) for where in fake_where_list] mocked_get_sql.return_value.where.assert_has_calls(calls) assert compared_sql == expected_sql