Add insert locations
This commit is contained in:
@@ -62,6 +62,25 @@ class LocationRecorder:
|
||||
),
|
||||
)
|
||||
|
||||
async def insert_locations(self, person: str, locations: dict[datetime, LocationData]) -> None:
|
||||
async with self._engine.begin() as conn:
|
||||
for k, v in locations.items():
|
||||
dt = k
|
||||
if k.tzinfo != UTC:
|
||||
dt = k.astimezone(UTC)
|
||||
date_time_str = dt.strftime("%Y-%m-%dT%H:%M:%S%z")
|
||||
await conn.execute(
|
||||
insert(Location)
|
||||
.prefix_with("OR IGNORE")
|
||||
.values(
|
||||
person=person,
|
||||
datetime=date_time_str,
|
||||
latitude=v.latitude,
|
||||
longitude=v.longitude,
|
||||
altitude=v.altitude,
|
||||
),
|
||||
)
|
||||
|
||||
async def insert_location_now(self, person: str, location: LocationData) -> None:
|
||||
now_utc = datetime.now(tz=UTC)
|
||||
await self.insert_location(person, now_utc, location)
|
||||
|
||||
@@ -312,3 +312,43 @@ def test_insert_location_now() -> None:
|
||||
assert location[3] == longitude
|
||||
assert location[4] == altitude
|
||||
sqlite3_cursor.close()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("_reset_event_loop")
|
||||
@pytest.mark.usefixtures("_create_latest_db")
|
||||
@pytest.mark.usefixtures("_teardown")
|
||||
def test_insert_locations() -> None:
|
||||
locations: dict[datetime, LocationData] = {}
|
||||
person = "Tianyu"
|
||||
time_0 = datetime.now(tz=UTC)
|
||||
lat_0 = 1.0
|
||||
lon_0 = 2.0
|
||||
alt_0 = 3.0
|
||||
time_1 = datetime(2021, 8, 30, 10, 20, 15, tzinfo=UTC)
|
||||
lat_1 = 155.0
|
||||
lon_1 = 33.36
|
||||
alt_1 = 1058
|
||||
locations[time_0] = LocationData(lat_0, lon_0, alt_0)
|
||||
locations[time_1] = LocationData(lat_1, lon_1, alt_1)
|
||||
location_recorder = LocationRecorder(db_path=DB_PATH_STR)
|
||||
event_loop = asyncio.get_event_loop()
|
||||
event_loop.run_until_complete(location_recorder.create_db_engine())
|
||||
event_loop.run_until_complete(
|
||||
location_recorder.insert_locations(person=person, locations=locations),
|
||||
)
|
||||
sqlite3_db = sqlite3.connect(DB_PATH_STR)
|
||||
sqlite3_cursor = sqlite3_db.cursor()
|
||||
sqlite3_cursor.execute("SELECT * FROM location")
|
||||
locations = sqlite3_cursor.fetchall()
|
||||
assert len(locations) == 2 # noqa: PLR2004
|
||||
assert locations[0][0] == person
|
||||
assert locations[0][1] == time_0.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S%z")
|
||||
assert locations[0][2] == lat_0
|
||||
assert locations[0][3] == lon_0
|
||||
assert locations[0][4] == alt_0
|
||||
assert locations[1][0] == person
|
||||
assert locations[1][1] == time_1.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S%z")
|
||||
assert locations[1][2] == lat_1
|
||||
assert locations[1][3] == lon_1
|
||||
assert locations[1][4] == alt_1
|
||||
sqlite3_cursor.close()
|
||||
|
||||
Reference in New Issue
Block a user