class TestObswatch(unittest.TestCase): # nose knows about setUpClass, but python 2.6's unittest doesn't # @classmethod # def setUpClass(cls): def setUp(self): repo = Mock('repo') repo.name = 'standard' repo.arch = 'x86_64' package = Mock('package') package.project = 'openSUSE:11.3' package.name = 'osc' self.build = obswatch.Build(package=package, repo=repo, interested={'geeko':'*****@*****.**'}) self.package = package self.tt = TraceTracker() obswatch.SLEEP_TIME = 0 def tearDown(self): minimock.restore() self.tt.clear() def test_get_latest_packages(self): mock('obswatch.http_GET', tracker=self.tt, returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?> <latest_added> <package created="2010-09-09T14:03:06+02:00" name="antivir" project="home:varkoly:branches:openSUSE:11.3:NonFree"/> <project created="2010-09-09T14:03:05+02:00" name="home:varkoly:branches:openSUSE:11.3:NonFree"/> <package created="2010-09-09T13:50:37+02:00" name="test9" project="home:enzokiel:test"/> <package created="2010-09-09T13:12:54+02:00" name="kernel-bfs-source" project="home:jingtw"/> <package created="2010-09-09T13:12:08+02:00" name="getdata" project="home:christiantrippe:branches:KDE:Distro:Factory"/> <package created="2010-09-09T13:05:13+02:00" name="perl-String-CRC32" project="home:seife:byd"/> <package created="2010-09-09T13:05:04+02:00" name="autogen" project="home:psmt:branches:Base:System"/> </latest_added>''')) result = obswatch.get_latest_packages(7) assert_same_trace(self.tt,"""Called obswatch.http_GET( '%sstatistics/latest_updated?limit=7')""" % obswatch.APIURL) for p in result: self.assertTrue(isinstance(p, obswatch.Package)) self.assertEqual(result[0].name, 'antivir') self.assertEqual(len(result), 6) # second one is a project def test_get_user_email(self): mock('obswatch.http_GET', tracker=self.tt, returns=StringIO('''<person> <login>Geeko</login> <email>[email protected]</email> <realname>Geeko Chameleon</realname> <watchlist/> </person>''')) result = obswatch.get_user_email('Geeko') assert_same_trace(self.tt, """Called obswatch.http_GET( '%sperson/Geeko')""" % obswatch.APIURL) self.assertEqual(result, '*****@*****.**') def test_users_from_url(self): mock('obswatch.http_GET', tracker=self.tt, returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?> <project name="superkde" created="2005-01-01T00:00:02+01:00" updated="2007-01-19T10:44:45+01:00"> <title>SuperKDE</title> <description>SuperKDE is a heavily tuned version of KDE.</description> <link project="openSUSE:11.2:Update" /> <link project="openSUSE:11.2" /> <person role="maintainer" userid="Geeko"/> <person role="maintainer" userid="BrownGeeko"/> <group role="reviewer" groupid="release_team"/> <build> <disable /> </build> <repository name="kde4:factory" rebuild="transitive"> <path project="kde4" repository="factory"/> <arch>i386</arch> <arch>x86_64</arch> </repository> </project>''')) mock('obswatch.get_user_email', returns='*****@*****.**') result = obswatch.get_users_from_url('%ssource/superkde/_meta' % obswatch.APIURL) assert_same_trace(self.tt, """Called obswatch.http_GET( '%ssource/superkde/_meta')""" % obswatch.APIURL) self.assertEqual(len(result), 2) self.assertEqual(result['Geeko'], '*****@*****.**') self.assertEqual(result['BrownGeeko'], '*****@*****.**') def test_get_builds(self): mock('osc.core.http_GET', tracker=self.tt, returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?> <project name="superkde" created="2005-01-01T00:00:02+01:00" updated="2007-01-19T10:44:45+01:00"> <title>SuperKDE</title> <description>SuperKDE is a heavily tuned version of KDE.</description> <link project="openSUSE:11.2:Update" /> <link project="openSUSE:11.2" /> <person role="maintainer" userid="ernie"/> <group role="reviewer" groupid="release_team"/> <build> <disable /> </build> <useforbuild> <disable /> </useforbuild> <repository name="kde4:factory" rebuild="transitive"> <path project="kde4" repository="factory"/> <arch>i386</arch> <arch>x86_64</arch> </repository> <repository name="suselinux-9.3"> <path project="suselinux-9.3" repository="standard"/> <arch>i386</arch> </repository> <repository name="gnomespecial" rebuild="local"> <path project="gnome3" repository="suselinux-9.3"/> <path project="suselinux-9.3" repository="standard"/> <arch>i386</arch> </repository> </project>''')) # source/superkde/_meta # gets called by osc.core.get_repos_of_project mock('obswatch.get_interested', returns={'Geeko': '*****@*****.**'}) superkde = Mock('package') superkde.name = 'superkde' superkde.project = 'superkde' superkde.created = '2007-01-19T10:44:45+01:00' result = obswatch.get_builds(superkde) assert_same_trace(self.tt, """Called osc.core.http_GET( '%ssource/superkde/_meta')""" % obswatch.APIURL) def test_build_get_remote_status(self): mock('obswatch.http_GET', tracker=self.tt, returns=StringIO('''<status package="osc" code="disabled"> <details></details> </status>''')) code = self.build.get_remote_status() assert_same_trace(self.tt, """Called obswatch.http_GET( '%sbuild/openSUSE:11.3/standard/x86_64/osc/_status')""" % obswatch.APIURL) self.assertEqual(code, 'disabled') def test_process_same_status(self): self.build.get_remote_status = lambda : self.build.status result = obswatch.process_build(self.build) self.assertTrue(result) def test_process_intermediate(self): self.build.get_remote_status = lambda : 'building' result = obswatch.process_build(self.build) self.assertTrue(result) self.assertEqual(self.build.status, 'building') def test_process_other(self): self.build.get_remote_status = lambda : 'excluded' result = obswatch.process_build(self.build) self.assertFalse(result) def test_process_unknown(self): self.build.get_remote_status = lambda : 'infundibulated' self.assertRaises(Exception, obswatch.process_build, self.build) def test_process_final_not_succeeded(self): self.build.get_remote_status = lambda : 'failed' result = obswatch.process_build(self.build) self.assertFalse(result) def test_final_succeeded(self): self.build.get_remote_status = lambda : 'succeeded' mock('obswatch.Build.get_binaries', returns={'foo':'bar'}) mock('obswatch.send_email', tracker=self.tt) result = obswatch.process_build(self.build) self.assertFalse(result) expected_output = """Called obswatch.send_email( 'geeko', '*****@*****.**', <obswatch.Build instance at ...>, {'foo': 'bar'})""" assert_same_trace(self.tt, expected_output) def test_interested(self): mock('obswatch.get_users_from_url', returns_func=lambda url: {url: url}) result = obswatch.get_interested(self.package) # both the project and package page should be checked for users self.assertEqual(result, {'https://api.opensuse.org/source/openSUSE:11.3/_meta': 'https://api.opensuse.org/source/openSUSE:11.3/_meta', 'https://api.opensuse.org/source/openSUSE:11.3/osc/_meta': 'https://api.opensuse.org/source/openSUSE:11.3/osc/_meta'}) def test_send_email(self): mock('smtplib.SMTP', returns=Mock('smtp_connection', tracker=self.tt), tracker=self.tt) obswatch.send_email('geeko', '*****@*****.**', 'yourpackage', {'rpm1': 'http://opensuse.org/rpm1', 'rpm2': 'http://opensuse.org/rpm2'}) expected_output = """Called smtplib.SMTP('localhost') Called smtp_connection.sendmail( '*****@*****.**', ['*****@*****.**'], 'To: [email protected]\\nFrom: [email protected]\\nSubject: (osc) build succeeded: yourpackage\\n\\nThe package yourpackage has finished building and can now be downloaded from:\\nrpm1 - http://opensuse.org/rpm1\\nrpm2 - http://opensuse.org/rpm2') Called smtp_connection.quit() """ assert_same_trace(self.tt, expected_output)
class TestPyblr: def setUp(self): self.api_key = "consumer key" self.consumer = oauth.Consumer(self.api_key, "consumer secret") self.access_token = oauth.Token("oauth token", "oauth token secret") self.client = pyblr.Pyblr( oauth.Client(self.consumer, self.access_token)) self.params = {"name": "toqoz", "sex": "male"} self.parsed_params = "name=toqoz&sex=male" self.trackar = TraceTracker() mock("pyblr.Pyblr.get", tracker=self.trackar) mock("pyblr.Pyblr.post", tracker=self.trackar) def assert_not_raise(self, excClass, callable_, *args, **kwargs): try: callable_(*args, **kwargs) except excClass: if hasattr(excClass, "__name__"): excName = excClass.__name__ else: excName = str(excClass) message = "Against the expectationm Raised %s" % (excClass) raise AssertionError(message) def create_response(self, status, msg): result = ({}, json.dumps({ "meta": { "status": status, "msg": msg }, "response": {} })) return result # when assert_same_trace # required space between colon(:) and value in dict # [use this two times or more in same method] required call trackar.clear() def info_test(self): self.client.info("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/info', %s) """ % ({ 'api_key': self.api_key })) def followers_test(self): self.client.followers("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s) """ % ({})) self.trackar.clear() self.client.followers("toqoz.tumblr.com", {"limit": 10}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s) """ % ({ 'limit': 10 })) def posts_test(self): self.client.posts("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s) """ % ({ 'api_key': self.api_key })) self.trackar.clear() self.client.posts("toqoz.tumblr.com", {"type": "photo"}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s) """ % ({ 'api_key': self.api_key, 'type': 'photo' })) def queue_test(self): self.client.queue("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/queue', %s) """ % ({})) def draft_test(self): self.client.draft("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/draft', %s) """ % ({})) def submission_test(self): self.client.submission("toqoz.tumblr.com") assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/submission', %s) """ % ({})) def create_post_test(self): self.client.create_post("toqoz.tumblr.com", { 'type': 'text', 'body': 'text' }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ "type": "text", "body": "text" })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { "type": "photo", "source": "http://example.com/photo.png" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ 'type': 'photo', 'source': 'http://example.com/photo.png' })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { "type": "quote", "quote": "quote" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ 'type': 'quote', 'quote': 'quote' })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { 'type': 'like', 'url': 'http://example.com/' }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ 'type': 'like', 'url': 'http://example.com/' })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { "type": "chat", "conversation": "conversation" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ 'type': 'chat', 'conversation': 'conversation' })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { "type": "audio", "external_url": "http://example.com/audio.mp3" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ 'type': 'audio', 'external_url': 'http://example.com/audio.mp3' })) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", { "type": "video", "embed": "<embed>code</embed>" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({ "type": "video", "embed": "<embed>code</embed>" })) def edit_post_test(self): self.client.edit_post("toqoz.tumblr.com", { "id": 123456789, "type": "text", "body": "new text" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/edit', %s) """ % ({ "id": 123456789, "type": "text", "body": "new text" })) def reblog_post_test(self): self.client.reblog_post("toqoz.tumblr.com", { "id": 123456789, "reblog_key": "adcdefg" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s) """ % ({ "id": 123456789, "reblog_key": "adcdefg" })) self.trackar.clear() self.client.reblog_post("toqoz.tumblr.com", { "id": 123456789, "reblog_key": "adcdefg", "comment": "comment" }) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s) """ % ({ "id": 123456789, "reblog_key": "adcdefg", "comment": "comment" })) def delete_post_test(self): self.client.delete_post("toqoz.tumblr.com", {"id": 123456789}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/delete', %s) """ % ({ "id": 123456789 })) def dashboard_test(self): self.client.dashboard() assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/dashboard', %s) """ % ({})) self.trackar.clear() self.client.dashboard({"type": "photo"}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/dashboard', %s) """ % ({ "type": "photo" })) def likes_test(self): self.client.likes() assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/likes', %s) """ % ({})) self.trackar.clear() self.client.likes({"limit": 10}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/likes', %s) """ % ({ "limit": 10 })) def following_test(self): self.client.following() assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/following', %s) """ % ({})) self.trackar.clear() self.client.following({"limit": 10}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/following', %s) """ % ({ "limit": 10 })) def follow_test(self): self.client.follow({"url": "toqoz.tumblr.com"}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/user/follow', %s) """ % ({ "url": "toqoz.tumblr.com" })) def unfollow_test(self): self.client.unfollow({"url": "toqoz.tumblr.com"}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.post('/v2/user/unfollow', %s) """ % ({ "url": "toqoz.tumblr.com" })) def info_user_test(self): self.client.info_user({}) assert_same_trace( self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/info', %s) """ % ({})) def parse_params_test(self): assert_equals(self.client.parse_params(self.params), self.parsed_params) def APIError_test(self): self.assert_not_raise( pyblr.APIError, lambda: self.client.parse_response( self.create_response("200", "OK"))) self.assert_not_raise( pyblr.APIError, lambda: self.client.parse_response( self.create_response("300", "Found"))) assert_raises( pyblr.APIError, lambda: self.client.parse_response( self.create_response("401", "Not Authorized"))) assert_raises( pyblr.APIError, lambda: self.client.parse_response( self.create_response("404", "Not Found")))
class TestMediaMosaResource(unittest.TestCase): """Tests the generic functionality of a MediaMosaResource. This is done using the Asset object as concrete implementation. """ def setUp(self): self.api = MediaMosaAPI('http://video.example.com') self.tt = TraceTracker() mock('self.api.session', tracker=self.tt) self.response = Mock('requests.Response') self.response.status_code = 200 self.api.session.get.mock_returns = self.response self.item_dict = { u'provider_id': '', u'is_unappropriate': u'FALSE', u'videotimestampmodified': u'2012-07-05 11:34:35', u'app_id': u'2', u'is_favorite': u'FALSE', u'has_streamable_mediafiles': u'TRUE', u'viewed': u'4', u'asset_id': u'g1QkoSmSeHdWfGkMKlOlldLn', u'ega_still_url': '', u'granted': u'TRUE', u'played': u'1', u'mediafile_duration': u'00:00:52.20', # u'videotimestamp': u'2012-07-05 11:34:01', # cleared it for partial u'vpx_still_url': u'http://filvideod.ugent.be/media/17/Z/Z14cWALWKmfTRjTUKhhQQLv2.jpeg', u'owner_id': u'krkeppen', u'is_empty_asset': u'FALSE', u'play_restriction_end': '', u'asset_property_is_hidden': u'FALSE', u'dublin_core': {u'publisher': u'Kristof Keppens', u'rights': u'Kristof Keppens', u'description': u'test', u'language': u'nl', u'creator': u'Kristof Keppens', u'format': u'streaming video', u'coverage_spatial': '', u'date': '', u'relation': '', u'source': u'ugent', u'contributor': u', ', u'title': u'test sintel 2', u'identifier': '', u'type': u'video', u'coverage_temporal': '', u'subject': u'test'}, u'reference_id': '', u'isprivate': u'TRUE', u'qualified_dublin_core': {u'isformatof': '', u'description_abstract': '', u'license': '', u'created': '', u'issued': '', u'rightsholder': '', u'hasformat': '', u'title_alternative': '', u'format_medium': '', u'format_extent': '', u'isreferencedby': ''}, u'mediafile_container_type': u'matroska;webm', u'is_unappropiate': u'FALSE', u'is_external': u'FALSE', u'is_protected': u'FALSE', u'play_restriction_start': '', u'group_id': ''} # _mmmeta.state def test_create_empty_asset(self): """Tests if an empty asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn') self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.EMPTY) def test_create_partial_asset(self): """Tests if a partially pre-filled asset can be created""" a = Asset.fromdict(self.item_dict) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.PARTIAL) def test_create_full_asset(self): """Tests if an fully pre-filled asset can be created""" a = Asset.fromdict(self.item_dict, full=True) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.FULL) # _mmmeta.api def test_create_connected_asset(self): """Tests if a connected asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn', api=self.api) self.assertTrue(a.is_connected()) def test_create_unconnected_asset(self): """Tests if an unconnected asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn') self.assertFalse(a.is_connected()) # accessing supplied data def test_can_access_asset_data(self): """Tests if pre-filled data can be accessed""" a = Asset.fromdict(self.item_dict) self.assertEquals(a.asset_id, 'g1QkoSmSeHdWfGkMKlOlldLn') self.assertIsInstance(a.is_favorite, bool) self.assertIsInstance(a.videotimestampmodified, datetime.datetime) self.assertRaises(Exception, a.some_unexisting_attribute) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.PARTIAL) # accessing unsupplied data def test_accessing_empty_asset(self): """Tests if an empty asset will automatically fill itself if queried""" # setup self.response.content = open('tests/data/get_asset_id_response.xml')\ .read() # test asset = Asset('g1QkoSmSeHdWfGkMKlOlldLn', api=self.api) # validate self.assertIsInstance(asset.is_favorite, bool) self.assertNotEquals(self.tt.dump(), '') self.tt.clear() self.assertIsInstance(asset.videotimestamp, datetime.datetime) self.assertEquals(self.tt.dump(), '') self.assertRaises(Exception, asset.some_unexisting_attribute) self.assertEqual(asset._mmmeta.state, MediaMosaResource.STATE.FULL) def test_accessing_partial_asset(self): """Tests if a partial asset will automatically fill itself if queried""" # setup self.response.content = open('tests/data/get_asset_id_response.xml')\ .read() # test asset = Asset.fromdict(self.item_dict, api=self.api, full=False) # validate self.assertIsInstance(asset.is_favorite, bool) self.assertEquals(self.tt.dump(), '') self.assertIsInstance(asset.videotimestamp, datetime.datetime) self.assertNotEquals(self.tt.dump(), '') self.assertRaises(Exception, asset.some_unexisting_attribute) self.assertEqual(asset._mmmeta.state, MediaMosaResource.STATE.FULL)
class TestMediaMosaResource(unittest.TestCase): """Tests the generic functionality of a MediaMosaResource. This is done using the Asset object as concrete implementation. """ def setUp(self): self.api = MediaMosaAPI('http://video.example.com') self.tt = TraceTracker() mock('self.api.session', tracker=self.tt) self.response = Mock('requests.Response') self.response.status_code = 200 self.api.session.get.mock_returns = self.response self.item_dict = { u'provider_id': '', u'is_unappropriate': u'FALSE', u'videotimestampmodified': u'2012-07-05 11:34:35', u'app_id': u'2', u'is_favorite': u'FALSE', u'has_streamable_mediafiles': u'TRUE', u'viewed': u'4', u'asset_id': u'g1QkoSmSeHdWfGkMKlOlldLn', u'ega_still_url': '', u'granted': u'TRUE', u'played': u'1', u'mediafile_duration': u'00:00:52.20', # u'videotimestamp': u'2012-07-05 11:34:01', # cleared it for partial u'vpx_still_url': u'http://filvideod.ugent.be/media/17/Z/Z14cWALWKmfTRjTUKhhQQLv2.jpeg', u'owner_id': u'krkeppen', u'is_empty_asset': u'FALSE', u'play_restriction_end': '', u'asset_property_is_hidden': u'FALSE', u'dublin_core': { u'publisher': u'Kristof Keppens', u'rights': u'Kristof Keppens', u'description': u'test', u'language': u'nl', u'creator': u'Kristof Keppens', u'format': u'streaming video', u'coverage_spatial': '', u'date': '', u'relation': '', u'source': u'ugent', u'contributor': u', ', u'title': u'test sintel 2', u'identifier': '', u'type': u'video', u'coverage_temporal': '', u'subject': u'test' }, u'reference_id': '', u'isprivate': u'TRUE', u'qualified_dublin_core': { u'isformatof': '', u'description_abstract': '', u'license': '', u'created': '', u'issued': '', u'rightsholder': '', u'hasformat': '', u'title_alternative': '', u'format_medium': '', u'format_extent': '', u'isreferencedby': '' }, u'mediafile_container_type': u'matroska;webm', u'is_unappropiate': u'FALSE', u'is_external': u'FALSE', u'is_protected': u'FALSE', u'play_restriction_start': '', u'group_id': '' } # _mmmeta.state def test_create_empty_asset(self): """Tests if an empty asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn') self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.EMPTY) def test_create_partial_asset(self): """Tests if a partially pre-filled asset can be created""" a = Asset.fromdict(self.item_dict) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.PARTIAL) def test_create_full_asset(self): """Tests if an fully pre-filled asset can be created""" a = Asset.fromdict(self.item_dict, full=True) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.FULL) # _mmmeta.api def test_create_connected_asset(self): """Tests if a connected asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn', api=self.api) self.assertTrue(a.is_connected()) def test_create_unconnected_asset(self): """Tests if an unconnected asset can be created""" a = Asset('g1QkoSmSeHdWfGkMKlOlldLn') self.assertFalse(a.is_connected()) # accessing supplied data def test_can_access_asset_data(self): """Tests if pre-filled data can be accessed""" a = Asset.fromdict(self.item_dict) self.assertEquals(a.asset_id, 'g1QkoSmSeHdWfGkMKlOlldLn') self.assertIsInstance(a.is_favorite, bool) self.assertIsInstance(a.videotimestampmodified, datetime.datetime) self.assertRaises(Exception, a.some_unexisting_attribute) self.assertEqual(a._mmmeta.state, MediaMosaResource.STATE.PARTIAL) # accessing unsupplied data def test_accessing_empty_asset(self): """Tests if an empty asset will automatically fill itself if queried""" # setup self.response.content = open('tests/data/get_asset_id_response.xml')\ .read() # test asset = Asset('g1QkoSmSeHdWfGkMKlOlldLn', api=self.api) # validate self.assertIsInstance(asset.is_favorite, bool) self.assertNotEquals(self.tt.dump(), '') self.tt.clear() self.assertIsInstance(asset.videotimestamp, datetime.datetime) self.assertEquals(self.tt.dump(), '') self.assertRaises(Exception, asset.some_unexisting_attribute) self.assertEqual(asset._mmmeta.state, MediaMosaResource.STATE.FULL) def test_accessing_partial_asset(self): """Tests if a partial asset will automatically fill itself if queried""" # setup self.response.content = open('tests/data/get_asset_id_response.xml')\ .read() # test asset = Asset.fromdict(self.item_dict, api=self.api, full=False) # validate self.assertIsInstance(asset.is_favorite, bool) self.assertEquals(self.tt.dump(), '') self.assertIsInstance(asset.videotimestamp, datetime.datetime) self.assertNotEquals(self.tt.dump(), '') self.assertRaises(Exception, asset.some_unexisting_attribute) self.assertEqual(asset._mmmeta.state, MediaMosaResource.STATE.FULL)
class TestPyblr: def setUp(self): self.api_key = "consumer key" self.consumer = oauth.Consumer(self.api_key, "consumer secret") self.access_token = oauth.Token("oauth token", "oauth token secret") self.client = pyblr.Pyblr(oauth.Client(self.consumer, self.access_token)) self.params = { "name": "toqoz", "sex": "male" } self.parsed_params = "name=toqoz&sex=male" self.trackar = TraceTracker() mock("pyblr.Pyblr.get", tracker=self.trackar) mock("pyblr.Pyblr.post", tracker=self.trackar) def assert_not_raise(self, excClass, callable_, *args, **kwargs): try: callable_(*args, **kwargs) except excClass: if hasattr(excClass,"__name__"): excName = excClass.__name__ else: excName = str(excClass) message = "Against the expectationm Raised %s" % (excClass) raise AssertionError(message) def create_response(self, status, msg): result = ( {}, json.dumps({ "meta": { "status": status, "msg": msg }, "response": {} }) ) return result # when assert_same_trace # required space between colon(:) and value in dict # [use this two times or more in same method] required call trackar.clear() def info_test(self): self.client.info("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/info', %s) """ % ({'api_key': self.api_key})) def followers_test(self): self.client.followers("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s) """ % ({})) self.trackar.clear() self.client.followers("toqoz.tumblr.com", {"limit": 10}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/followers', %s) """ % ({'limit': 10})) def posts_test(self): self.client.posts("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s) """ % ({'api_key': self.api_key})) self.trackar.clear() self.client.posts("toqoz.tumblr.com", {"type": "photo"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts', %s) """ % ({'api_key': self.api_key, 'type': 'photo'})) def queue_test(self): self.client.queue("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/queue', %s) """ % ({})) def draft_test(self): self.client.draft("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/draft', %s) """ % ({})) def submission_test(self): self.client.submission("toqoz.tumblr.com") assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/blog/toqoz.tumblr.com/posts/submission', %s) """ %({})) def create_post_test(self): self.client.create_post("toqoz.tumblr.com", {'type': 'text', 'body': 'text'}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({"type": "text", "body": "text"})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {"type": "photo", "source": "http://example.com/photo.png"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({'type': 'photo', 'source': 'http://example.com/photo.png'})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {"type": "quote", "quote": "quote"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({'type': 'quote', 'quote': 'quote'})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {'type': 'like', 'url': 'http://example.com/'}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({'type': 'like', 'url': 'http://example.com/'})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {"type": "chat", "conversation": "conversation"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({'type': 'chat', 'conversation': 'conversation'})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {"type": "audio", "external_url": "http://example.com/audio.mp3"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({'type': 'audio', 'external_url': 'http://example.com/audio.mp3'})) self.trackar.clear() self.client.create_post("toqoz.tumblr.com", {"type": "video", "embed": "<embed>code</embed>"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post', %s) """ % ({"type": "video", "embed": "<embed>code</embed>"})) def edit_post_test(self): self.client.edit_post("toqoz.tumblr.com", {"id": 123456789, "type": "text", "body": "new text"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/edit', %s) """ % ({"id": 123456789, "type": "text", "body": "new text"})) def reblog_post_test(self): self.client.reblog_post("toqoz.tumblr.com", {"id": 123456789, "reblog_key": "adcdefg"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s) """ % ({"id": 123456789, "reblog_key": "adcdefg"})) self.trackar.clear() self.client.reblog_post("toqoz.tumblr.com", {"id": 123456789, "reblog_key": "adcdefg", "comment": "comment"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/reblog', %s) """ % ({"id": 123456789, "reblog_key": "adcdefg", "comment": "comment"})) def delete_post_test(self): self.client.delete_post("toqoz.tumblr.com", {"id": 123456789}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/blog/toqoz.tumblr.com/post/delete', %s) """ % ({"id": 123456789})) def dashboard_test(self): self.client.dashboard() assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/dashboard', %s) """ % ({})) self.trackar.clear() self.client.dashboard({"type": "photo"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/dashboard', %s) """ % ({"type": "photo"})) def likes_test(self): self.client.likes() assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/likes', %s) """ % ({})) self.trackar.clear() self.client.likes({"limit": 10}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/likes', %s) """ % ({"limit": 10})) def following_test(self): self.client.following() assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/following', %s) """ % ({})) self.trackar.clear() self.client.following({"limit": 10}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/following', %s) """ % ({"limit": 10})) def follow_test(self): self.client.follow({"url": "toqoz.tumblr.com"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/user/follow', %s) """ % ({"url": "toqoz.tumblr.com"})) def unfollow_test(self): self.client.unfollow({"url": "toqoz.tumblr.com"}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.post('/v2/user/unfollow', %s) """ % ({"url": "toqoz.tumblr.com"})) def info_user_test(self): self.client.info_user({}) assert_same_trace(self.trackar, """\ Called pyblr.Pyblr.get('/v2/user/info', %s) """ % ({})) def parse_params_test(self): assert_equals(self.client.parse_params(self.params), self.parsed_params) def APIError_test(self): self.assert_not_raise(pyblr.APIError, lambda: self.client.parse_response(self.create_response("200", "OK"))) self.assert_not_raise(pyblr.APIError, lambda: self.client.parse_response(self.create_response("300", "Found"))) assert_raises(pyblr.APIError, lambda: self.client.parse_response(self.create_response("401", "Not Authorized"))) assert_raises(pyblr.APIError, lambda: self.client.parse_response(self.create_response("404", "Not Found")))