我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用django.test.Client()。
def test_get_tiles(self): ''' Try to retrieve some tiles from this file ''' c1 = dt.Client() c1.login(username='user1', password='pass') # make sure that the dataset has been added ret = json.loads(c1.get('/api/v1/tilesets/?d=bw').content.decode('utf-8')) assert(ret['count'] == 1) # try to retrieve the top level tile # ret = json.loads(c1.get('/api/v1/tiles/?d=bw.0.0').content.decode('utf-8')) # print("ret:", ret) # retrieve a tile that lies completely beyond the end of # the assembly ret = json.loads(c1.get('/api/v1/tiles/?d=bw.22.4194303').content.decode('utf-8'))
def test_create_private_tileset(self): """Test to make sure that when we create a private dataset, we can only access it if we're logged in as the proper user """ upload_file =open('data/wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.hitile', 'rb') private_obj = tm.Tileset.objects.create( datafile=dcfu.SimpleUploadedFile(upload_file.name, upload_file.read()), filetype='hitile', private=True, owner=self.user1 ) c = dt.Client() c.login(username='user1', password='pass') returned = json.loads( self.client.get( '/api/v1/tileset_info/?d={uuid}'.format(uuid=private_obj.uuid) ).content.decode('utf-8') )
def test_create_experience_creates_and_returns_experience(self): orm_person = ORMPerson.objects.create(username='usr.nm', is_email_confirmed=True) orm_auth_token = ORMAuthToken.objects.create(person_id=orm_person.id) auth_headers = {'HTTP_AUTHORIZATION': 'Token {}'.format(orm_auth_token.access_token), } client = Client() response = client.post(reverse('experiences'), {'title': 'Experience title', 'description': 'Some description'}, **auth_headers) body = json.loads(response.content) created_experience = ORMExperience.objects.get(id=body['id'], title='Experience title', description='Some description') assert created_experience is not None assert body == { 'id': str(created_experience.id), 'title': 'Experience title', 'description': 'Some description', 'picture': None, 'author_id': orm_person.id, 'author_username': orm_person.username }
def test_wrong_attributes_doesnt_create_and_returns_error(self): orm_person = ORMPerson.objects.create(is_email_confirmed=True) orm_auth_token = ORMAuthToken.objects.create(person_id=orm_person.id) auth_headers = {'HTTP_AUTHORIZATION': 'Token {}'.format(orm_auth_token.access_token), } client = Client() response = client.post(reverse('experiences'), {'title': '', 'description': 'Some description'}, **auth_headers) assert not ORMExperience.objects.filter(title='', description='Some description').exists() body = json.loads(response.content) assert body == { 'error': { 'source': 'title', 'code': 'wrong_size', 'message': 'Title must be between 1 and 30 chars' } }
def test_modifies_and_returns_experience(self): orm_person = ORMPerson.objects.create(username='usr.nm') orm_auth_token = ORMAuthToken.objects.create(person_id=orm_person.id) auth_headers = {'HTTP_AUTHORIZATION': 'Token {}'.format(orm_auth_token.access_token), } orm_experience = ORMExperience.objects.create(title='T', description='', author=orm_person) client = Client() response = client.patch(reverse('experience', args=[orm_experience.id]), urllib.parse.urlencode({"description": "New description"}), **auth_headers, content_type='application/x-www-form-urlencoded') body = json.loads(response.content) updated_experience = ORMExperience.objects.get(id=orm_experience.id, title='T', description='New description') assert updated_experience is not None assert body == { 'id': str(orm_experience.id), 'title': 'T', 'description': 'New description', 'picture': None, 'author_id': orm_person.id, 'author_username': orm_person.username }
def test_modify_avatar_by_teacher(self): # Teacher role not allowed to modify avatar. username = "test1" password = "123123" user = User.objects.get(username=username) change_profile_perm = Permission.objects.get(name='Can change profile') user.user_permissions.add(change_profile_perm) user.save() client = Client() client.login(username=username, password=password) request_url = "/api/v1/profiles/%d" % (user.profile.pk,) img_name = 'img0' # NOTE: seq is 0 not 1, seq of the user 'parent1' img_path = os.path.join( app_path, 'migrations', 'avatars', img_name + '.jpg') # print(img_path) img_fd = open(img_path, 'rb') data = {'avatar': img_fd} encoded_data = encode_multipart(BOUNDARY, data) response = client.patch(request_url, content_type=MULTIPART_CONTENT, data=encoded_data) self.assertEqual(409, response.status_code)
def test_kuailexue_study_report(self): username = "parent1" password = "123123" client = Client() client.login(username=username, password=password) params = klx.klx_build_params({'uid': '12345678'}, False) klx.klx_sign_params(params) self.assertTrue(klx.klx_verify_sign(params)) request_url = "/api/v1/study_report" response = client.get(request_url, content_type='application/json') self.assertEqual(200, response.status_code) math_id = Subject.objects.get(name='??').id request_url = "/api/v1/study_report/%s"%(math_id) response = client.get(request_url, content_type='application/json') self.assertEqual(200, response.status_code)
def test_information_complete(self): client = Client() client.login(username=self.teacher_name, password=self.teacher_password) response = client.get(reverse("teacher:complete-information")) self.assertEqual(response.status_code, 200) post_client = Client() post_client.login(username=self.teacher_name, password=self.teacher_password) post_response = post_client.post(reverse("teacher:complete-information"), { "name": "???", "gender": "m", "region": "??", "subclass": "??", "grade": '["?????", "?????"]' }) self.assertEqual(post_response.status_code, 200) self.assertEqual(json.loads(post_response.content.decode("utf-8")), {"url": "/teacher/register/progress", "done": True})
def test_my_students(self): client = Client() client.login(username=self.teacher_name, password=self.teacher_password) teacher = self.the_teacher() parent = self.the_parent() school = teacher.schools.all()[0] grade = teacher.abilities.all()[0].grade subject = teacher.abilities.all()[0].subject hours = 5 coupon = None # ???? # TODO: ?????OrderManager??? new_order = Order.objects.create(parent, teacher, school, grade, subject, hours, coupon) # ??????? for student_type in range(3): response = client.get(reverse("teacher:my-students", kwargs={ "student_type": student_type, "page_offset": 1 })) self.assertEqual(response.status_code, 200)
def setUp(self): self.site = AdminSite() self.client = Client() self.factory = RequestFactory() # def test_spider_admin(self): # client = Client() # client.login(username='admin', password='pass') # base_admin = '/admin/driver27' # models = ['circuit', 'competition', 'driver', 'grandprix', 'race', 'season', 'seat', 'team'] # for model in models: # url = base_admin + '/' + model + '/' # resp = client.get(url, follow=True) # self.assertEqual(resp.status_code, 200, url + ' code='+str(resp.status_code)) # url = base_admin + '/' + model + '/add/' # resp = client.get(url, follow=True) # self.assertEqual(resp.status_code, 200, url + ' code='+str(resp.status_code)) # url = base_admin + '/' + model + '/1/change/' # resp = client.get(url, follow=True) # self.assertEqual(resp.status_code, 200, url + ' code='+str(resp.status_code))
def setUpTestData(cls): super().setUpTestData() cls.content = ContentFactory(visibility=Visibility.PUBLIC) cls.site = ContentFactory(visibility=Visibility.SITE) cls.selff = ContentFactory(visibility=Visibility.SELF) cls.limited = ContentFactory(visibility=Visibility.LIMITED) cls.user = UserFactory() cls.client = Client()
def setUpTestData(cls): super().setUpTestData() cls.user = PublicUserFactory() cls.content = ContentFactory(text="#tag") cls.tag_no_content = TagFactory(name="tagnocontent") cls.client = Client()
def test_kiosk_empty(self): c = Client() response = c.get('/kiosk/next_real') self.assertEqual(404, response.status_code)
def setUp(self): """Setup test case.""" self.c = Client() self.factory = RequestFactory() self.fake_title = 'Magna feugiat potenti erat.' self.fake_body = 'Euismod ad ac laoreet feugiat felis a vehicula.'
def setUp(self): self.client = Client()
def test_get_notify(self): client = Client() response = client.get('/paydirekt/notify/') self.assertEqual(response.status_code, 405)
def test_notify_callback_unknown_checkout(self): client = Client() post_data = {'checkoutId': '123-abc-notfound1', 'merchantOrderReferenceNumber': '123-abc-notfound1', 'checkoutStatus': 'OPEN'} response = client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') self.assertEqual(response.status_code, 400)
def test_known_checkout_unknown_at_paydirekt(self): client = Client() self._create_test_checkout(checkout_id='123-abc-notfound-paydirekt') post_data = {'checkoutId': '123-abc-notfound-paydirekt', 'merchantOrderReferenceNumber': '123-abc-notfound-paydirekt', 'checkoutStatus': 'APPROVED'} response = client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') self.assertEqual(response.status_code, 400)
def test_known_checkout_known_at_paydirekt_correct_status(self): client = Client() self._create_test_checkout(checkout_id='123-abc-approved') post_data = {'checkoutId': '123-abc-approved', 'merchantOrderReferenceNumber': '123-abc-approved', 'checkoutStatus': 'APPROVED'} response = client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') self.assertEqual(response.status_code, 200)
def test_known_checkout_known_at_paydirekt_correct_status_minimal(self): client = Client() self._create_test_checkout(checkout_id='123-abc-approved-minimal') post_data = {'checkoutId': '123-abc-approved-minimal', 'merchantOrderReferenceNumber': '123-abc-approved-minimal', 'checkoutStatus': 'APPROVED'} response = client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') self.assertEqual(response.status_code, 200)
def test_full_valid_order_checkout_full_with_notification(self): paydirekt_checkout = self._create_order() self.assertEqual(paydirekt_checkout.status, 'OPEN') self.assertEqual(paydirekt_checkout.total_amount, 100) test_customer = TestCustomer() test_customer.confirm_checkout(paydirekt_checkout) # give paydirekt time to approve time.sleep(10) client = Client() post_data = {'checkoutId': paydirekt_checkout.checkout_id, 'merchantOrderReferenceNumber': '', 'checkoutStatus': 'APPROVED'} client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') paydirekt_checkout.refresh_from_db() self.assertEqual(paydirekt_checkout.status, 'APPROVED')
def test_full_valid_direct_sale_checkout_full_with_notification(self): paydirekt_checkout = self._create_direct_sale() self.assertEqual(paydirekt_checkout.status, 'OPEN') self.assertEqual(paydirekt_checkout.total_amount, 100) test_customer = TestCustomer() test_customer.confirm_checkout(paydirekt_checkout) # give paydirekt time to approve time.sleep(10) client = Client() post_data = {'checkoutId': paydirekt_checkout.checkout_id, 'merchantOrderReferenceNumber': '', 'checkoutStatus': 'APPROVED'} client.post('/paydirekt/notify/', data=json.dumps(post_data), content_type='application/hal+json') paydirekt_checkout.refresh_from_db() self.assertEqual(paydirekt_checkout.status, 'APPROVED')
def setUp(self): self.user = User.objects.create_user(**fixtures['user']) self.client = Client()
def test_cache_in_request(client): assert isinstance(client, Client)
def test_get_tileset_info(self): c1 = dt.Client() ret = json.loads(c1.get('/api/v1/tileset_info/?d=bw').content.decode('utf-8'))
def test_upload_file(self): c = dt.Client() c.login(username='user1', password='pass') f = open('data/tiny.txt', 'rb') response = c.post( '/api/v1/tilesets/', { 'datafile': f, 'filetype': 'hitile', 'datatype': 'vector', 'uid': 'bb', 'private': 'True', 'coordSystem': 'hg19' }, format='multipart' ) if hss.UPLOAD_ENABLED: self.assertEqual(rfs.HTTP_201_CREATED, response.status_code) response = c.get('/api/v1/tilesets/') obj = tm.Tileset.objects.get(uuid='bb') # make sure the file was actually created self.assertTrue(op.exists, obj.datafile.url) else: self.assertEqual(403, response.status_code)
def test_stats_page(self): c = Client() c.login(username='test', password='test') response = c.get('/profile') # print(response.content)
def test_profile(self): c = Client() c.login(username='test', password='test') response = c.get('/profile') self.assertTemplateUsed(response, 'LL1_Academy/profile.html')
def setUp(self): """ Set up the test class. """ self.client = Client()
def test_index(self): client = Client() response = client.get('/herald/') self.assertContains(response, 'MyNotification')
def test_preview_text(self): client = Client() response = client.get('/herald/0/text/') self.assertContains(response, 'Hello World')
def test_preview_html(self): client = Client() response = client.get('/herald/0/html/') self.assertContains(response, '<html><body>Hello World</body></html>')
def test_company_home(self): client = Client() response = client.get(reverse('companies-home')) self.assertEqual(response.status_code, 200)
def test_company_creation(self): client = Client() response = client.post(reverse('companies-create'), {'name': 'jose', 'abn': '12312423422377777777', 'description': 'my description', 'logo': open('./android-icon.png')}) self.assertIn("Record succesfully created", response.content) num_companies = Company.objects.count() self.assertEqual(num_companies, 1) company = Company.objects.all()[0] self.assertEqual(company.name, "josej")