Skip to content

Commit

Permalink
Testing and types
Browse files Browse the repository at this point in the history
  • Loading branch information
Lars Falk-Petersen committed Oct 3, 2024
1 parent ab01c71 commit c211a9c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 11 deletions.
22 changes: 11 additions & 11 deletions fingr.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import pysolar
import timezonefinder
import socket # To catch connection error
from typing import Tuple, Union, Optional

__version__ = "2024-10"
__url__ = "https://github.com/ways/fingr"
Expand Down Expand Up @@ -70,11 +71,11 @@ def read_motdlist() -> list:
return motdlist


def random_message(messages) -> str:
def random_message(messages: list) -> str:
"""Pick a random message of the day."""
if 0 == len(messages):
return ""
return "[" + messages[secrets.randbelow(0, len(messages) - 1)] + "]\n"
return "[" + messages[secrets.randbelow(len(messages) - 1)] + "]\n"


def read_denylist() -> list:
Expand Down Expand Up @@ -103,12 +104,12 @@ def read_denylist() -> list:
return denylist


def get_timezone(lat, lon) -> str:
def get_timezone(lat: float, lon: float) -> pytz.BaseTzInfo:
"""Return timezone for coordinate."""
return pytz.timezone(timezone_finder.timezone_at(lng=lon, lat=lat))


def wind_direction(deg):
def wind_direction(deg: int) -> str:
"""Return compass direction from degrees."""
symbol = ""

Expand All @@ -135,7 +136,7 @@ def wind_direction(deg):
return symbol


def clean_input(data):
def clean_input(data: str) -> str:
"""Only allow numbers, letters, and some special chars from user."""
# Change sub score to space
data = data.replace("_", " ")
Expand All @@ -147,7 +148,7 @@ def clean_input(data):
)


def resolve_location(data="Oslo/Norway"):
def resolve_location(data="Oslo/Norway") -> Tuple[float | None, float | None, str, bool]:
"""Get coordinates from location name. Return lat, long, name."""
cache = None

Expand All @@ -157,7 +158,7 @@ def resolve_location(data="Oslo/Norway"):
try:
lat = float(lat)
lon = float(lon)
return lat, lon, "coordinates %s, %s" % (lat, lon), False
return lat, lon, f"coordinates {lat}, {lon}", False
except ValueError:
pass

Expand Down Expand Up @@ -202,7 +203,7 @@ def resolve_location(data="Oslo/Norway"):
return None, None, "No location found", False


def fetch_weather(lat, lon, address=""):
def fetch_weather(lat: float, lon: float, address:str = ""):
"""Get forecast data using metno-locationforecast."""
location = Place(address, lat, lon)
forecast = Forecast(location, user_agent=user_agent)
Expand All @@ -212,7 +213,7 @@ def fetch_weather(lat, lon, address=""):
return forecast, updated


def calculate_wind_chill(temperature, wind_speed):
def calculate_wind_chill(temperature: float, wind_speed: float):
return int(
13.12
+ (0.615 * float(temperature))
Expand All @@ -221,9 +222,8 @@ def calculate_wind_chill(temperature, wind_speed):
)


def sun_up(latitude, longitude, date):
def sun_up(latitude: float, longitude: float, date: datetime.datetime) -> bool:
"""Return symbols showing if sun is up at a place and time."""
# alt = pysolar.solar.get_altitude(latitude, longitude, date)
if 0 < pysolar.solar.get_altitude(latitude, longitude, date):
return True
return False
Expand Down
27 changes: 27 additions & 0 deletions fingr_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# https://docs.python.org/3/library/unittest.html

import unittest
import datetime
import pytz
import fingr

verbose = True
Expand Down Expand Up @@ -35,7 +37,32 @@ def test_resolve_location(self):
data="Oslo/Norway"
)
self.assertEqual(latitude, 59.9133301)
self.assertEqual(longitude, 10.7389701)
self.assertEqual(address, 'Oslo, Norway')

def test_random_message(self):
msglist = ["one", "two", "three"]
msg1 = msg2 = None
counts = 0
while msg1 is None and msg2 is None and counts < 100:
counts += 1
msg1 = fingr.random_message(msglist)
msg2 = fingr.random_message(msglist)
if msg1 != msg2:
break

if verbose:
print ("Count", counts)
self.assertIn(msg1.strip().replace("[", "").replace("]", ""), msglist)

def test_get_timezone(self):
tz = fingr.get_timezone(lat = 59, lon = 11)
self.assertEqual(tz.zone, "Europe/Oslo")

def test_sun_up(self):
dt = datetime.datetime.fromtimestamp(1727987676, tz=pytz.timezone("UTC"))
test = fingr.sun_up(latitude = 59, longitude = 11, date = dt)
self.assertFalse(test)

if __name__ == "__main__":
unittest.main()

0 comments on commit c211a9c

Please sign in to comment.