本文整理汇总了Python中rest_framework.test.APIClient类的典型用法代码示例。如果您正苦于以下问题:Python APIClient类的具体用法?Python APIClient怎么用?Python APIClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了APIClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_make_build
def test_make_build(self):
"""
Test that a superuser can use the API
"""
client = APIClient()
client.login(username='super', password='test')
resp = client.post(
'/api/v2/build/',
{
'project': 1,
'version': 1,
'success': True,
'output': 'Test Output',
'error': 'Test Error',
'state': 'cloning',
},
format='json')
self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
build = resp.data
self.assertEqual(build['state_display'], 'Cloning')
resp = client.get('/api/v2/build/%s/' % build['id'])
self.assertEqual(resp.status_code, 200)
build = resp.data
self.assertEqual(build['output'], 'Test Output')
self.assertEqual(build['state_display'], 'Cloning')
示例2: test_perm
def test_perm(self):
client = APIClient()
response = client.get(reverse('node-list'))
# user not logged
assert response.status_code == status.HTTP_403_FORBIDDEN
示例3: get_authorized_client
def get_authorized_client(user):
token = Token.objects.create(user=user)
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
return client
示例4: login_client
def login_client(self, user):
"""
Helper method for getting the client and user and logging in. Returns client.
"""
client = APIClient()
client.login(username=user.username, password=self.TEST_PASSWORD)
return client
示例5: api_client
def api_client(user, db):
"""
A rest_framework api test client not auth'd.
"""
client = APIClient()
client.force_authenticate(user=user)
return client
示例6: test_get_product_with_auth
def test_get_product_with_auth(self):
c = APIClient()
c.login(username='bruce', password='testpass')
response = c.get('/products/1/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content, '{"id":1,"owner":"bruce","name":"Bat Mobile","description":"Black Batmobile","price":200,"category":"Automobile","image":""}')
示例7: test_queueing
def test_queueing(self, mocked_now):
test_datetime = datetime.utcnow().isoformat() + 'Z'
mocked_now.return_value = test_datetime
task_post_data = {
'task_def': self.task_def_name,
'data': {
'foo': 'bar'
}
}
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=self.token)
response = client.post('/tasks', task_post_data, format='json')
self.assertEqual(response.status_code, 201)
self.assertEqual(list(response.data.keys()), task_keys)
self.assertEqual(response.data['task_def'], self.task_def_name)
## test fields defaults
self.assertEqual(response.data['status'], 'queued')
self.assertEqual(response.data['priority'], 'normal')
self.assertEqual(response.data['run_at'], test_datetime)
示例8: setUp
def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.non_csrf_client = APIClient(enforce_csrf_checks=False)
self.username = 'john'
self.email = '[email protected]'
self.password = 'password'
self.user = User.objects.create_user(self.username, self.email, self.password)
示例9: test_token_login_form
def test_token_login_form(self):
"""Ensure token login view using form POST works."""
client = APIClient(enforce_csrf_checks=True)
response = client.post('/auth-token/',
{'username': self.username, 'password': self.password})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['token'], self.key)
示例10: UserAPITest
class UserAPITest(APITestCase):
fixtures = ['user.json']
def setUp(self):
self.client = APIClient()
self.user = User.objects.get(email='[email protected]')
payload = jwt_payload_handler(self.user)
self.token = utils.jwt_encode_handler(payload)
def testUpdateAccountDetails(self):
auth = 'JWT {0}'.format(self.token)
response = self.client.patch('/api/account/{}'.format(self.user.id),
{
"contact_number": '09175226502'
}, HTTP_AUTHORIZATION=auth, format='json')
def testChangePassword(self):
auth = 'JWT {0}'.format(self.token)
user = User.objects.get(email='[email protected]')
response = self.client.patch('/api/change_password'.format(self.user.id),
{
"password": 'corruptionsucks',
"old_password": 'abcdefgh1'
}, HTTP_AUTHORIZATION=auth, format='json')
print(user.password)
user = User.objects.get(email='[email protected]')
print(user.password)
示例11: XeroxViewTest
class XeroxViewTest(TestCase):
def setUp(self):
self.client = APIClient()
self.sizes = ('q', 'n')
self.urls = {}
self.nurls = {}
x_hash = XeroxMachine().add('http://www.google.com/google.jpg')
no_hash = XeroxMachine().add('http://zarautz.xyz/open.jpg')
for size in self.sizes:
self.urls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, x_hash, size)))
self.nurls[size] = get_absolute_uri(reverse('image', args=(XeroxMachine.IMAGE_TYPE_IN_URL, no_hash, size)))
def test_default_response(self):
response = self.client.get(self.urls[self.sizes[0]])
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response['Content-Type'], 'image/jpeg')
self.assertEqual(response['Cache-Control'], 'max-age=604800')
def test_no_response(self):
response = self.client.get(self.nurls[self.sizes[0]])
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_no_event_response(self):
response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/e/')) # EventImage
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_no_place_response(self):
response = self.client.get(self.urls[self.sizes[0]].replace('/x/', '/p/')) # PlaceImage
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_image_sizes(self):
for size in self.sizes:
image = Image.open(StringIO(self.client.get(self.urls[size]).content))
self.assertEqual(image.size[0], IMAGE_SIZES[size]['size'][0])
示例12: test_get
def test_get(self):
client = APIClient()
response = client.get('/sources')
response.status_code.should.eql(status.HTTP_200_OK)
response.data.should.eql(['youtube', 'soundcloud'])
示例13: test_update_failure_line_replace
def test_update_failure_line_replace(eleven_jobs_stored, jm, failure_lines,
classified_failures, test_user):
MatcherManager.register_detector(ManualDetector)
client = APIClient()
client.force_authenticate(user=test_user)
failure_line = failure_lines[0]
assert failure_line.best_classification == classified_failures[0]
assert failure_line.best_is_verified is False
body = {"project": jm.project,
"best_classification": classified_failures[1].id}
resp = client.put(
reverse("failure-line-detail", kwargs={"pk": failure_line.id}),
body, format="json")
assert resp.status_code == 200
failure_line.refresh_from_db()
assert failure_line.best_classification == classified_failures[1]
assert failure_line.best_is_verified
assert len(failure_line.classified_failures.all()) == 2
expected_matcher = Matcher.objects.get(name="ManualDetector")
assert failure_line.matches.get(classified_failure_id=classified_failures[1].id).matcher == expected_matcher
示例14: TestAccountAPITransactions
class TestAccountAPITransactions(TransactionTestCase):
"""
Tests the transactional behavior of the account API
"""
test_password = "test"
def setUp(self):
super(TestAccountAPITransactions, self).setUp()
self.client = APIClient()
self.user = UserFactory.create(password=self.test_password)
self.url = reverse("accounts_api", kwargs={'username': self.user.username})
@patch('student.views.do_email_change_request')
def test_update_account_settings_rollback(self, mock_email_change):
"""
Verify that updating account settings is transactional when a failure happens.
"""
# Send a PATCH request with updates to both profile information and email.
# Throw an error from the method that is used to process the email change request
# (this is the last thing done in the api method). Verify that the profile did not change.
mock_email_change.side_effect = [ValueError, "mock value error thrown"]
self.client.login(username=self.user.username, password=self.test_password)
old_email = self.user.email
json_data = {"email": "[email protected]", "gender": "o"}
response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json")
self.assertEqual(400, response.status_code)
# Verify that GET returns the original preferences
response = self.client.get(self.url)
data = response.data
self.assertEqual(old_email, data["email"])
self.assertEqual(u"m", data["gender"])
示例15: GroupTests
class GroupTests(APITestCase):
def setUp(self):
self.user = User.objects.create_user(username='chet', email='[email protected]', password='chet')
self.cl = Client.objects.create(user=self.user,
redirect_uri="http://localhost/",
client_type=2
)
self.token = AccessToken.objects.create(
user=self.user, client=self.cl,
expires=datetime.date(
year=2015, month=1, day=2
)
)
self.client = APIClient()
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.token)
def test_create_group(self):
"""
Ensure we can create a group.
"""
url = reverse('group-create')
data = { 'name': 'SECSI',
'description': 'SECSI, DO YOU SPEAK IT', 'creator': self.user.id}
response = self.client.post(url + ".json", data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)