本文整理汇总了Python中tastypie.test.TestApiClient.post方法的典型用法代码示例。如果您正苦于以下问题:Python TestApiClient.post方法的具体用法?Python TestApiClient.post怎么用?Python TestApiClient.post使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tastypie.test.TestApiClient
的用法示例。
在下文中一共展示了TestApiClient.post方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HandleBounces
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class HandleBounces(ResourceTestCase):
def setUp(self):
super(HandleBounces, self).setUp()
call_command('loaddata', 'example_data', verbosity=0)
self.api_client = TestApiClient()
self.user = User.objects.all()[0]
self.outbound_message = OutboundMessage.objects.all()[0]
self.identifier = OutboundMessageIdentifier.objects.get(outbound_message=self.outbound_message)
def get_credentials(self):
credentials = self.create_apikey(username=self.user.username, api_key=self.user.api_key.key)
return credentials
def test_handle_bounces_endpoint(self):
url = '/api/v1/handle_bounce/'
bounce_data = {
'key':self.identifier.key
}
resp = self.api_client.post(url, data=bounce_data, authentication=self.get_credentials())
self.assertHttpCreated(resp)
def test_handle_bounces_sets_the_contact_to_bounced(self):
url = '/api/v1/handle_bounce/'
bounce_data = {
'key':self.identifier.key
}
resp = self.api_client.post(url, data=bounce_data, authentication=self.get_credentials())
self.assertTrue(self.outbound_message.contact.is_bounced)
示例2: CreateOrListGroupsTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class CreateOrListGroupsTest(ResourceTestCase):
serializer = Serializer()
def setUp(self):
self.api_client = TestApiClient()
self.user = hydroshare.create_account(
'[email protected]',
username='user0',
first_name='User0_FirstName',
last_name='User0_LastName',
superuser=True,
password='foobar'
)
g0=hydroshare.create_group(name="group0")
g1=hydroshare.create_group(name="group1")
g2=hydroshare.create_group(name="group2")
self.user.groups.add(g0,g1,g2)
self.g_ids=[g0.id,g1.id,g2.id]
self.groups_url_base = '/hsapi/groups/'
self.api_client.client.login(username=self.user.username, password=self.user.password)
def tearDown(self):
Group.objects.all().delete()
User.objects.all().delete()
def test_create_group(self):
post_data = {'name': 'newgroup'}
resp = self.api_client.post(self.groups_url_base, data=post_data)
self.assertHttpCreated(resp)
grouplist = Group.objects.all()
num_of_groups=len(grouplist)
self.assertTrue(any(Group.objects.filter(name='newgroup')))
self.assertEqual(num_of_groups, 4)
def test_list_groups(self):
query = self.serialize({'user': self.user.id})
get_data = {'query': query}
resp = self.api_client.get(self.groups_url_base, data=get_data)
print resp
self.assertEqual(resp.status_code, 200)
groups = self.deserialize(resp)
new_ids = []
for num in range(len(groups)):
new_ids.append(groups[num]['id'])
self.assertTrue(Group.objects.filter(user='user{0}'.format(num)).exists())
self.assertEqual(str(groups[num]['name']), 'group{0}'.format(num))c
self.assertEqual(sorted(self.g_ids), sorted(new_ids))
示例3: JobTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [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))
示例4: mock_request
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [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
示例5: RunTriggersTestCase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class RunTriggersTestCase(BaseProcessorTestCase, PreparedData):
def setUp(self):
super(RunTriggersTestCase, self).setUp()
self.api_client = TestApiClient()
self.d = self.run_processor('test:triggers:create-file')
t = Trigger()
t.name = 'test.trigger'
t.type = 'data:test:triggers:create:'
t.author_id = str(self.admin.pk)
t.trigger_input = 'in_file'
t.input = {'in_file': 'INPUT'}
t.processor_name = 'test:triggers:check-file'
t.case_id = str(self.case2.id)
t.autorun = True
t.save()
@override_settings(TESTING=False)
def test_copy_before_triggers(self):
login_user(self.api_client, self.admin)
resp = self.api_client.post(
'/api/v1/data/{}/copy/'.format(self.d.id),
format='json',
data={'case_ids': [self.case2.id]})
self.assertEqual(resp.status_code, 201) # pylint: disable=no-member
all_objs = Data.objects.filter(case_ids__contains=str(self.case2.pk))
error_objs = Data.objects.filter(case_ids__contains=str(self.case2.pk),
status=Data.STATUS_ERROR)
# done_objs = Data.objects.filter(case_ids__contains=str(self.case2.pk),
# status=Data.STATUS_DONE)
self.assertEqual(len(all_objs), 2)
self.assertEqual(len(error_objs), 0)
示例6: handle
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
def handle(self, *args, **options):
logger.info(u'Старт')
api_client = TestApiClient()
test_email = '[email protected]'
User.objects.filter(email=test_email).delete()
user = User.objects.create(email=test_email, first_name=u'Тест', patronymic='Тестович')
api_key = 'ApiKey {}:{}'.format(user.email, user.api_key.key)
logger.info(u'Создал пользователя')
Card.objects.create(user=user, article='777')
logger.info(u'Привязал карту')
data = {'user': '/api/v1/users/{}/'.format(user.id)}
api_client.post('/api/v1/reserve/', data=data, authentication=api_key)
reserve = Reserve.objects.get(user=user)
logger.info(u'Создал Бронь № {}'.format(reserve.id))
ea1 = EA.objects.filter(count_in__gte=2).first()
data = {
'reserve': '/api/v1/reserve/{}/'.format(reserve.id),
'ea': '/api/v1/ea/{}/'.format(ea1.id),
'count': 2
}
api_client.post('/api/v1/reserve_item/', data=data, authentication=api_key)
ea2 = EA.objects.filter(count_in__gte=1).exclude(id=ea1.id).first()
data = {
'reserve': '/api/v1/reserve/{}/'.format(reserve.id),
'ea': '/api/v1/ea/{}/'.format(ea2.id),
'count': 1
}
api_client.post('/api/v1/reserve_item/', data=data, authentication=api_key)
logger.info(u'Добавил в бронь 3 вещи')
logger.info(u'Конец')
示例7: InstanceResourceTestCase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class InstanceResourceTestCase(ResourceTestCase):
def setUp(self):
super(InstanceResourceTestCase, self).setUp()
call_command('loaddata', 'example_data', verbosity=0)
self.user = User.objects.get(id=1)
self.writeitinstance = WriteItInstance.objects.create(name=u"a test", slug=u"a-test", owner=self.user)
self.api_client = TestApiClient()
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_api_exists(self):
url = '/api/v1/'
resp = self.api_client.get(url, data=self.data)
self.assertValidJSONResponse(resp)
def test_api_needs_authentication(self):
url = '/api/v1/instance/'
response = self.api_client.get(url)
self.assertHttpUnauthorized(response)
def test_get_list_of_instances(self):
url = '/api/v1/instance/'
response = self.api_client.get(url, data=self.data)
self.assertValidJSONResponse(response)
instances = self.deserialize(response)['objects']
self.assertEqual(len(instances), WriteItInstance.objects.count()) # All the instances
first_instance = instances[0]
self.assertEqual(first_instance['messages_uri'], '/api/v1/instance/{0}/messages/'.format(first_instance['id']))
def test_get_detail_of_an_instance(self):
url = '/api/v1/instance/{0}/'.format(self.writeitinstance.id)
response = self.api_client.get(url, data=self.data)
self.assertValidJSONResponse(response)
def test_get_persons_of_an_instance(self):
writeitinstance = WriteItInstance.objects.get(id=1)
url = '/api/v1/instance/{0}/'.format(writeitinstance.id)
response = self.api_client.get(url, data=self.data)
instance = self.deserialize(response)
self.assertIn('persons', instance)
pedro = Person.objects.get(id=1)
self.assertIn(pedro.popit_url, instance['persons'])
def test_create_a_new_instance(self):
instance_data = {
'name': 'The instance',
'slug': 'the-instance',
}
url = '/api/v1/instance/'
response = self.api_client.post(url, data=instance_data, format='json', authentication=self.get_credentials())
self.assertHttpCreated(response)
match_id = re.match(r'^http://testserver/api/v1/instance/(?P<id>\d+)/?', response['Location'])
self.assertIsNotNone(match_id)
instance_id = match_id.group('id')
instance = WriteItInstance.objects.get(id=instance_id)
self.assertValidJSON(force_text(response.content))
instance_as_json = force_text(response.content)
self.assertIn('resource_uri', instance_as_json)
self.assertEquals(instance.name, instance_data['name'])
self.assertEquals(instance.slug, instance_data['slug'])
self.assertEquals(instance.owner, self.user)
@skipUnless(settings.LOCAL_POPIT, "No local popit running")
def test_create_a_new_instance_with_only_name(self):
instance_data = {
'name': 'The instance',
}
url = '/api/v1/instance/'
response = self.api_client.post(url, data=instance_data, format='json', authentication=self.get_credentials())
self.assertHttpCreated(response)
match_id = re.match(r'^http://testserver/api/v1/instance/(?P<id>\d+)/?', response['Location'])
self.assertIsNotNone(match_id)
instance_id = match_id.group('id')
instance = WriteItInstance.objects.get(id=instance_id)
self.assertEquals(instance.name, instance_data['name'])
self.assertEquals(instance.owner, self.user)
self.assertTrue(instance.slug)
def test_does_not_create_a_user_if_not_logged(self):
instance_data = {
'name': 'The instance',
'slug': 'the-instance',
}
url = '/api/v1/instance/'
response = self.api_client.post(url, data=instance_data, format='json')
self.assertHttpUnauthorized(response)
@skipUnless(settings.LOCAL_POPIT, "No local popit running")
def test_create_and_pull_people_from_a_popit_api(self):
#.........这里部分代码省略.........
示例8: MessageResourceTestCase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
#.........这里部分代码省略.........
self.assertTrue('answers' in messages[0])
def test_the_message_has_the_people_it_was_sent_to(self):
url = '/api/v1/message/'
response = self.api_client.get(url, data=self.data)
self.assertValidJSONResponse(response)
messages = self.deserialize(response)['objects']
self.assertTrue('persons' in messages[0])
message_from_the_api = messages[0]
message = Message.objects.get(id=messages[0]['id'])
for person in message_from_the_api['people']:
self.assertIn('popit_url', person)
self.assertIn(
Person.objects.get(id=person['id']),
message.people.all(),
)
self.assertEquals(len(message_from_the_api['people']), message.people.count())
def test_create_a_new_message(self):
writeitinstance = WriteItInstance.objects.get(id=1)
message_data = {
'author_name': 'Felipipoo',
'subject': 'new message',
'content': 'the content thing',
'writeitinstance': '/api/v1/instance/{0}/'.format(writeitinstance.id),
'persons': [writeitinstance.persons.all()[0].popit_url],
}
url = '/api/v1/message/'
previous_amount_of_messages = Message.objects.count()
response = self.api_client.post(url, data=message_data, format='json', authentication=self.get_credentials())
self.assertHttpCreated(response)
self.assertValidJSON(force_text(response.content))
message_as_json = force_text(response.content)
self.assertIn('resource_uri', message_as_json)
post_amount_of_messages = Message.objects.count()
self.assertEquals(post_amount_of_messages, previous_amount_of_messages + 1)
the_message = Message.objects.get(author_name='Felipipoo')
outbound_messages = the_message.outboundmessage_set.all()
self.assertTrue(outbound_messages.count() > 0)
for outbound_message in outbound_messages:
self.assertEquals(outbound_message.status, 'ready')
def test_create_a_new_message_in_not_my_instance(self):
not_me = User.objects.create_user(username='not_me', password='not_my_password')
writeitinstance = WriteItInstance.objects.create(name=u"a test", slug=u"a-test", owner=not_me)
person1 = Person.objects.get(id=1)
writeitinstance.add_person(person1)
message_data = {
'author_name': 'Felipipoo',
'subject': 'new message',
'content': 'the content thing',
'writeitinstance': '/api/v1/instance/{0}/'.format(writeitinstance.id),
'persons': [person1.popit_url],
}
url = '/api/v1/message/'
response = self.api_client.post(url, data=message_data, format='json', authentication=self.get_credentials())
self.assertHttpUnauthorized(response)
示例9: CommentResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class CommentResourceTest(ResourceTestCase):
fixtures = ['group.json', 'group_permission.json',
'user_group.json', 'user.json',
'user_project.json', 'project_part.json',
'project.json', 'profile.json',
'post.json', 'comment.json']
def setUp(self):
self.api_client = TestApiClient()
self.post_id = 1
self.post_data = {'post': {'pk': self.post_id,
'text': 'New comment'}}
self.detail_url = '/api/v1/comment/{0}/'.format(self.post_id)
self.list_url = '/api/v1/comment/'
self.serializer = Serializer()
def get_credentials(self):
result = self.api_client.client.login(email='[email protected]',
password='django')
# def test_post_list(self):
# self.get_credentials()
# self.assertIn('_auth_user_id', self.api_client.client.session)
# self.assertEqual(self.api_client.client.session['_auth_user_id'], 1)
# self.assertEqual(Comment.objects.count(), 1)
# self.assertHttpCreated(self.api_client.post(self.list_url,
# format='json',
# data=self.post_data))
# self.assertEqual(Comment.objects.count(), 2)
def test_get_list_unauthorized(self):
self.assertHttpUnauthorized(self.api_client.get(self.list_url,
format='json'))
def test_get_list(self):
self.get_credentials()
resp = self.api_client.get(self.list_url,
format='json')
self.assertValidJSONResponse(resp)
self.assertEqual(len(json.loads(resp.content)['objects']), 1)
def test_get_detail_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.get(self.detail_url, format='json'))
# def test_get_detail(self):
# self.get_credentials()
# resp = self.api_client.get(self.detail_url, format='json')
# self.assertValidJSONResponse(resp)
# self.assertEqual(json.loads(resp.content)['comment'], '')
def test_post_list_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.post(self.list_url, format='json',
data=self.post_data))
def test_put_detail_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.put(self.detail_url, format='json', data={}))
def test_put_detail(self):
self.get_credentials()
resp = self.api_client.get(self.detail_url, format='json')
original_data = json.loads(resp.content)
new_data = original_data.copy()
new_data['title'] = 'Updated: First Comment'
self.assertEqual(Comment.objects.count(), 1)
self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))
self.assertEqual(Comment.objects.count(), 1)
def test_delete_detail_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.delete(self.detail_url, format='json'))
def test_delete_detail(self):
self.get_credentials()
self.assertEqual(Comment.objects.count(), 1)
resp = self.api_client.delete(self.detail_url, format='json')
self.assertHttpAccepted(resp)
self.assertEqual(Comment.objects.count(), 0)
示例10: TestCampaignResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class TestCampaignResource(ResourceTestCase):
def setUp(self):
# Tastypie stuff
super(TestCampaignResource, self).setUp()
self.bob_api_client = TestApiClient()
self.bill_api_client = TestApiClient()
self.anon_api_client = TestApiClient()
# Create a user bob.
self.user_bob_username = "bob"
self.user_bob_password = "bob"
self.user_bob = User.objects.create_user(self.user_bob_username, "[email protected]", self.user_bob_password)
# Create a user bob.
self.user_bill_username = "bill"
self.user_bill_password = "bill"
self.user_bill = User.objects.create_user(
self.user_bill_username, "[email protected]", self.user_bill_password
)
self.bob_api_client.client.login(username="bob", password="bob")
self.bill_api_client.client.login(username="bill", password="bill")
# assign users to the Public group
public_group, created = Group.objects.get_or_create(name="Public")
self.user_bob.groups.add(public_group)
self.user_bill.groups.add(public_group)
guardian.utils.get_anonymous_user().groups.add(public_group)
# make a couple of campaigns and save
self.campaign_bobs = mommy.make_one("catamidb.Campaign")
self.campaign_bills = mommy.make_one("catamidb.Campaign")
# assign this one to bob
authorization.apply_campaign_permissions(self.user_bob, self.campaign_bobs)
# assign this one to bill
authorization.apply_campaign_permissions(self.user_bill, self.campaign_bills)
# the API url for campaigns
self.campaign_url = "/api/dev/campaign/"
# some post data for testing campaign creation
self.post_data = {
"short_name": "Blah",
"description": "Blah",
"associated_researchers": "Blah",
"associated_publications": "Blah",
"associated_research_grant": "Blah",
"date_start": "2012-05-01",
"date_end": "2012-05-01",
"contact_person": "Blah",
}
# can only do GET at this stage
def test_campaign_operations_disabled(self):
# test that we are unauthorized to create
self.assertHttpUnauthorized(self.anon_api_client.post(self.campaign_url, format="json", data=self.post_data))
# test that we can NOT modify
self.assertHttpMethodNotAllowed(
self.anon_api_client.put(self.campaign_url + self.campaign_bobs.id.__str__() + "/", format="json", data={})
)
# test that we can NOT delete
self.assertHttpMethodNotAllowed(
self.anon_api_client.delete(self.campaign_url + self.campaign_bobs.id.__str__() + "/", format="json")
)
# test that we can NOT modify authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.put(self.campaign_url + self.campaign_bobs.id.__str__() + "/", format="json", data={})
)
# test that we can NOT delete authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.delete(self.campaign_url + self.campaign_bobs.id.__str__() + "/", format="json")
)
# test can get a list of campaigns authorised
def test_campaigns_operations_as_authorised_users(self):
# create a campaign that only bill can see
bills_campaign = mommy.make_one("catamidb.Campaign")
assign("view_campaign", self.user_bill, bills_campaign)
# check that bill can see via the API
response = self.bill_api_client.get(self.campaign_url, format="json")
self.assertValidJSONResponse(response)
self.assertEqual(len(self.deserialize(response)["objects"]), 3)
# check that bill can get to the object itself
response = self.bill_api_client.get(self.campaign_url + bills_campaign.id.__str__() + "/", format="json")
self.assertValidJSONResponse(response)
# check that bob can not see - now we know tastypie API has correct
# permission validation
response = self.bob_api_client.get(self.campaign_url, format="json")
self.assertValidJSONResponse(response)
#.........这里部分代码省略.........
示例11: HelpResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class HelpResourceTest(ResourceTestCase):
def setUp(self):
super(HelpResourceTest, self).setUp()
# TODO: If we end up supporting the PATCH method, use our
# FixedTestApiClient instead of the default
self.api_client = TestApiClient()
self.username = "test"
self.password = "test"
self.user = User.objects.create_user(self.username, "[email protected]", self.password)
def test_get_detail(self):
help = create_help(title="Test Help Item", body="Test Help Item body")
uri = "/api/0.1/help/%s/" % (help.help_id)
resp = self.api_client.get(uri)
self.assertValidJSONResponse(resp)
self.assertEqual(self.deserialize(resp)["title"], "Test Help Item")
self.assertEqual(self.deserialize(resp)["body"], "Test Help Item body")
def test_get_detail_by_slug(self):
help = create_help(title="Test Help Item", body="Test Help Item body", slug="test")
uri = "/api/0.1/help/%s/" % (help.slug)
resp = self.api_client.get(uri)
self.assertValidJSONResponse(resp)
self.assertEqual(self.deserialize(resp)["title"], "Test Help Item")
self.assertEqual(self.deserialize(resp)["body"], "Test Help Item body")
def test_get_list_for_section(self):
section_help = create_help(title="Test section help item", body="Test section help item body")
nonsection_help = create_help(
title="Test non-section help item", body="Test non-section help item body", slug="test-nonsection"
)
story = create_story(
title="Test Story", summary="Test Summary", byline="Test Byline", status="published", language="en"
)
section = create_section(title="Test Section 1", story=story, help=section_help)
uri = "/api/0.1/help/sections/%s/" % (section.section_id)
resp = self.api_client.get(uri)
self.assertValidJSONResponse(resp)
self.assertEqual(len(self.deserialize(resp)["objects"]), 1)
self.assertEqual(self.deserialize(resp)["objects"][0]["title"], "Test section help item")
self.assertEqual(self.deserialize(resp)["objects"][0]["body"], "Test section help item body")
def test_post_list_for_section(self):
section_help = create_help(title="Test section help item", body="Test section help item body")
story = create_story(
title="Test Story",
summary="Test Summary",
byline="Test Byline",
status="published",
language="en",
author=self.user,
)
section = create_section(title="Test Section 1", story=story)
self.assertEqual(section.help, None)
post_data = {"help_id": section_help.help_id}
uri = "/api/0.1/help/sections/%s/" % (section.section_id)
self.api_client.client.login(username=self.username, password=self.password)
resp = self.api_client.post(uri, format="json", data=post_data)
self.assertHttpCreated(resp)
updated_section = Section.objects.get(pk=section.pk)
self.assertEqual(updated_section.help, section_help)
def test_post_list_for_section_unauthorized_unauthenticated(self):
"""
Test that anonymous users cannot set the help item for a section
"""
section_help = create_help(title="Test section help item", body="Test section help item body")
story = create_story(
title="Test Story",
summary="Test Summary",
byline="Test Byline",
status="published",
language="en",
author=self.user,
)
section = create_section(title="Test Section 1", story=story)
self.assertEqual(section.help, None)
post_data = {"help_id": section_help.help_id}
uri = "/api/0.1/help/sections/%s/" % (section.section_id)
resp = self.api_client.post(uri, format="json", data=post_data)
self.assertHttpUnauthorized(resp)
def test_post_list_for_section_unauthorized_other_user(self):
"""
Test that a user can't set the help text for another user's section
"""
user2 = User.objects.create(username="test2", email="[email protected]", password="test2")
section_help = create_help(title="Test section help item", body="Test section help item body")
story = create_story(
title="Test Story",
summary="Test Summary",
byline="Test Byline",
status="published",
language="en",
author=user2,
)
section = create_section(title="Test Section 1", story=story)
self.assertEqual(section.help, None)
post_data = {"help_id": section_help.help_id}
#.........这里部分代码省略.........
示例12: CreateOrListAccountsTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class CreateOrListAccountsTest(ResourceTestCase):
serializer = Serializer()
def setUp(self):
self.account_url_base = '/hsapi/accounts/'
self.sudo = hydroshare.create_account('[email protected]','hs','hydro','share',True,password='hs')
self.api_client = TestApiClient()
self.api_client.client.login(username=self.sudo.username, password=self.sudo.password)
def tearDown(self):
User.objects.all().delete()
def test_create_account(self):
username = 'creator'
password = 'password'
post_data_should_fail = CreateOrListAccounts.CreateAccountForm({
'email': '[email protected]',
'username': username,
'first_name': 'shaun',
'last_name': 'livingston',
'password': password,
'superuser': True
})
resp=self.api_client.post(self.account_url_base, data=post_data_should_fail)
self.assertHttpForbidden(resp)
post_data_should_succeed = CreateOrListAccounts.CreateAccountForm({
'email': '[email protected]',
'username': username,
'first_name': 'shaun',
'last_name': 'livingston',
'password': password
})
resp=self.api_client.post(self.account_url_base, data=post_data_should_succeed)
self.assertHttpCreated(resp)
self.assertTrue(User.objects.filter(email='[email protected]').exists())
self.assertTrue(User.objects.filter(username=username).exists())
self.assertTrue(User.objects.filter(first_name='shaun').exists())
self.assertTrue(User.objects.filter(last_name='livingston').exists())
self.assertTrue(User.objects.filter(superuser=True).exists())
def test_list_users(self):
hydroshare.create_account(
'[email protected]',
username='user0',
first_name='User0_FirstName',
last_name='User0_LastName',
)
hydroshare.create_account(
'[email protected]',
username='user1',
first_name='User1_FirstName',
last_name='User1_LastName',
)
hydroshare.create_account(
'[email protected]',
username='user2',
first_name='User2_FirstName',
last_name='User2_LastName',
)
num_of_accounts = len(User.objects.filter(email= '[email protected]'))
query = self.serialize({
'email': '[email protected]',
})
get_data = {'query': query}
resp = self.api_client.get(self.account_url_base, data=get_data)
self.assertEqual(resp.status_code,200)
users = self.deserialize(resp)
self.assertTrue(len(users)==num_of_accounts)
for num in range(num_of_accounts):
self.assertEqual(str(users[num]['email']), '[email protected]')
self.assertEqual(str(users[num]['username']), 'user{0}'.format(num))
self.assertEqual(str(users[num]['first_name']), 'User{0}_FirstName'.format(num))
self.assertEqual(str(users[num]['last_name']), 'User{0}_LastName'.format(num))
示例13: ApiTestCase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class ApiTestCase(ResourceTestCase):
def setUp(self):
super(ApiTestCase, self).setUp()
# Use custom api client
self.api_client = TestApiClient()
# Look for the test user
self.username = u"tester"
self.password = u"tester"
try:
self.user = User.objects.get(username=self.username)
jpp = Organization.objects.get(name=u"Journalism++")
jg = Organization.objects.get(name=u"Journalism Grant")
fra = Country.objects.get(name=u"France")
self.pr = pr = Person.objects.get(name=u"Pierre Roméra")
self.pb = pb = Person.objects.get(name=u"Pierre Bellon")
except ObjectDoesNotExist:
# Create the new user
self.user = User.objects.create_user(self.username, "[email protected]", self.password)
self.user.is_staff = True
self.user.is_superuser = True
self.user.save()
# Create related objects
jpp = Organization(name=u"Journalism++")
jpp.save()
jg = Organization(name=u"Journalism Grant")
jg.save()
fra = Country(name=u"France", isoa3=u"FRA")
fra.save()
self.pr = pr = Person(name=u"Pierre Roméra")
pr.based_in.add(fra)
pr.activity_in_organization.add(jpp)
pr.save()
self.pb = pb = Person(name=u"Pierre Bellon")
pb.based_in.add(fra)
pb.activity_in_organization.add(jpp)
pb.save()
self.post_data_simple = {"name": "Lorem ispum TEST", "twitter_handle": "loremipsum"}
self.post_data_related = {
"name": "Lorem ispum TEST RELATED",
"owner": [{"id": jpp.id}, {"id": jg.id}],
"activity_in_country": [{"id": fra.id}],
}
self.rdf_jpp = {
"label": u"Person that has activity in Journalism++",
"object": {"id": 283, "model": u"common:Organization", "name": u"Journalism++"},
"predicate": {
"label": u"has activity in",
"name": u"person_has_activity_in_organization+",
"subject": u"energy:Person",
},
"subject": {"label": u"Person", "name": u"energy:Person"},
}
def get_credentials(self):
return self.api_client.client.login(username=self.username, password=self.password)
def test_user_login_succeed(self):
auth = dict(username=u"tester", password=u"tester")
resp = self.api_client.post("/api/common/v1/user/login/", format="json", data=auth)
self.assertValidJSON(resp.content)
# Parse data to check the number of result
data = json.loads(resp.content)
self.assertEqual(data["success"], True)
def test_user_login_failed(self):
auth = dict(username=u"tester", password=u"wrong")
resp = self.api_client.post("/api/common/v1/user/login/", format="json", data=auth)
self.assertValidJSON(resp.content)
# Parse data to check the number of result
data = json.loads(resp.content)
self.assertEqual(data["success"], False)
def test_user_logout_succeed(self):
# First login
auth = dict(username=u"tester", password=u"tester")
self.api_client.post("/api/common/v1/user/login/", format="json", data=auth)
# Then logout
resp = self.api_client.get("/api/common/v1/user/logout/", format="json")
self.assertValidJSON(resp.content)
# Parse data to check the number of result
data = json.loads(resp.content)
self.assertEqual(data["success"], True)
def test_user_logout_failed(self):
resp = self.api_client.get("/api/common/v1/user/logout/", format="json")
self.assertValidJSON(resp.content)
# Parse data to check the number of result
data = json.loads(resp.content)
self.assertEqual(data["success"], False)
def test_user_status_isnt_logged(self):
resp = self.api_client.get("/api/common/v1/user/status/", format="json")
self.assertValidJSON(resp.content)
# Parse data to check the number of result
data = json.loads(resp.content)
#.........这里部分代码省略.........
示例14: PilotJobResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [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)
示例15: UserTestBase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import post [as 别名]
class UserTestBase(ResourceTestCase):
def setUp(self):
load_states()
load_statutes()
settings.DEBUG = True
self.api_client = TestApiClient()
self.get_credentials()
#user creates all the groups and requests initially, user should always have edit perms unless another user takes that away
self.user = User.objects.create_user('john', '[email protected]', 'secret')
self.user.is_staff = True#someone has to be responsible
self.user.save()
self.usertwo = User.objects.create_user('yoko', '[email protected]', 'secret')
self.userthree = User.objects.create_user('ringo', '[email protected]', 'secret')
self.post_data = {
'name': 'A TEST GROUP'
}
self.up, created = UserProfile.objects.get_or_create(user=self.user)
self.uptwo, created = UserProfile.objects.get_or_create(user=self.usertwo)
self.upthree, created = UserProfile.objects.get_or_create(user=self.userthree)
self.groupJSON = None
self.group = None
self.request = None
self.agency = None
self.agencyJSON = None
self.contact = None
self.contactJSON = None
self.government = None
self.governmentJSON = None
def tearDown(self):
Request.objects.all().delete()
Contact.objects.all_them().delete()
Agency.objects.all_them().delete()
FeeExemptionOther.objects.all_them().delete()
Statute.objects.all_them().delete()
Government.objects.all().delete()
Group.objects.all().delete()
User.objects.all().delete()
def get_user_group(self, userToGet):
#each user has their own group named after then which they are the sole member of
for group in userToGet.groups.all():
if group.name == userToGet.username:
return group
def create_group(self):
#creates the default group and sets default json
if self.groupJSON is not None:
return self.groupJSON
resp = self.api_client.post('/api/v1/group/', format='json', data=self.post_data, authentication=self.get_credentials())
self.group = Group.objects.get(name=self.post_data['name'])
self.groupJSON = json.loads(resp.content)
return resp
def get_group_json(self, group):
#gets json for a group
resp = self.api_client.get('/api/v1/group/%s/' % group.id, format='json', data={}, authentication=self.get_credentials())
return json.loads(resp.content)
def get_user_json(self, userToGet):
users_resp = self.api_client.get("/api/v1/user/%s/" % userToGet.id, format='json', authentication=self.get_credentials())
return json.loads(users_resp.content)
def add_user_to_group(self, userToAdd):
self.create_group()
users = self.get_user_json(userToAdd)
groupjson = self.groupJSON.copy()
groupjson['users'].append(users)
update_resp = self.api_client.put(self.groupJSON['resource_uri'], format='json', data=groupjson, authentication=self.get_credentials())
def create_request(self, username=None):
request_data = {
'contacts': [],
'free_edit_body': "<p>Something respectable, and testable!</p>",
'private': True,
'title': "test bangarang"
}
if username is None:
self.api_client.post('/api/v1/request/', format='json', data=request_data, authentication=self.get_credentials())
else:
self.api_client.post('/api/v1/request/', format='json', data=request_data, authentication=self.get_credentials_other(username))
self.request = Request.objects.get(title=request_data['title'])
def get_credentials(self):
#log in with self.user credentials
result = self.api_client.client.login(username='john',
password='secret')
return result
def get_credentials_other(self, username):
#log in with self.user credentials
result = self.api_client.client.login(username=username,
password='secret')
return result
def create_agency(self):
self.agencyData = {
#.........这里部分代码省略.........