def test_subscribing(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters # They subscribe to firefox-tips self.data['form-2-subscribed_check'] = u'True' # in English - and that's their language too self.user['lang'] = u'en' self.data['lang'] = u'en' url = reverse('newsletter.existing.token', args=(self.token,)) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('django.contrib.messages.add_message') as add_msg: with patch('lib.l10n_utils.render'): basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # Should have given no messages self.assertEqual(0, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should have called update_user with subscription list self.assertEqual(1, basket_patches['update_user'].call_count) kwargs = basket_patches['update_user'].call_args[1] self.assertEqual( {'newsletters': u'mozilla-and-you,firefox-tips'}, kwargs ) # Should not have called unsubscribe self.assertEqual(0, basket_patches['unsubscribe'].call_count) # Should not have called subscribe self.assertEqual(0, basket_patches['subscribe'].call_count) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert_redirect(rsp, url)
def check_url(product, version): if product == 'Firefox for Android': return 'https://support.mozilla.org/kb/will-firefox-work-my-mobile-device' elif product == 'Firefox for iOS': return reverse('firefox.ios.system_requirements', args=[version]) else: return reverse('firefox.system_requirements', args=[version])
def test_remove_all(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters self.data['remove_all'] = 'on' # any value should do url = reverse('newsletter.existing.token', args=(self.token,)) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render'): basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # Should not have updated user details at all self.assertEqual(0, basket_patches['update_user'].call_count) # Should have called unsubscribe self.assertEqual(1, basket_patches['unsubscribe'].call_count) # and said user opts out args, kwargs = basket_patches['unsubscribe'].call_args self.assertEqual((self.token, self.user['email']), args) self.assertTrue(kwargs['optout']) # Should redirect to the 'updated' view with unsub=1 and token url = reverse('newsletter.updated') + "?unsub=1" url += "&token=%s" % self.token assert_redirect(rsp, url)
def check_url(product, version): if product == 'Firefox for Android': return settings.FIREFOX_MOBILE_SYSREQ_URL elif product == 'Firefox for iOS': return reverse('firefox.ios.system_requirements', args=[version]) else: return reverse('firefox.system_requirements', args=[version])
def test_change_lang_country(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters self.data['lang'] = 'en' self.data['country'] = 'us' url = reverse('newsletter.existing.token', args=(self.token,)) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render'): with patch('django.contrib.messages.add_message') as add_msg: basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # We have an existing user with a change to their email data, # but none to their subscriptions. # 'subscribe' should not be called self.assertEqual(0, basket_patches['subscribe'].call_count) # update_user should be called once self.assertEqual(1, basket_patches['update_user'].call_count) # with the new lang and country and the newsletter list kwargs = basket_patches['update_user'].call_args[1] self.assertEqual( {'lang': u'en', 'country': u'us', 'newsletters': u'mozilla-and-you'}, kwargs ) # No messages should be emitted self.assertEqual(0, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert_redirect(rsp, url)
def test_post_user_not_found(self, mock_basket_request): # User submits form and passed token, but no user was found # Should issue message and redirect to recovery rand_token = unicode(uuid.uuid4()) url = reverse('newsletter.existing.token', args=(rand_token,)) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render') as render: render.return_value = HttpResponse('') with patch('django.contrib.messages.add_message') as add_msg: basket_patches['user'].side_effect = basket.BasketException rsp = self.client.post(url, self.data) # Shouldn't call basket except for the attempt to find the user self.assertEqual(0, basket_patches['update_user'].call_count) self.assertEqual(0, basket_patches['unsubscribe'].call_count) self.assertEqual(0, basket_patches['subscribe'].call_count) # Should have given a message self.assertEqual(1, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should have been redirected to recovery page self.assertEqual(302, rsp.status_code) self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
def test_unsubscribing(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters # They unsubscribe from the one newsletter they're subscribed to self.data['form-0-subscribed_radio'] = u'False' url = reverse('newsletter.existing.token', args=(self.token,)) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render'): basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # Should have called update_user with list of newsletters self.assertEqual(1, basket_patches['update_user'].call_count) kwargs = basket_patches['update_user'].call_args[1] self.assertEqual( {'newsletters': u''}, kwargs ) # Should not have called subscribe self.assertEqual(0, basket_patches['subscribe'].call_count) # Should not have called unsubscribe self.assertEqual(0, basket_patches['unsubscribe'].call_count) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert_redirect(rsp, url)
def releasenotes_url(release): prefix = 'aurora' if release.channel == 'Aurora' else 'release' if release.product == 'Firefox for Android': return reverse('firefox.android.releasenotes', args=(release.version, prefix)) if release.product == 'Firefox for iOS': return reverse('firefox.ios.releasenotes', args=(release.version, prefix)) else: return reverse('firefox.desktop.releasenotes', args=(release.version, prefix))
def test_download_button_bad_funnelcake(self): """The download button should not have a bad funnelcake ID.""" with self.activate('en-US'): resp = self.client.get(reverse('mozorg.home'), {'f': '5dude'}) ok_('product=firefox-stub&' in resp.content) ok_('product=firefox-stub-f5dude&' not in resp.content) resp = self.client.get(reverse('mozorg.home'), {'f': '999999999'}) ok_('product=firefox-stub&' in resp.content) ok_('product=firefox-stub-f999999999&' not in resp.content)
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) experience = request.GET.get('xv', None) variant = request.GET.get('v', None) locale = l10n_utils.get_locale(request) # ensure variant matches pre-defined value if variant not in ['a', 'b', 'c', 'd', 'e', 'f']: # place expected ?v= values in this list variant = None if scene == '2': # send to new permanent scene2 URL (bug 1438302) thanks_url = reverse('firefox.download.thanks') query_string = request.META.get('QUERY_STRING', '') if query_string: thanks_url = '?'.join([thanks_url, force_text(query_string, errors='ignore')]) return HttpResponsePermanentRedirect(thanks_url) # if no/incorrect scene specified, show scene 1 else: if lang_file_is_active('firefox/new/wait-face', locale) and experience == 'waitface': template = 'firefox/new/wait-face/scene1.html' elif lang_file_is_active('firefox/new/reggiewatts', locale) and experience == 'reggiewatts': template = 'firefox/new/reggie-watts/scene1.html' elif locale == 'de' and experience == 'berlin': template = 'firefox/new/berlin/scene1.html' elif locale == 'de' and experience == 'aus-gruenden': template = 'firefox/new/berlin/scene1-aus-gruenden.html' elif locale == 'de' and experience == 'herz': template = 'firefox/new/berlin/scene1-herz.html' elif locale == 'de' and variant == 'b': template = 'firefox/new/de/scene1-b.html' elif locale == 'en-US': if experience in ['portland', 'forgood']: template = 'firefox/new/portland/scene1.html' elif experience in ['portland-fast', 'fast']: template = 'firefox/new/portland/scene1-fast.html' elif experience in ['portland-safe', 'safe']: template = 'firefox/new/portland/scene1-safe.html' elif experience == 'betterbrowser' and variant: if variant == 'a': template = 'firefox/new/scene1.html' else: template = 'firefox/new/better-browser/scene1-{}.html'.format(variant) else: template = 'firefox/new/scene1.html' else: template = 'firefox/new/scene1.html' # no harm done by passing 'v' to template, even when no experiment is running # (also makes tests easier to maintain by always sending a context) return l10n_utils.render(request, template, {'experience': experience})
def check_url(product, version): if product == 'Firefox for Android': # System requirement pages for Android releases exist from 46.0 and upward. if show_android_sys_req(version): return reverse('firefox.android.system_requirements', args=[version]) else: return settings.FIREFOX_MOBILE_SYSREQ_URL elif product == 'Firefox for iOS': return reverse('firefox.ios.system_requirements', args=[version]) else: return reverse('firefox.system_requirements', args=[version])
def test_fx_hello_redirect_non_firefox(self): """Should redirect to /firefox/hello if not on Firefox""" self.user_agent = ( "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, " "like Gecko) Chrome/41.0.2228.0 Safari/537.36" ) self.url = reverse("firefox.hello.start", args=["35.0"]) response = self.client.get(self.url, HTTP_USER_AGENT=self.user_agent) eq_(response.status_code, 301) eq_(response.get("Vary"), "User-Agent") eq_("http://testserver%s" % reverse("firefox.hello"), response.get("Location"))
def test_fx_hello_redirect_non_firefox(self): """Should redirect to /firefox/hello if not on Firefox""" self.user_agent = ('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/41.0.2228.0 Safari/537.36') self.url = reverse('firefox.hello.start', args=['35.0']) response = self.client.get(self.url, HTTP_USER_AGENT=self.user_agent) eq_(response.status_code, 301) eq_(response['Cache-Control'], 'max-age=0') eq_('http://testserver%s' % reverse('firefox.hello'), response.get('Location'))
def test_sf_form_csrf_status(self): """Test that CSRF checks return 200 with token and 403 without.""" csrf_client = Client(enforce_csrf_checks=True) response = csrf_client.get(reverse("firefox.partners.index")) post_url = reverse("mozorg.partnerships") response = csrf_client.post( post_url, {"first_name": "Partner", "csrfmiddlewaretoken": response.cookies["csrftoken"].value} ) self.assertEqual(response.status_code, 200) response = csrf_client.post(post_url, {"first_name": "Partner"}) self.assertEqual(response.status_code, 403)
def get_download_url(release): if release.product == 'Thunderbird': return 'https://www.mozilla.org/thunderbird/' elif release.product == 'Firefox for Android': return android_builds(release.channel)[0]['download_link'] else: if release.channel == 'Aurora': return reverse('firefox.channel') + '#developer' elif release.channel == 'Beta': return reverse('firefox.channel') + '#beta' else: return reverse('firefox')
def assert_ua_redirects_to(self, ua, url_name, status_code=301): response = self.client.get(self.url, HTTP_USER_AGENT=ua) eq_(response.status_code, status_code) eq_(response["Vary"], "User-Agent") eq_(response["Location"], "http://testserver%s" % reverse(url_name)) # An additional redirect test with a query string query = "?ref=getfirefox" response = self.client.get(self.url + query, HTTP_USER_AGENT=ua) eq_(response.status_code, status_code) eq_(response["Vary"], "User-Agent") eq_(response["Location"], "http://testserver%s" % reverse(url_name) + query)
def test_invalid_token(self, mock_basket_request): # "Token" in URL is not syntactically a UUID - should redirect to # recovery *without* calling Exact Target token = "not a token" url = reverse('newsletter.existing.token', args=(token,)) with patch.multiple('basket', user=DEFAULT) as basket_patches: with patch('django.contrib.messages.add_message') as add_msg: rsp = self.client.get(url, follow=False) self.assertEqual(0, basket_patches['user'].call_count) self.assertEqual(1, add_msg.call_count) self.assertEqual(302, rsp.status_code) self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
def get_download_url(release): if release.product == 'Firefox for Android': return android_builds(release.channel)[0]['download_link'] elif release.product == 'Firefox for iOS': return ios_builds(release.channel)[0]['download_link'] else: if release.channel == 'Aurora': return reverse('firefox.channel.desktop') + '#developer' elif release.channel == 'Beta': return reverse('firefox.channel.desktop') + '#beta' else: return reverse('firefox')
def assert_ua_redirects_to(self, ua, url_name, status_code=301): response = self.client.get(self.url, HTTP_USER_AGENT=ua) assert response.status_code == status_code assert response['Cache-Control'] == 'max-age=0' assert response['Location'] == reverse(url_name) # An additional redirect test with a query string query = '?ref=getfirefox' response = self.client.get(self.url + query, HTTP_USER_AGENT=ua) assert response.status_code == status_code assert response['Cache-Control'] == 'max-age=0' assert response['Location'] == reverse(url_name) + query
def setUp(self): with self.activate('en-US'): self.url_en = reverse('mozorg.contribute.signup') with self.activate('pt-BR'): self.url_pt_br = reverse('mozorg.contribute.signup') self.contact = '*****@*****.**' self.data = { 'contribute-form': 'Y', 'email': self.contact, 'interest': 'coding', 'privacy': True, 'comments': 'Wesh!', }
def get_absolute_url(self): if self.product == 'Thunderbird': return reverse('thunderbird.notes', args=[self.version]) if self.product == 'Firefox for Android': urlname = 'firefox.android.releasenotes' elif self.product == 'Firefox for iOS': urlname = 'firefox.ios.releasenotes' else: urlname = 'firefox.desktop.releasenotes' prefix = 'aurora' if self.channel == 'Aurora' else 'release' return reverse(urlname, args=[self.version, prefix])
def assert_ua_redirects_to(self, ua, url_name, status_code=301): response = self.client.get(self.url, HTTP_USER_AGENT=ua) eq_(response.status_code, status_code) eq_(response['Cache-Control'], 'max-age=0') eq_(response['Location'], 'http://testserver%s' % reverse(url_name)) # An additional redirect test with a query string query = '?ref=getfirefox' response = self.client.get(self.url + query, HTTP_USER_AGENT=ua) eq_(response.status_code, status_code) eq_(response['Cache-Control'], 'max-age=0') eq_(response['Location'], 'http://testserver%s' % reverse(url_name) + query)
def fraud_report(request): form = FraudReportForm(auto_id='%s') form_submitted = False form_error = False if request.method == 'POST': form = FraudReportForm(request.POST, request.FILES) form_results = submit_form(request, form) form_submitted = form_results['form_submitted'] form_error = form_results['form_error'] template_vars = { 'form': form, 'form_submitted': form_submitted, 'form_error': form_error, } if request.POST and not form_error: # Seeing the form was submitted without error, redirect, do not simply # send a response to avoid problem described below. # @see https://bugzilla.mozilla.org/show_bug.cgi?id=873476 (3.2) response = redirect(reverse('legal.fraud-report'), template_vars) response['Location'] += '?submitted=%s' % form_submitted return response else: # If the below is called after a redirect the template_vars will be lost, therefore # we need to update the form_submitted state from the submitted url parameter. submitted = request.GET.get('submitted') == 'True' template_vars['form_submitted'] = submitted return l10n_utils.render(request, 'legal/fraud-report.html', template_vars)
def sms_send(request): form = SMSSendForm(request.POST or None) if request.method == "POST": error_msg = _("An error occurred in our system. Please try again later.") error = None if form.is_valid(): try: basket.send_sms(form.cleaned_data["number"], SMS_MESSAGES["android"], form.cleaned_data["optin"]) except basket.BasketException: error = error_msg else: number_errors = form.errors.get("number") if number_errors: # form error messages may contain unsanitized user input error = escape(number_errors[0]) else: error = error_msg if request.is_ajax(): # return JSON if error: resp = {"success": False, "error": error} else: resp = {"success": True} return HttpResponseJSON(resp) else: if error: form.errors["__all__"] = form.error_class([error]) else: return HttpResponseRedirect(reverse("firefox.android.sms-thankyou")) return l10n_utils.render(request, "firefox/android/sms-send.html", {"sms_form": form})
def setUp(self): patcher = patch('bedrock.mozorg.views.requests.post') self.addCleanup(patcher.stop) self.requests_mock = patcher.start() self.requests_mock.return_value.status_code = 200 self.factory = RequestFactory() self.template = 'mozorg/partnerships.html' self.view = 'mozorg.partnerships' self.post_data = { 'first_name': 'The', 'last_name': 'Dude', 'title': 'Abider of things', 'company': 'Urban Achievers', 'email': '*****@*****.**', } self.invalid_post_data = { 'first_name': 'The', 'last_name': 'Dude', 'title': 'Abider of things', 'company': 'Urban Achievers', 'email': 'thedude', } with self.activate('en-US'): self.url = reverse(self.view)
def thunderbird_url(page, channel=None): """ Return a product-related URL like /thunderbird/all/ or /thunderbird/beta/notes/. Examples ======== In Template ----------- {{ thunderbird_url('all', 'beta') }} {{ thunderbird_url('sysreq', channel) }} """ kwargs = {} # Tweak the channel name for the naming URL pattern in urls.py if channel == 'release': channel = None if channel == 'alpha': channel = 'earlybird' if channel: kwargs['channel'] = channel return reverse('thunderbird.latest.%s' % page, kwargs=kwargs)
def card_data(self): """Return a dict appropriate for calling the card() macro""" data = {} data.update(self.data) if 'image' in data: data['image_url'] = '%scontentcards/img/%s' % (settings.CONTENT_CARDS_URL, data['image']) del data['image'] if 'highres_image' in data: data['highres_image_url'] = '%scontentcards/img/%s' % (settings.CONTENT_CARDS_URL, data['highres_image']) del data['highres_image'] if 'ga_title' not in data: data['ga_title'] = data['title'] if 'media_icon' in data: data['media_icon'] = 'mzp-has-%s' % data['media_icon'] if 'aspect_ratio' in data: data['aspect_ratio'] = 'mzp-has-aspect-%s' % data['aspect_ratio'] if 'size' in data: data['class'] = 'mzp-c-card-%s' % data['size'] del data['size'] if 'link_url' in data and not URL_RE.match(data['link_url']): data['link_url'] = reverse(data['link_url']) return data
def test_normal(self): """Confirm works with a valid token""" with patch('basket.confirm') as confirm: confirm.return_value = {'status': 'ok'} rsp = self.client.get(self.url) self.assertEqual(302, rsp.status_code) self.assertTrue(rsp['Location'].endswith("%s?confirm=1" % reverse('newsletter.existing.token', kwargs={'token': self.token})))
def test_subscribe(self, mock_subscribe): mock_subscribe.return_value = {'status': 'ok'} data = { 'email': u'*****@*****.**', 'country': 'gr', 'fmt': 'H', 'first_name': 'foo', 'last_name': 'bar', 'status': 'teacher', 'school': 'TuC', 'city': 'Chania', 'age_confirmation': 'on', 'grad_year': '', 'nl_about_mozilla': 'on', 'major': 'science', 'major_free_text': '', 'privacy': 'True' } with self.activate('en-US'): self.client.post(reverse('mozorg.contribute.studentambassadors.join'), data) mock_subscribe.assert_called_with( data['email'], ['ambassadors', 'about-mozilla'], format=u'H', country=u'gr', source_url=u'', first_name=data['first_name'], last_name=data['last_name'], fsa_current_status=data['status'], fsa_school=data['school'], fsa_grad_year=data['grad_year'], fsa_major=data['major'], fsa_city=data['city'], fsa_allow_share=u'N', )
def test_newsletter_no_order(self, get_newsletters, mock_basket_request): """Newsletter views should work if we get no order from basket.""" orderless_newsletters = {} for key, val in newsletters.items(): nl_copy = val.copy() del nl_copy['order'] orderless_newsletters[key] = nl_copy get_newsletters.return_value = orderless_newsletters url = reverse('newsletter.existing.token', args=(self.token,)) self.user['newsletters'] = [u'mozilla-and-you', u'firefox-tips', u'beta'] with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render') as render: basket_patches['user'].return_value = self.user render.return_value = HttpResponse('') self.client.get(url) request, template_name, context = render.call_args[0] forms = context['formset'].initial_forms newsletters_in_order = [form.initial['newsletter'] for form in forms] self.assertEqual([u'mozilla-and-you', u'firefox-tips'], newsletters_in_order)
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) # note: v and xv params only allow a-z, A-Z, 0-9, -, and _ characters experience = request.GET.get('xv', None) variant = request.GET.get('v', None) locale = l10n_utils.get_locale(request) # ensure variant matches pre-defined value if variant not in ['a', 'b']: # place expected ?v= values in this list variant = None if scene == '2': # send to new permanent scene2 URL (bug 1438302) thanks_url = reverse('firefox.download.thanks') query_string = request.META.get('QUERY_STRING', '') if query_string: thanks_url = '?'.join( [thanks_url, force_text(query_string, errors='ignore')] ) return HttpResponsePermanentRedirect(thanks_url) # if no/incorrect scene specified, show scene 1 else: if locale == 'ru' and switch('firefox-yandex'): template = 'firefox/new/yandex/scene1.html' elif lang_file_is_active('firefox/new/trailhead', locale): template = 'firefox/new/trailhead/download.html' else: template = 'firefox/new/scene1.html' # no harm done by passing 'v' to template, even when no experiment is running # (also makes tests easier to maintain by always sending a context) return l10n_utils.render( request, template, {'experience': experience, 'v': variant} )
def test_language_selected(self): """ The correct language for the locale should be initially selected or 'en' if it's not an option. """ with self.activate('fr'): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) eq_(doc('#id_lang option[selected="selected"]').val(), 'fr') # with hyphenated regional locale, should have only lang with self.activate('pt-BR'): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) eq_(doc('#id_lang option[selected="selected"]').val(), 'pt') # not supported. should default to '' with self.activate('af'): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) eq_(doc('#id_lang option[selected="selected"]').val(), '')
def firefox_os_geo_redirect(request): locale = l10n_utils.get_locale(request) if locale == 'en-US': version = '2.5' else: country = get_country_from_request(request) version = settings.FIREFOX_OS_COUNTRY_VERSIONS.get( country, settings.FIREFOX_OS_COUNTRY_VERSIONS['default'] ) return HttpResponseRedirect(reverse('firefox.os.ver.{0}'.format(version)))
def test_normal_submit(self): """Confirm works with a valid token""" with patch('basket.request') as basket_mock: basket_mock.return_value = {'status': 'ok'} rsp = self.client.post(self.url, {'country': 'gb'}) self.assertEqual(302, rsp.status_code) basket_mock.assert_called_with('post', 'user-meta', data={'country': 'gb'}, token=self.token) assert rsp['Location'] == reverse('newsletter.country_success')
def test_language_selected(self): """ The correct language for the locale should be initially selected or 'en' if it's not an option. """ with self.activate("fr"): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) assert doc('#id_lang option[selected="selected"]').val() == "fr" # with hyphenated regional locale, should have only lang with self.activate("pt-BR"): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) assert doc('#id_lang option[selected="selected"]').val() == "pt" # not supported. should default to '' with self.activate("af"): resp = self.client.get(reverse(self.view_name)) doc = pq(resp.content) assert doc('#id_lang option[selected="selected"]').val() == ""
def test_normal_submit(self): """Confirm works with a valid token""" with patch("basket.request") as basket_mock: basket_mock.return_value = {"status": "ok"} rsp = self.client.post(self.url, {"country": "gb"}) self.assertEqual(302, rsp.status_code) basket_mock.assert_called_with("post", "user-meta", data={"country": "gb"}, token=self.token) assert rsp["Location"] == reverse("newsletter.country_success")
def test_unknown_email(self, mock_basket): """Unknown email addresses give helpful error message""" data = {'email': '*****@*****.**'} mock_basket.side_effect = basket.BasketException( status_code=404, code=basket.errors.BASKET_UNKNOWN_EMAIL) rsp = self.client.post(self.url, data) self.assertTrue(mock_basket.called) self.assertEqual(200, rsp.status_code) form = rsp.context['form'] expected_error = unknown_address_text % \ reverse('newsletter.subscribe') self.assertIn(expected_error, form.errors['email'])
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) experience = request.GET.get('xv', None) variant = request.GET.get('v', None) locale = l10n_utils.get_locale(request) # ensure variant matches pre-defined value if variant not in []: # place expected ?v= values in this list variant = None if scene == '2': # send to new permanent scene2 URL (bug 1438302) thanks_url = reverse('firefox.download.thanks') query_string = request.META.get('QUERY_STRING', '') if query_string: thanks_url = '?'.join([thanks_url, force_text(query_string, errors='ignore')]) return HttpResponsePermanentRedirect(thanks_url) # if no/incorrect scene specified, show scene 1 else: if lang_file_is_active('firefox/new/wait-face', locale) and experience == 'waitface': template = 'firefox/new/wait-face/scene1.html' elif lang_file_is_active('firefox/new/reggiewatts', locale) and experience == 'reggiewatts': template = 'firefox/new/reggie-watts/scene1.html' elif locale == 'de' and experience == 'berlin': template = 'firefox/new/berlin/scene1.html' elif locale == 'en-US': if experience == 'portland': template = 'firefox/new/portland/scene1.html' else: template = 'firefox/new/scene1.html' else: template = 'firefox/new/scene1.html' # no harm done by passing 'v' to template, even when no experiment is running # (also makes tests easier to maintain by always sending a context) return l10n_utils.render(request, template, {'v': variant})
def all_downloads(request, platform, channel): if platform is None: platform = 'desktop' if platform == 'desktop': product = firefox_desktop if platform == 'android': product = firefox_android if channel is None: channel = 'release' if channel in ['developer', 'aurora']: channel = 'alpha' if channel == 'organizations': channel = 'esr' # Since the regex in urls.py matches various URL patterns, we have to handle # nonexistent pages here as 404 Not Found if platform == 'ios': raise Http404 if platform == 'android' and channel == 'esr': raise Http404 # Aurora for Android is gone; the population has been migrated to Nightly. # Redirect /firefox/android/aurora/all/ to /firefox/android/nightly/all/ if platform == 'android' and channel == 'alpha': return HttpResponsePermanentRedirect( reverse('firefox.all', kwargs={'platform': 'android', 'channel': 'nightly'})) version = product.latest_version(channel) query = request.GET.get('q') context = { 'platform': platform, 'platforms': product.platforms(channel, True), 'platform_cls': product.platform_classification, 'full_builds_version': version.split('.', 1)[0], 'full_builds': product.get_filtered_full_builds(channel, version, query), 'test_builds': product.get_filtered_test_builds(channel, version, query), 'query': query, 'channel': channel, 'channel_label': product.channel_labels.get(channel, 'Firefox'), } if platform == 'desktop' and channel == 'esr': next_version = firefox_desktop.latest_version('esr_next') if next_version: context['full_builds_next_version'] = next_version.split('.', 1)[0] context['full_builds_next'] = firefox_desktop.get_filtered_full_builds('esr_next', next_version, query) context['test_builds_next'] = firefox_desktop.get_filtered_test_builds('esr_next', next_version, query) return l10n_utils.render(request, 'firefox/all.html', context)
def recovery(request): """ Let user enter their email address and be sent a message with a link to manage their subscriptions. """ if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] try: # Try it - basket will return an error if the email is unknown basket.send_recovery_message(email) except basket.BasketException as e: # Was it that their email was not known? Or it could be invalid, # but that doesn't really make a difference. if e.code in (basket.errors.BASKET_UNKNOWN_EMAIL, basket.errors.BASKET_INVALID_EMAIL): # Tell them, give them a link to go subscribe if they want url = reverse("newsletter.subscribe") form.errors["email"] = form.error_class([ ftl("newsletters-this-email-address-is-not", url=url, ftl_files=FTL_FILES) ]) else: # Log the details log.exception("Error sending recovery message") # and tell the user that something went wrong form.errors["__all__"] = form.error_class([general_error]) else: messages.add_message(request, messages.INFO, recovery_text) # Redir as GET, signalling success return redirect(request.path + "?success") elif "success" in request.GET: # We were redirected after a successful submission. # A message will be displayed; don't display the form again. form = None else: form = EmailForm() # This view is shared between two different templates. For context see bug 1442129. if "/newsletter/opt-out-confirmation/" in request.get_full_path(): template = "newsletter/opt-out-confirmation.html" ftl_files = ["newsletter/opt-out-confirmation"] else: template = "newsletter/recovery.html" ftl_files = FTL_FILES return l10n_utils.render(request, template, {"form": form}, ftl_files=ftl_files)
def url(self): """ The url for this node's page. If this node doesn't have a page, it will return the url of its first child. If it has no children, it will return None. """ if self.page: return reverse(self.page.name) elif self.children: return self.children[0].url else: return None
def test_sf_form_proxy_invalid_form(self, post_patch): """A form error should result in a 400 response.""" with self.activate('en-US'): url = reverse('mozorg.partnerships') resp = self.client.post(url, { 'first_name': 'Dude' * 20, }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 400) resp_data = json.loads(resp.content) self.assertEqual(resp_data['msg'], 'Form invalid') self.assertFalse(post_patch.called)
def test_change_lang_country(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters self.data["lang"] = "en" self.data["country"] = "us" with self.activate("en-US"): url = reverse("newsletter.existing.token", args=(self.token, )) with patch.multiple("basket", update_user=DEFAULT, subscribe=DEFAULT, request=DEFAULT) as basket_patches: with patch("lib.l10n_utils.render"): with patch("django.contrib.messages.add_message") as add_msg: basket_patches["request"].return_value = self.user rsp = self.client.post(url, self.data) # We have an existing user with a change to their email data, # but none to their subscriptions. # 'subscribe' should not be called self.assertEqual(0, basket_patches["subscribe"].call_count) # update_user should be called once self.assertEqual(1, basket_patches["update_user"].call_count) # with the new lang and country and the newsletter list kwargs = basket_patches["update_user"].call_args[1] self.assertEqual( { "api_key": "basket_key", "lang": "en", "country": "us", "newsletters": "mozilla-and-you" }, kwargs) # No messages should be emitted self.assertEqual(0, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should redirect to the 'updated' view url = reverse("newsletter.updated") assert rsp["Location"] == url
def test_change_lang_country(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters self.data['lang'] = 'en' self.data['country'] = 'us' with self.activate('en-US'): url = reverse('newsletter.existing.token', args=(self.token, )) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render'): with patch('django.contrib.messages.add_message') as add_msg: basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # We have an existing user with a change to their email data, # but none to their subscriptions. # 'subscribe' should not be called self.assertEqual(0, basket_patches['subscribe'].call_count) # update_user should be called once self.assertEqual(1, basket_patches['update_user'].call_count) # with the new lang and country and the newsletter list kwargs = basket_patches['update_user'].call_args[1] self.assertEqual( { 'lang': u'en', 'country': u'us', 'newsletters': u'mozilla-and-you' }, kwargs) # No messages should be emitted self.assertEqual(0, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert rsp['Location'] == url
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) if scene == '2': template = 'firefox/new/scene2.html' # if no/incorrect scene specified, show scene 1 else: template = 'firefox/new/scene1.html' return l10n_utils.render(request, template)
def test_will_show_confirm_copy(self, get_newsletters, mock_basket_request): # After successful confirm, ensure proper context var is set to display # confirmation-specific copy. get_newsletters.return_value = newsletters url = "%s?confirm=1" % reverse('newsletter.existing.token', args=(self.token,)) # noinspection PyUnresolvedReferences with patch.multiple('basket', user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render') as render: basket_patches['user'].return_value = self.user render.return_value = HttpResponse('') self.client.get(url) request, template_name, context = render.call_args[0] self.assertEqual(context['did_confirm'], True)
def setUp(self): self.factory = RequestFactory() with self.activate("en-US"): self.url = reverse("legal.fraud-report") self.data = { "input_url": "http://www.test.com/", "input_category": "Charging for software", "input_product": "Firefox", "input_specific_product": "", "input_details": "test details", "input_attachment_desc": "test attachment", "input_email": "*****@*****.**", }
def setUp(self): self.factory = RequestFactory() self.view = press_views.PressInquiryView.as_view() with self.activate("en-US"): self.url = reverse("press.press-inquiry") self.data = { "jobtitle": "Senior Inquiry Person", "name": "IceCat FireBadger", "user_email": "*****@*****.**", "media_org": "Big Money", "inquiry": "Want to know private stuff", "deadline": datetime.date.today() + datetime.timedelta(days=1), }
def setUp(self): self.factory = RequestFactory() with self.activate('en-US'): self.url = reverse('legal.fraud-report') self.data = { 'input_url': 'http://www.test.com/', 'input_category': 'Charging for software', 'input_product': 'Firefox', 'input_specific_product': '', 'input_details': 'test details', 'input_attachment_desc': 'test attachment', 'input_email': '*****@*****.**', }
def setUp(self): self.factory = RequestFactory() self.view = press_views.PressInquiryView.as_view() with self.activate('en-US'): self.url = reverse('press.press-inquiry') self.data = { 'jobtitle': 'Senior Inquiry Person', 'name': 'IceCat FireBadger', 'user_email': '*****@*****.**', 'media_org': 'Big Money', 'inquiry': 'Want to know private stuff', 'deadline': datetime.date.today() + datetime.timedelta(days=1) }
def setUp(self): self.factory = RequestFactory() self.view = press_views.SpeakerRequestView.as_view() with self.activate('en-US'): self.url = reverse('press.speaker-request') self.data = { 'sr_event_name': 'Test Event', 'sr_event_url': 'www.mozilla.org', 'sr_event_date': datetime.date.today() + datetime.timedelta(days=1), 'sr_event_time': '12:00 PM', 'sr_contact_name': 'The Dude', 'sr_contact_email': '*****@*****.**', }
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) experience = request.GET.get('xv', None) variant = request.GET.get('v', None) locale = l10n_utils.get_locale(request) # ensure variant matches pre-defined value if variant not in ['a', 'b', '1', '2', '3']: variant = None if scene == '2': # `wait-face`, `reggiewatts` variations are currently localized for both en-US and de locales. if lang_file_is_active('firefox/new/wait-face', locale) and experience == 'waitface': template = 'firefox/new/wait-face/scene2.html' elif lang_file_is_active('firefox/new/reggiewatts', locale) and experience == 'reggiewatts': template = 'firefox/new/reggie-watts/scene2.html' else: template = 'firefox/new/scene2.html' # if no/incorrect scene specified, show scene 1 else: if lang_file_is_active('firefox/new/wait-face', locale) and experience == 'waitface': if switch('experiment-firefox-new-waitface'): if variant == 'b': template = 'firefox/new/wait-face/scene1-video.html' else: template = 'firefox/new/wait-face/scene1.html' elif switch('experiment-firefox-new-waitface-switch'): if variant == '2': template = 'firefox/new/wait-face/scene1-newcopy.html' elif variant == '3': template = 'firefox/new/wait-face/scene1-switch.html' else: template = 'firefox/new/wait-face/scene1.html' else: template = 'firefox/new/wait-face/scene1.html' elif lang_file_is_active('firefox/new/reggiewatts', locale) and experience == 'reggiewatts': template = 'firefox/new/reggie-watts/scene1.html' else: template = 'firefox/new/scene1.html' return l10n_utils.render(request, template, {'v': variant})
def setUp(self): self.factory = RequestFactory() self.view = press_views.SpeakerRequestView.as_view() with self.activate("en-US"): self.url = reverse("press.speaker-request") self.data = { "sr_event_name": "Test Event", "sr_event_url": "www.mozilla.org", "sr_event_date": datetime.date.today() + datetime.timedelta(days=1), "sr_event_time": "12:00 PM", "sr_contact_name": "The Dude", "sr_contact_email": "*****@*****.**", }
def test_subscribing(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters # They subscribe to firefox-tips self.data['form-2-subscribed_check'] = u'true' # in English - and that's their language too self.user['lang'] = u'en' self.data['lang'] = u'en' url = reverse('newsletter.existing.token', args=(self.token, )) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('django.contrib.messages.add_message') as add_msg: with patch('lib.l10n_utils.render'): basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # Should have given no messages self.assertEqual(0, add_msg.call_count, msg=repr(add_msg.call_args_list)) # Should have called update_user with subscription list self.assertEqual(1, basket_patches['update_user'].call_count) kwargs = basket_patches['update_user'].call_args[1] self.assertEqual( { 'newsletters': u'mozilla-and-you,firefox-tips', 'lang': u'en' }, kwargs) # Should not have called unsubscribe self.assertEqual(0, basket_patches['unsubscribe'].call_count) # Should not have called subscribe self.assertEqual(0, basket_patches['subscribe'].call_count) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert rsp['Location'] == url
def test_get_token(self, get_newsletters, mock_basket_request): # If user gets page with valid token in their URL, they # see their data, and no privacy checkbox is presented get_newsletters.return_value = newsletters url = reverse("newsletter.existing.token", args=(self.token,)) # noinspection PyUnresolvedReferences with patch.multiple("basket", update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, request=DEFAULT) as basket_patches: with patch("lib.l10n_utils.render") as render: basket_patches["request"].return_value = self.user render.return_value = HttpResponse("") self.client.get(url) request, template_name, context = render.call_args[0] form = context["form"] self.assertNotIn("privacy", form.fields) self.assertEqual(self.user["lang"], form.initial["lang"])
def test_unsubscribing(self, get_newsletters, mock_basket_request): get_newsletters.return_value = newsletters # They unsubscribe from the one newsletter they're subscribed to self.data['form-0-subscribed_radio'] = u'false' url = reverse('newsletter.existing.token', args=(self.token, )) with patch.multiple('basket', update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, user=DEFAULT) as basket_patches: with patch('lib.l10n_utils.render'): basket_patches['user'].return_value = self.user rsp = self.client.post(url, self.data) # Should have called update_user with list of newsletters self.assertEqual(1, basket_patches['update_user'].call_count) kwargs = basket_patches['update_user'].call_args[1] self.assertEqual({'newsletters': u'', 'lang': u'pt'}, kwargs) # Should not have called subscribe self.assertEqual(0, basket_patches['subscribe'].call_count) # Should not have called unsubscribe self.assertEqual(0, basket_patches['unsubscribe'].call_count) # Should redirect to the 'updated' view url = reverse('newsletter.updated') assert rsp['Location'] == url
def test_newsletter_ordering(self, get_newsletters, mock_basket_request): # Newsletters are listed in 'order' order, if they have an 'order' # field get_newsletters.return_value = newsletters url = reverse("newsletter.existing.token", args=(self.token,)) self.user["newsletters"] = ["mozilla-and-you", "firefox-tips", "beta"] with patch.multiple("basket", update_user=DEFAULT, subscribe=DEFAULT, unsubscribe=DEFAULT, request=DEFAULT) as basket_patches: with patch("lib.l10n_utils.render") as render: basket_patches["request"].return_value = self.user render.return_value = HttpResponse("") self.client.get(url) request, template_name, context = render.call_args[0] forms = context["formset"].initial_forms newsletters_in_order = [form.initial["newsletter"] for form in forms] self.assertEqual(["firefox-tips", "mozilla-and-you"], newsletters_in_order)
def test_subscribe(self, mock_subscribe, mock_request): mock_subscribe.return_value = { 'token': 'token-example', 'status': 'ok', 'created': 'True' } data = { 'email': u'*****@*****.**', 'country': 'gr', 'fmt': 'H', 'first_name': 'foo', 'last_name': 'bar', 'status': 'teacher', 'school': 'TuC', 'city': 'Chania', 'age_confirmation': 'on', 'grad_year': '', 'nl_about_mozilla': 'on', 'major': '', 'major_free_text': '', 'privacy': 'True' } request_data = { 'FIRST_NAME': data['first_name'], 'LAST_NAME': data['last_name'], 'STUDENTS_CURRENT_STATUS': data['status'], 'STUDENTS_SCHOOL': data['school'], 'STUDENTS_GRAD_YEAR': data['grad_year'], 'STUDENTS_MAJOR': data['major'], 'COUNTRY_': data['country'], 'STUDENTS_CITY': data['city'], 'STUDENTS_ALLOW_SHARE': 'N' } with self.activate('en-US'): self.client.post( reverse('mozorg.contribute.studentambassadors.join'), data) mock_subscribe.assert_called_with( data['email'], ['ambassadors', 'about-mozilla'], format=u'H', country=u'gr', source_url=u'', sync='Y', welcome_message='Student_Ambassadors_Welcome') mock_request.assert_called_with('post', 'custom_update_student_ambassadors', token='token-example', data=request_data)
def redirect_to(self): """ Redirect visitors based on their user-agent. - Up-to-date Firefox users pass through. - Other Firefox users go to the new page. - Non Firefox users go to the configured page. """ query = self.request.META.get('QUERY_STRING') query = '?' + query if query else '' user_agent = self.request.META.get('HTTP_USER_AGENT', '') if 'Firefox' not in user_agent: return reverse(self.non_fx_redirect) + query # TODO : Where to redirect bug 757206 return None
def test_sf_form_proxy(self, post_patch): new_mock = Mock() new_mock.status_code = 200 post_patch.return_value = new_mock with self.activate('en-US'): url = reverse('mozorg.partnerships') resp = self.client.post(url, { 'first_name': 'The', 'last_name': 'Dude', 'title': 'Abider of things', 'company': 'Urban Achievers', 'email': '*****@*****.**', }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(resp.status_code, 200) resp_data = json.loads(resp.content) self.assertEqual(resp_data['msg'], 'ok') post_patch.assert_called_once_with( ANY, { 'first_name': u'The', 'last_name': u'Dude', 'description': u'', 'retURL': 'http://www.mozilla.org/en-US/about/' 'partnerships?success=1', 'title': u'Abider of things', 'URL': u'', 'company': u'Urban Achievers', 'oid': '00DU0000000IrgO', 'phone': u'', 'street': u'', 'zip': u'', 'city': u'', 'state': u'', 'country': u'', 'mobile': u'', '00NU0000002pDJr': [], # interest (multi-select) '00NU00000053D4G': u'', # interested_countries '00NU00000053D4L': u'', # interested_languages '00NU00000053D4a': u'', # campaign_type 'industry': u'', 'email': u'*****@*****.**', 'lead_source': 'www.mozilla.org/about/partnerships/', })