pytest -k vs pytest -m in Pytest

100 Views Asked by At

I created and used custom markers orange, apple and pineapple as shown below:

# "pytest.ini"

[pytest]
markers =
    orange: Orange marker
    apple: Apple marker
    pineapple: Pineapple marker
import pytest

@pytest.mark.orange
def test1():
    assert True

@pytest.mark.apple
def test2():
    assert True

@pytest.mark.pineapple
def test3():
    assert True

Then, I ran pytest with -k orange and -m orange as shown below:

pytest -k orange
pytest -m orange

Then, there was the exactly same output as shown below:

=================== test session starts ===================
platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0
django: settings: core.settings (from ini)
rootdir: C:\Users\kai\test-django-project2
configfile: pytest.ini
plugins: django-4.5.2
collected 3 items / 2 deselected / 1 selected

tests\test_store.py .                                [100%]

============= 1 passed, 2 deselected in 0.09s =============

So, what is the difference between -k and -m in Pytest?

1

There are 1 best solutions below

0
On

-k can run the markers which contain the given string.

-m can run the markers which is exactly same as the given string.

So, if you run pytest with -k apple as shown below:

pytest -k apple

Then, apple and pineapple are run as shown below:

import pytest

@pytest.mark.orange # Not run
def test1():
    assert True

@pytest.mark.apple # Run
def test2():
    assert True

@pytest.mark.pineapple # Run
def test3():
    assert True

Next, if you run pytest with -m apple as shown below:

pytest -m apple

Then, only apple is run as shown below:

import pytest

@pytest.mark.orange # Not run
def test1():
    assert True

@pytest.mark.apple # Run
def test2():
    assert True

@pytest.mark.pineapple # Not run
def test3():
    assert True