胡胡_pytest测试框架学习笔记一

一、 环境安装

  1. 使用命令:pip pytest 进行安装;
  2. pycharm中,针对对于的工程文件,进行配置。

二、用例编写命名规范

  1. 文件,test_开头或者_test结尾。
  2. 类名,Test开头。
  3. 方法/函数,test_开头。
    【注】测试类中不可以添加__init__构造函数。

三、pytest的使用

1. 编写规范示例

sample:

def inc(x):
    return x + 1


def test_answer():
    assert inc(3) == 5


class TestDemo:
    def test_demo1(self):
        pass

运行结果:

============================= test session starts =============================
collecting ... collected 2 items

test01_sample.py::test_answer FAILED                                     [ 50%]
test01_sample.py:12 (test_answer)
4 != 5

Expected :5
Actual   :4
<Click to see difference>

def test_answer():
>       assert inc(3) == 5
E       assert 4 == 5
E        +  where 4 = inc(3)

test01_sample.py:14: AssertionError

test01_sample.py::TestDemo::test_demo1 

========================= 1 failed, 1 passed in 0.06s =========================

Process finished with exit code 1
PASSED                            [100%]

【注意】运行过程中,鼠标光标应置于最后。

2. 断言:assert

1)程序中的一阶逻辑(一种结果为真或假的逻辑),目的为了验证开发者预期的结果。
2)当程序执行到断言的位置时,对应的断言应该为真。若断言不为真时,程序会中止断言,并给出错误信息。

0614

断言写法

  • assert <表达式>
  • assert <表达式>,<描述>
    eg:
    image
def test_assert():
    a = 1
    b = 4
    expect = 3
    assert a + b == expect


def test_str():
    assert "adc" in "abcd"


import sys
def test_modules():
    assert ('linux' in sys.platform,'该代码只能在Linux执行')

执行结果:

============================= test session starts =============================
collecting ... collected 3 items

test_assert.py::test_assert FAILED                                       [ 33%]
test_assert.py:7 (test_assert)
5 != 3

Expected :3
Actual   :5
<Click to see difference>

def test_assert():
        a = 1
        b = 4
        expect = 3
>       assert a + b == expect
E       assert (1 + 4) == 3

test_assert.py:12: AssertionError

test_assert.py::test_str FAILED                                          [ 66%]
test_assert.py:14 (test_str)
'adc' != 'abcd'

Expected :'abcd'
Actual   :'adc'
<Click to see difference>

def test_str():
>       assert "adc" in "abcd"
E       AssertionError: assert 'adc' in 'abcd'

test_assert.py:16: AssertionError

test_assert.py::test_modules PASSED                                      [100%]

=================== 2 failed, 1 passed, 1 warning in 0.10s ====================

3. pytest测试框架(setup/teardown)