Beispiel #1
0
 def test_templatetags(self):
     user = create_test_user("Monica Schlicht",
                             "*****@*****.**", "2380vh23v")
     entry = Entry.objects.create(
         title="Who owns Warhol portrait of Fawcett?")
     html = social_tags.like_entry_button(entry.pk, user)
     self.assertTrue(social_tags.get_div_dom_id(entry.pk) in html)
     self.assertTrue(social_tags.get_button_dom_id(entry.pk) in html)
Beispiel #2
0
 def setup_random(self):
     random.seed(834932784)
     self.users = []
     for i in range(20):
         self.users.append(
             create_test_user("User %d" % (i), "*****@*****.**" % (i),
                              "12345678987654321"))
     self.entries = []
     for i in range(20):
         self.entries.append(Entry.objects.create(title="Entry %d" % (i)))
Beispiel #3
0
 def test_nonexistent(self):
     user = create_test_user('she', '*****@*****.**', 'is here')
     user.save()
     from brabeion import badges
     # hack: fake the existence of this badge so an object can be created
     # simulating the situation where some badges were awarded, then a particular
     # badge was removed (in principle), but the previously awarded badges still
     # persist in the database
     badges._registry['thereisnosuchbadge'] = badges._registry['horse']
     b = BadgeAward.objects.create(user=user,
                                   slug='thereisnosuchbadge',
                                   level=0)
     del badges._registry['thereisnosuchbadge']
     c = Client()
     self.assertTrue(c.login(username='******', password='******'))
     response = c.get(reverse('dashboard'), follow=True)
Beispiel #4
0
    def test_links(self):
        c = Client()
        user = create_test_user('temporary', '*****@*****.**',
                                'temporary')
        c.login(username='******', password='******')

        q = Queue()
        mark = {reverse('dashboard'): False}
        q.put(reverse('dashboard'))

        external = set()
        while not q.empty():
            url = q.get()
            print 'checking %s' % (url)
            mark[url] = True
            r = c.get(url, follow=True)
            self.assertEqual(r.status_code, 200)
            soup = BeautifulSoup(r.content)
            outgoing = set()
            for link in soup.find_all('a'):
                outgoing.add(link.get('href'))
#            for form in soup.find_all('form'):
#                outgoing.add(form.get('action'))
            for child in outgoing:
                # some links have no href
                if child is not None and len(
                        child) > 0 and not child.startswith('/forum'):
                    self.assertEquals(type(child), unicode)
                    if child[0] == '/':  # internal
                        if not child in mark:
                            mark[child] = False
                            q.put(child)
                    elif child[:4] == 'http':  # external
                        external.add(child)
        # Those pages must be reachable from the dashboard:
#        self.assertTrue(mark[reverse('fund_home')])
        self.assertTrue(mark[reverse('groups_all')])
        self.assertTrue(mark[reverse('newstatus_home')])
Beispiel #5
0
    def test_restricted_access(self):
        client = Client()

        user_g = create_test_user("Guido van Rossum", "*****@*****.**",
                                  "3jh3j")
        user_h = create_test_user("Hilda von Varden", "*****@*****.**",
                                  "777777777")

        # must specify slug. Otherwise get_aboslute_url is broken and will get NoReverseMatch.

        entry = Entry(title="Django's wonderful permalink decorator 12321",
                      slug="django",
                      status=PUBLISHED,
                      start_publication=datetime.datetime(
                          2011, 8, 15, 8, 15, 12, 0, pytz.UTC))
        private_entry_g = Entry(
            title="Secret communication of Guido with space travellers",
            slug="secret-never-see",
            status=HIDDEN)
        private_entry_h = Entry(
            title="Hilda spent her vacation in New Zealand",
            slug="-k-a-n-g-a-r-o-o-",
            status=HIDDEN)

        ### NB!
        ### This will fail with an in-memory sqlite3 database, but works fine with an on-disk sqlite3 database. With in-memory database it fails with 'no such table zinnia_category'. If we omit status-PUBLISHED, it works just fine. This is really weird, because the code in a previous test manually queries the database (as sqlite3) and confirms that various Zinnia tables exist, including 'zinnia_category'. Perhaps, Zinnia has some extra functionality when saving PUBLISHED entries, and it does something that breaks with an in-memory database...
        entry.save()
        private_entry_g.save()
        private_entry_h.save()

        # Adding the respective users as authorized. We can only do it after first saving the models.
        private_entry_g.authorized_users.add(user_g)
        private_entry_g.save()
        private_entry_h.authorized_users.add(user_h)
        private_entry_h.save()

        # Logging in user_g
        client.login(username='******', password='******')

        # Now, we did not set the site for the new entries (see django.contrib.sites).
        # Thus, we do not expect them to show up when we follow a direct link.
        # By the way, they still shows up in the dashboard; this is probably a Zinnia issue.
        self.assertEqual(client.get(entry.get_absolute_url()).status_code, 404)
        self.assertEqual(
            client.get(private_entry_g.get_absolute_url()).status_code, 404)
        self.assertEqual(
            client.get(private_entry_h.get_absolute_url()).status_code, 404)

        # django.contrib.sites
        # Adding the current site to the Entry.
        # Otherwise it will not be displayed in the detailed view.
        # For some weird reason it is still displayed in the dashboard (that is, zinnia archive of entries). Created an issue for Zinnia on github...
        self.site = Site.objects.get(pk=settings.SITE_ID)
        entry.sites.add(self.site)
        entry.save()
        private_entry_g.sites.add(self.site)
        private_entry_g.save()
        private_entry_h.sites.add(self.site)
        private_entry_h.save()

        # Test a direct link to the entries. We should see the public entry and the private entry by one of the users
        self.assertContains(client.get(entry.get_absolute_url()),
                            'wonderful permalink decorator 12321',
                            status_code=200)
        #        self.assertContains(client.get(private_entry_g.get_absolute_url()), 'Secret communication of Guido with', status_code=200)
        #        self.assertEquals(client.get(private_entry_h.get_absolute_url()).status_code, 404)

        # Also, there should be no link to the hidden entry from the detail view of other entries!
        self.assertNotContains(client.get(entry.get_absolute_url()),
                               private_entry_h.get_absolute_url())
        self.assertNotContains(client.get(private_entry_g.get_absolute_url()),
                               private_entry_h.get_absolute_url())

        # Test the dashboard
        response_dash = client.get(reverse('dashboard'), follow=True)
        self.assertContains(response_dash,
                            'wonderful permalink decorator 12321',
                            status_code=200)
        self.assertContains(response_dash,
                            'Secret communication of Guido with',
                            status_code=200)
        self.assertNotContains(response_dash,
                               'spent her vacation',
                               status_code=200)
        # The dashboard should contain links "Continue Reading" to the visible posts
        self.assertContains(response_dash, entry.get_absolute_url())
        #        self.assertContains(response_dash, private_entry_g.get_absolute_url())
        #        self.assertNotContains(response_dash, private_entry_h.get_absolute_url())

        client.logout()
        # LOG OUT.
        # Still try a direct link to a public entry! But the private one should return 404.
        self.assertContains(client.get(entry.get_absolute_url()),
                            'wonderful permalink decorator 12321',
                            status_code=200)
        self.assertEquals(
            client.get(private_entry_g.get_absolute_url()).status_code, 404)
        self.assertEquals(
            client.get(private_entry_h.get_absolute_url()).status_code, 404)
        # Since we are logged out, the public entry cannot show links to either hidden entry
        self.assertNotContains(client.get(entry.get_absolute_url()),
                               private_entry_g.get_absolute_url())
        self.assertNotContains(client.get(entry.get_absolute_url()),
                               private_entry_h.get_absolute_url())

        # Now logging in user_h
        client.login(username="******", password="******")

        # Test a direct link to the entries. We should see the public entry and the private entry by the other user
        self.assertContains(client.get(entry.get_absolute_url()),
                            'wonderful permalink decorator 12321',
                            status_code=200)
        self.assertEquals(
            client.get(private_entry_g.get_absolute_url()).status_code, 404)
        self.assertContains(client.get(private_entry_h.get_absolute_url()),
                            'Hilda spent her vacation in New Zealand',
                            status_code=200)
        # Also, there should be no link to the hidden entry from the detail view of other entries!
        #        self.assertNotContains(client.get(entry.get_absolute_url()), private_entry_g.get_absolute_url())
        #        self.assertNotContains(client.get(private_entry_h.get_absolute_url()), private_entry_g.get_absolute_url())

        # Test the dashboard
        response_dash = client.get(reverse('dashboard'), follow=True)
        self.assertContains(response_dash,
                            'wonderful permalink decorator 12321',
                            status_code=200)
        self.assertNotContains(response_dash,
                               'Secret communication of Guido with',
                               status_code=200)
        self.assertContains(response_dash,
                            'spent her vacation',
                            status_code=200)
        # The dashboard should contain links "Continue Reading" to the visible posts
        self.assertContains(response_dash, entry.get_absolute_url())
        #        self.assertNotContains(response_dash, private_entry_g.get_absolute_url())
        #        self.assertContains(response_dash, private_entry_h.get_absolute_url())

        client.logout()
Beispiel #6
0
    def test_basic(self):
        # Make sure we are testing with sqlite3
        from django.conf import settings
        self.assertEqual(settings.DATABASES['default']['ENGINE'],
                         'django.db.backends.sqlite3')

        user = create_test_user("Monica Schlicht",
                                "*****@*****.**", "2380vh23v")
        entry = Entry.objects.create(
            title="Who owns Warhol portrait of Fawcett?")

        self.assertEqual(entry_is_liked(entry, user), 0)
        self.assertEqual(total_entry_likes(entry), 0)
        self.assertEqual(total_likes_by_user(user), 0)

        # Like and Unlike the entry several times in a row
        for i in range(5):
            count = toggle_like_unlike(entry, user)
            # Now the user likes the entry
            self.assertEqual(count, 1)
            self.assertEqual(total_entry_likes(entry), 1)
            self.assertEqual(total_likes_by_user(user), 1)

            count = toggle_like_unlike(entry, user)
            # Now the user unliked the entry, back to where we were
            self.assertEqual(count, 0)
            self.assertEqual(total_entry_likes(entry), 0)
            self.assertEqual(total_likes_by_user(user), 0)

        ### One user likes it, then the other, then the forer unlikes, then the latter unlikes

        u2 = create_test_user("Schwarzenegger", "*****@*****.**",
                              "32!!!@FJ#IOJV#E")
        # Now user u2 comes and likes the entry
        count = toggle_like_unlike(entry, u2)
        self.assertEqual(count, 1)
        count = entry_is_liked(entry, user)  # No, user doesn't like it
        self.assertEqual(count, 0)
        self.assertEqual(total_entry_likes(entry),
                         1)  # but we see the like of u2
        count = entry_is_liked(entry, u2)  # Yes, u2 likes it
        self.assertEqual(count, 1)

        # Now user also likes the entry
        count = toggle_like_unlike(entry, user)
        self.assertEqual(count, 1)
        count = entry_is_liked(entry, user)  # Now both like it
        self.assertEqual(count, 1)
        count = entry_is_liked(entry, u2)
        self.assertEqual(count, 1)
        self.assertEqual(total_entry_likes(entry), 2)

        # Now u2 unlikes the entry
        count = toggle_like_unlike(entry, u2)
        self.assertEqual(count, 0)  # user still likes it
        count = entry_is_liked(entry, user)
        self.assertEqual(count, 1)
        count = entry_is_liked(entry, u2)
        self.assertEqual(count, 0)
        self.assertEqual(total_entry_likes(entry), 1)

        # Now user also unlikes the entry
        count = toggle_like_unlike(entry, user)
        self.assertEqual(count, 0)
        count = entry_is_liked(entry, user)
        self.assertEqual(count, 0)
        count = entry_is_liked(entry, u2)
        self.assertEqual(count, 0)
        self.assertEqual(total_entry_likes(entry), 0)
Beispiel #7
0
    def test_ajax_star_rating(self):
        client = Client()
        url = reverse('ajax_star_rating')
        # User not authenticated. Expected AJAX response HTTP 401.
        response401 = client.post(
            url,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response401.status_code, 401)

        #Loggging in...
        user = create_test_user('temporary', '*****@*****.**',
                                'temporary')
        client.login(username='******', password='******')
        #Logged in

        # Now we are logged in and the request is ajax, but the data do not include rating. Bad request...
        response400 = client.post(
            url,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response400.status_code, 400)

        data = {
            'value': '5',
        }

        #try again
        response = client.post(url,
                               data,
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._headers['content-type'],
                         ('Content-Type', 'application/javascript'))
        resp_data = json.loads(response.content)

        # The user has just rated something (the website)

        self.assertTrue('message' in resp_data)
        self.assertEquals(resp_data['message'], "Thank you for your feedback!")

        # So far the user has rated once
        self.assertEquals(user.ratings.count(), 1)
        self.assertEqual(StarRating.objects.filter(user=user).count(), 1)

        self.assertEqual(user.badges_earned.count(), 1)
        self.assertIsInstance(user.badges_earned.all()[0]._badge,
                              status_awards.test_badges.FearlessRaterBadge)

        # NOW try voting again!
        data = {
            'value': '2',
        }
        response = client.post(url,
                               data,
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._headers['content-type'],
                         ('Content-Type', 'application/javascript'))
        resp_data = json.loads(response.content)

        # The user has just tried to rate the same item again

        self.assertTrue('message' in resp_data)
        self.assertEquals(resp_data['message'],
                          "You have already voted in the recent past.")
        # Still one rating
        self.assertEqual(user.ratings.count(), 1)
        # Namely, rating 5. The first one.
        self.assertEqual(user.ratings.all()[0].rating, 5)

        # Still one badge
        self.assertEqual(user.badges_earned.count(), 1)

        # NOW
        # Say, we can rate again after a day
        from django.conf import settings
        settings.MAGNATE_CAN_STAR_RATE_EVERY = 'days=1'

        # Say, the user actually rated this item 23 hours ago
        r = user.ratings.all()[0]
        r.date = r.date - datetime.timedelta(hours=23)
        r.save()

        # He still shouldn't be able to rate again!
        response = client.post(url,
                               data,
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._headers['content-type'],
                         ('Content-Type', 'application/javascript'))
        resp_data = json.loads(response.content)
        self.assertTrue('message' in resp_data)
        self.assertEquals(resp_data['message'],
                          "You have already voted in the recent past.")
        # Still one rating
        self.assertEqual(user.ratings.count(), 1)
        # Namely, rating 5. The first one.
        self.assertEqual(user.ratings.all()[0].rating, 5)
        # Still one badge
        self.assertEqual(user.badges_earned.count(), 1)

        # Now, say, the user actually rated this item 25 hours ago
        r = user.ratings.all()[0]
        r.date = r.date - datetime.timedelta(
            hours=2)  # shift back two more hours
        r.save()

        # Now he should be able to rate again! (This is also a nice check for timezones, etc.)
        data = {
            'value': '1',
        }
        response = client.post(url,
                               data,
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._headers['content-type'],
                         ('Content-Type', 'application/javascript'))
        resp_data = json.loads(response.content)
        self.assertTrue('message' in resp_data)
        self.assertEquals(resp_data['message'], "Thank you for your feedback!")
        # Now two ratings
        self.assertEqual(user.ratings.count(), 2)
        self.assertEqual(sorted([r.rating for r in user.ratings.all()]),
                         [1, 5])
        # Now two badges (same badge, but earned on two levels)
        self.assertEqual(user.badges_earned.count(), 2)
        self.assertEqual(
            sorted([(b.slug, b.level) for b in user.badges_earned.all()]),
            [('fearless-rater', 0), ('fearless-rater', 1)])

        # Try an AJAX GET request
        response405 = client.get(url,
                                 data,
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response405.status_code, 405)

        # Try a POST request that is not AJAX.. Expected HTTP 400.
        response400 = client.post(url, data)
        self.assertEqual(response400.status_code, 400)

        # Lastly, try a GET request that is not AJAX. Expected HTTP 400.
        response405 = client.get(url, data)
        self.assertEqual(response405.status_code, 405)
Beispiel #8
0
    def test_ajax_like(self):
        client = Client()
        url = reverse('ajax_like_entry')
        # User not authenticated. Expected AJAX response HTTP 401.
        response401 = client.post(
            url,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response401.status_code, 401)

        #Loggging in...
        user = create_test_user('temporary', '*****@*****.**',
                                'temporary')
        client.login(username='******', password='******')
        #Logged in

        # Now we are logged in and the request is ajax, but the data do not include entry_id
        response404 = client.post(
            url,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        )
        self.assertEqual(response404.status_code, 404)

        # Now using nonexistent entry_id = 17
        data = {
            'entry_id': '17',
        }
        response404 = client.post(url,
                                  data,
                                  HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response404.status_code, 404)

        # Create lots of users and entries...
        self.setup_random()
        # Now #17 exists. Just double-check; will raise DoesNotExist if anything.
        Entry.objects.get(pk=17)

        #try again
        response = client.post(url,
                               data,
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response._headers['content-type'],
                         ('Content-Type', 'application/javascript'))
        resp_data = json.loads(response.content)

        # The user just liked an Entry
        self.assertEqual(resp_data['liked'], True)
        # Nobody else likes it so far
        self.assertEqual(resp_data['total_likes'], 1)
        # resp_data['update_html'] contains html to update the div
        self.assertTrue('update_html' in resp_data)
        # the html should send something about unliking, since the user has just liked it
        # We expect resp_data["update_html"] to be like {"div-like-17": "<div id=div-like-17><input type=\"Button\" id=\"like-17\" value=\"Unlike it (1)\" style=\"float: right\" onClick=\"on_click_like_entry(17, this.id)\" /> </div>"}

        # If the text on the buttons is ever changed in social/templatetags,
        # change it here accordingly to 'unlike', 'unmark', or whatever
        self.assertTrue('unmark' in str(resp_data['update_html']).lower())

        # TODO: this is temporary check
        # Of course, the list of badges may change
        # But for now we know that there should be 1 badge awarded
        self.assertEquals(user.badges_earned.count(), 1)
        self.assertIsInstance(user.badges_earned.all()[0]._badge,
                              status_awards.test_badges.TestLikesBadge_0)

        # Try an AJAX GET request
        response405 = client.get(url,
                                 data,
                                 HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response405.status_code, 405)

        # Try a POST request that is not AJAX.. Expected HTTP 400.
        response400 = client.post(url, data)
        self.assertEqual(response400.status_code, 400)

        # Lastly, try a GET request that is not AJAX. Expected HTTP 400.
        response405 = client.get(url, data)
        self.assertEqual(response405.status_code, 405)
Beispiel #9
0
 def setUp(self):
     self.client = Client()
     user = create_test_user('temporary', '*****@*****.**',
                             'temporary')
     self.client.login(username='******', password='******')
Beispiel #10
0
    def test_AskQuestion(self):
        user = create_test_user("Water Cooler", "*****@*****.**", "12621262")
        self.client.login(username='******', password='******')

        # Anonymous user
        # Because if we were to log in, then we need to have ExtendedUser,
        # but all middleware is disabled in django.test.Client a.k.a. RequestFactory
        # but then it would fail, because request.user would not contain
        # reputation and other fields

        from zinnia.models.entry import Entry
        from zinnia.managers import PUBLISHED, DRAFT, HIDDEN
        import datetime, pytz

        # No questions about no entry
        r = self.client.get('/osqa_forum/questions/ask/')
        self.assertEqual(r.status_code, 404)

        e = Entry.objects.create(title='Can only ask about public entries',
                                 slug='j',
                                 start_publication=datetime.datetime(
                                     2011, 8, 15, 8, 15, 12, 0, pytz.UTC))

        # No questions about draft entries
        e.status = DRAFT
        e.save()
        r = self.client.get('/osqa_forum/questions/ask/?entry_id=1')
        self.assertEqual(r.status_code, 404)

        # No questions about hidden entries
        e.status = HIDDEN
        e.save()
        r = self.client.get('/osqa_forum/questions/ask/?entry_id=1')
        self.assertEqual(r.status_code, 404)

        # Yes, you can ask about public entries!
        e.status = PUBLISHED
        e.save()
        r = self.client.get('/osqa_forum/questions/ask/?entry_id=1')
        self.assertEqual(r.status_code, 200)

        r = self.client.post(
            '/osqa_forum/questions/ask/?entry_id=1', {
                'title': '',
                'text': 'This is the text of my first question',
                'tags': 'first second third'
            })
        self.assertEqual(r.status_code, 200)
        self.assertContains(r, 'errorlist')
        self.assertContains(r, 'This field is required')
        self.assertContains(
            r, 'please enter a descriptive title for your question')

        # with redirect follow=True
        r = self.client.post('/osqa_forum/questions/ask/?entry_id=1', {
            'title': 'First question! This is now a legitimate question!.',
            'text': 'This is great text.',
            'tags': 'good for real'
        },
                             follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertNotContains(r, 'errorlist')

        # with redirect follow=True
        r = self.client.post('/osqa_forum/questions/ask/?entry_id=1', {
            'title': 'Second question! This is a great title.',
            'text': '',
            'tags': 'good for real'
        },
                             follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertContains(r, 'errorlist')
        self.assertContains(r, 'This field is required')

        # ask another one
        # with redirect follow=True
        r = self.client.post('/osqa_forum/questions/ask/?entry_id=1', {
            'title': 'Third question!.',
            'text': 'Keeps getting better.',
            'tags': 'so good'
        },
                             follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertNotContains(r, 'errorlist')

        self.assertContains(r, 'First question!')  # was successful
        self.assertNotContains(r, 'Second question!')  # failed
        self.assertContains(r, 'Third question!')  # was successful