pytest -k 参数的用法—笔记

-k参数的用法,示例代码如下:

def test_a():
    print("test_a")

class TestDemo():

    def test_one(self):
        print("开始执行 test_one 方法")
        x = 'this'
        assert 'h' in x

    def test_two(self):
        print("开始执行 test_two 方法")
        x = 'hello'
        assert 'e' in x

    def test_three(self):
        print("开始执行 test_three 方法")
        a = 'hello'
        b = 'hello world'
        assert a not in b

class TestDemo1():
    def test_one(self):
        print("开始执行 test_one 方法")
        a = 'hello'
        b = 'hello world'
        assert a not in b

    def test_o2(self):
        print("开始执行 test_o2 方法")
        x = 'this'
        assert 'h' in x

    def test_3(self):
        print("开始执行 test_3 方法")
        x = 'hello'
        assert 'e' in x
  • 用法1:-k “类名”—>表示任意位置模糊匹配类名的所有类,并执行匹配到的这些类的所有方法
-k "TestDemo1"
  • 这里会运行TestDemo1类下的所有方法(即test_one,test_o2,test_3),运行截图如下:

  • 用法2:-k “方法名”—>表示任意位置模糊匹配方法名的所有方法,并执行匹配到的这些方法

-k "Test"
  • 这里会运行所有以test开头的方法(即test_a,test_one,test_two,test_three,test_one,test_o2,test_3),运行截图如下:

  • 用法3:-k “类名 and not 方法名”—>表示任意位置模糊匹配类名的所有类,并执行匹配到的这些类的所有方法,但不会执行任意位置模糊匹配的方法;如果多个类都有个指定的这个方法,则所有类中的这个方法都不会执行

-k "TestDemo and not test_o"
  • 这里会运行类TestDemo,TestDemo1下的,除了test_o**以外的所有方法(即test_two,test_three,test_3),运行截图如下:

  • 说明:不区分大小写

建议使用pytest的mark功能,可以自己给case加标签,比如客户端测试就可以打android/ios的标签,甚至可以加if判断是否执行,-k 这个功能说实话有点鸡肋

1 个赞

OK,非常感谢!