pytest文档1-环境准备与入门

前言

首先说下为什么要学pytest,在此之前相信大家已经掌握了python里面的unittest单元测试框架,那再学一个框架肯定是需要学习时间成本的。
刚开始我的内心是拒绝的,我想我用unittest也能完成自动化测试,干嘛要去学pytest呢?最近看到越来越多的招聘要求会pytest框架了,也有小伙伴出去面试说会unittest框架被鄙视的。
所以学此框架应该至少有以下2个理由,第一条已经足够:

  • 学会了可以装逼
  • 可以避免被面试官鄙视

python鄙视链:pytest 鄙视 > unittest  鄙视 > robotframework 鄙视 > 记流水账 鄙视 > “hello world”小白

pytest简介

pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。根据pytest的官方网站介绍,它具有如下特点:

  • 非常容易上手,入门简单,文档丰富,文档中有很多实例可以参考
  • 能够支持简单的单元测试和复杂的功能测试
  • 支持参数化
  • 执行测试过程中可以将某些测试跳过(skip),或者对某些预期失败的case标记成失败
  • 支持重复执行(rerun)失败的case
  • 支持运行由nose, unittest编写的测试case
  • 可生成html报告
  • 方便的和持续集成工具jenkins集成
  • 可支持执行部分用例
  • 具有很多第三方插件,并且可以自定义扩展

安装pytest

1.安装方法

pip install -U pytest

2.pip show pytest查看安装版本

pip show pytest

3.也可以pytest —version查看安装的版本

pytest —version

This is pytest version 3.6.3, imported from d:\soft\python3.6\lib\site-packagespytest.py

快速开始

1.新建一个test_sample.py文件,写以下代码

# content of test_sample.py def func(x):    return x +1 def test_answer():    assert func(3)==5

2.打开test_sample.py所在的文件夹,cmd窗口输入:pytest(或者输入py.test也可以)

D:\YOYO>pytest ============================= test session starts ============================= platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0 rootdir: D:\YOYO, inifile: collected 1 item test_sample.py F                                                         [100%] ================================== FAILURES =================================== _________________________________ test_answer _________________________________    def test_answer(): >       assert func(3)==5 E       assert 4 == 5 E        +  where 4 = func(3) test_sample.py:6: AssertionError ========================== 1 failed in 0.19 seconds ===========================

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

写个测试类

1.前面是写的一个test开头的测试函数,当用例用多个的时候,写函数就不太合适了。这时可以把多个测试用例,写到一个测试类里。

# test_class.py class TestClass:    def test_one(self):        x = "this"        assert 'h' in x    def test_two(self):        x = "hello"        assert hasattr(x, 'check')

2.打开cmd,cd到test_class.py的文件目录,如果只想运行这个文件,加上-q参数,-q参数用来指定执行的文件,不指定就执行该文件夹下所有的用例

py.test -q test_class.py

D:\YOYO>py.test -q test_class.py .F                                                                       [100%] ================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass object at 0x00000000039F1828>    def test_two(self):        x = "hello" >       assert hasattr(x, 'check') E       AssertionError: assert False E        +  where False = hasattr('hello', 'check') test_class.py:11: AssertionError 1 failed, 1 passed in 0.04 seconds

pytest用例规则

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用assert
  • 断言使用assert
    作者:上海-悠悠 QQ交流群:588402570
(0)

相关推荐