Python django.test.RequestFactory() Examples
The following are 30
code examples of django.test.RequestFactory().
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 also want to check out all available functions/classes of the module
django.test
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_briefcase_client.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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 #2
Source File: test_models.py From django-rest-messaging with ISC License | 6 votes |
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 #3
Source File: test_figures_home_view.py From figures with MIT License | 6 votes |
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 #4
Source File: test_views.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
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 #5
Source File: tests.py From django-rest-framework-httpsignature with MIT License | 6 votes |
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 #6
Source File: auth_tests.py From arches with GNU Affero General Public License v3.0 | 6 votes |
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 #7
Source File: test_form_enter_data.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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
Source File: test_speedrun.py From donation-tracker with Apache License 2.0 | 6 votes |
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 #9
Source File: test_exams.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/exams_form.html" # Setup request and view. request = RequestFactory().get('exams/') request.user = self.user view = ExamsCreateView.as_view(template_name=template) # Run. response = view(request, user=request.user) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/exams_form.html")
Example #10
Source File: middleware_tests.py From django-influxdb-metrics with MIT License | 5 votes |
def test_middleware(self): req = RequestFactory().get('/?campaign=bingo') req.META['HTTP_REFERER'] = 'http://google.co.uk/foobar/' req.user = AnonymousUser() mware = InfluxDBRequestMiddleware() mware.process_view(req, 'view_funx', 'view_args', 'view_kwargs') mware.process_exception(req, None) self.assertEqual( self.mock_write_points.call_args[0][0][0]['tags']['referer_tld'], 'google.co.uk', msg=('Should correctly determine referer_tld')) self.assertEqual( self.mock_write_points.call_args[0][0][0]['tags']['campaign'], 'bingo', msg=('Should correctly determine campaign query parameter')) req = RequestFactory().get('/') req.META['HTTP_REFERER'] = 'http://google.co.uk/foobar/' req.user = self.staff mware = InfluxDBRequestMiddleware() mware.process_view(req, 'view_funx', 'view_args', 'view_kwargs') mware.process_response(req, None) self.assertEqual( self.mock_write_points.call_args[0][0][0]['tags']['referer_tld'], 'google.co.uk', msg=('Should also work for successful responses')) req = RequestFactory().get('/', HTTP_X_REQUESTED_WITH='XMLHttpRequest') req.META['HTTP_REFERER'] = 'http://google.co.uk/foobar/' req.user = self.superuser mware = InfluxDBRequestMiddleware() mware.process_view(req, 'view_funx', 'view_args', 'view_kwargs') mware.process_response(req, None) self.assertEqual( self.mock_write_points.call_args[0][0][0]['tags']['referer_tld'], 'google.co.uk', msg=('Should also work for ajax requests'))
Example #11
Source File: real_connection_tests.py From django-influxdb-metrics with MIT License | 5 votes |
def test_middleware(self): self.influxdb_client.delete_series(measurement='django_request') req = RequestFactory().get('/?campaign=bingo') req.META['HTTP_REFERER'] = 'http://google.co.uk/foobar/' req.user = AnonymousUser() mware = InfluxDBRequestMiddleware() mware.process_view(req, 'view_funx', 'view_args', 'view_kwargs') mware.process_exception(req, None) results = list(query('select * from django_request')) self.assertEqual(len(results), 1) result = results[0][0] self.assertEqual(result['value'], 0)
Example #12
Source File: test_data_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): super(self.__class__, self).setUp() self._create_user_and_login() self._publish_transportation_form() self.factory = RequestFactory() self.extra = { 'HTTP_AUTHORIZATION': 'Token %s' % self.user.auth_token}
Example #13
Source File: test_appointments.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/appointments_form.html" # Setup request and view. request = RequestFactory().get('appoints/') request.user = self.user view = AppointmentsCreateView.as_view(template_name=template) # Run. response = view(request, user=request.user) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/appointments_form.html")
Example #14
Source File: test_meals.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/meals_form.html" # Setup request and view. request = RequestFactory().get('meals/edit/{}'.format( self.meals.id)) request.user = self.user view = MealsUpdateView.as_view(template_name=template) # Run. response = view(request, user=request.user, pk=self.meals.id) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/meals_form.html")
Example #15
Source File: test_meals.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = 'dj_diabetes/confirm_delete.html' # Setup request and view. request = RequestFactory().get('meals/delete/{}'.format( self.meals.id)) request.user = self.user view = MealsDeleteView.as_view(template_name=template) # Run. response = view(request, user=request.user, pk=self.meals.id) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], 'dj_diabetes/confirm_delete.html')
Example #16
Source File: test_issues.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/issues_form.html" # Setup request and view. request = RequestFactory().get('issues/') request.user = self.user view = IssuesCreateView.as_view(template_name=template) # Run. response = view(request, user=request.user) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/issues_form.html")
Example #17
Source File: test_issues.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/issues_form.html" # Setup request and view. request = RequestFactory().get('issues/edit/{}'.format(self.issues.id)) request.user = self.user view = IssuesUpdateView.as_view(template_name=template) # Run. response = view(request, user=request.user, pk=self.issues.id) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/issues_form.html")
Example #18
Source File: test_appointments.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): app = self.create_appointments() template = 'dj_diabetes/confirm_delete.html' # Setup request and view. request = RequestFactory().get('appoints/delete/{}'.format(app.id)) request.user = self.user view = AppointmentsDeleteView.as_view(template_name=template) # Run. response = view(request, user=request.user, pk=app.id) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], 'dj_diabetes/confirm_delete.html')
Example #19
Source File: test_form_list.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): super(TestFormList, self).setUp() self.factory = RequestFactory()
Example #20
Source File: test_simple_submission.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def test_corrupted_submission(self): """Test xml submissions that contain unicode characters. """ xml = 'v\xee\xf3\xc0k\x91\x91\xae\xff\xff\xff\xff\xcf[$b\xd0\xc9\'uW\x80RP\xff\xff\xff\xff7\xd0\x03%F\xa7p\xa2\x87\xb6f\xb1\xff\xff\xff\xffg~\xf3O\xf3\x9b\xbc\xf6ej_$\xff\xff\xff\xff\x13\xe8\xa9D\xed\xfb\xe7\xa4d\x96>\xfa\xff\xff\xff\xff\xc7h"\x86\x14\\.\xdb\x8aoF\xa4\xff\xff\xff\xff\xcez\xff\x01\x0c\x9a\x94\x18\xe1\x03\x8e\xfa\xff\xff\xff\xff39P|\xf9n\x18F\xb1\xcb\xacd\xff\xff\xff\xff\xce>\x97i;1u\xcfI*\xf2\x8e\xff\xff\xff\xffFg\x9d\x0fR:\xcd*\x14\x85\xf0e\xff\xff\xff\xff\xd6\xdc\xda\x8eM\x06\xf1\xfc\xc1\xe8\xd6\xe0\xff\xff\xff\xff\xe7G\xe1\xa1l\x02T\n\xde\x1boJ\xff\xff\xff\xffz \x92\xbc\tR{#\xbb\x9f\xa6s\xff\xff\xff\xff\xa2\x8f(\xb6=\xe11\xfcV\xcf\xef\x0b\xff\xff\xff\xff\xa3\x83\x7ft\xd7\x05+)\xeb9\\*\xff\xff\xff\xff\xfe\x93\xb2\xa2\x06n;\x1b4\xaf\xa6\x93\xff\xff\xff\xff\xe7\xf7\x12Q\x83\xbb\x9a\xc8\xc8q34\xff\xff\xff\xffT2\xa5\x07\x9a\xc9\x89\xf8\x14Y\xab\x19\xff\xff\xff\xff\x16\xd0R\x1d\x06B\x95\xea\\\x1ftP\xff\xff\xff\xff\x94^\'\x01#oYV\xc5\\\xb7@\xff\xff\xff\xff !\x11\x00\x8b\xf3[\xde\xa2\x01\x9dl\xff\xff\xff\xff\xe7z\x92\xc3\x03\xd3\xb5B5 \xaa7\xff\xff\xff\xff\xff\xc3Q:\xa6\xb3\xa3\x1e\x90 \xa0\\\xff\xff\xff\xff\xff\x14<\x03Vr\xe8Z.Ql\xf5\xff\xff\xff\xffEx\xf7\x0b_\xa1\x7f\xfcG\xa4\x18\xcd\xff\xff\xff\xff1|~i\x00\xb3. ,1Q\x0e\xff\xff\xff\xff\x87a\x933Y\xd7\xe1B#\xa7a\xee\xff\xff\xff\xff\r\tJ\x18\xd0\xdb\x0b\xbe\x00\x91\x95\x9e\xff\xff\xff\xffHfW\xcd\x8f\xa9z6|\xc5\x171\xff\xff\xff\xff\xf5tP7\x93\x02Q|x\x17\xb1\xcb\xff\xff\xff\xffVb\x11\xa0*\xd9;\x0b\xf8\x1c\xd3c\xff\xff\xff\xff\x84\x82\xcer\x15\x99`5LmA\xd5\xff\xff\xff\xfft\xce\x8e\xcbw\xee\xf3\xc0w\xca\xb3\xfd\xff\xff\xff\xff\xb0\xaab\x92\xd4\x02\x84H3\x94\xa9~\xff\xff\xff\xff\xfe7\x18\xcaW=\x94\xbc|\x0f{\x84\xff\xff\xff\xff\xe8\xdf\xde?\x8b\xb7\x9dH3\xc1\xf2\xaa\xff\xff\xff\xff\xbe\x00\xba\xd7\xba6!\x95g\xb01\xf9\xff\xff\xff\xff\x93\xe3\x90YH9g\xf7\x97nhv\xff\xff\xff\xff\x82\xc7`\xaebn\x9d\x1e}\xba\x1e/\xff\xff\xff\xff\xbd\xe5\xa1\x05\x03\xf26\xa0\xe2\xc1*\x07\xff\xff\xff\xffny\x88\x9f\x19\xd2\xd0\xf7\x1de\xa7\xe0\xff\xff\xff\xff\xc4O&\x14\x8dVH\x90\x8b+\x03\xf9\xff\xff\xff\xff\xf69\xc2\xabo%\xcc/\xc9\xe4dP\xff\xff\xff\xff (\x08G\xebM\x03\x99Y\xb4\xb3\x1f\xff\xff\xff\xffzH\xd2\x19p#\xc5\xa4)\xfd\x05\x9a\xff\xff\xff\xffd\x86\xb2F\x15\x0f\xf4.\xfd\\\xd4#\xff\xff\xff\xff\xaf\xbe\xc6\x9di\xa0\xbc\xd5>cp\xe2\xff\xff\xff\xff&h\x91\xe9\xa0H\xdd\xaer\x87\x18E\xff\xff\xff\xffjg\x08E\x8f\xa4&\xab\xff\x98\x0ei\xff\xff\xff\xff\x01\xfd{"\xed\\\xa3M\x9e\xc3\xf8K\xff\xff\xff\xff\x87Y\x98T\xf0\xa6\xec\x98\xb3\xef\xa7\xaa\xff\xff\xff\xffA\xced\xfal\xd3\xd9\x06\xc6~\xee}\xff\xff\xff\xff:\x7f\xa2\x10\xc7\xadB,}PF%\xff\xff\xff\xff\xb2\xbc\n\x17%\x98\x904\x89\tF\x1f\xff\xff\xff\xff\xdc\xd8\xc6@#M\x87uf\x02\xc6g\xff\xff\xff\xffK\xaf\xb0-=l\x07\xe1Nv\xe4\xf4\xff\xff\xff\xff\xdb\x13\'Ne\xb2UT\x9a#\xb1^\xff\xff\xff\xff\xb2\rne\xd1\x9d\x88\xda\xbb!\xfa@\xff\xff\xff\xffflq\x0f\x01z]uh\'|?\xff\xff\xff\xff\xd5\'\x19\x865\xba\xf2\xe7\x8fR-\xcc\xff\xff\xff\xff\xce\xd6\xfdi\x04\x9b\xa7\tu\x05\xb7\xc8\xff\xff\xff\xff\xc3\xd0)\x11\xdd\xb1\xa5kp\xc9\xd5\xf7\xff\xff\xff\xff\xffU\x9f \xb7\xa1#3rup[\xff\xff\xff\xff\xfc=' # noqa request = RequestFactory().post('/') request.user = self.user error, instance = safe_create_instance( self.user.username, TempFileProxy(xml), None, None, request) text = 'File likely corrupted during transmission' self.assertContains(error, text, status_code=400)
Example #21
Source File: test_weights.py From dj-diabetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_get(self): template = "dj_diabetes/weights_form.html" # Setup request and view. request = RequestFactory().get('weights/edit/{}'.format( self.weights.id)) request.user = self.user view = WeightsUpdateView.as_view(template_name=template) # Run. response = view(request, user=request.user, pk=self.weights.id) # Check. self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name[0], "dj_diabetes/weights_form.html")
Example #22
Source File: test_note_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): super(self.__class__, self).setUp() self._create_user_and_login() self._publish_transportation_form() self._make_submissions() self.view = NoteViewSet.as_view({ 'get': 'list', 'post': 'create', 'delete': 'destroy' }) self.factory = RequestFactory() self.extra = { 'HTTP_AUTHORIZATION': 'Token %s' % self.user.auth_token}
Example #23
Source File: test_export_viewset.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): super(self.__class__, self).setUp() self._create_user_and_login() self._publish_transportation_form() self.factory = RequestFactory() self.extra = { 'HTTP_AUTHORIZATION': 'Token %s' % self.user.auth_token}
Example #24
Source File: test_form_enter_data.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def test_enter_data_redir(self): if not self._running_enketo(): raise SkipTest with HTTMock(enketo_mock): factory = RequestFactory() request = factory.get('/') request.user = self.user response = enter_data( request, self.user.username, self.xform.id_string) # make sure response redirect to an enketo site enketo_base_url = urlparse(settings.ENKETO_URL).netloc redirected_base_url = urlparse(response['Location']).netloc # TODO: checking if the form is valid on enketo side self.assertIn(enketo_base_url, redirected_base_url) self.assertEqual(response.status_code, 302)
Example #25
Source File: test_form_enter_data.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def _get_grcode_view_response(self): factory = RequestFactory() request = factory.get('/') request.user = self.user response = qrcode( request, self.user.username, self.xform.id_string) return response
Example #26
Source File: ocp.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, request): """Initialize settings object with incoming request.""" self.request = request self.factory = RequestFactory() self.schema = request.user.customer.schema_name
Example #27
Source File: test_views.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): """Set up the customer view tests.""" super().setUp() self.client = APIClient() self.factory = RequestFactory() self.dh = DateHelper()
Example #28
Source File: tests_views.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): """Set up the customer view tests.""" super().setUp() self.client = APIClient() self.factory = RequestFactory()
Example #29
Source File: test_views.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): """Set up the customer view tests.""" super().setUp() self.client = APIClient() self.factory = RequestFactory()
Example #30
Source File: iam_test_case.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def setUpClass(cls): """Set up each test class.""" super().setUpClass() post_save.disconnect(storage_callback, sender=Sources) cls.customer_data = cls._create_customer_data() cls.user_data = cls._create_user_data() cls.request_context = cls._create_request_context(cls.customer_data, cls.user_data) cls.schema_name = cls.customer_data.get("schema_name") cls.tenant = Tenant.objects.get_or_create(schema_name=cls.schema_name)[0] cls.tenant.save() cls.headers = cls.request_context["request"].META cls.provider_uuid = UUID("00000000-0000-0000-0000-000000000001") cls.factory = RequestFactory()