Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
python-visualization
GitHub Repository: python-visualization/folium
Path: blob/main/tests/selenium/test_selenium.py
1601 views
1
import base64
2
import glob
3
import os
4
import subprocess
5
from html.parser import HTMLParser
6
from urllib.parse import unquote
7
8
import nbconvert
9
import pytest
10
from selenium.common.exceptions import UnexpectedAlertPresentException
11
12
from folium.utilities import temp_html_filepath
13
14
15
def find_notebooks():
16
"""Return a list of filenames of the example notebooks."""
17
path = os.path.dirname(__file__)
18
pattern = os.path.join(path, "..", "..", "docs", "**", "*.md")
19
files = glob.glob(pattern, recursive=True)
20
if files:
21
return files
22
else:
23
raise OSError("Could not find the notebooks")
24
25
26
@pytest.mark.parametrize("filepath", find_notebooks())
27
def test_notebook(filepath, driver):
28
if "WmsTimeDimension" in filepath:
29
pytest.xfail("WmsTimeDimension.ipynb external resource makes this test flaky")
30
for filepath_html in get_notebook_html(filepath):
31
driver.get_file(filepath_html)
32
try:
33
assert driver.wait_until(".folium-map")
34
except UnexpectedAlertPresentException:
35
# in Plugins.ipynb we get an alert about geolocation permission
36
# for some reason it cannot be closed or avoided, so just ignore it
37
print("skipping", filepath_html, "because of alert")
38
continue
39
driver.verify_js_logs()
40
41
42
def get_notebook_html(filepath_notebook):
43
"""Convert markdown to notebook to html files, remove them when done."""
44
subprocess.run(
45
[
46
"jupytext",
47
"--to",
48
"notebook",
49
"--execute",
50
filepath_notebook,
51
]
52
)
53
filepath_notebook = filepath_notebook.replace(".md", ".ipynb")
54
55
html_exporter = nbconvert.HTMLExporter()
56
body, _ = html_exporter.from_filename(filepath_notebook)
57
58
parser = IframeParser()
59
parser.feed(body)
60
iframes = parser.iframes
61
62
for iframe in iframes:
63
with temp_html_filepath(iframe) as filepath_html:
64
yield filepath_html
65
66
67
class IframeParser(HTMLParser):
68
"""Extract the iframes from an html page."""
69
70
def __init__(self):
71
super().__init__()
72
self.iframes = []
73
74
def handle_starttag(self, tag, attrs):
75
if tag == "iframe":
76
attrs = dict(attrs)
77
if "srcdoc" in attrs:
78
html_bytes = attrs["srcdoc"].encode()
79
elif "data-html" in attrs: # legacy
80
data_html = attrs["data-html"]
81
if "%" in data_html[:20]:
82
# newest branca version: data-html is percent-encoded
83
html_bytes = unquote(data_html).encode()
84
else:
85
# legacy branca version: data-html is base64 encoded
86
html_bytes = base64.b64decode(data_html)
87
else: # legacy
88
src = attrs["src"]
89
html_base64 = src.split(",")[-1]
90
html_bytes = base64.b64decode(html_base64)
91
self.iframes.append(html_bytes)
92
93