pytest实例

一、题目:

      实现一个测试用例集合,包含3个类TestA TestB TestC,每个类包含3个方法,总共9个方法test_1到test_9,完成特定动作只要print打印即可。执行顺序如下:

      1、测试module开始执行

      2、TestA

      3、TestA teardown清理环境

      4、TestB每个方法都要有初始化,但是没有teardown

      5、TestB的3个方法包含3种参数化用例

      6、TestC的执行顺序是test8 test9 test7

     7、整个module完成执行清理环境

# -*- coding: utf-8 -*- 
# @Time : 2020/9/17 10:28 
# @Author : hl
# @File : test_word01.py

import pytest
import json
import yaml

def setup_module():
    print("\n测试module开始执行")

def teardown_module():
    print("\n整个module完成执行清理环境")

#第一个类TestA
class  TestA(object):
    @classmethod
    def teardown_class(cls):
        print("\nTestA teardown清理环境")

    @pytest.mark.run(order=1)
    def test_1(self):
        print("开始执行TestA中的方法了:")
        print("\ntest_1,测试用例1")

    @pytest.mark.run(order=2)
    def test_2(self):
        print("\ntest_2,测试用例2")

    @pytest.mark.run(order=3)
    def test_3(self):
        print("\ntest_3,测试用例3")

#第二个类TestB
class  TestB(object):
    def setup_method(self):
        print("\nsetup_method1,每个测试方法都执行一次")

    @pytest.mark.run(order=4)
    @pytest.mark.parametrize("a,b,c",[
        (1,1,2),
        (1,0,1),
        (1,-1,0)
    ])
    def test_4(self,a,b,c):
        print("test_4,测试用例4")
        print(a,b,c)
        assert a+b == c

    @pytest.mark.run(order=5)
    @pytest.mark.parametrize("a,b,c",json.load(open(r"C:\Users\洛北11\PycharmProjects\rsxq\pytest_demo\5.json")))
    def test_5(self,a,b,c):
        print("test_5,测试用例5")
        print(a,b,c)
        assert a+b == c

    @pytest.mark.run(order=6)
    @pytest.mark.parametrize("a,b,c", yaml.full_load(open(r"C:\Users\洛北11\PycharmProjects\rsxq\pytest_demo\6.yaml")))
    def test_6(self,a,b,c):
        print("test_6,测试用例6")
        print(a,b,c)
        assert a+b == c

#第三个类TestC
class  TestC(object):

    @pytest.mark.run(order=9)
    def test_7(self):
        print("test_7,测试用例7")
        assert 1==1

    @pytest.mark.run(order=7)
    def test_8(self):
        print("test_8,测试用例8")
        assert 1 == 1

    @pytest.mark.run(order=8)
    def test_9(self):
        print("test_9,测试用例9")
        assert 1 == 1

if __name__ == "__main__":
    pytest.main(["-s","test_word01.py"])    #在运行结果中打印 print 输出的代码

5.json:

[
  [1,2,3],
  [2,3,5],
  [4,5,9]
]

6.yaml:

#6.yaml
#[['1,1,2'], ['2,2,4'], ['1,2,3']]

-
  - 1
  - 1
  - 2
-
  - 2
  - 2
  - 4
-
  - 1
  - 2
  - 3

 

       
posted @ 2020-09-18 10:52  我可以2030  阅读(429)  评论(0编辑  收藏  举报