forked from pytest-dev/pytest-html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlegacy_test_pytest_html.py
1242 lines (1135 loc) · 42.3 KB
/
legacy_test_pytest_html.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# type: ignore
import json
import os
import random
import re
import sys
from base64 import b64encode
import pkg_resources
import pytest
pytest_plugins = ("pytester",)
def run(testdir, path="report.html", *args):
path = testdir.tmpdir.join(path)
result = testdir.runpytest("--html", path, *args)
return result, read_html(path)
def read_html(path):
with open(str(path)) as f:
return f.read()
def assert_results_by_outcome(html, test_outcome, test_outcome_number, label=None):
# Asserts if the test number of this outcome in the summary is correct
regex_summary = rf"(\d)+ {label or test_outcome}"
assert int(re.search(regex_summary, html).group(1)) == test_outcome_number
# Asserts if the generated checkbox of this outcome is correct
regex_checkbox = (
f'<input checked="true" class="filter" data-test-result="{test_outcome}"'
)
if test_outcome_number == 0:
regex_checkbox += ' disabled="true"'
assert re.search(regex_checkbox, html) is not None
# Asserts if the table rows of this outcome are correct
regex_table = f'tbody class="{test_outcome} '
assert len(re.findall(regex_table, html)) == test_outcome_number
def assert_results(
html,
tests=1,
duration=None,
passed=1,
skipped=0,
failed=0,
errors=0,
xfailed=0,
xpassed=0,
rerun=0,
):
# Asserts total amount of tests
total_tests = re.search(r"(\d)+ tests ran", html)
assert int(total_tests.group(1)) == tests
# Asserts tests running duration
if duration is not None:
tests_duration = re.search(r"([\d,.]+) seconds", html)
assert float(tests_duration.group(1)) >= float(duration)
# Asserts by outcome
assert_results_by_outcome(html, "passed", passed)
assert_results_by_outcome(html, "skipped", skipped)
assert_results_by_outcome(html, "failed", failed)
assert_results_by_outcome(html, "error", errors, "errors")
assert_results_by_outcome(html, "xfailed", xfailed, "expected failures")
assert_results_by_outcome(html, "xpassed", xpassed, "unexpected passes")
assert_results_by_outcome(html, "rerun", rerun)
class TestHTML:
def test_durations(self, testdir):
sleep = float(0.2)
testdir.makepyfile(
"""
import time
def test_sleep():
time.sleep({:f})
""".format(
sleep * 2
)
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, duration=sleep)
p = re.compile(r'<td class="col-duration">([\d,.]+)</td>')
m = p.search(html)
assert float(m.group(1)) >= sleep
@pytest.mark.parametrize(
"duration_formatter,expected_report_content",
[
("%f", r'<td class="col-duration">\d{2}</td>'),
("%S.%f", r'<td class="col-duration">\d{2}\.\d{2}</td>'),
(
"ABC%H %M %S123",
r'<td class="col-duration">ABC\d{2} \d{2} \d{2}123</td>',
),
],
)
def test_can_format_duration_column(
self, testdir, duration_formatter, expected_report_content
):
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
setattr(report, "duration_formatter", "{duration_formatter}")
"""
)
sleep = float(0.2)
testdir.makepyfile(
"""
import time
def test_sleep():
time.sleep({:f})
""".format(
sleep
)
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, duration=sleep)
compiled_regex = re.compile(expected_report_content)
assert compiled_regex.search(html)
def test_pass(self, testdir):
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert_results(html)
def test_skip(self, testdir):
reason = str(random.random())
testdir.makepyfile(
f"""
import pytest
def test_skip():
pytest.skip('{reason}')
"""
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, tests=0, passed=0, skipped=1)
assert f"Skipped: {reason}" in html
def test_fail(self, testdir):
testdir.makepyfile("def test_fail(): assert False")
result, html = run(testdir)
assert result.ret
assert_results(html, passed=0, failed=1)
assert "AssertionError" in html
@pytest.mark.skipif(sys.platform == "win32", reason="Test is flaky on Windows")
def test_rerun(self, testdir):
testdir.makeconftest(
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
pytest_html = item.config.pluginmanager.getplugin("html")
outcome = yield
report = outcome.get_result()
extra = getattr(report, "extra", [])
if report.when == "call":
extra.append(pytest_html.extras.url("http://www.example.com/"))
report.extra = extra
"""
)
testdir.makepyfile(
"""
import pytest
import time
@pytest.mark.flaky(reruns=2)
def test_example():
time.sleep(1)
assert False
"""
)
result, html = run(testdir)
assert result.ret
assert_results(html, passed=0, failed=1, rerun=2)
expected_report_durations = r'<td class="col-duration">1.\d{2}</td>'
assert len(re.findall(expected_report_durations, html)) == 3
expected_report_extras = (
r'<td class="col-links"><a class="url" href="http://www.example.com/" '
'target="_blank">URL</a> </td>'
)
assert len(re.findall(expected_report_extras, html)) == 3
def test_no_rerun(self, testdir):
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "-p", "no:rerunfailures")
assert result.ret == 0
assert re.search('data-test-result="rerun"', html) is None
def test_conditional_xfails(self, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xfail(False, reason='reason')
def test_fail(): assert False
@pytest.mark.xfail(False, reason='reason')
def test_pass(): pass
@pytest.mark.xfail(True, reason='reason')
def test_xfail(): assert False
@pytest.mark.xfail(True, reason='reason')
def test_xpass(): pass
"""
)
result, html = run(testdir)
assert result.ret
assert_results(html, tests=4, passed=1, failed=1, xfailed=1, xpassed=1)
def test_setup_error(self, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.fixture
def arg(request):
raise ValueError()
def test_function(arg):
pass
"""
)
result, html = run(testdir)
assert result.ret
assert_results(html, tests=0, passed=0, errors=1)
assert "::setup" in html
assert "ValueError" in html
def test_xfail(self, testdir):
reason = str(random.random())
testdir.makepyfile(
f"""
import pytest
def test_xfail():
pytest.xfail('{reason}')
"""
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, passed=0, xfailed=1)
assert f"XFailed: {reason}" in html
def test_xpass(self, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xfail()
def test_xpass():
pass
"""
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, passed=0, xpassed=1)
def test_create_report_path(self, testdir):
testdir.makepyfile("def test_pass(): pass")
path = os.path.join("directory", "report.html")
result, html = run(testdir, path)
assert result.ret == 0
assert_results(html)
@pytest.mark.parametrize(
"path, is_custom", [("", False), ("", True), ("directory", False)]
)
def test_report_title(self, testdir, path, is_custom):
testdir.makepyfile("def test_pass(): pass")
report_name = "report.html"
report_title = "My Custom Report" if is_custom else report_name
if is_custom:
testdir.makeconftest(
f"""
import pytest
from py.xml import html
def pytest_html_report_title(report):
report.title = "{report_title}"
"""
)
path = os.path.join(path, report_name)
result, html = run(testdir, path)
assert result.ret == 0
report_head_title_string = f"<title>{report_title}</title>"
assert len(re.findall(report_head_title_string, html)) == 1, html
report_body_title_string = f"<h1>{report_title}</h1>"
assert len(re.findall(report_body_title_string, html)) == 1, html
def test_report_title_addopts_env_var(self, testdir, monkeypatch):
report_location = "REPORT_LOCATION"
report_name = "MuhReport"
monkeypatch.setenv(report_location, report_name)
testdir.makefile(
".ini",
pytest=f"""
[pytest]
addopts = --html ${report_location}
""",
)
testdir.makepyfile("def test_pass(): pass")
result = testdir.runpytest()
assert result.ret == 0
report_title = f"<h1>{report_name}</h1>"
assert report_title in read_html(report_name)
def test_resources_inline_css(self, testdir):
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
content = pkg_resources.resource_string(
"pytest_html", os.path.join("resources", "style.css")
)
content = content.decode("utf-8")
assert content
assert content in html
def test_resources(self, testdir):
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
content = pkg_resources.resource_string(
"pytest_html", os.path.join("resources", "old_main.js")
)
content = content.decode("utf-8")
assert content
assert content in html
regex_css_link = '<link href="assets/style.css" rel="stylesheet"'
assert re.search(regex_css_link, html) is not None
@pytest.mark.parametrize("result", ["pass", "fail"])
def test_stdout(self, testdir, result):
content = "<spam>ham</spam>"
escaped = "<spam>ham</spam>"
testdir.makepyfile(
f"""
def test_stdout():
print('{content}')
assert f'{result}' == 'pass'"""
)
_, html = run(testdir)
assert content not in html
assert escaped in html
def test_custom_content_in_summary(self, testdir):
content_prefix = str(random.random())
content_summary = str(random.random())
content_suffix = str(random.random())
testdir.makeconftest(
f"""
import pytest
from py.xml import html
def pytest_html_results_summary(prefix, summary, postfix):
prefix.append(html.p("prefix is {content_prefix}"))
summary.extend([html.p("extra summary is {content_summary}")])
postfix.extend([html.p("postfix is {content_suffix}")])
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert len(re.findall(content_prefix, html)) == 1
assert len(re.findall(content_summary, html)) == 1
assert len(re.findall(content_suffix, html)) == 1
def test_extra_html(self, testdir):
content = str(random.random())
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.html('<div>{content}</div>')]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert content in html
@pytest.mark.parametrize(
"content, encoded",
[("u'\u0081'", "woE="), ("'foo'", "Zm9v"), ("b'\\xe2\\x80\\x93'", "4oCT")],
)
def test_extra_text(self, testdir, content, encoded):
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.text({content})]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
href = f"data:text/plain;charset=utf-8;base64,{encoded}"
link = f'<a class="text" href="{href}" target="_blank">Text</a>'
assert link in html
def test_extra_json(self, testdir):
content = {str(random.random()): str(random.random())}
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.json({content})]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
content_str = json.dumps(content)
data = b64encode(content_str.encode("utf-8")).decode("ascii")
href = f"data:application/json;charset=utf-8;base64,{data}"
link = f'<a class="json" href="{href}" target="_blank">JSON</a>'
assert link in html
def test_extra_url(self, testdir):
content = str(random.random())
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.url('{content}')]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
link = f'<a class="url" href="{content}" target="_blank">URL</a>'
assert link in html
@pytest.mark.parametrize(
"mime_type, extension",
[
("image/png", "png"),
("image/png", "image"),
("image/jpeg", "jpg"),
("image/svg+xml", "svg"),
],
)
def test_extra_image(self, testdir, mime_type, extension):
content = str(random.random())
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.{extension}('{content}')]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
src = f"data:{mime_type};base64,{content}"
assert f'<img src="{src}"/>' in html
def test_extra_image_windows(self, mocker, testdir):
mock_isfile = mocker.patch("pytest_html.result.isfile")
mock_isfile.side_effect = ValueError("stat: path too long for Windows")
self.test_extra_image(testdir, "image/png", "png")
assert mock_isfile.call_count == 1
@pytest.mark.parametrize("mime_type, extension", [("video/mp4", "mp4")])
def test_extra_video(self, testdir, mime_type, extension):
content = str(random.random())
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.{extension}('{content}')]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
src = f"data:{mime_type};base64,{content}"
assert (
f'<video controls><source src="{src}" type="{mime_type}"></video>' in html
)
def test_extra_video_windows(self, mocker, testdir):
mock_isfile = mocker.patch("pytest_html.result.isfile")
mock_isfile.side_effect = ValueError("stat: path too long for Windows")
self.test_extra_video(testdir, "video/mp4", "mp4")
assert mock_isfile.call_count == 1
@pytest.mark.parametrize(
"content", [("u'\u0081'"), ("'foo'"), ("b'\\xe2\\x80\\x93'")]
)
def test_extra_text_separated(self, testdir, content):
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.text({content})]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
src = "assets/test_extra_text_separated.py__test_pass_0_0.txt"
link = f'<a class="text" href="{src}" target="_blank">'
assert link in html
assert os.path.exists(src)
@pytest.mark.parametrize(
"file_extension, extra_type",
[("png", "image"), ("png", "png"), ("svg", "svg"), ("jpg", "jpg")],
)
def test_extra_image_separated(self, testdir, file_extension, extra_type):
content = b64encode(b"foo").decode("ascii")
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.{extra_type}('{content}')]
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
src = f"assets/test_extra_image_separated.py__test_pass_0_0.{file_extension}"
link = f'<a class="image" href="{src}" target="_blank">'
img = f'<img src="{src}"/>'
assert link in html
assert img in html
assert os.path.exists(src)
@pytest.mark.parametrize(
"file_extension, extra_type",
[("png", "image"), ("png", "png"), ("svg", "svg"), ("jpg", "jpg")],
)
def test_extra_image_separated_rerun(self, testdir, file_extension, extra_type):
content = b64encode(b"foo").decode("ascii")
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.{extra_type}('{content}')]
"""
)
testdir.makepyfile(
"""
import pytest
@pytest.mark.flaky(reruns=2)
def test_fail():
assert False"""
)
result, html = run(testdir)
for i in range(1, 4):
asset_name = "test_extra_image_separated_rerun.py__test_fail"
src = f"assets/{asset_name}_0_{i}.{file_extension}"
link = f'<a class="image" href="{src}" target="_blank">'
img = f'<img src="{src}"/>'
assert result.ret
assert link in html
assert img in html
assert os.path.exists(src)
@pytest.mark.parametrize("src_type", ["https://", "file://", "image.png"])
def test_extra_image_non_b64(self, testdir, src_type):
content = src_type
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.image('{content}')]
"""
)
testdir.makepyfile("def test_pass(): pass")
if src_type == "image.png":
testdir.makefile(".png", image="pretty picture")
result, html = run(testdir, "report.html")
assert result.ret == 0
assert '<a href="{0}"><img src="{0}"/>'.format(content) in html
@pytest.mark.parametrize("max_asset_filename_length", [10, 100])
def test_very_long_test_name(self, testdir, max_asset_filename_length):
testdir.makeconftest(
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.image('image.png')]
"""
)
# This will get truncated
test_name = "test_{}".format("a" * 300)
testdir.makepyfile(
f"""
def {test_name}():
assert False
"""
)
testdir.makeini(
f"""
[pytest]
max_asset_filename_length = {max_asset_filename_length}
"""
)
result, html = run(testdir, "report.html")
file_name = f"test_very_long_test_name.py__{test_name}_0_0.png"[
-max_asset_filename_length:
]
src = "assets/" + file_name
link = f'<a class="image" href="{src}" target="_blank">'
img = f'<img src="{src}"/>'
assert result.ret
assert link in html
assert img in html
assert os.path.exists(src)
def test_extra_fixture(self, testdir):
content = b64encode(b"foo").decode("ascii")
testdir.makepyfile(
f"""
def test_pass(extra):
from pytest_html import extras
extra.append(extras.png('{content}'))
"""
)
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
src = f"data:image/png;base64,{content}"
assert f'<img src="{src}"/>' in html
def test_no_invalid_characters_in_filename(self, testdir):
testdir.makeconftest(
"""
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
from pytest_html import extras
report.extra = [extras.image('image.png')]
"""
)
testdir.makepyfile(
"""
def test_fail():
assert False
"""
)
run(testdir)
for filename in os.listdir("assets"):
assert re.search(r'[:\\<>\*\?\|"}{}~]', filename) is None
def test_no_environment(self, testdir):
testdir.makeconftest(
"""
def pytest_configure(config):
config._metadata = None
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert "Environment" not in html
def test_environment(self, testdir):
content = str(random.random())
testdir.makeconftest(
f"""
def pytest_configure(config):
config._metadata['content'] = '{content}'
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert "Environment" in html
assert len(re.findall(content, html)) == 1
def test_environment_xdist(self, testdir):
content = str(random.random())
testdir.makeconftest(
f"""
def pytest_configure(config):
for i in range(2):
config._metadata['content'] = '{content}'
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir, "report.html", "-n", "1")
assert result.ret == 0
assert "Environment" in html
assert len(re.findall(content, html)) == 1
def test_environment_xdist_reruns(self, testdir):
content = str(random.random())
testdir.makeconftest(
f"""
def pytest_configure(config):
for i in range(2):
config._metadata['content'] = '{content}'
"""
)
testdir.makepyfile("def test_fail(): assert False")
result, html = run(testdir, "report.html", "-n", "1", "--reruns", "1")
assert result.ret
assert "Environment" in html
assert len(re.findall(content, html)) == 1
_unsorted_tuples = [
("Hello", "fzWZP6vKRv", "hello", "garAge", "123Go"),
(2, 4, 2, 1, 54),
("Yes", 400, "5.4"),
]
_sorted_tuples = [
"123Go, Hello, fzWZP6vKRv, garAge, hello",
"1, 2, 2, 4, 54",
"400, 5.4, Yes",
]
_test_environment_list_value_data_set = zip(_unsorted_tuples, _sorted_tuples)
@pytest.mark.parametrize(
"content,expected_content", _test_environment_list_value_data_set
)
def test_environment_list_value(self, testdir, content, expected_content):
expected_html_re = rf"<td>content</td>\n\s+<td>{expected_content}</td>"
testdir.makeconftest(
f"""
def pytest_configure(config):
for i in range(2):
config._metadata['content'] = {content}
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert "Environment" in html
assert len(re.findall(expected_html_re, html)) == 1
_unordered_dict = {k: len(k) for k in _unsorted_tuples[0]}
_unordered_dict_expected = (
r'<td>content</td>\n\s+<td>{"123Go": 5, "Hello": 5, '
r'"fzWZP6vKRv": 10, "garAge": 6, "hello": 5}</td>'
)
_unordered_dict_with_html = {
"First Link": r'<a href="https://www.w3schools.com">W3Schools</a>',
"Second Link": r'<a href="https://www.w3schools.com">W2Schools</a>',
"Third Link": r'<a href="https://www.w3schools.com">W4Schools</a>',
}
_unordered_dict_with_html_expected = (
r"<td>content</td>\n\s+<td>{"
r'"First Link": "<a href=\\"https://www.w3schools.com\\">W3Schools</a>", '
r'"Second Link": "<a href=\\"https://www.w3schools.com\\">W2Schools</a>", '
r'"Third Link": "<a href=\\"https://www.w3schools.com\\">W4Schools</a>"}</td>'
)
@pytest.mark.parametrize(
"unordered_dict,expected_output",
[
(_unordered_dict, _unordered_dict_expected),
(_unordered_dict_with_html, _unordered_dict_with_html_expected),
],
)
def test_environment_unordered_dict_value(
self, testdir, unordered_dict, expected_output
):
testdir.makeconftest(
f"""
def pytest_configure(config):
values = dict({json.dumps(unordered_dict)})
config._metadata['content'] = values
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert "Environment" in html
assert len(re.findall(expected_output, html)) == 1
def test_environment_ordered(self, testdir):
testdir.makeconftest(
"""
from collections import OrderedDict
def pytest_configure(config):
config._metadata = OrderedDict([('ZZZ', 1), ('AAA', 2)])
"""
)
testdir.makepyfile("def test_pass(): pass")
result, html = run(testdir)
assert result.ret == 0
assert "Environment" in html
assert len(re.findall("ZZZ.+AAA", html, re.DOTALL)) == 1
def test_xdist_crashing_worker(self, testdir):
"""https://github.com/pytest-dev/pytest-html/issues/21"""
testdir.makepyfile(
"""
import os
def test_exit():
os._exit(0)
"""
)
result, html = run(testdir, "report.html", "-n", "1")
assert "INTERNALERROR>" not in result.stdout.str()
def test_utf8_surrogate(self, testdir):
testdir.makepyfile(
r"""
import pytest
@pytest.mark.parametrize('val', ['\ud800'])
def test_foo(val):
pass
"""
)
result, html = run(testdir)
assert result.ret == 0
assert_results(html, passed=1)
@pytest.mark.parametrize(
"with_ansi",
[True, False],
)
def test_ansi_color(self, testdir, mocker, with_ansi):
if not with_ansi:
mock_ansi_support = mocker.patch("pytest_html.html_report.ansi_support")
mock_ansi_support = mocker.patch("pytest_html.result.ansi_support")
mock_ansi_support.return_value = None
pass_content = [
'<span class="ansi31">RCOLOR',
'<span class="ansi32">GCOLOR',
'<span class="ansi33">YCOLOR',
]
testdir.makepyfile(
r"""
def test_ansi():
colors = ['\033[31mRCOLOR\033[0m', '\033[32mGCOLOR\033[0m',
'\033[33mYCOLOR\033[0m']
for color in colors:
print(color)
"""
)
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret == 0
for content in pass_content:
if with_ansi:
assert content in html
else:
assert content not in html
def test_ansi_escape_sequence_removed(self, testdir):
testdir.makeini(
r"""
[pytest]
log_cli = 1
log_cli_level = INFO
"""
)
testdir.makepyfile(
r"""
import logging
logging.basicConfig()
LOGGER = logging.getLogger()
def test_ansi():
LOGGER.info("ANSI removed")
"""
)
result, html = run(
testdir, "report.html", "--self-contained-html", "--color=yes"
)
assert result.ret == 0
assert not re.search(r"\[[\d;]+m", html)
@pytest.mark.parametrize("content", ["'foo'", "u'\u0081'"])
def test_utf8_longrepr(self, testdir, content):
testdir.makeconftest(
f"""
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == 'call':
report.longrepr = 'utf8 longrepr: ' + {content}
"""
)
testdir.makepyfile(
"""
def test_fail():
testtext = 'utf8 longrepr: '
assert False
"""
)
result, html = run(testdir, "report.html", "--self-contained-html")
assert result.ret
assert "utf8 longrepr" in html
def test_collect_error(self, testdir):
testdir.makepyfile(
"""
import xyz
def test_pass(): pass
"""
)
result, html = run(testdir)
assert result.ret
assert_results(html, tests=0, passed=0, errors=1)
regex_error = "(Import|ModuleNotFound)Error: No module named .*xyz"
assert re.search(regex_error, html) is not None
@pytest.mark.parametrize("colors", [(["red"]), (["green", "blue"])])
def test_css(self, testdir, recwarn, colors):
testdir.makepyfile("def test_pass(): pass")
css = {}
cssargs = []
for color in colors:
style = f"* {{color: {color}}}"
path = testdir.makefile(".css", **{color: style})
css[color] = {"style": style, "path": path}
cssargs.extend(["--css", path])
result, html = run(testdir, "report.html", "--self-contained-html", *cssargs)