Commits

Bohdan Rybak committed 32d6dcf

AniDb api anime info lookup

Comments (0)

Files changed (2)

 import re
 import urllib2
 from datetime import datetime
+from StringIO import StringIO
 
 from xml.etree import ElementTree
 
                 for name in anime.findall('title'):
                     if name.text.lower() == title.lower():
                         return int(anime.attrib['aid'])
+
+class AniDbApi(object):
+    _url = 'http://api.anidb.net:9001/httpapi?request=anime&client=%s&clientver=%d&protover=1'
+
+    def __init__(self, client, clientver):
+        self._apiurl = self._url % (client, clientver)
+
+    def get_anime_info(self, anime_id):
+        u = urllib2.urlopen(self._apiurl + '&aid=%d' %(anime_id,))
+
+        # Gunzipping
+        buf = StringIO(u.read())
+        with gzip.GzipFile(fileobj=buf) as f:
+            xml = f.read()
+
+        return ElementTree.fromstring(xml)

tests/anidb_test.py

 import tempfile
 import os
 import datetime
+from xml.etree import ElementTree
+from StringIO import StringIO
+
 import gzip
 
 import anidb
 
+def get_stream_mock(data):
+        stream_mock = mock.MagicMock(spec=file)
+        stream_mock.read.return_value = data
+        return stream_mock
 
 class DbDumpTestCase(unittest.TestCase):
     def setUp(self):
     def tearDown(self):
         os.unlink(self._tfile)
 
-    def get_stream_mock(self, data):
-        stream_mock = mock.MagicMock(spec=file)
-        stream_mock.read.return_value = data
-        return stream_mock
-
     def test_update(self):
         data = 'TEST'
 
         with mock.patch('urllib2.urlopen') as mock_urlopen:
-            mock_urlopen.return_value = self.get_stream_mock(data)
+            mock_urlopen.return_value = get_stream_mock(data)
 
             self.db.update()
 
         # Nisemonogatari id is 8658
         _id = self.db.search('Nisemonogatari')
         self.assertEqual(_id, 8658)
+
+class AniDbApiTestCase(unittest.TestCase):
+    def setUp(self):
+        self.api = anidb.AniDbApi('ongohell', 1)
+
+    def test_get_anime_info(self):
+        data = '''<anime id="8658">
+                  </anime>'''
+        # Gzipping data
+        strio = StringIO()
+        with gzip.GzipFile(fileobj=strio, mode='wb') as f:
+             f.write(data)
+
+        zdata = strio.getvalue()
+
+        with mock.patch('urllib2.urlopen') as mock_urlopen:
+            mock_urlopen.return_value = get_stream_mock(zdata)
+
+            vanillaXML = ElementTree.tostring(ElementTree.fromstring(data))
+            apiXML = ElementTree.tostring(self.api.get_anime_info(1))
+            self.assertEqual(apiXML, vanillaXML)