def main(): LOGGER.info('-- Run started') ### Step 1: Get the text forecasts from the NOAA JSON API json_url = 'http://forecast.weather.gov/MapClick.php?FcstType=json' json_url += '&lat=%.2f&lon=%.2f' % (LAT, LNG) json_parser = ForecastJSONParser(LOGGER) json_data = json_parser.fetch_api_json(json_url) try: text_forecasts = json_parser.parse_forecasts(json_data) LOGGER.debug('JSON text forecasts loaded successfully') LOGGER.debug('Number of text forecasts parsed: %d', len(text_forecasts)) except ForecastParserException, exception: LOGGER.critical(exception) sys.exit()
def setUp(self): with open('forecast_good.json') as f: self.good_json_response = f.read() self.json_parser = ForecastJSONParser()
class TestJSONForecast(unittest.TestCase): def setUp(self): with open('forecast_good.json') as f: self.good_json_response = f.read() self.json_parser = ForecastJSONParser() def test_bad_json(self): """ Test the parsing of bad json """ # Make sure we get back an error when parsing bad JSON self.assertRaises(ForecastParserException, self.json_parser.parse_forecasts, 'this is not JSON') # Test for unequal period names and text values unbalanced_json = json.loads(self.good_json_response) unbalanced_json['time']['startPeriodName'].pop(0) unbalanced_json_response = json.dumps(unbalanced_json) self.assertRaises(ForecastParserException, self.json_parser.parse_forecasts, unbalanced_json_response) # Test for missing keys by corrupting the JSON bad_json = json.loads(self.good_json_response) bad_json['data']['text'].pop() bad_json_response = json.dumps(bad_json) self.assertRaises(ForecastParserException, self.json_parser.parse_forecasts, unbalanced_json_response) def test_good_json(self): """ Test the parsing of good forecasts """ forecasts = self.json_parser.parse_forecasts(self.good_json_response) # There should always be 4 forecasts self.assertEqual(len(forecasts), 4) # Ensure we got the correct period names self.assertEqual(forecasts[0].period, 'Tonight') self.assertEqual(forecasts[1].period, 'Tuesday') self.assertEqual(forecasts[2].period, 'Tuesday Night') self.assertEqual(forecasts[3].period, 'Wednesday') # Ensure that we got the correct text self.assertEqual(forecasts[0].text[0:25], 'A chance of snow showers ') self.assertEqual(forecasts[1].text[0:25], 'A chance of flurries, wit') self.assertEqual(forecasts[2].text[0:25], 'A 20 percent chance of sh') self.assertEqual(forecasts[3].text[0:25], 'Partly sunny, with a high') # Make sure the text whitespace is trimmed self.assertEqual(forecasts[-1].text, 'Partly sunny, with a high near 78. Southwest wind 5 to 7 mph becoming northeast in the afternoon.') # Make sure we're finding the word 'snow' and 'flurries' in the text self.assertEqual(forecasts[0].has_snow, True) self.assertEqual(forecasts[1].has_snow, True) self.assertEqual(forecasts[2].has_snow, False) self.assertEqual(forecasts[3].has_snow, False)