[파이썬] pytest 마크(Mark) 기능 활용

Pytest is a powerful and popular testing framework for Python. It provides various features to make test writing and execution easier, including the Mark functionality. The Mark functionality allows you to tag your tests, which can be useful for categorizing and executing specific subsets of tests.

How to use Mark in Pytest

To use the Mark functionality in Pytest, you need to add special markers to your test functions or classes. These markers are written as decorators that are placed above the test functions or classes.

Here’s an example of how to use the Mark functionality in Pytest:

import pytest

@pytest.mark.smoke
def test_login():
    # Test code for the login functionality

@pytest.mark.sanity
@pytest.mark.regression
def test_search():
    # Test code for the search functionality

@pytest.mark.regression
def test_add_to_cart():
    # Test code for adding items to the cart

@pytest.mark.smoke
def test_checkout():
    # Test code for the checkout functionality

In the code above, we have used the Mark functionality to tag our tests with different markers such as smoke, sanity, and regression. These markers help us categorize our tests based on their purpose.

Running marked tests

To run tests based on their markers, you can use the -m flag followed by the marker name when executing pytest:

pytest -m smoke

The above command will only run the tests marked with the smoke marker.

pytest -m sanity or regression

The above command will run tests marked with either the sanity or regression markers.

Skipping marked tests

Sometimes you may want to skip certain tests based on their markers. To do this, you can use the skipif marker from pytest.

import pytest

@pytest.mark.skipif("sys.version_info < (3, 6)")
def test_new_feature():
    # Test code for new feature

def test_old_feature():
    # Test code for old feature

In the code above, the test test_new_feature() will be skipped if the Python version is less than 3.6.

Conclusion

The Mark functionality in Pytest provides a convenient way to categorize tests and selectively run or skip them based on their markers. This can be extremely helpful in managing and organizing test suites, especially in large projects with many tests.

By effectively utilizing the Mark functionality, you can streamline your testing process and ensure that your tests are executed efficiently and effectively.