.. currentmodule:: kcrw.nprapi Tests for :class:`StoryMapping` ------------------------------- This is a comprehensive set of unit tests for the :mod:`kcrw.nprapi` class:`StoryMapping` class. Let's create an instance of the :class:`StoryMapping` class and see how it works:: >>> from kcrw.nprapi import StoryMapping >>> api = StoryMapping('MY_KEY') The :class:`StoryMapping` instance starts out with some default values for its various properties:: >>> api.version '' >>> api.title '' >>> api.description '' >>> api.data {} >>> api.stories [] In order to make this a properly isolated unit test, we need to isolate our code from :class:`StoryAPI` instance the :class:`StoryMapping` class depends on. Fortunately, we have a mock :class:`StoryAPI` class, :class:`mocks.MockStoryAPI`, we can substitute in for this purpose:: >>> from kcrw.nprapi.mocks import MockStoryAPI >>> api.story_api = MockStoryAPI(api.story_api.api_key, api.story_api.output_format) Now we can make requests without worrying about connecting to the NPR service. Let's look at the URL that was generated by the query method, by looking at our custom opener:: >>> result = api.query(1) >>> result [{u'link': {u'api': u'http://...', u'html': u'http://...'}, u'id': u'1234567', u'title': u'Some other title'}, {u'link': {u'api': u'http://...', u'html': u'http://...'}, u'id': u'3456789', u'title': u'Some other title'}] >>> api.stories == result True >>> api.data {u'version': u'0.93', u'list': {u'teaser': u'More Test Data', u'story': [{u'link': {u'api': u'http://...', u'html': u'http://...'}, u'id': u'1234567', u'title': u'Some other title'}, {u'link': {u'api': u'http://...', u'html': u'http://...'}, u'id': u'3456789', u'title': u'Some other title'}], u'title': u'Test Data'}} >>> api.version u'0.93' >>> api.title u'Test Data' >>> api.description u'More Test Data' Look at :const:`mocks.MOCK_RESPONSES` to see where this data is coming from and how it is being transformed. Any NPR service errors will be re-raised: >>> api.query('error') Traceback (most recent call last): ... NPRError: XXX - Some Error!! The :class:`StoryMapping` class takes another argument that allows you to get the raw json structure, rather than the slightly cleaned up structure returned by default:: >>> api2 = StoryMapping('MY_KEY', prune_text_nodes=False) >>> api2.story_api = api.story_api Let's see how this alters the result: >>> result2 = api2.query([1]) >>> result2 == result False >>> result[0]['title'] u'Some other title' >>> result2[0]['title'] {u'$text': u'Some other title'} >>> api2.data['list']['title'] {u'$text': u'Test Data'} >>> api2.title == api.title True >>> api2.description == api.description True >>> api2.stories == api.stories False >>> api2.stories == result2 True