You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Marker仅执行指定的Python pytest测试类?

问题原因

你的TestQuebec类继承了TestNevada类,而pytest会自动继承父类测试类的所有标记,同时也会继承父类的测试方法。所以TestQuebec不仅带有自己的G2S、Quebec标记,还继承了父类的Nevada标记。当执行pytest -m Nevada时,pytest会认为TestQuebec也符合标记条件,因此会创建它的实例并执行继承来的test_txt_24102_2测试。

解决方案

最彻底的解决方法是把父类重构为非测试基类(去掉类名的Test前缀),这样pytest不会将其视为测试类,子类也就不会继承父类的标记,同时可以复用父类的方法:

class NevadaBase:
    def step_1(self):
        print("Step 1 for Nevada")

    def step_2(self):
        print("Step 2 for Nevada")

    def step_3(self):
        print("Step 3 for Nevada")

@pytest.mark.Nevada
class TestNevada(NevadaBase):
    def test_txt_24102_2(self):
        self.step_1()
        self.step_2()
        self.step_3()

@pytest.mark.G2S
@pytest.mark.Quebec
class TestQuebec(NevadaBase):
    def step_1(self):
        print("Step 1 for Quebec")
    
    def step_2(self):
        print("Step 2 for Quebec")
    
    def test_txt_24102_2(self):
        self.step_1()
        self.step_2()
        self.step_3()

这样修改后:

  • 执行pytest -m Nevada只会运行TestNevada类的测试
  • 执行pytest -m Quebec只会运行TestQuebec类的测试
  • 两个测试类各自保留独立的标记,不会互相干扰

如果不想重构代码,也可以用命令行过滤的方式临时解决:

pytest -m "Nevada and not Quebec"

但这种方法需要每次执行都添加额外条件,不如重构基类彻底。

内容的提问来源于stack exchange,提问作者rajat shandilya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:45:55