Bruno Renié avatar Bruno Renié committed d67691b

Made all the activity tests less retarded

Comments (0)

Files changed (5)

 	django-admin.py test ${ARGS} $(test_settings) --failfast
 
 debugtest:
-	django-admin.py test $(test_settings) -v2
+	django-admin.py test ${ARGS} $(test_settings) -v2

dotim/activity/fixtures/test_fixtures.json

-[
-  {
-    "pk": 1,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "https://twitter.com/statuses/user_timeline/brutasse.json",
-      "event_type": "twitter"
-    }
-  },
-  {
-    "pk": 2,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "dotim/activity/tests/web/github.brutasse.atom",
-      "username": "brutasse",
-      "event_type": "github"
-    }
-  },
-  {
-    "pk": 3,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "dotim/activity/tests/web/delicious.brutasse.xml",
-      "event_type": "delicious"
-    }
-  },
-  {
-    "pk": 4,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "dotim/activity/tests/web/bitbucket.bruno.xml",
-      "username": "bruno",
-      "event_type": "bitbucket"
-    }
-  },
-  {
-    "pk": 5,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "dotim/activity/tests/web/gitorious.wombat.atom",
-      "username": "brutasse",
-      "event_type": "gitorious"
-    }
-  },
-  {
-    "pk": 6,
-    "model": "activity.eventconfig",
-    "fields": {
-      "url": "dotim/activity/tests/web/djangosnippets.brutasse.xml",
-      "event_type": "djangosnippets"
-    }
-  }
-]

dotim/activity/models.py

 
 from dateutil.parser import parse
 
+from django.conf import settings
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
 
     def get_filters(self):
         return [f.strip() for f in self.filters.split(',')]
 
-    def update(self, feedparser=feedparser):
+    def update(self):
+        if (getattr(settings, 'TESTS', False) and
+            str(type(requests.get)) != "<class 'mock.MagicMock'>"):
+            assert False, "Not mocked"
+        response = requests.get(self.url, timeout=10, headers={
+            'User-Agent': USER_AGENT,
+        })
         if self.event_type == 'twitter':
-            self.update_twitter()
+            self.update_twitter(response)
         elif self.event_type in ('bitbucket', 'github', 'delicious',
                                  'gitorious', 'djangosnippets'):
-            self.update_from_feed(feedparser=feedparser)
+            self.update_from_feed(response)
 
-    def update_twitter(self):
+    def update_twitter(self, response):
         """
         Fetches the lates tweets from this user.
         It uses the JSON method since the RSS one truncates the long tweets.
         """
-        response = requests.get(self.url, timeout=10, headers={
-            'User-Agent': USER_AGENT,
-        })
         items = json.loads(response.content)
         # Items will contain 20 elements by default. ?count=X cannot be > 200
 
             self.last_event_date = max_date
             self.save()
 
-    def update_from_feed(self, feedparser=feedparser):
+    def update_from_feed(self, response):
         """
         Updates things from an RSS or Atom feed.
         """
-        feed = feedparser.parse(self.url)
-        if not feed.status == 200:
+        if response.status_code != 200:
             return
+        feed = feedparser.parse(response.content)
         max_date = self.last_event_date
         for event in feed.entries:
             date = datetime.datetime(*event.updated_parsed[:6])

dotim/activity/tests/__init__.py

         return parsed
 
 
+def response(file_name, status_code=200):
+    resp = Response()
+    resp.status_code = status_code
+    with open(os.path.join(ROOT, file_name)) as f:
+        resp._content = f.read()
+    return resp
+
+
+def twitter():
+    return EventConfig.objects.create(
+        url='https://twitter.com/statuses/user_timeline/brutasse.json',
+        event_type='twitter',
+    )
+
+
+def github():
+    return EventConfig.objects.create(
+        url='https://github.com/brutasse.atom',
+        username='brutasse',
+        event_type='github',
+    )
+
+
+def delicious():
+    return EventConfig.objects.create(
+        url='http://feeds.delicious.com/v2/rss/brutasse?count=50',
+        event_type='delicious',
+    )
+
+
+def bitbucket():
+    return EventConfig.objects.create(
+        url='https://bitbucket.org/bruno/rss/feed?token=foobarbaz',
+        username='bruno',
+        event_type='bitbucket',
+    )
+
+
+def gitorious():
+    return EventConfig.objects.create(
+        url='http://gitorious.org/wombat.atom',
+        username='brutasse',
+        event_type='gitorious',
+    )
+
+
+def djangosnippets():
+    return EventConfig.objects.create(
+        url='http://djangosnippets.org/feeds/author/brutasse/',
+        event_type='djangosnippets',
+    )
+
+
 class ModelTest(TestCase):
     """Testing the behaviour of the Events logger"""
-    fixtures = ['test_fixtures']
-
     def test_unicode(self):
-        conf = EventConfig.objects.get(pk=1)
-        conf.url = 'http://twitter.com/statuses/user_timeline/brutasse.json'
+        conf = EventConfig(
+            url='http://twitter.com/statuses/user_timeline/brutasse.json',
+            event_type='twitter',
+        )
         self.assertEqual('%s' % conf, 'twitter: brutasse.json')
 
-        conf = EventConfig.objects.get(pk=2)
-        conf.url = 'http://github.com/brutasse.atom'
+        conf = EventConfig(
+            url='http://github.com/brutasse.atom',
+            username='brutasse',
+            event_type='github',
+        )
         self.assertEqual('%s' % conf, 'github: brutasse.atom')
 
     def test_twitter_username(self):
-        conf = EventConfig.objects.get(pk=1)
-        conf.url = 'http://twitter.com/statuses/user_timeline/brutasse.json'
+        conf = EventConfig(
+            url='http://twitter.com/statuses/user_timeline/brutasse.json',
+            event_type='twitter',
+        )
         self.assertEqual(conf.twitter_username, 'brutasse')
 
     @patch('requests.get')
     def test_update_twitter(self, get):
-        conf = EventConfig.objects.get(pk=1)
-        response = Response()
-        response.status_code = 200
-        with open(os.path.join(ROOT, 'twitter.brutasse.json')) as f:
-            response._content = f.read()
-        get.return_value = response
+        conf = twitter()
+        get.return_value = response('twitter.brutasse.json')
         conf.update()
         get.assert_called_with(
             u'https://twitter.com/statuses/user_timeline/brutasse.json',
             Event.objects.filter(title__contains='#europython').exists()
         )
 
-    def test_update_feed(self):
-        """
-        Checking the update of all types of feed works.
-        """
-        # GitHub
-        self._test_feed(2)
+    @patch('requests.get')
+    def test_github(self, get):
+        conf = github()
+        get.return_value = response('github.brutasse.atom')
+        conf.update()
+        self.assertEqual(Event.objects.count(), 35)
 
-        # Del.icio.us
-        self._test_feed(3)
+    @patch('requests.get')
+    def test_delicious(self, get):
+        conf = delicious()
+        get.return_value = response('delicious.brutasse.xml')
+        conf.update()
+        self.assertEqual(Event.objects.count(), 50)
 
-        # Bitbucket
-        self._test_feed(4)
+    @patch('requests.get')
+    def test_bitbucket(self, get):
+        conf = bitbucket()
+        get.return_value = response('bitbucket.bruno.xml')
+        conf.update()
+        self.assertEqual(Event.objects.count(), 9)
 
-        # Gitorious
-        self._test_feed(5)
+    @patch('requests.get')
+    def test_gitorious(self, get):
+        conf = gitorious()
+        get.return_value = response('gitorious.wombat.atom')
+        conf.update()
+        self.assertEqual(Event.objects.count(), 16)
 
-        # Django snippets
-        self._test_feed(6)
+    @patch('requests.get')
+    def test_django_snippets(self, get):
+        conf = djangosnippets()
+        get.return_value = response('djangosnippets.brutasse.xml')
+        conf.update()
+        self.assertEqual(Event.objects.count(), 3)
 
-    def test_filter(self):
-        conf = EventConfig.objects.get(pk=2)
+    @patch('requests.get')
+    def test_filter(self, get):
+        conf = github()
         conf.filters = 'aspirator'
-        conf.save()
-        self._test_feed(2)
+        get.return_value = response('github.brutasse.atom')
+        conf.update()
         self.assertEqual(Event.objects.count(), 27)  # 35 if not filtered
 
     @patch('requests.get')
     def test_error(self, get):
-        get.side_effect
-        conf = EventConfig.objects.get(pk=2)
-        conf.url += 'nostatus'
-        conf.update(feedparser=FakeFeedParser)
+        conf = github()
+        get.return_value = response('github.brutasse.atom', status_code=500)
+        conf.update()
         self.assertEqual(Event.objects.count(), 0)
-
-    def _test_feed(self, id):
-        conf = EventConfig.objects.get(pk=id)
-        conf.update(feedparser=FakeFeedParser)
-        self.assertTrue(Event.objects.filter(
-            event_type=conf.event_type).count() > 2)
+        get.assert_called_with(
+            'https://github.com/brutasse.atom',
+            headers={'User-Agent': 'Dotim/dev (http://bruno.im)'}, timeout=10)
 
 
 class ViewsTest(TestCase):
-    fixtures = ['test_fixtures']
-
-    def setUp(self):
-        for e in EventConfig.objects.filter(pk__gte=2):
-            e.update(feedparser=FakeFeedParser)
+    def update(self, get):
+        for conf, path in (
+            (github(), 'github.brutasse.atom'),
+            # Add more if needed
+        ):
+            get.return_value = response('github.brutasse.atom')
+            conf.update()
 
     def test_index(self):
         url = reverse('activity:page')
         response = self.client.get(url)
         self.assertContains(response, 'Timeline')
 
-    def test_page_2(self):
+    @patch('requests.get')
+    def test_page_2(self, get):
+        self.update(get)
         url = reverse('activity:page', args=[2])
         response = self.client.get(url)
         url = '<a href="%s">' % reverse('activity:page')
         self.assertContains(response, url)
 
-    def test_typed(self):
+    @patch('requests.get')
+    def test_typed(self, get):
+        self.update(get)
         url = reverse('activity:page', args=['github'])
         response = self.client.get(url)
         expected = '<li class="current"><div><a href="%s">Github' % url
         self.assertContains(response, expected)
 
-    def test_typed_page_2(self):
+    @patch('requests.get')
+    def test_typed_page_2(self, get):
+        self.update(get)
         url = reverse('activity:page', args=['github', 2])
         response = self.client.get(url)
         self.assertEqual(response.status_code, 200)

dotim/test_settings.py

 
 SECRET_KEY = 'test secret key'
 
+TESTS = True
+
 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.