• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python test.APIClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中rest_framework.test.APIClient的典型用法代码示例。如果您正苦于以下问题:Python APIClient类的具体用法?Python APIClient怎么用?Python APIClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了APIClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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')
开发者ID:123667,项目名称:readthedocs.org,代码行数:26,代码来源:test_api.py


示例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
开发者ID:RafaAguilar,项目名称:vaultier,代码行数:7,代码来源:nodes_api_test.py


示例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
开发者ID:Maxbey,项目名称:socialaggregator,代码行数:7,代码来源:helpers.py


示例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
开发者ID:Endika,项目名称:edx-platform,代码行数:7,代码来源:test_views.py


示例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
开发者ID:pipermerriam,项目名称:voldb,代码行数:7,代码来源:conftest.py


示例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":""}')
开发者ID:vipul-sharma20,项目名称:online-store,代码行数:7,代码来源:tests.py


示例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)
开发者ID:cognoma,项目名称:task-service,代码行数:25,代码来源:test_tasks.py


示例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)
开发者ID:Ian-Foote,项目名称:django-rest-framework,代码行数:7,代码来源:test_authentication.py


示例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)
开发者ID:Ian-Foote,项目名称:django-rest-framework,代码行数:7,代码来源:test_authentication.py


示例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)
开发者ID:heyandie,项目名称:studentassembly,代码行数:32,代码来源:tests.py


示例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])
开发者ID:zarautz,项目名称:pagoeta,代码行数:34,代码来源:tests.py


示例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'])
开发者ID:Amoki,项目名称:Amoki-Music,代码行数:7,代码来源:test_sources.py


示例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
开发者ID:jamesthechamp,项目名称:treeherder,代码行数:29,代码来源:test_failureline.py


示例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"])
开发者ID:Colin-Fredericks,项目名称:edx-platform,代码行数:33,代码来源:test_views.py


示例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)
开发者ID:TownHall,项目名称:TownHall,代码行数:28,代码来源:test.py


示例16: UserViewSetTestCase

class UserViewSetTestCase(APITestCase, TestCaseUtils):
    def setUp(self):
        self.client = APIClient()
        self.factory = APIRequestFactory()
        self.dev_user = User.objects.create_user("dev_user", "[email protected]", "123456")
        self.post_view = UserViewSet.as_view({"post": "create"})

        self.application = Application(
            name="Test Password Application",
            user=self.dev_user,
            client_type=Application.CLIENT_PUBLIC,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )
        self.application.save()

    def test_signup_new_user(self):
        new_user = {"grant_type": "password", "username": "test_user", "password": "123456"}
        auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
        response = self.client.post(reverse("user-list"), data=new_user, **auth_headers)
        self.assertEqual(User.objects.count(), 2)

    def test_signup_bad_request(self):
        new_user = {"grant_type": "password", "username": "test_user_2"}
        auth_headers = self.get_basic_auth_header(self.application.client_id, self.application.client_secret)
        response = self.client.post(reverse("user-list"), data=new_user, **auth_headers)
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def tearDown(self):
        self.application.delete()
        self.dev_user.delete()
开发者ID:alexacristina,项目名称:lab_ipp_2,代码行数:31,代码来源:tests.py


示例17: BaseDiscussionAclTests

class BaseDiscussionAclTests(TestCase):
    def setUp(self):
        self.category = CategoryFactory()
        self.user1 = UserFactory(
            email='[email protected]',
            password='pass',
            is_superuser=True,
            category=self.category
        )
        self.user2 = UserFactory(
            email='[email protected]',
            password='pass',
            category=self.category
        )
        self.user3 = UserFactory(email='[email protected]', password='pass')
        self.doc = DocumentFactory(
            category=self.category,
            revision={
                'leader': self.user1,
            }
        )
        self.client = APIClient()
        self.client.login(email=self.user1.email, password='pass')
        self.doc.latest_revision.start_review()
        self.discussion_list_url = reverse('note-list', args=[self.doc.document_key, 1])
开发者ID:andyjia,项目名称:phase,代码行数:25,代码来源:test_api.py


示例18: create_client

def create_client(user, url, get=True, kwargs=None):
    token = Token.objects.get_or_create(user=user)[0]
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
    if get:
        return client.get(url, kwargs=kwargs)
    return client.post(url, data=kwargs)
开发者ID:WALR,项目名称:OhMyCommand,代码行数:7,代码来源:test_api.py


示例19: test_bug_job_map_delete

def test_bug_job_map_delete(webapp, eleven_jobs_processed,
                            jm, mock_message_broker):
    """
    test retrieving a list of bug_job_map
    """
    client = APIClient()
    user = User.objects.create(username="MyName", is_staff=True)
    client.force_authenticate(user=user)

    job_id = jm.get_job_list(0, 1)[0]["id"]
    bug_id = random.randint(0, 100)

    jm.insert_bug_job_map(job_id, bug_id, "manual")

    pk = "{0}-{1}".format(job_id, bug_id)



    resp = client.delete(
        reverse("bug-job-map-detail", kwargs={
            "project": jm.project,
            "pk": pk
        })
    )

    user.delete()

    content = json.loads(resp.content)
    assert content == {"message": "Bug job map deleted"}

    jm.disconnect()
开发者ID:uberj,项目名称:treeherder-service,代码行数:31,代码来源:test_bug_job_map_api.py


示例20: test_anonymous

 def test_anonymous(self):
     """Verifies that an anonymous client cannot access the team
     dashboard, and is redirected to the login page."""
     anonymous_client = APIClient()
     response = anonymous_client.get(self.teams_url)
     redirect_url = '{0}?next={1}'.format(settings.LOGIN_URL, self.teams_url)
     self.assertRedirects(response, redirect_url)
开发者ID:vehery,项目名称:edx-platform,代码行数:7,代码来源:test_views.py



注:本文中的rest_framework.test.APIClient类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python test.APIRequestFactory类代码示例发布时间:2022-05-26
下一篇:
Python test.force_authenticate函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap