File: test_benchmark.py

package info (click to toggle)
python-pytest-benchmark 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,072 kB
  • sloc: python: 5,232; makefile: 12
file content (1211 lines) | stat: -rw-r--r-- 40,581 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
import json
import platform

import pytest

pytest_plugins = ('pytester',)
platform  # noqa: B018


def test_help(testdir):
    result = testdir.runpytest_subprocess('--help')
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            'benchmark:',
            '  --benchmark-min-time=SECONDS',
            "                        *Default: '0.000005'",
            '  --benchmark-max-time=SECONDS',
            "                        *Default: '1.0'",
            '  --benchmark-min-rounds=NUM',
            '                        *Default: 5',
            '  --benchmark-timer=FUNC',
            '  --benchmark-calibration-precision=NUM',
            '                        *Default: 10',
            '  --benchmark-warmup=[KIND]',
            '  --benchmark-warmup-iterations=NUM',
            '                        *Default: 100000',
            '  --benchmark-disable-gc',
            '  --benchmark-skip      *',
            '  --benchmark-only      *',
            '  --benchmark-save=NAME',
            '  --benchmark-autosave  *',
            '  --benchmark-save-data',
            '  --benchmark-json=PATH',
            '  --benchmark-compare=[NUM|_ID]',
            '  --benchmark-compare-fail=EXPR?[[]EXPR?...[]]',
            '  --benchmark-cprofile=COLUMN',
            '  --benchmark-storage=URI',
            "                        *Default: 'file://./.benchmarks'.",
            '  --benchmark-verbose   *',
            '  --benchmark-sort=COL  *',
            '  --benchmark-group-by=LABEL',
            "                        *Default: 'group'",
            '  --benchmark-columns=LABELS',
            '  --benchmark-histogram=[FILENAME-PREFIX]',
            '*',
        ]
    )


def test_groups(testdir):
    test = testdir.makepyfile(
        '''"""
    >>> print('Yay, doctests!')
    Yay, doctests!
"""
import time
import pytest

def test_fast(benchmark):
    benchmark(lambda: time.sleep(0.000001))
    assert 1 == 1

def test_slow(benchmark):
    benchmark(lambda: time.sleep(0.001))
    assert 1 == 1

@pytest.mark.benchmark(group="A")
def test_slower(benchmark):
    benchmark(lambda: time.sleep(0.01))
    assert 1 == 1

@pytest.mark.benchmark(group="A", warmup=True)
def test_xfast(benchmark):
    benchmark(lambda: None)
    assert 1 == 1
'''
    )
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            '*',
            'test_groups.py::*test_groups PASSED*',
            'test_groups.py::test_fast PASSED*',
            'test_groups.py::test_slow PASSED*',
            'test_groups.py::test_slower PASSED*',
            'test_groups.py::test_xfast PASSED*',
            '*',
            '* benchmark: 2 tests *',
            '*',
            "* benchmark 'A': 2 tests *",
            '*',
            '*====== 5 passed * ======*',
        ]
    )


SIMPLE_TEST = '''
"""
    >>> print('Yay, doctests!')
    Yay, doctests!
"""
import time
import pytest

def test_fast(benchmark):
    @benchmark
    def result():
        return time.sleep(0.000001)
    assert result == None

def test_slow(benchmark):
    benchmark(lambda: time.sleep(0.1))
    assert 1 == 1
'''

FIXTURES_ALSO_SKIPPED_TEST = '''
import pytest

@pytest.fixture
def dep():
    print("""
dep created""")

def test_normal(dep):
    pass

def test_bench(benchmark):
    benchmark.pedantic(lambda: None)
'''

GROUPING_TEST = """
import pytest

@pytest.mark.parametrize("foo", range(2))
@pytest.mark.benchmark(group="A")
def test_a(benchmark, foo):
    benchmark(str)

@pytest.mark.parametrize("foo", range(2))
@pytest.mark.benchmark(group="B")
def test_b(benchmark, foo):
    benchmark(int)
"""

GROUPING_PARAMS_TEST = """
import pytest

@pytest.mark.parametrize("bar", ["bar1", "bar2"])
@pytest.mark.parametrize("foo", ["foo1", "foo2"])
@pytest.mark.benchmark(group="A")
def test_a(benchmark, foo, bar):
    benchmark(str)


@pytest.mark.parametrize("bar", ["bar1", "bar2"])
@pytest.mark.parametrize("foo", ["foo1", "foo2"])
@pytest.mark.benchmark(group="B")
def test_b(benchmark, foo, bar):
    benchmark(int)
"""


def test_group_by_name(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'name', test_x, test_y)
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            '*',
            "* benchmark 'test_a[[]0[]]': 2 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_a[[]0[]]             *',
            'test_a[[]0[]]             *',
            '----------------------*',
            '*',
            "* benchmark 'test_a[[]1[]]': 2 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_a[[]1[]]             *',
            'test_a[[]1[]]             *',
            '----------------------*',
            '*',
            "* benchmark 'test_b[[]0[]]': 2 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_b[[]0[]]             *',
            'test_b[[]0[]]             *',
            '----------------------*',
            '*',
            "* benchmark 'test_b[[]1[]]': 2 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_b[[]1[]]             *',
            'test_b[[]1[]]             *',
            '----------------------*',
        ]
    )


def test_group_by_func(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'func', test_x, test_y)
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            "* benchmark 'test_a': 4 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_a[[]*[]]             *',
            'test_a[[]*[]]             *',
            'test_a[[]*[]]             *',
            'test_a[[]*[]]             *',
            '----------------------*',
            '*',
            "* benchmark 'test_b': 4 tests *",
            'Name (time in ?s)     *',
            '----------------------*',
            'test_b[[]*[]]             *',
            'test_b[[]*[]]             *',
            'test_b[[]*[]]             *',
            'test_b[[]*[]]             *',
            '----------------------*',
            '*',
            '*',
            '============* 8 passed * ============*',
        ]
    )


def test_group_by_fullfunc(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'fullfunc', test_x, test_y)
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            '*',
            "* benchmark 'test_x.py::test_a': 2 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_a[[]*[]]         *',
            'test_a[[]*[]]         *',
            '------------------*',
            '',
            "* benchmark 'test_x.py::test_b': 2 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_b[[]*[]]         *',
            'test_b[[]*[]]         *',
            '------------------*',
            '',
            "* benchmark 'test_y.py::test_a': 2 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_a[[]*[]]         *',
            'test_a[[]*[]]         *',
            '------------------*',
            '',
            "* benchmark 'test_y.py::test_b': 2 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_b[[]*[]]         *',
            'test_b[[]*[]]         *',
            '------------------*',
            '',
            'Legend:',
            '  Outliers: 1 Standard Deviation from M*',
            '============* 8 passed * ============*',
        ]
    )


def test_group_by_param_all(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'param', test_x, test_y)
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            '*',
            "* benchmark '0': 4 tests *",
            'Name (time in ?s)  *',
            '-------------------*',
            'test_*[[]0[]]          *',
            'test_*[[]0[]]          *',
            'test_*[[]0[]]          *',
            'test_*[[]0[]]          *',
            '-------------------*',
            '',
            "* benchmark '1': 4 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_*[[]1[]]         *',
            'test_*[[]1[]]         *',
            'test_*[[]1[]]         *',
            'test_*[[]1[]]         *',
            '------------------*',
            '',
            'Legend:',
            '  Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd ' 'Quartile.',
            '============* 8 passed * ============*',
        ]
    )


def test_group_by_param_select(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_PARAMS_TEST)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--benchmark-group-by', 'param:foo', '--benchmark-sort', 'fullname', test_x
    )
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            '*',
            "* benchmark 'foo=foo1': 4 tests *",
            'Name (time in ?s)  *',
            '-------------------*',
            'test_a[[]foo1-bar1[]]    *',
            'test_a[[]foo1-bar2[]]    *',
            'test_b[[]foo1-bar1[]]    *',
            'test_b[[]foo1-bar2[]]    *',
            '-------------------*',
            '',
            "* benchmark 'foo=foo2': 4 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_a[[]foo2-bar1[]]    *',
            'test_a[[]foo2-bar2[]]    *',
            'test_b[[]foo2-bar1[]]    *',
            'test_b[[]foo2-bar2[]]    *',
            '------------------*',
            '',
            'Legend:',
            '  Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd ' 'Quartile.',
            '============* 8 passed * ============*',
        ]
    )


def test_group_by_param_select_multiple(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_PARAMS_TEST)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--benchmark-group-by', 'param:foo,param:bar', '--benchmark-sort', 'fullname', test_x
    )
    result.stdout.fnmatch_lines(
        [
            '*',
            '*',
            '*',
            '*',
            '*',
            "* benchmark 'foo=foo1 bar=bar1': 2 tests *",
            'Name (time in ?s)  *',
            '-------------------*',
            'test_a[[]foo1-bar1[]]    *',
            'test_b[[]foo1-bar1[]]    *',
            '-------------------*',
            '',
            "* benchmark 'foo=foo1 bar=bar2': 2 tests *",
            'Name (time in ?s)  *',
            '-------------------*',
            'test_a[[]foo1-bar2[]]    *',
            'test_b[[]foo1-bar2[]]    *',
            '-------------------*',
            '',
            "* benchmark 'foo=foo2 bar=bar1': 2 tests *",
            'Name (time in ?s) *',
            '------------------*',
            'test_a[[]foo2-bar1[]]    *',
            'test_b[[]foo2-bar1[]]    *',
            '-------------------*',
            '',
            "* benchmark 'foo=foo2 bar=bar2': 2 tests *",
            'Name (time in ?s)  *',
            '-------------------*',
            'test_a[[]foo2-bar2[]]    *',
            'test_b[[]foo2-bar2[]]    *',
            '------------------*',
            '',
            'Legend:',
            '  Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd ' 'Quartile.',
            '============* 8 passed * ============*',
        ]
    )


def test_group_by_fullname(testdir):
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'fullname', test_x, test_y)
    result.stdout.fnmatch_lines_random(
        [
            "* benchmark 'test_x.py::test_a[[]0[]]': 1 tests *",
            "* benchmark 'test_x.py::test_a[[]1[]]': 1 tests *",
            "* benchmark 'test_x.py::test_b[[]0[]]': 1 tests *",
            "* benchmark 'test_x.py::test_b[[]1[]]': 1 tests *",
            "* benchmark 'test_y.py::test_a[[]0[]]': 1 tests *",
            "* benchmark 'test_y.py::test_a[[]1[]]': 1 tests *",
            "* benchmark 'test_y.py::test_b[[]0[]]': 1 tests *",
            "* benchmark 'test_y.py::test_b[[]1[]]': 1 tests *",
            '============* 8 passed * ============*',
        ]
    )


def test_double_use(testdir):
    test = testdir.makepyfile(
        """
def test_a(benchmark):
    benchmark(lambda: None)
    benchmark.pedantic(lambda: None)

def test_b(benchmark):
    benchmark.pedantic(lambda: None)
    benchmark(lambda: None)
"""
    )
    result = testdir.runpytest_subprocess(test, '--tb=line')
    result.stdout.fnmatch_lines(
        [
            '*FixtureAlreadyUsed: Fixture can only be used once. Previously it was used in benchmark(...) mode.',
            '*FixtureAlreadyUsed: Fixture can only be used once. Previously it was used in benchmark.pedantic(...) mode.',
        ]
    )


def test_only_override_skip(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-only', '--benchmark-skip', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 2 items',
            'test_only_override_skip.py ..*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          *',
            'test_slow          *',
            '------*',
            '*====== 2 passed * ======*',
        ]
    )


def test_fixtures_also_skipped(testdir):
    test = testdir.makepyfile(FIXTURES_ALSO_SKIPPED_TEST)
    result = testdir.runpytest_subprocess('--benchmark-only', '-s', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 2 items',
            '*====== 1 passed, 1 skipped in * ======*',
        ]
    )
    assert 'dep created' not in result.stdout.lines


def test_conflict_between_only_and_disable(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-only', '--benchmark-disable', test)
    result.stderr.fnmatch_lines(
        [
            "ERROR: Can't have both --benchmark-only and --benchmark-disable options. Note that --benchmark-disable is "
            "automatically activated if xdist is on or you're missing the statistics dependency."
        ]
    )


def test_max_time_min_rounds(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-max-time=0.000001', '--benchmark-min-rounds=1', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 3 items',
            'test_max_time_min_rounds.py ...*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          * 1  *',
            'test_slow          * 1  *',
            '------*',
            '*====== 3 passed * ======*',
        ]
    )


def test_max_time(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-max-time=0.000001', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 3 items',
            'test_max_time.py ...*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          * 5  *',
            'test_slow          * 5  *',
            '------*',
            '*====== 3 passed * ======*',
        ]
    )


def test_bogus_max_time(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-max-time=bogus', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-max-time: Invalid decimal value 'bogus': InvalidOperation*",
        ]
    )


@pytest.mark.skipif("platform.python_implementation() == 'PyPy'")
def test_pep418_timer(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-timer=pep418.perf_counter', test
    )
    result.stdout.fnmatch_lines(
        [
            '* (defaults: timer=*.perf_counter*',
        ]
    )


def test_bad_save(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-save=asd:f?', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-save: Must not contain any of these characters: /:*?<>|\\ (it has ':?')",
        ]
    )


def test_bad_save_2(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-save=', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-save: Can't be empty.",
        ]
    )


def test_bad_compare_fail(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-compare-fail=?', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-compare-fail: Could not parse value: '?'.",
        ]
    )


def test_bad_rounds(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-min-rounds=asd', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-min-rounds: invalid literal for int() with base 10: 'asd'",
        ]
    )


def test_bad_rounds_2(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-min-rounds=0', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            '*: error: argument --benchmark-min-rounds: Value for --benchmark-rounds must be at least 1.',
        ]
    )


def test_compare(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0001', '--benchmark-compare-fail=min:0.1', test
    )
    result.stderr.fnmatch_lines(
        [
            'Comparing against benchmarks from: *0001_unversioned_*.json',
        ]
    )
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0001', '--benchmark-compare-fail=min:1%', test
    )
    result.stderr.fnmatch_lines(
        [
            'Comparing against benchmarks from: *0001_unversioned_*.json',
        ]
    )


def test_compare_last(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare', '--benchmark-compare-fail=min:0.1', test
    )
    result.stderr.fnmatch_lines(
        [
            'Comparing against benchmarks from: *0001_unversioned_*.json',
        ]
    )
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare', '--benchmark-compare-fail=min:1%', test
    )
    result.stderr.fnmatch_lines(
        [
            'Comparing against benchmarks from: *0001_unversioned_*.json',
        ]
    )


def test_compare_non_existing(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0002', '-rw', test)
    result.stderr.fnmatch_lines(
        [
            "* PytestBenchmarkWarning: Can't compare. No benchmark files * '0002'.",
        ]
    )


def test_compare_non_existing_verbose(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0002', test, '--benchmark-verbose'
    )
    result.stderr.fnmatch_lines(
        [
            " WARNING: Can't compare. No benchmark files * '0002'.",
        ]
    )


def test_compare_no_files(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '-rw', test, '--benchmark-compare')
    result.stderr.fnmatch_lines(["* PytestBenchmarkWarning: Can't compare. No benchmark files in '*'. Can't load the previous benchmark."])


def test_compare_no_files_verbose(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', test, '--benchmark-compare', '--benchmark-verbose'
    )
    result.stderr.fnmatch_lines([" WARNING: Can't compare. No benchmark files in '*'." " Can't load the previous benchmark."])


def test_compare_no_files_match(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '-rw', test, '--benchmark-compare=1')
    result.stderr.fnmatch_lines(["* PytestBenchmarkWarning: Can't compare. No benchmark files in '*' match '1'."])


def test_compare_no_files_match_verbose(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess(
        '--benchmark-max-time=0.0000001', '--doctest-modules', test, '--benchmark-compare=1', '--benchmark-verbose'
    )
    result.stderr.fnmatch_lines([" WARNING: Can't compare. No benchmark files in '*' match '1'."])


def test_verbose(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-verbose', '-vv', test)
    result.stderr.fnmatch_lines(
        [
            '  Calibrating to target round *s; will estimate when reaching *s (using: *, precision: *).',
            '    Measured * iterations: *s.',
            '  Running * rounds x * iterations ...',
            '  Ran for *s.',
        ]
    )


def test_save(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-save=foobar', '--benchmark-max-time=0.0000001', test)
    result.stderr.fnmatch_lines(
        [
            'Saved benchmark data in: *',
        ]
    )
    json.loads(testdir.tmpdir.join('.benchmarks').listdir()[0].join('0001_foobar.json').read())


def test_save_extra_info(testdir):
    test = testdir.makepyfile(
        """
    def test_extra(benchmark):
        benchmark.extra_info['foo'] = 'bar'
        benchmark(lambda: None)
    """
    )
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-save=foobar', '--benchmark-max-time=0.0000001', test)
    result.stderr.fnmatch_lines(
        [
            'Saved benchmark data in: *',
        ]
    )
    info = json.loads(testdir.tmpdir.join('.benchmarks').listdir()[0].join('0001_foobar.json').read())
    bench_info = info['benchmarks'][0]
    assert bench_info['name'] == 'test_extra'
    assert bench_info['extra_info'] == {'foo': 'bar'}


def test_update_machine_info_hook_detection(testdir):
    """Tests detection and execution and update_machine_info_hooks.

    Verifies that machine info hooks are detected and executed in nested
    `conftest.py`s.

    """

    record_path_conftest = """
import os

def pytest_benchmark_update_machine_info(config, machine_info):
    machine_info["conftest_path"] = (
        machine_info.get("conftest_path", []) + [os.path.relpath(__file__)]
    )
    """

    simple_test = """
def test_simple(benchmark):
    @benchmark
    def resuilt():
        1+1
    """

    testdir.makepyfile(
        **{
            'conftest': record_path_conftest,
            'test_module/conftest': record_path_conftest,
            'test_module/tests/conftest': record_path_conftest,
            'test_module/tests/simple_test.py': simple_test,
        }
    )

    def run_verify_pytest(*args):
        testdir.runpytest_subprocess('--benchmark-json=benchmark.json', '--benchmark-max-time=0.0000001', *args)

        benchmark_json = json.loads(testdir.tmpdir.join('benchmark.json').read())
        machine_info = benchmark_json['machine_info']

        assert sorted(i.replace('\\', '/') for i in machine_info['conftest_path']) == sorted(
            [
                'conftest.py',
                'test_module/conftest.py',
                'test_module/tests/conftest.py',
            ]
        )

    run_verify_pytest('test_module/tests')
    run_verify_pytest('test_module')
    run_verify_pytest('.')


def test_histogram(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-histogram=foobar', '--benchmark-max-time=0.0000001', test)
    result.stderr.fnmatch_lines(
        [
            'Generated histogram: *foobar.svg',
        ]
    )
    assert [f.basename for f in testdir.tmpdir.listdir('*.svg', sort=True)] == [
        'foobar.svg',
    ]


def test_autosave(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-autosave', '--benchmark-max-time=0.0000001', test)
    result.stderr.fnmatch_lines(
        [
            'Saved benchmark data in: *',
        ]
    )
    json.loads(testdir.tmpdir.join('.benchmarks').listdir()[0].listdir('0001_*.json')[0].read())


def test_bogus_min_time(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-min-time=bogus', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-min-time: Invalid decimal value 'bogus': InvalidOperation*",
        ]
    )


def test_disable_gc(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-disable-gc', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 2 items',
            'test_disable_gc.py ..*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          *',
            'test_slow          *',
            '------*',
            '*====== 2 passed * ======*',
        ]
    )


def test_custom_timer(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-timer=time.time', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 2 items',
            'test_custom_timer.py ..*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          *',
            'test_slow          *',
            '------*',
            '*====== 2 passed * ======*',
        ]
    )


def test_bogus_timer(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-timer=bogus', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            '*: error: argument --benchmark-timer: Value for --benchmark-timer must be in dotted form. Eg: ' "'module.attr'.",
        ]
    )


def test_sort_by_mean(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-sort=mean', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 2 items',
            'test_sort_by_mean.py ..*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_fast          *',
            'test_slow          *',
            '------*',
            '*====== 2 passed * ======*',
        ]
    )


def test_bogus_sort(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-sort=bogus', test)
    result.stderr.fnmatch_lines(
        [
            '*usage: *',
            "*: error: argument --benchmark-sort: Unacceptable value: 'bogus'. Value for --benchmark-sort must be one "
            "of: 'min', 'max', 'mean', 'stddev', 'name', 'fullname'.",
        ]
    )


def test_xdist(testdir):
    pytest.importorskip('xdist')
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '-n', '1', '-rw', test)
    result.stderr.fnmatch_lines(
        [
            '* Benchmarks are automatically disabled because xdist plugin is active.Benchmarks cannot be '
            'performed reliably in a parallelized environment.',
        ]
    )


def test_xdist_verbose(testdir):
    pytest.importorskip('xdist')
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '-n', '1', '--benchmark-verbose', test)
    result.stderr.fnmatch_lines(
        [
            '------*',
            ' WARNING: Benchmarks are automatically disabled because xdist plugin is active.Benchmarks cannot be performed '
            'reliably in a parallelized environment.',
            '------*',
        ]
    )


def test_cprofile(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-cprofile=cumtime', test)
    result.stdout.fnmatch_lines(
        [
            '------------*----------- cProfile (time in s) ------------*-----------',
            'test_cprofile.py::test_fast',
            'ncalls	tottime	percall	cumtime	percall	filename:lineno(function)',
            # "1	0.0000	0.0000	0.0001	0.0001	test_cprofile0/test_cprofile.py:9(result)",
            # "1	0.0001	0.0001	0.0001	0.0001	~:0(<built-in method time.sleep>)",
            # "1	0.0000	0.0000	0.0000	0.0000	~:0(<method 'disable' of '_lsprof.Profiler' objects>)",
            '',
            'test_cprofile.py::test_slow',
            'ncalls	tottime	percall	cumtime	percall	filename:lineno(function)',
            # "1	0.0000	0.0000	0.1002	0.1002	test_cprofile0/test_cprofile.py:15(<lambda>)",
            # "1	0.1002	0.1002	0.1002	0.1002	~:0(<built-in method time.sleep>)",
            # "1	0.0000	0.0000	0.0000	0.0000	~:0(<method 'disable' of '_lsprof.Profiler' objects>)",
        ]
    )


def test_disabled_and_cprofile(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--benchmark-disable', '--benchmark-cprofile=cumtime', test)
    result.stdout.fnmatch_lines(
        [
            '*==== 2 passed*',
        ]
    )


def test_abort_broken(testdir):
    """
    Test that we don't benchmark code that raises exceptions.
    """
    test = testdir.makepyfile(
        '''
"""
    >>> print('Yay, doctests!')
    Yay, doctests!
"""
import time
import pytest

def test_bad(benchmark):
    @benchmark
    def result():
        raise Exception()
    assert 1 == 1

def test_bad2(benchmark):
    @benchmark
    def result():
        time.sleep(0.1)
    assert 1 == 0

@pytest.fixture(params=['a', 'b', 'c'])
def bad_fixture(request):
    raise ImportError()

def test_ok(benchmark, bad_fixture):
    @benchmark
    def result():
        time.sleep(0.1)
    assert 1 == 0
'''
    )
    result = testdir.runpytest_subprocess('-vv', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            '*',
            'test_abort_broken.py::test_bad FAILED*',
            'test_abort_broken.py::test_bad2 FAILED*',
            'test_abort_broken.py::test_ok*a* ERROR*',
            'test_abort_broken.py::test_ok*b* ERROR*',
            'test_abort_broken.py::test_ok*c* ERROR*',
            '*====== ERRORS ======*',
            '*______ ERROR at setup of test_ok[[]a[]] ______*',
            "request = <SubRequest 'bad_fixture' for <Function *test_ok*>>",
            "    @pytest.fixture(params=['a', 'b', 'c'])",
            '    def bad_fixture(request):',
            '>       raise ImportError()',
            'E       ImportError',
            'test_abort_broken.py:22: ImportError',
            '*______ ERROR at setup of test_ok[[]b[]] ______*',
            "request = <SubRequest 'bad_fixture' for <Function *test_ok*>>",
            "    @pytest.fixture(params=['a', 'b', 'c'])",
            '    def bad_fixture(request):',
            '>       raise ImportError()',
            'E       ImportError',
            'test_abort_broken.py:22: ImportError',
            '*______ ERROR at setup of test_ok[[]c[]] ______*',
            "request = <SubRequest 'bad_fixture' for <Function *test_ok*>>",
            "    @pytest.fixture(params=['a', 'b', 'c'])",
            '    def bad_fixture(request):',
            '>       raise ImportError()',
            'E       ImportError',
            'test_abort_broken.py:22: ImportError',
            '*====== FAILURES ======*',
            '*______ test_bad ______*',
            'benchmark = <pytest_benchmark.*.BenchmarkFixture object at *>',
            '    def test_bad(benchmark):',
            '?       @benchmark',
            'test_abort_broken.py:*',
            '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _*',
            '*',
            '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _*',
            '    @benchmark',
            '    def result():',
            '>       raise Exception()',
            'E       Exception',
            'test_abort_broken.py:11: Exception',
            '*______ test_bad2 ______*',
            'benchmark = <pytest_benchmark.*.BenchmarkFixture object at *>',
            '    def test_bad2(benchmark):',
            '        @benchmark',
            '        def result():',
            '            time.sleep(0.1)',
            '>       assert 1 == 0',
            'E       assert 1 == 0',
            'test_abort_broken.py:18: AssertionError',
        ]
    )

    result.stdout.fnmatch_lines(
        [
            '* benchmark: 1 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_bad2           *',
            '------*',
            '*====== 2 failed*, 3 error* ======*',
        ]
    )


BASIC_TEST = '''
"""
Just to make sure the plugin doesn't choke on doctests::
    >>> print('Yay, doctests!')
    Yay, doctests!
"""
import time
from functools import partial

import pytest

def test_fast(benchmark):
    @benchmark
    def result():
        return time.sleep(0.000001)
    assert result is None

def test_slow(benchmark):
    assert benchmark(partial(time.sleep, 0.001)) is None

def test_slower(benchmark):
    benchmark(lambda: time.sleep(0.01))

@pytest.mark.benchmark(min_rounds=2)
def test_xfast(benchmark):
    benchmark(str)

def test_fast(benchmark):
    benchmark(int)
'''


def test_basic(testdir):
    test = testdir.makepyfile(BASIC_TEST)
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            'test_basic.py::*test_basic PASSED*',
            'test_basic.py::test_fast PASSED*',
            'test_basic.py::test_slow PASSED*',
            'test_basic.py::test_slower PASSED*',
            'test_basic.py::test_xfast PASSED*',
            '',
            '* benchmark: 4 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_*         *',
            'test_*         *',
            'test_*         *',
            'test_*         *',
            '------*',
            '',
            '*====== 5 passed * ======*',
        ]
    )


def test_skip(testdir):
    test = testdir.makepyfile(BASIC_TEST)
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', '--benchmark-skip', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            'test_skip.py::*test_skip PASSED*',
            'test_skip.py::test_fast SKIPPED*',
            'test_skip.py::test_slow SKIPPED*',
            'test_skip.py::test_slower SKIPPED*',
            'test_skip.py::test_xfast SKIPPED*',
            '*====== 1 passed, 4 skipped * ======*',
        ]
    )


def test_disable(testdir):
    test = testdir.makepyfile(BASIC_TEST)
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', '--benchmark-disable', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            'test_disable.py::*test_disable PASSED*',
            'test_disable.py::test_fast PASSED*',
            'test_disable.py::test_slow PASSED*',
            'test_disable.py::test_slower PASSED*',
            'test_disable.py::test_xfast PASSED*',
            '*====== 5 passed * ======*',
        ]
    )


def test_mark_selection(testdir):
    test = testdir.makepyfile(BASIC_TEST)
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', '-m', 'benchmark', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items*',
            'test_mark_selection.py::test_xfast PASSED*',
            '* benchmark: 1 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_xfast       *',
            '------*',
            '*====== 1 passed, 4 deselected * ======*',
        ]
    )


def test_only_benchmarks(testdir):
    test = testdir.makepyfile(BASIC_TEST)
    result = testdir.runpytest_subprocess('-vv', '--doctest-modules', '--benchmark-only', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 5 items',
            'test_only_benchmarks.py::*test_only_benchmarks SKIPPED*',
            'test_only_benchmarks.py::test_fast PASSED*',
            'test_only_benchmarks.py::test_slow PASSED*',
            'test_only_benchmarks.py::test_slower PASSED*',
            'test_only_benchmarks.py::test_xfast PASSED*',
            '* benchmark: 4 tests *',
            'Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations',
            '------*',
            'test_*         *',
            'test_*         *',
            'test_*         *',
            'test_*         *',
            '------*',
            '*====== 4 passed, 1 skipped * ======*',
        ]
    )


def test_columns(testdir):
    test = testdir.makepyfile(SIMPLE_TEST)
    result = testdir.runpytest_subprocess('--doctest-modules', '--benchmark-columns=max,iterations,min', test)
    result.stdout.fnmatch_lines(
        [
            '*collected 3 items',
            'test_columns.py ...*',
            '* benchmark: 2 tests *',
            'Name (time in ?s) * Max * Iterations * Min *',
            '------*',
        ]
    )