class UtilityTestCase(TestCase): 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() def create_user(self, username, **attrs): user = get_user_model().objects.create_user( username, username + '@example.com', DEFAULT_PASSWORD ) for name, value in attrs.items(): setattr(user, name, value) user.save() return user def login(self, client, username): client.login(username=username, password=DEFAULT_PASSWORD) def get_request(self, url=None): if url is None: url = '/' request = self.factory.get(url) request.user = AnonymousUser() self.session_middleware.process_request(request) return request
class InviteAcceptViewTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.session_middleware = SessionMiddleware() def _add_session(self, request): self.session_middleware.process_request(request) def test_context_data__no_invite(self): view = InviteAcceptView() view.invite = None view.content = None view.request = RequestFactory().get('/') context = view.get_context_data() self.assertIsNone(context['invite']) self.assertIsNone(context['content']) self.assertFalse(context['invited_person_exists']) self.assertFalse(context['sender_display']) self.assertFalse(context['invited_person_exists']) def test_invite(self): view = InviteAcceptView() event = EventFactory() invite = InviteFactory(content_id=event.pk, kind=EventInvite.slug, user=PersonFactory(first_name="Conan", last_name="O'Brien")) view.content = event view.request = RequestFactory().get('/') view.request.user = PersonFactory(email=invite.email, confirmed_email=invite.email) self._add_session(view.request) with mock.patch.object(wraps=Order.objects.for_request, target=Order.objects, attribute='for_request') as for_request: view.get(view.request, code=invite.code) for_request.assert_called_once_with(create=True, request=view.request, event=view.content) orders = Order.objects.all() self.assertEqual(len(orders), 1) self.assertEqual(orders[0].person, view.request.user)
def add_session_to_request(request): """ Annotate a request object with a session """ middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
def test_generate_instant_vouchers_POST(self): # Create package response = send_api_request(settings.PACKAGE_INSERT_URL, data={'package_type': 'Daily', 'volume': '3', 'speed': '1.5', 'price': 4}) package = response['result'] self.c.post(reverse('login'), {'username': '******', 'password': '******'}) factory = RequestFactory() session = SessionMiddleware() request = factory.post(reverse('vouchers:generate_instant'), data={'package': package['id'], 'quantity': '20'}) request.user = self.user session.process_request(request) request.session.save() messages = FallbackStorage(request) setattr(request, '_messages', messages) response = generate(request, template='vouchers/generate_instant.html', voucher_form=forms.GenerateInstantVoucherForm, redirect_to='vouchers:generate_instant') storage = get_messages(request) lst = [] for message in storage: lst.append(message) self.assertEqual(response.status_code, 302) self.assertEqual('Vouchers generated successfully.', lst[0].__str__()) self.assertEqual(response.get('location'), reverse('vouchers:generate_instant')) # Delete package send_api_request(settings.PACKAGE_DELETE_URL, data={'package_id': package['id']})
def get_request(self, url='/'): request = self.factory.get('/') middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.resolver_match = resolve(url) return request
def test_generate_standard_vouchers_POST(self): self.c.post(reverse('login'), {'username': '******', 'password': '******'}) factory = RequestFactory() session = SessionMiddleware() request = factory.post(reverse('vouchers:generate_standard'), data={'price': '1', 'quantity': '20'}) request.user = self.user session.process_request(request) request.session.save() messages = FallbackStorage(request) setattr(request, '_messages', messages) response = generate(request, template='vouchers/generate_standard.html', voucher_form=forms.GenerateStandardVoucherForm, redirect_to='vouchers:generate_standard') storage = get_messages(request) lst = [] for message in storage: lst.append(message) self.assertEqual(response.status_code, 302) self.assertEqual('Vouchers generated successfully.', lst[0].__str__()) self.assertEqual(response.get('location'), reverse('vouchers:generate_standard'))
def request(self, **request): """ Rather than issuing a request and returning the response, this simply constructs an ``HttpRequest`` object and returns it. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.input': None, } environ.update(self.defaults) environ.update(request) request = WSGIRequest(environ) # We have to manually add a session since we'll be bypassing # the middleware chain. session_middleware = SessionMiddleware() session_middleware.process_request(request) return request
class TestUserPreferenceMiddleware(TestCase): """ Tests to make sure user preferences are getting properly set in the middleware """ def setUp(self): self.middleware = LanguagePreferenceMiddleware() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() self.request = RequestFactory().get('/somewhere') self.request.user = self.user self.session_middleware.process_request(self.request) def test_no_language_set_in_session_or_prefs(self): # nothing set in the session or the prefs self.middleware.process_request(self.request) self.assertNotIn('django_language', self.request.session) def test_language_in_user_prefs(self): # language set in the user preferences and not the session UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEquals(self.request.session['django_language'], 'eo') def test_language_in_session(self): # language set in both the user preferences and session, # session should get precedence self.request.session['django_language'] = 'en' UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEquals(self.request.session['django_language'], 'en')
def test_set_language(self): request = self.factory.post('/languages/', json.dumps({'lang': 'ru'}), content_type="application/json") smiddleware = SessionMiddleware() lmiddleware = LocaleMiddleware() smiddleware.process_request(request) lmiddleware.process_request(request) request.session.save() response = LanguagesView.as_view()(request) lmiddleware.process_response(request, response) self.assertEqual(response.status_code, 200) response_content = response.content if six.PY3: response_content = str(response_content, encoding='utf8') self.assertJSONEqual(response_content, {u'success': True}) self.assertEqual(response['Content-Language'], u'ru')
def test_session_delete_on_end(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header looks like: # Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( 'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; ' 'Max-Age=0; Path=/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) ) # SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie' # from being cached. self.assertEqual(response['Vary'], 'Cookie')
def test_session_delete_on_end_with_custom_domain(self): request = RequestFactory().get("/") response = HttpResponse("Session test") middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = "abc" # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # Check that the cookie was deleted, not recreated. # A deleted cookie header with a custom domain looks like: # Set-Cookie: sessionid=; Domain=.example.local; # expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( "Set-Cookie: {}={}; Domain=.example.local; expires=Thu, " "01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/".format( settings.SESSION_COOKIE_NAME, '""' if sys.version_info >= (3, 5) else "" ), str(response.cookies[settings.SESSION_COOKIE_NAME]), )
def test_session_delete_on_end_with_custom_domain_and_path(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header with a custom domain and path looks like: # Set-Cookie: sessionid=; Domain=.example.local; # expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; # Path=/example/ self.assertEqual( 'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, ' '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) )
def test_session_delete_on_end(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header looks like: # Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( 'Set-Cookie: {}={}; expires=Thu, 01-Jan-1970 00:00:00 GMT; ' 'Max-Age=0; Path=/'.format( settings.SESSION_COOKIE_NAME, '""' if sys.version_info >= (3, 5) else '', ), str(response.cookies[settings.SESSION_COOKIE_NAME]) )
def test_empty_session_saved(self): """ If a session is emptied of data but still has a key, it should still be updated. """ request = RequestFactory().get("/") response = HttpResponse("Session test") middleware = SessionMiddleware() # Set a session key and some data. middleware.process_request(request) request.session["foo"] = "bar" # Handle the response through the middleware. response = middleware.process_response(request, response) self.assertEqual(tuple(request.session.items()), (("foo", "bar"),)) # A cookie should be set, along with Vary: Cookie. self.assertIn("Set-Cookie: sessionid=%s" % request.session.session_key, str(response.cookies)) self.assertEqual(response["Vary"], "Cookie") # Empty the session data. del request.session["foo"] # Handle the response through the middleware. response = HttpResponse("Session test") response = middleware.process_response(request, response) self.assertEqual(dict(request.session.values()), {}) session = Session.objects.get(session_key=request.session.session_key) self.assertEqual(session.get_decoded(), {}) # While the session is empty, it hasn't been flushed so a cookie should # still be set, along with Vary: Cookie. self.assertGreater(len(request.session.session_key), 8) self.assertIn("Set-Cookie: sessionid=%s" % request.session.session_key, str(response.cookies)) self.assertEqual(response["Vary"], "Cookie")
class UtilityTestCase(TestCase): def setUp(self): self.session_backend = SessionStore() self.session_middleware = SessionMiddleware() self.factory = RequestFactory() self.user = self.create_user('user') self.admin = self.create_user('admin', is_superuser=True) self.staff = self.create_user('staff', is_staff=True) self.client = Client() def create_user(self, username, **attrs): if attrs is None: attrs = {} user = User.objects.create_user(username, username + '@example.com', DEFAULT_PASSWORD) user.profile = Profile.objects.create(user=user) user.__dict__.update(**attrs) user.backend = self.session_backend user.save() return user def login(self, client, username): client.login(username=username, password=DEFAULT_PASSWORD) def get_request_for_user(self, user): request = self.factory.get('/') request.user = self.user self.session_middleware.process_request(request) logout(request) return request
class SignedCookiesTest(TestCase): def setUp(self): self.middleware = SignedCookiesMiddleware() self.auth_middleware = AuthenticationMiddleware() self.session_middleware = SessionMiddleware() def _process_request(self, request): self.session_middleware.process_request(request) self.auth_middleware.process_request(request) self.middleware.process_request(request) def _process_response(self, request, response): self.middleware.process_response(request, response) self.session_middleware.process_response(request, response) def test_middleware(self): request = HttpRequest() request.COOKIES['key'] = 'foo' self._process_request(request) self.failIf('key' in request.COOKIES) response = HttpResponse() request = HttpRequest() self._process_request(request) response.set_cookie('key', 'foo') self._process_response(request, response) signed_val = response.cookies['key'].value self.failIfEqual(signed_val, 'foo') request.COOKIES['key'] = signed_val self._process_request(request) self.failUnlessEqual(request.COOKIES['key'], 'foo')
def should_raise_exception_if_session_middleware_not_used(): class Step1(forms.Form): name = forms.CharField() class Step2(forms.Form): name = forms.CharField() class StepsWizardView(WizardView): # pylint: ignore=W0223 storage = 'formwizard.storage.SessionStorage' steps = ( ("Step 1", Step1), ("Step 2", Step2), ) template_name = 'simple.html' view = StepsWizardView.as_view() request = factory.get('/') with Assert.raises(ImproperlyConfigured): view(request) # use session middleware and no exceptions should be raised middleware = SessionMiddleware() request = factory.get('/') middleware.process_request(request) view(request)
class TestLangPrefView(TestCase): """ Language preference view tests. """ def setUp(self): super(TestLangPrefView, self).setUp() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() self.request = RequestFactory().get('/somewhere') self.request.user = self.user self.session_middleware.process_request(self.request) def test_language_session_update(self): # test language session updating correctly. self.request.session[LANGUAGE_SESSION_KEY] = 'ar' response = self.client.patch(reverse("session_language"), json.dumps({'pref-lang': 'eo'})) self.assertEqual(response.status_code, 200) self.client.get('/') self.assertEquals(get_language(), 'eo') response = self.client.patch(reverse("session_language"), json.dumps({'pref-lang': 'en'})) self.assertEqual(response.status_code, 200) self.client.get('/') self.assertEquals(get_language(), 'en')
def do_session_middleware_stuff(self, request): """ If using the RequestFactory, middleware is skipped which breaks auth. Use this to re-add session info to request """ middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
def request(self, **request): """ Rather than issuing a request and returning the response, this simply constructs an ``HttpRequest`` object and returns it. """ environ = { "HTTP_COOKIE": self.cookies, "PATH_INFO": "/", "QUERY_STRING": "", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, } environ.update(self.defaults) environ.update(request) request = WSGIRequest(environ) # We have to manually add a session since we'll be bypassing # the middleware chain. session_middleware = SessionMiddleware() session_middleware.process_request(request) return request
def test_user_can_only_select_journal_contacts(self): """ Test list of contacts Make sure the list contains all the contacts of the publisher and only that """ request = self.factory.get( reverse('userspace:journal:editor:add'), args=(self.journal.pk, )) request.user = self.user middleware = SessionMiddleware() middleware.process_request(request) request.session.save() view = IssueSubmissionCreate(request=request, journal_pk=self.journal.pk) view.current_journal = self.journal form = view.get_form() user_contacts = set(User.objects.filter( journals=self.user.journals.all() ).distinct()) form_contacts = set( form.fields['contact'].queryset ) self.assertEquals( user_contacts, form_contacts )
def get_request(self, method=RequestFactory().get, ajax=False, data=None, user=AnonymousUser(), add_session=False, session_dict={}, view_kwargs=None, **kwargs): if data is not None: kwargs.update({'data': data}) req = method(self.get_url(view_kwargs=view_kwargs), **kwargs) req.user = user # the messages framework only works with the FallbackStorage in case of # requestfactory tests if add_session: middleware = SessionMiddleware() middleware.process_request(req) req.session.save() else: setattr(req, 'session', {}) if session_dict: for var in session_dict: req.session[var] = session_dict[var] messages = FallbackStorage(req) setattr(req, '_messages', messages) if ajax: req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' req = self.setUpRequest(req) if req is None: raise RuntimeError( 'The request has become None. You probably forgot to return' ' the request again, when implementing `setUpRequest`.') return req
def test_can_render_a_list_of_forums_according_to_their_minimum_tree_level(self): # Setup forums = Forum.objects.all() request = self.request_factory.get('/') middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.user = self.user ForumPermissionMiddleware().process_request(request) t = Template(self.loadstatement + '{% forum_list forums %}') c = Context({'forums': forums, 'request': request}) expected_out = render_to_string( 'machina/forum/forum_list.html', { 'forums': forums, 'user': self.user, 'root_level': 0, 'root_level_middle': 1, 'root_level_sub': 2, } ) # Run rendered = t.render(c) # Check assert rendered != '' assert rendered == expected_out
def request(self, *args, **kwargs): """Perform request from factory :param method: Request method as string :returns: Request instance Several additional keywords arguments can be passed in: user User instance to use for the request, will default to an :py:class:`AnonymousUser` instance otherwise. session Dictionary to instantiate the session handler with. Other keyword arguments are passed into the request method """ factory = RequestFactory() method = kwargs.pop('method', 'get') fn = getattr(factory, method) request = fn(*args, **kwargs) # Mock user, session, and messages request.user = kwargs.pop('user', AnonymousUser()) session = kwargs.pop('session', {}) middleware = SessionMiddleware() middleware.process_request(request) request.session.update(session) messages = FallbackStorage(request) setattr(request, '_messages', messages) return request
def setUp(self): self.mk_main() self.request = RequestFactory().get('/') self.request.user = self.login() session_middleware = SessionMiddleware() session_middleware.process_request(self.request) self.request.session.save() self.section = SectionPage(title='test section') self.section_index.add_child(instance=self.section) self.important_tag = Tag(title='important tag') self.another_tag = Tag(title='other tag') self.tags = [self.important_tag, self.another_tag] for tag in self.tags: self.tag_index.add_child(instance=tag) tag.save_revision() self.page = ArticlePage(title='test article') self.section.add_child(instance=self.page) self.page.save_revision() for tag in self.tags: ArticlePageTags.objects.create( tag=tag, page=self.page, ) self.adapter = PersistentSurveysSegmentsAdapter(self.request)
def test_samesite_session_cookie(self): request = self.request_factory.get('/') response = HttpResponse() middleware = SessionMiddleware() middleware.process_request(request) request.session['hello'] = 'world' response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')
def test_auth_false(self): request = self.factory.post('/auth_view/',{'username':'******','password':'******'}) middleware = SessionMiddleware() middleware.process_request(request) request.session.save() response=auth_view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.content,'invalid')
def setup_method(self, method): # prepare session self.r = RequestFactory().get('/rand') middleware = SessionMiddleware() middleware.process_request(self.r) self.r.session.save() self.rs = self.root.sf.getConfigService() self.conn = BlitzGateway(client_obj=self.new_client())
def gen_request_with_session(factory): session_middleware = SessionMiddleware(); request = factory.get('/auth/test'); session_middleware.process_request(request); request.session.save(); return request;
class FacebookCanvasMiddlewareTest(FacebookTest): def setUp(self): super(FacebookCanvasMiddlewareTest, self).setUp() self.factory = RequestFactory() self.middleware = FacebookCanvasMiddleWare() self.session_middleware = SessionMiddleware() def get_canvas_url(self, data={}): request = self.factory.post('/', data) request.META['HTTP_REFERER'] = 'https://apps.facebook.com/canvas/' self.session_middleware.process_request(request) return request def test_referer(self): # test empty referer request = self.factory.get('/') self.assertIsNone(self.middleware.process_request(request)) # test referer not facebook request = self.factory.get('/') request.META['HTTP_REFERER'] = 'https://*****:*****@patch.object(FacebookAuthorization, 'parse_signed_data') def test_non_auth_user(self, mocked_method=FacebookAuthorization.parse_signed_data): mocked_method.return_value = {} data = {'signed_request': 'dXairHLF8dfUKaL7ZFXaKmTsAglg0EkyHesTLnPcPAE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTM1ODA2MTU1MSwidXNlciI6eyJjb3VudHJ5IjoiYnIiLCJsb2NhbGUiOiJlbl9VUyIsImFnZSI6eyJtaW4iOjIxfX19'} request = self.get_canvas_url(data=data) response = self.middleware.process_request(request) self.assertTrue(mocked_method.called) self.assertIsInstance(response, ScriptRedirect) @patch('django_facebook.middleware.connect_user', fake_connect) @patch.object(OpenFacebook, 'permissions') @patch.object(FacebookAuthorization, 'parse_signed_data') def test_auth_user( self, mocked_method_1=FacebookAuthorization.parse_signed_data, mocked_method_2=OpenFacebook.permissions): data = {'signed_request': 'd7JQQIfxHgEzLIqJMeU9J5IlLg7shzPJ8DFRF55L52w.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTgwNzQ4MDAsImlzc3VlZF9hdCI6MTM1ODA2ODU1MCwib2F1dGhfdG9rZW4iOiJBQUFGdk02MWpkT0FCQVBhWkNzR1pDM0dEVFZtdDJCWkFQVlpDc0F0aGNmdXBYUnhMN1cwUHBaQm53OEUwTzBBRVNYNjVaQ0JHdjZpOFRBWGhnMEpzbER5UmtmZUlnYnNHUmV2eHQxblFGZ0hNcFNpeTNWRTB3ZCIsInVzZXIiOnsiY291bnRyeSI6ImJyIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiMTAwMDA1MDEyNDY2Nzg1In0'} request = self.get_canvas_url(data=data) request.user = AnonymousUser() mocked_method_1.return_value = {'user_id': '123456', 'oauth_token': 'qwertyuiop'} mocked_method_2.return_value = facebook_settings.FACEBOOK_DEFAULT_SCOPE self.assertIsNone(self.middleware.process_request(request)) self.assertTrue(mocked_method_1.called)
def test_session_delete_on_end(self): def response_ending_session(request): request.session.flush() return HttpResponse('Session test') request = self.request_factory.get('/') middleware = SessionMiddleware(response_ending_session) # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Handle the response through the middleware response = middleware(request) # The cookie was deleted, not recreated. # A deleted cookie header looks like: # Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( 'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; ' 'Max-Age=0; Path=/'.format(settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME])) # SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie' # from being cached. self.assertEqual(response['Vary'], 'Cookie')
def test_can_process_userinfo_included_in_the_id_token_instead_of_calling_the_userinfo_endpoint( self, rf): httpretty.register_uri( httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT, body=json.dumps({ 'id_token': self.generate_jws(email='*****@*****.**'), 'access_token': 'accesstoken', 'refresh_token': 'refreshtoken', }), content_type='text/json') request = rf.get('/oidc/cb/', { 'state': 'state', 'code': 'authcode', }) SessionMiddleware().process_request(request) request.session.save() backend = OIDCAuthBackend() user = backend.authenticate(request, 'nonce') assert user.email == '*****@*****.**' assert user.oidc_user.sub == '1234'
def test_with_questions(self): request_factory = RequestFactory() request = request_factory.get('/qa/') request.user = AnonymousUser() questions = [ factories.PreguntaFactory.create(titulo='first'), factories.PreguntaFactory.create(titulo='second'), factories.PreguntaFactory.create(titulo='last'), ] discusions = [question.discusion for question in questions] discusions.reverse() SessionMiddleware().process_request(request) request.session.save() view = views.IndexView() view.setup(request) response = view.dispatch(request) context = view.get_context_data() self.assertEqual(response.status_code, 200) self.assertEqual(len(context['object_list']), 3) # Veryfing list ordering self.assertEqual(list(context['object_list']), discusions)
def create_fake_api_request(event, body): """ Emulates an API request from the API gateway's data. """ file = tempfile.NamedTemporaryFile(mode="r+b", suffix=".log") file.write(body) file.flush() file.seek(0) data = event["query"] data["file"] = file data["type"] = int(UploadEventType.POWER_LOG) headers = event["headers"] extra = { "HTTP_X_FORWARDED_FOR": event["source_ip"], "HTTP_AUTHORIZATION": headers["Authorization"], "HTTP_X_API_KEY": headers["X-Api-Key"], } factory = APIRequestFactory() request = factory.post(event["path"], data, **extra) SessionMiddleware().process_request(request) return request
def test_user_email_update(self): """ Users can alter their Google account's primary email address. Make sure that we update it on the Django model. """ email = '*****@*****.**' user = users.User(email, _user_id='111111111100000000001') User = get_user_model() request = HttpRequest() SessionMiddleware().process_request( request) # Make the damn sessions work request.session[ BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', lambda: user): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user = request.user self.assertEqual(email, django_user.email) new_email = '*****@*****.**' user = users.User(new_email, _user_id=user.user_id()) with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', lambda: user): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user = request.user self.assertEqual(new_email, django_user.email) self.assertEqual(new_email.lower(), django_user.email_lower)
def test_session_delete_on_end_with_custom_domain_and_path(self): def response_ending_session(request): request.session.flush() return HttpResponse('Session test') request = self.request_factory.get('/') middleware = SessionMiddleware(response_ending_session) # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Handle the response through the middleware response = middleware(request) # The cookie was deleted, not recreated. # A deleted cookie header with a custom domain and path looks like: # Set-Cookie: sessionid=; Domain=.example.local; # expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; # Path=/example/ self.assertEqual( 'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, ' '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]))
def test_log_out_the_user_if_the_refresh_token_is_expired(self, rf): request = rf.get('/oidc/cb/', { 'state': 'state', 'code': 'authcode', }) SessionMiddleware().process_request(request) request.session.save() backend = OIDCAuthBackend() user = backend.authenticate('nonce', request) request.session['oidc_auth_id_token_exp_timestamp'] = \ (tz.now() - dt.timedelta(minutes=1)).timestamp() request.session['oidc_auth_refresh_token'] = 'this_is_a_refresh_token' auth.login(request, user) request.user = user httpretty.register_uri(httpretty.POST, oidc_rp_settings.PROVIDER_TOKEN_ENDPOINT, body=json.dumps({'error': 'yes'}), content_type='text/json', status=400) middleware = OIDCRefreshIDTokenMiddleware(lambda r: 'OK') middleware(request) assert not request.user.is_authenticated
def test_account_switch(self): user1 = users.User('*****@*****.**', _user_id='111111111100000000001') user2 = users.User('*****@*****.**', _user_id='222222222200000000002') request = HttpRequest() SessionMiddleware().process_request( request) # Make the damn sessions work request.session[ BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): middleware.process_request(request) self.assertEqual(user1.user_id(), request.user.username) with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', lambda: user2): middleware.process_request(request) self.assertEqual(user2.user_id(), request.user.username)
def test_serve_post_valid_calls_feedback_block_handler(self): """A valid post should call the feedback block handler. This returns a redirect to the calling page and also uses the Django messages framework to set a message. """ page = BrowsePage(title='test', slug='test') page.content = blocks.StreamValue( page.content.stream_block, [{'type': 'feedback', 'value': 'something'}], True ) save_new_page(page) request = self.factory.post('/', {'form_id': 'form-content-0'}) SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) response = page.serve_post(request) self.assertEqual( (response.status_code, response['Location']), (302, request.path) )
def test_verify_email(self, views_iam_admin_client): # create an EmailVerification record with a next url email_verification = models.EmailVerification(username='******') email_verification.save() verify_email_url = reverse( 'django_airavata_auth:verify_email', kwargs={'code': email_verification.verification_code}) request = self.factory.get(verify_email_url) request.user = AnonymousUser() # Skip enabling the user views_iam_admin_client.is_user_enabled.return_value = True # RequestFactory doesn't load middleware so have to manually call # SessionMiddleware and MessageMiddleware since create_account uses # 'messages' framework response = SessionMiddleware( MessageMiddleware(lambda r: views.verify_email( r, email_verification.verification_code)))(request) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(reverse('django_airavata_auth:login'), response.url) email_verification = models.EmailVerification.objects.get( username="******") self.assertTrue(email_verification.verified)
def _test_signup_email_verified_externally(self, signup_email, verified_email): username = '******' request = RequestFactory().post( reverse('account_signup'), { 'username': username, 'email': signup_email, 'password1': 'johndoe', 'password2': 'johndoe' }) # Fake stash_verified_email from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) request.user = AnonymousUser() request.session['account_verified_email'] = verified_email from .views import signup resp = signup(request) self.assertEqual(resp.status_code, 302) self.assertEqual(resp['location'], get_adapter().get_login_redirect_url(request)) self.assertEqual(len(mail.outbox), 0) return get_user_model().objects.get(username=username)
def test_email_address_created(self): factory = RequestFactory() request = factory.get('/accounts/login/callback/') request.user = AnonymousUser() SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) User = get_user_model() user = User() setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test') setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, "*****@*****.**") account = SocialAccount(provider='openid', uid='123') sociallogin = SocialLogin(user=user, account=account) complete_social_login(request, sociallogin) user = User.objects.get( **{account_settings.USER_MODEL_USERNAME_FIELD: 'test'}) self.assertTrue( SocialAccount.objects.filter(user=user, uid=account.uid).exists()) self.assertTrue( EmailAddress.objects.filter(user=user, email=user_email(user)).exists())
def test_calling_user_fails_when_attribute_error_is_raised(self): """ This proves that when an AttributeError is raised inside of the request.user property, that we can handle this and report the true, underlying error. """ class AuthRaisesAttributeError(object): def authenticate(self, request): import rest_framework rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(), )) SessionMiddleware().process_request(self.request) login(self.request, self.user) try: self.request.user except AttributeError as error: assert str(error) in ( "'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", # Python < 3.5 "module 'rest_framework' has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'", # Python >= 3.5 ) else: assert False, 'AttributeError not raised'
def test_datagroup_create_url_len_err(self): long_url = "http://www.epa.gov" * 16 csv_string = ( "filename,title,document_type,url,organization\n" "0bf5755e-3a08-4024-9d2f-0ea155a9bd17.pdf,NUTRA NAIL,MS,, \n" f"another.pdf,Body Cream,MS,{long_url}, \n") data = io.StringIO(csv_string) sample_csv = InMemoryUploadedFile( data, field_name="csv", name="register_records.csv", content_type="text/csv", size=len(csv_string), charset="utf-8", ) form_data = { "name": ["Walmart MSDS Test Group"], "description": ["test data group"], "group_type": ["2"], "downloaded_by": [str(User.objects.get(username="******").pk)], "downloaded_at": ["08/02/2018"], "download_script": ["1"], "data_source": ["10"], } request = self.factory.post(path="/datagroup/new/", data=form_data) request.FILES["csv"] = sample_csv middleware = SessionMiddleware() middleware.process_request(request) request.session.save() middleware = MessageMiddleware() middleware.process_request(request) request.session.save() request.user = User.objects.get(username="******") request.session = {} request.session["datasource_title"] = "Walmart" request.session["datasource_pk"] = 10 resp = views.data_group_create(request=request, pk=10) self.assertContains(resp, "url: Enter a valid URL")
def test_csv_line_endings(self): csv_string = ( "filename,title,document_type,url,organization\r" "0bf5755e-3a08-4024-9d2f-0ea155a9bd17.pdf,NUTRA NAIL,MS,, \r" "0c68ab16-2065-4d9b-a8f2-e428eb192465.pdf,Body Cream,MS,, \r\n") data = io.StringIO(csv_string) sample_csv = InMemoryUploadedFile( data, field_name="csv", name="register_records.csv", content_type="text/csv", size=len(csv_string), charset="utf-8", ) form_data = { "name": ["Walmart MSDS Test Group"], "description": ["test data group"], "group_type": ["2"], "downloaded_by": [f"{User.objects.first().pk}"], "downloaded_at": ["08/02/2018"], "download_script": ["1"], "data_source": ["10"], } request = self.factory.post(path="/datagroup/new/", data=form_data) request.FILES["csv"] = sample_csv middleware = SessionMiddleware() middleware.process_request(request) request.session.save() middleware = MessageMiddleware() middleware.process_request(request) request.session.save() request.user = User.objects.get(username="******") request.session = {"datasource_title": "Walmart", "datasource_pk": 10} resp = views.data_group_create(request=request, pk=10) dg = DataGroup.objects.filter(name="Walmart MSDS Test Group") self.assertTrue(resp.status_code == 302, "Redirect to detail page") self.assertTrue(dg.exists(), "Group should be created")
def test_invalid_clean_comp_data_upload(self): sample_csv = self.generate_invalid_clean_comp_data_csv_string() sample_csv_bytes = sample_csv.encode(encoding="UTF-8", errors="strict") in_mem_sample_csv = InMemoryUploadedFile( io.BytesIO(sample_csv_bytes), field_name="cleancomp-bulkformsetfileupload", name="clean_comp_data.csv", content_type="text/csv", size=len(sample_csv), charset="utf-8", ) req_data = {"cleancomp-script_id": 12, "cleancomp-submit": "Submit"} req_data.update(self.mng_data) req = self.factory.post(path="/datagroup/47/", data=req_data) middleware = SessionMiddleware() middleware.process_request(req) req.session.save() middleware = MessageMiddleware() middleware.process_request(req) req.session.save() req.FILES["cleancomp-bulkformsetfileupload"] = in_mem_sample_csv req.user = User.objects.get(username="******") resp = views.data_group_detail(request=req, pk=47) self.assertContains( resp, "lower_wf_analysis: Quantity 1.7777 must be between 0 and 1") self.assertContains( resp, "Both minimum and maximimum weight fraction values must be provided, not just one.", ) self.assertContains( resp, "The following IDs do not exist in ExtractedChemicals for this data group: 999", ) self.assertContains( resp, "Central weight fraction value cannot be defined with minimum value and maximum value.", )
def test_noscript(self): sample_csv = self.generate_valid_clean_comp_data_csv_string() sample_csv_bytes = sample_csv.encode(encoding="UTF-8", errors="strict") in_mem_sample_csv = InMemoryUploadedFile( io.BytesIO(sample_csv_bytes), field_name="cleancomp-bulkformsetfileupload", name="clean_comp_data.csv", content_type="text/csv", size=len(sample_csv), charset="utf-8", ) req_data = {"cleancomp-submit": "Submit"} req_data.update(self.mng_data) req = self.factory.post(path="/datagroup/47/", data=req_data) req.FILES["cleancomp-bulkformsetfileupload"] = in_mem_sample_csv middleware = SessionMiddleware() middleware.process_request(req) req.session.save() middleware = MessageMiddleware() middleware.process_request(req) req.session.save() req.user = User.objects.get(username="******") resp = views.data_group_detail(request=req, pk=47) self.assertContains(resp, "This field is required")
def setUp(self): """ create a user """ self.user = User.objects.create_user( username='******', email='*****@*****.**', password='******' ) # create a a site for that will bear the HTTP_HOST header Site.objects.create(domain='testing.com', name='Testing Domain') request = APIRequestFactory().get('rest_login', HTTP_HOST='testing.com') # in your test method: """Annotate a request object with a session""" middleware = SessionMiddleware() middleware.process_request(request) request.session.save() """Annotate a request object with a messages""" middleware = MessageMiddleware() middleware.process_request(request) request.session.save() self.serializer_class = LoginSerializer self.context = {'request': request}
def test_empty_session_saved(self): """ If a session is emptied of data but still has a key, it should still be updated. """ request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Set a session key and some data. middleware.process_request(request) request.session['foo'] = 'bar' # Handle the response through the middleware. response = middleware.process_response(request, response) self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),)) # A cookie should be set, along with Vary: Cookie. self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Empty the session data. del request.session['foo'] # Handle the response through the middleware. response = HttpResponse('Session test') response = middleware.process_response(request, response) self.assertEqual(dict(request.session.values()), {}) session = Session.objects.get(session_key=request.session.session_key) self.assertEqual(session.get_decoded(), {}) # While the session is empty, it hasn't been flushed so a cookie should # still be set, along with Vary: Cookie. self.assertGreater(len(request.session.session_key), 8) self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie')
def setUp(self): self.request = RequestFactory().request() session_middleware = SessionMiddleware() session_middleware.process_request(self.request) auth_middleware = AuthenticationMiddleware() auth_middleware.process_request(self.request)
class TestUserPreferenceMiddleware(CacheIsolationTestCase): """ Tests to make sure user preferences are getting properly set in the middleware. """ def setUp(self): super(TestUserPreferenceMiddleware, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.middleware = LanguagePreferenceMiddleware() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() self.anonymous_user = AnonymousUserFactory() self.request = RequestFactory().get('/somewhere') self.request.user = self.user self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0' self.session_middleware.process_request(self.request) self.client = Client() def test_logout_shouldnt_remove_cookie(self): self.middleware.process_request(self.request) self.request.user = self.anonymous_user response = mock.Mock(spec=HttpResponse) self.middleware.process_response(self.request, response) response.delete_cookie.assert_not_called() @ddt.data(None, 'es', 'en') def test_preference_setting_changes_cookie(self, lang_pref_out): """ Test that the LANGUAGE_COOKIE is always set to the user's current language preferences at the end of the request, with an expiry that's the same as the users current session cookie. """ if lang_pref_out: set_user_preference(self.user, LANGUAGE_KEY, lang_pref_out) else: delete_user_preference(self.user, LANGUAGE_KEY) response = mock.Mock(spec=HttpResponse) self.middleware.process_response(self.request, response) if lang_pref_out: response.set_cookie.assert_called_with( settings.LANGUAGE_COOKIE, value=lang_pref_out, domain=settings.SESSION_COOKIE_DOMAIN, max_age=COOKIE_DURATION, secure=self.request.is_secure(), ) else: response.delete_cookie.assert_called_with( settings.LANGUAGE_COOKIE, domain=settings.SESSION_COOKIE_DOMAIN, ) assert LANGUAGE_SESSION_KEY not in self.request.session @ddt.data(*itertools.product( (None, 'eo', 'es'), # LANGUAGE_COOKIE (None, 'es', 'en'), # Language Preference In )) @ddt.unpack @mock.patch( 'openedx.core.djangoapps.lang_pref.middleware.set_user_preference') def test_preference_cookie_changes_setting(self, lang_cookie, lang_pref_in, mock_set_user_preference): self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie if lang_pref_in: set_user_preference(self.user, LANGUAGE_KEY, lang_pref_in) else: delete_user_preference(self.user, LANGUAGE_KEY) self.middleware.process_request(self.request) if lang_cookie is None: assert mock_set_user_preference.mock_calls == [] else: mock_set_user_preference.assert_called_with( self.user, LANGUAGE_KEY, lang_cookie) @ddt.data(*( (logged_in, ) + test_def for logged_in in (True, False) for test_def in [ # (LANGUAGE_COOKIE, LANGUAGE_SESSION_KEY, Accept-Language In, # Accept-Language Out, Session Lang Out) (None, None, None, None, None), (None, 'eo', None, None, 'eo'), (None, 'en', None, None, 'en'), (None, 'eo', 'en', 'en', 'eo'), (None, None, 'en', 'en', None), ('en', None, None, 'en', None), ('en', 'en', None, 'en', 'en'), ('en', None, 'eo', 'en;q=1.0,eo', None), ('en', None, 'en', 'en', None), ('en', 'eo', 'en', 'en', None), ('en', 'eo', 'eo', 'en;q=1.0,eo', None) ])) @ddt.unpack def test_preference_cookie_overrides_browser( self, logged_in, lang_cookie, lang_session_in, accept_lang_in, accept_lang_out, lang_session_out, ): if not logged_in: self.request.user = self.anonymous_user if lang_cookie: self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie if lang_session_in: self.request.session[LANGUAGE_SESSION_KEY] = lang_session_in if accept_lang_in: self.request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang_in else: del self.request.META['HTTP_ACCEPT_LANGUAGE'] self.middleware.process_request(self.request) accept_lang_result = self.request.META.get('HTTP_ACCEPT_LANGUAGE') if accept_lang_result: accept_lang_result = parse_accept_lang_header(accept_lang_result) if accept_lang_out: accept_lang_out = parse_accept_lang_header(accept_lang_out) if accept_lang_out and accept_lang_result: six.assertCountEqual(self, accept_lang_result, accept_lang_out) else: assert accept_lang_result == accept_lang_out assert self.request.session.get( LANGUAGE_SESSION_KEY) == lang_session_out @ddt.data(None, 'es', 'en') def test_logout_preserves_cookie(self, lang_cookie): if lang_cookie: self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie elif settings.LANGUAGE_COOKIE in self.client.cookies: del self.client.cookies[settings.LANGUAGE_COOKIE] # Use an actual call to the logout endpoint, because the logout function # explicitly clears all cookies self.client.get(reverse('logout')) if lang_cookie: assert self.client.cookies[ settings.LANGUAGE_COOKIE].value == lang_cookie else: assert settings.LANGUAGE_COOKIE not in self.client.cookies @ddt.data((None, None), ('es', 'es-419'), ('en', 'en'), ('es-419', 'es-419')) @ddt.unpack def test_login_captures_lang_pref(self, lang_cookie, expected_lang): if lang_cookie: self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie elif settings.LANGUAGE_COOKIE in self.client.cookies: del self.client.cookies[settings.LANGUAGE_COOKIE] # Use an actual call to the login endpoint, to validate that the middleware # stack does the right thing response = self.client.post( reverse('user_api_login_session'), data={ 'email': self.user.email, 'password': UserFactory._DEFAULT_PASSWORD, # pylint: disable=protected-access 'remember': True, }) assert response.status_code == 200 if lang_cookie: assert response['Content-Language'] == expected_lang assert get_user_preference(self.user, LANGUAGE_KEY) == lang_cookie assert self.client.cookies[ settings.LANGUAGE_COOKIE].value == lang_cookie else: assert response['Content-Language'] == 'en' assert get_user_preference(self.user, LANGUAGE_KEY) is None assert self.client.cookies[settings.LANGUAGE_COOKIE].value == '' def test_process_response_no_user_noop(self): del self.request.user response = mock.Mock(spec=HttpResponse) result = self.middleware.process_response(self.request, response) assert result is response assert response.mock_calls == [] def test_preference_update_noop(self): self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'es' # No preference yet, should write to the database assert get_user_preference(self.user, LANGUAGE_KEY) is None self.middleware.process_request(self.request) assert get_user_preference(self.user, LANGUAGE_KEY) == 'es' response = mock.Mock(spec=HttpResponse) with self.assertNumQueries(1): self.middleware.process_response(self.request, response) # Preference is the same as the cookie, shouldn't write to the database with self.assertNumQueries(3): self.middleware.process_request(self.request) assert get_user_preference(self.user, LANGUAGE_KEY) == 'es' response = mock.Mock(spec=HttpResponse) with self.assertNumQueries(1): self.middleware.process_response(self.request, response) # Cookie changed, should write to the database again self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'en' self.middleware.process_request(self.request) assert get_user_preference(self.user, LANGUAGE_KEY) == 'en' with self.assertNumQueries(1): self.middleware.process_response(self.request, response) @mock.patch( 'openedx.core.djangoapps.lang_pref.middleware.is_request_from_mobile_app' ) @mock.patch( 'openedx.core.djangoapps.lang_pref.middleware.get_user_preference') def test_remove_lang_cookie_for_mobile_app(self, mock_get_user_preference, mock_is_mobile_request): """ Test to verify language preference cookie removed for mobile app requests. """ mock_get_user_preference.return_value = 'en' mock_is_mobile_request.return_value = False response = mock.Mock(spec=HttpResponse) response = self.middleware.process_response(self.request, response) response.delete_cookie.assert_not_called() response.set_cookie.assert_called() mock_is_mobile_request.return_value = True response = self.middleware.process_response(self.request, response) response.delete_cookie.assert_called()
def process_request(request): middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
class TestUserPreferenceMiddleware(TestCase): """ Tests to make sure user preferences are getting properly set in the middleware """ def setUp(self): super(TestUserPreferenceMiddleware, self).setUp() self.middleware = LanguagePreferenceMiddleware() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() self.anonymous_user = AnonymousUserFactory() self.request = RequestFactory().get('/somewhere') self.request.user = self.user self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0' # pylint: disable=no-member self.session_middleware.process_request(self.request) def test_no_language_set_in_session_or_prefs(self): # nothing set in the session or the prefs self.middleware.process_request(self.request) self.assertNotIn(LANGUAGE_SESSION_KEY, self.request.session) @mock.patch('lang_pref.middleware.released_languages', mock.Mock(return_value=[('eo', 'esperanto')])) def test_language_in_user_prefs(self): # language set in the user preferences and not the session set_user_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEquals(self.request.session[LANGUAGE_SESSION_KEY], 'eo') @mock.patch('lang_pref.middleware.released_languages', mock.Mock(return_value=[('en', 'english'), ('eo', 'esperanto')])) def test_language_in_session(self): # language set in both the user preferences and session, # preference should get precedence. The session will hold the last value, # which is probably the user's last preference. Look up the updated preference. # Dark lang middleware should run after this middleware, so it can # set a session language as an override of the user's preference. self.request.session[LANGUAGE_SESSION_KEY] = 'en' set_user_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEquals(self.request.session[LANGUAGE_SESSION_KEY], 'eo') @mock.patch('lang_pref.middleware.released_languages', mock.Mock(return_value=[('eo', 'dummy Esperanto'), ('ar', 'arabic')]) ) def test_supported_browser_language_in_session(self): """ test: browser language should be set in user session if it is supported by system for unauthenticated user. """ self.request.user = self.anonymous_user self.middleware.process_request(self.request) self.assertEqual(self.request.session[LANGUAGE_SESSION_KEY], 'ar') # pylint: disable=no-member @mock.patch('lang_pref.middleware.released_languages', mock.Mock(return_value=[('en', 'english')])) def test_browser_language_not_be_in_session(self): """ test: browser language should not be set in user session if it is not supported by system. """ self.request.user = self.anonymous_user self.middleware.process_request(self.request) self.assertNotEqual(self.request.session.get(LANGUAGE_SESSION_KEY), 'ar') # pylint: disable=no-member @mock.patch('lang_pref.middleware.released_languages', mock.Mock(return_value=[('en', 'english'), ('ar', 'arabic')])) def test_delete_user_lang_preference_not_supported_by_system(self): """ test: user preferred language has been removed from user preferences model if it is not supported by system for authenticated users. """ set_user_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEqual(get_user_preference(self.request.user, LANGUAGE_KEY), None)
class FacebookCanvasMiddlewareTest(FacebookTest): def setUp(self): super(FacebookCanvasMiddlewareTest, self).setUp() self.factory = RequestFactory() self.middleware = FacebookCanvasMiddleWare() self.session_middleware = SessionMiddleware() def get_canvas_url(self, data={}): request = self.factory.post('/', data) request.META['HTTP_REFERER'] = 'https://apps.facebook.com/canvas/' self.session_middleware.process_request(request) return request def test_referer(self): # test empty referer request = self.factory.get('/') self.assertIsNone(self.middleware.process_request(request)) # test referer not facebook request = self.factory.get('/') request.META['HTTP_REFERER'] = 'https://*****:*****@patch.object(FacebookAuthorization, 'parse_signed_data') def test_non_auth_user( self, mocked_method=FacebookAuthorization.parse_signed_data): mocked_method.return_value = {} data = { 'signed_request': 'dXairHLF8dfUKaL7ZFXaKmTsAglg0EkyHesTLnPcPAE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTM1ODA2MTU1MSwidXNlciI6eyJjb3VudHJ5IjoiYnIiLCJsb2NhbGUiOiJlbl9VUyIsImFnZSI6eyJtaW4iOjIxfX19' } request = self.get_canvas_url(data=data) response = self.middleware.process_request(request) self.assertTrue(mocked_method.called) self.assertIsInstance(response, ScriptRedirect) @patch('django_facebook.middleware.connect_user', fake_connect) @patch.object(OpenFacebook, 'permissions') @patch.object(FacebookAuthorization, 'parse_signed_data') def test_auth_user(self, mocked_method_1=FacebookAuthorization.parse_signed_data, mocked_method_2=OpenFacebook.permissions): data = { 'signed_request': 'd7JQQIfxHgEzLIqJMeU9J5IlLg7shzPJ8DFRF55L52w.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTgwNzQ4MDAsImlzc3VlZF9hdCI6MTM1ODA2ODU1MCwib2F1dGhfdG9rZW4iOiJBQUFGdk02MWpkT0FCQVBhWkNzR1pDM0dEVFZtdDJCWkFQVlpDc0F0aGNmdXBYUnhMN1cwUHBaQm53OEUwTzBBRVNYNjVaQ0JHdjZpOFRBWGhnMEpzbER5UmtmZUlnYnNHUmV2eHQxblFGZ0hNcFNpeTNWRTB3ZCIsInVzZXIiOnsiY291bnRyeSI6ImJyIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiMTAwMDA1MDEyNDY2Nzg1In0' } request = self.get_canvas_url(data=data) request.user = AnonymousUser() mocked_method_1.return_value = { 'user_id': '123456', 'oauth_token': 'qwertyuiop' } mocked_method_2.return_value = facebook_settings.FACEBOOK_DEFAULT_SCOPE self.assertIsNone(self.middleware.process_request(request)) self.assertTrue(mocked_method_1.called)
class CountryMiddlewareTests(TestCase): """ Tests of CountryMiddleware. """ def setUp(self): super(CountryMiddlewareTests, self).setUp() self.country_middleware = CountryMiddleware() self.session_middleware = SessionMiddleware() self.authenticated_user = UserFactory.create() self.anonymous_user = AnonymousUserFactory.create() self.request_factory = RequestFactory() self.patcher = patch.object(pygeoip.GeoIP, 'country_code_by_addr', self.mock_country_code_by_addr) self.patcher.start() def tearDown(self): self.patcher.stop() def mock_country_code_by_addr(self, ip_addr): """ Gives us a fake set of IPs """ ip_dict = { '117.79.83.1': 'CN', '117.79.83.100': 'CN', '4.0.0.0': 'SD', '2001:da8:20f:1502:edcf:550b:4a9c:207d': 'CN', } return ip_dict.get(ip_addr, 'US') def test_country_code_added(self): request = self.request_factory.get( '/somewhere', HTTP_X_FORWARDED_FOR='117.79.83.1', ) request.user = self.authenticated_user self.session_middleware.process_request(request) # No country code exists before request. self.assertNotIn('country_code', request.session) self.assertNotIn('ip_address', request.session) self.country_middleware.process_request(request) # Country code added to session. self.assertEqual('CN', request.session.get('country_code')) self.assertEqual('117.79.83.1', request.session.get('ip_address')) def test_ip_address_changed(self): request = self.request_factory.get( '/somewhere', HTTP_X_FORWARDED_FOR='4.0.0.0', ) request.user = self.anonymous_user self.session_middleware.process_request(request) request.session['country_code'] = 'CN' request.session['ip_address'] = '117.79.83.1' self.country_middleware.process_request(request) # Country code is changed. self.assertEqual('SD', request.session.get('country_code')) self.assertEqual('4.0.0.0', request.session.get('ip_address')) def test_ip_address_is_not_changed(self): request = self.request_factory.get( '/somewhere', HTTP_X_FORWARDED_FOR='117.79.83.1', ) request.user = self.anonymous_user self.session_middleware.process_request(request) request.session['country_code'] = 'CN' request.session['ip_address'] = '117.79.83.1' self.country_middleware.process_request(request) # Country code is not changed. self.assertEqual('CN', request.session.get('country_code')) self.assertEqual('117.79.83.1', request.session.get('ip_address')) def test_same_country_different_ip(self): request = self.request_factory.get( '/somewhere', HTTP_X_FORWARDED_FOR='117.79.83.100', ) request.user = self.anonymous_user self.session_middleware.process_request(request) request.session['country_code'] = 'CN' request.session['ip_address'] = '117.79.83.1' self.country_middleware.process_request(request) # Country code is not changed. self.assertEqual('CN', request.session.get('country_code')) self.assertEqual('117.79.83.100', request.session.get('ip_address')) def test_ip_address_is_none(self): # IP address is not defined in request. request = self.request_factory.get('/somewhere') request.user = self.anonymous_user # Run process_request to set up the session in the request # to be able to override it. self.session_middleware.process_request(request) request.session['country_code'] = 'CN' request.session['ip_address'] = '117.79.83.1' self.country_middleware.process_request(request) # No country code exists after request processing. self.assertNotIn('country_code', request.session) self.assertNotIn('ip_address', request.session) def test_ip_address_is_ipv6(self): request = self.request_factory.get( '/somewhere', HTTP_X_FORWARDED_FOR='2001:da8:20f:1502:edcf:550b:4a9c:207d') request.user = self.authenticated_user self.session_middleware.process_request(request) # No country code exists before request. self.assertNotIn('country_code', request.session) self.assertNotIn('ip_address', request.session) self.country_middleware.process_request(request) # Country code added to session. self.assertEqual('CN', request.session.get('country_code')) self.assertEqual('2001:da8:20f:1502:edcf:550b:4a9c:207d', request.session.get('ip_address'))
def get_request(self, url='/'): request = self.request_factory.get('/') middleware = SessionMiddleware() middleware.process_request(request) request.session.save() return request
def setUp(self): super(FacebookCanvasMiddlewareTest, self).setUp() self.factory = RequestFactory() self.middleware = FacebookCanvasMiddleWare() self.session_middleware = SessionMiddleware()
class TestMiddleware(DjangoTestCase): django_session_middleware = SessionMiddleware() django_auth_middleware = AuthenticationMiddleware() middleware = APIAuthenticationMiddleware() def test_impropertly_configured(self): request = RequestFactory().get('/') assert_raises(ImproperlyConfigured, self.middleware.process_request, request) def _get_request(self, **headers): # boilerplate stuff request = RequestFactory(**headers).get('/') self.django_session_middleware.process_request(request) self.django_auth_middleware.process_request(request) assert request.user return request def test_no_token_key(self): request = self._get_request() eq_(self.middleware.process_request(request), None) def test_non_existant_token_key(self): request = self._get_request(HTTP_AUTH_TOKEN='xxx') response = self.middleware.process_request(request) eq_(response.status_code, 403) # the response content will be JSON result = json.loads(response.content) eq_(result['error'], 'API Token not matched') def test_expired_token(self): user = User.objects.create(username='******') token = models.Token.objects.create(user=user, ) token.expires -= datetime.timedelta( days=settings.TOKENS_DEFAULT_EXPIRATION_DAYS) token.save() request = self._get_request(HTTP_AUTH_TOKEN=token.key) response = self.middleware.process_request(request) eq_(response.status_code, 403) result = json.loads(response.content) eq_(result['error'], 'API Token found but expired') def test_token_valid(self): user = User.objects.create(username='******') token = models.Token.objects.create(user=user, ) request = self._get_request(HTTP_AUTH_TOKEN=token.key) response = self.middleware.process_request(request) eq_(response, None) eq_(request.user, user) def test_token_permissions(self): user = User.objects.create(username='******') token = models.Token.objects.create(user=user, ) ct, __ = ContentType.objects.get_or_create( model='', app_label='crashstats', ) permission = Permission.objects.create(codename='play', content_type=ct) token.permissions.add(permission) Permission.objects.create(codename='fire', content_type=ct) # deliberately not adding this second permission request = self._get_request(HTTP_AUTH_TOKEN=token.key) # do the magic to the request self.middleware.process_request(request) eq_(request.user, user) ok_(request.user.has_perm('crashstats.play')) ok_(not request.user.has_perm('crashstats.fire'))
def add_session_to_request(request): """Annotate a request object with a session""" middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
def generate_request_anonymous(): request = RequestFactory().get('/') SessionMiddleware().process_request(request) request.session.save() request.user = AnonymousUser() return request