Completed
Push — master ( 5dce03...efda8a )
by Ionel Cristian
01:05
created

tests.test_help()   B

Complexity

Conditions 1

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 78
rs 8.902

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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