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


Python MagicMock.side_effect方法代码示例

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


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

示例1: test_http_errors

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
def test_http_errors(monkeypatch):
    resp = MagicMock()
    resp.status_code = 404
    resp.raise_for_status.side_effect = requests.HTTPError("Not Found")
    get = MagicMock()
    get.return_value = resp
    monkeypatch.setattr("requests.get", get)
    http = HttpWrapper("http://example.org")
    # the code method will not raise an exception..
    assert 404 == http.code()
    for meth in ("time", "json", "cookies", "headers"):
        with pytest.raises(HttpError) as ex:
            # ..but other methods will!
            getattr(http, meth)()
        assert "Not Found" == ex.value.message

    get.side_effect = requests.Timeout("timed out")
    http = HttpWrapper("http://example.org")
    with pytest.raises(HttpError) as ex:
        http.time()
    assert "timeout" == ex.value.message

    get.side_effect = requests.ConnectionError("connfail")
    http = HttpWrapper("http://example.org")
    with pytest.raises(HttpError) as ex:
        http.code()
    assert "connection failed" == ex.value.message

    get.side_effect = Exception("foofail")
    http = HttpWrapper("http://example.org")
    with pytest.raises(HttpError) as ex:
        http.code()
    assert "foofail" == ex.value.message
开发者ID:amjedonline,项目名称:zmon-worker,代码行数:35,代码来源:test_http.py

示例2: test_check_connection

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_check_connection(self):
        """
        Does it only ping the server if the option was set?
        """
        ping = MagicMock()
        dut = MagicMock()
        configuration_mock = MagicMock()
        dut.operating_system = 'linux'
        self.tester._dut = dut
        self.tester._server = MagicMock()
        self.tester._server.TestInterface = 'server'

        # check that it doesn't run
        self.parser.has_section.return_value = False
        #self.tester.configuration.ping = None
        outcome = self.tester.connected()
        with self.assertRaises(AssertionError):
            ping.assert_called_with()
        self.assertTrue(outcome)

        # check that it does run
        self.tester._ping = ping
        mock_time = MagicMock()
        times = [500,4,3, 2, 1]
        # pinged
        mock_time.side_effect = lambda: times.pop()
        with patch('time.time', mock_time):
            ping.return_value = True
            outcome = self.tester.connected()
            ping.assert_called_with()
            
        times = [700, 600, 500,400 ,300, 40,30, 20, 10]
        def time_effects():
            output =  times.pop()
            return output
        
        # timed out
        mock_time.side_effect = time_effects
        #mock_time_2 = MagicMock()
        self.tester._result_location = 'cache'
        with patch('time.time', mock_time):
            ping.return_value = False
            outcome = self.tester.connected()
            ping.assert_called_with()
            self.assertFalse(outcome)
        
        # timed out
        times = [700, 600, 100, 10]
        
        mock_time.side_effect = lambda: times.pop()
        # raises exception if asked to
        start = 0
        attenuation = 0
        with self.assertRaises(CameraobscuraError):
            with patch('time.time', mock_time):
                ping.return_value = False
                self.tester.connected(raise_error=start==attenuation)
        return
开发者ID:russellnakamura,项目名称:cameraobscura,代码行数:60,代码来源:testautomatedrvr.py

示例3: test_results_set

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
        def test_results_set(self, mock_algorithms, model):
            # Mock out algorithm return value.
            first_algo = MagicMock()
            first_algo.algorithm.return_value = sentinel.results
            first_algo.name = sentinel.algo_name
            mock_algorithms.registry = [first_algo]

            # Mock out timing.
            class DefaultTimer(object):
                RETVALS = [24, 35]

                def __init__(self):
                    self.times_called = 0

                def __call__(self):
                    retval = self.RETVALS[self.times_called]
                    self.times_called += 1
                    return retval

            mock_default_timer = MagicMock()
            mock_default_timer.side_effect = DefaultTimer()

            with patch('timeit.default_timer', mock_default_timer):
                model.compute_islands(sentinel.seq_record,
                                      sentinel.island_size,
                                      sentinel.min_gc_ratio,
                                      sentinel.min_obs_exp_cpg_ratio,
                                      0)
            assert mock_default_timer.mock_calls == [call() for _ in xrange(2)]
            assert (model.results_model.mock_calls ==
                    [call.set_results(
                        sentinel.results, sentinel.algo_name, 11)])
开发者ID:seanfisk,项目名称:cpg-islands,代码行数:34,代码来源:test_seq_input.py

示例4: mock_connect

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
def mock_connect(connect_error=False, fetch_error=False, no_login=False, no_group=False, results={}):
    conn = MagicMock()
    cursor = MagicMock()
    row = MagicMock()

    row.can_login = False if no_login else True
    row.member_of = [] if no_group else [REQUIRED_GROUP]

    row._asdict.return_value = results

    if not fetch_error:
        cursor.fetchone.return_value = row
        cursor.fetchmany.return_value = [row] * RESULT_COUNT
    else:
        cursor.fetchone.side_effect = Exception()
        cursor.fetchmany.side_effect = Exception()

    conn.cursor = MagicMock()
    conn.cursor.return_value = cursor

    connect = MagicMock()
    if not connect_error:
        connect.return_value = conn
    else:
        connect.side_effect = Exception()

    return connect
开发者ID:drummerwolli,项目名称:zmon-worker,代码行数:29,代码来源:test_sql_postgresql.py

示例5: test_process_function_logs_error

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
def test_process_function_logs_error(mock_loop, mock_resource, mock_log, mock_get_task):
    "test ..."
    # Arrange
    Q = QueueProcessor(run=False)

    fake_task_name = fake.pystr()
    fake_params = fake.pylist()

    fake_message = {
        'task': fake_task_name,
        'parameters': fake_params
    }
    mock_task = MagicMock()
    def raise_exception(*args, **kwargs):
        raise Exception()
    mock_task.side_effect = raise_exception
    mock_get_task.return_value = mock_task

    # Act
    Q.process(fake_message)

    # Assert
    mock_get_task.assert_called_once_with(fake_task_name)
    mock_log.exception.assert_called()
    mock_task.assert_called_once_with(Q, *fake_params)
开发者ID:playconsult,项目名称:eurystheus,代码行数:27,代码来源:test_eurystheus.py

示例6: test_call

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_call(self):
        """
        Does the call try to ping the device correctly?
        """
        time_mock = MagicMock()
        logger = Mock()
        self.ping._logger = logger

        # case 1 : success
        test_line = '64 bytes from pc-in-f147.1e100.net (74.125.28.147): icmp_req=1 ttl=44 time=13.7 ms'
        self.assertIsNotNone(self.ping.command.data_expression.search(test_line))
        self.connection.exec_command.return_value = None, [test_line], StringIO('')
        
        time_mock.return_value = 0
        with patch('time.time', time_mock):
            self.assertTrue(self.ping())

        ## case 2: failure
        ## this fails sometimes -- the actual path needs to be worked out
        self.connection.exec_command.return_value = None, '', ''
        times = [self.timeout] * 2 + [0] * (self.threshold + 1)
        time_mock.side_effect = lambda: times.pop()
        with patch('time.time', time_mock):
            self.assertFalse(self.ping())

        # case 3: connection problem
        self.connection.exec_command.side_effect = socket.timeout("socket timed out-- catch it")
        with self.assertRaises(CameraobscuraError):
            self.ping()
        return
开发者ID:russellnakamura,项目名称:cameraobscura,代码行数:32,代码来源:testping.py

示例7: test_export_full_json

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_export_full_json(self):
        mock_warc_iter_cls = MagicMock()
        mock_warc_iter = MagicMock()
        mock_warc_iter_cls.side_effect = [mock_warc_iter]
        mock_warc_iter.iter.return_value = [
            IterItem(None, None, None, None, {"key1": "k1v1", "key2": "k2v1", "key3": "k3v1"}),
            IterItem(None, None, None, None, {"key1": "k1v2", "key2": "k2v2", "key3": "k3v2"}),
        ]

        export_filepath = os.path.join(self.export_path, "test")
        now = datetime_now()
        limit_uids = [11, 14]

        exporter = BaseExporter(
            None, mock_warc_iter_cls, None, self.working_path, warc_base_path=self.warc_base_path, host="testhost"
        )

        exporter._full_json_export(self.warcs, export_filepath, True, now, None, limit_uids, None)

        mock_warc_iter_cls.assert_called_once_with(self.warcs, limit_uids)
        mock_warc_iter.iter.assert_called_once_with(
            dedupe=True, item_date_start=now, item_date_end=None, limit_item_types=None
        )

        file_path = export_filepath + "_001.json"
        self.assertTrue(os.path.exists(file_path))
        with open(file_path, "r") as f:
            lines = f.readlines()
        self.assertEqual(2, len(lines))
        self.assertDictEqual({"key1": "k1v1", "key2": "k2v1", "key3": "k3v1"}, json.loads(lines[0]))
开发者ID:gwu-libraries,项目名称:sfm-utils,代码行数:32,代码来源:test_exporter.py

示例8: test_wait_for_state_boto3_error

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
 def test_wait_for_state_boto3_error(self, mock_sleep):
     """Test wait_for_state_boto3 with RuntimeError and returned RuntimeError"""
     mock_describe_func = MagicMock()
     mock_describe_func.side_effect = RuntimeError
     self.assertRaises(RuntimeError, wait_for_state_boto3, mock_describe_func, {"param1": "p1"},
                       "myresource", 'available', state_attr='status', timeout=30)
     self.assertEqual(1, mock_describe_func.call_count)
开发者ID:amplifylitco,项目名称:asiaq,代码行数:9,代码来源:test_resource_helper.py

示例9: test_stream_mentions_multiple_people

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_stream_mentions_multiple_people(self, mock_random_token: MagicMock) -> None:
        """A mention should take precedence over regular stream messages for email subjects.

        Each sender who has mentioned a user should appear in the email subject line.
        """
        tokens = self._get_tokens()
        mock_random_token.side_effect = tokens

        hamlet = self.example_user('hamlet')
        msg_id_1 = self.send_stream_message(self.example_email('iago'),
                                            "Denmark",
                                            '@**King Hamlet**')
        msg_id_2 = self.send_stream_message(self.example_email('othello'),
                                            "Denmark",
                                            '@**King Hamlet**')
        msg_id_3 = self.send_stream_message(self.example_email('cordelia'),
                                            "Denmark",
                                            'Regular message')

        handle_missedmessage_emails(hamlet.id, [
            {'message_id': msg_id_1, "trigger": "mentioned"},
            {'message_id': msg_id_2, "trigger": "mentioned"},
            {'message_id': msg_id_3, "trigger": "stream_email_notify"},
        ])
        self.assertEqual(len(mail.outbox), 1)
        email_subject = 'Iago, Othello, the Moor of Venice mentioned you'
        self.assertEqual(mail.outbox[0].subject, email_subject)
开发者ID:akashnimare,项目名称:zulip,代码行数:29,代码来源:test_notifications.py

示例10: test_throttled_call_clienterror_timeout

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
 def test_throttled_call_clienterror_timeout(self, mock_sleep):
     """Test throttle_call using ClientError and timeout"""
     mock_func = MagicMock()
     error_response = {"Error": {"Code": "Throttling"}}
     client_error = ClientError(error_response, "test")
     mock_func.side_effect = client_error
     self.assertRaises(ClientError, throttled_call, mock_func)
开发者ID:amplifylitco,项目名称:asiaq,代码行数:9,代码来源:test_resource_helper.py

示例11: _extra_context_in_missed_stream_messages_mention

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def _extra_context_in_missed_stream_messages_mention(self, send_as_user: bool,
                                                         mock_random_token: MagicMock,
                                                         show_message_content: bool=True) -> None:
        tokens = self._get_tokens()
        mock_random_token.side_effect = tokens

        for i in range(0, 11):
            self.send_stream_message(self.example_email('othello'), "Denmark", content=str(i))
        self.send_stream_message(
            self.example_email('othello'), "Denmark",
            '11', topic_name='test2')
        msg_id = self.send_stream_message(
            self.example_email('othello'), "denmark",
            '@**King Hamlet**')

        if show_message_content:
            body = 'Denmark > test Othello, the Moor of Venice 1 2 3 4 5 6 7 8 9 10 @**King Hamlet**'
            email_subject = 'Othello, the Moor of Venice mentioned you'
            verify_body_does_not_include = []  # type: List[str]
        else:
            # Test in case if message content in missed email message are disabled.
            body = 'While you were away you received 1 new message in which you were mentioned!'
            email_subject = 'New missed message'
            verify_body_does_not_include = ['Denmark > test', 'Othello, the Moor of Venice',
                                            '1 2 3 4 5 6 7 8 9 10 @**King Hamlet**', 'private', 'group',
                                            'Or just reply to this email.']
        self._test_cases(tokens, msg_id, body, email_subject, send_as_user,
                         show_message_content=show_message_content,
                         verify_body_does_not_include=verify_body_does_not_include,
                         trigger='mentioned')
开发者ID:akashnimare,项目名称:zulip,代码行数:32,代码来源:test_notifications.py

示例12: test_extra_kwargs

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_extra_kwargs(self):

        # create and connect a pre and post fake receiver to the desired signal
        pre_receiver = MagicMock(return_value=None)
        post_receiver = MagicMock(return_value=None)

        # set the return value of the pre_receiver to the uuid value
        # so we can use it in later test.
        def side_effect(*args, **kwargs):
            pre_receiver.return_value = kwargs['uuid']
            return kwargs

        pre_receiver.side_effect = side_effect
        pre_transition_event.connect(
            pre_receiver, dispatch_uid='blah kwargs pre'
        )
        post_transition_event.connect(
            post_receiver, dispatch_uid='blah kwargs post'
        )

        # call the transition that will trigger the signal
        self.new_instance.test_some_event()

        # ensure the receiver was only called once with the correct args
        post_receiver.assert_called_once_with(
            instance=self.new_instance, from_state=FakeStates.NEW,
            to_state=FakeStates.WHATEVER, state='fake_state',
            transition_name='test_some_event', signal=post_transition_event,
            sender=self.new_instance.__class__, uuid=pre_receiver.return_value,
            some_event_name="Yes An Event"
        )

        # cleanup
        pre_transition_event.disconnect(pre_receiver)
        post_transition_event.disconnect(post_receiver)
开发者ID:hangarunderground,项目名称:transmission,代码行数:37,代码来源:tests.py

示例13: mock_controller

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def mock_controller(self, plugin_label, method, return_value = None,
            side_effect = None, mock = None):
        """
        Mocks controller by label. Can only be used to test controllers
        that get instantiated automatically by cement.
        @param plugin_label: e.g. 'drupal'
        @param method: e.g. 'enumerate_plugins'
        @param return_value: what to return. Default is None, unless the
            method starts with enumerate_*, in which case the result is a
            tuple as expected by BasePlugin.
        @param mock: the MagicMock to place. If None, a blank MagicMock is
            created.
        @param side_effect: if set to an exception, it will raise an
            exception.
        """
        if mock:
            m = mock
        else:
            m = MagicMock()

        if return_value != None:
            m.return_value = return_value
        else:
            if method.startswith("enumerate_"):
                m.return_value = ({"a":[]}, True)

        if side_effect:
            m.side_effect = side_effect

        setattr(self.controller_get(plugin_label), method, m)
        return m
开发者ID:vielsoft,项目名称:droopescan,代码行数:33,代码来源:__init__.py

示例14: test_get_request_exception_and_retry_four_times

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_get_request_exception_and_retry_four_times(self, Session):
        request_exception = RequestException('I raise RequestException!')
        def exception_raiser(method, url, data, params, headers=None,
                             allow_redirects=None):
            raise request_exception

        Session.return_value = MagicMock(request=exception_raiser)

        ex = HttpExecutor('http://api.stormpath.com/v1', ('user', 'pass'))

        def try_four_times(retries, status):
            return retries <= 3

        ShouldRetry = MagicMock()
        ShouldRetry.side_effect = try_four_times

        with patch('stormpath.http.HttpExecutor.should_retry', ShouldRetry):
            with self.assertRaises(Error):
                ex.get('/test')

        should_retry_calls = [
            call(0, request_exception), call(1, request_exception),
            call(2, request_exception), call(3, request_exception),
            call(4, request_exception)
        ]
        ShouldRetry.assert_has_calls(should_retry_calls)
开发者ID:seanodonnell,项目名称:stormpath-sdk-python,代码行数:28,代码来源:test_http.py

示例15: test_retry_decorator

# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import side_effect [as 别名]
    def test_retry_decorator(self, m_logger, m_config):
        """
        Raise AutoReconnect once (simulate no connection to db), hijack the logger to fix the mock
        so it is not an infinite loop.
        """
        mock_r = MagicMock()
        mock_r.side_effect = AutoReconnect

        def restart_mongo(*args):
            """
            Simulate turning Mongo back on.
            """
            mock_r.side_effect = None
            mock_r.return_value = 'final'

        @connection.UnsafeRetry.retry_decorator(full_name='mock_coll')
        def mock_func():
            """
            Simple function to decorate.
            """
            return mock_r()

        m_config.getboolean.return_value = True
        m_logger.error.side_effect = restart_mongo

        final_answer = mock_func()
        m_logger.error.assert_called_once_with('mock_func operation failed on mock_coll')
        self.assertTrue(final_answer is 'final')
开发者ID:alanoe,项目名称:pulp,代码行数:30,代码来源:test_connection.py


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