bump version to 1.10
[mygpoclient.git] / mygpoclient / json_test.py
bloba8a370a1f644085301de4afcdae214fe3374e603
1 # -*- coding: utf-8 -*-
2 # gpodder.net API Client
3 # Copyright (C) 2009-2013 Thomas Perl and the gPodder Team
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 try:
19 # Python 3
20 from io import BytesIO
21 from urllib import request
23 except ImportError:
24 # Python 2
25 from StringIO import StringIO as BytesIO
26 import urllib2 as request
28 from mygpoclient import json
30 import unittest
31 import minimock
34 def fqname(o):
35 return o.__module__ + "." + o.__name__
38 class Test_JsonClient(unittest.TestCase):
39 PORT = 9876
40 URI_BASE = 'http://localhost:%(PORT)d' % locals()
41 USERNAME = 'john'
42 PASSWORD = 'secret'
44 @classmethod
45 def setUpClass(cls):
46 cls.odName = fqname(request.OpenerDirector)
47 cls.boName = fqname(request.build_opener)
49 def setUp(self):
50 self.mockopener = minimock.Mock(self.odName)
51 request.build_opener = minimock.Mock(self.boName)
52 request.build_opener.mock_returns = self.mockopener
54 def tearDown(self):
55 minimock.restore()
57 def mock_setHttpResponse(self, value):
58 self.mockopener.open.mock_returns = BytesIO(value)
60 def test_parseResponse_worksWithDictionary(self):
61 client = json.JsonClient(self.USERNAME, self.PASSWORD)
62 self.mock_setHttpResponse(b'{"a": "B", "c": "D"}')
63 items = list(sorted(client.GET(self.URI_BASE + '/').items()))
64 self.assertEqual(items, [('a', 'B'), ('c', 'D')])
66 def test_parseResponse_worksWithIntegerList(self):
67 client = json.JsonClient(self.USERNAME, self.PASSWORD)
68 self.mock_setHttpResponse(b'[1,2,3,6,7]')
69 self.assertEqual(client.GET(self.URI_BASE + '/'), [1, 2, 3, 6, 7])
71 def test_parseResponse_emptyString_returnsNone(self):
72 client = json.JsonClient(self.USERNAME, self.PASSWORD)
73 self.mock_setHttpResponse(b'')
74 self.assertEqual(client.GET(self.URI_BASE + '/'), None)
76 def test_invalidContent_raisesJsonException(self):
77 client = json.JsonClient(self.USERNAME, self.PASSWORD)
78 self.mock_setHttpResponse(b'this is not a valid json string')
79 self.assertRaises(json.JsonException, client.GET, self.URI_BASE + '/')