本文整理汇总了Python中tastypie.test.TestApiClient.patch方法的典型用法代码示例。如果您正苦于以下问题:Python TestApiClient.patch方法的具体用法?Python TestApiClient.patch怎么用?Python TestApiClient.patch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tastypie.test.TestApiClient
的用法示例。
在下文中一共展示了TestApiClient.patch方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: JobTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
class JobTest(ResourceTestCase):
def setUp(self):
super(JobTest, self).setUp()
self.client = TestApiClient()
self.endpoint = '/api/v1/jobs/'
self.format = 'json'
# Create one user
self.user = User(username="testuser")
self.user.save()
# Create on token
self.token = UserToken(user=self.user)
self.token.save()
# create a job
self.job = Job(user=self.user, application=Application.objects.all()[0])
self.job.save()
def test_get_job_list(self):
url = "%s?token=%s" % (self.endpoint, self.token.token)
request = self.client.get(url, self.format)
self.assertValidJSONResponse(request)
def test_get_job_detail(self):
url = "%s%d/?token=%s" % (self.endpoint, self.job.id, self.token.token)
request = self.client.get(url, self.format)
self.assertValidJSONResponse(request)
def test_post_job(self):
data = {"application" : "/api/v1/apps/1/"}
url = "%s?token=%s" % (self.endpoint, self.token.token)
self.assertHttpCreated(self.client.post(url, self.format, data=data))
def test_patch_job(self):
job = Job(user=self.user, application=Application.objects.all()[0])
job.save()
data = {"progress":"50"}
url = "%s%d/?token=%s" % (self.endpoint, job.id, self.token.token)
resp = self.client.patch(url, self.format, data=data)
self.assertHttpAccepted(resp)
def test_delete_job(self):
job = Job(user=self.user, application=Application.objects.all()[0])
job.save()
url = "%s%d/?token=%s" % (self.endpoint, job.id, self.token.token)
self.assertHttpAccepted(self.client.delete(url, self.format))
示例2: EncounterParticipantResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
class EncounterParticipantResourceTest(ResourceTestCase):
fixtures = ['testing_users.json', 'testing_data.json']
def setUp(self):
super(EncounterParticipantResourceTest, self).setUp()
self.api_client = TestApiClient()
self.username = 'SuperUser'
self.password = 'FakePass'
self.user = User.objects.create_superuser(self.username, '[email protected]', self.password)
self.encounter_participant = EncounterParticipant.objects.get(id=1)
def get_credentials(self):
return self.api_client.client.login(username=self.username,
password=self.password)
def test_pc_initiative_save_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.patch('/dm/api/v1/encounter_participant/1/',
format='json', data={'initiative': 5}))
def test_pc_initiative_save(self):
"""
Should save initiative for PC
"""
resp = self.api_client.patch('/dm/api/v1/encounter_participant/1/',
authorization=self.get_credentials(),
format='json', data={'initiative': 5})
self.assertHttpAccepted(resp)
resp = self.api_client.get('/dm/api/v1/encounter_participant/1/',
format='json',
authentication=self.get_credentials())
self.assertEqual(self.deserialize(resp)['initiative'], 5)
示例3: mock_request
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
def mock_request(obj, method, url, **kwargs):
client = TestApiClient()
authentication = 'Basic %s' % base64.b64encode(':'.join([
get_setting('SUPERUSER_USERNAME', None),
get_setting('SUPERUSER_PASSWORD', None),
]))
if method == 'GET':
data = kwargs.get('params', {})
djresponse = client.get(url, data=data, authentication=authentication)
elif method == 'POST':
data = json.loads(kwargs.get('data', '{}'))
djresponse = client.post(url, data=data, authentication=authentication)
elif method == 'PUT':
data = json.loads(kwargs.get('data', '{}'))
djresponse = client.put(url, data=data, authentication=authentication)
elif method == 'PATCH':
data = json.loads(kwargs.get('data', '{}'))
djresponse = client.patch(url, data=data, authentication=authentication)
elif method == 'DELETE':
data = kwargs.get('params', {})
djresponse = client.delete(url, data=data, authentication=authentication)
# convert django.http.HttpResponse to requests.models.Response
response = requests.models.Response()
response.status_code = djresponse.status_code
response.headers = {}
try:
response.headers['content-type'] = djresponse['content-type']
response.headers['location'] = djresponse['location']
except:
pass
response.encoding = requests.utils.get_encoding_from_headers(response.headers)
response._content = djresponse.content
return response
示例4: ApiResourceTestCase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
#.........这里部分代码省略.........
count = self.resource._meta.queryset.count()
resp = self.api_client.post(url, data=kwargs['data'], **req_kwargs)
self.assertEqual(resp.status_code, expected_status_code or self.rejected_status_code)
self.assertEqual(self.resource._meta.queryset.count(), count)
return resp
def successful_put(self, url, **kwargs):
req_kwargs = self.get_req_kwargs(kwargs)
if kwargs.get('data', None):
req_kwargs['data'] = kwargs['data']
count = self.resource._meta.queryset.count()
resp = self.api_client.put(url, **req_kwargs)
self.assertHttpAccepted(resp)
# Make sure the count hasn't changed
self.assertEqual(self.resource._meta.queryset.count(), count)
def rejected_put(self, url, expected_status_code=None, **kwargs):
req_kwargs = self.get_req_kwargs(kwargs)
if kwargs.get('data', None):
req_kwargs['data'] = kwargs['data']
count = self.resource._meta.queryset.count()
resp = self.api_client.put(url, **req_kwargs)
self.assertEqual(resp.status_code, expected_status_code or self.rejected_status_code)
# Make sure the count hasn't changed
self.assertEqual(self.resource._meta.queryset.count(), count)
def successful_patch(self, url, check_results=True, **kwargs):
req_kwargs = self.get_req_kwargs(kwargs)
if check_results:
# Fetch the existing data for comparison.
resp = self.api_client.get(url, **req_kwargs)
self.assertHttpOK(resp)
self.assertValidJSONResponse(resp)
old_data = self.deserialize(resp)
new_data = dict(old_data, **kwargs['data'])
else:
new_data = kwargs['data']
count = self.resource._meta.queryset.count()
patch_resp = self.api_client.patch(url, data=new_data, **req_kwargs)
self.assertHttpAccepted(patch_resp)
# Make sure the count hasn't changed & we did an update.
self.assertEqual(self.resource._meta.queryset.count(), count)
if check_results:
fresh_data = self.deserialize(self.api_client.get(url, **req_kwargs))
for attr in kwargs['data'].keys():
try:
# Make sure the data actually changed
self.assertNotEqual(fresh_data[attr], old_data[attr])
# Make sure the data changed to what we specified
self.assertEqual(fresh_data[attr], new_data[attr])
except AssertionError:
# If we specified a nested ID, we'll be getting back an object
if str(new_data[attr]).isdigit() and isinstance(fresh_data[attr], dict):
示例5: AnswerCreationResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
class AnswerCreationResource(ResourceTestCase):
def setUp(self):
super(AnswerCreationResource, self).setUp()
call_command('loaddata', 'example_data', verbosity=0)
self.outbound_message = OutboundMessage.objects.all()[0]
self.identifier = OutboundMessageIdentifier.objects.get(outbound_message=self.outbound_message)
self.api_client = TestApiClient()
self.user = User.objects.all()[0]
self.data = {'format': 'json', 'username': self.user.username, 'api_key':self.user.api_key.key}
def get_credentials(self):
credentials = self.create_apikey(username=self.user.username, api_key=self.user.api_key.key)
return credentials
def test_I_can_create_an_answer_with_only_an_identifier_and_a_content(self):
url = '/api/v1/create_answer/'
content = 'Fiera tiene una pulga'
answer_data = {
'key':self.identifier.key,
'content':content
}
previous_answers = Answer.objects.count()
response = self.api_client.post(url, data = answer_data, format='json', authentication=self.get_credentials())
self.assertHttpCreated(response)
answers_count = Answer.objects.count()
self.assertEquals(answers_count, previous_answers + 1)
def test_authorization_using_api_key(self):
url = '/api/v1/create_answer/'
content = 'una sola'
answer_data = {
'key':self.identifier.key,
'content':content
}
response = self.api_client.post(url, data = answer_data, format='json')
self.assertHttpUnauthorized(response)
def test_only_the_owner_can_create_an_answer(self):
not_the_owner = User.objects.create(username='not_the_owner')
his_api_key = not_the_owner.api_key
credentials = self.create_apikey(username=not_the_owner.username, api_key=his_api_key.key)
url = '/api/v1/create_answer/'
content = 'una sola'
answer_data = {
'key':self.identifier.key,
'content':content
}
response = self.api_client.post(url, data = answer_data, format='json', authentication=credentials)
self.assertHttpUnauthorized(response)
def test_only_post_endpoint(self):
url = '/api/v1/create_answer/'
content = 'una sola'
answer_data = {
'key':self.identifier.key,
'content':content
}
response = self.api_client.get(url)
self.assertHttpMethodNotAllowed(response)
response = self.api_client.put(url, data = answer_data)
self.assertHttpMethodNotAllowed(response)
response = self.api_client.patch(url, data = answer_data)
self.assertHttpMethodNotAllowed(response)
示例6: test_2api_init
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
def test_2api_init(self):
print '***================ super: db test_2api_init =============== '
super(TestApiInit, self).test_2api_init()
print '***================ local: db test_2api_init =============== '
serializer=CSVSerializer()
# todo: doesn't work for post, see TestApiClient.post() method, it is
# incorrectly "serializing" the data before posting
testApiClient = TestApiClient(serializer=serializer)
filename = os.path.join(self.db_directory,'api_init_actions.csv')
with open(filename) as input_file:
api_init_actions = serializer.from_csv(input_file.read(), root=None)
bootstrap_files = [
'metahash_resource_data.csv',
'vocabularies_data.csv']
for action in api_init_actions:
print '\n++++=========== processing action', json.dumps(action)
command = action['command'].lower()
resource = action['resource'].lower()
resource_uri = BASE_REPORTS_URI + '/' + resource
if command == 'delete':
resp = testApiClient.delete(
resource_uri, authentication=self.get_credentials())
self.assertHttpAccepted(resp)
else:
filename = os.path.join(self.db_directory,action['file'])
search_excludes = []
# exclude 'resource_uri' from equivalency check during
# bootstrap, because resource table needs to be loaded for
# the uri generation
if action['file'] in bootstrap_files:
search_excludes = ['resource_uri']
logger.info(str(('+++++++++++processing file', filename)))
with open(filename) as data_file:
input_data = serializer.from_csv(data_file.read())
if command == 'put':
resp = testApiClient.put(
resource_uri, format='csv', data=input_data,
authentication=self.get_credentials() )
logger.debug(str(('action: ', json.dumps(action),
'response: ' , resp.status_code)))
self.assertTrue(
resp.status_code in [200], str((resp.status_code, resp)))
# now see if we can get these objects back
resp = testApiClient.get(
resource_uri, format='json',
authentication=self.get_credentials(), data={ 'limit': 999 })
self.assertTrue(
resp.status_code in [200], str((resp.status_code, resp)))
# self.assertValidJSONResponse(resp)
new_obj = self.deserialize(resp)
result, msgs = find_all_obj_in_list(
input_data['objects'], new_obj['objects'],
excludes=search_excludes)
self.assertTrue(
result, str((command, 'input file', filename,
msgs, new_obj['objects'])) )
elif command == 'patch':
resp = testApiClient.patch(
resource_uri, format='csv', data=input_data,
authentication=self.get_credentials() )
# self.assertHttpAccepted(resp)
self.assertTrue(resp.status_code in [202, 204], str((
'response not accepted, resource_uri:', resource_uri,
'response', resp)))
resp = testApiClient.get(
resource_uri, format='json',
authentication=self.get_credentials(), data={ 'limit': 999 } )
self.assertTrue(
resp.status_code in [200], str((resp.status_code, resp)))
# self.assertValidJSONResponse(resp)
new_obj = self.deserialize(resp)
with open(filename) as f2:
input_data2 = serializer.from_csv(f2.read())
result, msgs = find_all_obj_in_list(
input_data2['objects'], new_obj['objects'],
excludes=search_excludes)
self.assertTrue(
result, str(( command, 'input file', filename, msgs )) )
elif command == 'post':
self.fail((
'resource entry: ' + json.dumps(action) + '; '
'cannot POST multiple objects to tastypie; '
'therefore the "post" command is invalid with '
'the initialization scripts'))
else:
self.fail('unknown command: ' + command + ', ' + json.dumps(action))
示例7: PilotJobResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import patch [as 别名]
class PilotJobResourceTest(ResourceTestCase):
fixtures = ['local_site.json']
def setUp(self):
super(PilotJobResourceTest, self).setUp()
self.client = TestApiClient()
self.endpoint = '/api/v1/dispatcher/'
self.format = 'json'
# Create one user
self.user = User(username="testuser")
self.user.save()
# create a job
self.job = Job(user=self.user, application=Application.objects.all()[0])
self.job.maxtime = 30
self.job.save()
self.site = Site.objects.get(pk=1)
self.pilot = self.site.submit_pilot_based_on_job(self.job)
def test_submit_pilot(self):
pilot = self.site.submit_pilot_based_on_job(self.job)
self.assertEqual(type(pilot), type(Pilot()))
def test_pilot_post_job(self):
self.job.status='P'
self.job.save()
data = {"time_left": 60}
token = self.pilot.token
url = "%s?token=%s" % (self.endpoint, token)
request = self.client.post(url, self.format, data=data)
self.assertHttpCreated(request)
def test_pilot_get_job(self):
self.job.status='R'
self.job.pilot = self.pilot
self.job.save()
token = self.pilot.token
url = "%s%d/?token=%s" % (self.endpoint, self.job.id, token)
request = self.client.get(url, self.format)
self.assertValidJSONResponse(request)
def test_wrong_token(self):
url = "%s%d/?token=%s" % (self.endpoint, self.job.id, "not-a-valid-token")
request = self.client.get(url, self.format)
self.assertHttpUnauthorized(request)
def test_no_token(self):
url = "%s%d/" % (self.endpoint, self.job.id)
request = self.client.get(url, self.format)
self.assertHttpUnauthorized(request)
def test_pilot_patch_job(self):
self.job.status='R'
self.job.pilot = self.pilot
self.job.save()
data = {"progress": 50}
token = self.pilot.token
url = "%s%d/?token=%s" % (self.endpoint, self.job.id, token)
request = self.client.patch(url, self.format, data=data)
self.assertHttpAccepted(request)