def test__inject__with_list_qualifier_dependency(self, mocker: MockFixture): # given mocked_inject = mocker.patch("injectable.autowiring.autowired_type.inject") mocked_inject_multiple = mocker.patch( "injectable.autowiring.autowired_type.inject_multiple" ) expected = "Expected" autowired = Autowired(list[expected]) # when autowired.inject() # then assert mocked_inject.call_count == 0 assert mocked_inject_multiple.call_count == 1 args, kwargs = mocked_inject_multiple.call_args assert args[0] == expected
def test_game_starts_incorrectly(mocker: MockFixture): mock_socket_cls = mocker.patch("socket.socket") sock = get_socket_with_mocked_recv(mock_socket_cls, "HEY! boring Hawking".encode("utf-8")) with pytest.raises(WrongCommand): init_game(sock, 3, "happy Pascal") sock.close()
def test_signature_all_missing(mocker: ptm.MockFixture) -> None: async def foo() -> pipeline.Response: ... with pytest.raises(handler.InvalidHandlerError) as err: handler._resolve( handler=foo, operation=operation, request_processor=mocker.Mock(), response_processor=mocker.Mock(), ) assert err.value.operation_id == 'TestAnalysisParameters' assert len(err.value) == 4 for key in ('id', 'limit', 'page', 'includeExtra'): assert key in err.value assert err.value[key] == 'missing'
def mock_requests_get(mocker: MockFixture) -> Mock: """Fixture for mocking requests get.""" mock = mocker.patch("requests.get") mock.return_value.__enter__.return_value.json.return_value = { "title": "Wicked Wicki", "extract": "The Wicked Wicki whacked the whacky tricky API", } return mock
def test_post_to_dict_no_coments(mocker: MockFixture) -> None: """The reddit.post_to_dict function suceeds when there are no comments.""" post = mocker.MagicMock() post.comments.__iter__.return_value = [] res = reddit.post_to_dict(post) assert len(res["comments"]) == 0
async def test_disconnect_and_stop(uiserver: CylcUIServer, mocker: MockFixture, one_workflow_aiter, async_client: AsyncClientFixture): """Test disconnecting and stopping a workflow. If a workflow is active, but the next state is inactive, the workflow manager will take care to stop and disconnect the workflow.""" workflow_name = 'disconnect-stop' workflow_id = f'{getuser()}|{workflow_name}' flow = { 'name': workflow_name, 'contact': False, CFF.HOST: 'localhost', CFF.PORT: 0, CFF.PUBLISH_PORT: 0, CFF.API: 1, 'req_client': async_client } uiserver.workflows_mgr.active[workflow_id] = flow assert workflow_id not in uiserver.workflows_mgr.inactive assert workflow_id in uiserver.workflows_mgr.active uiserver.workflows_mgr._scan_pipe = one_workflow_aiter(**flow) # NOTE: here we will yield a workflow that is running, it has contact # data, is not active nor inactive (i.e. pending registration). # This is what forces the .update() to call register()! # We don't have a real workflow, so we mock get_location. mocker.patch('cylc.flow.network.client.get_location', return_value=('localhost', 0, None)) # The following functions also depend on a running workflow # with pyzmq socket, so we also mock them. mocker.patch('cylc.flow.network.client.SuiteRuntimeClient.start') mocker.patch('cylc.flow.network.client.SuiteRuntimeClient.get_header') mocker.patch('cylc.uiserver.data_store_mgr.DataStoreMgr.' 'start_subscription') mocker.patch('cylc.uiserver.data_store_mgr.DataStoreMgr.update_contact') await uiserver.workflows_mgr.update() # connect must have created an active entry for the workflow, # and the update method must have taken care to remove from inactive assert workflow_id not in uiserver.workflows_mgr.active assert workflow_id in uiserver.workflows_mgr.inactive
def test_b_package(mocker: MockFixture): import griff4.py101.a.mya as mya import griff4.py101.a.b.myb as myb mock_cls = mocker.patch('griff4.py101.a.b.myb.AClass') mock_instance = mock_cls.return_value print(mock_instance) print(mya.AClass()) print(myb.b_method())
def test_update(self, mocker: MockFixture, mocked_layer: Any) -> None: # Opta file check 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_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_update_secrets = mocker.patch( "opta.commands.secret.update_secrets") mocked_restart_deployments = mocker.patch( "opta.commands.secret.restart_deployments") mocker.patch("opta.commands.secret.set_kube_config") mocked_amplitude_client = mocker.patch( "opta.commands.secret.amplitude_client", spec=AmplitudeClient) mocked_amplitude_client.UPDATE_SECRET_EVENT = amplitude_client.UPDATE_SECRET_EVENT runner = CliRunner() result = runner.invoke( update, [ "dummysecret", "dummysecretvalue", "--env", "dummyenv", "--config", "dummyconfig", ], ) assert result.exit_code == 0 mocked_create_namespace_if_not_exists.assert_called_once_with( "dummy_layer") mocked_update_secrets.assert_called_once_with( "dummy_layer", "manual-secrets", {"dummysecret": "dummysecretvalue"}) 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.UPDATE_SECRET_EVENT) mocked_restart_deployments.assert_called_once_with("dummy_layer") # test updating a secret that is not listed in the config file - should work result = runner.invoke(update, ["unlistedsecret", "newvalue"]) assert result.exit_code == 0 mocked_update_secrets.assert_called_with( "dummy_layer", "manual-secrets", {"unlistedsecret": "newvalue"})
def test_messenger_send(user: User, mocker: MockFixture): """Should send messages.""" mocks = [] for i in range(0, 4): mock = mocker.Mock() mock.apply_async = mocker.Mock(return_value=i) mocks.append(mock) messenger = Messenger() messenger.messengers = mocks messenger.send( user=user, subject="test subject", template="message_notification", context={}, ) for mock in mocks: assert mock.apply_async.call_count == 1
def mock_requests_get(mocker: MockFixture) -> Mock: """Mocks a page summary returned from the Wikipedia API.""" mock = mocker.patch("requests.get") mock.return_value.__enter__.return_value.json.return_value = { "title": "Lorem Ipsum", "extract": "According to all known laws of aviation...", } return mock
def test_user_text(session_mocker: MockFixture) -> None: """Runs various methods depending on whether text has been entered args: mocker: Wrapper for pytest of the mock package """ # Prevents pop ups from appearing session_mocker.patch("kintercrypt.main_gui.showerror") # Text not entered WINDOW.start_cipher() # Text entered session_mocker.patch("tests.main_gui_test.WINDOW.output_area.get", return_value="example text") WINDOW.start_cipher()
def test_add_class_not_notifies_listeners_with_special_flag( f_registry: Registry, mocker: MockFixture, ) -> None: listener = mocker.MagicMock() f_registry.subscribe(listener) f_registry.set(RegisterTestClass, notify_listeners=False) assert not listener.notify.called
def test__inject__with_optional_list_class_dependency(self, mocker: MockFixture): # given mocked_inject = mocker.patch("injectable.autowiring.autowired_type.inject") mocked_inject_multiple = mocker.patch( "injectable.autowiring.autowired_type.inject_multiple" ) autowired = Autowired(Optional[list[TestAutowiredTypePy39]]) # when autowired.inject() # then assert mocked_inject.call_count == 0 assert mocked_inject_multiple.call_count == 1 args, kwargs = mocked_inject_multiple.call_args assert args[0] == TestAutowiredTypePy39 assert kwargs["optional"] is True
def test_available(mocker: MockFixture) -> None: which = mocker.patch("luoda.plugins.org.which") which.return_value = "xyz" assert available() which.return_value = None assert not available()
def test_slug_called(mocker: MockFixture, talk_factory: factories.TalkFactory) -> None: """Test slug is created if not passed.""" mocked_slugger = mocker.patch("domain.utils.generate_unique_slug") mocked_slugger.return_value = "python" talk = talk_factory(name="Python", description="Best talk ever.") assert mocked_slugger.called assert talk.slug == "python"
def test_delete_duplicates(test_files, mocker: MockFixture, helper_obj): """Tests that new_file2.txt was removed.""" wait_input = mocker.patch( 'plushkins_helper.main.PlushkinsHelper.wait_for_input') wait_input.return_value = 1 helper_obj.find_all_duplicates() helper_obj.prepare_to_delete() assert not os.path.exists(test_files / 'new_file2.txt')
def test_unique_files(test_files, mocker: MockFixture, helper_obj): """Tests that script don`t remove unique files.""" wait_input = mocker.patch( 'plushkins_helper.main.PlushkinsHelper.wait_for_input') wait_input.return_value = 1 helper_obj.find_all_duplicates() helper_obj.prepare_to_delete() assert os.path.exists(test_files / 'unique_file.txt')
def mock_requests_get(mocker: MockFixture) -> Mock: """Fixture for mocking requests.get.""" mock = mocker.patch("requests.get") mock.return_value.__enter__.return_value.json.return_value = { "title": "Lorem Ipsum", "extract": "Lorem ipsum dolor sit amet", } return mock
async def test_ok_in(self, mocker: MockFixture, fake_model_data_provider: ModelDataProvider): fake_filter_name = mocker.Mock() fake_filter_value = mocker.Mock(spec=list) fake_in = mocker.patch.object(fake_model_data_provider, 'COMPARISON_OPERATOR_IN') mocked_search = mocker.patch('re.search', return_value=None) compared_operator = fake_model_data_provider.get_comparison_operator( fake_filter_name, fake_filter_value) expected_operator = fake_in assert compared_operator == expected_operator mocked_search.assert_called_once_with( '__({})$'.format(fake_model_data_provider.COMPARISON_SIGNS), fake_filter_name)
def test_template_context_addons(app_context: AppContext, mocker: MockFixture) -> None: addons_mock = mocker.patch("superset.jinja_context.context_addons") addons_mock.return_value = {"datetime": datetime} maindb = superset.utils.database.get_example_database() template = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'" tp = get_template_processor(database=maindb) assert tp.process_template(template) == "SELECT '2017-01-01T00:00:00'"
def test_manager_active_subscriptions_to_event(mocker: MockFixture): mock = mocker.patch( 'crm.models.ClientSubscriptionQuerySet.active_subscriptions_to_event') models.ClientSubscriptions.objects.active_subscriptions_to_event( mocker.ANY) mock.assert_called_once_with(mocker.ANY)
async def test_mutation_add_nonexisting_job(mocker: MockFixture): """Test the resolver for adding jobs.""" job = read_jobs()[1] args = {"input": job, 'cookie': COOKIE} # Mock database ctx = { "mongodb": { "jobs_awesome_data": MockedCollection(None), "awesome_data": MockedCollection(None) } } mocker.patch("ceiba.mutation_resolvers.is_user_authenticated", return_value=True) reply = await resolve_mutation_add_job(PARENT, args, ctx, INFO) check_reply(reply)
def test_add_class_notifies_listeners( f_registry: Registry, mocker: MockFixture, ) -> None: listeners = [mocker.MagicMock() for _ in range(2)] [f_registry.subscribe(listener) for listener in listeners] f_registry.set(RegisterTestClass) assert all(listener.notify.called for listener in listeners)
async def test_mutation_update_property(mocker: MockFixture): """Check the job status updater.""" args = { "input": { "_id": 101010, "collection_name": "awesome_data", "data": '{"pi": "3.14159265358979323846"}' }, 'cookie': COOKIE } # Mock database ctx = {"mongodb": {"awesome_data": MockedCollection(None)}} mocker.patch("ceiba.mutation_resolvers.is_user_authenticated", return_value=True) reply = await resolve_mutation_update_property(PARENT, args, ctx, INFO) assert reply['status'] == 'DONE'
async def test_mutation_authentication_valid_user(mocker: MockFixture): """Check the authentication resolver for an invalid_token.""" args = {"token": "RosalindToken"} # Mock database ctx = { "mongodb": { USERS_COLLECTION: MockedCollection({"username": "******"}) } } mocker.patch("ceiba.mutation_resolvers.authenticate_username", return_value="RosalindFranklin") reply = await resolve_mutation_authentication(PARENT, args, ctx, INFO) cookie = json.loads(reply['text']) assert reply['status'] == "DONE" assert cookie['username'] == "RosalindFranklin"
async def test_mutation_update_job_status(mocker: MockFixture): """Check the job status updater.""" args = { "input": { "_id": 3141592, "collection_name": "awesome_data", "status": "RESERVED" }, 'cookie': COOKIE } # Mock database ctx = {"mongodb": {"jobs_awesome_data": MockedCollection(read_jobs())}} mocker.patch("ceiba.mutation_resolvers.is_user_authenticated", return_value=True) reply = await resolve_mutation_update_job_status(PARENT, args, ctx, INFO) assert reply['status'] == 'DONE'
def test_deployment_source_show_output( self, mock_machinelearning_client: MLClient, mocker: MockFixture, mock_poller: LROPoller) -> None: mocker.patch( "azure.ml._arm_deployments.ArmDeploymentExecutor._get_poller", return_value=mock_poller) executor = ArmDeploymentExecutor( credentials=mock_machinelearning_client._credential, resource_group_name="test_group", subscription_id="test_subscription", deployment_name="testdeployment", ) with pytest.raises(Exception): executor.deploy_resource( template="template", resources_being_deployed={"test": ("test", None)}, show_output=False)
def test_mqtt_client_factory(mocker: MockFixture): mocker.patch('app.network.Client') broker_config = BrokerConfig(uri='test.com', port=1223, user='******', password='******') client = mqtt_client_factory(broker_config) assert client.tls_set.called assert client.username_pw_set.called assert client.username_pw_set.call_args.args == (broker_config.user, broker_config.password) assert client.connect.called assert client.connect.call_args.args == (broker_config.uri, broker_config.port, broker_config.keep_alive)
def test_saved_chart_is_owner(mocker: MockFixture, app_context: AppContext) -> None: from superset.connectors.sqla.models import SqlaTable from superset.explore.utils import check_access as check_chart_access from superset.models.slice import Slice mocker.patch(dataset_find_by_id, return_value=SqlaTable()) mocker.patch(can_access_datasource, return_value=True) mocker.patch(is_user_admin, return_value=False) mocker.patch(is_owner, return_value=True) mocker.patch(chart_find_by_id, return_value=Slice()) check_chart_access( datasource_id=1, chart_id=1, actor=User(), datasource_type=DatasourceType.TABLE, )
def run_pytest(testdir: Testdir, mocker: MockFixture, *args) -> RunResult: mocker.patch("pytest_helm_charts.fixtures.ExistingCluster", autospec=True) result = testdir.runpytest( "--cluster-type", "existing", "--log-cli-level", "info", "--kube-config", "/tmp/kat_test/kube.config", # nosec '--chart-extra-info="key1=val1,external_cluster_type=kind"', "-v", *args, ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines(["*Cluster configured*", "*Cluster released*"]) return result
def mocker_context(): result = MockFixture(FakePytestConfig()) yield result result.stopall()
def mocker_context(): result = MockFixture() yield result result.stopall()