Example #1
0
def test_getInteresting():
    mock_http = mock.Mock()
    instance = DarkSky(
        api_key="abc",
        http_interface=mock_http
    )
    mock_http.open.return_value = (
        200,
        json.dumps(
            {
                "storms": {
                    "data": True
                }
            }
        )
    )

    yield (
        assert_equals,
        True,
        instance.getInteresting()["data"]
    )
    
    yield (
        assert_equals,
        "https://api.darkskyapp.com/v1/interesting/abc",
        mock_http.open.call_args[1]["url"]
    )
Example #2
0
def test_getInteresting():
    mock_http = mock.Mock()
    instance = DarkSky(api_key="abc", http_interface=mock_http)
    mock_http.open.return_value = (200, json.dumps({"storms": {"data": True}}))

    yield (assert_equals, True, instance.getInteresting()["data"])

    yield (assert_equals, "https://api.darkskyapp.com/v1/interesting/abc",
           mock_http.open.call_args[1]["url"])
Example #3
0
 def __get_weather(self):
     dk = DarkSky()
     if dk.is_success():
         logger.info('API success on attempt: ' + str(self.api_tries) + ' current_temp: ' + str(dk.current_temp()) + ' todays_low: ' +
                     str(dk.todays_low()) + ' todays_high: ' + str(dk.todays_high()) + ' icon: ' + str(dk.icon()))
         self.current_temp = dk.current_temp()
         self.todays_low = dk.todays_low()
         self.todays_high = dk.todays_high()
         self.icon = dk.icon()
         self.api_tries = 0
     else:
         self.api_tries += 1
         if self.api_tries >= DATA_DELAY_REFRESH_LIMIT or self.current_temp is None:
             self.__reset_os_network_interface()
             now = datetime.datetime.now()
             try_again_time = now + datetime.timedelta(seconds=CALL_INTERVAL_SECONDS)
             logger.warning(
                 "failed to get weather data after " + str(self.api_tries) + " attempt(s). Will try again in " + str(round(CALL_INTERVAL_SECONDS/60)) + " minutes (at " + try_again_time.strftime("%d-%b-%y %H:%M:%S") + ")"
             )
             self.__display_data_failure(try_again_time)
             time.sleep(CALL_INTERVAL_SECONDS)
             self.matrix.Clear()
             self.__get_weather()
         else:
             logger.warning("Attempt: " + str(self.api_tries) + ". Will try again in " + str(round(CALL_INTERVAL_SECONDS/60)) + " minutes to update weather data. Displaying old data.")
             pass
     self.matrix.Clear()
Example #4
0
 def darksky_with_data(self):
     yield DarkSky(key=generate_random_key())
     # make sure test file is deleted
     print("teardown")
     if check_files(OUT_FILE):
         print("removing {}".format(OUT_FILE))
         os.remove(OUT_FILE)
Example #5
0
 async def get(self):
     """Return forecast data for location"""
     lat = self.request.query.get("lat", "")
     lng = self.request.query.get("lng", "")
     dark_sky = DarkSky(self.config.DARKSKY_API_KEY, self.client)
     forecast = await dark_sky.get_forecast(lat, lng)
     return web.json_response(forecast)
Example #6
0
def test_getInteresting_failure():
    mock_http = mock.Mock()
    instance = DarkSky(api_key="abc", http_interface=mock_http)
    mock_http.open.return_value = (403,
                                   json.dumps({
                                       "code": 403,
                                       "error": "Forbidden"
                                   }))
    yield (assert_raises, DarkSkyException, instance.getInteresting)
Example #7
0
def get_forecast():
    '''
    Returns forecast for configured timeframe
    '''
    darksky = DarkSky(config['darksky']['apikey'])
    forecast = darksky.get(config['forecast']['location']['latitude'],
                           config['forecast']['location']['longitude'])
    timeframe = config['forecast']['timeframe']

    if timeframe == 0:
        forecast = [forecast.currently]
    else:
        forecast = forecast.hourly.data[:timeframe]

    temperature = mean(
        list(map(lambda hour: hour.apparentTemperature, forecast)))
    condition = get_most_significant_condition(
        list(map(lambda hour: hour.icon, forecast)))

    return {'temperature': temperature, 'condition': condition}
Example #8
0
def test_getWeathers():
    mock_http = mock.Mock()
    instance = DarkSky(api_key="abc", http_interface=mock_http)
    mock_http.open.return_value = (200,
                                   json.dumps({
                                       "precipitation": [{
                                           "probability": 1.0,
                                           "intensity": 15.6,
                                           "error": 1.0,
                                           "type": "rain",
                                           "time": 1325607100
                                       }, {
                                           "probability": 0.0,
                                           "intensity": 0.0,
                                           "error": 0.0,
                                           "type": "rain",
                                           "time": 1325607791
                                       }]
                                   }))
    time1 = datetime.datetime(year=1999, month=12, day=1)
    time2 = datetime.datetime(
        year=1995,
        month=12,
        day=1,
    )
    ret = instance.getWeathers([{
        "latitude": 12345.11,
        "longitude": 12345.12,
        "time": time1
    }, {
        "latitude": 12345.13,
        "longitude": 12345.14,
        "time": time2
    }])
    yield (assert_equals, 15.6, ret[0]["intensity"])
    yield (assert_equals, 0, ret[1]["intensity"])
    yield (
        assert_equals,
        "https://api.darkskyapp.com/v1/precipitation/abc/12345.11,12345.12,944006400;12345.13,12345.14,817776000",
        mock_http.open.call_args[1]["url"])
Example #9
0
def test_getWeather_success():
    mock_http = mock.Mock()
    mock_dsresponse = mock.Mock()
    mock_dsresponse.return_value.checkTimeout = 323
    instance = DarkSky(
        api_key="abc",
        http_interface=mock_http,
        DarkSkyResponseClass=mock_dsresponse
    )
    mock_http.open.return_value = (
        200,
        json.dumps(
            {"data": True}
        )
    )
    ret_val = instance.getWeather(latitude=123, longitude=1234)
    
    yield (
        assert_equals,
        mock_dsresponse.return_value,
        ret_val
    )

    yield (
        assert_equals,
        "https://api.forecast.io/forecast/abc/123,1234",
        mock_http.open.call_args[1]["url"]
    )

    yield (
        assert_equals,
        {"data": True},
        mock_dsresponse.call_args[1]["response_body"]
    )

    yield (
        assert_equals,
        "forecast",
        mock_dsresponse.call_args[1]["forecast_type"]
    )
Example #10
0
def test_getWeather_success():
    mock_http = mock.Mock()
    mock_dsresponse = mock.Mock()
    mock_dsresponse.return_value = "something"
    instance = DarkSky(
        api_key="abc",
        http_interface=mock_http,
        DarkSkyResponseClass=mock_dsresponse
    )
    mock_http.open.return_value = (
        200,
        json.dumps(
            {"data": True}
        )
    )
    ret_val = instance.getWeather(latitude=123, longitude=1234, forecast_type="brief")
    
    yield (
        assert_equals,
        "something",
        ret_val
    )

    yield (
        assert_equals,
        "https://api.darkskyapp.com/v1/brief/abc/123,1234",
        mock_http.open.call_args[1]["url"]
    )

    yield (
        assert_equals,
        {"data": True},
        mock_dsresponse.call_args[1]["response_body"]
    )

    yield (
        assert_equals,
        "brief",
        mock_dsresponse.call_args[1]["forecast_type"]
    )
Example #11
0
def test_getWeather_success():
    mock_http = mock.Mock()
    mock_dsresponse = mock.Mock()
    mock_dsresponse.return_value = "something"
    instance = DarkSky(api_key="abc",
                       http_interface=mock_http,
                       DarkSkyResponseClass=mock_dsresponse)
    mock_http.open.return_value = (200, json.dumps({"data": True}))
    ret_val = instance.getWeather(latitude=123,
                                  longitude=1234,
                                  forecast_type="brief")

    yield (assert_equals, "something", ret_val)

    yield (assert_equals, "https://api.darkskyapp.com/v1/brief/abc/123,1234",
           mock_http.open.call_args[1]["url"])

    yield (assert_equals, {
        "data": True
    }, mock_dsresponse.call_args[1]["response_body"])

    yield (assert_equals, "brief",
           mock_dsresponse.call_args[1]["forecast_type"])
Example #12
0
    def w_response(self, mask, args):
        """
        Returns appropriate reponse to .w request
        example: <bot> New York, NY - Clear, 75.4°F
        """
        local = " ".join(args['<location>'])
        if not local:
            location = yield from self.get_local(mask.nick)
            # XXX tempory fix
            if location == mask.nick:
                response = "Sorry, I don't remember where you are"
                return response
        else:
            try:
                location = yield from self.get_geo(mask.nick, args)
            except ConnectionError:
                response = "Sorry, I could't find that place"
                return response
            # if args are provided remember them
            self.set_local(mask.nick, location)

        latlng, place = location
        try:
            self.ds = DarkSky(latlng, key=self.api_key)
        except (requests.exceptions.Timeout,
                requests.exceptions.TooManyRedirects,
                requests.exceptions.RequestException,
                requests.exceptions.HTTPError, ValueError, KeyError) as e:
            errmsg = str(e)
            return errmsg

        current = self.ds.forecast.currently
        time = _unixformat(current.time, self.ds.forecast.timezone)
        deg = "F" if self.ds.forecast.flags.units == "us" else "C"

        response = "\x02{0} \x0F({4}) - {1}, {2}\u00B0{3}".format(
            place, current.summary, current.temperature, deg, time)
        return response
Example #13
0

@app.route("/")
def weather():
    """
    Test route to ensure flask will serve pages with the schedule running.
    """
    weather_dict = dark_sky.read_file(config.weather_file)
    w = weather_dict['minutely']['summary']
    t = weather_dict['currently']['time']
    print("Weather summary:\n{}".format(w))
    return f"Weather at {t} is like: {w}"


if __name__ == '__main__':
    dark_sky = DarkSky(key=config.dark_sky_api_key)

    create_schedule(update_weather,
                    config.weather_file,
                    interval=config.darksky_interval,
                    units='seconds')  # for test purposes only

    # run the update now in it's own thread
    s = Thread(target=schedule.run_all())
    s.start()
    # thread the check for subsequent updates
    t = Thread(target=threaded_schedule_run)
    t.start()

    app.run(debug=True, use_reloader=False)
Example #14
0
 def test_init_raises_TypeError_with_no_key_variable(self):
     with pytest.raises(TypeError) as e:
         DarkSky()
     assert "Missing argument. Key is required." in str(e.value)
Example #15
0
    def __init__(self):
        super(LWeather, self).__init__(color="black")

        self.ds = DarkSky()
        self.last_temperature = 0.0

        self.ch2 = 20  # component height 2
        self.sh1 = 2  # separator height 1

        # Offsets
        self.row_1_y = self.ch2
        self.sep_2_y = self.row_1_y + 2 * self.ch2
        self.row_2_y = self.sep_2_y + self.sh1
        self.sep_3_y = self.row_2_y + self.ch2
        self.row_3_y = self.sep_3_y + self.sh1
        self.sep_4_y = self.row_3_y + self.ch2
        self.row_4_y = self.sep_4_y + self.sh1

        # N/A: u'\uf07b'

        # Build the layout
        self.mi = Component(self.ch2,
                            self.ch2,
                            font='weathericons-regular-webfont.ttf',
                            font_size=14,
                            bg_color=0,
                            align=1)
        self.mi.set_position(2, 0)
        self.mi.set_text(u'\uF0E2')  # Moon phase, TODO use the 28 icons

        self.cdate = Component(52, self.ch2, font_size=14, bg_color=0, align=1)
        self.cdate.set_position(20, 0)
        self.cdate.set(time.strftime('%d-%b'))

        self.ctime = Component(56, self.ch2, font_size=14, bg_color=0, align=1)
        self.ctime.set_position(72, 0)
        self.ctime.set(time.strftime('%H:%M'))
        # ----------------
        self.tv = Component(48,
                            2 * self.ch2,
                            font_size=24,
                            format_string="{0:.0f}" + u'\N{DEGREE SIGN}',
                            align=1)
        self.tv.set_position(0, self.row_1_y)
        self.tv.set(-23.45)

        self.ti = Component(48,
                            2 * self.ch2,
                            font='weathericons-regular-webfont.ttf',
                            font_size=26,
                            align=1,
                            bg_color=255)
        self.ti.set_position(44, self.row_1_y)
        self.ti.set_text(u'\uF002')  # Weather icon

        self.tmax = Component(34,
                              self.ch2,
                              font_size=14,
                              format_string="{0:.0f}" + u'\N{DEGREE SIGN}',
                              align=2)
        self.tmax.set_position(94, self.row_1_y)
        self.tmax.set(-18.87)

        self.tmin = Component(34,
                              self.ch2,
                              font_size=14,
                              format_string="{0:.0f}" + u'\N{DEGREE SIGN}',
                              align=2)
        self.tmin.set_position(94, self.row_1_y + self.ch2)
        self.tmin.set(-27.64)
        # -----------------------------
        self.ln = Component(92,
                            self.ch2,
                            font_size=13,
                            font='Roboto-Condensed.ttf',
                            align=1)
        self.ln.set_position(0, self.row_2_y)
        self.ln.set_text("Valkenburg, ZH")

        self.td = Component(34,
                            self.ch2,
                            font_size=22,
                            font='weathericons-regular-webfont.ttf',
                            align=1)  # temperature direction
        self.td.set_position(94, self.row_2_y)
        self.td.set_text(u'\uF095')  # Arrow up: f058, down: f044
        # -------------------------------------
        self.hi = Component(self.ch2,
                            self.ch2,
                            font='weathericons-regular-webfont.ttf',
                            font_size=16,
                            bg_color=0)
        self.hi.set_position(0, self.row_3_y)
        self.hi.set_text(u'\uF07A', align=1)  # Humidity, Water drop: u'\uF078'

        self.hv = Component(44,
                            self.ch2,
                            font_size=18,
                            font='Roboto-Condensed.ttf',
                            format_string="{0:.0f}%",
                            align=0,
                            bg_color=0)
        self.hv.set_position(20, self.row_3_y)
        self.hv.set(67)

        self.ri = Component(24,
                            self.ch2,
                            font='weathericons-regular-webfont.ttf',
                            font_size=16,
                            bg_color=0)
        self.ri.set_position(66, self.row_3_y)
        self.ri.set_text(u'\uF084', align=1)  # Umbrella

        self.rv = Component(38,
                            self.ch2,
                            font_size=18,
                            font='Roboto-Condensed.ttf',
                            format_string="{0:.0f}%",
                            align=0,
                            bg_color=0)
        self.rv.set_position(90, self.row_3_y)
        self.rv.set(26.32)

        self.pi = Component(self.ch2,
                            self.ch2,
                            font_size=18,
                            font='weathericons-regular-webfont.ttf',
                            bg_color=0)
        self.pi.set_position(0, self.row_4_y)
        self.pi.set_text(u'\uF079', x=0, align=1)  # Barometer

        self.pv = Component(64,
                            self.ch2,
                            font_size=18,
                            format_string="{0:.1f}",
                            align=0,
                            bg_color=0)
        self.pv.set_position(20, self.row_4_y)
        self.pv.set(1023.52)

        self.wi = Component(34,
                            self.ch2,
                            font='weathericons-regular-webfont.ttf',
                            font_size=20,
                            bg_color=0,
                            align=0)
        self.wi.set_position(94, self.row_4_y)
        self.wi.set_text(u'\uF0B7')  # Wind

        # Add components to the layout
        self.add([self.mi, self.cdate, self.ctime])
        self.add([self.tv, self.ti, self.tmax, self.tmin])
        self.add([self.ln, self.td])
        self.add([self.hi, self.hv, self.ri, self.rv])
        self.add([self.pi, self.pv, self.wi])
Example #16
0
 def test_init_stores_key_variable(self, exec_no):
     key = generate_random_key()
     print("Test {} with key: {}".format(exec_no, key))
     darksky_with_key = DarkSky(key=key)
     assert darksky_with_key.key == key
Example #17
0
 def darksky():
     return DarkSky(key=generate_random_key())
Example #18
0
def test_getWeathers():
    mock_http = mock.Mock()
    instance = DarkSky(
        api_key="abc",
        http_interface=mock_http
    )
    mock_http.open.return_value = (
        200,
        json.dumps(
            {
              "precipitation": [
                { "probability": 1.0,
                  "intensity": 15.6,
                  "error": 1.0,
                  "type": "rain",
                  "time": 1325607100 },
                { "probability": 0.0,
                  "intensity": 0.0,
                  "error": 0.0,
                  "type": "rain",
                  "time": 1325607791 }
              ]
            }
        )
    )
    time1 = datetime.datetime(
        year=1999,
        month=12,
        day=1
    )
    time2 = datetime.datetime(
        year=1995,
        month=12,
        day=1,
    )
    ret = instance.getWeathers(
        [
            {
                "latitude": 12345.11,
                "longitude": 12345.12,
                "time": time1
            },
            {
                "latitude": 12345.13,
                "longitude": 12345.14,
                "time": time2
            }
        ]
    )
    yield (
        assert_equals,
        15.6,
        ret[0]["intensity"]
    )
    yield (
        assert_equals,
        0,
        ret[1]["intensity"]
    )
    yield (
        assert_equals,
        "https://api.darkskyapp.com/v1/precipitation/abc/12345.11,12345.12,944006400;12345.13,12345.14,817776000",
        mock_http.open.call_args[1]["url"]
    )
Example #19
0
import sys

sys.path.append('../')

from darksky import DarkSky

darksky = DarkSky('YOUR_API_KEY')
forecast = darksky.get(47.2, 27.6)

print('Summary: %s' % forecast.currently.summary)
print('Temperature: %s*C, feels like %s*C' %
      (forecast.currently.temperature, forecast.currently.apparentTemperature))