def get_page_request(self, page, user, path=None, edit=False, lang='en'): """ Createds a GET request for the given page suitable for use the django CMS toolbar :param page: current page object :param user: current user :param path: path (if different from the current page path) :param edit: editing mode :param lang: request language :return: request """ from cms.middleware.toolbar import ToolbarMiddleware path = path or page and page.get_absolute_url() if edit: path += '?edit' request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} request.current_page = page mid = ToolbarMiddleware() mid.process_request(request) return request
def get_page_request(self, page, user, path=None, edit=False, lang_code='en', disable=False): path = path or page and page.get_absolute_url() if edit: path += '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang_code if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} if disable: request.GET[get_cms_setting('CMS_TOOLBAR_URL__DISABLE')] = None request.current_page = page mid = ToolbarMiddleware() mid.process_request(request) if hasattr(request, 'toolbar'): request.toolbar.populate() return request
def test_get_runs_from_request_filters_invalid(): alert_errors = [] alert_infos = [] alert_filters = [] invalid_date = "20199-06-10" invalid_run = "99das" user = mixer.blend(get_user_model()) req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['date'] = invalid_date req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert invalid_date in alert_errors[0] assert not resp req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['date_range_0'] = invalid_date req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert invalid_date in alert_errors[1] assert not resp req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['date_range_1'] = invalid_date req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert invalid_date in alert_errors[2] assert not resp req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['runs_0'] = invalid_run req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert invalid_run in alert_errors[3] assert not resp req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['runs_1'] = invalid_run req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert invalid_run in alert_errors[4] assert not resp
def test_request_contains_filter_parameter(): req = RequestFactory().get("/") assert False is request_contains_filter_parameter(req) user = mixer.blend(User) req.GET = req.GET.copy() req.GET["userid"] = user.id assert True is request_contains_filter_parameter(req) req = RequestFactory().get("/") req.GET = req.GET.copy() assert False is request_contains_filter_parameter(req) req.GET["date_year"] = "2017" assert True is request_contains_filter_parameter(req)
def test_result(self): request = RequestFactory().get("/result") request.GET = {"query": "3330720662002"} view = result(request) assert view.status_code == 200
def test_get_request_data(): request = RequestFactory().get('/sso/test') request.META = { 'HTTP_HOST': 'test.org', 'PATH_INFO': '/sso/test', 'SERVER_PORT': '999', } request.POST = { 'post_data': 'test', } request.GET = { 'get_data': 'test', } eq( get_request_data(request), { 'https': 'on', 'http_host': 'test.org', 'script_name': '/sso/test', 'server_port': '443', 'get_data': { 'get_data': 'test', }, 'post_data': { 'post_data': 'test', } } )
def test__custom_sitemap__output(): """Tests custom_sitemap view for proper details in response.""" # Setup details to call view section = 'Test Section' sitemaps = {'Test Section': ['Test Page']} request = RequestFactory() request.GET = {'p': 2} request.scheme = 'http' # Call view and get response response = views.custom_sitemap(request, sitemaps, section) # Test for expected output details assert response.template_name == 'sitemap.xml' assert response.headers['Content-Type'] == 'application/xml' assert isinstance(response.context_data, dict) assert 'urlset' in response.context_data assert response.context_data['urlset'][0] == {'play': 1} assert 'play_urlset' in response.context_data assert response.context_data['play_urlset'] == 1 assert 'study_urlset' in response.context_data assert response.context_data['study_urlset'] == 2 assert 'tools_urlset' in response.context_data assert response.context_data['tools_urlset'] == 3 assert 'read_urlset' in response.context_data assert response.context_data['read_urlset'] == 4 assert 'other_urlset' in response.context_data assert response.context_data['other_urlset'] == 5
def test_free_period_should_return_period_is_free_and_extra_info(self): request = RequestFactory().get("/") request.GET = {"persons": 3} request.shop = self.shop self.reservable.pricing_per_person = True self.reservable.pricing_per_person_included = 2 self.reservable.pricing_per_person_price = Decimal("10.00") self.reservable.save() response = self.client.get( "%s?reservable_id=%s&start=%s&end=%s&persons=3" % ( reverse('reservations:check_period'), self.reservable.id, self.next.strftime("%Y-%m-%d"), (self.next + datetime.timedelta(days=3)).strftime("%Y-%m-%d") ) ) price_info = self.reservable.product.get_price_info(request, quantity=3) self.assertJSONEqual(response.content.decode("utf-8"), { "result": True, "price": { "total": format_money(price_info.price), "period_modifiers": str(price_info.period_modifiers.quantize(Decimal("1.00"))), "per_person_modifiers": str(price_info.per_person_modifiers.quantize(Decimal("1.00"))), "has_extra_info": True, "special_period_str": "Special period", "persons_count_str": "Person count", } })
def get_page_request(page, user=None, path=None, edit=False, language='en'): path = path or page and page.get_absolute_url() if edit: path += '?edit' request = RequestFactory().get(path) request.session = {} request.user = user or AnonymousUser() request.LANGUAGE_CODE = language if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} request.current_page = page mid = ToolbarMiddleware() mid.process_request(request) return request
def get_response_data(self, **params): query_params = QueryDict(mutable=True) query_params.update(**params) request = RequestFactory().get('/') request.GET = query_params view = test_views.OwnerAPITestView.as_view() return view(request, pk=self.owner.pk).data
def test_view(self): req = RequestFactory().get('/') req.GET = {'pk': 1, } resp = GetCTypeDetails.as_view()(req) ctype = ContentType.objects.get(pk=1) self.assertTrue(ctype.app_label in resp.content, msg=( 'Should return a JSON string containing app_label and model'))
def test_view_with_request_arguments(): req = RequestFactory().get(reverse("shiftleader:shiftleader")) req.GET = req.GET.copy() req.GET['date__gte']="2019-6-10" req.GET['date__lte']="2019-6-16" req.user = mixer.blend(get_user_model()) resp = shiftleader_view(req) assert resp.status_code == 200
def get_page_request(self, page, user, path=None, edit=False, lang_code='en'): from cms.middleware.toolbar import ToolbarMiddleware path = path or page and page.get_absolute_url(lang_code) if edit: path += '?edit' request = RequestFactory().get(path) request.session = {} request.user = user request.LANGUAGE_CODE = lang_code if edit: request.GET = {'edit': None} else: request.GET = {'edit_off': None} request.current_page = page mid = ToolbarMiddleware() mid.process_request(request) return request
def test_view_compare_with_run_registry(): create_runs(3, 1, "collisions", "express", date="2018-05-14") req = RequestFactory().get("shiftleader/") req.GET = req.GET.copy() req.GET['date__gte']="2018-5-13" req.GET['date__lte']="2018-5-16" req.user = mixer.blend(get_user_model()) resp = shiftleader_view(req) assert resp.status_code == 200
def test_signin(self): """TEST 1 - WITH A CONNECTED USER""" request = RequestFactory().get("/signin") request.user = User.objects.get(username="******") view = signin(request) # 302 - REDIRECT TO Signin to account assert view.status_code == 302 assert view.url == "/account" """ TEST 2 - TO LOGIN WITH ANONYMOUS USER """ request = RequestFactory().post("/signin") middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.user = AnonymousUser() request.POST = {"username": "******", "password": "******"} view = signin(request) # 302 - Home page assert view.status_code == 302 assert view.url == "/" """ TEST 3 - WITH UNCONNECTED CLIENT FROM RESULT """ request = RequestFactory().post("/signin") middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.user = AnonymousUser() request.POST = {"username": "******", "password": "******"} request.GET = {"query": "80177173"} view = signin(request) # 302 - Result page assert view.status_code == 302 assert view.url == "/result?query=80177173" """ TEST 4 - WITH UNCONNECTED CLIENT FROM HOMEPAGE """ request = RequestFactory().get("/signin") request.user = AnonymousUser() view = signin(request) # 200 - Signin again assert view.status_code == 200
def build_request(self): """ Build a request that contains the instance user, coupon data, site, and an empty set of cookies. """ request = RequestFactory() request.user = self.user request.data = self.coupon_data request.site = self.site request.COOKIES = {} request.GET = {} return request
def test_filter_parameters(self): # TODO test invalid parameter values req = RequestFactory().get("/") req.user = mixer.blend(User) req.GET = req.GET.copy() req.GET["date_range_0"] = "2018-06-13" req.GET["date_range_1"] = "2018-06-13" req.GET["runs_0"] = "42" req.GET["runs_1"] = "1728" req.GET["type"] = "3" resp = get_view_response(listruns, req) assert resp.status_code == 200
def test_with_invalid_filters(self): req = RequestFactory().get("/") req.user = mixer.blend(User) req.GET = req.GET.copy() req.GET["date"] = "20sfd18-06-01" req.GET["date_range_0"] = "201-asasgsa6-13" req.GET["date_range_1"] = "BLUME" req.GET["runs_0"] = "sadfasdf" req.GET["runs_1"] = "ýxkushd" req.GET["type"] = " asad /4332re" resp = get_view_response(summaryView, req) assert resp.status_code == 200
def test_with_filters(self): req = RequestFactory().get("/") req.user = mixer.blend(User) req.GET = req.GET.copy() req.GET["date"] = "2018-06-01" req.GET["date_range_0"] = "2018-06-13" req.GET["date_range_1"] = "2018-06-13" req.GET["runs_0"] = "42" req.GET["runs_1"] = "1728" req.GET["type"] = "3" resp = get_view_response(summaryView, req) assert resp.status_code == 200
def test_comment_edit(db): commnet = mixer.blend('blog.Comment') post = mixer.blend('blog.Post') post.title = 'TEST' post.save() commnet.post = post path = reverse('blog:edit', args=[ commnet.id, post.title, ]) req = RequestFactory().get(path) req.GET = {'commentbody': "Test"} res = edit(req, c_id=commnet.id, title=post.title) assert res.status_code == 302
def setUp(self): request = RequestFactory().get('/') our_list_display = EditRegionAdmin.list_display our_list_links = (EditRegionAdmin(User, admin.site) .get_list_display_links(request=request, list_display=our_list_display)) user = User(username='******') user.set_password('test') user.full_clean() user.save() self.user = user user_content_type = get_content_type(User) attach_configuration(user, EditRegionConfiguration) config = get_configuration(user) request.GET = QueryDict('', mutable=True) request.GET.update({REQUEST_VAR_ID: user.pk, REQUEST_VAR_CT: user_content_type.pk, REQUEST_VAR_REGION: 'test'}) try: admin.site.unregister(User) except NotRegistered: pass admin.site.register(User, TestUserAdmin) cl = EditRegionChangeList(request=request, model=EditRegionChunk, list_display=our_list_display, list_display_links=our_list_links, list_filter=EditRegionAdmin.list_filter, date_hierarchy=None, search_fields=None, list_select_related=None, list_per_page=100, list_max_show_all=100, list_editable=None, model_admin=admin.site._registry[EditRegionChunk], # noqa parent_obj=user, parent_conf=config) self.changelist = cl badconfig = EditRegionConfiguration() cl2 = EditRegionChangeList(request=request, model=EditRegionChunk, list_display=our_list_display, list_display_links=our_list_links, list_filter=EditRegionAdmin.list_filter, date_hierarchy=None, search_fields=None, list_select_related=None, list_per_page=100, list_max_show_all=100, list_editable=None, model_admin=admin.site._registry[EditRegionChunk], # noqa parent_obj=user, parent_conf=badconfig) self.changelist2 = cl2
def test__custom_sitemap__without_sections(): """Tests custom_sitemap view when sections are not provided.""" # Setup details to call view section = None sitemaps = {'Test Section': ['Test Page']} request = RequestFactory() request.GET = {'p': 2} request.scheme = 'http' # Call view and get response response = views.custom_sitemap(request, sitemaps, section) # Test for the passed in sitemap details to confirm right # paths were followed assert list(response.context_data['urlset'][5])[0] == 'maps'
def test_composer_creation(db): comp = mixer.blend('blog.Composer') comp.filepath = 'weights1.hdf5' post = mixer.blend('blog.Post') post.title = 'TEST' post.save() comp.post = post comp.save() path = reverse('blog:detail', args=[ post.title, ]) req = RequestFactory().get(path) req.user = mixer.blend('blog.Account') req.GET = ['submit_network'] resp = post_detail(req, title=post.title) assert resp.status_code == 200
def test__custom_sitemap__with_invalid_section(): """Tests custom_sitemap view when invalid section is provided.""" # Setup details to call view section = 'Wrong Section' sitemaps = {'Test Section': ['Test Page']} request = RequestFactory() request.GET = {'p': 2} request.scheme = 'http' # Call view and get response try: views.custom_sitemap(request, sitemaps, section) except Http404 as e: assert 'No sitemap available for section: Wrong Section' in str(e) else: assert False
def test_addreference_invalid(self): run_number = 9999999 reco = "express" arguments={'run_number': run_number, 'reco': reco } req = RequestFactory().get(reverse("addrefrun:addrefrun")) req.GET = req.GET.copy() req.GET["run_number"] = run_number req.GET["reco"] = reco req.user = mixer.blend(User) setattr(req, 'session', 'session') messages = FallbackStorage(req) setattr(req, '_messages', messages) resp = views.addreference(req) assert 200 == resp.status_code assert not RunReconstruction.objects.exists()
def test_save(self): # BUILD REQUEST request = RequestFactory().get("/save") request.GET = {"query": "3330720662002,4028491400907"} """ TEST 1 - WITH UNCONNECTED USER """ request.user = AnonymousUser() view = save(request) # 302 - REDIRECT TO Signin/ assert view.status_code == 302 assert view.url == "/signin" """ TEST 2 - WITH CONNECTED USER """ request.user = User.objects.get(username="******") view = save(request) # 302 - REDIRECT TO MyFood/ assert view.status_code == 302 assert view.url == "/myfood"
def test_get_runs_from_request_filters_date(): alert_errors = [] alert_infos = [] alert_filters = [] run_number = 321123 user = mixer.blend(get_user_model()) mixer.blend("certifier.TrackerCertification", runreconstruction=mixer.blend("certifier.RunReconstruction", run=mixer.blend( "oms.OmsRun", run_number=run_number)), date="2019-6-10", user=user) req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['date'] = "2019-6-10" req.user = user resp = get_runs_from_request_filters(req, alert_errors, alert_infos, alert_filters) assert run_number == resp[0].runreconstruction.run.run_number
def test__custom_sitemap__without_all_lastmod(mock_get_urls): """Tests custom_sitemap view when all_sites_lastmod not provided.""" # Setup details to call view section = 'Test Section' sitemaps = {'Test Section': ['Test Page']} request = RequestFactory() request.GET = {'p': 2} request.scheme = 'http' # Set patched return values for modify details mock_get_urls.return_value = ( [], { 'all_sites_lastmod': False, 'lastmod': (2000, 1, 1, 0, 0, 0) }, ) # Call view and get response response = views.custom_sitemap(request, sitemaps, section) # Test that additional last-modified details not added assert 'Last-Modified' not in response
def test_addreference_already_exists(self): run_number = 321123 reco = "express" mixer.blend(RunReconstruction, reconstruction=reco, run=mixer.blend(OmsRun, run_number=run_number)) assert RunReconstruction.objects.exists() arguments={'run_number': run_number, 'reco': reco } req = RequestFactory().get(reverse("addrefrun:addrefrun")) req.GET = req.GET.copy() req.GET["run_number"] = run_number req.GET["reco"] = reco req.user = mixer.blend(User) setattr(req, 'session', 'session') messages = FallbackStorage(req) setattr(req, '_messages', messages) resp = views.addreference(req) assert 200 == resp.status_code assert RunReconstruction.objects.exists() assert RunReconstruction.objects.all().count() == 1
def test_get_runs_from_request_filters(): alert_errors = [] alert_infos = [] alert_filters = [] run_number1 = 321123 run_number2 = 321126 user = mixer.blend(get_user_model()) mixer.blend("certifier.TrackerCertification", runreconstruction=mixer.blend("certifier.RunReconstruction", run=mixer.blend( "oms.OmsRun", run_number=run_number1)), date="2019-6-10", user=user) mixer.blend("certifier.TrackerCertification", runreconstruction=mixer.blend("certifier.RunReconstruction", run=mixer.blend( "oms.OmsRun", run_number=run_number2)), date="2019-6-16", user=user) req = RequestFactory().get("summary/") req.GET = req.GET.copy() req.GET['date_range_0'] = "2019-6-10" req.GET['date_range_1'] = "2019-6-16" req.GET['runs_0'] = "321123" req.GET['runs_1'] = "321126" req.user = user resp = get_runs_from_request_filters( req, alert_errors, alert_infos, alert_filters).order_by("runreconstruction__run__run_number") assert run_number1 == resp[0].runreconstruction.run.run_number assert run_number2 == resp[1].runreconstruction.run.run_number
def create_coupon(self, benefit_type=Benefit.PERCENTAGE, benefit_value=100, catalog=None, catalog_query=None, client=None, code='', course_seat_types=None, email_domains=None, enterprise_customer=None, enterprise_customer_catalog=None, max_uses=None, note=None, partner=None, price=100, quantity=5, title='Test coupon', voucher_type=Voucher.SINGLE_USE, course_catalog=None, program_uuid=None, start_datetime=None, end_datetime=None): """Helper method for creating a coupon. Arguments: benefit_type(str): The voucher benefit type benefit_value(int): The voucher benefit value catalog(Catalog): Catalog of courses for which the coupon applies catalog_query(str): Course query string client (BusinessClient): Optional business client object code(str): Custom coupon code course_catalog (int): Course catalog id from Discovery Service course_seat_types(str): A string of comma-separated list of seat types enterprise_customer (str): Hex-encoded UUID for an Enterprise Customer object from the Enterprise app. enterprise_customer_catalog (str): UUID for an Enterprise Customer Catalog from the Enterprise app. email_domains(str): A comma seperated list of email domains max_uses (int): Number of Voucher max uses note (str): Coupon note. partner(Partner): Partner used for creating a catalog price(int): Price of the coupon quantity (int): Number of vouchers to be created and associated with the coupon title(str): Title of the coupon voucher_type (str): Voucher type program_uuid (str): Program UUID Returns: coupon (Coupon) """ if partner is None: partner = PartnerFactory(name='Tester') if client is None: client, __ = BusinessClient.objects.get_or_create(name='Test Client') if (catalog is None and not enterprise_customer_catalog and not ((catalog_query or course_catalog or program_uuid) and course_seat_types)): catalog = Catalog.objects.create(partner=partner) if code != '': quantity = 1 with mock.patch( "ecommerce.extensions.voucher.utils.get_enterprise_customer", mock.Mock(return_value={'name': 'Fake enterprise'})): coupon = create_coupon_product( benefit_type=benefit_type, benefit_value=benefit_value, catalog=catalog, catalog_query=catalog_query, category=self.category, code=code, course_catalog=course_catalog, course_seat_types=course_seat_types, email_domains=email_domains, end_datetime=end_datetime or (datetime.datetime.now() + datetime.timedelta(days=500)), enterprise_customer=enterprise_customer, enterprise_customer_catalog=enterprise_customer_catalog, max_uses=max_uses, note=note, partner=partner, price=price, quantity=quantity, start_datetime=start_datetime or datetime.datetime(2015, 1, 1), title=title, voucher_type=voucher_type, program_uuid=program_uuid, site=self.site ) request = RequestFactory() request.site = self.site request.user = UserFactory() request.COOKIES = {} request.GET = {} self.basket = prepare_basket(request, [coupon]) view = CouponViewSet() view.request = request self.response_data = view.create_order_for_invoice(self.basket, coupon_id=coupon.id, client=client) coupon.client = client return coupon
def test_view(self): req = RequestFactory().get('/') req.GET = {'content': 'BEGIN%3AVCALENDAR%0AVERSION%3A2.0%0APRODID%3Ajquery.icalendar%0AMETHOD%3APUBLISH%0ABEGIN%3AVEVENT%0AUID%3A1364815856688@localhost%3A8000%0ADTSTAMP%3A20130401T113056Z%0AURL%3Ahttp%3A//localhost%3A8000/en/events/1/%0ATITLE%3AA%20Test%20Event%0ADTSTART%3A20130531T220000Z%0ADTEND%3A20130604T040000Z%0ASUMMARY%3AA%20Test%20Event%0ADESCRIPTION%3AWorkshop%0ALOCATION%3AA%20Venue%20Name%20Wuppertal%2C%20Germany%0AEND%3AVEVENT%0AEND%3AVCALENDAR', } # NOQA resp = ICSView.as_view()(req) self.assertTrue('BEGIN' in resp.content, msg=( 'Should return a .ics file as a attachment download'))
def test_bad_pk(self): req = RequestFactory().get('/') req.GET = {'pk': 999, } self.assertRaises(Http404, GetCTypeDetails.as_view(), req)