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


Python mock.call函数代码示例

本文整理汇总了Python中unittest.mock.call函数的典型用法代码示例。如果您正苦于以下问题:Python call函数的具体用法?Python call怎么用?Python call使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: test_setup_full_config

    def test_setup_full_config(self, mock_uvc, mock_remote):
        """"Test the setup with full configuration."""
        config = {
            'platform': 'uvc',
            'nvr': 'foo',
            'port': 123,
            'key': 'secret',
        }
        fake_cameras = [
            {'uuid': 'one', 'name': 'Front', 'id': 'id1'},
            {'uuid': 'two', 'name': 'Back', 'id': 'id2'},
            {'uuid': 'three', 'name': 'Old AirCam', 'id': 'id3'},
        ]

        def fake_get_camera(uuid):
            """"Create a fake camera."""
            if uuid == 'id3':
                return {'model': 'airCam'}
            else:
                return {'model': 'UVC'}

        mock_remote.return_value.index.return_value = fake_cameras
        mock_remote.return_value.get_camera.side_effect = fake_get_camera
        mock_remote.return_value.server_version = (3, 2, 0)

        assert setup_component(self.hass, 'camera', {'camera': config})

        self.assertEqual(mock_remote.call_count, 1)
        self.assertEqual(
            mock_remote.call_args, mock.call('foo', 123, 'secret')
        )
        mock_uvc.assert_has_calls([
            mock.call(mock_remote.return_value, 'id1', 'Front'),
            mock.call(mock_remote.return_value, 'id2', 'Back'),
        ])
开发者ID:GadgetReactor,项目名称:home-assistant,代码行数:35,代码来源:test_uvc.py

示例2: test_validate_true

 def test_validate_true (self):
     corpus = MagicMock(spec_set=tacl.Corpus)
     text = MagicMock(spec_set=tacl.Text)
     text.get_checksum.return_value = sentinel.checksum
     text.get_names.return_value = (sentinel.name, sentinel.siglum)
     corpus.get_texts.return_value = (text,)
     catalogue = collections.OrderedDict(
         [(sentinel.text1, sentinel.label1),
          (sentinel.text2, sentinel.label2),
          (sentinel.text3, sentinel.label1)])
     store = tacl.DataStore(':memory:')
     store._conn = MagicMock(spec_set=sqlite3.Connection)
     cursor = store._conn.execute.return_value
     cursor.fetchone.return_value = {'checksum': sentinel.checksum}
     actual_result = store.validate(corpus, catalogue)
     corpus.get_texts.assert_has_calls([
         call(sentinel.text1), call(sentinel.text2), call(sentinel.text3)])
     self.assertEqual(store._conn.mock_calls,
                      [call.execute(tacl.constants.SELECT_TEXT_SQL,
                                    [sentinel.name, sentinel.siglum]),
                       call.execute().fetchone(),
                       call.execute(tacl.constants.SELECT_TEXT_SQL,
                                    [sentinel.name, sentinel.siglum]),
                       call.execute().fetchone(),
                       call.execute(tacl.constants.SELECT_TEXT_SQL,
                                    [sentinel.name, sentinel.siglum]),
                       call.execute().fetchone()])
     self.assertEqual(actual_result, True)
开发者ID:cwittern,项目名称:tacl,代码行数:28,代码来源:data_store_test.py

示例3: test_build_local_sources

    def test_build_local_sources(self):
        class Options:
            source = '.'
            node_packages = []
            node_engine = '4'

        plugin = nodejs.NodePlugin('test-part', Options(),
                                   self.project_options)

        os.makedirs(plugin.sourcedir)
        open(os.path.join(plugin.sourcedir, 'package.json'), 'w').close()

        plugin.build()

        self.run_mock.assert_has_calls([
            mock.call(['npm', '--cache-min=Infinity', 'install'],
                      cwd=plugin.builddir),
            mock.call(['npm', '--cache-min=Infinity', 'install', '--global'],
                      cwd=plugin.builddir)])
        self.tar_mock.assert_has_calls([
            mock.call(
                nodejs.get_nodejs_release(plugin.options.node_engine),
                path.join(os.path.abspath('.'), 'parts', 'test-part', 'npm')),
            mock.call().provision(
                plugin.installdir, clean_target=False, keep_tarball=True)])
开发者ID:SamYaple,项目名称:snapcraft,代码行数:25,代码来源:test_plugin_nodejs.py

示例4: test_download_build

def test_download_build(mock_cc, mock_sp, capsys):
    mock_client = MagicMock(no_config=False)
    mock_client.get_build_details.return_value = \
        MagicMock(
            data={"chroots": {
                u'epel-6-x86_64': u'succeeded', u'epel-6-i386': u'succeeded'
            }},
            results_by_chroot={
                u'epel-6-x86_64': u'http://example.com/results/epel-6-x86_64/python-copr-1.50-1.fc20',
                u'epel-6-i386': u'http://example.com/results/epel-6-i386/python-copr-1.50-1.fc20',
            }
        )
    mock_cc.create_from_file_config.return_value = mock_client

    mock_sp.call.return_value = None
    main.main(argv=["download-build", "foo"])
    stdout, stderr = capsys.readouterr()

    expected_sp_call_args = [
        mock.call([
            'wget', '-r', '-nH', '--no-parent', '--reject', "'index.html*'",
            '-P', u'./epel-6-x86_64', '--cut-dirs', '6',
            'http://example.com/results/epel-6-x86_64/python-copr-1.50-1.fc20'
        ]),
        mock.call([
            'wget', '-r', '-nH', '--no-parent', '--reject', "'index.html*'",
            '-P', u'./epel-6-i386', '--cut-dirs', '6',
            'http://example.com/results/epel-6-i386/python-copr-1.50-1.fc20'
        ])
    ]

    assert mock_sp.call.call_args_list == expected_sp_call_args
开发者ID:domcleal,项目名称:copr,代码行数:32,代码来源:test_cli.py

示例5: test_flavor_grant

    def test_flavor_grant(self, mock_get_nova):
        nova_client = mock.Mock()
        mock_get_nova.return_value = nova_client

        def good_get_keys():
            return {'flavor_class:name': 'compute'}

        def bad_get_keys():
            return {'flavor_class:name': 'standard'}

        def none_get_keys():
            return {'foo': 'bar'}

        small = mock.Mock(get_keys=good_get_keys)
        small.name = 'c3.small'
        medium = mock.Mock(get_keys=good_get_keys)
        medium.name = 'c3.medium'
        large = mock.Mock(get_keys=good_get_keys)
        large.name = 'c3.large'
        other = mock.Mock(get_keys=bad_get_keys)
        other.name = 'c1.small'
        no_prefix = mock.Mock(get_keys=none_get_keys)
        no_prefix.name = 'custom-flavor'
        all_flavors = [small, medium, large, other, no_prefix]

        nova_client.flavors.list.return_value = all_flavors

        self.manager.flavor_grant(self.allocation, 'compute')
        calls = [mock.call(small, self.allocation.project_id),
                 mock.call(medium, self.allocation.project_id),
                 mock.call(large, self.allocation.project_id),
        ]
        nova_client.flavor_access.add_tenant_access.assert_has_calls(
            calls)
开发者ID:NeCTAR-RC,项目名称:nectar-tools,代码行数:34,代码来源:test_provisioner.py

示例6: run_fetch

    def run_fetch(self, value, opcode, instruction_size, r2=True):
        """Run one fetch test."""
        address1 = 10
        address2 = 42
        self.ram.put(address1, value, instruction_size)
        increment = instruction_size // self.ram.word_size

        # pylint: disable=no-member
        self.registers.fetch.reset_mock()
        self.registers.put.reset_mock()

        def get_register(name, size):
            """Get PC."""
            if name == "PC":
                assert size == 2 * BYTE_SIZE
                return address1
            elif name == "R2":
                assert size == WORD_SIZE
                return address2
            else:
                raise KeyError()

        self.registers.fetch.side_effect = get_register

        self.control_unit.fetch_and_decode()
        if r2:
            self.registers.fetch.assert_has_calls([call("PC", 2 * BYTE_SIZE),
                                                   call("R2", WORD_SIZE)])
        else:
            self.registers.fetch.assert_any_call("PC", 2 * BYTE_SIZE)
        self.registers.put.assert_has_calls([call("RI", value, WORD_SIZE),
                                             call("PC", address1 + increment, 2 * BYTE_SIZE)])
        assert self.control_unit.opcode == opcode
开发者ID:cmc-python,项目名称:modelmachine,代码行数:33,代码来源:test_cu_variable.py

示例7: test_pull_with_revision

    def test_pull_with_revision(self, run_mock, script_mock):
        plugin = rust.RustPlugin("test-part", self.options, self.project_options)
        os.makedirs(plugin.sourcedir)
        plugin.options.rust_revision = "1.13.0"
        plugin.options.rust_channel = ""

        plugin.pull()

        self.assertThat(run_mock.call_count, Equals(2))

        rustdir = os.path.join(plugin.partdir, "rust")
        run_mock.assert_has_calls(
            [
                mock.call(
                    [
                        os.path.join(rustdir, "rustup.sh"),
                        "--prefix={}".format(rustdir),
                        "--disable-sudo",
                        "--save",
                        "--revision=1.13.0",
                    ]
                ),
                mock.call(
                    [
                        plugin._cargo,
                        "fetch",
                        "--manifest-path",
                        os.path.join(plugin.sourcedir, "Cargo.toml"),
                    ],
                    env=plugin._build_env(),
                ),
            ]
        )
开发者ID:mvo5,项目名称:snapcraft,代码行数:33,代码来源:test_rust.py

示例8: test_loop

def test_loop(mock_input, mock_time, use_case):
    """Test each use case"""
    pin = 19

    def input_generator(readings):
        for r in readings:
            incr_time(r[0])
            yield r[1]
    mock_input.side_effect = input_generator(use_case['readings'])

    sleeps = [r[0] for r in use_case['readings']]
    mock_time.side_effect = sleeps

    observer = Mock()
    w = Watcher(observer,
                pin,
                debounce_delay=use_case['debounce'],
                sleep=sleeps)
    w.start()
    w.join()

    assert mock_time.mock_calls == [call(s) for s in sleeps]
    assert mock_input.mock_calls == [call(pin) for i in range(len(sleeps))]
    assert observer.update_pin.mock_calls == [
        call(19, u) for u in use_case['expected_updates']
    ]
开发者ID:dmreiland,项目名称:thingpin,代码行数:26,代码来源:test_pin_watcher.py

示例9: test_verisure_no_default_code

async def test_verisure_no_default_code(hass):
    """Test configs without a default lock code."""
    await setup_verisure_locks(hass, NO_DEFAULT_LOCK_CODE_CONFIG)
    with mock_hub(NO_DEFAULT_LOCK_CODE_CONFIG,
                  STATE_UNLOCKED) as hub:

        mock = hub.session.set_lock_state
        await hass.services.async_call(LOCK_DOMAIN, SERVICE_LOCK, {
            'entity_id': 'lock.door_lock',
        })
        await hass.async_block_till_done()
        assert mock.call_count == 0

        await hass.services.async_call(LOCK_DOMAIN, SERVICE_LOCK, {
            'entity_id': 'lock.door_lock',
            'code': '12345',
        })
        await hass.async_block_till_done()
        assert mock.call_args == call('12345', LOCKS[0], 'lock')

        mock.reset_mock()
        await hass.services.async_call(LOCK_DOMAIN, SERVICE_UNLOCK, {
            'entity_id': 'lock.door_lock',
        })
        await hass.async_block_till_done()
        assert mock.call_count == 0

        await hass.services.async_call(LOCK_DOMAIN, SERVICE_UNLOCK, {
            'entity_id': 'lock.door_lock',
            'code': '12345',
        })
        await hass.async_block_till_done()
        assert mock.call_args == call('12345', LOCKS[0], 'unlock')
开发者ID:Martwall,项目名称:home-assistant,代码行数:33,代码来源:test_verisure.py

示例10: test_login_tries_both_addrs_and_caches

    def test_login_tries_both_addrs_and_caches(self, mock_camera, mock_store):
        """"Test the login tries."""
        responses = [0]

        def fake_login(*a):
            """Fake login."""
            try:
                responses.pop(0)
                raise socket.error
            except IndexError:
                pass

        mock_store.return_value.get_camera_password.return_value = None
        mock_camera.return_value.login.side_effect = fake_login
        self.uvc._login()
        self.assertEqual(2, mock_camera.call_count)
        self.assertEqual('host-b', self.uvc._connect_addr)

        mock_camera.reset_mock()
        self.uvc._login()
        self.assertEqual(mock_camera.call_count, 1)
        self.assertEqual(
            mock_camera.call_args, mock.call('host-b', 'admin', 'seekret')
        )
        self.assertEqual(mock_camera.return_value.login.call_count, 1)
        self.assertEqual(mock_camera.return_value.login.call_args, mock.call())
开发者ID:JiShangShiDai,项目名称:home-assistant,代码行数:26,代码来源:test_uvc.py

示例11: test_setup_partial_config_v31x

    def test_setup_partial_config_v31x(self, mock_uvc, mock_remote):
        """Test the setup with a v3.1.x server."""
        config = {
            'platform': 'uvc',
            'nvr': 'foo',
            'key': 'secret',
        }
        fake_cameras = [
            {'uuid': 'one', 'name': 'Front', 'id': 'id1'},
            {'uuid': 'two', 'name': 'Back', 'id': 'id2'},
        ]
        mock_remote.return_value.index.return_value = fake_cameras
        mock_remote.return_value.get_camera.return_value = {'model': 'UVC'}
        mock_remote.return_value.server_version = (3, 1, 3)

        assert setup_component(self.hass, 'camera', {'camera': config})

        self.assertEqual(mock_remote.call_count, 1)
        self.assertEqual(
            mock_remote.call_args, mock.call('foo', 7080, 'secret')
        )
        mock_uvc.assert_has_calls([
            mock.call(mock_remote.return_value, 'one', 'Front', 'ubnt'),
            mock.call(mock_remote.return_value, 'two', 'Back', 'ubnt'),
        ])
开发者ID:JiShangShiDai,项目名称:home-assistant,代码行数:25,代码来源:test_uvc.py

示例12: test_pip

    def test_pip(self, mock_run, mock_setup_pip):
        self.options.requirements = 'requirements.txt'
        self.options.constraints = 'constraints.txt'
        self.options.python_packages = ['test', 'packages']

        plugin = python2.Python2Plugin('test-part', self.options,
                                       self.project_options)
        setup_directories(plugin)

        pip2 = os.path.join(plugin.installdir, 'usr', 'bin', 'pip2')
        include = os.path.join(
            plugin.installdir, 'usr', 'include', 'python2.7')
        target = os.path.join(
            plugin.installdir, 'usr', 'lib', 'python2.7', 'site-packages')
        pip_install = ['python2', pip2, 'install',
                       '--global-option=build_ext',
                       '--global-option=-I{}'.format(include),
                       '--target', target]

        requirements_path = os.path.join(plugin.sourcedir, 'requirements.txt')
        constraints_path = os.path.join(plugin.sourcedir, 'constraints.txt')
        pip_install = pip_install + ['--constraint', constraints_path]
        calls = [
            mock.call(pip_install + ['--requirement', requirements_path]),
            mock.call(pip_install + ['--upgrade', 'test', 'packages']),
            mock.call(pip_install + ['.'], cwd=plugin.sourcedir)
        ]
        plugin.pull()
        mock_run.assert_has_calls(calls)
开发者ID:markshuttle,项目名称:snapcraft,代码行数:29,代码来源:test_plugin_python2.py

示例13: test_download_redownload_as_hash_mismatches

    def test_download_redownload_as_hash_mismatches(self):
        with open('os.snap', 'wb') as f:
            f.write(b'0000000')

        snap_content = b'1234567890'
        snap_sha512 = ('12b03226a6d8be9c6e8cd5e55dc6c7920caaa39df14aab92d5e'
                       '3ea9340d1c8a4d3d0b8e4314f1f6ef131ba4bf1ceb9186ab87c'
                       '801af0d5c95b1befb8cedae2b9')
        mock_details = self.mock_get.return_value
        mock_details.ok = True
        mock_details.content = json.dumps({
            '_embedded': {
                    'clickindex:package': [{
                        'download_url': 'http://localhost',
                        'anon_download_url': 'http://localhost',
                        'download_sha512': snap_sha512,
                    }],
            }
        }).encode('utf-8')
        mock_snap = Response()
        mock_snap.status_code = 200
        mock_snap._content = snap_content

        self.mock_get.side_effect = [mock_details, mock_snap]

        download('os', 'edge', 'os.snap', None, 'amd64')

        self.mock_logger.info.assert_has_calls([
            call("Getting details for 'os'"),
            call("Downloading 'os'"),
            call("Successfully downloaded 'os'")])
        self.assertTrue(os.path.exists('os.snap'))
开发者ID:0-T-0,项目名称:snapcraft,代码行数:32,代码来源:test_storeapi_download.py

示例14: test_download_fails_due_to_hash_mismatch

    def test_download_fails_due_to_hash_mismatch(self):
        snap_content = b'1234567890'
        mock_details = self.mock_get.return_value
        mock_details.ok = True
        mock_details.content = json.dumps({
            '_embedded': {
                    'clickindex:package': [{
                        'download_url': 'http://localhost',
                        'anon_download_url': 'http://localhost',
                        'download_sha512': '12345',
                    }],
            }
        }).encode('utf-8')
        mock_snap = Response()
        mock_snap.status_code = 200
        mock_snap._content = snap_content

        self.mock_get.side_effect = [mock_details, mock_snap]

        with self.assertRaises(RuntimeError) as raised:
            download('os', 'edge', 'os.snap', None, 'amd64')

        self.assertEqual("Failed to download 'os'", str(raised.exception))
        self.mock_logger.info.assert_has_calls([
            call("Getting details for 'os'"),
            call("Downloading 'os'")])
        self.assertTrue(os.path.exists('os.snap'))
开发者ID:0-T-0,项目名称:snapcraft,代码行数:27,代码来源:test_storeapi_download.py

示例15: test_run_ansible_with_check

    def test_run_ansible_with_check(self, mc_check_for_ans_errror):
        builder = self.get_test_builder()

        cmd = "cmd"
        module_name = "module_name"
        as_root = True

        err_codes = [1, 3, 7, ]
        success_codes = [0, 255]

        results = mock.MagicMock()

        err_results = mock.MagicMock()

        mc_check_for_ans_errror.return_value = (False, [])
        builder._run_ansible = mock.MagicMock()
        builder._run_ansible.return_value = results

        got_results = builder.run_ansible_with_check(
            cmd, module_name, as_root, err_codes, success_codes)

        assert results == got_results
        expected_call_run = mock.call(cmd, module_name, as_root)
        assert expected_call_run == builder._run_ansible.call_args
        expected_call_check = mock.call(results, builder.hostname,
                                        err_codes, success_codes)
        assert expected_call_check == mc_check_for_ans_errror.call_args

        mc_check_for_ans_errror.side_effect = AnsibleResponseError(msg="err message", **err_results)

        with pytest.raises(AnsibleCallError):
            builder.run_ansible_with_check(
                cmd, module_name, as_root, err_codes, success_codes)
开发者ID:danvratil,项目名称:copr,代码行数:33,代码来源:test_builder.py


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