Path: blob/main/tests/plugins/test_time_slider_choropleth.py
1601 views
"""1tests TimeSliderChoropleth2--------------------------34"""56import json7import sys89import numpy as np10import pandas as pd11import pytest12from branca.colormap import linear1314import folium15from folium.plugins import TimeSliderChoropleth16from folium.utilities import normalize171819@pytest.mark.xfail(sys.version_info[0:2] == (3, 8), reason="too modern for py38")20def test_timedynamic_geo_json():21"""22tests folium.plugins.TimeSliderChoropleth23"""24import geodatasets25import geopandas as gpd2627datapath = geodatasets.get_path("naturalearth land")28gdf = gpd.read_file(datapath)2930"""31Timestamps, start date is carefully chosen to be earlier than 2001-09-0932(9 digit timestamp), end date is later (10 digits). This is to ensure an33integer sort is used (and not a string sort were '2' > '10').34datetime.strftime('%s') on Windows just generates date and not timestamp so avoid.35"""36n_periods = 337dt_range = pd.Series(pd.date_range("2001-08-1", periods=n_periods, freq="ME"))38dt_index = [f"{dt.timestamp():.0f}" for dt in dt_range]3940styledata = {}4142for country in gdf.index:43pdf = pd.DataFrame(44{45"color": np.random.normal(size=n_periods),46"opacity": np.random.normal(size=n_periods),47},48index=dt_index,49)50styledata[country] = pdf.cumsum()5152max_color, min_color = 0, 05354for country, data in styledata.items():55max_color = max(max_color, data["color"].max())56min_color = min(max_color, data["color"].min())5758cmap = linear.PuRd_09.scale(min_color, max_color)5960# Define function to normalize column into range [0,1]61def norm(col):62return (col - col.min()) / (col.max() - col.min())6364for country, data in styledata.items():65data["color"] = data["color"].apply(cmap)66data["opacity"] = norm(data["opacity"])6768styledict = {69str(country): data.to_dict(orient="index")70for country, data in styledata.items()71}7273m = folium.Map((0, 0), zoom_start=2)7475time_slider_choropleth = TimeSliderChoropleth(gdf.to_json(), styledict)76time_slider_choropleth.add_to(m)7778rendered = time_slider_choropleth._template.module.script(time_slider_choropleth)7980m._repr_html_()81out = normalize(m._parent.render())82assert '<script src="https://d3js.org/d3.v4.min.js"></script>' in out8384# We verify that data has been inserted correctly85expected_timestamps = sorted(dt_index, key=int) # numeric sort86expected_timestamps = f"let timestamps = {expected_timestamps};"87expected_timestamps = expected_timestamps.split(";")[0].strip().replace("'", '"')88rendered_timestamps = rendered.strip(" \n{").split(";")[0].strip()89assert expected_timestamps == rendered_timestamps9091expected_styledict = normalize(json.dumps(styledict, sort_keys=True))92assert expected_styledict in normalize(rendered)939495