django.test.client.Client

Here are the examples of the python api django.test.client.Client taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

188 Examples 7

Example 1

Project: PiplMesh Source File: test_basic.py
    def setUp(self):
        self.user = backends.User.create_user(username=self.user_username, password=self.user_password)
        self.user2 = backends.User.create_user(username=self.user_username2, password=self.user_password2)

        self.client = client.Client()
        self.assertTrue(self.client.login(username=self.user_username, password=self.user_password))
        self.client2 = client.Client()
        self.assertTrue(self.client2.login(username=self.user_username2, password=self.user_password2))

        self.updates_data = []
        signals.post_send_update.connect(self._on_update, dispatch_uid='send-update')

Example 2

Project: django-roa Source File: tests.py
    def test_admin_views(self):
        remote_page1 = RemotePage.objects.create(title='A remote page')
        remote_page2 = RemotePage.objects.create(title='Another remote page')
        remote_page3 = RemotePage.objects.create(title='Yet another remote page')
        remote_page4 = RemotePage.objects.create(title='Still another remote page')
        bob = User.objects.create_superuser(username=u'bob', password=u'secret', email=u'[email protected]')
        bob = User.objects.get(username=u'bob')
        self.assertEqual(bob.is_superuser, True)
        c = Client()
        response = c.login(username=u'bob', password=u'secret')
        self.assertEqual(response, True)
        response = c.get('/admin/')
        # ._wrapped necessary because we compare string, comparison should
        # work with User.objects.get(username="bob") but slower...
        self.assertEqual(repr(response.context[-1]["user"]._wrapped), '<User: bob>')
        response = c.get('/admin/django_roa_client/remotepage/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(repr(response.context[-1]["cl"].result_list), '[<RemotePage: Still another remote page (4)>, <RemotePage: Yet another remote page (3)>]')
        self.assertEqual(response.context[-1]["cl"].result_count, 4)

Example 3

Project: django-maintenancemode Source File: tests.py
    def test_middleware_with_internal_ips_range(self):
        client = Client(REMOTE_ADDR='10.10.10.1')

        with self.settings(MAINTENANCE_MODE=True, INTERNAL_IPS=('10.10.10.0/24', )):
            response = client.get('/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)

Example 4

Project: django-rq Source File: tests.py
    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()

Example 5

Project: tendenci Source File: test_public_actions.py
    def setUp(self):
        """
        Create a queue & ticket we can use for later tests.
        """
        self.queue = Queue.objects.create(title='Queue 1', slug='q', allow_public_submission=True, new_ticket_cc='[email protected]', updated_ticket_cc='[email protected]')
        self.ticket = Ticket.objects.create(title='Test Ticket', queue=self.queue, submitter_email='[email protected]', description='This is a test ticket.')

        self.client = Client()

Example 6

Project: roundware-server Source File: test_commands.py
    def test_func_get_available_assets_pass_multiple_asset_ids_POST(self):
        """ make sure response includes proper JSON using a Client request
        """
        cl = Client()
        req_dict = {'operation': 'get_available_assets',
                    'asset_id': '1,2', 'project_id': '2', 'tagids': '2,3'}
        # f_set = cl.encode_multipart(req_dict)
        response = cl.post('/api/1/', req_dict)
        self.assertEquals(200, response.status_code)
        js = json.loads(response.content)
        self.assertEqual(2, js['number_of_assets']['audio'])
        self.assertEqual(0, js['number_of_assets']['photo'])
        self.assertEqual(0, js['number_of_assets']['video'])
        self.assertEqual(0, js['number_of_assets']['text'])
        self.assertEqual([dict(self.ASSET_1.items() +
                               self.ASSET_1_TAGS_EN.items()),

                          dict(self.ASSET_2.items() +
                               self.ASSET_2_TAGS_ES.items())], js['assets'])

Example 7

Project: django-goflow Source File: tests.py
Function: test_details
    def test_details(self):
        client = Client()
        ok = client.login(username='primus', password='bad_passwd')
        self.assertFalse(ok, 'authentication ko')
        ok = client.login(username='primus', password='p')
        self.assertTrue(ok, 'authentication ok')
        
        ok = client.login(username='admin', password='open')
        self.assertTrue(ok, 'authentication ok')
        response = client.get('/leave/admin/')
        self.failUnlessEqual(response.status_code, 200)
        client.logout()

Example 8

Project: Rhetoric Source File: __init__.py
    def setUp(self):
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.testapp.testapp.settings")

        from django.test.client import Client
        from tests.testapp.testapp.wsgi import application
        import rhetoric


        DEFAULT_HEADERS = {
            'X-API-VERSION': '1.0'
        }
        self.client = Client(**DEFAULT_HEADERS)
        self.rhetoric = rhetoric
        self.wsgi_app = application

Example 9

Project: django-articles Source File: tests.py
    def setUp(self):
        self.client = Client()

        status = ArticleStatus.objects.filter(is_live=True)[0]
        self.new_article('This is a test!', 'Testing testing 1 2 3',
                         tags=Tag.objects.all(), status=status)

Example 10

Project: qualitio Source File: views.py
Function: set_up
    def setUp(self):
        self.addTestApps(['core.tests.testapp'])

        User.objects.create_user('john', '[email protected]', 'johnpassword')

        self.client = Client()
        self.client.login(username='john', password='johnpassword')

Example 11

Project: transifex Source File: status.py
Function: test_status_code
    def testStatusCode(self):
        """Test that the response status code is correct"""

        client = Client()
        for expected_code, pages in self.pages.items():
            for page_url in pages:
                page = client.get(page_url)
                self.assertEquals(page.status_code, expected_code,
                    "Status code for page '%s' was %s instead of %s" %
                    (page_url, page.status_code, expected_code))

Example 12

Project: django-permissionsx Source File: utils.py
    def setUp(self):
        self.session_backend = SessionStore()
        self.session_middleware = SessionMiddleware()
        self.factory = RequestFactory()
        self.user = self.create_user('user')
        self.owner = self.create_user('owner')
        self.admin = self.create_user('admin', is_superuser=True)
        self.staff = self.create_user('staff', is_staff=True)
        self.client = Client()

Example 13

Project: Open-Data-Catalog Source File: tests.py
    def setUp(self):
        self.c = Client()
        self.password = "password"
        self.u = User.objects.create(username="testuser")
        self.u.set_password(self.password)
        self.u.save()

        self.u2 = User.objects.create(username="testuser2")
        self.u2.set_password(self.password)
        self.u2.save()

Example 14

Project: kala-app Source File: view_tests.py
Function: set_up
    def setUp(self):
        self.client = Client()
        self.person = PersonFactory(is_active=True)
        self.person.set_password('test')
        self.person.save()
        self.client = Client()
        self.client.login(username=self.person.username, password='test')

Example 15

Project: vumi-go Source File: test_views.py
Function: test_csrf_protect
    def test_csrf_protect(self):
        user = self.user_helper.get_django_user()
        client = Client(
            username=user.email,
            password=user.password,
            enforce_csrf_checks=True)
        task = self.create_task('Test task')
        r = client.post(
            reverse('scheduler:delete_task', kwargs={'pk': task.pk}))
        self.assertContains(r, 'CSRF verification failed.', status_code=403)

Example 16

Project: djangolint Source File: __init__.py
Function: set_up
    def setUp(self):
        self.qs = Commit.objects.filter(
            hash='2e7be88382545a9dc7a05b9d2e85a7041e311075',
            repo_name='test', repo_user='xobb1t'
        )
        with open(PAYLOAD_PATH) as f:
            self.payload = f.read()
        self.client = Client()
        self.task_patcher = mock.patch('webhooks.views.process_commit')
        self.process_commit = self.task_patcher.start()

Example 17

Project: django-dumper Source File: test_full_stack.py
Function: set_up
    def setUp(self):
        self.c = Client()
        self.instance = self.model.objects.create()
        self.url = self.instance.get_absolute_url()
        self.access_instance = lambda: self.c.get(self.url)

        def assert_responses_not_equal(first, second):
            return self.assertNotEqual(first.content, second.content)
        self.assert_responses_not_equal = assert_responses_not_equal

Example 18

Project: canvas Source File: tests.py
Function: test_valid
    def test_valid(self):
        auth_headers = {
            'HTTP_AUTHORIZATION': 'Basic '
                + base64.b64encode('{}:{}'.format(self.user.username, PASSWORD)),
        }
        c = Client()
        response = c.get('/feed', **auth_headers)
        self.assertEqual(200, response.status_code)

Example 19

Project: django-likes Source File: test_views.py
    @classmethod
    def setUpClass(cls):
        secretballot.enable_voting_on(TestModel)
        cls.client = Client()
        cls.obj1 = TestModel.objects.create()
        cls.obj2 = TestModel.objects.create()

Example 20

Project: splinter Source File: djangoclient.py
Function: init
    def __init__(self, user_agent=None, wait_time=2, **kwargs):
        from django.test.client import Client
        self._custom_headers = kwargs.pop('custom_headers', {})

        client_kwargs = {}
        for key, value in six.iteritems(kwargs):
            if key.startswith('client_'):
                client_kwargs[key.replace('client_', '')] = value

        self._browser = Client(**client_kwargs)
        self._user_agent = user_agent
        self._cookie_manager = CookieManager(self._browser.cookies)
        super(DjangoClient, self).__init__(wait_time=wait_time)

Example 21

Project: django-treebeard Source File: conftest.py
Function: pytest_funcarg_client
def pytest_funcarg__client(request):
    def setup():
        mail.outbox = []
        return Client()

    def teardown(client):
        call_command('flush', verbosity=0, interactive=False)

    return request.cached_setup(setup, teardown, 'function')

Example 22

Project: Tangaza Source File: tests.py
    def setUp(self):
        self.invalid_member = '222111333'
        self.valid_member = '254777888999'
        self.lang = utility.LanguageFactory.create_language('eng')
        self.member = Watumiaji.objects.get(name_text = 'rodrigo')
        self.c = Client()

Example 23

Project: django-simple-autocomplete Source File: test_it.py
    def setUp(self):
        self.adam = User.objects.create_user(
            'adam', '[email protected]', 'password'
        )
        self.eve = User.objects.create_user('eve', '[email protected]', 'password')
        self.andre = User.objects.create_user(
            'andré', '[email protected]', 'password'
        )

        self.dummy = DummyModel()
        self.dummy.save()
        self.client = Client()
        self.request = RequestFactory()

Example 24

Project: django-unsubscribe Source File: test_core.py
    def test_list_unsubscribe_view(self):
        closure_test = [0]

        def test_callback(sender, user, **kwargs):
            closure_test[0] = 1

        from unsubscribe.signals import user_unsubscribed
        user_unsubscribed.connect(test_callback)

        from django.test.client import Client
        c = Client()
        url = reverse('unsubscribe_unsubscribe',
                      args=(self.user.pk, get_token_for_user(self.user)))
        c.get(url)
        self.assertTrue(closure_test[0])

Example 25

Project: rapidsms-core-dev Source File: test_views.py
Function: test_log_in
def test_login():
    c = Client()
    login_url = reverse("rapidsms.views.login")

    # check that the login form is displayed.
    response = c.get(login_url)
    assert_equals(response.status_code, 200)

    # check that visitors can log in successfully.
    u = User.objects.create_user("testuser", "[email protected]", "testpass")
    response = c.post(login_url, {'username': "testuser", 'password': "testpass"})
    assert_equals(response.status_code, 302)

    # clean up.
    u.delete()

Example 26

Project: sublimall-server Source File: tests.py
Function: set_up
    def setUp(self):
        self.member = Member(email="[email protected]")
        self.member.set_password('foobar')
        self.member.save()

        self.c = Client()

Example 27

Project: RatticWeb Source File: tests.py
Function: set_up
    def setUp(self):
        self.client = Client()
        self.tmpdir = tempfile.mkdtemp()
        self.homefile = os.path.join(self.tmpdir, 'Home.md')
        self.testfile = os.path.join(self.tmpdir, 'Test.md')
        with open(self.homefile, 'w') as f:
            f.write("# Heading 1")
        with open(self.testfile, 'w') as f:
            f.write("[[Test Link]]")

Example 28

Project: dojopuzzles Source File: view_test.py
    def test_nenhum_problema_utilizado(self):
        """
        Se nenhum problema foi utilizado ainda, não deve exibir nenhuma
        informação referente a problemas utilizados.
        """
        problema1 = novo_problema({})
        problema2 = novo_problema({})
        client = Client()
        response = client.get(reverse('inicio'))
        self.assertNotContains(response, u"Os problemas deste site já foram utilizados")

Example 29

Project: django-cached_authentication_middleware Source File: tests.py
    @override_settings(CACHED_AUTH_PREPROCESSOR='test_project.utils.auth_preprocessor')
    def test_cached_auth_preprocessor_function(self):
        reload(cached_auth)
        client = Client()
        key = cached_auth.CACHE_KEY % self.user.id
        self.assertEqual(cache.get(key), None)

        client.login(username='test', password='a')
        client.get(reverse('admin:index'))
        user = cache.get(key)
        self.assertEqual(user.username, 'test_auth')

Example 30

Project: molo Source File: test_search.py
    def setUp(self):
        self.client = Client()
        # Creates Main language
        self.english = SiteLanguage.objects.create(
            locale='en',
        )
        # Creates translation Language
        self.french = SiteLanguage.objects.create(
            locale='fr',
        )
        self.mk_main()

        # Creates a section under the index page
        self.english_section = self.mk_section(
            self.section_index, title='English section')

Example 31

Project: pytest_django Source File: plugin.py
def pytest_funcarg__admin_client(request):
    """
    Returns a Django test client logged in as an admin user.
    """
    try:
        User.objects.get(username='admin')
    except User.DoesNotExist:
        user = User.objects.create_user('admin', '[email protected]', 
                                        'password')
        user.is_staff = True
        user.is_superuser = True
        user.save()
        
    client = Client()
    client.login(username='admin', password='password')
    
    return client    

Example 32

Project: folivora Source File: tests.py
    def test_set_user_lang(self):
        self.c = Client()
        user = User.objects.get(username='apollo13')
        profile = user.get_profile()
        profile.language = 'at'
        profile.timezone = 'Europe/Vienna'
        profile.save()
        self.c.login(username='apollo13', password='pwd')
        self.assertEqual(self.c.session['django_language'], 'at')
        self.assertEqual(self.c.session['django_timezone'], 'Europe/Vienna')
        profile.delete()
        # Even without a profile login shouldn't throw errors.
        self.c.login(username='apollo13', password='pwd')

Example 33

Project: django-tastypie-mongoengine Source File: test_runner.py
def client_patch(self, path, data=None, content_type=client.MULTIPART_CONTENT, follow=False, **extra):
    """
    Send a resource to the server using PATCH.
    """

    data = data or {}
    response = super(client.Client, self).patch(path, data=data, content_type=content_type, **extra)
    if follow:
        response = self._handle_redirects(response, **extra)
    return response

Example 34

Project: symposion Source File: test_views.py
    def test_populated_empty_presentations(self):

        factories.SlotFactory.create_batch(size=5)

        c = Client()
        r = c.get('/conference.json')
        assert r.status_code == 200

        conference = json.loads(r.content)
        assert 'schedule' in conference
        assert len(conference['schedule']) == 5

Example 35

Project: devil Source File: tests.py
    def test_my_mapper(self):
        client = Client()
        response = client.put(
            '/simple/mapper/reverse',
            'reppam ,olleh',
            'text/plain')
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response['Content-Type'], 'text/plain; charset=utf-8')
        self.assertEquals(testurls.mapperresource.last_data, 'hello, mapper')
        self.assertEquals(response.content, '')

Example 36

Project: django-cms-redirects Source File: tests.py
    def test_302_page_redirect(self):
        r_302_page = CMSRedirect(site=self.site, page=self.page, old_path='/302_page.php', response_code='302')
        r_302_page.save()

        c = Client()
        r = c.get('/302_page.php')
        self.assertEqual(r.status_code, 302)
        self.assertEqual(r._headers['location'][1], 'http://testserver/')

Example 37

Project: django-goflow Source File: tests.py
    def test_otherswork_anonymous(self):
        client = Client()
        response = client.get('/leave/otherswork/', {'worker':'primus'})
        self.failUnlessEqual(response.status_code, 200)
        response = client.get('/leave/otherswork/', {'worker':'secundus'})
        self.failUnlessEqual(response.status_code, 200)
        response = client.get('/leave/otherswork/', {'worker':'tertius'})
        self.failUnlessEqual(response.status_code, 200)

Example 38

Project: vumi-go Source File: test_views.py
Function: test_csrf_protect
    def test_csrf_protect(self):
        user = self.user_helper.get_django_user()
        client = Client(
            username=user.email,
            password=user.password,
            enforce_csrf_checks=True)
        task = self.create_task('Test task')
        r = client.post(
            reverse('scheduler:reactivate_task', kwargs={'pk': task.pk}))
        self.assertContains(r, 'CSRF verification failed.', status_code=403)

Example 39

Project: django-comps Source File: test_views.py
    def setUp(self):
        self.client = Client()
        #setup testing template path
        cwd = os.path.dirname(__file__)
        path_parts = cwd.split(os.sep)[:-1]
        base_path = os.path.join(*path_parts)
        settings.COMPS_DIR = os.path.join(os.sep, base_path,
                                         'templates', 'comps_test')

Example 40

Project: mybitbank Source File: tests.py
Function: test_login_success
    def test_login_success(self):
        '''
        Test login success
        '''
        
        client = Client()
        # client.login(username='testing', password='testingpassword')
        
        post_data = {
                    'username': "testing",
                    'password': "testingpassword",
                    'csrfmiddlewaretoken': "",
                    }
        
        response = client.post(reverse('login:processLogin'), post_data)
        self.assertContains(response, text='', count=None, status_code=302)

Example 41

Project: rolf Source File: test_views.py
    def setUp(self):
        self.c = Client()
        self.u = UserFactory()
        self.u.set_password("test")
        self.u.save()
        self.c.login(username=self.u.username, password="test")

Example 42

Project: django-activity-stream Source File: tests.py
    def test_cascaded_delete(self):
        c = Client()
        c.login(username='admin', password='localhost')
        photo = TestSubject.objects.create(test=True)
        photo2 = TestSubject.objects.create(test=True)
        activityItem = create_activity_item("placed", User.objects.get(username="admin"), photo)
        activityItem.delete()
        self.assertTrue(TestSubject.objects.get(pk=photo.id))

        activityItem2 = create_activity_item("placed", User.objects.get(username="admin"), photo2)
        items = users_activity_stream({}, User.objects.get(username="admin"),1000)
        self.assertEquals(len(items['activity_items']), 1)

        photo2.delete()

        items = users_activity_stream({}, User.objects.get(username="admin"),1000)
        self.assertEquals(len(items['activity_items']), 0)

Example 43

Project: write-it Source File: home_view_tests.py
    def test_list_instances_view(self):
        '''All instances are displayed in home'''
        for instance in WriteItInstance.objects.all():
            instance.config.testing_mode = False
            instance.config.save()
        url = reverse('instance_list')
        self.assertTrue(url)
        c = Client()
        response = c.get(url)
        self.assertEquals(response.status_code, 200)
        self.assertIn('object_list', response.context)
        self.assertIsInstance(response.context['object_list'][0], WriteItInstance)
        self.assertEquals(len(response.context['object_list']), WriteItInstance.objects.count())

        self.assertTemplateUsed(response, 'nuntium/template_list.html')

Example 44

Project: django-shibboleth Source File: test_shibboleth.py
Function: test_valid_attributes
    def test_valid_attributes(self):
        client = Client()
        response = client.post('/login',
                              HTTP_SHIB_IDENTITY_PROVIDER='idp.test.com',
                              HTTP_SHIB_SHARED_TOKEN='3ho9qqthnbj0q0OE',
                              HTTP_SHIB_CN="Joe Blog",
                              HTTP_SHIB_MAIL="[email protected]",
                              HTTP_SHIB_GIVENNAME="Joesph",
                              HTTP_SHIB_SN="Blog",
            )
        self.assertEqual(302, response.status_code, response.content)
        self.assertEqual("http://testserver/success", response["location"])

Example 45

Project: pytest-django Source File: fixtures.py
@pytest.fixture()
def admin_client(db, 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.username, password='password')
    return client

Example 46

Project: talk.org Source File: testcases.py
Function: call
    def __call__(self, result=None):
        """
        Wrapper around default __call__ method to perform common Django test
        set up. This means that user-defined Test Cases aren't required to
        include a call to super().setUp().
        """
        self.client = Client()
        try:
            self._pre_setup()
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            import sys
            result.addError(self, sys.exc_info())
            return
        super(TestCase, self).__call__(result)

Example 47

Project: django-audit-log Source File: test_logging.py
    def test_fields(self):
        c = Client()
        self.run_client(c)
        owner = PropertyOwner.objects.get(pk = 1)
        prop = Property.objects.get(pk = 1)
        self.assertEqual(prop.audit_log.all()[0]._meta.get_field('owned_by').__class__, models.ForeignKey)

Example 48

Project: jmbo Source File: __init__.py
    @classmethod
    def setUpClass(cls):
        cls.request = RequestFactory()
        cls.request.method = 'GET'
        cls.request._path = '/'
        cls.request.get_full_path = lambda: cls.request._path
        cls.client = Client()

        # Add an extra site
        site, dc = Site.objects.get_or_create(id=4, name='another', domain='another.com')

Example 49

Project: django-emailauth Source File: tests.py
Function: test_login_fail
    def testLoginFail(self):
        user, user_email = self.createActiveUser()
        client = Client()
        response = client.post('/login/', {
            'email': '[email protected]',
            'password': 'wrongpassword',
        })
        self.assertStatusCode(response, Status.OK)

Example 50

Project: overmind Source File: test_provisioning.py
    def setUp(self):
        self.path = "/api/providers/"

        op = Group.objects.get(name='Operator')
        self.user = User.objects.create_user(
            username='testuser', email='[email protected]', password='test1')
        self.user.groups.add(op)
        self.user.save()

        self.client = Client()
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4