Completed
Pull Request — master (#37)
by
unknown
58s
created

tests.test_group_by_param()   B

Complexity

Conditions 1

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 27
rs 8.8571
1
import json
2
import platform
3
4
import pytest
5
6
pytest_plugins = 'pytester',
7
platform
8
9
10
def test_help(testdir):
11
    result = testdir.runpytest('--help')
12
    result.stdout.fnmatch_lines([
13
        "*", "*",
14
        "benchmark:",
15
        "  --benchmark-min-time=SECONDS",
16
        "                        Minimum time per round in seconds. Default: '0.000005'",
17
        "  --benchmark-max-time=SECONDS",
18
        "                        Maximum run time per test - it will be repeated until",
19
        "                        this total time is reached. It may be exceeded if test",
20
        "                        function is very slow or --benchmark-min-rounds is",
21
        "                        large (it takes precedence). Default: '1.0'",
22
        "  --benchmark-min-rounds=NUM",
23
        "                        Minimum rounds, even if total time would exceed",
24
        "                        `--max-time`. Default: 5",
25
        "  --benchmark-sort=COL  Column to sort on. Can be one of: 'min', 'max', 'mean'",
26
        "                        or 'stddev'. Default: 'min'",
27
        "  --benchmark-group-by=LABEL",
28
        "                        How to group tests. Can be one of: 'group', 'name',",
29
        "                        'fullname', 'func', 'fullfunc' or 'param'. Default:",
30
        "                        'group'",
31
        "  --benchmark-timer=FUNC",
32
        "                        Timer to use when measuring time. Default:*",
33
        "  --benchmark-calibration-precision=NUM",
34
        "                        Precision to use when calibrating number of",
35
        "                        iterations. Precision of 10 will make the timer look",
36
        "                        10 times more accurate, at a cost of less precise",
37
        "                        measure of deviations. Default: 10",
38
        "  --benchmark-warmup=[KIND]",
39
        "                        Activates warmup. Will run the test function up to",
40
        "                        number of times in the calibration phase. See",
41
        "                        `--benchmark-warmup-iterations`. Note: Even the warmup",
42
        "                        phase obeys --benchmark-max-time. Available KIND:",
43
        "                        'auto', 'off', 'on'. Default: 'auto' (automatically",
44
        "                        activate on PyPy).",
45
        "  --benchmark-warmup-iterations=NUM",
46
        "                        Max number of iterations to run in the warmup phase.",
47
        "                        Default: 100000",
48
        "  --benchmark-verbose   Dump diagnostic and progress information.",
49
        "  --benchmark-disable-gc",
50
        "                        Disable GC during benchmarks.",
51
        "  --benchmark-skip      Skip running any tests that contain benchmarks.",
52
        "  --benchmark-only      Only run benchmarks.",
53
        "  --benchmark-save=NAME",
54
        "                        Save the current run into 'STORAGE-",
55
        "                        PATH/counter_NAME.json'.",
56
        "  --benchmark-autosave  Autosave the current run into 'STORAGE-",
57
        "                        PATH/counter_*.json",
58
        "  --benchmark-save-data",
59
        "                        Use this to make --benchmark-save and --benchmark-",
60
        "                        autosave include all the timing data, not just the",
61
        "                        stats.",
62
        "  --benchmark-compare=[NUM]",
63
        "                        Compare the current run against run NUM or the latest",
64
        "                        saved run if unspecified.",
65
        "  --benchmark-compare-fail=EXPR=[EXPR=...]",
66
        "                        Fail test if performance regresses according to given",
67
        "                        EXPR (eg: min:5% or mean:0.001 for number of seconds).",
68
        "                        Can be used multiple times.",
69
        "  --benchmark-storage=STORAGE-PATH",
70
        "                        Specify a different path to store the runs (when",
71
        "                        --benchmark-save or --benchmark-autosave are used).",
72
        "                        Default: './.benchmarks/*'",
73
        "  --benchmark-histogram=[FILENAME-PREFIX]",
74
        "                        Plot graphs of min/max/avg/stddev over time in",
75
        "                        FILENAME-PREFIX-test_name.svg. If FILENAME-PREFIX",
76
        "                        contains slashes ('/') then directories will be",
77
        "                        created. Default: '*'",
78
        "  --benchmark-json=PATH",
79
        "                        Dump a JSON report into PATH. Note that this will",
80
        "                        include the complete data (all the timings, not just",
81
        "                        the stats).",
82
        "*",
83
    ])
84
85
86
def test_groups(testdir):
87
    test = testdir.makepyfile('''"""
88
    >>> print('Yay, doctests!')
89
    Yay, doctests!
90
"""
91
import time
92
import pytest
93
94
def test_fast(benchmark):
95
    benchmark(lambda: time.sleep(0.000001))
96
    assert 1 == 1
97
98
def test_slow(benchmark):
99
    benchmark(lambda: time.sleep(0.001))
100
    assert 1 == 1
101
102
@pytest.mark.benchmark(group="A")
103
def test_slower(benchmark):
104
    benchmark(lambda: time.sleep(0.01))
105
    assert 1 == 1
106
107
@pytest.mark.benchmark(group="A", warmup=True)
108
def test_xfast(benchmark):
109
    benchmark(lambda: None)
110
    assert 1 == 1
111
''')
112
    result = testdir.runpytest('-vv', '--doctest-modules', test)
113
    result.stdout.fnmatch_lines([
114
        "*collected 5 items",
115
        "*",
116
        "test_groups.py::*test_groups PASSED",
117
        "test_groups.py::test_fast PASSED",
118
        "test_groups.py::test_slow PASSED",
119
        "test_groups.py::test_slower PASSED",
120
        "test_groups.py::test_xfast PASSED",
121
        "*",
122
        "* benchmark: 2 tests *",
123
        "*",
124
        "* benchmark 'A': 2 tests *",
125
        "*",
126
        "*====== 5 passed* seconds ======*",
127
    ])
128
129
130
SIMPLE_TEST = '''
131
"""
132
    >>> print('Yay, doctests!')
133
    Yay, doctests!
134
"""
135
import time
136
import pytest
137
138
def test_fast(benchmark):
139
    @benchmark
140
    def result():
141
        return time.sleep(0.000001)
142
    assert result == None
143
144
def test_slow(benchmark):
145
    benchmark(lambda: time.sleep(0.1))
146
    assert 1 == 1
147
'''
148
149
GROUPING_TEST = '''
150
import pytest
151
152
@pytest.mark.parametrize("foo", range(2))
153
@pytest.mark.benchmark(group="A")
154
def test_a(benchmark, foo):
155
    benchmark(str)
156
157
@pytest.mark.parametrize("foo", range(2))
158
@pytest.mark.benchmark(group="B")
159
def test_b(benchmark, foo):
160
    benchmark(int)
161
'''
162
163
GROUPING_PARAMS_TEST = '''
164
import pytest
165
166
@pytest.mark.parametrize("bar", ["bar1", "bar2"])
167
@pytest.mark.parametrize("foo", ["foo1", "foo2"])
168
@pytest.mark.benchmark(group="A")
169
def test_a(benchmark, foo, bar):
170
    benchmark(str)
171
172
173
@pytest.mark.parametrize("bar", ["bar1", "bar2"])
174
@pytest.mark.parametrize("foo", ["foo1", "foo2"])
175
@pytest.mark.benchmark(group="B")
176
def test_b(benchmark, foo, bar):
177
    benchmark(int)
178
'''
179
180
181
def test_group_by_name(testdir):
182
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
183
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
184
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'name', test_x, test_y)
185
    result.stdout.fnmatch_lines([
186
        '*', '*', '*', '*', '*',
187
        "* benchmark 'test_a[[]0[]]': 2 tests *",
188
        'Name (time in ?s)     *',
189
        '----------------------*',
190
        'test_a[[]0[]]             *',
191
        'test_a[[]0[]]             *',
192
        '----------------------*',
193
        '*',
194
        "* benchmark 'test_a[[]1[]]': 2 tests *",
195
        'Name (time in ?s)     *',
196
        '----------------------*',
197
        'test_a[[]1[]]             *',
198
        'test_a[[]1[]]             *',
199
        '----------------------*',
200
        '*',
201
        "* benchmark 'test_b[[]0[]]': 2 tests *",
202
        'Name (time in ?s)     *',
203
        '----------------------*',
204
        'test_b[[]0[]]             *',
205
        'test_b[[]0[]]             *',
206
        '----------------------*',
207
        '*',
208
        "* benchmark 'test_b[[]1[]]': 2 tests *",
209
        'Name (time in ?s)     *',
210
        '----------------------*',
211
        'test_b[[]1[]]             *',
212
        'test_b[[]1[]]             *',
213
        '----------------------*',
214
    ])
215
216
217
def test_group_by_func(testdir):
218
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
219
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
220
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'func', test_x, test_y)
221
    result.stdout.fnmatch_lines([
222
        '*', '*', '*', '*',
223
        "* benchmark 'test_a': 4 tests *",
224
        'Name (time in ?s)     *',
225
        '----------------------*',
226
        'test_a[[]*[]]             *',
227
        'test_a[[]*[]]             *',
228
        'test_a[[]*[]]             *',
229
        'test_a[[]*[]]             *',
230
        '----------------------*',
231
        '*',
232
        "* benchmark 'test_b': 4 tests *",
233
        'Name (time in ?s)     *',
234
        '----------------------*',
235
        'test_b[[]*[]]             *',
236
        'test_b[[]*[]]             *',
237
        'test_b[[]*[]]             *',
238
        'test_b[[]*[]]             *',
239
        '----------------------*',
240
        '*', '*',
241
        '============* 8 passed* seconds ============*',
242
    ])
243
244
245
def test_group_by_fullfunc(testdir):
246
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
247
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
248
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'fullfunc', test_x, test_y)
249
    result.stdout.fnmatch_lines([
250
        '*', '*', '*', '*', '*',
251
        "* benchmark 'test_x.py::test_a': 2 tests *",
252
        'Name (time in ?s) *',
253
        '------------------*',
254
        'test_a[[]*[]]         *',
255
        'test_a[[]*[]]         *',
256
        '------------------*',
257
        '',
258
        "* benchmark 'test_x.py::test_b': 2 tests *",
259
        'Name (time in ?s) *',
260
        '------------------*',
261
        'test_b[[]*[]]         *',
262
        'test_b[[]*[]]         *',
263
        '------------------*',
264
        '',
265
        "* benchmark 'test_y.py::test_a': 2 tests *",
266
        'Name (time in ?s) *',
267
        '------------------*',
268
        'test_a[[]*[]]         *',
269
        'test_a[[]*[]]         *',
270
        '------------------*',
271
        '',
272
        "* benchmark 'test_y.py::test_b': 2 tests *",
273
        'Name (time in ?s) *',
274
        '------------------*',
275
        'test_b[[]*[]]         *',
276
        'test_b[[]*[]]         *',
277
        '------------------*',
278
        '',
279
        '(*) Outliers: 1 Standard Deviation from M*',
280
        '============* 8 passed* seconds ============*',
281
    ])
282
283
284
def test_group_by_param_all(testdir):
285
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
286
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
287
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'param', test_x, test_y)
288
    result.stdout.fnmatch_lines([
289
        '*', '*', '*', '*', '*',
290
        "* benchmark '0': 4 tests *",
291
        'Name (time in ?s)  *',
292
        '-------------------*',
293
        'test_*[[]0[]]          *',
294
        'test_*[[]0[]]          *',
295
        'test_*[[]0[]]          *',
296
        'test_*[[]0[]]          *',
297
        '-------------------*',
298
        '',
299
        "* benchmark '1': 4 tests *",
300
        'Name (time in ?s) *',
301
        '------------------*',
302
        'test_*[[]1[]]         *',
303
        'test_*[[]1[]]         *',
304
        'test_*[[]1[]]         *',
305
        'test_*[[]1[]]         *',
306
        '------------------*',
307
        '',
308
        '(*) Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd '
309
        'Quartile.',
310
        '============* 8 passed* seconds ============*',
311
    ])
312
313
def test_group_by_param_select(testdir):
314
    test_x = testdir.makepyfile(test_x=GROUPING_PARAMS_TEST)
315
    result = testdir.runpytest('--benchmark-max-time=0.0000001',
316
                               '--benchmark-group-by', 'param:foo',
317
                               '--benchmark-sort', 'fullname',
318
                               test_x)
319
    result.stdout.fnmatch_lines([
320
        '*', '*', '*', '*', '*',
321
        "* benchmark 'foo1': 4 tests *",
322
        'Name (time in ?s)  *',
323
        '-------------------*',
324
        'test_a[[]foo1-bar1[]]    *',
325
        'test_a[[]foo1-bar2[]]    *',
326
        'test_b[[]foo1-bar1[]]    *',
327
        'test_b[[]foo1-bar2[]]    *',
328
        '-------------------*',
329
        '',
330
        "* benchmark 'foo2': 4 tests *",
331
        'Name (time in ?s) *',
332
        '------------------*',
333
        'test_a[[]foo2-bar1[]]    *',
334
        'test_a[[]foo2-bar2[]]    *',
335
        'test_b[[]foo2-bar1[]]    *',
336
        'test_b[[]foo2-bar2[]]    *',
337
        '------------------*',
338
        '',
339
        '(*) Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd '
340
        'Quartile.',
341
        '============* 8 passed* seconds ============*',
342
    ])
343
344
345
def test_group_by_fullname(testdir):
346
    test_x = testdir.makepyfile(test_x=GROUPING_TEST)
347
    test_y = testdir.makepyfile(test_y=GROUPING_TEST)
348
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--benchmark-group-by', 'fullname', test_x, test_y)
349
    result.stdout.fnmatch_lines_random([
350
        "* benchmark 'test_x.py::test_a[[]0[]]': 1 tests *",
351
        "* benchmark 'test_x.py::test_a[[]1[]]': 1 tests *",
352
        "* benchmark 'test_x.py::test_b[[]0[]]': 1 tests *",
353
        "* benchmark 'test_x.py::test_b[[]1[]]': 1 tests *",
354
        "* benchmark 'test_y.py::test_a[[]0[]]': 1 tests *",
355
        "* benchmark 'test_y.py::test_a[[]1[]]': 1 tests *",
356
        "* benchmark 'test_y.py::test_b[[]0[]]': 1 tests *",
357
        "* benchmark 'test_y.py::test_b[[]1[]]': 1 tests *",
358
        '============* 8 passed* seconds ============*',
359
    ])
360
361
362
def test_double_use(testdir):
363
    test = testdir.makepyfile('''
364
def test_a(benchmark):
365
    benchmark(lambda: None)
366
    benchmark.pedantic(lambda: None)
367
368
def test_b(benchmark):
369
    benchmark.pedantic(lambda: None)
370
    benchmark(lambda: None)
371
''')
372
    result = testdir.runpytest(test, '--tb=line')
373
    result.stdout.fnmatch_lines([
374
        '*FixtureAlreadyUsed: Fixture can only be used once. Previously it was used in benchmark(...) mode.',
375
        '*FixtureAlreadyUsed: Fixture can only be used once. Previously it was used in benchmark.pedantic(...) mode.',
376
    ])
377
378
379
def test_conflict_between_only_and_skip(testdir):
380
    test = testdir.makepyfile(SIMPLE_TEST)
381
    result = testdir.runpytest('--benchmark-only', '--benchmark-skip', test)
382
    result.stderr.fnmatch_lines([
383
        "ERROR: Can't have both --benchmark-only and --benchmark-skip options."
384
    ])
385
386
387
def test_conflict_between_only_and_disable(testdir):
388
    test = testdir.makepyfile(SIMPLE_TEST)
389
    result = testdir.runpytest('--benchmark-only', '--benchmark-disable', test)
390
    result.stderr.fnmatch_lines([
391
        "ERROR: Can't have both --benchmark-only and --benchmark-disable options. Note that --benchmark-disable is "
392
        "automatically activated if xdist is on or you're missing the statistics dependency."
393
    ])
394
395
396
def test_max_time_min_rounds(testdir):
397
    test = testdir.makepyfile(SIMPLE_TEST)
398
    result = testdir.runpytest('--doctest-modules', '--benchmark-max-time=0.000001', '--benchmark-min-rounds=1', test)
399
    result.stdout.fnmatch_lines([
400
        "*collected 3 items",
401
        "test_max_time_min_rounds.py ...",
402
        "* benchmark: 2 tests *",
403
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
404
        "------*",
405
        "test_fast          * 1  *",
406
        "test_slow          * 1  *",
407
        "------*",
408
        "*====== 3 passed* seconds ======*",
409
    ])
410
411
412
def test_max_time(testdir):
413
    test = testdir.makepyfile(SIMPLE_TEST)
414
    result = testdir.runpytest('--doctest-modules', '--benchmark-max-time=0.000001', test)
415
    result.stdout.fnmatch_lines([
416
        "*collected 3 items",
417
        "test_max_time.py ...",
418
        "* benchmark: 2 tests *",
419
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
420
        "------*",
421
        "test_fast          * 5  *",
422
        "test_slow          * 5  *",
423
        "------*",
424
        "*====== 3 passed* seconds ======*",
425
    ])
426
427
428
def test_bogus_max_time(testdir):
429
    test = testdir.makepyfile(SIMPLE_TEST)
430
    result = testdir.runpytest('--doctest-modules', '--benchmark-max-time=bogus', test)
431
    result.stderr.fnmatch_lines([
432
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
433
        "py*: error: argument --benchmark-max-time: Invalid decimal value 'bogus': InvalidOperation*",
434
    ])
435
436
437
@pytest.mark.skipif("platform.python_implementation() == 'PyPy'")
438
def test_pep418_timer(testdir):
439
    test = testdir.makepyfile(SIMPLE_TEST)
440
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules',
441
                               '--benchmark-timer=pep418.perf_counter', test)
442
    result.stdout.fnmatch_lines([
443
        "* (defaults: timer=*.perf_counter*",
444
    ])
445
446
447
def test_bad_save(testdir):
448
    test = testdir.makepyfile(SIMPLE_TEST)
449
    result = testdir.runpytest('--doctest-modules', '--benchmark-save=asd:f?', test)
450
    result.stderr.fnmatch_lines([
451
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
452
        "py*: error: argument --benchmark-save: Must not contain any of these characters: /:*?<>|\\ (it has ':?')",
453
    ])
454
455
456
def test_bad_save_2(testdir):
457
    test = testdir.makepyfile(SIMPLE_TEST)
458
    result = testdir.runpytest('--doctest-modules', '--benchmark-save=', test)
459
    result.stderr.fnmatch_lines([
460
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
461
        "py*: error: argument --benchmark-save: Can't be empty.",
462
    ])
463
464
465
def test_bad_compare_fail(testdir):
466
    test = testdir.makepyfile(SIMPLE_TEST)
467
    result = testdir.runpytest('--doctest-modules', '--benchmark-compare-fail=?', test)
468
    result.stderr.fnmatch_lines([
469
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
470
        "py*: error: argument --benchmark-compare-fail: Could not parse value: '?'.",
471
    ])
472
473
474
def test_bad_rounds(testdir):
475
    test = testdir.makepyfile(SIMPLE_TEST)
476
    result = testdir.runpytest('--doctest-modules', '--benchmark-min-rounds=asd', test)
477
    result.stderr.fnmatch_lines([
478
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
479
        "py*: error: argument --benchmark-min-rounds: invalid literal for int() with base 10: 'asd'",
480
    ])
481
482
483
def test_bad_rounds_2(testdir):
484
    test = testdir.makepyfile(SIMPLE_TEST)
485
    result = testdir.runpytest('--doctest-modules', '--benchmark-min-rounds=0', test)
486
    result.stderr.fnmatch_lines([
487
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
488
        "py*: error: argument --benchmark-min-rounds: Value for --benchmark-rounds must be at least 1.",
489
    ])
490
491
492
def test_compare(testdir):
493
    test = testdir.makepyfile(SIMPLE_TEST)
494
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
495
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0001',
496
                               '--benchmark-compare-fail=min:0.1', test)
497
    result.stderr.fnmatch_lines([
498
        "Comparing against benchmark 0001_unversioned_*.json:",
499
    ])
500
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0001',
501
                               '--benchmark-compare-fail=min:1%', test)
502
    result.stderr.fnmatch_lines([
503
        "Comparing against benchmark 0001_unversioned_*.json:",
504
    ])
505
506
507
def test_compare_last(testdir):
508
    test = testdir.makepyfile(SIMPLE_TEST)
509
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
510
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare',
511
                               '--benchmark-compare-fail=min:0.1', test)
512
    result.stderr.fnmatch_lines([
513
        "Comparing against benchmark 0001_unversioned_*.json:",
514
    ])
515
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare',
516
                               '--benchmark-compare-fail=min:1%', test)
517
    result.stderr.fnmatch_lines([
518
        "Comparing against benchmark 0001_unversioned_*.json:",
519
    ])
520
521
522
def test_compare_non_existing(testdir):
523
    test = testdir.makepyfile(SIMPLE_TEST)
524
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
525
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0002', '-rw',
526
                               test)
527
    result.stdout.fnmatch_lines([
528
        "WBENCHMARK-C1 * Can't compare. No benchmark files matched '0002'",
529
    ])
530
531
532
def test_compare_non_existing_verbose(testdir):
533
    test = testdir.makepyfile(SIMPLE_TEST)
534
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
535
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0002',
536
                               test, '--benchmark-verbose')
537
    result.stderr.fnmatch_lines([
538
        " WARNING: Can't compare. No benchmark files matched '0002'",
539
    ])
540
541
542
def test_compare_no_files(testdir):
543
    test = testdir.makepyfile(SIMPLE_TEST)
544
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '-rw',
545
                               test, '--benchmark-compare')
546
    result.stdout.fnmatch_lines([
547
         "WBENCHMARK-C3 * Can't compare. No benchmark files in '*'. Expected files matching *.json."
548
         " Can't load the previous benchmark."
549
    ])
550
551
552
def test_compare_no_files_verbose(testdir):
553
    test = testdir.makepyfile(SIMPLE_TEST)
554
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules',
555
                               test, '--benchmark-compare', '--benchmark-verbose')
556
    result.stderr.fnmatch_lines([
557
        " WARNING: Can't compare. No benchmark files in '*'. Expected files matching *.json."
558
        " Can't load the previous benchmark."
559
    ])
560
561
562
def test_compare_no_files_match(testdir):
563
    test = testdir.makepyfile(SIMPLE_TEST)
564
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '-rw',
565
                               test, '--benchmark-compare=1')
566
    result.stdout.fnmatch_lines([
567
        "WBENCHMARK-C4 * Can't compare. No benchmark files in '*'. Expected files matching *.json."
568
         " Can't match anything to '1'."
569
    ])
570
571
572
def test_compare_no_files_match_verbose(testdir):
573
    test = testdir.makepyfile(SIMPLE_TEST)
574
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules',
575
                               test, '--benchmark-compare=1', '--benchmark-verbose')
576
    result.stderr.fnmatch_lines([
577
        " WARNING: Can't compare. No benchmark files in '*'. Expected files matching *.json."
578
        " Can't match anything to '1'."
579
    ])
580
581
582
def test_compare_too_many(testdir):
583
    test = testdir.makepyfile(SIMPLE_TEST)
584
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
585
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
586
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0', '-rw',
587
                               test)
588
    result.stdout.fnmatch_lines([
589
        "WBENCHMARK-C2 * Can't compare. Too many benchmark files matched '0':",
590
        ' - *0001_unversioned_*.json',
591
        ' - *0002_unversioned_*.json',
592
    ])
593
594
595
def test_compare_too_many_verbose(testdir):
596
    test = testdir.makepyfile(SIMPLE_TEST)
597
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
598
    testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-autosave', test)
599
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-compare=0',
600
                               '--benchmark-verbose', test)
601
    result.stderr.fnmatch_lines([
602
        " WARNING: Can't compare. Too many benchmark files matched '0':",
603
        ' - *0001_unversioned_*.json',
604
        ' - *0002_unversioned_*.json',
605
    ])
606
607
608
def test_verbose(testdir):
609
    test = testdir.makepyfile(SIMPLE_TEST)
610
    result = testdir.runpytest('--benchmark-max-time=0.0000001', '--doctest-modules', '--benchmark-verbose',
611
                               '-vv', test)
612
    result.stderr.fnmatch_lines([
613
        "  Timer precision: *s",
614
        "  Calibrating to target round *s; will estimate when reaching *s.",
615
        "    Measured * iterations: *s.",
616
        "  Running * rounds x * iterations ...",
617
        "  Ran for *s.",
618
    ])
619
620
621
def test_save(testdir):
622
    test = testdir.makepyfile(SIMPLE_TEST)
623
    result = testdir.runpytest('--doctest-modules', '--benchmark-save=foobar',
624
                               '--benchmark-max-time=0.0000001', test)
625
    result.stderr.fnmatch_lines([
626
        "Saved benchmark data in *",
627
    ])
628
    json.loads(testdir.tmpdir.join('.benchmarks').listdir()[0].join('0001_foobar.json').read())
629
630
631
def test_histogram(testdir):
632
    test = testdir.makepyfile(SIMPLE_TEST)
633
    result = testdir.runpytest('--doctest-modules', '--benchmark-histogram=foobar',
634
                               '--benchmark-max-time=0.0000001', test)
635
    result.stderr.fnmatch_lines([
636
        "Generated histogram *foobar-test_histogram.py_test_fast.svg",
637
        "Generated histogram *foobar-test_histogram.py_test_slow.svg",
638
    ])
639
    assert [f.basename for f in testdir.tmpdir.listdir("*.svg", sort=True)] == [
640
        'foobar-test_histogram.py_test_fast.svg',
641
        'foobar-test_histogram.py_test_slow.svg',
642
    ]
643
644
645
def test_autosave(testdir):
646
    test = testdir.makepyfile(SIMPLE_TEST)
647
    result = testdir.runpytest('--doctest-modules', '--benchmark-autosave',
648
                               '--benchmark-max-time=0.0000001', test)
649
    result.stderr.fnmatch_lines([
650
        "Saved benchmark data in *",
651
    ])
652
    json.loads(testdir.tmpdir.join('.benchmarks').listdir()[0].listdir('0001_*.json')[0].read())
653
654
655
def test_bogus_min_time(testdir):
656
    test = testdir.makepyfile(SIMPLE_TEST)
657
    result = testdir.runpytest('--doctest-modules', '--benchmark-min-time=bogus', test)
658
    result.stderr.fnmatch_lines([
659
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
660
        "py*: error: argument --benchmark-min-time: Invalid decimal value 'bogus': InvalidOperation*",
661
    ])
662
663
664
def test_disable_gc(testdir):
665
    test = testdir.makepyfile(SIMPLE_TEST)
666
    result = testdir.runpytest('--benchmark-disable-gc', test)
667
    result.stdout.fnmatch_lines([
668
        "*collected 2 items",
669
        "test_disable_gc.py ..",
670
        "* benchmark: 2 tests *",
671
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
672
        "------*",
673
        "test_fast          *",
674
        "test_slow          *",
675
        "------*",
676
        "*====== 2 passed* seconds ======*",
677
    ])
678
679
680
def test_custom_timer(testdir):
681
    test = testdir.makepyfile(SIMPLE_TEST)
682
    result = testdir.runpytest('--benchmark-timer=time.time', test)
683
    result.stdout.fnmatch_lines([
684
        "*collected 2 items",
685
        "test_custom_timer.py ..",
686
        "* benchmark: 2 tests *",
687
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
688
        "------*",
689
        "test_fast          *",
690
        "test_slow          *",
691
        "------*",
692
        "*====== 2 passed* seconds ======*",
693
    ])
694
695
696
def test_bogus_timer(testdir):
697
    test = testdir.makepyfile(SIMPLE_TEST)
698
    result = testdir.runpytest('--benchmark-timer=bogus', test)
699
    result.stderr.fnmatch_lines([
700
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
701
        "py*: error: argument --benchmark-timer: Value for --benchmark-timer must be in dotted form. Eg: "
702
        "'module.attr'.",
703
    ])
704
705
706
def test_sort_by_mean(testdir):
707
    test = testdir.makepyfile(SIMPLE_TEST)
708
    result = testdir.runpytest('--benchmark-sort=mean', test)
709
    result.stdout.fnmatch_lines([
710
        "*collected 2 items",
711
        "test_sort_by_mean.py ..",
712
        "* benchmark: 2 tests *",
713
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
714
        "------*",
715
        "test_fast          *",
716
        "test_slow          *",
717
        "------*",
718
        "*====== 2 passed* seconds ======*",
719
    ])
720
721
722
def test_bogus_sort(testdir):
723
    test = testdir.makepyfile(SIMPLE_TEST)
724
    result = testdir.runpytest('--benchmark-sort=bogus', test)
725
    result.stderr.fnmatch_lines([
726
        "usage: py* [[]options[]] [[]file_or_dir[]] [[]file_or_dir[]] [[]...[]]",
727
        "py*: error: argument --benchmark-sort: Unacceptable value: 'bogus'. Value for --benchmark-sort must be one of: 'min', 'max', 'mean' or 'stddev'."
728
729
    ])
730
731
732
def test_xdist(testdir):
733
    pytest.importorskip('xdist')
734
    test = testdir.makepyfile(SIMPLE_TEST)
735
    result = testdir.runpytest('--doctest-modules', '-n', '1', '-rw', test)
736
    result.stdout.fnmatch_lines([
737
        "WBENCHMARK-U2 * Benchmarks are automatically disabled because xdist plugin is active.Benchmarks cannot be "
738
        "performed reliably in a parallelized environment.",
739
    ])
740
741
742
def test_xdist_verbose(testdir):
743
    pytest.importorskip('xdist')
744
    test = testdir.makepyfile(SIMPLE_TEST)
745
    result = testdir.runpytest('--doctest-modules', '-n', '1', '--benchmark-verbose', test)
746
    result.stderr.fnmatch_lines([
747
        "------*",
748
        " WARNING: Benchmarks are automatically disabled because xdist plugin is active.Benchmarks cannot be performed "
749
        "reliably in a parallelized environment.",
750
        "------*",
751
    ])
752
753
754
def test_abort_broken(testdir):
755
    """
756
    Test that we don't benchmark code that raises exceptions.
757
    """
758
    test = testdir.makepyfile('''
759
"""
760
    >>> print('Yay, doctests!')
761
    Yay, doctests!
762
"""
763
import time
764
import pytest
765
766
def test_bad(benchmark):
767
    @benchmark
768
    def result():
769
        raise Exception()
770
    assert 1 == 1
771
772
def test_bad2(benchmark):
773
    @benchmark
774
    def result():
775
        time.sleep(0.1)
776
    assert 1 == 0
777
778
@pytest.fixture(params=['a', 'b', 'c'])
779
def bad_fixture(request):
780
    raise ImportError()
781
782
def test_ok(benchmark, bad_fixture):
783
    @benchmark
784
    def result():
785
        time.sleep(0.1)
786
    assert 1 == 0
787
''')
788
    result = testdir.runpytest('-vv', test)
789
    result.stdout.fnmatch_lines([
790
        "*collected 5 items",
791
792
        "test_abort_broken.py::test_bad FAILED",
793
        "test_abort_broken.py::test_bad2 FAILED",
794
        "test_abort_broken.py::test_ok[a] ERROR",
795
        "test_abort_broken.py::test_ok[b] ERROR",
796
        "test_abort_broken.py::test_ok[c] ERROR",
797
798
        "*====== ERRORS ======*",
799
        "*______ ERROR at setup of test_ok[[]a[]] ______*",
800
801
        "request = <SubRequest 'bad_fixture' for <Function 'test_ok[a]'>>",
802
803
        "    @pytest.fixture(params=['a', 'b', 'c'])",
804
        "    def bad_fixture(request):",
805
        ">       raise ImportError()",
806
        "E       ImportError",
807
808
        "test_abort_broken.py:22: ImportError",
809
        "*______ ERROR at setup of test_ok[[]b[]] ______*",
810
811
        "request = <SubRequest 'bad_fixture' for <Function 'test_ok[b]'>>",
812
813
        "    @pytest.fixture(params=['a', 'b', 'c'])",
814
        "    def bad_fixture(request):",
815
        ">       raise ImportError()",
816
        "E       ImportError",
817
818
        "test_abort_broken.py:22: ImportError",
819
        "*______ ERROR at setup of test_ok[[]c[]] ______*",
820
821
        "request = <SubRequest 'bad_fixture' for <Function 'test_ok[c]'>>",
822
823
        "    @pytest.fixture(params=['a', 'b', 'c'])",
824
        "    def bad_fixture(request):",
825
        ">       raise ImportError()",
826
        "E       ImportError",
827
828
        "test_abort_broken.py:22: ImportError",
829
        "*====== FAILURES ======*",
830
        "*______ test_bad ______*",
831
832
        "benchmark = <pytest_benchmark.plugin.BenchmarkFixture object at *>",
833
834
        "    def test_bad(benchmark):",
835
        ">       @benchmark",
836
        "        def result():",
837
838
        "test_abort_broken.py:*",
839
        "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _*",
840
        "*pytest_benchmark/plugin.py:*: in __call__",
841
        "    duration, iterations, loops_range = self._calibrate_timer(runner)",
842
        "*pytest_benchmark/plugin.py:*: in _calibrate_timer",
843
        "    duration = runner(loops_range)",
844
        "*pytest_benchmark/plugin.py:*: in runner",
845
        "    *",
846
        "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _*",
847
848
        "    @benchmark",
849
        "    def result():",
850
        ">       raise Exception()",
851
        "E       Exception",
852
853
        "test_abort_broken.py:11: Exception",
854
        "*______ test_bad2 ______*",
855
856
        "benchmark = <pytest_benchmark.plugin.BenchmarkFixture object at *>",
857
858
        "    def test_bad2(benchmark):",
859
        "        @benchmark",
860
        "        def result():",
861
        "            time.sleep(0.1)",
862
        ">       assert 1 == 0",
863
        "E       assert 1 == 0",
864
865
        "test_abort_broken.py:18: AssertionError",
866
        "* benchmark: 1 tests *",
867
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
868
        "------*",
869
        "test_bad2           *",
870
        "------*",
871
872
        "*====== 2 failed*, 3 error* seconds ======*",
873
    ])
874
875
876
BASIC_TEST = '''
877
"""
878
Just to make sure the plugin doesn't choke on doctests::
879
    >>> print('Yay, doctests!')
880
    Yay, doctests!
881
"""
882
import time
883
from functools import partial
884
885
import pytest
886
887
def test_fast(benchmark):
888
    @benchmark
889
    def result():
890
        return time.sleep(0.000001)
891
    assert result is None
892
893
def test_slow(benchmark):
894
    assert benchmark(partial(time.sleep, 0.001)) is None
895
896
def test_slower(benchmark):
897
    benchmark(lambda: time.sleep(0.01))
898
899
@pytest.mark.benchmark(min_rounds=2)
900
def test_xfast(benchmark):
901
    benchmark(str)
902
903
def test_fast(benchmark):
904
    benchmark(int)
905
'''
906
907
908
def test_basic(testdir):
909
    test = testdir.makepyfile(BASIC_TEST)
910
    result = testdir.runpytest('-vv', '--doctest-modules', test)
911
    result.stdout.fnmatch_lines([
912
        "*collected 5 items",
913
        "test_basic.py::*test_basic PASSED",
914
        "test_basic.py::test_slow PASSED",
915
        "test_basic.py::test_slower PASSED",
916
        "test_basic.py::test_xfast PASSED",
917
        "test_basic.py::test_fast PASSED",
918
        "",
919
        "* benchmark: 4 tests *",
920
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
921
        "------*",
922
        "test_*         *",
923
        "test_*         *",
924
        "test_*         *",
925
        "test_*         *",
926
        "------*",
927
        "",
928
        "*====== 5 passed* seconds ======*",
929
    ])
930
931
932
def test_skip(testdir):
933
    test = testdir.makepyfile(BASIC_TEST)
934
    result = testdir.runpytest('-vv', '--doctest-modules', '--benchmark-skip', test)
935
    result.stdout.fnmatch_lines([
936
        "*collected 5 items",
937
        "test_skip.py::*test_skip PASSED",
938
        "test_skip.py::test_slow SKIPPED",
939
        "test_skip.py::test_slower SKIPPED",
940
        "test_skip.py::test_xfast SKIPPED",
941
        "test_skip.py::test_fast SKIPPED",
942
        "*====== 1 passed, 4 skipped* seconds ======*",
943
    ])
944
945
946
def test_disable(testdir):
947
    test = testdir.makepyfile(BASIC_TEST)
948
    result = testdir.runpytest('-vv', '--doctest-modules', '--benchmark-disable', test)
949
    result.stdout.fnmatch_lines([
950
        "*collected 5 items",
951
        "test_disable.py::*test_disable PASSED",
952
        "test_disable.py::test_slow PASSED",
953
        "test_disable.py::test_slower PASSED",
954
        "test_disable.py::test_xfast PASSED",
955
        "test_disable.py::test_fast PASSED",
956
        "*====== 5 passed * seconds ======*",
957
    ])
958
959
960
def test_mark_selection(testdir):
961
    test = testdir.makepyfile(BASIC_TEST)
962
    result = testdir.runpytest('-vv', '--doctest-modules', '-m', 'benchmark', test)
963
    result.stdout.fnmatch_lines([
964
        "*collected 5 items",
965
        "test_mark_selection.py::test_xfast PASSED",
966
        "* benchmark: 1 tests *",
967
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
968
        "------*",
969
        "test_xfast       *",
970
        "------*",
971
        "*====== 4 tests deselected by \"-m 'benchmark'\" ======*",
972
        "*====== 1 passed, 4 deselected* seconds ======*",
973
    ])
974
975
976
def test_only_benchmarks(testdir):
977
    test = testdir.makepyfile(BASIC_TEST)
978
    result = testdir.runpytest('-vv', '--doctest-modules', '--benchmark-only', test)
979
    result.stdout.fnmatch_lines([
980
        "*collected 5 items",
981
        "test_only_benchmarks.py::*test_only_benchmarks SKIPPED",
982
        "test_only_benchmarks.py::test_slow PASSED",
983
        "test_only_benchmarks.py::test_slower PASSED",
984
        "test_only_benchmarks.py::test_xfast PASSED",
985
        "test_only_benchmarks.py::test_fast PASSED",
986
        "* benchmark: 4 tests *",
987
        "Name (time in ?s) * Min * Max * Mean * StdDev * Rounds * Iterations",
988
        "------*",
989
        "test_*         *",
990
        "test_*         *",
991
        "test_*         *",
992
        "test_*         *",
993
        "------*",
994
        "*====== 4 passed, 1 skipped* seconds ======*",
995
    ])
996
997
def test_columns(testdir):
998
    test = testdir.makepyfile(SIMPLE_TEST)
999
    result = testdir.runpytest('--doctest-modules', '--benchmark-columns=max,iterations,min', test)
1000
    result.stdout.fnmatch_lines([
1001
        "*collected 3 items",
1002
        "test_columns.py ...",
1003
        "* benchmark: 2 tests *",
1004
        "Name (time in ?s) * Max * Iterations * Min *",
1005
        "------*",
1006
    ])
1007