def test_datetime(self): """Expects datetime format.""" value_test = datetime.fromordinal(733900) value_expected = format_datetime(value_test, locale=u'en_US') value_returned = datetimeformat(self.context, value_test, format='datetime') eq_(pq(value_returned)('time').text(), value_expected)
def test_zone_url_ends_with_slash(self): """Ensure urls only rewrite with a '/' at the end of url_root bug 1189596 """ zone_url_root = 'Firéfox' zone_root_content = 'This is the Firéfox zone' root_rev = revision(title='Firéfox', slug='Mozilla/Firéfox', content=zone_root_content, is_approved=True, save=True) root_doc = root_rev.document root_zone = DocumentZone(document=root_doc) root_zone.url_root = zone_url_root root_zone.save() none_zone_rev = revision(title='Firéfox for iOS', slug='Mozilla/Firéfox_for_iOS', content='Page outside zone with same prefix', is_approved=True, save=True) non_zone_doc = none_zone_rev.document non_zone_doc.save() url = '/en-US/docs/%s' % non_zone_doc.slug response = self.client.get(url, follow=False) eq_(200, response.status_code)
def test_persona_signin_captcha(self): persona_signup_email = '*****@*****.**' persona_signup_username = '******' with mock.patch('requests.post') as requests_mock: requests_mock.return_value.json.return_value = { 'status': 'okay', 'email': persona_signup_email, } self.client.post(reverse('persona_login'), follow=True) data = {'website': '', 'username': persona_signup_username, 'email': persona_signup_email, 'terms': True, 'g-recaptcha-response': 'FAILED'} signup_url = reverse('socialaccount_signup', locale=settings.WIKI_DEFAULT_LANGUAGE) with mock.patch('captcha.client.request') as request_mock: request_mock.return_value.read.return_value = '{"success": null}' response = self.client.post(signup_url, data=data, follow=True) eq_(response.status_code, 200) eq_(response.context['form'].errors, {'captcha': [u'Incorrect, please try again.']})
def test_logged_in_argument(self): request = self.rf.get('/foo') request.user = self.user_model.objects.get(username='******') view = logout_required('/bar')(simple_view) response = view(request) eq_(302, response.status_code) eq_('/bar', response['location'])
def test_locale_timezone_fields(self): """We've added locale and timezone fields. Verify defaults.""" user = self.user_model.objects.get(username='******') ok_(hasattr(user, 'locale')) ok_(user.locale == 'en-US') ok_(hasattr(user, 'timezone')) eq_(user.timezone, 'US/Pacific')
def test_my_user_edit(self): u = self.user_model.objects.get(username='******') self.client.login(username=u.username, password=TESTUSER_PASSWORD) resp = self.client.get(reverse('users.my_edit_page')) eq_(302, resp.status_code) ok_(reverse('users.user_edit', args=(u.username,)) in resp['Location'])
def test_bug_709938_interests(self): testuser = self.user_model.objects.get(username='******') self.client.login(username=testuser.username, password=TESTUSER_PASSWORD) url = reverse('users.user_edit', args=(testuser.username,)) response = self.client.get(url, follow=True) doc = pq(response.content) test_tags = [u'science,Technology,paradox,knowledge,modeling,big data,' u'vector,meme,heuristics,harmony,mathesis universalis,' u'symmetry,mathematics,computer graphics,field,chemistry,' u'religion,astronomy,physics,biology,literature,' u'spirituality,Art,Philosophy,Psychology,Business,Music,' u'Computer Science'] form = self._get_current_form_field_values(doc) form['user-interests'] = test_tags response = self.client.post(url, form, follow=True) eq_(200, response.status_code) doc = pq(response.content) eq_(1, doc.find('ul.errorlist li').length) assert ('Ensure this value has at most 255 characters' in doc.find('ul.errorlist li').text())
def test_pre_social_login_matched_login(self): """ https://bugzil.la/1063830, happy path A user tries to sign in with GitHub, but their GitHub email matches an existing Persona-backed MDN account. They follow the prompt to login with Persona, and the accounts are connected. """ # Set up a GitHub SocialLogin in the session github_account = SocialAccount.objects.get(user__username='******') github_login = SocialLogin(account=github_account, user=github_account.user) request = self.rf.get('/') session = self.client.session session['sociallogin_provider'] = 'github' session['socialaccount_sociallogin'] = github_login.serialize() session.save() request.session = session # Set up an matching Persona SocialLogin for request persona_account = SocialAccount.objects.create( user=github_account.user, provider='persona', uid=github_account.user.email) persona_login = SocialLogin(account=persona_account) # Verify the social_login receiver over-writes the provider # stored in the session self.adapter.pre_social_login(request, persona_login) session = request.session eq_(session['sociallogin_provider'], 'persona')
def test_main_view(self): response = self.client.get(reverse('dashboards.revisions', locale='en-US')) eq_(200, response.status_code) ok_('text/html' in response['Content-Type']) ok_('dashboards/revisions.html' in [template.name for template in response.templates])
def test_pre_social_login_same_provider(self): """ pre_social_login passes if existing provider is the same. I'm not sure what the real-world counterpart of this is. Logging in with a different GitHub account? Needed for branch coverage. """ # Set up a GitHub SocialLogin in the session github_account = SocialAccount.objects.get(user__username='******') github_login = SocialLogin(account=github_account, user=github_account.user) request = self.rf.get('/') session = self.client.session session['sociallogin_provider'] = 'github' session['socialaccount_sociallogin'] = github_login.serialize() session.save() request.session = session # Set up an un-matching GitHub SocialLogin for request github2_account = SocialAccount(user=self.user_model(), provider='github', uid=github_account.uid + '2') github2_login = SocialLogin(account=github2_account) self.adapter.pre_social_login(request, github2_login) eq_(request.session['sociallogin_provider'], 'github')
def test_pre_social_login_error_for_unmatched_login(self): """ https://bugzil.la/1063830 """ # Set up a GitHub SocialLogin in the session github_account = SocialAccount.objects.get(user__username='******') github_login = SocialLogin(account=github_account, user=github_account.user) request = self.rf.get('/') session = self.client.session session['socialaccount_sociallogin'] = github_login.serialize() session.save() request.session = session messages = self.get_messages(request) # Set up an un-matching Persona SocialLogin for request persona_account = SocialAccount(user=self.user_model(), provider='persona', uid='*****@*****.**') persona_login = SocialLogin(account=persona_account) self.assertRaises(ImmediateHttpResponse, self.adapter.pre_social_login, request, persona_login) queued_messages = list(messages) eq_(len(queued_messages), 1) eq_(django_messages.ERROR, queued_messages[0].level)
def test_invalid_document_form(self): """Make sure we handle invalid document form without a 500.""" translate_uri = self._translate_uri() data = _translation_data() data['slug'] = '' # Invalid slug response = self.client.post(translate_uri, data) eq_(200, response.status_code)
def _test_form_maintains_based_on_rev(client, doc, view, post_data, trans_lang=None, locale=None): """Confirm that the based_on value set in the revision created by an edit or translate form is the current_revision of the document as of when the form was first loaded, even if other revisions have been approved in the meantime.""" if trans_lang: translate_path = doc.slug uri = urllib.quote(reverse('wiki.translate', locale=trans_lang, args=[translate_path])) else: uri = reverse(view, locale=locale, args=[doc.slug]) response = client.get(uri) orig_rev = doc.current_revision eq_(orig_rev.id, int(pq(response.content)('input[name=based_on]').attr('value'))) # While Fred is editing the above, Martha approves a new rev: martha_rev = revision(document=doc) martha_rev.is_approved = True martha_rev.save() # Then Fred saves his edit: post_data_copy = {'based_on': orig_rev.id, 'slug': orig_rev.slug} post_data_copy.update(post_data) # Don't mutate arg. response = client.post(uri, data=post_data_copy) ok_(response.status_code in (200, 302)) fred_rev = Revision.objects.all().order_by('-id')[0] eq_(orig_rev, fred_rev.based_on)
def test_bad_parameters(self): """Ensure badly-formed revision parameters do not cause errors""" url = reverse('wiki.compare_revisions', args=[self.document.slug]) query = {'from': '1e309', 'to': u'1e309'} url = urlparams(url, **query) response = self.client.get(url) eq_(404, response.status_code)
def test_compare_revisions_invalid_from_int(self): """Provide invalid 'from' int for revision ids.""" url = reverse('wiki.compare_revisions', args=[self.document.slug]) query = {'from': 'invalid', 'to': ''} url = urlparams(url, **query) response = self.client.get(url) eq_(404, response.status_code)
def test_new_document_form_defaults(self): """The new document form should have all all 'Relevant to' options checked by default.""" self.client.login(username='******', password='******') response = self.client.get(reverse('wiki.create')) doc = pq(response.content) eq_("Name Your Article", doc('input#id_title').attr('placeholder'))
def test_new_revision_GET_logged_out(self): """Creating a revision without being logged in redirects to login page. """ self.client.logout() response = self.client.get(reverse('wiki.edit', args=[self.d.slug])) eq_(302, response.status_code)
def test_mail_handler(self): self.logger.handlers = [AdminEmailHandler()] response = self.client.get(self.suspicous_path) eq_(response.status_code, 400) eq_(1, len(mail.outbox)) ok_('*****@*****.**' in mail.outbox[0].to) ok_(self.suspicous_path in mail.outbox[0].body)
def test_new_document_GET_with_perm(self): """HTTP GET to new document URL renders the form.""" self.client.login(username='******', password='******') response = self.client.get(reverse('wiki.create')) eq_(200, response.status_code) doc = pq(response.content) eq_(1, len(doc('form#wiki-page-edit input[name="title"]')))
def test_user_revisions_in_one_click_page_template(self): """The user's revisions show up in the ban and cleanup template.""" # Create 3 revisions for testuser, titled 'Revision 1', 'Revision 2'... revisions_expected = self.create_revisions( num=3, creator=self.testuser, document=self.document) self.client.login(username='******', password='******') ban_url = reverse('users.ban_user_and_cleanup', kwargs={'user_id': self.testuser.id}) resp = self.client.get(ban_url, follow=True) eq_(200, resp.status_code) page = pq(resp.content) revisions_found = page.find('.dashboard-row') revisions_found_text = '' for rev in revisions_found: revisions_found_text += rev.text_content() eq_(len(revisions_found), len(revisions_expected)) # The title for each of the created revisions shows up in the template for revision in revisions_expected: ok_(revision.title in revisions_found_text) # The original revision created by the admin user is not in the template ok_(self.original_revision.title not in revisions_found_text)
def test_user_revisions_in_summary_page_template(self): """The user's revisions show up in ban and cleanup summary template.""" # Create 3 revisions for self.testuser, titled 'Revision 1', 'Revision 2'... revisions_expected = self.create_revisions( num=3, document=self.document, creator=self.testuser) self.client.login(username='******', password='******') ban_url = reverse('users.ban_user_and_cleanup_summary', kwargs={'user_id': self.testuser.id}) full_ban_url = self.client.get(ban_url)['Location'] resp = self.client.post(full_ban_url) eq_(200, resp.status_code) page = pq(resp.content) revisions_reverted = page.find('#revisions-reverted li') revisions_reverted_text = '' for rev in revisions_reverted: revisions_reverted_text += rev.text_content() eq_(len(revisions_reverted), len(revisions_expected)) # The title for each of the created revisions shows up in the template for revision in revisions_expected: ok_(revision.title in revisions_reverted_text) # The title for the original revision is not in the template ok_(self.original_revision.title not in revisions_reverted_text)
def test_ignore_heading_section_replace(self): doc_src = """ <h1 id="s1">Head 1</h1> <p>test</p> <p>test</p> <h1 id="s2">Head 2</h1> <p>test</p> <p>test</p> <h1 id="s3">Head 3</h1> <p>test</p> <p>test</p> """ replace_src = """ <p>replacement worked yay hooray</p> """ expected = """ <h1 id="s1">Head 1</h1> <p>test</p> <p>test</p> <h1 id="s2">Head 2</h1> <p>replacement worked yay hooray</p> <h1 id="s3">Head 3</h1> <p>test</p> <p>test</p> """ result = (kuma.wiki.content .parse(doc_src) .replaceSection(id="s2", replace_src=replace_src, ignore_heading=True) .serialize()) eq_(normalize_html(expected), normalize_html(result))
def test_generate_toc_h2(self): doc_src = """ <h2 id="HTML">HTML</h2> <h3 id="HTML5_canvas_element">HTML5 <code>canvas</code> element</h3> <h2 id="JavaScript">JavaScript</h2> JavaScript is awesome. <h3 id="WebGL">WebGL</h3> <h3 id="Audio">Audio</h3> <h4 id="Audio-API">Audio API</h4> <h2 id="CSS">CSS</h2> <h4 id="CSS_transforms">CSS transforms</h4> <h3 id="Gradients">Gradients</h3> <h4 id="Scaling_backgrounds">Scaling backgrounds</h4> """ expected = """ <li><a rel="internal" href="#HTML">HTML</a> </li> <li><a rel="internal" href="#JavaScript">JavaScript</a> </li> <li><a rel="internal" href="#CSS">CSS</a> </li> """ result = (kuma.wiki.content .parse(doc_src) .filter(H2TOCFilter).serialize()) eq_(normalize_html(expected), normalize_html(result))
def test_section_edit_links(self): doc_src = """ <h1 id="s1">Head 1</h1> <p>test</p> <p>test</p> <h2 id="s2">Head 2</h2> <p>test</p> <p>test</p> <h3 id="s3">Head 3</h3> <p>test</p> <p>test</p> """ expected = """ <h1 id="s1"><a class="edit-section" data-section-id="s1" data-section-src-url="/en-US/docs/some-slug?raw=true&section=s1" href="/en-US/docs/some-slug$edit?section=s1&edit_links=true" title="Edit section">Edit</a>Head 1</h1> <p>test</p> <p>test</p> <h2 id="s2"><a class="edit-section" data-section-id="s2" data-section-src-url="/en-US/docs/some-slug?raw=true&section=s2" href="/en-US/docs/some-slug$edit?section=s2&edit_links=true" title="Edit section">Edit</a>Head 2</h2> <p>test</p> <p>test</p> <h3 id="s3"><a class="edit-section" data-section-id="s3" data-section-src-url="/en-US/docs/some-slug?raw=true&section=s3" href="/en-US/docs/some-slug$edit?section=s3&edit_links=true" title="Edit section">Edit</a>Head 3</h3> <p>test</p> <p>test</p> """ result = (kuma.wiki.content .parse(doc_src) .injectSectionEditingLinks('some-slug', 'en-US') .serialize()) eq_(normalize_html(expected), normalize_html(result))
def test_code_syntax_conversion(self): doc_src = """ <h2>Some JavaScript</h2>: <pre class="deki-transform" function="syntax.JavaScript"> function foo(){ alert("bar"); } </pre> <pre>Some CSS:</pre> <pre class="dek-trans" function="syntax.CSS"> .dek-trans { color: red; } </pre> """ expected = """ <h2>Some JavaScript</h2>: <pre class="brush: js"> function foo(){ alert("bar"); } </pre> <pre>Some CSS:</pre> <pre class="brush: css"> .dek-trans { color: red; } </pre> """ result = (kuma.wiki.content .parse(doc_src) .filter(CodeSyntaxFilter).serialize()) eq_(normalize_html(expected), normalize_html(result))
def test_keep_markup(self): content = """ <h2 id="Summary">Summary</h2> <p>The <strong>Document Object Model </strong> (<strong>DOM</strong>) is an API for <a href="/en-US/docs/HTML" title="en-US/docs/HTML">HTML</a> and <a href="/en-US/docs/XML" title="en-US/docs/XML">XML</a> documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as <a href="/en-US/docs/JavaScript" title="https://developer.mozilla.org/en-US/docs/JavaScript"> JavaScript</a>.</span></p> """ expected = """ The <strong>Document Object Model </strong> (<strong>DOM</strong>) is an API for <a href="/en-US/docs/HTML" title="en-US/docs/HTML">HTML</a> and <a href="/en-US/docs/XML" title="en-US/docs/XML">XML</a> documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as <a href="/en-US/docs/JavaScript" title="https://developer.mozilla.org/en-US/docs/JavaScript"> JavaScript</a>.</span> """ eq_(normalize_html(expected), normalize_html(get_seo_description(content, 'en-US', False)))
def test_multilevel_implicit_section_extract(self): doc_src = """ <p>test</p> <h1 id="s4">Head 4</h1> <p>test</p> <p>test</p> <h2 id="s4-1">Head 4-1</h2> <p>test</p> <p>test</p> <h3 id="s4-2">Head 4-1-1</h3> <p>test</p> <p>test</p> <h1 id="s4-next">Head</h1> <p>test</p> """ expected = """ <h1 id="s4">Head 4</h1> <p>test</p> <p>test</p> <h2 id="s4-1">Head 4-1</h1> <p>test</p> <p>test</p> <h3 id="s4-2">Head 4-1-1</h1> <p>test</p> <p>test</p> """ result = (kuma.wiki.content.parse(doc_src) .extractSection(id="s4") .serialize()) eq_(normalize_html(expected), normalize_html(result))
def test_editor_safety_filter(self): """Markup that's hazardous for editing should be stripped""" doc_src = """ <svg><circle onload=confirm(3)> <h1 class="header1">Header One</h1> <p>test</p> <section> <h1 class="header2">Header Two</h1> <p>test</p> </section> <h1 class="header3">Header Three</h1> <p>test</p> """ expected_src = """ <svg><circle> <h1 class="header1">Header One</h1> <p>test</p> <section> <h1 class="header2">Header Two</h1> <p>test</p> </section> <h1 class="header3">Header Three</h1> <p>test</p> """ result_src = (kuma.wiki.content.parse(doc_src) .filterEditorSafety() .serialize()) eq_(normalize_html(expected_src), normalize_html(result_src))
def test_logged_in_default(self): """Active user login.""" request = self.rf.get('/foo') request.user = self.user_model.objects.get(username='******') view = login_required(simple_view) response = view(request) eq_(200, response.status_code)
def test_persona_form_present(self): """ When not authenticated, the Persona authentication components, with correct data attributes, are present in page contents, and the 'next' parameter is filled in. """ all_docs_url = reverse('wiki.all_documents', locale=settings.WIKI_DEFAULT_LANGUAGE) response = self.client.get(all_docs_url, follow=True) parsed = pq(response.content) request_info = '{"siteName": "%(siteName)s", "siteLogo": "%(siteLogo)s"}' % \ settings.SOCIALACCOUNT_PROVIDERS['persona']['REQUEST_PARAMETERS'] stub_attrs = ( ('data-csrf-token-url', reverse('persona_csrf_token')), ('data-request', request_info), ) auth_attrs = ( ('data-service', 'Persona'), ('data-next', all_docs_url), ) stub_persona_form = parsed.find('#_persona_login') ok_(len(stub_persona_form) > 0) for stub_attr in stub_attrs: ok_(stub_persona_form.attr(stub_attr[0])) eq_(stub_attr[1], stub_persona_form.attr(stub_attr[0])) auth_persona_form = parsed.find('.launch-persona-login') ok_(len(auth_persona_form) > 0) for auth_attr in auth_attrs: ok_(auth_persona_form.attr(auth_attr[0])) eq_(auth_attr[1], auth_persona_form.attr(auth_attr[0]))
def test_non_existent_fallback(self): """Respect user's preferences as much as possible.""" best = get_best_language('qaz-ZZ, fr-FR;q=0.5') eq_('fr', best)
def test_logged_in_admin(self): request = self.rf.get('/foo') request.user = self.user_model.objects.get(username='******') view = permission_required('perm')(simple_view) response = view(request) eq_(200, response.status_code)
def test_global_message(self): m = Message(message='Global', is_global=True, is_active=True, url='/') m.save() eq_(m.message, get_soapbox_messages('/')[0].message) eq_(m.message, get_soapbox_messages('/en-US/')[0].message)
def test_yesno(self): eq_('Yes', yesno(True)) eq_('No', yesno(False)) eq_('Yes', yesno(1)) eq_('No', yesno(0))
def test_json_helper(self): eq_('false', jsonencode(False)) eq_('{"foo": "bar"}', jsonencode({'foo': 'bar'}))
def test_url_root_internal_redirect(self): """Ensure document zone with URL root results in internal redirect""" url = '/en-US/{0!s}?raw'.format(self.zone_root) response = self.client.get(url, follow=False) eq_(200, response.status_code) eq_(self.zone_root_content, response.content) url = '/en-US/{0!s}/Middle/SubPage?raw'.format(self.zone_root) response = self.client.get(url, follow=False) eq_(200, response.status_code) eq_(self.sub_doc.html, response.content) self.root_zone.url_root = 'NewRoot' self.root_zone.save() url = '/en-US/{0!s}/Middle/SubPage?raw'.format('NewRoot') response = self.client.get(url, follow=False) eq_(200, response.status_code) eq_(self.sub_doc.html, response.content)
def test_blank_url_root(self): """Ensure a blank url_root does not trigger URL remap""" url = '/en-US/docs/{0!s}?raw=1'.format(self.other_doc.slug) response = self.client.get(url, follow=False) eq_(200, response.status_code)
def test_prefix_fallback(self): """No matches during the first pass. Fall back to prefix.""" best = get_best_language('fr-FR, de-DE;q=0.5') eq_('fr', best)
def test_non_existent(self): """If we don't have any matches, return false.""" best = get_best_language('qaz-ZZ, qaz;q=0.5') eq_(False, best)
def test_english_fallback(self): """Fall back to our canonical English locale, 'en-US'.""" best = get_best_language('en-GB, fr-FR;q=0.5') eq_('en-US', best)
def test_prefix_alias(self): """A generic request for Portuguese should go to 'pt-PT'.""" best = get_best_language('pt, fr;q=0.5') eq_('pt-PT', best)
def test_second_choice(self): """Respect the user's preferences during the first pass.""" best = get_best_language('fr-FR, de;q=0.5') eq_('de', best)
def test_english_alias(self): """Our canonical English locale is 'en-US'.""" best = get_best_language('en, fr;q=0.5') eq_('en-US', best)
def test_script_alias(self): """Our traditional Chinese locale is 'zh-TW'.""" best = get_best_language('zh-Hant, fr;q=0.5') eq_('zh-TW', best)
def test_exact_match_language(self): """Exact match of a locale with only a language subtag.""" best = get_best_language('fr, en-US;q=0.5') eq_('fr', best)
def test_overspecific_alias(self): """Our Irish locale is 'ga-IE'.""" best = get_best_language('ga, fr;q=0.5') eq_('ga-IE', best)
def test_new_key(self): data = {"description": "This is meant for a test app"} url = reverse('authkeys.new', locale='en-US') # Check out the creation page, look for the form. resp = self.client.get(url) eq_(200, resp.status_code) page = pq(resp.content) eq_(1, page.find('form.key').length) # We don't have this key yet, right? keys = Key.objects.filter(description=data['description']) eq_(0, keys.count()) # Okay, create it. resp = self.client.post(url, data, follow=False) eq_(200, resp.status_code) # We have the key now, right? keys = Key.objects.filter(description=data['description']) eq_(1, keys.count()) # Okay, and it should belong to the logged-in user key = keys[0] eq_(key.user, self.user) # Take a look at the description and key shown on the result page. page = pq(resp.content) ok_(data['description'], page.find('.key .description').text()) ok_(key.key, page.find('.key .key').text()) # Ensure the secret on the page checks out. secret = page.find('.key .secret').text() ok_(key.check_secret(secret))
def test_exact_match_region(self): """Exact match of a locale with language and region subtags.""" best = get_best_language('pt-BR, en-US;q=0.5') eq_('pt-BR', best)
def test_redirect_to_mozilla_org(self): url = '/en-US/events' response = self.client.get(url) eq_(302, response.status_code) eq_('https://mozilla.org/contribute/events', response['Location'])
def test_english_only(self): """Any way you slice it, this should be 'en-US'.""" best = get_best_language('en-US, en;q=0.5') eq_('en-US', best)
def test_list_files(self): list_files_url = reverse('attachments.list_files', locale=settings.WIKI_DEFAULT_LANGUAGE) resp = self.client.get(list_files_url) eq_(200, resp.status_code) ok_('All Files' in resp.content)
def test_no_mail_handler(self): self.logger.handlers = [logging.NullHandler()] response = self.client.get(self.suspicous_path) eq_(response.status_code, 400) eq_(0, len(mail.outbox))
def test_querystring(self): path = '/one/two?something' request = self.rf.get(path) eq_(next_url(request)['next_url'], path)
def test_edit_attachment(self): file_for_upload = make_test_file( content='I am a test file for editing.') post_data = { 'title': 'Test editing file', 'description': 'A test file for editing.', 'comment': 'Initial upload', 'file': file_for_upload, } resp = self.client.post(reverse('attachments.new_attachment'), data=post_data) tdir = tempfile.gettempdir() edited_file_for_upload = tempfile.NamedTemporaryFile(suffix=".txt", dir=tdir) edited_file_for_upload.write( 'I am a new version of the test file for editing.') edited_file_for_upload.seek(0) post_data = { 'title': 'Test editing file', 'description': 'A test file for editing.', 'comment': 'Second revision.', 'file': edited_file_for_upload, } attachment = Attachment.objects.get(title='Test editing file') resp = self.client.post(reverse('attachments.edit_attachment', kwargs={ 'attachment_id': attachment.id, }), data=post_data) eq_(302, resp.status_code) # Re-fetch because it's been updated. attachment = Attachment.objects.get(title='Test editing file') eq_(resp['Location'], 'http://testserver{0!s}'.format(attachment.get_absolute_url())) eq_(2, attachment.revisions.count()) rev = attachment.current_revision eq_('admin', rev.creator.username) eq_('Second revision.', rev.comment) ok_(rev.is_approved) url = attachment.get_file_url() resp = self.client.get(url, HTTP_HOST=settings.ATTACHMENT_HOST) eq_('text/plain', rev.mime_type) ok_('I am a new version of the test file for editing.' in resp.streaming_content)
def test_find_roots(self): """Ensure sub pages can find the content zone root""" root_rev = revision(title='ZoneRoot', slug='ZoneRoot', content='This is the Zone Root', is_approved=True, save=True) root_doc = root_rev.document middle_rev = revision(title='Zonemiddle', slug='Zonemiddle', content='This is the Zone middle', is_approved=True, save=True) middle_doc = middle_rev.document middle_doc.parent_topic = root_doc middle_doc.save() sub_rev = revision(title='SubPage', slug='SubPage', content='This is a subpage', is_approved=True, save=True) sub_doc = sub_rev.document sub_doc.parent_topic = middle_doc sub_doc.save() sub_sub_rev = revision(title='SubSubPage', slug='SubSubPage', content='This is a subsubpage', is_approved=True, save=True) sub_sub_doc = sub_sub_rev.document sub_sub_doc.parent_topic = sub_doc sub_sub_doc.save() other_rev = revision(title='otherPage', slug='otherPage', content='This is an otherpage', is_approved=True, save=True) other_doc = other_rev.document root_zone = DocumentZone(document=root_doc) root_zone.save() middle_zone = DocumentZone(document=middle_doc) middle_zone.save() eq_(self.get_zone_stack(root_doc)[0], root_zone) eq_(self.get_zone_stack(middle_doc)[0], middle_zone) eq_(self.get_zone_stack(sub_doc)[0], middle_zone) eq_(0, len(self.get_zone_stack(other_doc))) zone_stack = self.get_zone_stack(sub_sub_doc) eq_(zone_stack[0], middle_zone) eq_(zone_stack[1], root_zone)
def test_files_dict(self): doc = document(locale='en', slug='attachment-test-files-dict') doc.save() rev = revision(document=doc, is_approved=True) rev.save() test_file_1 = make_test_file( content='A file for testing the files dict') post_data = { 'title': 'Files dict test file', 'description': 'Files dict test file', 'comment': 'Initial upload', 'file': test_file_1, } add_url = urlparams(reverse('attachments.new_attachment'), document_id=doc.id) self.client.post(add_url, data=post_data) test_file_2 = make_test_file( content='Another file for testing the files dict') post_data = { 'title': 'Files dict test file 2', 'description': 'Files dict test file 2', 'comment': 'Initial upload', 'file': test_file_2, } self.client.post(add_url, data=post_data) doc = Document.objects.get(pk=doc.id) files_dict = doc.files_dict() file1 = files_dict[test_file_1.name.split('/')[-1]] eq_('admin', file1['attached_by']) eq_('Files dict test file', file1['description']) eq_('text/plain', file1['mime_type']) ok_(test_file_1.name.split('/')[-1] in file1['url']) file2 = files_dict[test_file_2.name.split('/')[-1]] eq_('admin', file2['attached_by']) eq_('Files dict test file 2', file2['description']) eq_('text/plain', file2['mime_type']) ok_(test_file_2.name.split('/')[-1] in file2['url'])
def test_tojson(self): eq_( tojson({'title': '<script>alert("Hi!")</script>'}), '{"title": "<script>alert("Hi!")</script>"}')
def test_basic(self): path = '/one/two' request = self.rf.get(path) eq_(next_url(request)['next_url'], path)
def test_user_edit(self): testuser = self.user_model.objects.get(username='******') url = reverse('users.user_detail', args=(testuser.username, )) response = self.client.get(url, follow=True) doc = pq(response.content) eq_(0, doc.find('#user-head .edit .button').length) self.client.login(username=testuser.username, password=TESTUSER_PASSWORD) url = reverse('users.user_detail', args=(testuser.username, )) response = self.client.get(url, follow=True) doc = pq(response.content) edit_button = doc.find('#user-head .user-buttons #edit-user') eq_(1, edit_button.length) url = edit_button.attr('href') response = self.client.get(url, follow=True) doc = pq(response.content) eq_(testuser.fullname, doc.find('#user-edit input[name="user-fullname"]').val()) eq_(testuser.title, doc.find('#user-edit input[name="user-title"]').val()) eq_(testuser.organization, doc.find('#user-edit input[name="user-organization"]').val()) eq_(testuser.location, doc.find('#user-edit input[name="user-location"]').val()) eq_(testuser.irc_nickname, doc.find('#user-edit input[name="user-irc_nickname"]').val()) new_attrs = { 'user-username': testuser.username, 'user-email': '*****@*****.**', 'user-fullname': "Another Name", 'user-title': "Another title", 'user-organization': "Another org", } response = self.client.post(url, new_attrs, follow=True) doc = pq(response.content) eq_(1, doc.find('#user-head').length) eq_(new_attrs['user-fullname'], doc.find('#user-head .fn').text()) eq_(new_attrs['user-title'], doc.find('#user-head .user-info .title').text()) eq_(new_attrs['user-organization'], doc.find('#user-head .user-info .org').text()) testuser = self.user_model.objects.get(username=testuser.username) eq_(new_attrs['user-fullname'], testuser.fullname) eq_(new_attrs['user-title'], testuser.title) eq_(new_attrs['user-organization'], testuser.organization)
def test_absolutify(self, get_current): get_current.return_value.domain = 'testserver' eq_(absolutify(''), 'https://testserver/') eq_(absolutify('/'), 'https://testserver/') eq_(absolutify('//'), 'https://testserver/') eq_(absolutify('/foo/bar'), 'https://testserver/foo/bar') eq_(absolutify('http://domain.com'), 'http://domain.com') site = Site(domain='otherserver') eq_(absolutify('/woo', site), 'https://otherserver/woo') eq_(absolutify('/woo?var=value'), 'https://testserver/woo?var=value') eq_(absolutify('/woo?var=value#fragment'), 'https://testserver/woo?var=value#fragment')