当前位置: 首页>>代码示例>>Python>>正文


Python MagicMock.assert_called_with方法代码示例

本文整理汇总了Python中mock.MagicMock.assert_called_with方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.assert_called_with方法的具体用法?Python MagicMock.assert_called_with怎么用?Python MagicMock.assert_called_with使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mock.MagicMock的用法示例。


在下文中一共展示了MagicMock.assert_called_with方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_walk_passes_the_specified_argument_to_callback

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
def test_walk_passes_the_specified_argument_to_callback(listdir_mock):
    listdir_mock.return_value = ['f1.py']
    cb = MagicMock()

    fs.walk('/dummy/path', cb, 'arg')

    cb.assert_called_with(ANY, 'arg')
开发者ID:povilasb,项目名称:pycity-generator,代码行数:9,代码来源:test_filesys.py

示例2: test_setup_func

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_setup_func(self):
        # Run it when the collection doesn't exist
        with mock.patch('anki.storage.Collection') as anki_storage_Collection:
            col = anki_storage_Collection.return_value
            setup_new_collection = MagicMock()
            self.assertFalse(os.path.exists(self.collection_path))
            wrapper = CollectionWrapper(self.collection_path, setup_new_collection)
            wrapper.open()
            anki_storage_Collection.assert_called_with(self.collection_path)
            setup_new_collection.assert_called_with(col)
            wrapper = None

        # Make sure that no collection was actually created
        self.assertFalse(os.path.exists(self.collection_path))
        
        # Create a faux collection file
        with file(self.collection_path, 'wt') as fd:
            fd.write('Collection!')

        # Run it when the collection does exist
        with mock.patch('anki.storage.Collection'):
            setup_new_collection = lambda col: self.fail("Setup function called when collection already exists!")
            self.assertTrue(os.path.exists(self.collection_path))
            wrapper = CollectionWrapper(self.collection_path, setup_new_collection)
            wrapper.open()
            anki_storage_Collection.assert_called_with(self.collection_path)
            wrapper = None
开发者ID:28554010,项目名称:anki-sync-server,代码行数:29,代码来源:test_collection.py

示例3: test_run

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
 def test_run(self):
     mock = MagicMock()
     code = "some SDK code"
     with patch('omnimax.sdk.base_sdk.execute', mock):
         sdk = omnimax.sdk.BaseSDK('ruby')
         sdk.run(code)
     mock.assert_called_with(self.sdk_dir + '/run.sh', code, cwd=self.sdk_dir)
开发者ID:mauriciovieira,项目名称:omnimax,代码行数:9,代码来源:test_base_sdk.py

示例4: test_metrics

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
def test_metrics(monkeypatch):
    client = client_mock(monkeypatch)

    resp = MagicMock()
    resp.text = 'metrics'

    client.return_value.session.get.return_value = resp

    parsed = MagicMock()
    parsed.samples = [
        ('metric-1', {}, 20.17), ('metric-2', {'verb': 'GET'}, 20.16), ('metric-1', {'verb': 'POST'}, 20.18)
    ]

    parser = MagicMock()
    parser.return_value = [parsed]

    monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.kubernetes.text_string_to_metric_families', parser)

    k = KubernetesWrapper()
    metrics = k.metrics()

    expected = {
        'metric-1': [({}, 20.17), ({'verb': 'POST'}, 20.18)],
        'metric-2': [({'verb': 'GET'}, 20.16)],
    }

    assert metrics == expected

    parser.assert_called_with(resp.text)
    client.return_value.session.get.assert_called_with(CLUSTER_URL + '/metrics')
开发者ID:drummerwolli,项目名称:zmon-worker,代码行数:32,代码来源:test_kubernetes.py

示例5: test_wait_list

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
 def test_wait_list(self):
     self.update_ci.deploy_jobs = MagicMock(
         side_effect=[['autopilot-ci'], []])
     sleep_mock = MagicMock()
     with patch('time.sleep', sleep_mock):
         self.update_ci.update_jenkins(self.jenkins, self.jjenv, self.stack)
     sleep_mock.assert_called_with(10)
开发者ID:didrocks,项目名称:cupstream2distro-config,代码行数:9,代码来源:test_cu2dUpdateCi.py

示例6: pyodbc_exception_test

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def pyodbc_exception_test(self):
        """
        Test that exceptions raised by pyodbc are handled
        """
        # GIVEN: A mocked out SongImport class, a mocked out pyodbc module, a mocked out translate method,
        #       a mocked "manager" and a mocked out logError method.
        with patch('openlp.plugins.songs.lib.worshipcenterproimport.SongImport'), \
            patch('openlp.plugins.songs.lib.worshipcenterproimport.pyodbc.connect') as mocked_pyodbc_connect, \
            patch('openlp.plugins.songs.lib.worshipcenterproimport.translate') as mocked_translate:
            mocked_manager = MagicMock()
            mocked_log_error = MagicMock()
            mocked_translate.return_value = 'Translated Text'
            importer = WorshipCenterProImport(mocked_manager)
            importer.logError = mocked_log_error
            importer.import_source = 'import_source'
            pyodbc_errors = [pyodbc.DatabaseError, pyodbc.IntegrityError, pyodbc.InternalError, pyodbc.OperationalError]
            mocked_pyodbc_connect.side_effect = pyodbc_errors

            # WHEN: Calling the doImport method
            for effect in pyodbc_errors:
                return_value = importer.doImport()

                # THEN: doImport should return None, and pyodbc, translate & logError are called with known calls
                self.assertIsNone(return_value, 'doImport should return None when pyodbc raises an exception.')
                mocked_pyodbc_connect.assert_called_with( 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=import_source')
                mocked_translate.assert_called_with('SongsPlugin.WorshipCenterProImport',
                    'Unable to connect the WorshipCenter Pro database.')
                mocked_log_error.assert_called_with('import_source', 'Translated Text')
开发者ID:marmyshev,项目名称:bug_1117098,代码行数:30,代码来源:test_worshipcenterproimport.py

示例7: test_aws_relationship_external

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_aws_relationship_external(self):
        fake_class_instance = MagicMock()
        FakeClass = MagicMock(return_value=fake_class_instance)

        mock_func = MagicMock()

        @decorators.aws_relationship(class_decl=FakeClass)
        def test_with_mock(*args, **kwargs):
            mock_func(*args, **kwargs)

        _ctx = self._gen_decorators_realation_context(test_properties={
            'use_external_resource': True
        })

        test_with_mock(ctx=_ctx)

        mock_func.assert_not_called()

        # force run
        test_with_mock(ctx=_ctx, force_operation=True)

        mock_func.assert_called_with(
            ctx=_ctx,
            iface=fake_class_instance, resource_config={},
            force_operation=True, resource_type='AWS Resource')
开发者ID:cloudify-cosmo,项目名称:cloudify-aws-plugin,代码行数:27,代码来源:test_decorators.py

示例8: test_patching_a_builtin

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_patching_a_builtin(self):
        mock = MagicMock(return_value=sentinel.file_handle)
        with patch('__builtin__.open', mock):
            handle = open('filename', 'r')

        mock.assert_called_with('filename', 'r')
        assert handle == sentinel.file_handle, "incorrect file handle returned"
开发者ID:jangxyz,项目名称:xyz.daum,代码行数:9,代码来源:mock_sample_test.py

示例9: test_open

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_open(self):
        """
        Does it open a file with the given filename?
        """
        name = 'aoeu'
        dict_writer = MagicMock()
        dict_writer_instance = MagicMock()
        storage = MagicMock()
        dict_writer.return_value = dict_writer_instance
        self.file_storage.open = MagicMock()
        opened = MagicMock()
        self.file_storage.open.return_value = opened
        
        with patch('csv.DictWriter', dict_writer):
            # the call to `open`
            writer = self.storage.open(name)

            # did it open a file using the filename?
            self.file_storage.open.assert_called_with(name)

            # Did it create and store a DictWriter?
            self.assertEqual(writer.writer, dict_writer_instance)

            # Did it create the DictWriter using the opened file and headers?
            dict_writer.assert_called_with(opened,
                                           self.headers)

            # Did it write the header to the file?
            dict_writer_instance.writeheader.assert_called_with()

            # did it return a copy of itself?
            self.assertIsInstance(writer, CsvDictStorage)
            self.assertNotEqual(writer, self.storage)
        return        
开发者ID:russellnakamura,项目名称:thetuna,代码行数:36,代码来源:testcsvstorage.py

示例10: test_no_error_loading_users

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_no_error_loading_users(self, base, toolkit, model, g, logic):

        # actions
        default_user = {'user_name': 'test', 'another_val': 'example value'}
        user_show = MagicMock(return_value=default_user)
        acquisitions_list = MagicMock()

        toolkit.get_action = MagicMock(side_effect=lambda action: user_show if action == 'user_show' else acquisitions_list)

        # Call the function
        returned = views.acquired_datasets()

        # User_show called correctly
        expected_context = {
            'auth_user_obj': g.userobj,
            'for_view': True,
            'model': model,
            'session': model.Session,
            'user': g.user,
        }

        user_show.assert_called_once_with(expected_context, {'user_obj': g.userobj})
        acquisitions_list.assert_called_with(expected_context, None)

        # Check that the render method has been called
        base.render.assert_called_once_with('user/dashboard_acquired.html', {'user_dict': default_user, 'acquired_datasets': acquisitions_list()})
        self.assertEqual(returned, base.render())
开发者ID:conwetlab,项目名称:ckanext-privatedatasets,代码行数:29,代码来源:test_views.py

示例11: TestGraphiteTarget

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
class TestGraphiteTarget(TestCase):

    def setUp(self):
        self.base_url = 'BASE_URL'
        self.record_class = MagicMock(GraphiteDataRecord)
        self.http_get = MagicMock(requests.get)
        self.http_get().content = SAMPLE_RESPONSE
        self.target = 'TARGET'

        self.records = get_records(
            self.base_url,
            self.http_get,
            self.record_class,
            self.target,
        )

    def test_hits_correct_url(self):
        url = 'BASE_URL/render/?target=TARGET&rawData=true&from=-1min'
        self.http_get.assert_called_with(url, verify=False)

    def should_create_two_records(self):
        calls = [call(SAMPLE_1), call(SAMPLE_2)]
        self.assertEqual(self.record_class.call_args_list, calls)

    def should_return_data_records(self):
        self.assertEqual(self.records[0], self.record_class(SAMPLE_1))
        self.assertEqual(self.records[1], self.record_class(SAMPLE_2))

    def should_raise_for_status(self):
        self.http_get().raise_for_status.assert_called_with()
开发者ID:Dipsomaniac,项目名称:graphite-alerts,代码行数:32,代码来源:test_graphite_target.py

示例12: test_load

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
    def test_load(self):
        """tests load method"""

        mock_run_statement = MagicMock()
        MySqlDatabase.run_statement = mock_run_statement

        config = MagicMock()
        config.schema = self.schema
        config.data = self.data
        fixture = MySqlFixture(
            config=config
        )

        fixture.load()

        # Brittle way of testing that insert statement is run
        # Assumes the keys of first row in self.data are the fields to insert
        data_row = self.data[0]
        stmnt_fields, expected_statement = MySqlInsertStatementMixin.create_insert_statement(
            table=self.schema.config.get_table(),
            fields=data_row.keys(),
            statement_string=True
        )

        expected_params = [data_row[field] for field in stmnt_fields]

        mock_run_statement.assert_called_with(
            expected_statement,
            params=expected_params,
            commit=True
        )
开发者ID:pantheon-systems,项目名称:etl-framework,代码行数:33,代码来源:test_mysql_fixture.py

示例13: test_refresh_invalid_response

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
def test_refresh_invalid_response(monkeypatch, tmpdir):
    tokens.configure(dir=str(tmpdir), url='https://example.org')
    tokens.manage('mytok', ['myscope'])
    tokens.start()  # this does not do anything..

    response = MagicMock()
    response.json.return_value = {'foo': 'bar'}
    post = MagicMock()
    post.return_value = response
    monkeypatch.setattr('requests.post', post)
    monkeypatch.setattr('tokens.read_credentials', lambda path: (VALID_USER_JSON, VALID_CLIENT_JSON))

    with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
        tokens.get('mytok')
    assert str(exc_info.value) == """Invalid token response: Expected a JSON object with keys "expires_in" and "access_token": 'expires_in'"""

    # verify that we use a proper HTTP timeout..
    post.assert_called_with('https://example.org',
                            data={'username': 'app', 'scope': 'myscope', 'password': 'pass', 'grant_type': 'password'},
                            headers={'User-Agent': 'python-tokens/{}'.format(tokens.__version__)},
                            timeout=(1.25, 2.25), auth=('cid', 'sec'))

    response.json.return_value = {'access_token': '', 'expires_in': 100}
    with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
        tokens.get('mytok')
    assert str(exc_info.value) == 'Invalid token response: Empty "access_token" value'
开发者ID:last-g,项目名称:python-tokens,代码行数:28,代码来源:test_tokens.py

示例14: TestDisableInterface

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
class TestDisableInterface(unittest.TestCase):
    def setUp(self):
        self.connection = MagicMock(name='connection')
        self.html = MagicMock(name='html')
        self.connection.return_value = self.html
        self.html.text = open('radio_5_asp.html').read()
        return

    def test_24_ghz(self):
        """
        Does it setup the right data dictionary and make the right call?
        """
        command = DisableInterface(connection=self.connection,
                                   band='2.4')
        expected_data = {'action':'Apply',
                        'wl_unit':'0',
                        'wl_radio':'0'}
        self.assertEqual(command.data, expected_data)
        command()
        self.connection.assert_called_with(data=expected_data)
        self.assertEqual(self.connection.path, 'radio.asp')
        return

    def test_5_ghz(self):
        """
        Does it set up the right data dictionary to disable the 5 Ghz interface?
        """
        command = DisableInterface(connection=self.connection,
                                   band='5')
        expected_data = {'action':'Apply',
                        'wl_unit':'1',
                        'wl_radio':'0'}
        self.assertEqual(command.data, expected_data)
开发者ID:russellnakamura,项目名称:apcommand,代码行数:35,代码来源:commands.py

示例15: test_scalyr_timeseries_aligned

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import assert_called_with [as 别名]
def test_scalyr_timeseries_aligned(monkeypatch, fx_timeseries_aligned):
    kwargs, res, exp = fx_timeseries_aligned

    read_key = '123'

    post = MagicMock()
    post.return_value.json.return_value = res

    monkeypatch.setattr('requests.post', post)

    scalyr = ScalyrWrapper(read_key)
    result = scalyr.timeseries(**kwargs)

    assert result == exp

    query = get_query('facet', kwargs.get('function', 'count'), read_key, **kwargs)

    query.pop('queryType')

    final_q = {
        'token': query.pop('token'),
        'queries': [query]
    }

    post.assert_called_with(
        scalyr._ScalyrWrapper__timeseries_url, json=final_q, headers={'Content-Type': 'application/json'})
开发者ID:drummerwolli,项目名称:zmon-worker,代码行数:28,代码来源:test_scalyr.py


注:本文中的mock.MagicMock.assert_called_with方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。