Is there a way to specify which pytest tests to run from a file?

前端 未结 8 588
长情又很酷
长情又很酷 2020-12-12 11:05

Is there a way to select pytest tests to run from a file? For example, a file foo.txt containing a list of tests to be executed:

tes         


        
8条回答
  •  生来不讨喜
    2020-12-12 11:54

    My answer provides a ways to run a subset of test in different scenarios.

    Run all tests in a project

    pytest
    

    Run tests in a Single Directory

    To run all the tests from one directory, use the directory as a parameter to pytest:

    pytest tests/my-directory
    

    Run tests in a Single Test File/Module

    To run a file full of tests, list the file with the relative path as a parameter to pytest:

    pytest tests/my-directory/test_demo.py
    

    Run a Single Test Function

    To run a single test function, add :: and the test function name:

    pytest -v tests/my-directory/test_demo.py::test_specific_function
    

    -v is used so you can see which function was run.

    Run a Single Test Class

    To run just a class, do like we did with functions and add ::, then the class name to the file parameter:

    pytest -v tests/my-directory/test_demo.py::TestClassName
    

    Run a Single Test Method of a Test Class

    If you don't want to run all of a test class, just one method, just add another :: and the method name:

    pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method
    

    Run a Set of Tests Based on Test Name

    The -k option enables you to pass in an expression to run tests that have certain names specified by the expression as a substring of the test name. It is possible to use and, or, and not to create complex expressions.

    For example, to run all of the functions that have _raises in their name:

    pytest -v -k _raises
    

提交回复
热议问题