當前位置: 首頁>>代碼示例>>Python>>正文


Python mock.patch方法代碼示例

本文整理匯總了Python中mock.patch方法的典型用法代碼示例。如果您正苦於以下問題:Python mock.patch方法的具體用法?Python mock.patch怎麽用?Python mock.patch使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mock的用法示例。


在下文中一共展示了mock.patch方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_callSnappy

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_callSnappy():
    """
    Test pdinstall.snappy.callSnappy
    """
    from pdinstall.snappy import callSnappy

    with patch("pdinstall.snappy.subprocess") as subprocess:
        proc = MagicMock()
        subprocess.Popen.return_value = proc
        proc.stdout = ["Output message"]
        proc.stderr = ["Error message"]
        proc.returncode = 0

        assert callSnappy("install")
        assert proc.wait.called

        subprocess.Popen.side_effect = Exception("Boom!")
        assert callSnappy("install") is False 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:20,代碼來源:test_snappy.py

示例2: test_installedSnaps

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_installedSnaps():
    """
    Test pdinstall.snappy.installedSnaps
    """
    from pdinstall.snappy import installedSnaps

    with patch("pdinstall.snappy.subprocess") as subprocess:
        proc = MagicMock()
        subprocess.Popen.return_value = proc
        proc.stdout = [
            "Name Date Version Developer",
            "bad line",
            "paradrop 2015-01-01 0.1.0"
        ]

        snaps = installedSnaps()
        assert snaps == {'paradrop': '0.1.0'}

        subprocess.Popen.side_effect = Exception("Boom!")
        assert_raises(Exception, installedSnaps) 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:22,代碼來源:test_snappy.py

示例3: test_get_with_course_id_for_other_site

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_get_with_course_id_for_other_site(self):
        """
        This tests if the course can't be found in the organization

        This test is incomplete
        """
        with mock.patch('figures.helpers.settings.FEATURES', {'FIGURES_IS_MULTISITE': True}):
            assert figures.helpers.is_multisite()

            # Stand up other site. Candidate for a fixture
            other_site = SiteFactory(domain='other.site')
            other_org = OrganizationFactory(sites=[other_site])
            course = CourseOverviewFactory(org=other_org.short_name)

            request = APIRequestFactory().get(self.request_path)
            force_authenticate(request, user=self.staff_user)
            view = self.view_class.as_view({'get': 'retrieve'})
            response = view(request, pk=str(course.id))
            assert response.status_code == 403 
開發者ID:appsembler,項目名稱:figures,代碼行數:21,代碼來源:test_general_course_data_view.py

示例4: testUnzip

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def testUnzip(self, build_info, create_dir):
    src = '/tmp/input.zip'
    dst = '/out/dir/path'
    # bad args
    un = files.Unzip([], build_info)
    self.assertRaises(files.ActionError, un.Run)
    un = files.Unzip([src], build_info)
    self.assertRaises(files.ActionError, un.Run)
    # bad path
    un = files.Unzip([src, dst], build_info)
    self.assertRaises(files.ActionError, un.Run)
    # create error
    create_dir.side_effect = files.file_util.Error
    self.assertRaises(files.ActionError, un.Run)
    # good
    create_dir.side_effect = None
    with mock.patch.object(files.zipfile, 'ZipFile', autospec=True) as z:
      un = files.Unzip([src, dst], build_info)
      un.Run()
      z.assert_called_with(src)
      z.return_value.extractall.assert_called_with(dst)
      create_dir.assert_called_with(dst) 
開發者ID:google,項目名稱:glazier,代碼行數:24,代碼來源:files_test.py

示例5: logger

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def logger():
    # Configure logger mock
    logger = mock.MagicMock()
    logger_patch = mock.patch('logging.getLogger', mock.MagicMock(return_value=logger))
    logger_patch.start()

    yield logger

    logger_patch.stop()

    # Clear jira module configuration
    jira.enabled = None
    jira.execution_url = None
    jira.summary_prefix = None
    jira.labels = None
    jira.comments = None
    jira.fix_version = None
    jira.build = None
    jira.only_if_changes = None
    jira.jira_tests_status.clear()
    jira.attachments = [] 
開發者ID:Telefonica,項目名稱:toolium,代碼行數:23,代碼來源:test_jira.py

示例6: test_wait_until_done

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_wait_until_done(self):
    mock_projects = mock.Mock()
    mock_opearations = mock.Mock()
    mock_request = mock.Mock()
    self._mock_service.projects = mock.Mock(return_value=mock_projects)
    mock_projects.operations = mock.Mock(return_value=mock_opearations)
    mock_opearations.get = mock.Mock(return_value=mock_request)
    mock_request.execute = mock.Mock(return_value={'done': True, 'error': {}})
    test_instance = self._create_test_instance()
    with patch('apache_beam.io.filesystems.FileSystems', _MockFileSystems):
      test_instance.run_on_all_files()
      with self.assertRaisesRegexp(AssertionError, '.*already.*running.*'):
        # Since there are running operations, the next call raises an exception.
        test_instance.run_on_all_files()
      test_instance.wait_until_done()
      # Since all operations are done, the next call should raise no exceptions.
      test_instance.run_on_all_files() 
開發者ID:googlegenomics,項目名稱:gcp-variant-transforms,代碼行數:19,代碼來源:vep_runner_test.py

示例7: test_corrupted_split

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_corrupted_split(self):
        self.incoming.add_measures(self.metric.id, [
            incoming.Measure(datetime64(2014, 1, 1, 12, 0, 1), 69),
        ])
        self.trigger_processing()

        aggregation = self.metric.archive_policy.get_aggregation(
            "mean", numpy.timedelta64(5, 'm'))

        with mock.patch('gnocchi.carbonara.AggregatedTimeSerie.unserialize',
                        side_effect=carbonara.InvalidData()):
            results = self.storage._get_splits_and_unserialize({
                self.metric: {
                    aggregation: [
                        carbonara.SplitKey(
                            numpy.datetime64(1387800000, 's'),
                            numpy.timedelta64(5, 'm'))
                    ],
                },
            })[self.metric][aggregation]
            self.assertEqual(1, len(results))
            self.assertIsInstance(results[0], carbonara.AggregatedTimeSerie)
            # Assert it's an empty one since corrupted
            self.assertEqual(0, len(results[0]))
            self.assertEqual(results[0].aggregation, aggregation) 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:27,代碼來源:test_storage.py

示例8: test_add_measures_update_subset

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_add_measures_update_subset(self):
        m, m_sql = self._create_metric('medium')
        measures = [
            incoming.Measure(datetime64(2014, 1, 6, i, j, 0), 100)
            for i in six.moves.range(2) for j in six.moves.range(0, 60, 2)]
        self.incoming.add_measures(m.id, measures)
        self.trigger_processing([m])

        # add measure to end, in same aggregate time as last point.
        new_point = datetime64(2014, 1, 6, 1, 58, 1)
        self.incoming.add_measures(m.id, [incoming.Measure(new_point, 100)])

        with mock.patch.object(self.incoming, 'add_measures') as c:
            self.trigger_processing([m])
        for __, args, __ in c.mock_calls:
            self.assertEqual(
                list(args[3])[0][0], carbonara.round_timestamp(
                    new_point, args[1].granularity * 10e8)) 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:20,代碼來源:test_storage.py

示例9: test_bad_filter_lambda2

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_bad_filter_lambda2(self):
        # Causes error because not every d has the attribute "real"
        # but error only shows on grow
        filter_lambda = "d['real']"
        self.display_a()
        self.a.remove_filter(self.filter_lambda)

        self.check_num_nodes_edges(6, 8)
        with patch(SHOWERROR_FUNC) as errorMsgBox:
            self.a.add_filter(filter_lambda)
            self.assertFalse(errorMsgBox.called)
        with patch(SHOWERROR_FUNC) as errorMsgBox:
            try:
                self.a.grow_node(self.a._find_disp_node('out'))
            except Exception:
                pass
        self.assertTrue(errorMsgBox.called)
        # Make sure no edges added or removed
        #self.check_num_nodes_edges(6, 8) 
開發者ID:jsexauer,項目名稱:networkx_viewer,代碼行數:21,代碼來源:tests.py

示例10: test_interrupted_flush_index

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_interrupted_flush_index(self, local_client):
        target_index = {"red": {"local_timestamp": 4000, "remote_timestamp": 4000}}

        utils.set_local_index(local_client, target_index)

        local_client.index = {"invalid_data": []}

        with mock.patch("json.dump") as json_dump:
            json_dump.side_effect = ValueError("something went wrong")
            with pytest.raises(ValueError):
                local_client.flush_index(compressed=False)

        with open(local_client.index_path(), "rt") as fp:
            index = json.load(fp)

        assert index == target_index 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:18,代碼來源:test_local.py

示例11: test_get_index_timestamps

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_get_index_timestamps(self, s3_client, compression, magic_result):
        with mock.patch("magic.from_buffer") as from_buffer:
            # given
            from_buffer.return_value = magic_result

            utils.set_s3_index(
                s3_client,
                {
                    "hello": {"remote_timestamp": 1234, "local_timestamp": 1200},
                    "world": {"remote_timestamp": 5000},
                },
                compression=compression,
            )

            # then
            assert s3_client.get_remote_timestamp("hello") == 1234
            assert s3_client.get_index_local_timestamp("hello") == 1200

            assert s3_client.get_remote_timestamp("world") == 5000
            assert s3_client.get_index_local_timestamp("world") is None 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:22,代碼來源:test_s3.py

示例12: test_injector_does_not_fail_for_401_responses_with_no_content_type

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_injector_does_not_fail_for_401_responses_with_no_content_type():
    bower = bowerstatic.Bower()

    components = bower.components('components', os.path.join(
        os.path.dirname(__file__), 'bower_components'))

    def wsgi(environ, start_response):
        # Can not use 401 here as webtest only accepts 200 or 3xx, which is ok
        # as we want to test the behaviour if no content type is given
        start_response('302', [('Content-Type', None)])
        include = components.includer(environ)
        with pytest.raises(bowerstatic.Error):
            include('jquery/nonexistent.js')
        return [b'<html><head></head><body>Hello!</body></html>']

    injector = bower.injector(wsgi)

    c = Client(injector)

    # webtest checks, in contracy to pyramid, the headers and breaks if one of
    # them is not a string.
    with mock.patch('webtest.lint.check_headers'):
        c.get('/') 
開發者ID:faassen,項目名稱:bowerstatic,代碼行數:25,代碼來源:test_injector.py

示例13: setUp

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def setUp(self):
        self.patcher = patch('requests.get', side_effect=mock_requestsGithub)
        self.patcher.start() 
開發者ID:CLARIAH,項目名稱:grlc,代碼行數:5,代碼來源:test_loaders.py

示例14: test_load_with_include

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_load_with_include(main_contents, inner_contents):
    with mock.patch('pca.utils.serialization.yaml.read_from_file') as mocked_read_from_file:
        mocked_read_from_file.return_value = inner_contents
        result = serialization.load_yaml(main_contents)

    assert result == {
        'foo': ['spam', 'eggs'],
        'included': {'bar': ['spam', 'eggs']},
    } 
開發者ID:pcah,項目名稱:python-clean-architecture,代碼行數:11,代碼來源:test_yaml.py

示例15: test_load_from_file

# 需要導入模塊: import mock [as 別名]
# 或者: from mock import patch [as 別名]
def test_load_from_file():
    contents = (
        "---\n"
        "foo: bar\n"
    )

    with mock.patch('pca.utils.serialization.yaml.read_from_file') as mocked_read_from_file:
        mocked_read_from_file.return_value = contents
        result = serialization.load_yaml_from_filepath('path/to/a/file.yaml')

    assert result == {'foo': 'bar'}
    mocked_read_from_file.assert_called_with('path/to/a/file.yaml') 
開發者ID:pcah,項目名稱:python-clean-architecture,代碼行數:14,代碼來源:test_yaml.py


注:本文中的mock.patch方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。