summaryrefslogtreecommitdiff
path: root/testing/test_mark.py
blob: d6a021a0b5c9655c9286c9321104fd5e2ceb57fc (plain)
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
import py, pytest
from _pytest.mark import MarkGenerator as Mark

class TestMark:
    def test_markinfo_repr(self):
        from _pytest.mark import MarkInfo
        m = MarkInfo("hello", (1,2), {})
        repr(m)

    def test_pytest_exists_in_namespace_all(self):
        assert 'mark' in py.test.__all__
        assert 'mark' in pytest.__all__

    def test_pytest_mark_notcallable(self):
        mark = Mark()
        pytest.raises((AttributeError, TypeError), mark)

    def test_pytest_mark_bare(self):
        mark = Mark()
        def f():
            pass
        mark.hello(f)
        assert f.hello

    def test_pytest_mark_keywords(self):
        mark = Mark()
        def f():
            pass
        mark.world(x=3, y=4)(f)
        assert f.world
        assert f.world.kwargs['x'] == 3
        assert f.world.kwargs['y'] == 4

    def test_apply_multiple_and_merge(self):
        mark = Mark()
        def f():
            pass
        mark.world
        mark.world(x=3)(f)
        assert f.world.kwargs['x'] == 3
        mark.world(y=4)(f)
        assert f.world.kwargs['x'] == 3
        assert f.world.kwargs['y'] == 4
        mark.world(y=1)(f)
        assert f.world.kwargs['y'] == 1
        assert len(f.world.args) == 0

    def test_pytest_mark_positional(self):
        mark = Mark()
        def f():
            pass
        mark.world("hello")(f)
        assert f.world.args[0] == "hello"
        mark.world("world")(f)

    def test_pytest_mark_reuse(self):
        mark = Mark()
        def f():
            pass
        w = mark.some
        w("hello", reason="123")(f)
        assert f.some.args[0] == "hello"
        assert f.some.kwargs['reason'] == "123"
        def g():
            pass
        w("world", reason2="456")(g)
        assert g.some.args[0] == "world"
        assert 'reason' not in g.some.kwargs
        assert g.some.kwargs['reason2'] == "456"


def test_ini_markers(testdir):
    testdir.makeini("""
        [pytest]
        markers =
            a1: this is a webtest marker
            a2: this is a smoke marker
    """)
    testdir.makepyfile("""
        def test_markers(pytestconfig):
            markers = pytestconfig.getini("markers")
            print (markers)
            assert len(markers) >= 2
            assert markers[0].startswith("a1:")
            assert markers[1].startswith("a2:")
    """)
    rec = testdir.inline_run()
    rec.assertoutcome(passed=1)

def test_markers_option(testdir):
    testdir.makeini("""
        [pytest]
        markers =
            a1: this is a webtest marker
            a1some: another marker
    """)
    result = testdir.runpytest("--markers", )
    result.stdout.fnmatch_lines([
        "*a1*this is a webtest*",
        "*a1some*another marker",
    ])

def test_mark_on_pseudo_function(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.mark.r(lambda x: 0/0)
        def test_hello():
            pass
    """)
    reprec = testdir.inline_run()
    reprec.assertoutcome(passed=1)

def test_strict_prohibits_unregistered_markers(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.mark.unregisteredmark
        def test_hello():
            pass
    """)
    result = testdir.runpytest("--strict")
    assert result.ret != 0
    result.stdout.fnmatch_lines([
        "*unregisteredmark*not*registered*",
    ])

@pytest.mark.multi(spec=[
        ("xyz", ("test_one",)),
        ("xyz and xyz2", ()),
        ("xyz2", ("test_two",)),
        ("xyz or xyz2", ("test_one", "test_two"),)
])
def test_mark_option(spec, testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.mark.xyz
        def test_one():
            pass
        @pytest.mark.xyz2
        def test_two():
            pass
    """)
    opt, passed_result = spec
    rec = testdir.inline_run("-m", opt)
    passed, skipped, fail = rec.listoutcomes()
    passed = [x.nodeid.split("::")[-1] for x in passed]
    assert len(passed) == len(passed_result)
    assert list(passed) == list(passed_result)

@pytest.mark.multi(spec=[
        ("interface", ("test_interface",)),
        ("not interface", ("test_nointer",)),
])
def test_mark_option_custom(spec, testdir):
    testdir.makeconftest("""
        import pytest
        def pytest_collection_modifyitems(items):
            for item in items:
                if "interface" in item.nodeid:
                    item.keywords["interface"] = pytest.mark.interface
    """)
    testdir.makepyfile("""
        def test_interface():
            pass
        def test_nointer():
            pass
    """)
    opt, passed_result = spec
    rec = testdir.inline_run("-m", opt)
    passed, skipped, fail = rec.listoutcomes()
    passed = [x.nodeid.split("::")[-1] for x in passed]
    assert len(passed) == len(passed_result)
    assert list(passed) == list(passed_result)

@pytest.mark.multi(spec=[
        ("interface", ("test_interface",)),
        ("not interface", ("test_nointer",)),
])
def test_keyword_option_custom(spec, testdir):
    testdir.makepyfile("""
        def test_interface():
            pass
        def test_nointer():
            pass
    """)
    opt, passed_result = spec
    rec = testdir.inline_run("-k", opt)
    passed, skipped, fail = rec.listoutcomes()
    passed = [x.nodeid.split("::")[-1] for x in passed]
    assert len(passed) == len(passed_result)
    assert list(passed) == list(passed_result)


class TestFunctional:

    def test_mark_per_function(self, testdir):
        p = testdir.makepyfile("""
            import pytest
            @pytest.mark.hello
            def test_hello():
                assert hasattr(test_hello, 'hello')
        """)
        result = testdir.runpytest(p)
        result.stdout.fnmatch_lines(["*1 passed*"])

    def test_mark_per_module(self, testdir):
        item = testdir.getitem("""
            import pytest
            pytestmark = pytest.mark.hello
            def test_func():
                pass
        """)
        keywords = item.keywords
        assert 'hello' in keywords

    def test_marklist_per_class(self, testdir):
        item = testdir.getitem("""
            import pytest
            class TestClass:
                pytestmark = [pytest.mark.hello, pytest.mark.world]
                def test_func(self):
                    assert TestClass.test_func.hello
                    assert TestClass.test_func.world
        """)
        keywords = item.keywords
        assert 'hello' in keywords

    def test_marklist_per_module(self, testdir):
        item = testdir.getitem("""
            import pytest
            pytestmark = [pytest.mark.hello, pytest.mark.world]
            class TestClass:
                def test_func(self):
                    assert TestClass.test_func.hello
                    assert TestClass.test_func.world
        """)
        keywords = item.keywords
        assert 'hello' in keywords
        assert 'world' in keywords

    @pytest.mark.skipif("sys.version_info < (2,6)")
    def test_mark_per_class_decorator(self, testdir):
        item = testdir.getitem("""
            import pytest
            @pytest.mark.hello
            class TestClass:
                def test_func(self):
                    assert TestClass.test_func.hello
        """)
        keywords = item.keywords
        assert 'hello' in keywords

    @pytest.mark.skipif("sys.version_info < (2,6)")
    def test_mark_per_class_decorator_plus_existing_dec(self, testdir):
        item = testdir.getitem("""
            import pytest
            @pytest.mark.hello
            class TestClass:
                pytestmark = pytest.mark.world
                def test_func(self):
                    assert TestClass.test_func.hello
                    assert TestClass.test_func.world
        """)
        keywords = item.keywords
        assert 'hello' in keywords
        assert 'world' in keywords

    def test_merging_markers(self, testdir):
        p = testdir.makepyfile("""
            import pytest
            pytestmark = pytest.mark.hello("pos1", x=1, y=2)
            class TestClass:
                # classlevel overrides module level
                pytestmark = pytest.mark.hello(x=3)
                @pytest.mark.hello("pos0", z=4)
                def test_func(self):
                    pass
        """)
        items, rec = testdir.inline_genitems(p)
        item, = items
        keywords = item.keywords
        marker = keywords['hello']
        assert marker.args == ("pos0", "pos1")
        assert marker.kwargs == {'x': 1, 'y': 2, 'z': 4}

        # test the new __iter__ interface
        l = list(marker)
        assert len(l) == 3
        assert l[0].args == ("pos0",)
        assert l[1].args == ()
        assert l[2].args == ("pos1", )

    @pytest.mark.xfail(reason='unfixed')
    def test_merging_markers_deep(self, testdir):
        # issue 199 - propagate markers into nested classes
        p = testdir.makepyfile("""
            import pytest
            class TestA:
                pytestmark = pytest.mark.a
                def test_b(self):
                    assert True
                class TestC:
                    # this one didnt get marked
                    def test_d(self):
                        assert True
        """)
        items, rec = testdir.inline_genitems(p)
        for item in items:
            print (item, item.keywords)
            assert 'a' in item.keywords

    def test_mark_with_wrong_marker(self, testdir):
        reprec = testdir.inline_runsource("""
                import pytest
                class pytestmark:
                    pass
                def test_func():
                    pass
        """)
        l = reprec.getfailedcollections()
        assert len(l) == 1
        assert "TypeError" in str(l[0].longrepr)

    def test_mark_dynamically_in_funcarg(self, testdir):
        testdir.makeconftest("""
            import pytest
            def pytest_funcarg__arg(request):
                request.applymarker(pytest.mark.hello)
            def pytest_terminal_summary(terminalreporter):
                l = terminalreporter.stats['passed']
                terminalreporter.writer.line("keyword: %s" % l[0].keywords)
        """)
        testdir.makepyfile("""
            def test_func(arg):
                pass
        """)
        result = testdir.runpytest()
        result.stdout.fnmatch_lines([
            "keyword: *hello*"
        ])

    def test_merging_markers_two_functions(self, testdir):
        p = testdir.makepyfile("""
            import pytest
            @pytest.mark.hello("pos1", z=4)
            @pytest.mark.hello("pos0", z=3)
            def test_func():
                pass
        """)
        items, rec = testdir.inline_genitems(p)
        item, = items
        keywords = item.keywords
        marker = keywords['hello']
        l = list(marker)
        assert len(l) == 2
        assert l[0].args == ("pos0",)
        assert l[1].args == ("pos1",)

    def test_no_marker_match_on_unmarked_names(self, testdir):
        p = testdir.makepyfile("""
            import pytest
            @pytest.mark.shouldmatch
            def test_marked():
                assert 1

            def test_unmarked():
                assert 1
        """)
        reprec = testdir.inline_run("-m", "test_unmarked", p)
        passed, skipped, failed = reprec.listoutcomes()
        assert len(passed) + len(skipped) + len(failed) == 0
        dlist = reprec.getcalls("pytest_deselected")
        deselected_tests = dlist[0].items
        assert len(deselected_tests) == 2

    def test_keywords_at_node_level(self, testdir):
        testdir.makepyfile("""
            import pytest
            @pytest.fixture(scope="session", autouse=True)
            def some(request):
                request.keywords["hello"] = 42
                assert "world" not in request.keywords

            @pytest.fixture(scope="function", autouse=True)
            def funcsetup(request):
                assert "world" in request.keywords
                assert "hello" in  request.keywords

            @pytest.mark.world
            def test_function():
                pass
        """)
        reprec = testdir.inline_run()
        reprec.assertoutcome(passed=1)

    def test_keyword_added_for_session(self, testdir):
        testdir.makeconftest("""
            import pytest
            def pytest_collection_modifyitems(session):
                session.add_marker("mark1")
                session.add_marker(pytest.mark.mark2)
                session.add_marker(pytest.mark.mark3)
                pytest.raises(ValueError, lambda:
                        session.add_marker(10))
        """)
        testdir.makepyfile("""
            def test_some(request):
                assert "mark1" in request.keywords
                assert "mark2" in request.keywords
                assert "mark3" in request.keywords
                assert 10 not in request.keywords
                marker = request.node.get_marker("mark1")
                assert marker.name == "mark1"
                assert marker.args == ()
                assert marker.kwargs == {}
        """)
        reprec = testdir.inline_run("-m", "mark1")
        reprec.assertoutcome(passed=1)

class TestKeywordSelection:
    def test_select_simple(self, testdir):
        file_test = testdir.makepyfile("""
            def test_one():
                assert 0
            class TestClass(object):
                def test_method_one(self):
                    assert 42 == 43
        """)
        def check(keyword, name):
            reprec = testdir.inline_run("-s", "-k", keyword, file_test)
            passed, skipped, failed = reprec.listoutcomes()
            assert len(failed) == 1
            assert failed[0].nodeid.split("::")[-1] == name
            assert len(reprec.getcalls('pytest_deselected')) == 1

        for keyword in ['test_one', 'est_on']:
            check(keyword, 'test_one')
        check('TestClass and test', 'test_method_one')

    @pytest.mark.parametrize("keyword", [
        'xxx', 'xxx and test_2', 'TestClass', 'xxx and -test_1',
        'TestClass and test_2', 'xxx and TestClass and test_2'])
    def test_select_extra_keywords(self, testdir, keyword):
        p = testdir.makepyfile(test_select="""
            def test_1():
                pass
            class TestClass:
                def test_2(self):
                    pass
        """)
        testdir.makepyfile(conftest="""
            def pytest_pycollect_makeitem(__multicall__, name):
                if name == "TestClass":
                    item = __multicall__.execute()
                    item.extra_keyword_matches.add("xxx")
                    return item
        """)
        reprec = testdir.inline_run(p.dirpath(), '-s', '-k', keyword)
        py.builtin.print_("keyword", repr(keyword))
        passed, skipped, failed = reprec.listoutcomes()
        assert len(passed) == 1
        assert passed[0].nodeid.endswith("test_2")
        dlist = reprec.getcalls("pytest_deselected")
        assert len(dlist) == 1
        assert dlist[0].items[0].name == 'test_1'

    def test_select_starton(self, testdir):
        threepass = testdir.makepyfile(test_threepass="""
            def test_one(): assert 1
            def test_two(): assert 1
            def test_three(): assert 1
        """)
        reprec = testdir.inline_run("-k", "test_two:", threepass)
        passed, skipped, failed = reprec.listoutcomes()
        assert len(passed) == 2
        assert not failed
        dlist = reprec.getcalls("pytest_deselected")
        assert len(dlist) == 1
        item = dlist[0].items[0]
        assert item.name == "test_one"

    def test_keyword_extra(self, testdir):
        p = testdir.makepyfile("""
           def test_one():
               assert 0
           test_one.mykeyword = True
        """)
        reprec = testdir.inline_run("-k", "mykeyword", p)
        passed, skipped, failed = reprec.countoutcomes()
        assert failed == 1

    @pytest.mark.xfail
    def test_keyword_extra_dash(self, testdir):
        p = testdir.makepyfile("""
           def test_one():
               assert 0
           test_one.mykeyword = True
        """)
        # with argparse the argument to an option cannot
        # start with '-'
        reprec = testdir.inline_run("-k", "-mykeyword", p)
        passed, skipped, failed = reprec.countoutcomes()
        assert passed + skipped + failed == 0

    def test_no_magic_values(self, testdir):
        """Make sure the tests do not match on magic values,
        no double underscored values, like '__dict__',
        and no instance values, like '()'.
        """
        p = testdir.makepyfile("""
            def test_one(): assert 1
        """)
        def assert_test_is_not_selected(keyword):
            reprec = testdir.inline_run("-k", keyword, p)
            passed, skipped, failed = reprec.countoutcomes()
            dlist = reprec.getcalls("pytest_deselected")
            assert passed + skipped + failed == 0
            deselected_tests = dlist[0].items
            assert len(deselected_tests) == 1

        assert_test_is_not_selected("__")
        assert_test_is_not_selected("()")