【问题标题】:Python test fixture to run a single test?运行单个测试的 Python 测试夹具?
【发布时间】:2017-07-23 16:40:25
【问题描述】:

我正在寻找诸如 ruby​​ rspec 的 focus 元数据或 elixir 的混合标签之类的东西来运行单个 python 测试。

Ruby RSpec 示例:

# $ rspec spec
it 'runs a single test', :focus do 
  expect(2).to eq(2)
end

Elixir ExUnit & Mix 示例:

# $ mix test --only focus
@tag :focus
test "only run this test" do
  assert true
end

这是否可能/适用于任何 python 测试运行器和夹具组合?通过命令行参数指定嵌套的module.class.test_name 来运行单个测试在大型项目中可能会变得非常冗长。

有点像:

所需的 Python 代码:

# $ nosetests --only focus

from tests.fixtures import focus

class TestSomething(unittest.TestCase):
    @focus
    def test_all_the_things(self):
        self.assertEqual(1, 1)

【问题讨论】:

    标签: python unit-testing pytest nose


    【解决方案1】:

    pytest mark问好。您可以创建一个焦点标签,分配给任何测试用例或方法,然后使用pytest -v -m focus 命令运行测试。例如:

    import unittest
    import pytest
    
    class TestOne(unittest.TestCase):
        def test_method1(self):
            # I won't be executed with focus mark
            self.assertEqual(1, 1)
    
        @pytest.mark.focus
        def test_method2(self):  
            # I will be executed with focus mark          
            self.assertEqual(1, 1)
    

    将运行test_method2。要在某个 TestCase 中运行所有方法,只需标记一个类:

    import unittest
    import pytest
    
    @pytest.mark.focus
    class TestOne(unittest.TestCase):
        ...
    

    您需要在pytest.ini 中注册您的自定义标记

    [pytest]
    markers =
        focus: what is being developed right now
    

    要查看可用标记,请运行 pytest --markers

    【讨论】:

    • 我错过了什么吗?如果没有设置标记,AFAIK 这种方式将不运行任何测试,因此不可能像 rspec 允许的那样工作,您开始运行完整的测试套件,然后使用焦点深入到组或单个测试。跨度>
    【解决方案2】:

    遇到了类似的问题,想模仿 rspec 为 ruby​​ 提供的相同行为,即在没有集中测试时运行整个测试套件,但在有集中测试时只运行集中测试。

    设置与 Piotr 建议的非常相似,但增加了一个额外的步骤来过滤掉选定的测试。

    1. 按照 Piotr 在您的 pytest.inipyproject.toml 中的建议配置标记:

      [pytest]
      markers = 
          focus: what is being developed right now
      
    2. 将以下代码添加到您的根目录conftest.py

      def pytest_collection_modifyitems(session: pytest.Session, config: Any, items: list[pytest.Item]):
          focused = [i for i in items if i.get_closest_marker("focus")]
      
          if focused:
              items[:] = focused
      

    当有一个或多个测试具有焦点标记时,这将过滤收集的测试。将它与 pytest-testmon 结合使用时,您的行为与来自红宝石背景时的 guard 提供的行为相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多