本文整理汇总了Python中tastypie.test.TestApiClient.put方法的典型用法代码示例。如果您正苦于以下问题:Python TestApiClient.put方法的具体用法?Python TestApiClient.put怎么用?Python TestApiClient.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tastypie.test.TestApiClient
的用法示例。
在下文中一共展示了TestApiClient.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SetAccessRulesTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class SetAccessRulesTest(ResourceTestCase):
serializer = Serializer()
def setUp(self):
self.account_url_base = '/hsapi/resource/accessRules/'
self.api_client = TestApiClient()
def tearDown(self):
User.objects.all().delete()
Group.objects.all().delete()
def test_set_user_rules(self):
user = hydroshare.create_account(
'[email protected]',
username='user0',
first_name='User0_FirstName',
last_name='User0_LastName',
)
url = '{0}{1}/'.format(self.account_url_base, user.id)
put_data = {
'pid':user.id,
'principaltype': 'user',
'principleID': user.id,
'access': 'view',
'allow': 'true'
}
resp = self.api_client.put(url, data=put_data)
self.assertEqual(resp.status_code, 200)
def test_set_group_rules(self):
group = hydroshare.create_group(name="group0")
url = '{0}{1}/'.format(self.account_url_base, group.id)
put_data = self.serialize({
'principaltype': 'group',
'principleID': group.id,
'access': 'view',
'allow': 'true'
})
resp = self.api_client.put(url, data=put_data)
self.assertEqual(resp.status_code, 200)
示例2: SetResourceOwnerTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class SetResourceOwnerTest(ResourceTestCase):
serializer = Serializer()
def setUp(self):
self.api_client = TestApiClient()
self.user = hydroshare.create_account(
"[email protected]",
username="user",
first_name="User_FirstName",
last_name="User_LastName",
password="foobar",
superuser=True,
)
self.url_base = "/hsapi/resource/owner/"
self.api_client.client.login(username=self.user.username, password=self.user.password)
def tearDown(self):
User.objects.all().delete()
def test_set_owner(self):
res = hydroshare.create_resource("GenericResource", self.user, "res1")
user2 = hydroshare.create_account(
"[email protected]",
username="user2",
first_name="User2_FirstName",
last_name="User2_LastName",
password="password",
)
post_data = {"user": user2.pk, "api_key": self.user.api_key.key}
url = "{0}{1}/".format(self.url_base, res.short_id)
resp = self.api_client.put(url, data=post_data)
self.assertEqual(resp.body, res.short_id)
hydroshare.delete_resource(res.short_id)
示例3: mock_request
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [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: AnswerCreationResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [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)
示例5: TestCampaignResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [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', id=1)
self.campaign_bills = mommy.make_one('catamidb.Campaign', id=2)
#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 can NOT create
self.assertHttpMethodNotAllowed(
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 create authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.post(self.campaign_url,
format='json',
data=self.post_data)
)
# 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(
#.........这里部分代码省略.........
示例6: ResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class ResourceTest(ResourceTestCase):
def setUp(self):
self.logger = logging.getLogger(__name__)
self.api_client = TestApiClient()
self.username = "creator"
self.password = "mybadpassword"
# create a user to be used for creating the resource
self.user_creator = hydroshare.create_account(
"[email protected]",
username=self.username,
first_name="Creator_FirstName",
last_name="Creator_LastName",
superuser=False,
password=self.password,
groups=[],
)
self.user_url = "/hsapi/accounts/{0}/".format(self.user_creator.username)
self.api_client.client.login(username=self.username, password=self.password)
# create a resource
self.resource = hydroshare.create_resource(
resource_type="GenericResource",
title="My resource",
owner=self.user_creator,
last_changed_by=self.user_creator,
)
self.resource_url_base = "/hsapi/resource/"
self.resource_url = "{0}{1}/".format(self.resource_url_base, self.resource.short_id)
self.post_data = {"title": "My REST API-created resource", "resource_type": "GenericResource"}
def tearDown(self):
User.objects.all().delete()
GenericResource.objects.all().delete()
def get_credentials(self):
k = self.create_basic(username=self.username, password=self.password)
print k
return k
def test_resource_get(self):
resp = self.api_client.get(self.resource_url)
self.assertTrue(resp["Location"].endswith(".zip"))
def test_resource_post(self):
resp = self.api_client.post(self.resource_url_base, data=self.post_data)
self.assertIn(resp.status_code, [201, 200])
# PID comes back as body of response, but API client doesn't seem to be
# parsing the response for us
pid = str(resp).split("\n")[-1]
new_resource_url = "{0}{1}/".format(self.resource_url_base, pid)
# Fetch the newly created resource
resp = self.api_client.get(new_resource_url)
self.assertTrue(resp["Location"].endswith(".zip"))
def test_resource_put(self):
new_data = {}
new_data["title"] = "My UPDATED REST API-created resource"
resp = self.api_client.put(self.resource_url, data=new_data)
self.assertIn(resp.status_code, ["202", "204"])
def test_resource_delete(self):
x = self.api_client.delete(self.resource_url, format="json")
self.assertIn(x.status_code, [202, 204, 301])
self.assertHttpNotFound(self.api_client.get(self.resource_url, format="json"))
示例7: ProjectPartResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class ProjectPartResourceTest(ResourceTestCase):
fixtures = ['group.json', 'group_permission.json',
'user_group.json', 'user.json',
'user_project.json', 'project_part.json',
'project.json', 'profile.json']
def setUp(self):
self.api_client = TestApiClient()
self.post_data = {'title': 'new part',
'project_id': {'pk': 3},
'project_part_id': {'pk': 1},
'order': 0,
'weight': 20
}
self.project_part_id = 1
self.open_project_part_id = 2
self.detail_base_url = '/api/v1/project_part/{0}/'
self.open_detail_url = self.detail_base_url.format(self.open_project_part_id)
self.detail_url = self.detail_base_url.format(self.project_part_id)
self.list_url = '/api/v1/project_part/'
self.serializer = Serializer()
def get_credentials(self):
self.api_client.client.login(email='[email protected]',
password='django')
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()
self.assertHttpUnauthorized(self.api_client.get(self.list_url, format='json'))
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)['title'], 'Project Part 1')
# FIXME Idem from above
# def test_post_list_unauthenticated(self):
# self.assertHttpUnauthorized(self.api_client.post(self.list_url, format='json', data=self.post_data))
def test_post_list(self):
self.get_credentials()
self.assertEqual(ProjectPart.objects.count(), 2)
resp = self.api_client.post(self.list_url, format='json',
data=self.post_data)
self.assertHttpCreated(resp)
self.assertEqual(ProjectPart.objects.count(), 3)
def test_put_detail_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.put(self.detail_url, format='json', data={}))
@mock.patch('wevolve.projects.api.update_drive_folder')
def test_put_detail(self, method):
self.get_credentials()
content = self.api_client.get(self.detail_url, format='json').content
original_data = json.loads(content)
new_data = original_data.copy()
new_data['title'] = 'Updated First Post'
self.assertEqual(ProjectPart.objects.count(), 2)
resp = self.api_client.put(self.detail_url, format='json', data=new_data)
self.assertHttpAccepted(resp)
self.assertEqual(ProjectPart.objects.count(), 2)
self.assertEqual(ProjectPart.objects.get(pk=self.project_part_id).title, 'Updated First Post')
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(ProjectPart.objects.count(), 2)
self.assertHttpAccepted(self.api_client.delete(self.detail_url, format='json'))
self.assertEqual(ProjectPart.objects.count(), 1)
# Project parts in open projects
def test_get_detail_open(self):
resp = self.api_client.get(self.open_detail_url, format='json')
self.assertValidJSONResponse(resp)
self.assertEqual(json.loads(resp.content)['title'], 'Project Part 2')
def test_put_detail_open(self):
content = self.api_client.get(self.open_detail_url, format='json').content
original_data = json.loads(content)
new_data = original_data.copy()
new_data['title'] = 'Updated First Post'
self.assertEqual(ProjectPart.objects.count(), 2)
resp = self.api_client.put(self.detail_url, format='json', data=new_data)
self.assertHttpUnauthorized(resp)
def test_delete_detail_open(self):
self.assertEqual(ProjectPart.objects.count(), 2)
#.........这里部分代码省略.........
示例8: TestScientificImageMeasurementResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
#.........这里部分代码省略.........
camera=self.camera_bills)
#make image measurements
self.image_measurement_bobs = mommy.make_one(
'catamidb.ScientificImageMeasurement', id=1, image=self.image_bobs
)
self.image_measurement_bills = mommy.make_one(
'catamidb.ScientificImageMeasurement', id=2, image=self.
image_bills)
#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.image_measurement_url = '/api/dev/scientificimagemeasurement/'
self.post_data = []
# can only do GET at this stage
def test_image_measurement_operations_disabled(self):
# test that we can NOT create
self.assertHttpMethodNotAllowed(
self.anon_api_client.post(self.image_measurement_url,
format='json',
data=self.post_data))
# test that we can NOT modify
self.assertHttpMethodNotAllowed(
self.anon_api_client.put(
self.image_measurement_url +
self.deployment_bobs.id.__str__() + "/",
format='json',
data={}
)
)
# test that we can NOT delete
self.assertHttpMethodNotAllowed(
self.anon_api_client.delete(
self.image_measurement_url +
self.deployment_bobs.id.__str__() + "/",
format='json'
)
)
# test that we can NOT create authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.post(
self.image_measurement_url,
format='json',
data=self.post_data
)
)
# test that we can NOT modify authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.put(
self.image_measurement_url +
self.deployment_bobs.id.__str__() + "/",
format='json',
data={}
示例9: TestMeasurementsResource
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class TestMeasurementsResource(ResourceTestCase):
def setUp(self):
# Tastypie stuff
super(TestMeasurementsResource, 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", id=1)
self.campaign_bills = mommy.make_one("catamidb.Campaign", id=2)
# make a deployments
self.deployment_bobs = mommy.make_recipe("catamidb.Deployment1", id=1, campaign=self.campaign_bobs)
self.deployment_bills = mommy.make_recipe("catamidb.Deployment2", id=2, campaign=self.campaign_bills)
# make images
self.image_bobs = mommy.make_recipe("catamidb.Image1", id=1, deployment=self.deployment_bobs)
self.image_bills = mommy.make_recipe("catamidb.Image2", id=2, deployment=self.deployment_bills)
# make measurements
self.measurements_bobs = mommy.make_one("catamidb.Measurement", id=1, image=self.image_bobs)
self.measurements_bills = mommy.make_one("catamidb.Measurement", id=2, image=self.image_bills)
# 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 Measurements
self.image_measurement_url = "/api/dev/measurements/"
self.post_data = {
"altitude": "13",
"pitch": "1",
"roll": "5",
"salinity": "20",
"temperature": "22",
"yaw": "1",
}
# can only do GET at this stage
def test_measurement_operations_disabled(self):
# test that we can NOT modify
self.assertHttpUnauthorized(
self.anon_api_client.put(
self.image_measurement_url + self.deployment_bobs.id.__str__() + "/", format="json", data={}
)
)
# test that we can NOT delete
self.assertHttpMethodNotAllowed(
self.anon_api_client.delete(
self.image_measurement_url + self.deployment_bobs.id.__str__() + "/", format="json"
)
)
# test that we can NOT modify authenticated
self.assertHttpUnauthorized(
self.bob_api_client.put(
self.image_measurement_url + self.deployment_bobs.id.__str__() + "/", format="json", data={}
)
)
# test that we can NOT delete authenticated
self.assertHttpMethodNotAllowed(
self.bob_api_client.delete(
self.image_measurement_url + self.deployment_bobs.id.__str__() + "/", format="json"
)
)
def test_measurement_operations_as_authorised_users(self):
# create a campaign & deployment that ONLY bill can see
bills_campaign = mommy.make_one("catamidb.Campaign", id=3, short_name="cp__3")
bills_deployment = mommy.make_recipe("catamidb.Deployment1", id=3, campaign=bills_campaign, short_name="dp__3")
bills_image = mommy.make_recipe("catamidb.Image3", id=3, deployment=bills_deployment)
bills_measurements = mommy.make_one("catamidb.Measurement", id=3, image=bills_image)
#.........这里部分代码省略.........
示例10: PostResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class PostResourceTest(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):
# Generic
self.api_client = TestApiClient()
self.serializer = Serializer()
# API List data
self.list_url = '/api/v1/post/'
# API requests data
self.project_part_id = 1
self.post_id = 1
self.detail_url = '/api/v1/post/{0}/'.format(self.post_id)
self.project_part_query = '='.join(['?project_part', str(self.project_part_id)])
self.post_data = {'content': 'My post', 'project_part': {'pk': self.project_part_id}}
# Open API request data
self.open_project_part_id = 2
self.open_post_id = 2
self.open_detail_url = '/api/v1/post/{0}/'.format(self.open_post_id)
self.open_project_part_query = '='.join(['?project_part', str(self.open_project_part_id)])
self.open_post_data = {'content': 'My post', 'project_part': {'pk': self.open_project_part_id}}
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(Post.objects.count(), 2)
self.assertHttpCreated(self.api_client.post(self.list_url,
format='json',
data=self.post_data))
self.assertEqual(Post.objects.count(), 3)
def test_get_list_unauthorzied(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(''.join([self.list_url, self.project_part_query]),
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)['content'], 'hola')
# 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()
original_data = json.loads(self.api_client.get(self.detail_url, format='json').content)
new_data = original_data.copy()
new_data['title'] = 'Updated: First Post'
self.assertEqual(Post.objects.count(), 2)
self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))
# Make sure the count hasn't changed & we did an update.
self.assertEqual(Post.objects.count(), 2)
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(Post.objects.count(), 2)
resp = self.api_client.delete(self.detail_url, format='json')
self.assertHttpAccepted(resp)
self.assertEqual(Post.objects.count(), 1)
# Open Projects
# FIXME It fails because tastypie is not accessing authorization
# before calling obj_create
# def test_post_list_open(self):
# self.assertEqual(Post.objects.count(), 2)
# resp = self.api_client.post(self.list_url,
# format='json',
# data=self.open_post_data)
#.........这里部分代码省略.........
示例11: UserTestBase
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [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 = {
#.........这里部分代码省略.........
示例12: CommentResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [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)
示例13: DocumentResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class DocumentResourceTest(ResourceTestCase):
fixtures = ['group.json', 'group_permission.json',
'user_group.json', 'user.json',
'user_project.json', 'project_part.json',
'project.json', 'profile.json',
'document.json']
def setUp(self):
self.api_client = TestApiClient()
self.project_part_id = 1
self.document_data = {'text': 'My document', 'project_part': {'pk': self.project_part_id}}
self.document_id = 1
self.project_part_query = '='.join(['?project_part', str(self.project_part_id)])
self.detail_url = '/api/v1/document/{0}/'.format(self.document_id)
self.list_url = '/api/v1/document/'
self.serializer = Serializer()
def get_credentials(self):
result = self.api_client.client.login(email='[email protected]',
password='django')
def test_document_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(Document.objects.count(), 2)
self.assertHttpCreated(self.api_client.post(self.list_url,
format='json',
data=self.document_data))
self.assertEqual(Document.objects.count(), 3)
def test_get_list_unauthorzied(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(''.join([self.list_url, self.project_part_query]),
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)['text'], '<h1>hola</h1>')
# def test_post_list_unauthenticated(self):
# self.assertHttpUnauthorized(self.api_client.post(self.list_url, format='json',
# data=self.document_data))
def test_put_detail_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.put(self.detail_url, format='json', data={'text': 'data'}))
def test_put_detail(self):
self.get_credentials()
original_data = json.loads(self.api_client.get(self.detail_url, format='json').content)
new_data = original_data.copy()
new_data['title'] = 'Updated: First Document'
self.assertEqual(Document.objects.count(), 2)
self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))
# Make sure the count hasn't changed & we did an update.
self.assertEqual(Document.objects.count(), 2)
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(Document.objects.count(), 2)
resp = self.api_client.delete(self.detail_url, format='json')
self.assertHttpAccepted(resp)
self.assertEqual(Document.objects.count(), 1)
示例14: ResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class ResourceTest(ResourceTestCase):
serializer= Serializer()
def setUp(self):
self.api_client = TestApiClient()
self.username = 'creator'
self.password = 'mybadpassword'
self.user = hydroshare.create_account(
'[email protected]',
username=self.username,
password=self.password,
first_name='User0_FirstName',
last_name='User0_LastName',
)
self.api_client.client.login(username=self.username, password=self.password)
self.url_proto = '/hsapi/resource/{0}/files/{1}/'
self.filename = 'test.txt'
def tearDown(self):
User.objects.all().delete()
GenericResource.objects.all().delete()
def test_resource_file_get(self):
myfile = open(self.filename, 'w')
myfile.write('hello world!\n')
myfile.close()
myfile = open(self.filename, 'r')
res1 = hydroshare.create_resource('GenericResource', self.user, 'res1')
hydroshare.add_resource_files(res1.short_id, myfile)
url = self.url_proto.format(res1.short_id, self.filename)
resp = self.api_client.get(url)
self.assertIn(resp.status_code, [201, 200])
def test_resource_file_put(self):
myfile = open(self.filename, 'w')
myfile.write('hello world!\n')
myfile.close()
myfile = open(self.filename, 'r')
res1 = hydroshare.create_resource('GenericResource', self.user, 'res1')
hydroshare.add_resource_files(res1.short_id, myfile)
mynewfile = open(self.filename, 'w')
mynewfile.write('anyone there?\n')
mynewfile.close()
mynewfile = open(self.filename, 'r')
url = self.url_proto.format(res1.short_id, self.filename)
put_data = { 'resource_file': mynewfile
}
resp = self.api_client.put(url, data=put_data)
self.assertHttpAccepted(resp)
resp = self.api_client.get(url)
self.assertIn(resp.status_code, [201, 200])
def test_resource_file_post(self):
myfile = open(self.filename, 'w')
myfile.write('hello world!\n')
myfile.close()
myfile = open(self.filename, 'r')
res1 = hydroshare.create_resource('GenericResource', self.user, 'res1')
post_data = { 'resource_file': myfile
}
url = self.url_proto.format(res1.short_id, self.filename)
resp = self.api_client.post(url, data=post_data)
self.assertHttpAccepted(resp)
resp = self.api_client.get(url)
self.assertIn(resp.status_code, [201, 200])
def test_resource_file_delete(self):
myfile = open(self.filename, 'w')
myfile.write('hello world!\n')
myfile.close()
myfile = open(self.filename, 'r')
#.........这里部分代码省略.........
示例15: TaskResourceTest
# 需要导入模块: from tastypie.test import TestApiClient [as 别名]
# 或者: from tastypie.test.TestApiClient import put [as 别名]
class TaskResourceTest(ResourceTestCase):
fixtures = ['group.json', 'group_permission.json',
'user_group.json', 'user.json',
'user_project.json', 'project_part.json',
'project.json', 'profile.json',
'task.json']
def setUp(self):
self.api_client = TestApiClient()
self.task_id = 1
self.project_part_id = 1
self.task = {'description': 'new Task',
'project_part': {'pk': self.project_part_id},
'flag_finished': 0,
'weight': 20
}
self.detail_url = '/api/v1/task/{0}/'.format(self.task_id)
self.project_part_query = '='.join(['?project_part', str(self.project_part_id)])
self.list_url = '/api/v1/task/'
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(Task.objects.count(), 2)
resp = self.api_client.post(self.list_url,
format='json',
data=self.task)
self.assertHttpCreated(resp)
self.assertEqual(Task.objects.count(), 3)
def test_get_list_unauthenticated(self):
self.assertHttpUnauthorized(self.api_client.get(''.join([self.list_url, self.project_part_query]),
format='json'))
def test_get_list_json(self):
self.get_credentials()
resp = self.api_client.get(''.join([self.list_url, self.project_part_query]),
format='json')
self.assertValidJSONResponse(resp)
self.assertEqual(len(json.loads(resp.content)['objects']), 2)
def test_get_detail_unauthenticated(self):
resp = self.api_client.get(self.detail_url, format='json')
self.assertHttpUnauthorized(resp)
def test_get_detail_json(self):
self.get_credentials()
resp = self.api_client.get(self.detail_url, format='json')
self.assertValidJSONResponse(resp)
self.assertEqual(json.loads(resp.content)['description'], 'new task')
# def test_post_list_unauthenticated(self):
# self.assertHttpUnauthorized(self.api_client.post(self.list_url, format='json',
# data=self.task))
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()
original_data = json.loads(self.api_client.get(self.detail_url, format='json').content)
new_data = original_data.copy()
new_data['title'] = 'Updated: First Task'
self.assertEqual(Task.objects.count(), 2)
self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))
self.assertEqual(Task.objects.count(), 2)
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(Task.objects.count(), 2)
self.assertHttpAccepted(self.api_client.delete(self.detail_url, format='json'))
self.assertEqual(Task.objects.count(), 1)