Believe in yourself.

Pytest学习笔记(一) 环境安装及入门

简介

  pytest是python的一个单元测试框架,类似于unittest,相对unittest来说,pytest使用更简单,功能更强大。

 

安装  

pip3 install -U pytest  

 查看版本

pytest --version

简单的测试

1、新建一个文件test_sample.py,编写如下测试用例

def func(x):
    return x + 1

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

打开cmd窗口,进入到test_sample.py所在的文件夹,执行:pytest命令

pytest运行规则:查找当前目录及其子目录下test*.py或*test.py文件,找到文件后,运行文件中以test开头的函数。

 

2、单个函数的测试用例包含在一个类中。新建一个test_class.py的文件,编写如下测试用例

class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

在cmd窗口中执行如下命令,指定需要运行的文件名

pytest -q test_class.py

参数 -q:显示简单结果。

在用pytest编写测试用例时,需遵守以下规则:

  • 测试文件应该命名为test_.py或_test.py
  • 测试方法和函数应该被命名为test_。
  • 测试类应该被命名为Test
posted @ 2019-04-18 16:21  eastonliu  阅读(1041)  评论(0编辑  收藏  举报