1import os
2import sys
3import pytest
4import sh
5from PIL import Image
6from pathlib import Path
7from sh import psql
8from bs4 import BeautifulSoup
9import imagehash
10import shutil
11
12
13test_dir = Path(Path(__file__).parent)
14
15
16@pytest.fixture
17def python():
18 print(sys.executable)
19 return sh.Command(sys.executable)
20
21
22@pytest.fixture
23def reporting_tool(python, project_root):
24 return python.bake(
25 project_root / "bin/chartepssg",
26 "report",
27 f"--template={ test_dir / 'testdata/report/test_report.xml'}",
28 "--db=integrationtest",
29 "--sid=EPSSGA",
30 "--sensing-start=20201002000000",
31 "--sensing-stop=20201004000000",
32 _truncate_exc=False,
33 )
34
35
36@pytest.fixture
37def postgresql_db_chart_with_data(psql_conn):
38<<<hidden due to potential security issue>>>
39 psql(
40 "--host=localhost",
41 "--port=5123",
42 "--username=dev",
43 "-d",
44 "postgres",
45 "-f",
46 test_dir / "testdata/report/chartepssg.sql",
47 )
48 return psql_conn
49
50
51@pytest.fixture
52def outdir():
53 p = Path("report_tool_output")
54 if p.exists():
55 shutil.rmtree(p)
56 yield p
57 shutil.rmtree(p)
58
59
60def test_reporting(postgresql_db_chart_with_data, reporting_tool, outdir):
61 print("using sql script" + str(test_dir))
62 reporting_tool("-o", outdir)
63
64 assert True == outdir.exists()
65 assert True == (outdir / "report.html").exists()
66
67 expected_images = list(sorted((test_dir / "testdata/report").glob("*.png")))
68 out_images = list(sorted(_get_images_in_report(outdir / "report.html")))
69
70 assert [x.parts[-1] for x in expected_images] == [x.parts[-1] for x in out_images]
71
72 for expected_img, out_img in zip(expected_images, out_images):
73 assert_hash(expected_img, out_img)
74
75
76def assert_hash(out_img, expected_img):
77 hashfunc = imagehash.dhash
78 out_hash = hashfunc(Image.open(out_img))
79 expected_hash = hashfunc(Image.open(expected_img))
80 assert expected_hash == out_hash, (
81 f"Hash comparison failed for {out_img}, "
82 f"difference was {(expected_hash - out_hash) / len(out_hash.hash) **2 * 100}%)"
83 )
84
85
86def _get_images_in_report(report_filename):
87 with report_filename.open("r") as f:
88 html_content = f.read()
89 soup = BeautifulSoup(html_content, "html.parser")
90 images = []
91 for link in soup.find_all("img"):
92 dest = link.get("src")
93 if "png" in dest:
94 images.append(dest)
95 images = list(set(images))
96 images = [Path(Path(report_filename).parent) / x for x in images]
97 return images