How to use the mock.create_autospec function in mock

To help you get started, we’ve selected a few mock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github QualiSystems / vCenterShell / tests / test_common_pyvmomi.py View on Github external
def test_clone_vm_vm_name_is_none(self):
        """
        Checks clone_vm
        """
        '#arrange'
        si = create_autospec(spec=vim.ServiceInstance)

        pv_service = pyVmomiService(None, None)
        params = pv_service.CloneVmParameters(si=si,
                                              template_name='my_temp',
                                              vm_name=None,
                                              vm_folder=None)

        '#act'
        res = pv_service.clone_vm(params)

        '#assert'
        self.assertTrue(res.error is not None)
github man-group / arctic / tests / unit / test_arctic.py View on Github external
def test_initialize_library_with_list_coll_names():
    self = create_autospec(Arctic)
    self._conn = create_autospec(MongoClient)
    self._cache = create_autospec(Cache)
    lib = create_autospec(ArcticLibraryBinding)
    lib.database_name = sentinel.db_name
    lib.get_quota.return_value = None
    self._conn.__getitem__.return_value.list_collection_names.return_value = [x for x in six.moves.xrange(5001)]
    lib_type = Mock()
    with patch.dict('arctic.arctic.LIBRARY_TYPES', {sentinel.lib_type: lib_type}), \
         patch('arctic.arctic.ArcticLibraryBinding', return_value=lib, autospec=True) as ML:
        Arctic.initialize_library(self, sentinel.lib_name, sentinel.lib_type, thing=sentinel.thing, check_library_count=False)
    assert ML.call_args_list == [call(self, sentinel.lib_name)]
    assert ML.return_value.set_library_type.call_args_list == [call(sentinel.lib_type)]
    assert ML.return_value.set_quota.call_args_list == [call(10 * 1024 * 1024 * 1024)]
    assert lib_type.initialize_library.call_args_list == [call(ML.return_value, thing=sentinel.thing)]
github testing-cabal / mock / tests / testhelpers.py View on Github external
def test_autospec_functions_with_self_in_odd_place(self):
        class Foo(object):
            def f(a, self):
                pass

        a = create_autospec(Foo)
        a.f(10)
        a.f.assert_called_with(10)
        a.f.assert_called_with(self=10)
        a.f(self=10)
        a.f.assert_called_with(10)
        a.f.assert_called_with(self=10)
github Yelp / paasta / tests / test_setup_marathon_job.py View on Github external
fake_client: MarathonClient = mock.create_autospec(marathon.MarathonClient)
        fake_clients: marathon_tools.MarathonClients = marathon_tools.MarathonClients(
            current=[fake_client], previous=[fake_client]
        )

        old_tasks = [
            mock.Mock(id=id, app_id="old_app")
            for id in ["old_one", "old_two", "old_three"]
        ]
        old_tasks_with_clients = {(task, fake_client) for task in old_tasks}

        fake_bounce_func_return: bounce_lib.BounceMethodResult = {
            "create_app": False,
            "tasks_to_drain": old_tasks_with_clients,
        }
        fake_bounce_func = mock.create_autospec(
            bounce_lib.brutal_bounce, return_value=fake_bounce_func_return
        )

        fake_config: marathon_tools.FormattedMarathonAppDict = {"instances": 3}
        fake_new_app_running = True
        fake_happy_new_tasks = [mock.Mock(), mock.Mock(), mock.Mock()]
        fake_old_app_live_happy_tasks: Dict[
            Tuple[str, MarathonClient], Set[MarathonTask]
        ] = {("old_app", fake_client): set()}
        fake_old_app_live_unhappy_tasks: Dict[
            Tuple[str, MarathonClient], Set[MarathonTask]
        ] = {("old_app", fake_client): set(old_tasks)}
        fake_old_app_draining_tasks: Dict[
            Tuple[str, MarathonClient], Set[MarathonTask]
        ] = {("old_app", fake_client): set()}
        fake_old_app_at_risk_tasks: Dict[
github Ulauncher / Ulauncher / tests / api / server / test_DeferredResultRenderer.py View on Github external
def controller(self, manifest):
        controller = mock.create_autospec(ExtensionController)
        controller.get_manifest.return_value = manifest
        return controller
github Wordseer / wordseer / tests / testcounter.py View on Github external
def test_count_documents(self, mock_db, mock_project_logger):
        """Test the count_documents method
        """
        interval =  2

        mock_project = mock.create_autospec(Project)
        mock_project.get_documents.return_value = []

        for i in range(0, interval * 2 + 1):
            document = mock.create_autospec(Document)
            document.all_sentences = range(0, 5)
            mock_project.get_documents.return_value.append(document)

        counter.count_documents(mock_project, interval)

        assert mock_db.session.commit.call_count == interval + 1

        for document in mock_project.get_documents.return_value:
            assert document.sentence_count == 5
github man-group / arctic / tests / unit / store / test_metadata_store.py View on Github external
def test_list_symbols_regex():
    ms = create_autospec(MetadataStore)
    ms.aggregate.return_value = []

    expected_pipeline = [
        {'$sort': {'symbol': 1, 'start_time': -1}},
        {'$match': {'symbol': {'$regex': 'test.*'}}},
        {'$group': {'_id': '$symbol', 'metadata': {'$first': '$metadata'}}},
        {'$project': {'_id': 0, 'symbol':  '$_id'}}
    ]

    MetadataStore.list_symbols(ms, regex='test.*')
    ms.aggregate.assert_called_once_with(expected_pipeline)
github yahoo / panoptes / tests / plugins / test_base_snmp_plugin.py View on Github external
self.assertEqual(panoptes_snmp_base_plugin.plugin_context, self._plugin_context)
        self.assertEqual(panoptes_snmp_base_plugin.plugin_config, self._plugin_context.config)
        self.assertEqual(panoptes_snmp_base_plugin.resource, self._plugin_context.data)
        self.assertEqual(panoptes_snmp_base_plugin.enrichment, self._plugin_context.enrichment)
        self.assertEqual(panoptes_snmp_base_plugin.execute_frequency,
                         int(self._plugin_context.config['main']['execute_frequency']))
        self.assertEqual(panoptes_snmp_base_plugin.host, self._plugin_context.data.resource_endpoint)
        self.assertIsInstance(panoptes_snmp_base_plugin.snmp_connection, PanoptesSNMPV2Connection)

        # Test PanoptesSNMPPluginConfiguration Error
        mock_plugin_context = create_autospec(self._plugin_context)
        with self.assertRaises(PanoptesPluginConfigurationError):
            panoptes_snmp_base_plugin.run(mock_plugin_context)

        # Test Error in getting SNMP Connection
        mock_snmp_connection_class = create_autospec(PanoptesSNMPConnectionFactory)
        with patch('yahoo_panoptes.framework.plugins.base_snmp_plugin.PanoptesSNMPConnectionFactory',
                   mock_snmp_connection_class):
            with self.assertRaises(PanoptesPluginRuntimeError):
                panoptes_snmp_base_plugin.run(self._plugin_context)

        # Ensure log message hit if get_results does not return None
        mock_get_results = MagicMock(return_value={"test": "test"})
        with patch('yahoo_panoptes.framework.plugins.base_snmp_plugin.PanoptesSNMPBasePlugin.get_results',
                   mock_get_results):
            panoptes_snmp_base_plugin.run(self._plugin_context)
github testing-cabal / mock / tests / testhelpers.py View on Github external
def test_builtins(self):
        # used to fail with infinite recursion
        create_autospec(1)

        create_autospec(int)
        create_autospec('foo')
        create_autospec(str)
        create_autospec({})
        create_autospec(dict)
        create_autospec([])
        create_autospec(list)
        create_autospec(set())
        create_autospec(set)
        create_autospec(1.0)
        create_autospec(float)
        create_autospec(1j)
        create_autospec(complex)
        create_autospec(False)
        create_autospec(True)
github Wordseer / wordseer / tests / testcollectionprocessor.py View on Github external
def test_extract_record_metadata(self, mock_os, mock_strucex, mock_logger):
        """Test the extract_record_metadata method.
        """
        # Set up the input objects
        collection_dir = "/foobar/"
        docstruc_filename = mock.create_autospec(str)
        filename_extension = ".xml"
        files = ["file1.xml", "file2.XmL", "file3.foo", ".file4.xml"]

        # Configure the mock os
        mock_os.listdir.return_value = files
        mock_os.path.splitext.side_effect = os.path.splitext
        mock_os.path.join.side_effect = os.path.join

        # Configure mock logger
        mock_logger.get.return_value = ""

        # Make the structure extractor return useful objects
        extracted_docs = [
            (os.path.join(collection_dir, files[0]),
                [mock.create_autospec(Document) for x in range(10)]),
            (os.path.join(collection_dir, files[1]),