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


Python responses.reset函数代码示例

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


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

示例1: test_check_catches_connection_problems

    def test_check_catches_connection_problems(self):
        # Try to actually hit http://dummy_host. It's bad practice to do live
        # requests in tests, but this is fast and doesn't actually go outside
        # the host (aka this test will work on an airplane).
        response = self.resource.check()
        self.assertEqual(response['status'], 'error')
        self.assertIn('Connection refused', response['error'])

        # Now mock
        es_urls = re.compile(r'https?://dummy_host.*')
        responses.add(
            responses.GET, es_urls,
            body=requests.exceptions.ConnectionError('Connection refused'))

        response = self.resource.check()
        self.assertEqual(response['status'], 'error')
        self.assertIn('Connection refused', response['error'])

        responses.reset()
        responses.add(
            responses.GET, es_urls,
            body=requests.exceptions.HTTPError('derp'))
        response = self.resource.check()
        self.assertEqual(response['status'], 'error')
        self.assertIn('derp', response['error'])
开发者ID:TabbedOut,项目名称:django_canary_endpoint,代码行数:25,代码来源:test_search_resources.py

示例2: test_calls

    def test_calls(self):
        # rpc call with positional parameters:
        def callback1(request):
            request_message = json.loads(request.body)
            self.assertEqual(request_message["params"], [42, 23])
            return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}')

        responses.add_callback(
            responses.POST, 'http://mock/xmlrpc',
            content_type='application/json',
            callback=callback1,
        )
        self.assertEqual(self.server.subtract(42, 23), 19)
        responses.reset()

        # rpc call with named parameters
        def callback2(request):
            request_message = json.loads(request.body)
            self.assertEqual(request_message["params"], {'y': 23, 'x': 42})
            return (200, {}, u'{"jsonrpc": "2.0", "result": 19, "id": 1}')

        responses.add_callback(
            responses.POST, 'http://mock/xmlrpc',
            content_type='application/json',
            callback=callback2,
        )
        self.assertEqual(self.server.subtract(x=42, y=23), 19)
        responses.reset()
开发者ID:spielzeugland,项目名称:jsonrpc-requests,代码行数:28,代码来源:tests.py

示例3: test_notification

 def test_notification(self):
     # Verify that we ignore the server response
     responses.add(responses.POST, 'http://mock/xmlrpc',
                   body='{"jsonrpc": "2.0", "result": 19, "id": 3}',
                   content_type='application/json')
     self.assertIsNone(self.server.subtract(42, 23, _notification=True))
     responses.reset()
开发者ID:spielzeugland,项目名称:jsonrpc-requests,代码行数:7,代码来源:tests.py

示例4: test_create_user

    def test_create_user(self):
        responses.reset()

        fixture = load_fixture("users/show/39.json")
        fixture = json.loads(fixture)
        fixture.update({'password':'password', 'password_confirmation':'password', 'login':'myname'})

        def check_user_was_created(request):
            body = json.loads(request.body)
            expected_data = {
                'access_token': body['access_token'],
                'user': fixture,
            }

            nose.tools.assert_equal(expected_data, body)
            return (200, {}, {})


        mock_auth_response()

        responses.add_callback(responses.POST,
                      RequestHandler._build_end_point_uri('/users/create'),
                      callback=check_user_was_created,
                      content_type='application/json')

        api = CsaAPI("admin", 'taliesin')
        api.create_user(fixture)
开发者ID:samueljackson92,项目名称:CSAlumni-client,代码行数:27,代码来源:api_tests.py

示例5: test_user_can_update_self

    def test_user_can_update_self(self):
        # Mock requests for auth, get user
        mock_auth_response()
        fixture = mock_show_user_response(39)

        # Mock update request to modify the fixture
        def check_payload(request):
            payload = json.loads(request.body)
            nose.tools.assert_equal(1986, payload["grad_year"])
            fixture['grad_year'] = payload["grad_year"]
            return (200, {}, {})

        responses.add_callback(responses.PUT,
                      RequestHandler._build_end_point_uri('/users/update/:id',
                                                    {':id': '39'}),
                      callback=check_payload,
                      content_type='application/json')


        # Get the user and make some changes
        api = CsaAPI("cwl39", 'taliesin')
        user = api.get_user(39)
        user["grad_year"] = 1986
        api.update_user(user)

        # Mock the updated user response
        responses.reset()
        mock_show_user_response(39, body=json.dumps(fixture))

        # Check it matches
        resp = api.get_user(39)
        nose.tools.assert_equal(1986, resp["grad_year"])
开发者ID:samueljackson92,项目名称:CSAlumni-client,代码行数:32,代码来源:api_tests.py

示例6: test_is_implemented

    def test_is_implemented(self):
        lists = load_fixture('lists.yml')['items']
        fixt = lists[1]

        responses.add(responses.GET,
                      pyholster.api.baseurl +
                      '/lists/{}'.format(fixt['address']),
                      status=400,
                      body=json.dumps({'list': fixt}))

        lst = pyholster.MailingList(**fixt)

        assert not lst.is_implemented()
        assert len(responses.calls) is 1

        responses.reset()

        responses.add(responses.GET,
                      pyholster.api.baseurl +
                      '/lists/{}'.format(fixt['address']),
                      status=200,
                      body=json.dumps({'list': fixt}))

        lst = pyholster.MailingList.load(fixt['address'])

        assert isinstance(lst, pyholster.MailingList)
        assert lst.address == fixt['address']
        assert lst.name == fixt['name']
        assert lst.description == fixt['description']
开发者ID:psomhorst,项目名称:pyholster,代码行数:29,代码来源:test_mailing_list.py

示例7: test_parse_response

    def test_parse_response(self):
        class MockResponse(object):
            def __init__(self, json_data, status_code=200):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

        # catch non-json responses
        with self.assertRaises(ProtocolError) as protocol_error:
            responses.add(responses.POST, 'http://mock/xmlrpc', body='not json', content_type='application/json')
            self.server.send_request('my_method', is_notification=False, params=None)

        if sys.version_info > (3, 0):
            self.assertEqual(protocol_error.exception.message,
                             """Cannot deserialize response body: Expecting value: line 1 column 1 (char 0)""")
        else:
            self.assertEqual(protocol_error.exception.message,
                             """Cannot deserialize response body: No JSON object could be decoded""")

        self.assertIsInstance(protocol_error.exception.server_response, requests.Response)
        responses.reset()

        with self.assertRaisesRegex(ProtocolError, 'Response is not a dictionary'):
            self.server.parse_response(MockResponse([]))

        with self.assertRaisesRegex(ProtocolError, 'Response without a result field'):
            self.server.parse_response(MockResponse({}))

        with self.assertRaises(ProtocolError) as protoerror:
            body = {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}
            self.server.parse_response(MockResponse(body))
        self.assertEqual(protoerror.exception.message, '''Error: -32601 Method not found''')
开发者ID:cgzzz,项目名称:jsonrpc-requests,代码行数:34,代码来源:tests.py

示例8: test_idrac_scan_success

def test_idrac_scan_success(mock_args):
    responses.reset()
    responses.add(**MockResponses.idrac_fp)
    responses.add(**MockResponses.idrac_auth)
    reset_handlers()
    se = core.main()
    assert se.found_q.qsize() == 1
开发者ID:ztgrace,项目名称:changeme,代码行数:7,代码来源:http.py

示例9: set_existing_search_response

    def set_existing_search_response(self, name, content, hook_type, response_content=None, dld_url='http://www.someurl.com/'):
        responses.reset()

        responses.add(
            responses.GET,
            'http://www.git-hooks.com/api/v1/hooks/',
            json={
                'count': 1,
                'next': None,
                'prev': None,
                'results': [{
                    'name': name,
                    'current_version': 1,
                    'content': {
                        'checksum': hashlib.sha256(content.encode()).hexdigest(),
                        'hook_type': hook_type,
                        'download_url': dld_url
                    }
                }]
            },
            status=200,
        )

        responses.add(
            responses.GET,
            dld_url,
            body=response_content or content,
            status=200,
        )
开发者ID:wildfish,项目名称:git-hooks,代码行数:29,代码来源:test_cmd.py

示例10: testArgument18

def testArgument18() :
    response = '{"meta":{"code":999,"message":"NOT OK","details":[]},"data":{}}'
    responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=headers, body=response, status=200)
    api = Postmen('KEY', 'REGION', raw=True)
    ret = api.get('labels')
    assert ret == response
    responses.reset()
开发者ID:marekyggdrasil,项目名称:postmen-sdk-python,代码行数:7,代码来源:postmen_test.py

示例11: test_update_with_invalid_mentenanceid

    def test_update_with_invalid_mentenanceid(self):
        def request_callback(request):
            method = json.loads(request.body)['method']
            if method == 'maintenance.get':
                return (200, {}, json.dumps(get_response('22')))
            else:
                return (200, {}, json.dumps(update_response('22')))

        responses.add(
            responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
            body=json.dumps({
                'result': 'authentication_token',
                'id': 1,
                'jsonrpc': '2.0'
            }),
            status=200,
            content_type='application/json'
        )
        m = self._makeOne(
            host='https://example.com',
            user='osamunmun',
            password='foobar')
        maintenance_id = '22'
        responses.reset()
        responses.add_callback(responses.POST, 'https://example.com/zabbix/api_jsonrpc.php',
                     callback=request_callback,
                     content_type='application/json')
        for key in ('maintenanceid', 'name', 'active_since', 'active_till'):
            required_params = {'maintenanceid': maintenance_id,
                               'name': 'test',
                               'active_since': '2004-04-01T12:00+09:00',
                               'active_till': '2014-04-01T12:00+09:00'}
            with self.assertRaises(jsonschema.exceptions.ValidationError):
                required_params.pop(key)
                m.update(required_params)
开发者ID:osamunmun,项目名称:zabbix-api-client,代码行数:35,代码来源:test_maintenance.py

示例12: testIncorrectResponseHeaders

def testIncorrectResponseHeaders():
    response = '{"meta":{"code":200,"message":"OK","details":[]},"data":{"key":"value"}}'
    responses.add(responses.GET, 'https://REGION-api.postmen.com/v3/labels', adding_headers=incorrect, body=response, status=200)
    api = Postmen('KEY', 'REGION')
    ret = api.get('labels')
    assert ret['key'] == 'value'
    responses.reset()
开发者ID:marekyggdrasil,项目名称:postmen-sdk-python,代码行数:7,代码来源:postmen_test.py

示例13: test_we_can_update_a_bug_from_bugzilla

def test_we_can_update_a_bug_from_bugzilla():
    responses.add(
        responses.GET,
        rest_url("bug", 1017315),
        body=json.dumps(example_return),
        status=200,
        content_type="application/json",
        match_querystring=True,
    )
    bugzilla = Bugsy()
    bug = bugzilla.get(1017315)
    import copy

    bug_dict = copy.deepcopy(example_return)
    bug_dict["bugs"][0]["status"] = "REOPENED"
    responses.reset()
    responses.add(
        responses.GET,
        "https://bugzilla.mozilla.org/rest/bug/1017315",
        body=json.dumps(bug_dict),
        status=200,
        content_type="application/json",
    )
    bug.update()
    assert bug.status == "REOPENED"
开发者ID:pkdevboxy,项目名称:version-control-tools,代码行数:25,代码来源:test_bugs.py

示例14: test

    def test():
        responses.reset()
        responses.add(**{
            'method': responses.GET,
            'url': 'http://www.pixiv.net/member_illust.php'
                   '?mode=medium&illust_id=53239740',
            'body': fx_ugoira_body,
            'content_type': 'text/html; charset=utf-8',
            'status': 200,
            'match_querystring': True,
        })
        responses.add(**{
            'method': responses.HEAD,
            'url': 'http://i1.pixiv.net/img-zip-ugoira/img/'
                   '2015/10/27/22/10/14/53239740_ugoira600x600.zip',
            'status': 200,
        })
        responses.add(**{
            'method': responses.GET,
            'url': 'http://i1.pixiv.net/img-zip-ugoira/img/'
                   '2015/10/27/22/10/14/53239740_ugoira600x600.zip',
            'body': fx_ugoira_zip,
            'content_type': 'application/zip',
            'status': 200,
        })

        data, frames = download_zip(53239740)
        file = fx_tmpdir / 'test.gif'
        make_gif(str(file), data, fx_ugoira_frames, 10.0)
        with Image(filename=str(file)) as img:
            assert img.format == 'GIF'
            assert len(img.sequence) == 3
            assert img.sequence[0].delay == 10
            assert img.sequence[1].delay == 20
            assert img.sequence[2].delay == 30
开发者ID:item4,项目名称:ugoira,代码行数:35,代码来源:lib_test.py

示例15: testTearDown

 def testTearDown(self):
     try:
         responses.stop()
     except RuntimeError:
         pass
     finally:
         responses.reset()
开发者ID:propertyshelf,项目名称:ps.plone.mls,代码行数:7,代码来源:testing.py


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