Python django.test.client 模块,Client() 实例源码

我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用django.test.client.Client()

项目:delft3d-gt-server    作者:openearth    | 项目源码 | 文件源码
def setUp(self):
        # set up client
        self.client = Client()

        # create users and store for later access
        self.user_foo = User.objects.create_user(
            username='foo', password="secret")

        # create Scene instance and assign permissions for user_foo
        self.scene = Scene.objects.create(
            suid="1be8dcc1-cf00-418c-9920-efa07b4fbeca",
            name="Test main workflow 1",
            owner=self.user_foo,
            shared="p",
            phase=Scene.phases.fin
        )

        self.user_foo.user_permissions.add(
            Permission.objects.get(codename='view_scene'))
        assign_perm('view_scene', self.user_foo, self.scene)
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def test_perf_database_render_no_instrumentation(benchmark, django_elasticapm_client):
    django_elasticapm_client.instrumentation_store.get_all()
    responses = []
    with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
        should_collect.return_value = False

        client = _TestClient()
        benchmark(lambda: responses.append(
            client_get(client, reverse("render-user-template"))
        ))

        for resp in responses:
            assert resp.status_code == 200

        transactions = django_elasticapm_client.instrumentation_store.get_all()
        assert len(transactions) == 0
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def test_perf_transaction_without_middleware(benchmark, django_elasticapm_client):
    django_elasticapm_client.instrumentation_store.get_all()
    with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
        should_collect.return_value = False
        client = _TestClient()
        django_elasticapm_client.events = []
        for i in range(10):
            resp = client_get(client, reverse("render-user-template"))
            assert resp.status_code == 200

        assert len(django_elasticapm_client.events) == 0

        @benchmark
        def result():
            # Code to be measured
            return client_get(client, reverse("render-user-template"))

        assert len(django_elasticapm_client.events) == 0
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def url_info(self, full_url):
    client = Client()
    info = []
    try:
        resp = client.get(full_url, follow = True)
    except Exception as e_status_code:
            self.error('Url: %s, error: %s' % (full_url, e_status_code))
            resp = type('object', (), {'status_code':0, 'content': str(e_status_code)})
    status_code = resp.status_code
    info.append(status_code)
    try:
        req = requests.get(full_url)
    except Exception as e_load_time:
            self.error('Url: %s, error: %s' % (full_url, e_load_time))
    load_time = req.elapsed
    info.append(load_time)
    return info
项目:daisychain    作者:daisychainme    | 项目源码 | 文件源码
def setUp(self):
        self.time = timezone.now()
        self.user = self.create_user()
        self.facebook_account = self.create_facebook_account(self.user)
        self.channel = FacebookChannel()
        self.channel_name = models.Channel.objects.get(name="Facebook").name
        self.channel_id = models.Channel.objects.get(name="Facebook").id
        self.client = Client()
        self.conditions = {'hashtag': '#me'}
        self.fields = 'message,actions,full_picture,picture,from,created_time,link,permalink_url,type,description,source,object_id'
        self.webhook_data = {
            "time": self.time,
            "id": "101915710270588",
            "changed_fields": ["statuses"],
            "uid": "101915710270588"
        }
项目:django-lock-tokens    作者:rparent    | 项目源码 | 文件源码
def test_view_decorators(self):
        c = Client()

        # Call a view that locks the object
        r = c.get(reverse('view-that-locks-object-1'), {
            'object_id': self.test_model_instance.id
        })
        self.assertEqual(r.status_code, 200)
        self.assertTrue(self.test_model_instance.is_locked())

        # Call another view that locks the object (same session)
        r = c.get(reverse('view-that-locks-object-2',
                          args=[self.test_model_instance.id]))
        self.assertEqual(r.status_code, 200)
        self.assertTrue(self.test_model_instance.is_locked())

        # Call a view that unlocks the object after execution
        r = c.get(reverse('view-that-unlocks-object',
                          args=[self.test_model_instance.id]))
        self.assertEqual(r.status_code, 200)
        self.assertFalse(self.test_model_instance.is_locked())
项目:djangocms-redirect    作者:nephila    | 项目源码 | 文件源码
def test_410_redirect(self):

        Redirect.objects.create(
            site=self.site,
            old_path=str(self.page1.get_absolute_url()),
            new_path='/en/',
            response_code='410',
        )

        client = Client()

        response = client.get('/en/test-page/')
        self.assertEqual(response.status_code, 410)

        Redirect.objects.create(
            site=self.site,
            old_path='/some-path/',
            response_code='302'
        )

        response2 = client.get('/some-path/')
        self.assertEqual(response2.status_code, 410)
项目:django-mapproxy    作者:terranodo    | 项目源码 | 文件源码
def setUp(self):
        super(DjmpTestBase, self).setUp()
        create_anonymous_user(None)

        self.user = 'admin'
        self.passwd = 'admin'
        self.client = Client()

        self.headers = {
            # TODO(mvv): these headers are specific to mvv's local env, that 
            #            may be bad long term
            'X-Script-Name': '/1/map/tms/1.0.0/test/EPSG3857/1/0/0.png',
            'HTTP_HOST': 'localhost:8000',
            'SERVER_NAME': 'michaels-macbook-pro-2.local',
            'X-Forwarded-Host': 'localhost:8000'
        }
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def setUpTestData(cls):
        super().setUpTestData()
        cls.content = LocalContentFactory(visibility=Visibility.PUBLIC)
        cls.private_content = LocalContentFactory(visibility=Visibility.LIMITED)
        cls.client = Client()
        cls.reply = PublicContentFactory(parent=cls.content)
        cls.share = PublicContentFactory(share_of=cls.content)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def admin_client(admin_user):
    """A Django test client logged in as an admin user."""
    from django.test.client import Client
    client = Client()
    client.login(username=admin_user.email, password='password')
    return client
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        make_basic_objects()
        # self.seen_links = set()
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        make_basic_objects()
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        self.db = make_basic_objects()
        self.new_cogclass = CognateClass.objects.create(alias="Y")
        self.new_source = Source.objects.create(citation_text="NEW SOURCE")
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        objects = make_basic_objects()
        # add additional objects here
        relation = SemanticRelation.objects.create(
                relation_code="R", long_name="RELATION")
        extension = SemanticExtension.objects.create(
                lexeme=objects[Lexeme],
                relation=relation)
        SemanticExtensionCitation.objects.create(
                extension=extension,
                source=objects[Source])
        self.seen_links = set()
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def setUp(self):
        user = User.objects.create_user('foo', password='pass')
        user.is_staff = True
        user.is_active = True
        user.save()
        self.client = Client()
        self.client.login(username=user.username, password='pass')
        get_queue('django_rq_test').connection.flushall()
项目:sga-lti    作者:mitodl    | 项目源码 | 文件源码
def setUp(self):
        """
        Common test setup
        """
        super(SGATestCase, self).setUp()
        self.client = Client()
        self.user_model = get_user_model()
        self.default_course = self.get_test_course()
项目:simplemooc    作者:paulopinda    | 项目源码 | 文件源码
def setUp(self):
        self.courses_django = mommy.make(
            'courses.Course', name='Python na Web com Django', _quantity=5)

        self.courses_dev = mommy.make(
            'courses.Course', name='Python para Devs', _quantity=10)

        self.client = Client()
项目:simplemooc    作者:paulopinda    | 项目源码 | 文件源码
def test_contact_form_error(self):
        data = {'name': 'Fulano de Tal', 'email': '', 'message': ''}
        client = Client()

        path = reverse('courses:details', args=[self.course.slug])
        response = client.post(path, data)

        self.assertFormError(
            response, 'form', 'email', 'Este campo é obrigatório.')

        self.assertFormError(
            response, 'form', 'message', 'Este campo é obrigatório.')
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def test_perf_transaction_with_collection(benchmark, django_elasticapm_client):
    django_elasticapm_client.instrumentation_store.get_all()
    with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
        should_collect.return_value = False
        django_elasticapm_client.events = []

        client = _TestClient()

        with override_settings(**middleware_setting(django.VERSION,
                                                    ['elasticapm.contrib.django.middleware.TracingMiddleware'])):
            for i in range(10):
                resp = client_get(client, reverse("render-user-template"))
                assert resp.status_code == 200

        assert len(django_elasticapm_client.events) == 0

        # Force collection on next request
        should_collect.return_value = True

        @benchmark
        def result():
            # Code to be measured
            return client_get(client, reverse("render-user-template"))

        assert result.status_code is 200
        assert len(django_elasticapm_client.events) > 0
项目:djabaas    作者:nnsnodnb    | 项目源码 | 文件源码
def test_url_index(self):
        c = Client()
        response = c.get('/')
        self.assertEqual(response.status_code, 302)
项目:djabaas    作者:nnsnodnb    | 项目源码 | 文件源码
def test_url_index_page(self):
        c = Client()
        response = c.get('/', {'page': 2})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.content, '')
项目:prestashop-sync    作者:dragoon    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
项目:cookiecutter-saas    作者:jayfk    | 项目源码 | 文件源码
def setUp(self):
        self.user = self.make_user()
        self.other_user = self.make_user(username="other_user")
        self.client = Client()
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def __init__(self, serializer=None):
        """
        Sets up a fresh ``TestApiClient`` instance.

        If you are employing a custom serializer, you can pass the class to the
        ``serializer=`` kwarg.
        """
        self.client = Client()
        self.serializer = serializer

        if not self.serializer:
            self.serializer = Serializer()
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def _login(self, username, password):
        client = Client()
        assert client.login(username=username, password=password)
        return client
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def _create_user_and_login(self, username="bob", password="bob"):
        self.login_username = username
        self.login_password = password
        self.user = self._create_user(username, password)

        # create user profile and set require_auth to false for tests
        profile, created = UserProfile.objects.get_or_create(user=self.user)
        profile.require_auth = False
        profile.save()

        self.client = self._login(username, password)
        self.anon = Client()
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def setup(self):
        self.client = Client()
        self.assertEqual(len(User.objects.all()), 0)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def _login(self, username, password):
        client = Client()
        assert client.login(username=username, password=password)
        return client
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def _create_user_and_login(self, username="bob", password="bob"):
        self.login_username = username
        self.login_password = password
        self.user = self._create_user(username, password)

        # create user profile and set require_auth to false for tests
        profile, created = UserProfile.objects.get_or_create(user=self.user)
        profile.require_auth = False
        profile.save()

        self.client = self._login(username, password)
        self.anon = Client()
项目:django-useraudit    作者:muccg    | 项目源码 | 文件源码
def test_login_is_logged(self):
        client = Client(REMOTE_ADDR='192.168.1.1', HTTP_USER_AGENT='Test client')
        client.post('/admin/login/', {
                    'username': 'john',
                    'password': 'sue',
                    'this_is_the_login_form': 1,
        })
        self.assertEquals(m.FailedLoginLog.objects.count(), 0)
        self.assertEquals(m.LoginLog.objects.count(), 1)
        log = m.LoginLog.objects.all()[0]
        self.assertEquals(log.username, 'john')
        self.assertTrue(is_recent(log.timestamp), 'Should have logged it recently')
        self.assertEquals(log.ip_address, '192.168.1.1')
        self.assertEquals(log.user_agent, 'Test client')
项目:django-useraudit    作者:muccg    | 项目源码 | 文件源码
def test_long_user_agent_is_truncated(self):
        user_agent_field_length = m.LoginLog._meta.get_field('user_agent').max_length
        long_user_agent = 'x' * (user_agent_field_length) + 'this should be truncated'

        client = Client(REMOTE_ADDR='192.168.1.1', HTTP_USER_AGENT=long_user_agent)
        client.post('/admin/login/', {
                    'username': 'john',
                    'password': 'sue',
                    'this_is_the_login_form': 1,
        })
        log = m.LoginLog.objects.all()[0]
        self.assertEquals(len(log.user_agent), user_agent_field_length)
        self.assertTrue(long_user_agent.startswith(log.user_agent))
项目:django-useraudit    作者:muccg    | 项目源码 | 文件源码
def test_ip_forwarded_by_proxies(self):
        client = Client(REMOTE_ADDR='3.3.3.3',
                        HTTP_X_FORWARDED_FOR='192.168.1.1, 1.1.1.1, 2.2.2.2')
        client.post('/admin/login/', {
                    'username': 'john',
                    'password': 'sue',
                    'this_is_the_login_form': 1,
        })
        log = m.LoginLog.objects.first()
        self.assertIsNotNone(log)
        self.assertEquals(log.ip_address, '192.168.1.1')
        self.assertEquals(log.forwarded_by, '3.3.3.3,2.2.2.2,1.1.1.1')
项目:daisychain    作者:daisychainme    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        self.user = self.create_user()
        self.user.save()
        self.trigger_channel = self.create_channel("Twitter")
        self.action_channel = self.trigger_channel
        self.trigger = self.create_trigger(channel=self.trigger_channel,
                                           trigger_type=200,
                                           name="New Image")
        self.action = self.create_action(channel=self.action_channel,
                                         action_type=200,
                                         name="Post Image")
        self.trigger_output = "image_data"
        self.trigger_input = self.create_trigger_input(trigger=self.trigger,
                                                       name="test input")
        self.action_input = self.create_action_input(self.action,
                                                     "image_data",
                                                     "image")
        self.recipe = self.create_recipe(self.trigger, self.action, self.user)
        self.recipe_mapping = self.create_recipe_mapping(
                self.recipe,
                self.trigger_output,
                self.action_input)
        self.recipe_condition = self.create_recipe_condition(
                self.recipe,
                self.trigger_input,
                "test value")
        self.payload = {"foo": "bar"}

        self.conditions_dict = {"test input": "test value"}
项目:daisychain    作者:daisychainme    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client()
        self.user = self.create_user()