Eric J Ma's Website

Annotating code tests and selectively running tests

written by Eric J. Ma on 2018-02-25 | tags: programming python testing software engineering


In this blog post, let me share with you how we can selectively run a test using pytest's machinery.

I just learned about a neat trick when using pytest - the ability to "mark" tests with metadata, and the ability to selectively run groups of marked tests.

Here's an example:

import pytest

@pytest.mark.slow  # annotate it as a "slow" test
def test_that_runs_slowly():
    ....

@pytest.mark.slow  # annotate test as a "slow" test.
@pytest.mark.integration  # annotate test as being an "integration" test
def test_that_does_integration():
    ....

What's really cool here is that I can selectively run slow tests or selectively run integration tests:

$ py.test -m "slow"   # only runs "slow" tests
$ py.test -m "integration"  # only runs "integration" tests
$ py.test -m "not integration"  # only runs tests that are not "integration" tests.

Cite this blog post:
@article{
    ericmjl-2018-annotating-code-tests-and-selectively-running-tests,
    author = {Eric J. Ma},
    title = {Annotating code tests and selectively running tests},
    year = {2018},
    month = {02},
    day = {25},
    howpublished = {\url{https://ericmjl.github.io}},
    journal = {Eric J. Ma's Blog},
    url = {https://ericmjl.github.io/blog/2018/2/25/annotating-code-tests-and-selectively-running-tests},
}
  

I send out a newsletter with tips and tools for data scientists. Come check it out at Substack.

# TODO(eric): learn how to learn anything. feb 2027.

If you would like to sponsor the coffee that goes into making my posts, please consider GitHub Sponsors!

learn anything --with ai --feb 2027 → 5 days · in person · a small cohort → feb 14-20, 2027 · learn-anything.nonlinearlabs.ai