pytest命令相关

安装

  • 在命令行中运行以下命令:

    pip install -U pytest
    
  • 检查您是否安装了正确的版本:

    pytest --version
    

常用的执行命令

  • -q简短输出,在执行用例的时候加上-q会简洁输出

    pytest -q xxx.py
    
  • -k是根据表达式匹配用例并执行用例,表达式不区分大小写,可以匹配文件名、类、方法

    • 代码示例
      # test001.py
      def test01(self):
          print(1)
      
      def test02(self):
          print(2)
      
      def test03(self):
          print(3)
      
    • 执行示例
      pytest test001.py -k "t01 or t02" # 执行包含 t01 或者包含 t02用例
      pytest test001.py -k "t01 and es" # 执行包含 t01 并且包含 es用例
      pytest test001.py -k "not t02"    # 执行不包含 t02的测试用例
      pytest test001.py -k "t01 and es or t02 and es" # 执行用例包含t01并且包含es 或者包含 t02并且包含es
      
  • -m执行某些标签用例,按照打的标签执行测试用例,可以按照表达式执行

    • 代码示例
      # test001.py
      class Test():
      
        @pytest.mark.p0
        def test01(self):
            print(1)
      
        @pytest.mark.p1
        @pytest.mark.p4
        def test02(self):
            print(2)
      
        @pytest.mark.p2
        def test03(self):
            print(3)
      
    • 执行示例
      pytest test001.py -m "p1 or p2" # 执行标签包含 p1 或者 p2用例
      pytest test001.py -m "p1 and p4" # 执行标签包含 p1 并且 p4 的标签用例用例
      pytest test001.py -m "not p2"    # 执行标签不包含 p2的测试用例
      pytest test001.py -m "p1 and p4 or p3" # 执行标签包含 p1 并且包含 p4的标签用例 或者是 p3
      
  • --markers查询可用标记,输出内置可用标记和自定义标记(自定义标记是指 pytest.ini文件自己注册的标记)

    pytest --markers 
    
  • -x ,--exitfirst在第一个错误或失败的测试时立即退出

    pytest --markers 
    
  • --fixtures, --funcargs查询可用的fixture包含内置和自定义的

    pytest --fixtures
    
  • --fixtures-per-test查询本次测试使用的fixture

    pytest xxx.py --fixtures
    
  • --runxfail忽略xfail标记,执行的时候加上--runxfail相等于没有打标签(xfail)

    pytest xxx.py --runxfail
    
  • --lf, --last-failed运行上次失败的用的,如果没有失败的将执行全部用例

    pytest --lf xxx.py
    
  • --ff, --failed-first优先运行上次执行失败的测试用例,然后在运行其他用例

    pytest --ff xxx.py
    
  • --nf, --new-first优先运行新创建的文件,比如新创建一个用例py文件执行的时候加上--nf就会先运行新创建的文件

    pytest --nf
    
  • --nf, --new-first优先运行新创建的文件,比如新创建一个用例py文件执行的时候加上--nf就会先运行新创建的文件

    pytest --nf
    
  • --cache-show查看缓存内容

    pytest --cache-show
    
  • --cache-show清除缓存内容

    pytest --cache-clear
    
  • --lfnf={all,none}配合lf使用,--lfnf=all的时候 找不到缓存和用例将运行全部用例,--lfnf=none的时候 找不到缓存和用例将不运行

    pytest --lfnf
    
  • --sw, --stepwise逐步运行,当运行到某个用例失败后立即退出测试,下次再执行的时候从失败的用例开始执行

    pytest xxx.py --sw
    
  • --sw-skip, --stepwise-skip逐步运行,遇到第一个失败用例跳过继续执行,再遇到失败将停止执行并推出,当再次执行的时候在退出的用例位子执行

    pytest xxx.py --sw-skip
    

报告相关命令

  • --durations=N显示用例最慢的n条用例,参数如果是0将显示全部的耗时,加上-vv显示详情信息
    pytest xxx.py --durations=3 -vv
    
  • --durations-min=N显示最慢的三条用例当中耗时大于1秒的用例,加上-vv显示详情信息,如果三条最慢的用例当中有两条大于一秒一条小于一秒加上-vv将会显示三条最慢的用例
    pytest --durations=3 --durations-min=1.0
    
    
  • -v, --verbose-v或者-vv显示详情信息
    pytest xx.py -v
    
    
posted @ 2022-11-10 09:32  zhq9  阅读(49)  评论(0编辑  收藏  举报