def test_not_staff(self): """ User is not staff - should be rejected. """ self.user.is_staff = False self.user.save() response = self.client.get(reverse('manage:home')) self.assertRedirects(response, settings.LOGIN_URL + '?next=' + reverse('manage:home'))
def test_cant_view_all_revision_changes(self): event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) # base revision base_revision = EventRevision.objects.create_from_event(event) # change the event without saving so we can make a new revision event.title = 'Different title' user = User.objects.create_user( 'mary', '*****@*****.**', 'secret' ) user_revision = EventRevision.objects.create_from_event( event, user=user ) change_url = reverse( 'main:event_change', args=(event.slug, user_revision.pk) ) difference_url = reverse( 'main:event_difference', args=(event.slug, base_revision.pk) ) # you're not allowed to view these if you're not signed in response = self.client.get(change_url) eq_(response.status_code, 302) response = self.client.get(difference_url) eq_(response.status_code, 302)
def test_save_on_an_active_event_edit(self, rhead): def mocked_head(url, **options): return HeadResponse(**{'content-length': 123456}) rhead.side_effect = mocked_head user = self._login() user.is_superuser = True user.is_staff = True user.save() event = Event.objects.get(title='Test event') event_upload_url = reverse('manage:event_upload', args=(event.pk,)) response = self.client.get(event_upload_url) eq_(response.status_code, 200) url = reverse('uploads:save') response = self.client.post(url, { 'url': 'https://aws.com/foo.flv' }) eq_(response.status_code, 200) structure = json.loads(response.content) new_id = structure['id'] upload = Upload.objects.get(pk=new_id) eq_(upload.size, 123456) eq_(upload.url, 'https://aws.com/foo.flv') eq_(upload.file_name, 'foo.flv') eq_(upload.user, user) eq_(upload.event, event) event = Event.objects.get(pk=event.pk) eq_(event.upload, upload)
def test_save(self, rhead): def mocked_head(url, **options): return HeadResponse(**{'content-length': 123456}) rhead.side_effect = mocked_head url = reverse('uploads:save') response = self.client.post(url) eq_(response.status_code, 302) ok_(reverse('main:login') in response['location']) user = self._login() response = self.client.post(url) eq_(response.status_code, 400) response = self.client.post(url, { 'url': 'https://aws.com/foo.flv' }) eq_(response.status_code, 200) structure = json.loads(response.content) new_id = structure['id'] upload = Upload.objects.get(pk=new_id) eq_(upload.size, 123456) eq_(upload.url, 'https://aws.com/foo.flv') eq_(upload.file_name, 'foo.flv') eq_(upload.user, user)
def test_deferred_award_claim_on_login(self): """Ensure that a deferred award gets claimed on login.""" deferred_email = "*****@*****.**" user1 = self._get_user(username="******", email="*****@*****.**") b1 = Badge.objects.create(creator=user1, title="Badge to defer") url = reverse('badger.views.award_badge', args=(b1.slug,)) self.client.login(username="******", password="******") r = self.client.get(url, follow=True) eq_(200, r.status_code) doc = pq(r.content) form = doc('form#award_badge') eq_(1, form.length) eq_(1, form.find('*[name=emails]').length) eq_(1, form.find('input.submit,button.submit').length) r = self.client.post(url, dict( emails=deferred_email, ), follow=False) ok_('award' not in r['Location']) user2 = self._get_user(username="******", email=deferred_email) self.client.login(username="******", password="******") r = self.client.get(reverse('badger.views.detail', args=(b1.slug,)), follow=True) ok_(b1.is_awarded_to(user2))
def test_event(self): """Event view page loads correctly if the event is public and scheduled and approved; request a login otherwise.""" event = Event.objects.get(title='Test event') group = Group.objects.get() approval = Approval(event=event, group=group) approval.save() event_page = reverse('main:event', kwargs={'slug': event.slug}) response_fail_approval = self.client.get(event_page) eq_(response_fail_approval.status_code, 200) ok_('not approved' in response_fail_approval.content) approval.approved = True approval.processed = True approval.save() response_ok = self.client.get(event_page) eq_(response_ok.status_code, 200) event.public = False event.save() response_fail = self.client.get(event_page) self.assertRedirects(response_fail, reverse('main:login')) event.public = True event.status = Event.STATUS_INITIATED event.save() response_fail = self.client.get(event_page) eq_(response_fail.status_code, 200) ok_('not scheduled' in response_fail.content)
def test_staticpage_edit_custom_headers(self): staticpage = StaticPage.objects.get(title='Test page') staticpage.headers = { 'Key': 'Value', } staticpage.save() url = reverse('manage:staticpage_edit', kwargs={'id': staticpage.id}) response = self.client.get(url) eq_(response.status_code, 200) ok_('Key: Value' in response.content) data = { 'url': staticpage.url, 'title': 'New test page', 'content': '<p>New content</p>', 'privacy': Event.PRIVACY_CONTRIBUTORS, } response = self.client.post(url, dict( data, headers=" Singleword ", )) eq_(response.status_code, 200) ok_('Form errors' in response.content) response = self.client.post(url, dict( data, headers=" Custom: Value ", )) self.assertRedirects(response, reverse('manage:staticpages')) staticpage = StaticPage.objects.get(id=staticpage.id) eq_(staticpage.headers, {'Custom': 'Value'})
def test_edit_nothing(self): """basically pressing save without changing anything""" event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) url = reverse('main:event_edit', args=(event.slug,)) data = self._event_to_dict(event) previous = json.dumps(data) data = { 'event_id': event.id, 'previous': previous, 'title': event.title, 'short_description': event.short_description, 'description': event.description, 'additional_links': event.additional_links, 'tags': ', '.join(x.name for x in event.tags.all()), 'channels': [x.pk for x in event.channels.all()] } response = self.client.post(url, data) eq_(response.status_code, 302) self.assertRedirects( response, reverse('main:event', args=(event.slug,)) ) self._login() response = self.client.post(url, data) eq_(response.status_code, 302) ok_(not EventRevision.objects.all())
def test_firstrun_alternate(self): """ Hitting /firefox/{version}/firstrun/?f={fx_views.FirstrunView.funnelcake_campaign} with latest Fx & en-US locale should render firefox/firstrun/a.html, regardless of {version}. Any other f value or locale should render firefox/firstrun.html. """ user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) " "Gecko/20100101 Firefox/16.0" fc_id = fx_views.FirstrunView.funnelcake_campaign expected = "Use Themes to change the look of your Firefox just about any way you like." # en-US with proper funnelcake id should give expected content response = self.client.get(self.url + "?f=" + fc_id, HTTP_USER_AGENT=user_agent) self.assertIn(expected, response.content) # en-US with improper funnelcake id should not give expected content response = self.client.get(self.url + "?f=0", HTTP_USER_AGENT=user_agent) self.assertNotIn(expected, response.content) # en-US with no funnelcake id should not give expected content response = self.client.get(self.url, HTTP_USER_AGENT=user_agent) self.assertNotIn(expected, response.content) # en-US with proper funnelcake id and no {version} should give expected content self.url = reverse("firefox.firstrun") response = self.client.get(self.url + "?f=" + fc_id, HTTP_USER_AGENT=user_agent) self.assertIn(expected, response.content) # es-ES with proper funnelcake id should not give expected content with self.activate("es-ES"): self.url = reverse("firefox.firstrun", args=["16.0"]) response = self.client.get(self.url + "?f=" + fc_id, HTTP_USER_AGENT=user_agent) self.assertNotIn(expected, response.content)
def test_participant_edit(self): """Participant edit page responds OK; bad form results in failure; submission induces a change. """ participant = Participant.objects.get(name='Tim Mickel') response = self.client.get(reverse('manage:participant_edit', kwargs={'id': participant.id})) eq_(response.status_code, 200) response_ok = self.client.post( reverse('manage:participant_edit', kwargs={'id': participant.id}), { 'name': 'George Washington', 'email': '*****@*****.**', 'role': Participant.ROLE_PRINCIPAL_PRESENTER, 'cleared': Participant.CLEARED_YES } ) self.assertRedirects(response_ok, reverse('manage:participants')) participant_george = Participant.objects.get(id=participant.id) eq_(participant_george.name, 'George Washington') response_fail = self.client.post( reverse('manage:participant_edit', kwargs={'id': participant.id}), { 'name': 'George Washington', 'email': 'bademail' } ) eq_(response_fail.status_code, 200)
def test_participant_pages(self): """Participants pagination always returns valid pages.""" response = self.client.get(reverse('manage:participants')) eq_(response.status_code, 200) response = self.client.get(reverse('manage:participants'), {'page': 5000}) eq_(response.status_code, 200)
def test_calendars_description(self): event = Event.objects.get(title="Test event") event.description = """ Check out the <a href="http://example.com">Example</a> page and <strong>THIS PAGE</strong> here. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. If the text is getting really long it will be truncated. """.strip() event.save() response_public = self.client.get(reverse("main:calendar")) eq_(response_public.status_code, 200) ok_("Check out the Example page" in response_public.content) ok_("and THIS PAGE here" in response_public.content) ok_("will be truncated" not in response_public.content) event.short_description = "One-liner" event.save() response_public = self.client.get(reverse("main:calendar")) eq_(response_public.status_code, 200) ok_("Check out the" not in response_public.content) ok_("One-liner" in response_public.content)
def register(request): """Registers Users. Pulls out an invite code if it exists and auto validates the user if so. Single-purpose view. """ if 'code' in request.GET: request.session['invite-code'] = request.GET['code'] return redirect('home') user = request.user if user.is_authenticated() and user.userprofile.is_complete: return redirect('home') user_form = UserForm(request.POST or None, instance=user) profile_form = RegisterForm(request.POST or None, instance=user.get_profile()) if (user_form.is_valid() and profile_form.is_valid()): user_form.save() profile_form.save() auth.login(request, user) _update_invites(request) messages.info(request, _(u'Your account has been created.')) return redirect(reverse('profile', args=[request.user.username])) # 'user' object must be passed in because we are not logged in return render(request, 'registration/register.html', dict(profile_form=profile_form, user_form=user_form, edit_form_action=reverse('register'), mode='new', profile=user.get_profile(), user=user, ))
def test_pending_edit_profile(self): # do all then reset newbie_client = self.pending_client newbie = self.pending profile_url = reverse('profile', args=[newbie.username]) edit_profile_url = reverse('profile.edit') # original r = newbie_client.get(profile_url) newbie = r.context['profile'] first = newbie.user.first_name last = newbie.user.last_name bio = newbie.bio # update data = dict(first_name='Hobo', last_name='LaRue', bio='Rides the rails') edit = newbie_client.post(edit_profile_url, data, follow=True) eq_(200, edit.status_code, 'Edits okay') r = newbie_client.get(profile_url) newbie = r.context['profile'] self.assertNotEqual(first, newbie.user.first_name) self.assertNotEqual(last, newbie.user.last_name) self.assertNotEqual(bio, newbie.bio) dn = "%s %s" % (newbie.user.first_name, newbie.user.last_name) eq_(dn, newbie.display_name, 'Editing should update display name') # cleanup delete_url = reverse('profile.delete') r = newbie_client.post(delete_url, follow=True) eq_(200, r.status_code, 'A Mozillian can delete their own account')
def test_pending_edit_profile(self): # do all then reset newbie_client = self.pending_client newbie = self.pending profile_url = reverse('profile', args=[newbie.username]) edit_profile_url = reverse('profile.edit') # original r = newbie_client.get(profile_url) newbie = r.context['profile'] full = newbie.full_name bio = newbie.bio # update data = self.data_privacy_fields.copy() data.update(dict(full_name='Hobo LaRue', country='pl', bio='Rides the rails')) edit = newbie_client.post(edit_profile_url, data, follow=True) eq_(200, edit.status_code, 'Edits okay') r = newbie_client.get(profile_url) newbie = r.context['profile'] self.assertNotEqual(full, newbie.full_name) self.assertNotEqual(bio, newbie.bio) # cleanup delete_url = reverse('profile.delete') r = newbie_client.post(delete_url, follow=True) eq_(200, r.status_code, 'A Mozillian can delete their own account')
def test_mozillian_can_vouch(self): """ Tests the vouching system's happy path. Kind of a big test because we want to: a. Test registration's happy path b. Test vouching c. Test account deletion """ moz_client = self.mozillian_client r = moz_client.get(reverse('profile', args=[self.pending.username])) eq_(200, r.status_code) doc = pq(r.content) self.assertTrue(doc('form#vouch-form')) vouch_url = reverse('vouch') data = dict(vouchee=self.pending.get_profile().id) vouched_profile = moz_client.post(vouch_url, data, follow=True) self.pending = User.objects.get(pk=self.pending.pk) eq_(200, vouched_profile.status_code) r = moz_client.get(reverse('profile', args=[self.pending.username])) eq_(200, r.status_code) doc = pq(r.content) self.assertTrue(not doc('form#vouch-form')) eq_(self.pending.get_profile().vouched_by.user, self.mozillian, 'Credit given')
def _delete_flow(self, user): """Private method used to walk through account deletion flow.""" self.client.login(email=user.email) user_id = User.objects.get(email=user.email).id r = self.client.get(reverse('profile.edit')) doc = pq(r.content) # Make sure there's a link to a confirm deletion page, and nothing # pointing directly to the delete URL. eq_(reverse('profile.delete_confirm'), doc('a.btn-danger').attr('href'), 'We see a link to a confirmation page.') self.assertFalse(any((reverse('profile.delete') in el.action) for el in doc('#main form')), "We don't see a form posting to the account delete URL.") # Follow the link to the deletion confirmation page. r = self.client.get(doc('a.btn-danger').attr('href')) # Test that we can go back (i.e. cancel account deletion). doc = pq(r.content) eq_(reverse('profile.edit'), doc('#cancel-action').attr('href')) # Test that account deletion works. delete_url = doc('#delete-action').closest('form').attr('action') r = self.client.post(delete_url, follow=True) eq_(200, r.status_code) self.assertFalse(_logged_in_html(r)) # Make sure the user data isn't there anymore assert not User.objects.get(id=user_id).first_name assert not User.objects.get(id=user_id).email assert not User.objects.get(id=user_id).is_active
def save(request): form = forms.SaveForm(request.POST) if not form.is_valid(): return http.HttpResponseBadRequest(str(form.errors)) url = form.cleaned_data['url'] upload_time = form.cleaned_data['upload_time'] cache_key = 'length_%s' % hashlib.md5(url).hexdigest() size = cache.get(cache_key) if not size: r = requests.head(url) size = int(r.headers['content-length']) if not size: return http.HttpResponseBadRequest('URL could not be downloaded') cache_key = 'file_name_%s' % hashlib.md5(url).hexdigest() file_name = cache.get(cache_key) if not file_name: file_name = os.path.basename(url) cache_key = 'mime_type_%s' % hashlib.md5(url).hexdigest() mime_type = cache.get(cache_key) new_upload = Upload.objects.create( user=request.user, url=url, size=size, file_name=file_name, mime_type=mime_type, upload_time=upload_time, ) messages.info( request, 'Upload saved.' ) context = {'id': new_upload.pk, 'url': new_upload.url} if request.session.get('active_event'): event_id = request.session['active_event'] event = Event.objects.get(pk=event_id) event.upload = new_upload event.save() new_upload.event = event new_upload.save() next_url = reverse('manage:event_archive', args=(event_id,)) next_url += '#vidly-shortcutter' context['event'] = { 'url': next_url, 'title': event.title, } elif request.session.get('active_suggested_event'): event_id = request.session['active_suggested_event'] event = SuggestedEvent.objects.get(pk=event_id) event.upload = new_upload event.save() new_upload.suggested_event = event new_upload.save() next_url = reverse('suggest:description', args=(event_id,)) context['suggested_event'] = { 'url': next_url, 'title': event.title } return context
def get_download_url(channel='Release'): if channel == 'Aurora': return reverse('firefox.channel') + '#aurora' elif channel == 'Beta': return reverse('firefox.channel') + '#beta' else: return reverse('firefox')
def test_groups_are_case_insensitive(self): """Ensure groups are case insensitive.""" profile = self.mozillian.get_profile() self.client.login(email=self.mozillian.email) self.client.post(reverse('profile.edit'), dict(last_name='tofumatt', groups='Awesome,foo,Bar'), follow=True) eq_(3, profile.groups.count(), 'Three groups should be saved.') group_string = stringify_groups(profile.groups.all()) for g in ['awesome', 'bar', 'foo']: assert g in group_string, ( 'All three saved groups should be lowercase.') assert not 'Awesome' in group_string, ( 'Uppercase group should be transformed to lowercase.') # Make an AJAX request for a group using a capital letter. r = self.client.get(reverse('group_search'), dict(term='Awesome'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') for g in json.loads(r.content): assert g.name == g.name.lower(), ( 'Group search is case-insensitive.')
def test_staticpage_edit_with_sidebar(self): staticpage = StaticPage.objects.get(title='Test page') url = reverse('manage:staticpage_edit', kwargs={'id': staticpage.id}) response = self.client.get(url) eq_(response.status_code, 200) response_fail = self.client.post(url, { 'url': 'sidebar_bottom_main', 'title': 'New test page', 'content': '<p>New content</p>', 'privacy': Event.PRIVACY_CONTRIBUTORS, 'headers': '', }) eq_(response_fail.status_code, 200) response_ok = self.client.post(url, { 'url': 'sidebar_bottom_main', 'title': 'New test page', 'content': '<p>New content</p>', 'privacy': Event.PRIVACY_PUBLIC, 'headers': '', }) self.assertRedirects(response_ok, reverse('manage:staticpages')) staticpage = StaticPage.objects.get(id=staticpage.id) eq_(staticpage.content, '<p>New content</p>') eq_('Sidebar (bottom) Main', staticpage.title)
def test_view_private_events_with_notices(self): # for https://bugzilla.mozilla.org/show_bug.cgi?id=821458 event = Event.objects.get(title="Test event") assert event.privacy == Event.PRIVACY_PUBLIC # default event.privacy = Event.PRIVACY_CONTRIBUTORS event.save() url = reverse("main:event", args=(event.slug,)) response = self.client.get(url) self.assertRedirects(response, reverse("main:login")) contributor = User.objects.create_user("nigel", "*****@*****.**", "secret") UserProfile.objects.create(user=contributor, contributor=True) assert self.client.login(username="******", password="******") response = self.client.get(url) eq_(response.status_code, 200) ok_("This video is available only to Mozilla volunteers and staff" in response.content) event.privacy = Event.PRIVACY_COMPANY event.save() response = self.client.get(url) self.assertRedirects(response, reverse("main:login")) User.objects.create_user("worker", "*****@*****.**", "secret") assert self.client.login(username="******", password="******") response = self.client.get(url) eq_(response.status_code, 200) ok_("This video is available only to Mozilla staff" in response.content)
def group_add_edit(request, url=None): """ Add or edit a group. (If a url is passed in, we're editing.) """ profile = request.user.userprofile if url: # Get the group to edit group = get_object_or_404(Group, url=url) # Only a group curator or an admin is allowed to edit a group is_curator = profile == group.curator if not (is_curator or request.user.is_superuser): messages.error(request, _('You must be a curator or an admin to edit a group')) return redirect(reverse('groups:show_group', args=[group.url])) else: group = Group(curator=profile) form_class = SuperuserGroupForm if request.user.is_superuser else GroupForm form = form_class(request.POST or None, instance=group) if form.is_valid(): group = form.save() # Ensure curator is in the group when it's created if profile == group.curator and not group.has_member(profile): group.add_member(profile) return redirect(reverse('groups:show_group', args=[group.url])) context = { 'form': form, 'creating': url is None, 'group': group if url else None, } return render(request, 'groups/add_edit.html', context)
def test_edit_no_image(self): """basically pressing save without changing anything""" event = Event.objects.get(title='Test event') event.placeholder_img = None event.save() url = reverse('main:event_edit', args=(event.slug,)) data = self._event_to_dict(event) previous = json.dumps(data) data = { 'event_id': event.id, 'previous': previous, 'title': event.title, 'short_description': event.short_description, 'description': event.description, 'additional_links': event.additional_links, 'tags': ', '.join(x.name for x in event.tags.all()), 'channels': [x.pk for x in event.channels.all()] } response = self.client.post(url, data) eq_(response.status_code, 302) self.assertRedirects( response, reverse('main:event', args=(event.slug,)) ) self._login() response = self.client.post(url, data) eq_(response.status_code, 200) ok_('Events needs to have a picture' in response.context['form'].errors['__all__']) ok_('Events needs to have a picture' in response.content)
def test_event_assignment(self): event = Event.objects.get(title='Test event') url = reverse('manage:event_assignment', args=(event.pk,)) edit_url = reverse('manage:event_edit', args=(event.pk,)) response = self.client.get(edit_url) eq_(response.status_code, 200) ok_(url in response.content) barcelona = Location.objects.create(name='Barcelona') moon = Location.objects.create(name='Moon', is_active=False) response = self.client.get(url) eq_(response.status_code, 200) ok_('<option value="%s">' % barcelona.id in response.content) ok_('<option value="%s">' % moon.id not in response.content) ok_(event.location.name in response.content) bob = User.objects.create(username='******') harry = User.objects.create(username='******') data = { 'users': [bob.pk, harry.pk], 'locations': [barcelona.pk] } response = self.client.post(url, data) eq_(response.status_code, 302) assignment = EventAssignment.objects.get(event=event) ok_(bob in assignment.users.all()) ok_(harry in assignment.users.all()) ok_(barcelona in assignment.locations.all())
def test_participant_autocomplete(self): """Autocomplete makes JSON pages and correct results for fixtures.""" response = self.client.get( reverse('manage:participant_autocomplete'), { 'q': 'Ti' } ) eq_(response.status_code, 200) parsed = json.loads(response.content) ok_('participants' in parsed) participants = [p['text'] for p in parsed['participants'] if 'text' in p] eq_(len(participants), 1) ok_('Tim Mickel' in participants) response_fail = self.client.get( reverse('manage:participant_autocomplete'), { 'q': 'ickel' } ) eq_(response_fail.status_code, 200) parsed_fail = json.loads(response_fail.content) eq_(parsed_fail, {'participants': []}) response_blank = self.client.get( reverse('manage:participant_autocomplete'), { 'q': '' } ) eq_(response_blank.status_code, 200) parsed_blank = json.loads(response_blank.content) eq_(parsed_blank, {'participants': []})
def test_home(self): """Index page loads and paginates correctly.""" response = self.client.get(reverse("main:home")) eq_(response.status_code, 200) response_empty_page = self.client.get(reverse("main:home", kwargs={"page": 10000})) eq_(response_empty_page.status_code, 200)
def test_deferred_award_immediate_claim(self): """Ensure that a deferred award can be immediately claimed rather than viewing detail""" deferred_email = "*****@*****.**" user1 = self._get_user(username="******", email="*****@*****.**") b1 = Badge.objects.create(creator=user1, title="Badge to defer") da = DeferredAward(badge=b1, creator=user1) da.save() url = da.get_claim_url() # Just viewing the claim URL shouldn't require login. r = self.client.get(url, follow=False) eq_(200, r.status_code) # But, attempting to claim the award should require login r = self.client.post(reverse('badger.views.claim_deferred_award'), dict( code=da.claim_code, ), follow=False) eq_(302, r.status_code) ok_('login' in r['Location']) # So, try logging in and fetch the immediate-claim URL user2 = self._get_user(username="******", email=deferred_email) self.client.login(username="******", password="******") r = self.client.post(reverse('badger.views.claim_deferred_award'), dict( code=da.claim_code, ), follow=False) eq_(302, r.status_code) ok_('awards' in r['Location']) ok_(b1.is_awarded_to(user2))
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 new 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('firefox.new') + query # TODO : Where to redirect bug 757206 user_version = '0' match = UA_REGEXP.search(user_agent) if match: user_version = match.group(1) if not is_current_or_newer(user_version): return reverse('firefox.new') + query return None
def tags_data(request): context = {} tags = [] counts = {} qs = ( Event.tags.through.objects.all() .values('tag_id').annotate(Count('tag')) ) for each in qs: counts[each['tag_id']] = each['tag__count'] _repeats = collections.defaultdict(int) for tag in Tag.objects.all(): _repeats[tag.name.lower()] += 1 for tag in Tag.objects.all(): tags.append({ 'name': tag.name, 'id': tag.id, '_usage_count': counts.get(tag.id, 0), '_repeated': _repeats[tag.name.lower()] > 1, }) context['tags'] = tags context['urls'] = { 'manage:tag_edit': reverse('manage:tag_edit', args=(0,)), 'manage:tag_remove': reverse('manage:tag_remove', args=(0,)), } return context
def test_vidly_media(self): url = reverse('manage:vidly_media') response = self.client.get(url) eq_(response.status_code, 200) event = Event.objects.get(title='Test event') ok_(event.title not in response.content) event.template = Template.objects.create( name='Vid.ly Something', content='<iframe>' ) event.save() response = self.client.get(url) eq_(response.status_code, 200) ok_(event.title in response.content) # or the event might not yet have made the switch but already # has a VidlySubmission event.template = None event.save() response = self.client.get(url) eq_(response.status_code, 200) ok_(event.title not in response.content) then = timezone.now() - datetime.timedelta(days=1) VidlySubmission.objects.create( event=event, tag='xyz000', submission_time=then, finished=then + datetime.timedelta(seconds=7) ) response = self.client.get(url) eq_(response.status_code, 200) ok_(event.title in response.content) ok_('7s' in response.content)
def discussion(request, id): event = get_object_or_404(SuggestedEvent, pk=id) if event.user != request.user: return http.HttpResponseBadRequest('Not your event') discussion = SuggestedDiscussion.objects.get(event=event) if request.method == 'POST': form = forms.DiscussionForm(request.POST, instance=discussion) if form.is_valid(): discussion = form.save() discussion.moderators.clear() for email in form.cleaned_data['emails']: try: user = User.objects.get(email__iexact=email) except User.DoesNotExist: user = User.objects.create( username=email.split('@')[0], email=email ) user.set_unusable_password() user.save() discussion.moderators.add(user) url = reverse('suggest:placeholder', args=(event.pk,)) return redirect(url) else: emails = [] for moderator in discussion.moderators.all(): if moderator.email not in emails: emails.append(moderator.email) if not emails: emails.append(request.user.email) initial = {'emails': ', '.join(emails)} form = forms.DiscussionForm(instance=discussion, initial=initial) context = {'event': event, 'form': form, 'discussion': discussion} return render(request, 'suggest/discussion.html', context)
def test_edit_channel(self): event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) main_channel = Channel.objects.get(slug=settings.DEFAULT_CHANNEL_SLUG) assert main_channel in event.channels.all() url = reverse('main:event_edit', args=(event.slug, )) old_channel = Channel.objects.create(name='Old', slug='old', never_show=True) bad_channel = Channel.objects.create(name='Bad', slug='bad', never_show=True) good_channel = Channel.objects.create( name='Good', slug='good', ) event.channels.add(old_channel) self._login() response = self.client.get(url) eq_(response.status_code, 200) # the Good channel should be a choice html = '<option value="{0}">{1}</option>'.format( good_channel.id, good_channel.name) ok_(html in response.content) # the Main channel should be in there and already selected html = '<option value="{0}" selected="selected">{1}</option>'.format( main_channel.id, main_channel.name) ok_(html in response.content) # the Old channel should be in there and already selected html = '<option value="{0}" selected="selected">{1}</option>'.format( old_channel.id, old_channel.name) ok_(html in response.content) # the bad channel shouldn't even be a choice html = '<option value="{0}">{1}</option>'.format( bad_channel.id, bad_channel.name) ok_(html not in response.content)
def test_whatsnew_tour(self): """ Hitting /firefox/29.0/whatsnew/?f=30 with en-US locale should render firefox/australis/whatsnew-no-tour.html. Hitting en-US locale with f=31 should render firefox/australis/whatsnew-tour.html. Any other f value or locale should not show the tour. """ # en-US with funnelcake id 30 should not give a tour response = self.client.get(self.url + '?f=30', HTTP_USER_AGENT=self.user_agent) self.assertNotIn(self.expected, response.content) # en-US with funnelcake id 30 plus oldversion should not get a tour response = self.client.get(self.url + '?f=30&oldversion=28.0', HTTP_USER_AGENT=self.user_agent) self.assertNotIn(self.expected, response.content) # en-US with funnelcake id 31 should give a tour response = self.client.get(self.url + '?f=31', HTTP_USER_AGENT=self.user_agent) self.assertIn(self.expected, response.content) # en-US with improper funnelcake id should not give a tour response = self.client.get(self.url + '?f=0', HTTP_USER_AGENT=self.user_agent) self.assertNotIn(self.expected, response.content) # en-US with no funnelcake id should not give a tour response = self.client.get(self.url, HTTP_USER_AGENT=self.user_agent) self.assertNotIn(self.expected, response.content) with self.activate('de'): self.url = reverse('firefox.whatsnew', args=['29.0']) # de with funnelcake id 31 should not get a tour response = self.client.get(self.url + '?f=31', HTTP_USER_AGENT=self.user_agent) self.assertNotIn(self.expected, response.content)
def test_vidly_webhook(self, p_urllib2): xml_string = SAMPLE_MEDIA_RESULT_SUCCESS success_xml = xmltodict.parse(xml_string) url = reverse('popcorn:vidly_webhook') task = success_xml['Response']['Result']['Task'] tag = task['MediaShortLink'] file_url = task['SourceFile'] def make_mock_request(url, querystring): return mock.MagicMock() def mocked_urlopen(request): xml_string = get_custom_XML(tag=tag, status='Finished', private='false') return StringIO(xml_string) p_urllib2.Request.side_effect = make_mock_request p_urllib2.urlopen = mocked_urlopen event = Event.objects.get(title='Test event') event.template.name = 'this is a vid.ly video' event.template.save() event.template_environment = {'tag': tag} event.save() vidly_submission = VidlySubmission.objects.create( event=event, url=file_url, tag=tag, token_protection=False) response = self.client.post(url, {'xml': xml_string}) eq_(response.status_code, 200) eq_('OK\n', response.content) # Check that submission was created vidly_submission = VidlySubmission.objects.get(id=vidly_submission.id) ok_(vidly_submission.finished)
def test_popcorn_editor(self): event = Event.objects.get(title='Test event') event.template.name = 'this is a vid.ly video' event.template.save() event.template_environment = {'tag': 'abc123'} event.save() url = reverse('popcorn:render_editor', args=(event.slug, )) response = self.client.get(url, {'slug': event.slug}) eq_(response.status_code, 302) event.privacy = Event.PRIVACY_COMPANY event.save() response = self.client.get(url, {'slug': event.slug}) eq_(response.status_code, 302) self._login() response = self.client.get(url, {'slug': event.slug}) eq_(response.status_code, 200)
def test_invalid_reply_to(self): event = Event.objects.get(title='Test event') discussion = self._create_discussion(event) jay = User.objects.create(username='******', email='*****@*****.**') bob = User.objects.create(username='******', email='*****@*****.**') discussion.moderators.add(jay) Comment.objects.create( event=event, user=bob, comment='Bla bla', status=Comment.STATUS_APPROVED ) jay.set_password('secret') jay.save() assert self.client.login(username='******', password='******') # post a reply url = reverse('comments:event_data', args=(event.pk,)) response = self.client.post(url, { 'comment': 'I think this', 'reply_to': '999999999', }) eq_(response.status_code, 400)
def edit(request, slug): """Edit an existing badge""" badge = get_object_or_404(Badge, slug=slug) if not badge.allows_edit_by(request.user): return HttpResponseForbidden() if request.method != "POST": form = BadgeEditForm(instance=badge) else: form = BadgeEditForm(request.POST, request.FILES, instance=badge) if form.is_valid(): new_sub = form.save(commit=False) new_sub.save() form.save_m2m() return HttpResponseRedirect( reverse('badger.views.detail', args=(new_sub.slug, ))) return render_to_response('%s/badge_edit.html' % bsettings.TEMPLATE_BASE, dict( badge=badge, form=form, ), context_instance=RequestContext(request))
def test_url_transforms(self): url = reverse('manage:url_transforms') response = self.client.get(url) eq_(response.status_code, 200) def quote(x): return x.replace("'", ''') ok_(quote("{{ password('foo') }}") in response.content) # now with some matchers in there match = URLMatch.objects.create( name="Secure Things", string='secure' ) URLTransform.objects.create( match=match, find='^secure', replace_with='insecure' ) response = self.client.get(url) eq_(response.status_code, 200) ok_('Secure Things' in response.content)
def test_disallowed_badge_award(self): """User should not be able to POST an award to a badge for which the user hasn't got permission to do so""" user = self._get_user(username="******", email="*****@*****.**") badge = Badge(creator=user, title="Hey you badge", description="Another test", unique=True) badge.save() awards_url = reverse('badger.views.awards_list', args=(self.badge.slug, )) data = dict(emails=[ '*****@*****.**', ]) resp = self.client.post(awards_url, json.dumps(data), content_type='application/json', HTTP_AUTHORIZATION=self.basic_auth) ok_(403, resp.status_code)
def test_search_and_suggest_channels(self): url = reverse('search:home') event = Event.objects.get(title='Test event') channel = Channel.objects.create(name='Grow Mozilla') event.channels.add(channel) response = self.client.get(url, {'q': 'grow mozilla'}) eq_(response.status_code, 200) # because neither title or description contains this ok_('Nothing found' in response.content) channel_search_url = ( url + '?q=%s' % urllib.quote_plus('channel: Grow Mozilla') ) ok_(channel_search_url in response.content) # See https://bugzilla.mozilla.org/show_bug.cgi?id=1072985 Channel.objects.create(name='Rust', slug='rust') channel_search_url = ( url + '?q=%s' % urllib.quote_plus('y channel: Rust') ) response = self.client.get(url, {'q': 'rusty'}) eq_(response.status_code, 200) ok_(channel_search_url not in response.content)
def test_event_feed(self): event = Event.objects.get(title='Test event') start_time = event.start_time start_time = start_time.replace(year=2014) start_time = start_time.replace(month=9) start_time = start_time.replace(day=13) event.start_time = start_time event.save() self._attach_file(event, self.main_image) url = reverse('roku:event_feed', args=(event.id, )) response = self.client.get(url) eq_(response.status_code, 200) event = Event.objects.get(title='Test event') ok_(event.title not in response.content) vidly = Template.objects.create(name="Vid.ly Test", content="test") event.template = vidly event.template_environment = {'tag': 'xyz123'} event.save() response = self.client.get(url) eq_(response.status_code, 200) ok_('%s - Sep 13 2014' % event.title in response.content)
def test_sidebar_static_content(self): # create some flat pages FlatPage.objects.create(url='sidebar_top_main', content='<p>Sidebar Top Main</p>') FlatPage.objects.create(url='sidebar_bottom_main', content='<p>Sidebar Bottom Main</p>') FlatPage.objects.create(url='sidebar_top_testing', content='<p>Sidebar Top Testing</p>') FlatPage.objects.create(url='sidebar_bottom_testing', content='<p>Sidebar Bottom Testing</p>') response = self.client.get('/') ok_('<p>Sidebar Top Main</p>' in response.content) ok_('<p>Sidebar Bottom Main</p>' in response.content) ok_('<p>Sidebar Top Testing</p>' not in response.content) ok_('<p>Sidebar Bottom Testing</p>' not in response.content) url = reverse('main:home_channels', args=('testing', )) response = self.client.get(url) ok_('<p>Sidebar Top Main</p>' not in response.content) ok_('<p>Sidebar Bottom Main</p>' not in response.content) ok_('<p>Sidebar Top Testing</p>' in response.content) ok_('<p>Sidebar Bottom Testing</p>' in response.content)
def invite_someone(self, email): """ This method will invite a user. This will verify that an email with link has been sent. """ # Send an invite. url = reverse('invite') d = dict(recipient=email) r = self.mozillian_client.post(url, d, follow=True) eq_(r.status_code, 200) assert ('%s has been invited to Mozillians.' % email in pq(r.content)('div#main p').text()) # See that the email was sent. eq_(len(mail.outbox), 1) i = Invite.objects.get() invite_url = i.get_url() assert '*****@*****.**' in mail.outbox[0].from_email assert invite_url in mail.outbox[0].body, "No link in email." return i
def test_logged_search_not_empty_searches(self): url = reverse('search:home') response = self.client.get(url, {'q': ''}) eq_(response.status_code, 200) ok_('Nothing found' not in response.content) ok_(not LoggedSearch.objects.all()) # or something too short response = self.client.get(url, {'q': '1'}) eq_(response.status_code, 200) ok_('Too short' in response.content) ok_(not LoggedSearch.objects.all()) response = self.client.get(url, {'q': ' ' * 10}) eq_(response.status_code, 200) ok_('Nothing found' not in response.content) ok_(not LoggedSearch.objects.all()) # but search by channel or tag without a wildcard should log response = self.client.get(url, {'q': 'channel: Foo'}) eq_(response.status_code, 200) ok_('Nothing found' in response.content) ok_(LoggedSearch.objects.all())
def test_vidly_media_status(self, p_urlopen): def mocked_urlopen(request): return StringIO(SAMPLE_XML.strip()) p_urlopen.side_effect = mocked_urlopen event = Event.objects.get(title='Test event') url = reverse('manage:vidly_media_status') response = self.client.get(url) eq_(response.status_code, 400) event.template = Template.objects.create(name='Vid.ly Something', content='<iframe>') event.template_environment = {'tag': 'abc123'} event.save() response = self.client.get(url, {'id': 9999}) eq_(response.status_code, 404) response = self.client.get(url, {'id': event.pk}) eq_(response.status_code, 200) data = json.loads(response.content) eq_(data['status'], 'Finished')
def test_string_split_works_properly(self): """Ensure groups are saved correctly from a comma-delimited string. """ profile = self.pending.get_profile() profile.groups.clear() assert not profile.groups.all(), ( 'User has no groups at beginning of test.') data = self.data_privacy_fields data.update(dict(full_name='McAwesomepants', country='pl', groups='Awesome,,foo bar, Bar,g ')) self.pending_client.post(reverse('profile.edit'), data, follow=True) eq_(4, profile.groups.count(), 'User should have four groups.') assert profile.groups.get(name='foo bar'), ( 'Group should contain spaces.') for g in profile.groups.all(): assert not g.name.startswith(u' '), ( 'Group should not start with a space.') assert not g.name.endswith(u' '), ( 'Group should not end with a space.')
def test_remove_tag_edit(self): User.objects.create_user('r', '*****@*****.**', 'secret') assert self.client.login(username='******', password='******') tag = Tag.objects.create(name='Cake') event = Event.objects.get(title='Test event') event.tags.add(tag) url = reverse('main:too_few_tags') response = self.client.post(url, { 'tags': ',Compilers , ', 'event_id': event.id }) eq_(response.status_code, 302) # it shouldn't make a new tag for "CAKE" eq_(sorted(x.name for x in Tag.objects.all()), ['Cake', 'Compilers']) event = Event.objects.get(id=event.id) eq_(sorted(x.name for x in event.tags.all()), ['Compilers']) base_revision, revision = (EventRevision.objects.filter( event=event).order_by('created')) eq_(sorted(x.name for x in base_revision.tags.all()), ['Cake']) eq_(sorted(x.name for x in revision.tags.all()), ['Compilers'])
def edit_profile(request): profile = request.user.get_profile() user_groups = stringify_groups(profile.groups.all().order_by('name')) if request.method == 'POST': form = forms.ProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save(request) return redirect(reverse('profile', args=[request.user.username])) else: initial = dict(first_name=request.user.first_name, last_name=request.user.last_name, bio=profile.bio, website=profile.website, irc_nickname=profile.ircname, groups=user_groups) form = forms.ProfileForm(instance=profile, initial=initial) # When changing this keep in mind that the same view is used for # user.register. d = dict(form=form, mode='edit', user_groups=user_groups, profile=profile) return render(request, 'phonebook/edit_profile.html', d)
def redirect(to, permanent=False, anchor=None, **kwargs): """ Returns a redirect response by applying funfactory's locale-aware reverse to the given string. Pass in permanent=True to return a permanent redirect. All other keyword arguments are passed to reverse. """ if permanent: redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect try: url = reverse(to, **kwargs) except NoReverseMatch: # Assume to is a url url = to if anchor: url = '#'.join([url, anchor]) return redirect_class(url)
def invite(request): if request.method == 'POST': f = forms.InviteForm(request.POST) if f.is_valid(): ldap = UserSession.connect(request) unique_id = request.user.unique_id try: person = ldap.get_by_unique_id(unique_id, use_master=True) except NO_SUCH_PERSON: log.info('profile_uid Sending 404 for [%s]' % unique_id) raise Http404 invite = f.save(commit=False) invite.inviter = request.user.unique_id invite.save() invite.send(sender=person) return HttpResponseRedirect(reverse(invited, args=[invite.id])) else: f = forms.InviteForm() data = dict(form=f, foo='bar') return render(request, 'phonebook/invite.html', data)
def test_errored(self, p_urlopen): def mocked_urlopen(request): xml = SAMPLE_XML.replace( '<Status>Finished</Status>', '<Status>Error</Status>', ) return StringIO(xml.strip()) p_urlopen.side_effect = mocked_urlopen event = Event.objects.get(title='Test event') vidly_template = Template.objects.create(name='Vid.ly Test') event.template = vidly_template event.template_environment = {'tag': 'abc123'} event.save() archive(event) sent_email = mail.outbox[-1] eq_(sent_email.to, [x[1] for x in settings.ADMINS]) ok_('Unable to archive event' in sent_email.subject) ok_('abc123' in sent_email.subject) ok_(reverse('manage:event_edit', args=(event.pk,)) in sent_email.body)
def expire_page_cache(path, key_prefix=None): # pass the path through funfactory resolver in order to get locale resolved_path = resolve(path) path_with_locale = urlresolvers.reverse( resolved_path.func, args = resolved_path.args, kwargs = resolved_path.kwargs ) try: language = urlresolvers.split_path(path_with_locale)[0].lower() except: language = None # get cache key, expire if the cached item exists key = get_url_cache_key( path_with_locale, language=language, key_prefix=key_prefix ) if key: if cache.get(key): cache.set(key, None, 0) return True return False
def test_view_revision_change_on_recruitmentmessage(self): event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) # base revision EventRevision.objects.create_from_event(event) user = User.objects.create_user('bob', '*****@*****.**', 'secret') user_revision = EventRevision.objects.create_from_event(event, user=user) msg1 = RecruitmentMessage.objects.create( text='Web Developer', url='http://careers.mozilla.com/123', active=True) user_revision.recruitmentmessage = msg1 user_revision.save() # view the change url = reverse('main:event_change', args=(event.slug, user_revision.pk)) self._login() response = self.client.get(url) eq_(response.status_code, 200) ok_(msg1.text in response.content)
def customize(request, banner_pk=None): banner = get_object_or_404(Banner, pk=banner_pk) # Create a new banner form = BannerForm(request.POST or None) if request.method == 'POST' and form.is_valid(): image = form.cleaned_data['image'] instance, created = BannerInstance.objects.get_or_create( badge=banner, user=request.user, image=image) return redirect('my_badges', anchor='banner_%s' % instance.pk) back_href = reverse('badges.new.step2', kwargs={'subcategory_pk': banner.subcategory.pk}) banner_images = BannerImage.objects.customize_values(banner=banner) return dashboard( request, 'banners/customize.html', { 'back_href': back_href, 'banner': banner, 'banner_images': json.dumps(banner_images), 'form': form, 'subcategory': banner.subcategory })
def make_row(visitor): row = { 'id': visitor.pk, 'created': format_date(visitor.created), 'created_iso': visitor.created.isoformat(), 'modified_iso': visitor.modified.isoformat(), 'job_title': visitor.job_title, 'name': visitor.get_name(formal=True), 'thumbnail': None, 'visiting': visitor.visiting, 'company': visitor.company, } if visitor.picture and os.path.isfile(visitor.picture.path): thumbnail = get_thumbnail(visitor.picture, thumbnail_geometry) row['thumbnail'] = { 'url': thumbnail.url, 'width': thumbnail.width, 'height': thumbnail.height, } row['picture_url'] = ( reverse('main:log_entry_picture', args=(visitor.pk, )) + '?width=600&height=400') return row
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'] = [ 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'firefox-tips', u'beta', u'mozilla-and-you'], newsletters_in_order)
def test_unrelated_privacy(self): event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) # events with different privacies and logged in other = Event.objects.create( title='Happiness event', description='bla bla', status=event.status, start_time=event.start_time, archive_time=event.archive_time, privacy=Event.PRIVACY_COMPANY, placeholder_img=event.placeholder_img, ) tag1 = Tag.objects.create(name='SomeTag') event.tags.add(tag1) other.tags.add(tag1) related.index(all=True) self._login() url = reverse('main:related_content', args=(event.slug, )) response = self.client.get(url) ok_('Hapiness event' not in response.content)
def test_issue_multiple_awards(self): """Multiple emails can be submitted at once to issue awards""" # Build creator user and badge creator = self._get_user(username="******", email="*****@*****.**") b1 = Badge.objects.create(creator=creator, title="Badge to defer") # Build future awardees user1 = self._get_user(username="******", email="*****@*****.**") user2 = self._get_user(username="******", email="*****@*****.**") user3 = self._get_user(username="******", email="*****@*****.**") user4_email = '*****@*****.**' # Login as the badge creator, prepare to award... self.client.login(username="******", password="******") url = reverse('badger.views.award_badge', args=(b1.slug,)) r = self.client.get(url, follow=True) eq_(200, r.status_code) # Make sure the expected parts appear in the form. doc = pq(r.content) form = doc('form#award_badge') eq_(1, form.length) eq_(1, form.find('*[name=emails]').length) eq_(1, form.find('input.submit,button.submit').length) # Post a list of emails with a variety of separators. r = self.client.post(url, dict( emails=("%s,%s\n%s %s" % (user1.email, user2.email, user3.email, user4_email)), ), follow=False) # Ensure that the known users received awards and the unknown user got # a deferred award. ok_(b1.is_awarded_to(user1)) ok_(b1.is_awarded_to(user2)) ok_(b1.is_awarded_to(user3)) eq_(1, DeferredAward.objects.filter(email=user4_email).count())
def test_channel_feed(self): main_channel = Channel.objects.get(slug=settings.DEFAULT_CHANNEL_SLUG) main_url = reverse('roku:channel_feed', args=(main_channel.slug,)) response = self.client.get(main_url) eq_(response.status_code, 200) event = Event.objects.get(title='Test event') self._attach_file(event, self.main_image) ok_(event.title not in response.content) vidly = Template.objects.create( name="Vid.ly Test", content="test" ) event.template = vidly event.template_environment = {'tag': 'xyz123'} event.save() response = self.client.get(main_url) eq_(response.status_code, 200) ok_(event.title in response.content) # if the *needs* approval, it shouldn't appear app = Approval.objects.create(event=event) response = self.client.get(main_url) eq_(response.status_code, 200) ok_(event.title not in response.content) app.processed = True app.save() response = self.client.get(main_url) eq_(response.status_code, 200) ok_(event.title not in response.content) app.approved = True app.save() response = self.client.get(main_url) eq_(response.status_code, 200) ok_(event.title in response.content)