def test_get(self): request = Mock(spec_set=['GET', 'session']) request.session = {} show = 10 func_name = 'func_name' name = 'name' order_by = 'Time' request.GET = { 'show': show, 'func_name': func_name, 'name': name, 'order_by': order_by } context = ProfilingView()._create_context(request) self.assertDictContainsSubset( { 'show': show, 'order_by': order_by, 'func_name': func_name, 'name': name, 'options_show': ProfilingView.show, 'options_order_by': ProfilingView.order_by, 'options_func_names': ProfilingView()._get_function_names() }, context) self.assertIn('results', context)
def test_bad_restore(self): user = Mock() user.domain = None app_id = None request = Mock() request.GET = {} request.openrosa_headers = {} timing_context = Mock() timing_context.to_list.return_value = [] with patch('corehq.apps.hqadmin.views.users.get_restore_response', return_value=(HttpResponse('bad response', status=500), timing_context)): view = AdminRestoreView(user=user, app_id=app_id, request=request) context = view.get_context_data(foo='bar', view='AdminRestoreView') self.assertEqual( context, { 'foo': 'bar', 'view': 'AdminRestoreView', 'payload': '<error>Unexpected restore response 500: bad response. If you believe this is a bug ' 'please report an issue.</error>\n', 'status_code': 500, 'timing_data': [], 'hide_xml': False, })
def test_ok_with_remaining_data(self): user_model = get_user_model() user1 = user_model.objects.create(email='*****@*****.**') room_1 = Room.objects.create(owner=user1, title='test-room', slug='test-slug') message_1 = Message.objects.create(author=user1, room=room_1, text='test text') message_2 = Message.objects.create(author=user1, room=room_1, text='test text 2') message_3 = Message.objects.create(author=user1, room=room_1, text='test text 3') request = Mock() request.GET = { 'limit': 2, 'offset': 0, } messages, no_more_data = message_filter(request, room_1.slug) messages_list = [msg for msg in messages] expected_messages_list = [message_3, message_2] self.assertEqual(messages_list, expected_messages_list) self.assertFalse(no_more_data)
def test_bulk_add_collection(self): # create a DigitizedWorkAdmin object digworkadmin = DigitizedWorkAdmin(DigitizedWork, AdminSite()) fakerequest = Mock() fakerequest.session = {} # set some arbitary querystring filters fakerequest.GET = {'q': 1, 'foo': 'bar'} queryset = DigitizedWork.objects.all() redirect = digworkadmin.bulk_add_collection(fakerequest, queryset) # should return a redirect assert isinstance(redirect, HttpResponseRedirect) # url should reverse the appropriate route assert redirect.url == reverse('archive:add-to-collection') # session on request should be set with a key called collection-add-ids # that is not empty assert fakerequest.session['collection-add-ids'] # the key should have the ids of the three fixtures assert set(fakerequest.session['collection-add-ids']) == \ set(queryset.values_list('id', flat=True)) # the querystring should have been faithfully copied to session as well assert fakerequest.session['collection-add-filters'] == fakerequest.GET redirect = digworkadmin.bulk_add_collection(fakerequest, queryset) # test against an empty queryset just in case DigitizedWork.objects.all().delete() queryset = DigitizedWork.objects.all() redirect = digworkadmin.bulk_add_collection(fakerequest, queryset) # session variable should be set to an empty list assert fakerequest.session['collection-add-ids'] == []
def _build_request( self, method: str, path: str, data: Dict, request_params: Any ) -> Mock: request = Mock() request.method = method request.path = path request.body = "" request.COOKIES = {} request._dont_enforce_csrf_checks = True request.is_secure.return_value = False request.build_absolute_uri = build_absolute_uri if "user" not in request_params: request.user.is_authenticated = False request.META = request_params.pop("META", {}) request.FILES = request_params.pop("FILES", {}) request.META.update( dict( [ (f"HTTP_{k.replace('-', '_')}", v) for k, v in request_params.pop("headers", {}).items() ] ) ) if django.VERSION[:2] > (2, 1): from django.http.request import HttpHeaders request.headers = HttpHeaders(request.META) if isinstance(data, QueryDict): request.POST = data else: request.POST = QueryDict(mutable=True) for k, v in data.items(): request.POST[k] = v if "?" in path: request.GET = QueryDict(path.split("?")[1]) else: request.GET = QueryDict() for k, v in request_params.items(): setattr(request, k, v) return request
def test_set_default_flavour(self): request = Mock() request.META = MagicMock() request.GET = {} middleware = SetFlavourMiddleware() middleware.process_request(request) # default flavour is set self.assertEqual(get_flavour(), 'full')
def test_set_flavour_through_get_parameter(self, set_flavour): request = Mock() request.META = MagicMock() request.GET = {'flavour': 'mobile'} middleware = SetFlavourMiddleware() middleware.process_request(request) self.assertEqual(set_flavour.call_args, (('mobile', request), { 'permanent': True }))
def _build_request(room_id, popup=None): request = Mock() request.GET = { "hour": hour(2).strftime("%Y-%m-%d-%H-%M-%S-%f-%Z"), "room": room_id, } if popup: request.GET["_popup"] = 1 return request
def test_max_request(self): SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = 10 # 10kb mock_request = Mock() mock_request.META = {'CONTENT_TYPE': 'text/plain'} mock_request.GET = {} mock_request.method = 'get' mock_request.body = 'a'.encode('ascii') * 1024 * 100 # 100kb mock_request.path = reverse('silk:requests') request_model = RequestModelFactory(mock_request).construct_request_model() self.assertFalse(request_model.raw_body)
def test_no_long_url(self): url = '1234567890' * 19 # 190-character URL mock_request = Mock() mock_request.META = {'CONTENT_TYPE': 'text/plain'} mock_request.GET = {} mock_request.path = url mock_request.method = 'get' request_model = RequestModelFactory( mock_request).construct_request_model() self.assertEqual(request_model.path, url)
def test_redirect_url_returns_no_params_if_no_username(self): user = Mock() request = Mock() request.GET = {} view = DisableUserView(user=user, request=request) with patch('corehq.apps.hqadmin.views.users.reverse') as mock_reverse: mock_reverse.return_value = 'dummy_url' redirect_url = view.redirect_url self.assertEqual(redirect_url, 'dummy_url')
def test_long_url(self): url = '1234567890' * 200 # 2000-character URL mock_request = Mock() mock_request.META = {'CONTENT_TYPE': 'text/plain'} mock_request.GET = {} mock_request.method = 'get' mock_request.path = url request_model = RequestModelFactory( mock_request).construct_request_model() self.assertEqual(request_model.path, f'{url[:94]}...{url[1907:]}') self.assertEqual(len(request_model.path), 190)
def test_item_filtering(self): request = Mock() request.GET = {} with patch('snippets.base.feed.models.ASRSnippet') as ASRSnippetMock: with patch('snippets.base.feed.ASRSnippetFilter') as ASRSnippetFilterMock: ASRSnippetMock.objects.filter.return_value.order_by.return_value = 'foo' SnippetsFeed()(request) ASRSnippetMock.objects.filter.assert_called_with(for_qa=False, status=models.STATUS_CHOICES['Published']) ASRSnippetFilterMock.assert_called_with(request.GET, queryset='foo')
def test_with_not_valid_params(self): user_model = get_user_model() user1 = user_model.objects.create(email='*****@*****.**') room_1 = Room.objects.create(owner=user1, title='test-room', slug='test-slug') request = Mock() request.GET = {'limit': 3, 'offset': 'a'} with self.assertRaises(ParseError): message_filter(request, room_1.slug)
def test_no_max_request(self): SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = -1 mock_request = Mock() mock_request.META = {'CONTENT_TYPE': 'text/plain'} mock_request.GET = {} mock_request.path = reverse('silk:requests') mock_request.method = 'get' mock_request.body = b'a' * 1000 # 1000 bytes? request_model = RequestModelFactory( mock_request).construct_request_model() self.assertTrue(request_model.raw_body)
def test_item_filtering(self): request = Mock() request.GET = {} with patch('snippets.base.feed.models.Job') as JobMock: with patch('snippets.base.filters.JobFilter') as JobFilterMock: JobMock.objects.filter.return_value.order_by.return_value = 'foo' JobsFeed()(request) JobMock.objects.filter.assert_called() JobFilterMock.assert_called_with(request.GET, queryset='foo')
def test_redirect_url_username_is_encoded(self): user = Mock() request = Mock() request.GET = {'username': '******'} view = DisableUserView(user=user, request=request) with patch('corehq.apps.hqadmin.views.users.reverse') as mock_reverse: mock_reverse.return_value = 'dummy_url/' redirect_url = view.redirect_url self.assertEqual(redirect_url, 'dummy_url/?q=test%2Bexample%40dimagi.com')
def test_process_request_clear(self, redirect_mock): request = Mock() request.GET = { 'ZZ_FEATURE_CLEAR': 1, } request.path = '/dashboard/' assert self.middleware.process_request(request) == redirect_mock.return_value redirect_mock.assert_called_once_with('/dashboard/') response = redirect_mock.return_value response.delete_cookie.assert_called_once_with(FEATURE_FLAG_COOKIE_NAME)
def test_item_filtering(self): request = Mock() request.GET = {} with patch('snippets.base.feed.models.ASRSnippet') as ASRSnippetMock: with patch('snippets.base.feed.ASRSnippetFilter' ) as ASRSnippetFilterMock: ASRSnippetMock.objects.filter.return_value.order_by.return_value = 'foo' SnippetsFeed()(request) ASRSnippetMock.objects.filter.assert_called_with( for_qa=False, status=models.STATUS_CHOICES['Published']) ASRSnippetFilterMock.assert_called_with(request.GET, queryset='foo')
def test_querystring_replace(): mockrequest = Mock() mockrequest.GET = QueryDict("?q=contract") context = {"request": mockrequest} # replace when arg is not present args = corpus_extras.querystring_replace(context, page=1) # preserves existing args assert "q=contract" in args # adds new arg assert "page=1" in args mockrequest.GET = QueryDict("?q=contract&page=2") args = corpus_extras.querystring_replace(context, page=3) assert "q=contract" in args # replaces existing arg assert "page=3" in args assert "page=2" not in args mockrequest.GET = QueryDict("?q=contract&page=2&sort=relevance") args = corpus_extras.querystring_replace(context, page=10) assert "q=contract" in args assert "sort=relevance" in args assert "page=10" in args
def test_default(self): request = Mock(spec_set=['GET', 'session']) request.GET = {} request.session = {} context = ProfilingView()._create_context(request) self.assertTrue(dict_contains({ 'show': ProfilingView.default_show, 'order_by': ProfilingView.defualt_order_by, 'options_show': ProfilingView.show, 'options_order_by': ProfilingView.order_by, 'options_func_names': ProfilingView()._get_function_names() }, context)) self.assertNotIn('path', context) self.assertIn('results', context)
def test_process_request_clear(self, redirect_mock): request = Mock() request.GET = { 'ZZ_FEATURE_CLEAR': 1, } request.path = '/dashboard/' assert self.middleware.process_request( request) == redirect_mock.return_value redirect_mock.assert_called_once_with('/dashboard/') response = redirect_mock.return_value response.delete_cookie.assert_called_once_with( FEATURE_FLAG_COOKIE_NAME)
def test_logout_signal_trigger_django_messages(self, messages_mocked): # Setup org, admin, user and log the user org = setup_org() setup_admin(org) user = setup_user(org) setup_authenticated_session(self.client, org, user) message_to_display_on_login_page = "bingo!" messages_mocked.return_value = message_to_display_on_login_page mocked_request = Mock() mocked_request.GET = {} mocked_request.axes_attempt_time = datetime.now() user_logged_out.send(self.__class__, request=mocked_request, user=user) messages_mocked.assert_called_once()
def _build_request(self, method: str, path: str, data: dict, request_params: dict): request = Mock() request.method = method request.path = path request.body = "" request.COOKIES = {} if "user" not in request_params: request.user.is_authenticated = False request.META = request_params.pop("META", {}) request.META.update( dict([(f"HTTP_{k}", v) for k, v in request_params.pop("headers", {}).items()])) if django.VERSION[:2] > (2, 1): from django.http.request import HttpHeaders request.headers = HttpHeaders(request.META) if isinstance(data, QueryDict): request.POST = data else: request.POST = QueryDict(mutable=True) for k, v in data.items(): request.POST[k] = v if "?" in path: request.GET = QueryDict(path.split("?")[1]) else: request.GET = QueryDict() for k, v in request_params.items(): setattr(request, k, v) return request
def test_querystring_replace(): mockrequest = Mock() mockrequest.GET = QueryDict('query=saussure') context = {'request': mockrequest} # replace when arg is not present args = querystring_replace(context, page=1) # preserves existing args assert 'query=saussure' in args # adds new arg assert 'page=1' in args mockrequest.GET = QueryDict('query=saussure&page=2') args = querystring_replace(context, page=3) assert 'query=saussure' in args # replaces existing arg assert 'page=3' in args assert 'page=2' not in args # handle repeating terms mockrequest.GET = QueryDict('language=english&language=french') args = querystring_replace(context, page=10) assert 'language=english' in args assert 'language=french' in args assert 'page=10' in args
def test_default(self): request = Mock(spec_set=['GET', 'session']) request.session = {} request.GET = {} context = RequestsView()._create_context(request) self.assertDictContainsSubset( { 'show': RequestsView.default_show, 'order_by': RequestsView.default_order_by, 'options_show': RequestsView.show, 'options_order_by': RequestsView().options_order_by, 'options_order_dir': RequestsView().options_order_dir, }, context) self.assertQuerysetEqual(context['options_paths'], RequestsView()._get_paths()) self.assertNotIn('path', context) self.assertIn('results', context)
def test_process_request_query(self, redirect_mock): request = Mock() request.GET = { 'ZZ_FEATURE_EXAMPLE_FEATURE': 1, } request.path = '/dashboard/' assert self.middleware.process_request(request) == redirect_mock.return_value redirect_mock.assert_called_once_with('/dashboard/') response = redirect_mock.return_value response.set_signed_cookie.assert_called_once_with( FEATURE_FLAG_COOKIE_NAME, '1', max_age=FEATURE_FLAG_COOKIE_MAX_AGE_SECONDS, httponly=True, )
def test_process_request_query(self, redirect_mock): request = Mock() request.GET = { 'ZZ_FEATURE_EXAMPLE_FEATURE': 1, } request.path = '/dashboard/' assert self.middleware.process_request( request) == redirect_mock.return_value redirect_mock.assert_called_once_with('/dashboard/') response = redirect_mock.return_value response.set_signed_cookie.assert_called_once_with( FEATURE_FLAG_COOKIE_NAME, '1', max_age=FEATURE_FLAG_COOKIE_MAX_AGE_SECONDS, httponly=True, )
def prepare_request_mock( self, data=None, referer='http://localhost/user_with_workspaces/public-workspace', user=None, extra_headers={}, GET=''): request = Mock() request.get_host.return_value = 'localhost' GET_PARAMETERS = parse_qsl(GET) request.GET = MagicMock() request.GET.__len__.side_effect = lambda: len(GET_PARAMETERS) request.GET.__getitem__.side_effect = lambda key: GET_PARAMETERS[key] request.GET.urlencode.side_effect = lambda: GET request.COOKIES = { settings.SESSION_COOKIE_NAME: 'test', } request.META = { 'HTTP_ACCEPT': 'application/json', 'SERVER_PROTOCOL': 'http', 'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': 'localhost', 'HTTP_REFERER': referer, } if data is not None: request.method = 'POST' data = data.encode('utf-8') request.META['content_type'] = 'application/json' request.META['content_length'] = len(data) request.read.return_value = data else: request.method = 'GET' request.META['HTTP_FIWARE_OAUTH_TOKEN'] = 'true' request.META.update(extra_headers) if user is None: request.user = self.admin_mock else: request.user = user return request
def test_get(self): request = Mock(spec_set=['GET', 'session']) request.session = {} show = 10 path = '/path/to/somewhere/' order_by = 'path' request.GET = {'show': show, 'path': path, 'order_by': order_by} context = RequestsView()._create_context(request) self.assertDictContainsSubset( { 'show': show, 'order_by': order_by, 'path': path, 'options_show': RequestsView.show, 'options_order_by': RequestsView().options_order_by, 'options_order_dir': RequestsView().options_order_dir, }, context) self.assertQuerysetEqual(context['options_paths'], RequestsView()._get_paths()) self.assertIn('results', context)
def test_process_request_no_qs(self, get_value): request = Mock() request.GET = get_value assert self.middleware.process_request(request) is None
def test_get_params_from_url(self): r = Mock() r.GET = {'params': 'foo:bar|qux:mux'} res = get_params_from_request(r) self.assertEqual(res['foo'], 'bar') self.assertEqual(res['qux'], 'mux')