Пример #1
0
class EventsViewsTest(test_utils.TestCase):
    fixtures = ["devmo_calendar.json"]

    def setUp(self):
        self.client = LocalizingClient()
        devmo_calendar_reload()

    def test_events(self):
        url = reverse("devmo.views.events")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_events_map_flag(self):
        url = reverse("devmo.views.events")

        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_([], doc.find("#map_canvas"))
        ok_("maps.google.com" not in r.content)

        events_map_flag = Flag.objects.create(name="events_map", everyone=True)
        events_map_flag.save()

        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_(1, len(doc.find("#map_canvas")))
        ok_("maps.google.com" in r.content)
Пример #2
0
class HomeTests(test_utils.TestCase):
    def setUp(self):
        self.client = LocalizingClient()

    def test_social_promo(self):
        url = reverse('landing.views.home')

        aurora_promo, social_promo = get_promos(self.client, url)
        ok_(aurora_promo)
        ok_(not social_promo)

        Switch.objects.create(name="social_promo", active=True)

        aurora_promo, social_promo = get_promos(self.client, url)
        ok_(not aurora_promo)
        ok_(social_promo)

    def test_google_analytics(self):
        url = reverse('landing.views.home')

        constance.config.GOOGLE_ANALYTICS_ACCOUNT = ''
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        ok_('var _gaq' not in r.content)

        constance.config.GOOGLE_ANALYTICS_ACCOUNT = 'UA-99999999-9'
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        ok_('var _gaq' in r.content)
Пример #3
0
    def test_raw_with_editing_links_source(self):
        """The raw source for a document can be requested, with section editing
        links"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        d, r = doc_rev("""
            <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>
        """)
        expected = """
            <h1 id="s1"><a class="edit-section" data-section-id="s1" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s1" href="/en-US/docs/%(slug)s$edit?section=s1&amp;edit_links=true" title="Edit section">Edit</a>Head 1</h1>
            <p>test</p>
            <p>test</p>
            <h1 id="s2"><a class="edit-section" data-section-id="s2" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s2" href="/en-US/docs/%(slug)s$edit?section=s2&amp;edit_links=true" title="Edit section">Edit</a>Head 2</h1>
            <p>test</p>
            <p>test</p>
            <h1 id="s3"><a class="edit-section" data-section-id="s3" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s3" href="/en-US/docs/%(slug)s$edit?section=s3&amp;edit_links=true" title="Edit section">Edit</a>Head 3</h1>
            <p>test</p>
            <p>test</p>
        """ % {'slug': d.slug}
        response = client.get('%s?raw=true&edit_links=true' %
                              reverse('wiki.document', args=[d.slug]))
        eq_(normalize_html(expected), 
            normalize_html(response.content))
Пример #4
0
    def test_invalid_reserved_term_slug(self):
        """Slugs should not collide with reserved URL patterns"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()

        # TODO: This is info derived from urls.py, but unsure how to DRY it
        reserved_slugs = (
            'ckeditor_config.js',
            'watch-ready-for-review',
            'unwatch-ready-for-review',
            'watch-approved',
            'unwatch-approved',
            '.json',
            'new',
            'all',
            'preview-wiki-content',
            'category/10',
            'needs-review/technical',
            'needs-review/',
            'feeds/atom/all/',
            'feeds/atom/needs-review/technical',
            'feeds/atom/needs-review/',
            'tag/tasty-pie'
        )

        for term in reserved_slugs:
            data['title'] = 'invalid with %s' % term
            data['slug'] = term
            response = client.post(reverse('wiki.new_document'), data)
            self.assertContains(response, 'The slug provided is not valid.')
Пример #5
0
    def test_raw_section_source(self):
        """The raw source for a document section can be requested"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        d, r = doc_rev("""
            <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>
        """)
        expected = """
            <h1 id="s2">Head 2</h1>
            <p>test</p>
            <p>test</p>
        """
        response = client.get('%s?section=s2&raw=true' %
                              reverse('wiki.document', args=[d.slug]))
        eq_(normalize_html(expected), 
            normalize_html(response.content))
Пример #6
0
class ProfileViewsTest(TestCase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.old_debug = settings.DEBUG
        settings.DEBUG = True
        self.client = LocalizingClient()
        self.client.logout()

    def tearDown(self):
        settings.DEBUG = self.old_debug

    @attr('docs_activity')
    @attr('bug715923')
    @patch('devmo.models.UserDocsActivityFeed.fetch_user_feed')
    def test_bug715923_feed_parsing_errors(self, fetch_user_feed):
        fetch_user_feed.return_value = """
            THIS IS NOT EVEN XML, SO BROKEN
        """
        try:
            profile = UserProfile.objects.get(user__username='******')
            user = profile.user
            url = reverse('devmo.views.profile_view', args=(user.username, ))
            r = self.client.get(url, follow=True)
            pq(r.content)
        except Exception, e:
            raise e
            ok_(False, "There should be no exception %s" % e)
Пример #7
0
    def test_json_callback_validation(self):
        """Various json callbacks -- validation"""
        c = LocalizingClient()
        q = 'bookmarks'
        format = 'json'

        callbacks = (
            ('callback', 200),
            ('validCallback', 200),
            ('obj.method', 200),
            ('obj.someMethod', 200),
            ('arr[1]', 200),
            ('arr[12]', 200),
            ("alert('xss');foo", 400),
            ("eval('nastycode')", 400),
            ("someFunc()", 400),
            ('x', 200),
            ('x123', 200),
            ('$', 200),
            ('_func', 200),
            ('"></script><script>alert(\'xss\')</script>', 400),
            ('">', 400),
            ('var x=something;foo', 400),
            ('var x=', 400),
        )

        for callback, status in callbacks:
            response = c.get(reverse('search'), {
                'q': q,
                'format': format,
                'callback': callback,
            })
            eq_(response['Content-Type'], 'application/x-javascript')
            eq_(response.status_code, status)
Пример #8
0
class ReminderEmailTestCase(TestCase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.client = LocalizingClient()

    @mock.patch_object(Site.objects, 'get_current')
    def test_reminder_email(self, get_current):
        """Should send simple email reminder to user."""
        get_current.return_value.domain = 'dev.mo.org'

        response = self.client.post(reverse('users.send_email_reminder'),
                                    {'username': '******'},
                                    follow=True)
        eq_(200, response.status_code)
        eq_(1, len(mail.outbox))
        email = mail.outbox[0]
        assert email.subject.find('Email Address Reminder') == 0
        assert 'testuser' in email.body

    @mock.patch_object(Site.objects, 'get_current')
    def test_unknown_user_no_email_sent(self, get_current):
        """Should send simple email reminder to user."""
        get_current.return_value.domain = 'dev.mo.org'

        response = self.client.post(reverse('users.send_email_reminder'),
                                    {'username': '******'},
                                    follow=True)
        eq_(200, response.status_code)
        eq_(0, len(mail.outbox))
Пример #9
0
class ReminderEmailTestCase(TestCase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.client = LocalizingClient()

    @mock.patch_object(Site.objects, 'get_current')
    def test_reminder_email(self, get_current):
        """Should send simple email reminder to user."""
        get_current.return_value.domain = 'dev.mo.org'

        response = self.client.post(reverse('users.send_email_reminder'),
                                    {'username': '******'},
                                    follow=True)
        eq_(200, response.status_code)
        eq_(1, len(mail.outbox))
        email = mail.outbox[0]
        assert email.subject.find('Email Address Reminder') == 0
        assert 'testuser' in email.body

    @mock.patch_object(Site.objects, 'get_current')
    def test_unknown_user_no_email_sent(self, get_current):
        """Should send simple email reminder to user."""
        get_current.return_value.domain = 'dev.mo.org'

        response = self.client.post(reverse('users.send_email_reminder'),
                                    {'username': '******'},
                                    follow=True)
        eq_(200, response.status_code)
        eq_(0, len(mail.outbox))
Пример #10
0
    def test_raw_section_source(self):
        """The raw source for a document section can be requested"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        d, r = doc_rev("""
            <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>
        """)
        expected = """
            <h1 id="s2">Head 2</h1>
            <p>test</p>
            <p>test</p>
        """
        response = client.get('%s?section=s2&raw=true' %
                              reverse('wiki.document', args=[d.slug]))
        eq_(normalize_html(expected), normalize_html(response.content))
Пример #11
0
    def test_raw_with_editing_links_source(self):
        """The raw source for a document can be requested, with section editing
        links"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        d, r = doc_rev("""
            <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>
        """)
        expected = """
            <h1 id="s1"><a class="edit-section" data-section-id="s1" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s1" href="/en-US/docs/%(slug)s$edit?section=s1&amp;edit_links=true" title="Edit section">Edit</a>Head 1</h1>
            <p>test</p>
            <p>test</p>
            <h1 id="s2"><a class="edit-section" data-section-id="s2" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s2" href="/en-US/docs/%(slug)s$edit?section=s2&amp;edit_links=true" title="Edit section">Edit</a>Head 2</h1>
            <p>test</p>
            <p>test</p>
            <h1 id="s3"><a class="edit-section" data-section-id="s3" data-section-src-url="/en-US/docs/%(slug)s?raw=true&amp;section=s3" href="/en-US/docs/%(slug)s$edit?section=s3&amp;edit_links=true" title="Edit section">Edit</a>Head 3</h1>
            <p>test</p>
            <p>test</p>
        """ % {
            'slug': d.slug
        }
        response = client.get('%s?raw=true&edit_links=true' %
                              reverse('wiki.document', args=[d.slug]))
        eq_(normalize_html(expected), normalize_html(response.content))
Пример #12
0
class LandingViewsTest(test_utils.TestCase):
    fixtures = ["test_data.json"]

    def setUp(self):
        self.client = LocalizingClient()

    def test_home(self):
        url = reverse("landing.views.home")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

        doc = pq(r.content)
        dev_mdc_link = doc.find("a#dev-mdc-link")
        ok_(dev_mdc_link)

    def test_mozilla(self):
        url = reverse("landing.views.mozilla")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_web(self):
        url = reverse("landing.views.web")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_search(self):
        raise SkipTest("Search test disabled until we switch to kuma wiki")
        url = reverse("landing.views.search")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_promote_buttons(self):
        url = reverse("landing.views.promote_buttons")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
Пример #13
0
class EventsViewsTest(test_utils.TestCase):
    fixtures = ['devmo_calendar.json']

    def setUp(self):
        self.client = LocalizingClient()
        devmo_calendar_reload()

    def test_events(self):
        url = reverse('devmo.views.events')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_events_map_flag(self):
        url = reverse('devmo.views.events')

        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_([], doc.find('#map_canvas'))
        ok_("maps.google.com" not in r.content)

        events_map_flag = Flag.objects.create(name='events_map', everyone=True)
        events_map_flag.save()

        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_(1, len(doc.find('#map_canvas')))
        ok_("maps.google.com" in r.content)
Пример #14
0
class ProfileViewsTest(TestCase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.old_debug = settings.DEBUG
        settings.DEBUG = True
        self.client = LocalizingClient()
        self.client.logout()

    def tearDown(self):
        settings.DEBUG = self.old_debug

    @attr('docs_activity')
    @attr('bug715923')
    @patch('devmo.models.UserDocsActivityFeed.fetch_user_feed')
    def test_bug715923_feed_parsing_errors(self, fetch_user_feed):
        fetch_user_feed.return_value = """
            THIS IS NOT EVEN XML, SO BROKEN
        """
        try:
            profile = UserProfile.objects.get(user__username='******')
            user = profile.user
            url = reverse('devmo.views.profile_view',
                          args=(user.username,))
            r = self.client.get(url, follow=True)
            pq(r.content)
        except Exception, e:
            raise e
            ok_(False, "There should be no exception %s" % e)
Пример #15
0
    def test_json_callback_validation(self):
        """Various json callbacks -- validation"""
        c = LocalizingClient()
        q = 'bookmarks'
        format = 'json'

        callbacks = (
            ('callback', 200),
            ('validCallback', 200),
            ('obj.method', 200),
            ('obj.someMethod', 200),
            ('arr[1]', 200),
            ('arr[12]', 200),
            ("alert('xss');foo", 400),
            ("eval('nastycode')", 400),
            ("someFunc()", 400),
            ('x', 200),
            ('x123', 200),
            ('$', 200),
            ('_func', 200),
            ('"></script><script>alert(\'xss\')</script>', 400),
            ('">', 400),
            ('var x=something;foo', 400),
            ('var x=', 400),
        )

        for callback, status in callbacks:
            response = c.get(reverse('search'), {
                'q': q,
                'format': format,
                'callback': callback,
            })
            eq_(response['Content-Type'], 'application/x-javascript')
            eq_(response.status_code, status)
Пример #16
0
class AppsViewsTest(test_utils.TestCase):

    def setUp(self):
        self.client = LocalizingClient()

    @patch('landing.views.basket.subscribe')
    def test_apps_subscription(self, subscribe):
        subscribe.return_value = True
        url = reverse('landing.views.apps_newsletter')

        r = self.client.post(url,
                {'format': 'html',
                 'email': '*****@*****.**',
                 'agree': 'checked'},
            follow=True)
        eq_(200, r.status_code)
        # assert thank you message
        self.assertContains(r, 'Thank you')
        eq_(1, subscribe.call_count)

    @patch('landing.views.basket.subscribe')
    def test_apps_subscription_bad_values(self, subscribe):
        subscribe.return_value = True
        url = reverse('landing.views.apps_newsletter')
        r = self.client.post(url, {'format': 1, 'email': 'nope'})
        eq_(200, r.status_code)
        # assert error
        self.assertContains(r, 'Enter a valid e-mail address.')
        self.assertContains(r, 'Select a valid choice.')
        self.assertContains(r, 'You must agree to the privacy policy.')
Пример #17
0
class LandingViewsTest(test_utils.TestCase):
    fixtures = ['test_data.json', ]

    def setUp(self):
        self.client = LocalizingClient()

    def test_home(self):
        url = reverse('landing.views.home')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_mozilla(self):
        url = reverse('landing.views.mozilla')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_web(self):
        url = reverse('landing.views.web')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_search(self):
        raise SkipTest('Search test disabled until we switch to kuma wiki')
        url = reverse('landing.views.search')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_promote_buttons(self):
        url = reverse('landing.views.promote_buttons')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
Пример #18
0
class AppsViewsTest(test_utils.TestCase):
    def setUp(self):
        self.client = LocalizingClient()

    def test_apps_menu_item(self):
        url = reverse("landing.views.home")
        r = self.client.get(url)
        eq_(200, r.status_code)
        doc = pq(r.content)
        nav_sub_topics = doc.find("ul#nav-sub-topics")
        ok_(nav_sub_topics)
        apps_item = nav_sub_topics.find("li#nav-sub-apps")
        eq_("Apps", apps_item.text())

    def test_apps(self):
        url = reverse("landing.views.apps")
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        signup_form = doc.find("form.fm-subscribe")
        eq_(reverse("apps_subscription", locale="en-US"), signup_form.attr("action"))

    @patch("landing.views.basket.subscribe")
    def test_apps_subscription(self, subscribe):
        subscribe.return_value = True
        url = reverse("landing.views.apps_subscription")
        r = self.client.post(url, {"format": "html", "email": "*****@*****.**", "agree": "checked"}, follow=True)
        eq_(200, r.status_code)
        # assert thank you message
        self.assertContains(r, "Thank you")
        eq_(1, subscribe.call_count)

    @patch("landing.views.basket.subscribe")
    def test_apps_subscription_ajax(self, subscribe):
        subscribe.return_value = True
        url = reverse("landing.views.apps_subscription")
        r = self.client.post(
            url,
            {"format": "html", "email": "*****@*****.**", "agree": "checked"},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        eq_(200, r.status_code)
        # assert thank you message
        self.assertContains(r, "Thank you")
        self.assertNotContains(r, "<html")
        self.assertNotContains(r, "<head>")
        self.assertNotContains(r, "<title>")
        eq_(1, subscribe.call_count)

    @patch("landing.views.basket.subscribe")
    def test_apps_subscription_bad_values(self, subscribe):
        subscribe.return_value = True
        url = reverse("landing.views.apps_subscription")
        r = self.client.post(url, {"format": 1, "email": "nope"})
        eq_(200, r.status_code)
        # assert error
        self.assertContains(r, "Enter a valid e-mail address.")
        self.assertContains(r, "Select a valid choice.")
        self.assertContains(r, "You must agree to the privacy policy.")
Пример #19
0
 def test_json_format(self):
     """JSON without callback should return application/json"""
     c = LocalizingClient()
     response = c.get(reverse('search'), {
         'q': 'bookmarks',
         'format': 'json',
     })
     eq_(response['Content-Type'], 'application/json')
Пример #20
0
def test_breadcrumb():
    """Make sure breadcrumb links start with /."""
    c = LocalizingClient()
    response = c.get(reverse("search"))

    doc = pq(response.content)
    href = doc(".breadcrumbs a")[0]
    eq_("/", href.attrib["href"][0])
Пример #21
0
def test_breadcrumb():
    """Make sure breadcrumb links start with /."""
    c = LocalizingClient()
    response = c.get(reverse('search'))

    doc = pq(response.content)
    href = doc('.breadcrumbs a')[0]
    eq_('/', href.attrib['href'][0])
Пример #22
0
 def test_json_format(self):
     """JSON without callback should return application/json"""
     c = LocalizingClient()
     response = c.get(reverse('search'), {
         'q': 'bookmarks',
         'format': 'json',
     })
     eq_(response['Content-Type'], 'application/json')
Пример #23
0
def test_breadcrumb():
    """Make sure breadcrumb links start with /."""
    c = LocalizingClient()
    response = c.get(reverse('search'))

    doc = pq(response.content)
    href = doc('.breadcrumbs a')[0]
    eq_('/', href.attrib['href'][0])
Пример #24
0
class UploadImageTestCase(TestCase):
    fixtures = ['users.json', 'questions.json']

    def setUp(self):
        super(UploadImageTestCase, self).setUp()
        self.client = LocalizingClient()
        self.client.login(username='******', password='******')

    def tearDown(self):
        ImageAttachment.objects.all().delete()
        super(UploadImageTestCase, self).tearDown()

    def test_model_invalid(self):
        """Specifying an invalid model returns 400."""
        r = post(self.client, 'upload.up_image_async', {'image': ''},
                 args=['invalid.model', 123])

        eq_(400, r.status_code)
        json_r = json.loads(r.content)
        eq_('error', json_r['status'])
        eq_('Model does not exist.', json_r['message'])

    def test_object_notexist(self):
        """Upload nothing returns 404 error and html content."""
        r = post(self.client, 'upload.up_image_async', {'image': ''},
                 args=['questions.Question', 123])

        eq_(404, r.status_code)
        json_r = json.loads(r.content)
        eq_('error', json_r['status'])
        eq_('Object does not exist.', json_r['message'])

    def test_empty_image(self):
        """Upload nothing returns 400 error and json content."""
        r = post(self.client, 'upload.up_image_async', {'image': ''},
                 args=['questions.Question', 1])

        eq_(400, r.status_code)
        json_r = json.loads(r.content)
        eq_('error', json_r['status'])
        eq_('Invalid or no image received.', json_r['message'])

    def test_basic(self):
        """Uploading an image works."""
        # TODO: posting a valid image through the test client uploads it
        raise SkipTest

    def test_invalid_image(self):
        """Make sure invalid files are not accepted as images."""
        f = open('apps/upload/__init__.py', 'rb')
        r = post(self.client, 'upload.up_image_async', {'image': f},
                 args=['questions.Question', 1])
        f.close()

        eq_(400, r.status_code)
        json_r = json.loads(r.content)
        eq_('error', json_r['status'])
        eq_('Invalid or no image received.', json_r['message'])
Пример #25
0
class GalleryUploadTestCase(TestCase):
    fixtures = ['users.json']

    def setUp(self):
        super(GalleryUploadTestCase, self).setUp()
        self.client = LocalizingClient()
        self.client.login(username='******', password='******')
        self.u = User.objects.get(username='******')

    def tearDown(self):
        Image.objects.all().delete()
        Video.objects.all().delete()
        super(GalleryUploadTestCase, self).tearDown()

    def test_image_draft_shows(self):
        """The image draft is loaded for this user."""
        image(title=get_draft_title(self.u), creator=self.u)
        response = get(self.client, 'gallery.gallery', args=['image'])
        eq_(200, response.status_code)
        doc = pq(response.content)
        assert doc('.image-preview img').attr('src').endswith('098f6b.jpg')
        eq_(1, doc('.image-preview img').length)

    def test_video_draft_shows(self):
        """The video draft is loaded for this user."""
        video(title=get_draft_title(self.u), creator=self.u)
        response = get(self.client, 'gallery.gallery', args=['image'])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_(3, doc('ul li.video-preview').length)

    def test_image_draft_post(self):
        """Posting to the page saves the field values for the image draft."""
        image(title=get_draft_title(self.u), creator=self.u)
        response = post(self.client,
                        'gallery.gallery', {
                            'description': '??',
                            'title': 'test'
                        },
                        args=['image'])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_('??', doc('#gallery-upload-modal textarea').html())
        eq_('test', doc('#gallery-upload-modal input[name="title"]').val())

    def test_video_draft_post(self):
        """Posting to the page saves the field values for the video draft."""
        video(title=get_draft_title(self.u), creator=self.u)
        response = post(self.client,
                        'gallery.gallery', {'title': 'zTestz'},
                        args=['image'])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_('zTestz', doc('#gallery-upload-modal input[name="title"]').val())
Пример #26
0
 def setUp(self):
     # Ensure @ssl_required goes unenforced.
     settings.DEBUG = True
     # Set up some easily-testable redirects.
     settings.LOGIN_REDIRECT_URL = 'SUCCESS'
     settings.LOGIN_REDIRECT_URL_FAILURE = 'FAILURE'
     # BrowserID will squawk if this isn't set
     settings.SITE_URL = 'http://testserver'
     self.client = LocalizingClient()
Пример #27
0
    def test_json_empty_query(self):
        """Empty query returns JSON format"""
        c = LocalizingClient()

        # Test with flags for advanced search or not
        a_types = (0, 1, 2)
        for a in a_types:
            response = c.get(reverse('search'), {
                'format': 'json', 'a': a,
            })
            eq_(response['Content-Type'], 'application/json')
Пример #28
0
    def test_json_empty_query(self):
        """Empty query returns JSON format"""
        c = LocalizingClient()

        # Test with flags for advanced search or not
        a_types = (0, 1, 2)
        for a in a_types:
            response = c.get(reverse('search'), {
                'format': 'json', 'a': a,
            })
            eq_(response['Content-Type'], 'application/json')
Пример #29
0
    def test_invalid_slug(self):
        """Slugs cannot contain "$", but can contain "/"."""
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()

        data['title'] = 'valid slug'
        data['slug'] = 'valid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response,
                             reverse('wiki.document', args=[data['slug']]))

        # Slashes should be fine
        data['title'] = 'valid with slash'
        data['slug'] = 'va/lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response,
                             reverse('wiki.document', args=[data['slug']]))

        # Dollar sign is reserved for verbs
        data['title'] = 'invalid with dollars'
        data['slug'] = 'inva$lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, 'The slug provided is not valid.')

        # Question mark is reserved for query params
        data['title'] = 'invalid with questions'
        data['slug'] = 'inva?lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, 'The slug provided is not valid.')
Пример #30
0
class GalleryUploadTestCase(TestCase):
    fixtures = ["users.json"]

    def setUp(self):
        super(GalleryUploadTestCase, self).setUp()
        self.client = LocalizingClient()
        self.client.login(username="******", password="******")
        self.u = User.objects.get(username="******")

    def tearDown(self):
        Image.objects.all().delete()
        Video.objects.all().delete()
        super(GalleryUploadTestCase, self).tearDown()

    def test_image_draft_shows(self):
        """The image draft is loaded for this user."""
        image(title=get_draft_title(self.u), creator=self.u)
        response = get(self.client, "gallery.gallery", args=["image"])
        eq_(200, response.status_code)
        doc = pq(response.content)
        assert doc(".image-preview img").attr("src").endswith("098f6b.jpg")
        eq_(1, doc(".image-preview img").length)

    def test_video_draft_shows(self):
        """The video draft is loaded for this user."""
        video(title=get_draft_title(self.u), creator=self.u)
        response = get(self.client, "gallery.gallery", args=["image"])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_(3, doc("ul li.video-preview").length)

    def test_image_draft_post(self):
        """Posting to the page saves the field values for the image draft."""
        image(title=get_draft_title(self.u), creator=self.u)
        response = post(self.client, "gallery.gallery", {"description": "??", "title": "test"}, args=["image"])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_("??", doc("#gallery-upload-modal textarea").html())
        eq_("test", doc('#gallery-upload-modal input[name="title"]').val())

    def test_video_draft_post(self):
        """Posting to the page saves the field values for the video draft."""
        video(title=get_draft_title(self.u), creator=self.u)
        response = post(self.client, "gallery.gallery", {"title": "zTestz"}, args=["image"])
        eq_(200, response.status_code)
        doc = pq(response.content)
        # Preview for all 3 video formats: flv, ogv, webm
        eq_("zTestz", doc('#gallery-upload-modal input[name="title"]').val())
Пример #31
0
    def test_invalid_slug(self):
        """Slugs cannot contain /."""
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()
        data['slug'] = 'inva/lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, 'The slug provided is not valid.')

        data['slug'] = 'valid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response, reverse('wiki.document_revisions',
                                               args=[data['slug']],
                                               locale='en-US'))
Пример #32
0
 def test_retitling_ignored_for_iframe(self):
     """When the title of an article is edited in an iframe, the change is
     ignored."""
     client = LocalizingClient()
     client.login(username='******', password='******')
     new_title = 'Some New Title'
     d, r = doc_rev()
     old_title = d.title
     data = new_document_data()
     data.update({'title': new_title,
                  'slug': d.slug,
                  'form': 'rev'})
     client.post('%s?iframe=1' % reverse('wiki.edit_document', args=[d.slug]), data)
     eq_(old_title, Document.uncached.get(slug=d.slug).title)
     assert "REDIRECT" not in Document.uncached.get(title=old_title).html
Пример #33
0
    def test_raw_section_edit(self):
        client = LocalizingClient()
        client.login(username='******', password='******')
        d, r = doc_rev("""
            <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 = """
            <h1 id="s2">Replace</h1>
            <p>replace</p>
        """
        expected = """
            <h1 id="s2">Replace</h1>
            <p>replace</p>
        """
        response = client.post('%s?section=s2&raw=true' %
                               reverse('wiki.edit_document', args=[d.slug]),
                               {"form": "rev",
                                "content": replace},
                               follow=True)
        eq_(normalize_html(expected), 
            normalize_html(response.content))

        expected = """
            <h1 id="s1">Head 1</h1>
            <p>test</p>
            <p>test</p>

            <h1 id="s2">Replace</h1>
            <p>replace</p>

            <h1 id="s3">Head 3</h1>
            <p>test</p>
            <p>test</p>
        """
        response = client.get('%s?raw=true' %
                               reverse('wiki.document', args=[d.slug]))
        eq_(normalize_html(expected), 
            normalize_html(response.content))
Пример #34
0
class HomeTests(test_utils.TestCase):
    def setUp(self):
        self.client = LocalizingClient()

    def test_google_analytics(self):
        url = reverse('landing.views.home')

        with override_constance_settings(GOOGLE_ANALYTICS_ACCOUNT='0'):
            r = self.client.get(url, follow=True)
            eq_(200, r.status_code)
            ok_('var _gaq' not in r.content)

        with override_constance_settings(GOOGLE_ANALYTICS_ACCOUNT='UA-99999999-9'):
            r = self.client.get(url, follow=True)
            eq_(200, r.status_code)
            ok_('var _gaq' in r.content)
Пример #35
0
class SearchTestCase(TestCase):
    client = LocalizingClient()
    fixtures = ['users.json', 'gallery/media.json']

    def test_search_results(self):
        url = reverse('gallery.search', args=['image'])
        response = self.client.get(url, {'q': 'quicktime'}, follow=True)
        doc = pq(response.content)
        eq_(1, len(doc('#media-list li')))

    def test_image_search(self):
        url = reverse('gallery.search', args=['image'])
        response = self.client.get(url, {'q': 'quicktime'}, follow=True)
        doc = pq(response.content)
        eq_(1, len(doc('#media-list li')))

    def test_video_search(self):
        url = reverse('gallery.search', args=['video'])
        response = self.client.get(url, {'q': '1802'}, follow=True)
        doc = pq(response.content)
        eq_(1, len(doc('#media-list li')))

    def test_search_description(self):
        url = reverse('gallery.search', args=['image'])
        response = self.client.get(url, {'q': 'migrated'}, follow=True)
        doc = pq(response.content)
        eq_(5, len(doc('#media-list li')))

    def test_search_nonexistent(self):
        url = reverse('gallery.search', args=['foo'])
        response = self.client.get(url, {'q': 'foo'}, follow=True)
        eq_(404, response.status_code)
Пример #36
0
    def setUp(self):
        """Setup"""
        self.client = LocalizingClient()

        # Change the CACHE_PREFIX to avoid conflicts
        self.orig_cache_prefix = getattr(settings, 'CACHE_PREFIX', None)
        settings.CACHE_PREFIX = self.orig_cache_prefix or '' + 'test' + \
                                slugify(datetime.now())
Пример #37
0
    def test_ban_middleware(self):
        """Ban middleware functions correctly."""
        client = LocalizingClient()
        client.login(username='******', password='******')

        resp = client.get('/')
        self.assertTemplateNotUsed(resp, 'users/user_banned.html')

        admin = User.objects.get(username='******')
        testuser = User.objects.get(username='******')
        ban = UserBan(user=testuser, by=admin,
                      reason='Banned by unit test.',
                      is_active=True)
        ban.save()

        resp = client.get('/')
        self.assertTemplateUsed(resp, 'users/user_banned.html')
Пример #38
0
 def test_retitling(self):
     """When the title of an article is edited, a redirect is made."""
     # Not testing slug changes separately; the model tests cover those plus
     # slug+title changes. If title changes work in the view, the rest
     # should also.
     client = LocalizingClient()
     client.login(username='******', password='******')
     new_title = 'Some New Title'
     d, r = doc_rev()
     old_title = d.title
     data = new_document_data()
     data.update({'title': new_title,
                  'slug': d.slug,
                  'form': 'doc'})
     client.post(reverse('wiki.edit_document', args=[d.slug]), data)
     eq_(new_title, Document.uncached.get(slug=d.slug).title)
     assert Document.uncached.get(title=old_title).redirect_url()
Пример #39
0
    def setUp(self):
        super(TestCaseBase, self).setUp()
        self.client = LocalizingClient()

        ke_flag, created = Flag.objects.get_or_create(name='kumaediting')
        ke_flag.everyone = True
        ke_flag.save()
        self.kumaediting_flag = ke_flag
Пример #40
0
    def setUp(self):
        super(TestCaseBase, self).setUp()
        self.client = LocalizingClient()

        self.kumawiki_flag = Flag.objects.create(name='kumawiki',
                                                 everyone=True)
        self.kumaediting_flag = Flag.objects.create(name='kumaediting',
                                                   everyone=True)
Пример #41
0
    def test_invalid_slug(self):
        """Slugs cannot contain "$", but can contain "/"."""
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()

        data['title'] = 'valid slug'
        data['slug'] = 'valid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response, reverse('wiki.document',
                                               args=[data['slug']],
                                               locale='en-US'))

        # Slashes should be fine
        data['title'] = 'valid with slash'
        data['slug'] = 'va/lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response, reverse('wiki.document',
                                               args=[data['slug']],
                                               locale='en-US'))

        # Dollar sign is reserved for verbs
        data['title'] = 'invalid with dollars'
        data['slug'] = 'inva$lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, 'The slug provided is not valid.')

        # Question mark is reserved for query params
        data['title'] = 'invalid with questions'
        data['slug'] = 'inva?lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, 'The slug provided is not valid.')
Пример #42
0
    def test_kumawiki_waffle_flag(self):

        # Turn off the new wiki for everyone
        self.kumawiki_flag.everyone = False
        self.kumawiki_flag.save()
        
        client = LocalizingClient()

        resp = client.get(reverse('wiki.all_documents'))
        eq_(404, resp.status_code)
        
        resp = client.get(reverse('docs'))
        page = pq(resp.content)
        eq_(0, page.find('#kumawiki_preview').length)

        client.login(username='******', password='******')

        # Turn on the wiki for just superusers, ignore everyone else
        self.kumawiki_flag.superusers = True
        self.kumawiki_flag.everyone = None
        self.kumawiki_flag.save()

        resp = client.get(reverse('wiki.all_documents'))
        eq_(200, resp.status_code)
        
        resp = client.get(reverse('docs'))
        page = pq(resp.content)
        eq_(1, page.find('#kumawiki_preview').length)
Пример #43
0
    def test_review_tags(self):
        client = LocalizingClient()
        client.login(username='******', password='******')

        data = new_document_data()
        data.update({'review_tags':['editorial']})
        response = client.post(reverse('wiki.new_document'), data)

        doc = Document.objects.get(slug="a-test-article")

        combos = (
            ([], 0, 0, 0, 0),
            (['technical',], 1, 1, 0, 0),
            (['editorial',], 0, 0, 1, 1),
            (['technical', 'editorial',], 1, 1, 1, 1),
        )

        for tags, a, b, c, d in combos:

            # Edit the page and set the tags for this test
            data.update({ 'form': 'rev', 'review_tags': tags })
            response = client.post(reverse('wiki.edit_document', args=[doc.slug]), data)

            response = client.get(reverse('docs.views.docs'))
            page = pq(response.content)

            # Check for the section itself, and then the doc 
            eq_(a, page('div#review-technical').length)
            eq_(b, page("div#review-technical ul li h4 a:contains('%s')" %
                doc.title).length)
            eq_(c, page('div#review-editorial').length)
            eq_(d, page("div#review-editorial ul li h4 a:contains('%s')" %
                doc.title).length)
Пример #44
0
    def test_invalid_slugs(self, get_current):
        """Slugs cannot contain /."""
        get_current.return_value.domain = 'testserver'
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()
        error = 'The slug provided is not valid.'

        data['slug'] = 'inva/lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'no-question-marks?'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'no+plus'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'valid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response, reverse('wiki.document_revisions',
                                               args=[data['slug']],
                                               locale='en-US'))
Пример #45
0
def es_search_cmd(query, pages=1, log=log):
    """Simulates a front page search

    .. Note::

       This **doesn't** simulate an advanced search---just a front
       page search.

    """
    from sumo.tests import LocalizingClient
    from sumo.urlresolvers import reverse

    client = LocalizingClient()

    output = []
    output.append('Search for: %s' % query)
    output.append('')

    data = {
        'q': query, 'format': 'json'
        }
    url = reverse('search')

    # The search view shows 10 results at a time. So we hit it few
    # times---once for each page.
    for pageno in range(pages):
        pageno = pageno + 1
        data['page'] = pageno
        resp = client.get(url, data)
        if resp.status_code != 200:
            output.append('ERROR: %s' % resp.content)
            break

        else:
            content = json.loads(resp.content)
            results = content[u'results']

            for mem in results:
                output.append(u'%4d  %5.2f  %-10s  %-20s' % (
                        mem['rank'], mem['score'], mem['type'], mem['title']))

            output.append('')

    for line in output:
        log.info(line.encode('ascii', 'ignore'))
Пример #46
0
    def test_redirect_can_be_clobbered(self):
        """When an attempt is made to retitle an article, and another article
        with that title exists but is a redirect, there should be no errors and
        the redirect should be replaced."""
        client = LocalizingClient()
        client.login(username='******', password='******')

        exist_title = "Existing doc"
        exist_slug = "existing-doc"

        # Create a new doc.
        data = new_document_data()
        data.update({"title": exist_title, "slug": exist_slug})
        resp = client.post(reverse('wiki.new_document'), data)
        eq_(302, resp.status_code)

        # Change title and slug
        data.update({
            'form': 'rev',
            'title': "Changed title",
            'slug': "changed-title"
        })
        resp = client.post(reverse('wiki.edit_document', args=[exist_slug]),
                           data)
        eq_(302, resp.status_code)

        # Change title and slug back to originals, clobbering the redirect
        data.update({'form': 'rev', 'title': exist_title, 'slug': exist_slug})
        resp = client.post(
            reverse('wiki.edit_document', args=["changed-title"]), data)
        eq_(302, resp.status_code)
Пример #47
0
    def test_title_slug_collision_errors(self):
        """When an attempt is made to retitle an article and another with that
        title already exists, there should be form errors"""
        client = LocalizingClient()
        client.login(username='******', password='******')

        exist_title = "Existing doc"
        exist_slug = "existing-doc"

        # Create a new doc.
        data = new_document_data()
        data.update({"title": exist_title, "slug": exist_slug})
        resp = client.post(reverse('wiki.new_document'), data)
        eq_(302, resp.status_code)

        # Create another new doc.
        data = new_document_data()
        data.update({"title": 'Some new title', "slug": 'some-new-title'})
        response = client.post(reverse('wiki.new_document'), data)
        eq_(302, resp.status_code)

        # Now, post an update with duplicate slug and title
        data.update({'form': 'rev', 'title': exist_title, 'slug': exist_slug})
        resp = client.post(
            reverse('wiki.edit_document', args=['some-new-title']), data)
        eq_(200, resp.status_code)
        p = pq(resp.content)

        ok_(p.find('.errorlist').length > 0)
        ok_(p.find('.errorlist a[href="#id_title"]').length > 0)
        ok_(p.find('.errorlist a[href="#id_slug"]').length > 0)
Пример #48
0
def test_json_down():
    """When the Sphinx is down, return JSON and 503 status"""
    c = LocalizingClient()

    # Test with flags for advanced search or not
    callbacks = (
        ('', 503, 'application/json'),
        ('validCallback', 503, 'application/x-javascript'),
        # Invalid callback does not search
        ('eval("xss");a', 400, 'application/x-javascript'),
    )
    for callback, status, mimetype in callbacks:
        response = c.get(reverse('search'), {
            'q': 'json down', 'format': 'json',
            'callback': callback,
        })
        eq_(response['Content-Type'], mimetype)
        eq_(response.status_code, status)
Пример #49
0
def test_json_down():
    """When the Sphinx is down, return JSON and 503 status"""
    c = LocalizingClient()

    # Test with flags for advanced search or not
    callbacks = (
        ('', 503, 'application/json'),
        ('validCallback', 503, 'application/x-javascript'),
        # Invalid callback does not search
        ('eval("xss");a', 400, 'application/x-javascript'),
    )
    for callback, status, mimetype in callbacks:
        response = c.get(reverse('search'), {
            'q': 'json down', 'format': 'json',
            'callback': callback,
        })
        eq_(response['Content-Type'], mimetype)
        eq_(response.status_code, status)
Пример #50
0
 def setUp(self):
     # Ensure @ssl_required goes unenforced.
     settings.DEBUG = True
     # Set up some easily-testable redirects.
     settings.LOGIN_REDIRECT_URL = 'SUCCESS'
     settings.LOGIN_REDIRECT_URL_FAILURE = 'FAILURE'
     # BrowserID will squawk if this isn't set
     settings.SITE_URL = 'http://testserver'
     self.client = LocalizingClient()
Пример #51
0
def es_search_cmd(query, pages=1, log=log):
    """Simulates a front page search

    .. Note::

       This **doesn't** simulate an advanced search---just a front
       page search.

    """
    from sumo.tests import LocalizingClient
    from sumo.urlresolvers import reverse

    client = LocalizingClient()

    output = []
    output.append('Search for: %s' % query)
    output.append('')

    data = {'q': query, 'format': 'json'}
    url = reverse('search')

    # The search view shows 10 results at a time. So we hit it few
    # times---once for each page.
    for pageno in range(pages):
        pageno = pageno + 1
        data['page'] = pageno
        resp = client.get(url, data)
        if resp.status_code != 200:
            output.append('ERROR: %s' % resp.content)
            break

        else:
            content = json.loads(resp.content)
            results = content[u'results']

            for mem in results:
                output.append(
                    u'%4d  %5.2f  %-10s  %-20s' %
                    (mem['rank'], mem['score'], mem['type'], mem['title']))

            output.append('')

    for line in output:
        log.info(line.encode('ascii', 'ignore'))
Пример #52
0
class AppsViewsTest(test_utils.TestCase):
    def setUp(self):
        self.client = LocalizingClient()

    def _good_newsletter_post(self):
        url = reverse('landing.views.apps_newsletter')

        r = self.client.post(url, {
            'format': 'html',
            'country': 'pt',
            'email': '*****@*****.**',
            'agree': 'checked'
        },
                             follow=True)
        eq_(200, r.status_code)

        return r

    @patch('landing.views.basket.subscribe')
    def test_apps_subscription(self, subscribe):
        subscribe.return_value = {'status': 'success'}
        r = self._good_newsletter_post()
        # assert thank you message
        self.assertContains(r, 'Thank you')
        eq_(1, subscribe.call_count)

    @patch('landing.views.basket.subscribe')
    def test_apps_subscription_bad_values(self, subscribe):
        subscribe.return_value = True
        url = reverse('landing.views.apps_newsletter')
        r = self.client.post(url, {'format': 1, 'email': 'nope'})
        eq_(200, r.status_code)
        # assert error
        self.assertContains(r, 'Enter a valid e-mail address.')
        self.assertContains(r, 'Select a valid choice.')
        self.assertContains(r, 'You must agree to the privacy policy.')

    @patch('landing.views.basket.subscribe')
    def test_apps_subscription_exception_retry(self, subscribe):
        subscribe.side_effect = basket.base.BasketException("500!")
        subscribe.return_value = True
        self._good_newsletter_post()
        eq_(constance.config.BASKET_RETRIES, subscribe.call_count)
Пример #53
0
    def test_ban_permission(self):
        """The ban permission controls access to the ban view."""
        client = LocalizingClient()
        admin = User.objects.get(username='******')
        testuser = User.objects.get(username='******')

        # testuser doesn't have ban permission, can't ban.
        client.login(username='******', password='******')
        ban_url = reverse('users.ban_user', kwargs={'user_id': admin.id})
        resp = client.get(ban_url)
        eq_(302, resp.status_code)
        ok_(settings.LOGIN_URL in resp['Location'])
        client.logout()

        # admin has ban permission, can ban.
        client.login(username='******', password='******')
        ban_url = reverse('users.ban_user', kwargs={'user_id': testuser.id})
        resp = client.get(ban_url)
        eq_(200, resp.status_code)
Пример #54
0
    def setUp(self):
        q = Question.objects.get(pk=1)
        q.last_answer_id = 1
        q.save()

        self.client = LocalizingClient()

        # create a new cache key for top contributors to avoid conflict
        # TODO: May be able to go away once we flush memcache between tests.
        self.orig_tc_cache_key = settings.TOP_CONTRIBUTORS_CACHE_KEY
        settings.TOP_CONTRIBUTORS_CACHE_KEY += slugify(datetime.now())
Пример #55
0
class DemoListViewsTest(test_utils.TestCase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.user, self.admin_user, self.other_user = make_users()
        self.client = LocalizingClient()

    def test_all_demos_includes_hidden_for_staff(self):
        build_submission(self.user)
        build_hidden_submission(self.user)

        r = self.client.get(reverse('demos_all'))
        count = pq(r.content)('h2.count').text()
        eq_(count, "1 Demo")

        self.client.login(username=self.admin_user.username,
                          password='******')
        r = self.client.get(reverse('demos_all'))
        count = pq(r.content)('h2.count').text()
        eq_(count, "2 Demos")
Пример #56
0
class EventsViewsTest(test_utils.TestCase):
    fixtures = ['devmo_calendar.json']

    def setUp(self):
        self.client = LocalizingClient()
        devmo_calendar_reload()

    def test_events(self):
        url = reverse('devmo.views.events')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
Пример #57
0
class LandingViewsTest(test_utils.TestCase):
    fixtures = [
        'test_data.json',
    ]

    def setUp(self):
        self.client = LocalizingClient()

    def test_home(self):
        url = reverse('landing.views.home')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

        doc = pq(r.content)
        dev_mdc_link = doc.find('a#dev-mdc-link')
        ok_(dev_mdc_link)

    def test_addons(self):
        url = reverse('landing.views.addons')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_mozilla(self):
        url = reverse('landing.views.mozilla')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_mobile(self):
        url = reverse('landing.views.mobile')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_web(self):
        url = reverse('landing.views.web')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_promote_buttons(self):
        url = reverse('landing.views.promote_buttons')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_discussion(self):
        url = reverse('landing.views.discussion')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_forum_archive(self):
        url = reverse('landing.views.forum_archive')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
Пример #58
0
    def test_invalid_reserved_term_slug(self):
        """Slugs should not collide with reserved URL patterns"""
        client = LocalizingClient()
        client.login(username='******', password='******')
        data = new_document_data()

        # TODO: This is info derived from urls.py, but unsure how to DRY it
        reserved_slugs = ('ckeditor_config.js', 'watch-ready-for-review',
                          'unwatch-ready-for-review', 'watch-approved',
                          'unwatch-approved', '.json', 'new', 'all',
                          'preview-wiki-content', 'category/10',
                          'needs-review/technical', 'needs-review/',
                          'feeds/atom/all/',
                          'feeds/atom/needs-review/technical',
                          'feeds/atom/needs-review/', 'tag/tasty-pie')

        for term in reserved_slugs:
            data['title'] = 'invalid with %s' % term
            data['slug'] = term
            response = client.post(reverse('wiki.new_document'), data)
            self.assertContains(response, 'The slug provided is not valid.')
Пример #59
0
    def test_ban_view(self):
        testuser = User.objects.get(username='******')
        admin = User.objects.get(username='******')

        client = LocalizingClient()
        client.login(username='******', password='******')

        data = {'reason': 'Banned by unit test.'}
        ban_url = reverse('users.ban_user', kwargs={'user_id': testuser.id})

        resp = client.post(ban_url, data)
        eq_(302, resp.status_code)
        ok_(testuser.get_absolute_url() in resp['Location'])

        testuser_banned = User.objects.get(username='******')
        ok_(not testuser_banned.is_active)

        bans = UserBan.objects.filter(user=testuser,
                                      by=admin,
                                      reason='Banned by unit test.')
        ok_(bans.count())
Пример #60
0
class LearnViewsTest(test_utils.TestCase):
    def setUp(self):
        self.client = LocalizingClient()

    def test_learn(self):
        url = reverse('landing.views.learn')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_learn_html(self):
        url = reverse('landing.views.learn_html')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_learn_html5(self):
        url = reverse('landing.views.learn_html5')
        r = self.client.get(url, follow=True)
        eq_(404, r.status_code)
        s = Switch.objects.create(name='html5_landing', active=True)
        s.save()
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        s.delete()

    def test_learn_css(self):
        url = reverse('landing.views.learn_css')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)

    def test_learn_javascript(self):
        url = reverse('landing.views.learn_javascript')
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)