我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用django.contrib.auth.models.AnonymousUser()。
def test_get_json_context(self): view = self.get_instance(PublicStreamView, request=self.get_request(self.user)) self.assertEqual( view.get_json_context(), { "currentBrowsingProfileId": self.user.profile.id, "streamName": view.stream_name, "isUserAuthenticated": True, } ) view = self.get_instance(PublicStreamView, request=self.get_request(AnonymousUser())) self.assertEqual( view.get_json_context(), { "currentBrowsingProfileId": None, "streamName": view.stream_name, "isUserAuthenticated": False, } )
def test_get_json_context(self): view = self.get_instance(TagStreamView, request=self.get_request(self.user)) view.tag = self.tag_no_content self.assertEqual( view.get_json_context(), { "currentBrowsingProfileId": self.user.profile.id, "streamName": view.stream_name, "isUserAuthenticated": True, } ) view = self.get_instance(TagStreamView, request=self.get_request(AnonymousUser())) view.tag = self.tag_no_content self.assertEqual( view.get_json_context(), { "currentBrowsingProfileId": None, "streamName": view.stream_name, "isUserAuthenticated": False, } )
def _get_request_view_and_content(self, create_content=True, anonymous_user=False): request = self.client.get("/") if anonymous_user: request.user = AnonymousUser() profile = self.profile else: request.user = self.user profile = self.user.profile contents = [] if create_content: contents.extend([ ContentFactory(author=profile, order=3, pinned=True), ContentFactory(author=profile, order=2, pinned=True), ContentFactory(author=profile, order=1, pinned=True), ]) Content.objects.filter(id=contents[0].id).update(order=3) Content.objects.filter(id=contents[1].id).update(order=2) Content.objects.filter(id=contents[2].id).update(order=1) view = ProfileDetailView(request=request, kwargs={"guid": profile.guid}) view.object = profile view.target_profile = profile return request, view, contents, profile
def setUpTestData(cls): super().setUpTestData() cls.create_local_and_remote_user() cls.user2 = AnonymousUser() cls.local_user = UserFactory() cls.public_content = ContentFactory( visibility=Visibility.PUBLIC, text="**Foobar**", author=cls.profile, ) cls.site_content = ContentFactory( visibility=Visibility.SITE, text="_Foobar_" ) cls.limited_content = ContentFactory(visibility=Visibility.LIMITED) cls.self_content = ContentFactory(visibility=Visibility.SELF) cls.remote_content = ContentFactory( visibility=Visibility.PUBLIC, remote_created=make_aware(datetime.datetime(2015, 1, 1)), author=cls.remote_profile, ) cls.ids = [ cls.public_content.id, cls.site_content.id, cls.limited_content.id, cls.self_content.id ] cls.set = { cls.public_content, cls.site_content, cls.limited_content, cls.self_content }
def setUpTestData(cls): super().setUpTestData() cls.create_local_and_remote_user() cls.anonymous_user = AnonymousUser() cls.other_user = PublicUserFactory() cls.create_content_set() cls.public_reply = PublicContentFactory(parent=cls.public_content) cls.limited_reply = LimitedContentFactory(parent=cls.limited_content) cls.self_reply = SelfContentFactory(parent=cls.self_content) cls.site_reply = SiteContentFactory(parent=cls.site_content) cls.public_share = PublicContentFactory(share_of=cls.public_content, author=cls.remote_profile) cls.limited_share = LimitedContentFactory(share_of=cls.limited_content, author=cls.remote_profile) cls.self_share = SelfContentFactory(share_of=cls.self_content, author=cls.remote_profile) cls.site_share = SiteContentFactory(share_of=cls.site_content, author=cls.remote_profile) cls.public_share_reply = PublicContentFactory(parent=cls.public_share) cls.share_limited_reply = LimitedContentFactory(parent=cls.limited_share) cls.share_self_reply = SelfContentFactory(parent=cls.self_share) cls.share_site_reply = SiteContentFactory(parent=cls.site_share)
def test_create_issue(self): responses.add( responses.GET, 'https://getsentry.atlassian.net/rest/api/2/issue/createmeta', json=create_meta_response) responses.add(responses.POST, 'https://getsentry.atlassian.net/rest/api/2/issue', json={ 'key': 'SEN-1' }) self.plugin.set_option('instance_url', 'https://getsentry.atlassian.net', self.project) group = self.create_group(message='Hello world', culprit='foo.bar') request = self.request.get('/') request.user = AnonymousUser() form_data = { 'title': 'Hello', 'description': 'Fix this.', 'issuetype': 'bug', 'project': 'SEN' } assert self.plugin.create_issue(request, group, form_data) == 'SEN-1'
def test_amending_quantity_on_existing_item(self): session = self.client.session request = self.client.post(reverse('cart:add', kwargs={'product_id': self.test_product.id}), data={'quantity': 1}, follow=True) request.session = session request.user = AnonymousUser() quantity = 1 cart = get_cart(request) cart_item, cart_item_created = CartItem.objects.update_or_create( cart=cart, product=self.test_product) if cart_item_created == False: cart_item.quantity += quantity cart_item.save() self.assertEqual(cart_item.quantity, 2)
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated(): user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser()
def auth(request): """ Returns context variables required by apps that use Django's authentication system. If there is no 'user' attribute in the request, uses AnonymousUser (from django.contrib.auth). """ if hasattr(request, 'user'): user = request.user else: from django.contrib.auth.models import AnonymousUser user = AnonymousUser() return { 'user': user, 'perms': PermWrapper(user), }
def logout(request): """ Removes the authenticated user's ID from the request and flushes their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated: user = None user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None: request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser()
def test_checkout_deliveries(): partition = Mock( get_total=Mock(return_value=Price(10, currency=settings.DEFAULT_CURRENCY)), get_price_per_item=Mock(return_value=Price(10, currency=settings.DEFAULT_CURRENCY))) def f(): yield partition partition.__iter__ = Mock(return_value=f()) cart = Mock(partition=Mock(return_value=[partition]), currency=settings.DEFAULT_CURRENCY) checkout = Checkout( cart, AnonymousUser(), 'tracking_code') deliveries = list(checkout.deliveries) assert deliveries[0][1] == Price(0, currency=settings.DEFAULT_CURRENCY) assert deliveries[0][2] == partition.get_total() assert deliveries[0][0][0][0] == partition
def token_authentication_middleware(get_response): ''' A middleware that checks authentication token and sets request.user instance if the token is valid. ''' def middleware(request): if getattr(request, 'user', None) is not None and request.user.is_authenticated: warnings.warn(_('request.user has been set before token_middleware' ' and will be overwritten. To disable this message' ' remove AuthenticationMiddleware from middleware' ' list.')) token_header = request.META.get('HTTP_' + settings.TOKEN_HEADER, '') token_value = token_header.split(settings.TOKEN_PREFIX)[-1].strip() token = AuthToken.objects.filter( value=token_value, user_id__is_active=True).first() if token: request.user = token.user else: request.user = AnonymousUser() return get_response(request) return middleware
def test_create_message_mutation(): user = mixer.blend('auth.User') mut = schema.CreateMessageMutation() data = {'message': 'Test'} req = RequestFactory().get('/') req.user = AnonymousUser() res = mut.mutate(None, data, req, None) assert res.status == 403, 'Should return 403 if user is not logged in' req.user = user res = mut.mutate(None, {}, req, None) assert res.status == 400, 'Should return 400 if there are form errors' assert 'message' in res.formErrors, ( 'Should have form error for message field') req.user = user res = mut.mutate(None, {'message': 'Test'}, req, None) assert res.status == 200, 'Should return 400 if there are form errors' assert res.message.pk == 1, 'Should create new message'
def _build_mock_request(self, user=None, get=None, post=None): request = MagicMock() if user: request.user = user if django.VERSION[:2] >= (1, 10): # Django 1.10 made `User.is_authenticated` into a property for # some reason. request.user.is_authenticated.__get__ = MagicMock(return_value=True) # nopep8 else: request.user.is_authenticated = MagicMock(return_value=True) else: request.user = AnonymousUser() request.GET = {} request.POST = {} request.resolver_match.kwargs = {} if get is not None: request.GET.update(get) if post is not None: request.POST.update(post) return request
def get_user_jwt(request): """ Replacement for django session auth get_user & auth.get_user JSON Web Token authentication. Inspects the token for the user_id, attempts to get that user from the DB & assigns the user on the request object. Otherwise it defaults to AnonymousUser. This will work with existing decorators like LoginRequired ;) Returns: instance of user object or AnonymousUser object """ user = None try: user_jwt = JSONWebTokenAuthentication().authenticate(Request(request)) if user_jwt is not None: # store the first part from the tuple (user, obj) user = user_jwt[0] except: pass return user or AnonymousUser()
def test_scan_result_view_anonymous_user_get_request(self): request = RequestFactory().post('/urlscan/', {'url': 'https://github.com/'}) request.user = AnonymousUser() response = UrlScanView.as_view()(request) url = response.url digits_in_url = url[12:] scan_id = '' for character in digits_in_url: try: scan_id = scan_id + str(int(character)) except: pass scan_id = int(scan_id) request = RequestFactory().get('/scanresult/') response = ScanResults.as_view()(request, pk=scan_id) self.assertIn('<h3>Please wait... Your tasks are in the queue.\n Reload in 5-10 minutes</h3>\n', response.content)
def test_scan_result_view_anonymous_user_post_request(self): request = RequestFactory().post('/urlscan/', {'url': 'https://github.com/'}) request.user = AnonymousUser() response = UrlScanView.as_view()(request) url = response.url digits_in_url = url[12:] scan_id = '' for character in digits_in_url: try: scan_id = scan_id + str(int(character)) except: pass scan_id = int(scan_id) request = RequestFactory().post('/scanresult/', {'post_apple': 'Apple'}) response = ScanResults.as_view()(request, pk=scan_id) self.assertEqual(405, response.status_code)
def test_anonymous_user(self): user = AnonymousUser() voucher = Voucher.objects.create( name='Test Voucher', code='test-voucher', usage=Voucher.MULTI_USE, start_datetime=datetime.now(), end_datetime=datetime.now(), limit_usage_by_group=False) is_available, message = voucher.is_available_to_user(user) self.assertTrue(is_available) voucher.limit_usage_by_group = True voucher.save() is_available, message = voucher.is_available_to_user(user) self.assertFalse(is_available) self.assertEqual(message, "This voucher is only available to selected users")
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)
def _test_signup_email_verified_externally(self, signup_email, verified_email): username = 'johndoe' 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 groups_of_user(user): """ Returns a list of groups the *user* is a member of. The parameter *user* can be an instance of User or the id number of a user. """ if ( user is None or type( user ) == AnonymousUser ): return list() if isinstance(user, User): pass elif isinstance(user, int) or isinstance(user, long): user = User.objects.get(id=user) elif isinstance(user, unicode) or isinstance(user, str): user = User.objects.get( id = int( user ) ) else: raise TypeError( "'user' must be a User instance or an integer but it was " + str(user.__class__)) return list(Group.objects.filter(membership__user=user))
def test_middleware_current_user(self): mw = PublishingMiddleware() # Request processing sets current user, AnonymousUser by default mw.process_request(self._request()) self.assertTrue(mw.get_current_user().is_anonymous()) self.assertTrue(get_current_user().is_anonymous()) # Request processing sets current user when provided mw.process_request(self._request(user=self.reviewer_user)) self.assertEqual(mw.get_current_user(), self.reviewer_user) self.assertEqual(get_current_user(), self.reviewer_user) # Test context manager override mw.process_request(self._request(user=self.reviewer_user)) with override_current_user(AnonymousUser()): self.assertTrue(mw.get_current_user().is_anonymous()) self.assertTrue(get_current_user().is_anonymous()) # Response processing clears current user mw.process_response(self._request(), self.response) self.assertIsNone(mw.get_current_user()) self.assertIsNone(get_current_user())
def request(self, method='GET', user=AnonymousUser(), url_kwargs={}, post_data={}, get_data={}, view_kwargs={}, request_meta={}, session_data={}): kwargs = locals() del kwargs['self'] self._request, response = self._make_request(**kwargs) content_disp = response._headers.get('content-disposition') content = None if hasattr(response, 'render'): content = remove_csrf(response.render().content.decode('utf-8')) elif (hasattr(response, 'content') and not (content_disp and 'attachment' in content_disp[1])): content = response.content.decode('utf-8') return Response( status_code=response.status_code, content=content, location=response.get('location', None), messages=[str(m) for m in get_messages(self._request)], headers=response._headers )