matplotlib

Форк
0
/
visualize_tests.py 
160 строк · 5.0 Кб
1
#!/usr/bin/env python
2
#
3
# This builds a html page of all images from the image comparison tests
4
# and opens that page in the browser.
5
#
6
#   $ python tools/visualize_tests.py
7
#
8

9
import argparse
10
import os
11
from collections import defaultdict
12

13
# Non-png image extensions
14
NON_PNG_EXTENSIONS = ['pdf', 'svg', 'eps']
15

16
html_template = """<!DOCTYPE html>
17
<html lang="en"><head>
18
<meta charset="utf-8">
19
<title>Matplotlib test result visualization</title>
20
<style media="screen">
21
img{{
22
  width:100%;
23
  max-width:800px;
24
}}
25
</style>
26
</head><body>
27
{failed}
28
{body}
29
</body></html>
30
"""
31

32
subdir_template = """<h2>{subdir}</h2><table>
33
<thead><tr><th>name</th><th>actual</th><th>expected</th><th>diff</th></tr></thead>
34
<tbody>
35
{rows}
36
</tbody>
37
</table>
38
"""
39

40
failed_template = """<h2>Only Failed</h2><table>
41
<thead><tr><th>name</th><th>actual</th><th>expected</th><th>diff</th></tr></thead>
42
<tbody>
43
{rows}
44
</tbody>
45
</table>
46
"""
47

48
row_template = ('<tr>'
49
                '<td>{0}{1}</td>'
50
                '<td>{2}</td>'
51
                '<td><a href="{3}"><img src="{3}"></a></td>'
52
                '<td>{4}</td>'
53
                '</tr>')
54

55
linked_image_template = '<a href="{0}"><img src="{0}"></a>'
56

57

58
def run(show_browser=True):
59
    """
60
    Build a website for visual comparison
61
    """
62
    image_dir = "result_images"
63
    _subdirs = (name
64
                for name in os.listdir(image_dir)
65
                if os.path.isdir(os.path.join(image_dir, name)))
66

67
    failed_rows = []
68
    body_sections = []
69
    for subdir in sorted(_subdirs):
70
        if subdir == "test_compare_images":
71
            # These are the images which test the image comparison functions.
72
            continue
73

74
        pictures = defaultdict(dict)
75
        for file in os.listdir(os.path.join(image_dir, subdir)):
76
            if os.path.isdir(os.path.join(image_dir, subdir, file)):
77
                continue
78
            fn, fext = os.path.splitext(file)
79
            if fext != ".png":
80
                continue
81
            if "-failed-diff" in fn:
82
                file_type = 'diff'
83
                test_name = fn[:-len('-failed-diff')]
84
            elif "-expected" in fn:
85
                for ext in NON_PNG_EXTENSIONS:
86
                    if fn.endswith(f'_{ext}'):
87
                        display_extension = f'_{ext}'
88
                        extension = ext
89
                        fn = fn[:-len(display_extension)]
90
                        break
91
                else:
92
                    display_extension = ''
93
                    extension = 'png'
94
                file_type = 'expected'
95
                test_name = fn[:-len('-expected')] + display_extension
96
            else:
97
                file_type = 'actual'
98
                test_name = fn
99
            # Always use / for URLs.
100
            pictures[test_name][file_type] = '/'.join((subdir, file))
101

102
        subdir_rows = []
103
        for name, test in sorted(pictures.items()):
104
            expected_image = test.get('expected', '')
105
            actual_image = test.get('actual', '')
106

107
            if 'diff' in test:
108
                # A real failure in the image generation, resulting in
109
                # different images.
110
                status = " (failed)"
111
                failed = f'<a href="{test["diff"]}">diff</a>'
112
                current = linked_image_template.format(actual_image)
113
                failed_rows.append(row_template.format(name, "", current,
114
                                                       expected_image, failed))
115
            elif 'actual' not in test:
116
                # A failure in the test, resulting in no current image
117
                status = " (failed)"
118
                failed = '--'
119
                current = '(Failure in test, no image produced)'
120
                failed_rows.append(row_template.format(name, "", current,
121
                                                       expected_image, failed))
122
            else:
123
                status = " (passed)"
124
                failed = '--'
125
                current = linked_image_template.format(actual_image)
126

127
            subdir_rows.append(row_template.format(name, status, current,
128
                                                   expected_image, failed))
129

130
        body_sections.append(
131
            subdir_template.format(subdir=subdir, rows='\n'.join(subdir_rows)))
132

133
    if failed_rows:
134
        failed = failed_template.format(rows='\n'.join(failed_rows))
135
    else:
136
        failed = ''
137
    body = ''.join(body_sections)
138
    html = html_template.format(failed=failed, body=body)
139
    index = os.path.join(image_dir, "index.html")
140
    with open(index, "w") as f:
141
        f.write(html)
142

143
    show_message = not show_browser
144
    if show_browser:
145
        try:
146
            import webbrowser
147
            webbrowser.open(index)
148
        except Exception:
149
            show_message = True
150

151
    if show_message:
152
        print(f"Open {index} in a browser for a visual comparison.")
153

154

155
if __name__ == '__main__':
156
    parser = argparse.ArgumentParser()
157
    parser.add_argument('--no-browser', action='store_true',
158
                        help="Don't show browser after creating index page.")
159
    args = parser.parse_args()
160
    run(show_browser=not args.no_browser)
161

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.