Coverage for tests/historicalletters/test_utils.py: 100%

1 import math

2 from unittest.mock import Mock, patch

3 from collections import Counter

4 import pandas as pd

5 import geopandas as gpd

6 from shapely import Point, LineString, contains

7 from pathlib import Path

8 import pytest

9

10 from scicom.historicalletters.model import HistoricalLetters

11

12 from scicom.historicalletters.utils import (

13 createData,

14 getPositionOnLine,

15 getRegion

16)

17

18######

19# Utility function testing

20######

21

22

23 def test_initial_population_creation(tmp_path):

24 """Initial population should contain

25 lat/long and geometry information.

26 The chosen CRS is essential since overlap

27 calculation depends on the regions CRS.

28 """

29 file = createData(

30 population=30,

31 populationDistribution=Path(Path(__file__).parent.parent.parent.resolve(), "src/scicom/data/pone.0162678.s003.csv")

32 )

33 assert isinstance(file, gpd.GeoDataFrame)

34 assert file.shape[0] == 30

35 for col in ["longitude", "latitude", "unique_id", "geometry"]:

36 assert col in list(file.columns)

37 assert file.crs == "EPSG:3857"

38

39

40 def test_getPositionOnLine():

41 """Get random point on line between two points.

42 Return type is either a shaple geometry Point,

43 or a tuple of coordinates."""

44 p1 = (0.3,0.2,0.3)

45 p2 = (0.5, 0.4,0.9)

46 p3 = getPositionOnLine(p1,p2)

47 assert isinstance(p3, Point)

48 line = LineString([p1,p2])

49 assert contains(line, p3)

50 p4 = getPositionOnLine(p1,p2, returnType="coords")

51 assert isinstance(p4, tuple)

52

53

54 def test_getRegion():

55 """Returns the id of the overlaping region

56 for a given agent."""

57 model = HistoricalLetters(10)

58 a1 = model.schedule.agents[0]

59 ## New York coord

60 coord = (40.712728, -74.006015)

61 d1 = pd.DataFrame([coord], columns=["lat", "long"])

62 geodf = gpd.GeoDataFrame(

63 d1,

64 geometry=gpd.points_from_xy(d1.long, d1.lat),

65 crs="EPSG:4326"

66 )

67 geodf.to_crs("EPSG:3857")

68 a2fail = geodf.geometry.iloc[0]

69 reg = getRegion(a1.geometry, model)

70 assert isinstance(reg, str)

71 with pytest.raises(IndexError):

72 getRegion(a2fail, model)

73

74