Python django.test.RequestFactory() Examples

The following are 30 code examples for showing how to use django.test.RequestFactory(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.test , or try the search function .

Example 1
Project: figures   Author: appsembler   File: test_figures_home_view.py    License: MIT License 6 votes vote down vote up
def setup(self, db):
        self.factory = RequestFactory()
        self.callers = create_test_users()
        self.callers.append(
            UserFactory(username='inactive_regular_user',
                is_active=False))
        self.callers.append(
            UserFactory(username='inactive_staff_user',
                is_active=False, is_staff=True))
        self.callers.append(
            UserFactory(username='inactive_super_user',
                is_active=False, is_superuser=True))
        self.callers.append(
            UserFactory(username='inactive_superstaff_user',
                is_active=False, is_staff=True, is_superuser=True))
        self.redirect_startswith = '/accounts/login/?next=' 
Example 2
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: test_views.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.test_user = UserModel.objects.create_user(
            "test_user", "test@example.com", "123456")
        self.dev_user = UserModel.objects.create_user(
            "dev_user", "dev@example.com", "123456")

        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()

        oauth2_settings._SCOPES = ["read", "write"]
        oauth2_settings._DEFAULT_SCOPES = ["read", "write"] 
Example 3
Project: donation-tracker   Author: GamesDoneQuick   File: test_speedrun.py    License: Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.sessions = SessionMiddleware()
        self.messages = MessageMiddleware()
        self.event1 = models.Event.objects.create(
            datetime=today_noon,
            targetamount=5,
            timezone=pytz.timezone(getattr(settings, 'TIME_ZONE', 'America/Denver')),
        )
        self.run1 = models.SpeedRun.objects.create(
            name='Test Run 1', run_time='0:45:00', setup_time='0:05:00', order=1
        )
        self.run2 = models.SpeedRun.objects.create(
            name='Test Run 2', run_time='0:15:00', setup_time='0:05:00', order=2
        )
        if not User.objects.filter(username='admin').exists():
            User.objects.create_superuser('admin', 'nobody@example.com', 'password') 
Example 4
Project: arches   Author: archesproject   File: auth_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def setUpClass(cls):
        cls.factory = RequestFactory()
        cls.client = Client()
        cls.user = User.objects.create_user("test", "test@archesproject.org", "password")

        rdm_admin_group = Group.objects.get(name="RDM Administrator")
        cls.user.groups.add(rdm_admin_group)
        cls.anonymous_user = User.objects.get(username="anonymous")

        cls.token = "abc"
        cls.oauth_client_id = OAUTH_CLIENT_ID
        cls.oauth_client_secret = OAUTH_CLIENT_SECRET

        sql_str = CREATE_TOKEN_SQL.format(token=cls.token, user_id=cls.user.pk)
        cursor = connection.cursor()
        cursor.execute(sql_str) 
Example 5
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: ISC License 6 votes vote down vote up
def test_add_participants(self):
        # by default, a user will be authorized to add a participant if they are not yet in the thread
        # we add new and existing participants
        request = RequestFactory()
        request.user = self.user
        request.rest_messaging_participant = Participant.objects.get(id=self.user.id)
        self.assertTrue(all(participant in [self.participant1, self.participant2, self.participant3] for participant in self.thread1.participants.all()))
        self.assertEqual(3, len(self.thread1.participants.all()))
        with self.assertNumQueries(2):
            self.thread1.add_participants(request, self.participant4.id, self.participant5.id)
        self.assertTrue(all(participant in [self.participant1, self.participant2, self.participant3, self.participant4, self.participant5] for participant in self.thread1.participants.all()))
        self.assertEqual(5, len(self.thread1.participants.all()))
        # by default, the number of participants is limited to 10
        l = []
        for i in range(7, 16):  # setUp ends at 6
            l.append(Participant(id=i))
        Participant.objects.bulk_create(l)
        self.thread1.add_participants(request, *[p.id for p in l])
        self.assertEqual(10, len(self.thread1.participants.all())) 
Example 6
Project: django-rest-framework-httpsignature   Author: etoccalino   File: tests.py    License: MIT License 6 votes vote down vote up
def test_can_authenticate(self):
        headers = ['(request-target)', 'accept', 'date', 'host']
        expected_signature = 'SelruOP39OWoJrSopfYJ99zOLoswmpyGXyDPdebeELc='
        expected_signature_string = build_signature(
            headers,
            key_id=KEYID,
            signature=expected_signature)
        request = RequestFactory().get(
            '/packages/measures/', {},
            HTTP_ACCEPT='application/json',
            HTTP_DATE='Mon, 17 Feb 2014 06:11:05 GMT',
            HTTP_HOST='localhost:8000',
            HTTP_AUTHORIZATION=expected_signature_string,
            HTTP_X_API_KEY=KEYID)

        result = self.auth.authenticate(request)
        self.assertIsNotNone(result)
        self.assertEqual(result[0], self.test_user)
        self.assertEqual(result[1], KEYID) 
Example 7
Project: kobo-predict   Author: awemulya   File: test_form_enter_data.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_public_with_link_to_share_toggle_on(self):
        # sharing behavior as of 09/13/2012:
        # it requires both data_share and form_share both turned on
        # in order to grant anon access to form uploading
        # TODO: findout 'for_user': 'all' and what it means
        response = self.client.post(self.perm_url, {'for_user': 'all',
                                    'perm_type': 'link'})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(MetaData.public_link(self.xform), True)
        # toggle shared on
        self.xform.shared = True
        self.xform.shared_data = True
        self.xform.save()
        response = self.anon.get(self.show_url)
        self.assertEqual(response.status_code, 302)
        if not self._running_enketo():
            raise SkipTest
        with HTTMock(enketo_mock):
            factory = RequestFactory()
            request = factory.get('/')
            request.user = AnonymousUser()
            response = enter_data(
                request, self.user.username, self.xform.id_string)
            self.assertEqual(response.status_code, 302) 
Example 8
Project: kobo-predict   Author: awemulya   File: test_briefcase_client.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def form_list_xml(url, request, **kwargs):
    response = requests.Response()
    factory = RequestFactory()
    req = factory.get(url.path)
    req.user = authenticate(username='bob', password='bob')
    req.user.profile.require_auth = False
    req.user.profile.save()
    id_string = 'transportation_2011_07_25'
    if url.path.endswith('formList'):
        res = formList(req, username='bob')
    elif url.path.endswith('form.xml'):
        res = download_xform(req, username='bob', id_string=id_string)
    elif url.path.find('xformsManifest') > -1:
        res = xformsManifest(req, username='bob', id_string=id_string)
    elif url.path.find('formid-media') > -1:
        data_id = url.path[url.path.rfind('/') + 1:]
        res = download_media_data(
            req, username='bob', id_string=id_string, data_id=data_id)
        response._content = get_streaming_content(res)
    else:
        res = formList(req, username='bob')
    response.status_code = 200
    if not response._content:
        response._content = res.content
    return response 
Example 9
def setUp(self):
        cache.clear()
        self.factory = RequestFactory()
        self.operator = self._create_operator() 
Example 10
Project: Servo   Author: fpsw   File: test_forms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_customer(self):
        factory = RequestFactory()
        request = factory.get('/checkin/')
        request.user = AnonymousUser
        request = add_middleware_to_request(request, SessionMiddleware)
        #form = CustomerForm(request) 
Example 11
Project: OpenMDM   Author: OpenMDM   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='John Doe',
            email='',
            password='test')
        self.c = Client() 
Example 12
Project: django-pusherable   Author: pusher   File: test_example.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='pusher', email='pusher@example.com', password='hunter2'
        )
        self.object = PusherableExample.objects.create(
            text = "This is a test PusherableExample object"
        ) 
Example 13
Project: normandy   Author: mozilla   File: test_auth_backends.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_log_failure_username(self, mock_logger, mock_authenticate):
        mock_authenticate.return_value = None
        request = RequestFactory().get("/")
        user = LoggingModelBackend().authenticate(
            request, username="fakeuser", password="does.not.exist"
        )
        assert user is None
        mock_logger.warning.assert_called_with(
            Whatever.contains("fakeuser"), extra={"code": WARNING_LOGIN_FAILURE}
        ) 
Example 14
Project: normandy   Author: mozilla   File: test_auth_backends.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_log_failure_no_username(self, mock_logger, mock_authenticate):
        mock_authenticate.return_value = None
        request = RequestFactory().get("/")
        user = LoggingModelBackend().authenticate(request, password="does.not.exist")
        assert user is None
        mock_logger.warning.assert_called_with(
            Whatever.contains("no username provided"), extra={"code": WARNING_LOGIN_FAILURE}
        ) 
Example 15
Project: normandy   Author: mozilla   File: test_auth_backends.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_log_success(self, mock_logger, mock_authenticate):
        mock_authenticate.return_value = True
        request = RequestFactory().get("/")
        user = LoggingModelBackend().authenticate(
            request, username="fakeuser", password="does.not.exist"
        )
        assert user
        mock_logger.info.assert_called_with(
            Whatever.contains("fakeuser"), extra={"code": INFO_LOGIN_SUCCESS}
        ) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.rand = random.Random()
        self.factory = RequestFactory()
        self.locked_event = models.Event.objects.create(
            datetime=long_ago_noon, targetamount=5, short='locked', name='Locked Event'
        )
        self.event = models.Event.objects.create(
            datetime=today_noon, targetamount=5, short='event', name='Test Event'
        )
        self.anonymous_user = AnonymousUser()
        self.user = User.objects.create(username='test')
        self.add_user = User.objects.create(username='add')
        self.locked_user = User.objects.create(username='locked')
        self.locked_user.user_permissions.add(
            Permission.objects.get(name='Can edit locked events')
        )
        if self.model_name:
            self.add_user.user_permissions.add(
                Permission.objects.get(name='Can add %s' % self.model_name),
                Permission.objects.get(name='Can change %s' % self.model_name),
            )
            self.locked_user.user_permissions.add(
                Permission.objects.get(name='Can add %s' % self.model_name),
                Permission.objects.get(name='Can change %s' % self.model_name),
            )
        self.super_user = User.objects.create(username='super', is_superuser=True)
        self.maxDiff = None 
Example 17
Project: donation-tracker   Author: GamesDoneQuick   File: test_forms.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory() 
Example 18
Project: donation-tracker   Author: GamesDoneQuick   File: test_auth.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory() 
Example 19
Project: ideascube   Author: ideascube   File: test_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def build_request(target="http://example.org", verb="get", **kwargs):
    defaults = {
        'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
        'HTTP_REFERER': 'http://testserver/path/'
    }
    defaults.update(kwargs)
    func = getattr(RequestFactory(**defaults), verb)
    return func('/', {'url': target}) 
Example 20
Project: django-mptt-comments   Author: zmrenwu   File: test_views.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='test', email='test@test.com', password='test') 
Example 21
Project: django-mptt-comments   Author: zmrenwu   File: test_views.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='test', email='test@test.com', password='test')
        site = Site.objects.create(name='test', domain='test.com')
        self.comment = MPTTComment.objects.create(**{
            'content_type': ContentType.objects.get_for_model(site),
            'object_pk': site.pk,
            'site': site,
            'user': self.user,
            'comment': 'test comment',
        }) 
Example 22
Project: wagtail-schema.org   Author: neon-jungle   File: test_templates.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        super().setUp()

        self.factory = RequestFactory()
        self.request = self.factory.get('/test/')
        self.request.site = self.site 
Example 23
Project: django-rest-messaging   Author: raphaelgyory   File: test_middleware.py    License: ISC License 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get('/')
        self.request.user = User.objects.create(username='User')
        # we say the user is authenticated
        self.request.user.is_authenticated = lambda *args, **kwargs: True
        self.middleware = MessagingMiddleware() 
Example 24
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: ISC License 5 votes vote down vote up
def test_add_participants_callback(self):
        # this can be overriden
        request = RequestFactory()
        request.user = self.user
        request.rest_messaging_participant = Participant.objects.get(id=self.user.id)
        self.assertTrue(all(participant in [self.participant1, self.participant2, self.participant3] for participant in self.thread1.participants.all()))
        self.assertEqual(3, len(self.thread1.participants.all()))
        self.thread1.add_participants(request, self.participant4, self.participant5)
        # the count did not change
        self.assertEqual(3, len(self.thread1.participants.all())) 
Example 25
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: ISC License 5 votes vote down vote up
def remove_participant(self):
        # we need a request to use request.user
        # by default, a user will be authorized to add a participant if he himself is a participant
        request = RequestFactory()
        request.user = self.user
        # user 1 cannot remove another participant
        self.assertRaises(Exception, self.thread1.remove_participant, request, self.participant2)
        # he can remove himself
        self.assertTrue(self.participant1 in self.thread1.participants.all())
        self.assertTrue(self.thread1.remove_participant(request, self.participant1))
        self.assertFalse(self.participant1 in self.thread1.participants.all()) 
Example 26
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: ISC License 5 votes vote down vote up
def remove_participant_callback(self):
        # this can be overriden by the settings
        request = RequestFactory()
        request.user = self.participant1
        self.assertTrue(self.participant2 in self.thread1.participants.all())
        self.assertTrue(self.thread1.remove_participant(request, self.participant2))
        self.assertFalse(self.participant2 in self.thread1.participants.all()) 
Example 27
Project: PrivacyScore   Author: PrivacyScore   File: tests.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory() 
Example 28
Project: django-rest-framework-httpsignature   Author: etoccalino   File: tests.py    License: MIT License 5 votes vote down vote up
def test_build_signature(self):
        # TO SIGN:
        #
        # GET /packages/measures/ HTTP/1.1
        # host: localhost:8000
        # accept: application/json
        # date: Mon, 17 Feb 2014 06:11:05 GMT

        headers = ['(request-target)', 'host', 'accept', 'date']
        expected_signature = '+dV3yojX7N5I5J+rx0N+7kL5zES2L9Goo4ApJIn33IM='
        expected_signature_string = build_signature(
            headers,
            key_id=self.KEYID,
            signature=expected_signature)

        req = RequestFactory().get(
            '/packages/measures/', {},
            HTTP_HOST='localhost:8000',
            HTTP_ACCEPT='application/json',
            HTTP_DATE='Mon, 17 Feb 2014 06:11:05 GMT',
            HTTP_AUTHORIZATION=expected_signature_string)

        signature_string = self.auth.build_signature(
            self.KEYID, SECRET, req)
        signature = re.match(
            '.*signature="(.+)",?.*', signature_string).group(1)
        self.assertEqual(expected_signature, signature) 
Example 29
Project: django-rest-framework-httpsignature   Author: etoccalino   File: tests.py    License: MIT License 5 votes vote down vote up
def test_no_credentials(self):
        request = RequestFactory().get(ENDPOINT)
        res = self.auth.authenticate(request)
        self.assertIsNone(res) 
Example 30
Project: django-rest-framework-httpsignature   Author: etoccalino   File: tests.py    License: MIT License 5 votes vote down vote up
def test_only_api_key(self):
        request = RequestFactory().get(
            ENDPOINT, {},
            HTTP_X_API_KEY=KEYID)
        self.assertRaises(AuthenticationFailed,
                          self.auth.authenticate, request)