我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用httpretty.POST。
def test_auth_access(self): """ :return: """ body = """ { "access_token": "ACCESS_TOKEN", "expires_in": 1234, "remind_in":"798114", "uid":"12341234" } """ httpretty.register_uri( httpretty.POST, "https://api.weibo.com/oauth2/access_token", body=body, status=200, content_type='text/json' ) response = self.oauth2_client.auth_access("abcde") self.assertDictEqual(response, json.loads(body))
def test_revoke_auth_access(self): """ :return: """ body = '{"result":true}' httpretty.register_uri( httpretty.POST, "https://api.weibo.com/oauth2/revokeoauth2", body=body, status=200, content_type='text/json' ) response = self.oauth2_client.revoke_auth_access(self.access_token) self.assertTrue(response)
def test_refresh_token(self): """ :return: """ body = """ { "access_token": "SlAV32hkKG", "expires_in": 3600 } """ httpretty.register_uri( httpretty.POST, "https://api.weibo.com/oauth2/access_token", body=body, status=200, content_type='text/json' ) response = self.oauth2_client.refresh_token("xxxxxxxx") self.assertTrue(response, json.loads(body))
def test_get_token_info(self): """ :return: """ body = """ { "uid": 1073880650, "appkey": 1352222456, "scope": null, "create_at": 1352267591, "expire_in": 157679471 } """ httpretty.register_uri( httpretty.POST, "https://api.weibo.com/oauth2/get_token_info", body=body, status=200, content_type='text/json' ) response = self.oauth2_client.get_token_info(self.access_token) self.assertDictEqual(response, json.loads(body))
def test_assert_api_error(self): """ :return: """ body = """ { "error": "unsupported_response_type", "error_code": 21329, "error_description": "Unsupport ResponseType." } """ httpretty.register_uri( httpretty.POST, "https://api.weibo.com/oauth2/get_token_info", body=body, status=200, content_type='text/json' ) self.assertRaises(WeiboOauth2Error, self.oauth2_client.get_token_info, "dbdsds")
def test_record_add_document(min_score, connection, project, document): """Verifies adding document records to a project.""" httpretty.register_uri( httpretty.POST, '{}/records/upload/document/{}'.format( matchlight.MATCHLIGHT_API_URL_V2, project.upload_token), body=json.dumps({ 'id': uuid.uuid4().hex, 'name': 'name', 'description': '', 'ctime': time.time(), 'mtime': time.time(), 'metadata': '{}', }), content_type='application/json', status=200) connection.records.add_document( project=project, name=document['name'], description=document['description'], document_path=DOCUMENT_RECORD_PATH, min_score=min_score)
def test_feed_counts(connection, feed, start_time, end_time): """Verifies requesting feed counts.""" expected = { int(time.time()): random.randint(0, 1000), int(time.time()): random.randint(0, 1000), int(time.time()): random.randint(0, 1000), int(time.time()): random.randint(0, 1000), } httpretty.register_uri( httpretty.POST, '{}/feeds/{}'.format( matchlight.MATCHLIGHT_API_URL_V2, feed.name), body=json.dumps(expected), content_type='application/json', status=200) result = connection.feeds.counts(feed, start_time, end_time) assert result == connection.feeds._format_count(expected) result = connection.feeds.counts(feed.name, start_time, end_time) assert result == connection.feeds._format_count(expected)
def test_project_edit(connection, project, project_payload): """Verifies project renaming.""" httpretty.register_uri( httpretty.POST, '{}/project/{}/edit'.format( matchlight.MATCHLIGHT_API_URL_V2, project.upload_token, ), body='{}', status=200) new_name = 'Test Project 1' connection.projects.edit(project, new_name) assert project.name == new_name new_name = 'Test Project 2' httpretty.register_uri( httpretty.GET, '{}/project/{}'.format( matchlight.MATCHLIGHT_API_URL_V2, project.upload_token, ), body=json.dumps(project_payload), content_type='application/json', status=200) project = connection.projects.edit(project.upload_token, new_name) assert project.name == new_name
def test_project_delete(connection, project, project_payload): """Verifies project deletion.""" httpretty.register_uri( httpretty.POST, '{}/project/{}/delete'.format( matchlight.MATCHLIGHT_API_URL_V2, project.upload_token, ), body='{}', status=200) httpretty.register_uri( httpretty.GET, '{}/project/{}'.format( matchlight.MATCHLIGHT_API_URL_V2, project.upload_token, ), body=json.dumps(project_payload), content_type='application/json', status=200) connection.projects.delete(project)
def test_search_with_results(): httpretty.register_uri( httpretty.POST, 'https://pypi.python.org/pypi', body=RESULTS_RESPONSE, content_type='text/xml' ) app = Application() command = app.find('search') command_tester = CommandTester(command) command_tester.execute([ ('command', command.get_name()), ('tokens', ['pendulum']) ]) output = command_tester.get_display() assert '\npendulum (0.6.0)\n Python datetimes made easy.\n' == output
def test_request_timeout(): timeout = 0.1 http_scheme = 'http' host = 'coordinator' port = 8080 url = http_scheme + '://' + host + ':' + str(port) + constants.URL_STATEMENT_PATH def long_call(request, uri, headers): time.sleep(timeout * 2) return (200, headers, "delayed success") httpretty.enable() for method in [httpretty.POST, httpretty.GET]: httpretty.register_uri(method, url, body=long_call) # timeout without retry for request_timeout in [timeout, (timeout, timeout)]: req = PrestoRequest( host=host, port=port, user='test', http_scheme=http_scheme, max_attempts=1, request_timeout=request_timeout, ) with pytest.raises(requests.exceptions.Timeout): req.get(url) with pytest.raises(requests.exceptions.Timeout): req.post('select 1') httpretty.disable() httpretty.reset()
def tfs_server_mock(): for method in (httpretty.GET, httpretty.POST, httpretty.PATCH): httpretty.register_uri(method, re.compile(r"http://tfs.tfs.ru(.*)"), body=request_callback_get, content_type="application/json")
def test_download(self): httpretty.register_uri( httpretty.POST, DropboxAPIClient.DOWNLOAD_URL[1], body=TEST_CHUNK_BODY) self.assertEqual(TEST_CHUNK_BODY, self.client.download(self.chunk))
def test_upload(self): httpretty.register_uri( httpretty.POST, DropboxAPIClient.UPLOAD_URL[1], body='') self.client.upload(self.chunk, TEST_CHUNK_BODY)
def test_delete(self): httpretty.register_uri( httpretty.POST, DropboxAPIClient.DELETE_URL[1], body=TEST_CHUNK_BODY) self.client.delete(self.chunk)
def test_upload(self): # Box requires the file id in the URL, the file_id is assigned by Box, # and therefore is stored in ChunkStorage.attrs. httpretty.register_uri( httpretty.POST, BoxAPIClient.UPLOAD_URL[1].format(file_id='abc123'), body='{"entries": [{"id":1}]}', content_type='application/json') self.client.upload(self.chunk, TEST_CHUNK_BODY)
def test_upload(self): # GDrive requires the file id in the URL, the file_id is assigned by # Google, and therefore is stored in ChunkStorage.attrs. httpretty.register_uri( httpretty.POST, GDriveAPIClient.UPLOAD_URL[1].format(file_id='abc123'), body='{"id":1234}') self.client.upload(self.chunk, TEST_CHUNK_BODY)
def setUp(self): super().setUp() httpretty.register_uri( METHODS.get(self.oauth2_client.USER_PROFILE_URL[0]), self.oauth2_client.USER_PROFILE_URL[1], body=json.dumps(USER_PROFILE_BOX), content_type='application/json') httpretty.register_uri(httpretty.POST, self.oauth2_client.CREATE_URL, body=json.dumps(CREATE_BOX), content_type='application/json')
def setUp(self): httpretty.enable() httpretty.register_uri( httpretty.POST, self.oauth2_client.ACCESS_TOKEN_URL, body=json.dumps(ACCESS_TOKEN), content_type='application/json')
def test_project_add(connection, project_name, project_payload, project_type, upload_token): """Verifies project creation.""" httpretty.register_uri( httpretty.POST, '{}/project/add'.format( matchlight.MATCHLIGHT_API_URL_V2), body=json.dumps({'data': project_payload}), content_type='application/json', status=200) project = connection.projects.add(project_name, project_type) assert project.upload_token == upload_token
def test_create(self): """Method defined to test plan creation.""" httpretty.register_uri( httpretty.POST, "https://api.paystack.co/plan", content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) response = Plan.create( name="John Doe", description="Payment plan for awesome people contributions", amount=50000, interval="daily", send_invoices=True, ) self.assertTrue(response['status'])
def test_post_method_called(self): httpretty.register_uri( httpretty.POST, "https://api.paystack.co/transaction/charge_token", content_type='text/json', body='{"status": true, "contributors": null}', status=302, ) req = PayStackRequests() response = req.post('transaction/charge_token', data={'track': 'requests'}) self.assertTrue(response['status'])
def test_charge(self): httpretty.register_uri( httpretty.POST, "https://api.paystack.co/transaction/charge_authorization", content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) response = Transaction.charge( reference='getupall', authorization_code='authorization_code', email='email', amount='amount') self.assertTrue(response['status'])
def step_impl(context): d = context.bad_login assert d['source']['username'] != 'ValidUser' httpretty.enable() httpretty.register_uri( httpretty.POST, context.good_build_url, body='{"errors":[{"context":null,"message":"Authentication failed. Please check your credentials and try again.","exceptionName":"com.atlassian.bitbucket.auth.IncorrectPasswordAuthenticationException"}]}', status=401 ) from scripts.bitbucket import post_result, err result = post_result(context.good_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True) assert result.status_code == 401 httpretty.disable() httpretty.reset()
def step_impl(context): d = context.good_login assert context.good_login['source']['username'] == 'ValidUser' httpretty.enable() httpretty.register_uri( httpretty.POST, context.bad_build_url, body='{"errors":[{"context":null,"message":"You are not permitted to access this resource","exceptionName":"com.atlassian.bitbucket.AuthorisationException"}]}', status=403 ) from scripts.bitbucket import post_result, err result = post_result(context.bad_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True) assert result.status_code == 403 httpretty.disable() httpretty.reset()
def step_impl(context): d = context.good_login assert context.good_login['source']['username'] == 'ValidUser' assert 'somethingicantaccess' not in context.good_build_url httpretty.enable() httpretty.register_uri( httpretty.POST, context.good_build_url, status=204 ) from scripts.bitbucket import post_result, err result = post_result(context.good_build_url, d['source']['username'], d['source']['password'], False, good_status_dict(), True) assert result.status_code == 204 context.goodresult = result
def given_that_there_is_no_default_acl(self): self.start_mocking_http() self.fake_response('/streams/$settings', status=404) self.expect_call('/streams/$settings', httpretty.POST)
def given_a_default_acl(self): self.start_mocking_http() self.fake_response('/streams/$settings', file='settings-stream.js') self.fake_response('/streams/$settings/6', file='settings.json') self.expect_call('/streams/$settings', httpretty.POST)
def given_a_client(self): self.start_mocking_http() self.expect_call('/streams/my-stream/metadata', httpretty.POST)
def given_an_existing_stream_with_no_metadata(self): self.start_mocking_http() self.fake_response('/streams/my-stream/metadata', status=200, body='{}') self.expect_call('/streams/my-stream/metadata', httpretty.POST)
def given_a_stream_with_an_acl(self): self.start_mocking_http() self.expect_call('/streams/my-stream/metadata', httpretty.POST) self.fake_response('/streams/my-stream/metadata', status=200, body = """ { "$acl" : { "$w" : "greg", "$r" : ["greg", "john"], "$d" : "$admins", "$mw" : "$admins", "$mr" : "$admins" } }""")
def given_the_absence_of_a_stream(self): self.start_mocking_http() self.expect_call('/streams/my-stream/metadata', httpretty.POST) self.fake_response('/streams/missing-stream/metadata', status=404)