【问题标题】:How to test single file under pytest如何在pytest下测试单个文件
【发布时间】:2016-04-22 08:39:36
【问题描述】:

如何在 pytest 中测试单个文件?我只能在文档中找到忽略选项,而没有“仅测试此文件”选项。

最好这将在命令行而不是setup.cfg 上工作,因为我想在 ide 中运行不同的文件测试。整个套件耗时太长。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    只需使用文件路径运行pytest

    类似

    pytest tests/unit/some_test_file.py

    【讨论】:

    • 好的,这似乎是 pycharm 正在做的事情,但它仍在运行整个套件。由于某种原因,在命令行上运行 py.test 会出现段错误。我想这超出了原始问题的范围,所以如果我能让它起作用,我会接受你的回答。
    • 显然,如果在 setup.cfg 中添加路径,addopts 会出现问题。
    • @simonzack 我猜你想从文件中存在的多个测试用例中运行一个测试用例。试试这个: py.test test_basic.py -k test_first 这里 test_first 是我的 test_basic.py 文件中的一个测试用例。
    【解决方案2】:

    这很简单:

    $ pytest -v /path/to/test_file.py
    

    -v 标志是为了增加详细程度。如果您想在该文件中运行特定测试:

    $ pytest -v /path/to/test_file.py::test_name
    

    如果您想运行测试哪些名称遵循您可以使用的模式:

    $ pytest -v -k "pattern_one or pattern_two" /path/to/test_file.py
    

    您还可以选择标记测试,因此您可以使用-m 标志来运行标记测试的子集。

    test_file.py

    def test_number_one():
        """Docstring"""
        assert 1 == 1
    
    
    @pytest.mark.run_these_please
    def test_number_two():
        """Docstring"""
        assert [1] == [1]
    

    运行标有run_these_please的测试:

    $ pytest -v -m run_these_please /path/to/test_file.py
    

    【讨论】:

    • 对于path/to/test.py::test_method,我收到错误> 错误:未找到:/home/namgivu/NN/code/myproject/tests/models/test_bill.py::test_generate_for_today_normal_cycle(没有名称'/home/ [] 中的任何一个中的 namgivu/NN/code/myproject/tests/models/test_bill.py::test_generate_for_today_normal_cycle')
    • 带有 ID 的参数化测试怎么样? -k my_test[a test id here] 不起作用,到目前为止我管理的最好的格式是 -k "my_test and a and test and id and here",这几乎不是一种友好的格式。
    • 这个例子中给出的例子(特别是一个混合路径和节点选择语法)应该添加到 pytest 文档中,因为它真的不像 IMO 那样明显。
    【解决方案3】:

    这对我有用:

    python -m pytest -k some_test_file.py
    

    这也适用于单个测试功能:

    python -m pytest -k test_about_something
    

    【讨论】:

    • 这个pytest directory_to_tests/some_test_file.py 对我不起作用。我在 windows python 3.8.2 和 pytest 6.0.1
    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多