继续文档的第二章

(一)pytest中可以在命令行中静态/动态添加option,这里没什么好讲的,略过...

这里面主要讲下如何试用skip/xfail,还有incremental(包含一些列的测试步骤,如果某一步出错后,该步骤之后的所有步骤都没有任何意义了,xfail掉)

1)首先来看下怎样通过命令行来skip一些case,首先要添加个option,然后使用@pytest.mark.skipif( condition) , xfail使用@pytest.mark.xfail( condition,reson,run,raise),这里不详细介绍了

import pytest
def test_func_fast():
print 'fast'
@pytest.mark.skipif(not pytest.config.getoption("--runslow"))
def test_func_slow_1():
print 'skip slow'
@pytest.mark.xfail(not pytest.config.getoption("--runslow"))
def test_func_slow_2():
print 'xfail slow'

2)然后来看下如何实现incremental,首先在测试文件的目录下创建conftest.py, 代码如下:

# content of conftest.py

import pytest

def pytest_runtest_makereport(item, call):
if "incremental" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item def pytest_runtest_setup(item):
if "incremental" in item.keywords:
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" %previousfailed.name)

然后创建test_steps.py

# content of test_step.py
import pytest @pytest.mark.incremental
class TestUserHandling:
def test_login(self, fix_err):
pass
def test_modification(self):
assert 0
def test_deletion(self):
pass
def test_normal():
assert 0

执行结果,在test_modification后的test_deletion 执行为x

3)由于pytest中的Error也划分到Fail中,而Unittest中是单独讲Error独立出来,说明由于case中存在异常或错误导致case未能正常运行,其实在pytest中也可以做到这样,只需要加上一点儿代码,如下:

# content of test_step.py
import pytest @pytest.fixture
def fix_err(x):
raise x @pytest.mark.incremental
class TestUserHandling:
def test_modification(self):
pass
def test_login(self, fix_err):
try:
raise RuntimeError("error")
except AssertionError,e:
pass
except:
fix_err(e)
def test_deletion(self):
pass
def test_normal():
assert 0

其执行效果如下:

(二)、这里讲下关于fixture,fixture是pytest特有的功能,它用pytest.fixture标识,定义在函数前面。在你编写测试函数的时候,你可以将此函数名称做为传入参数,pytest将会以依赖注入方式,将该函数的返回值作为测试函数的传入参数。例如上面的例子fix_err.

1)准备函数usefixtures

@pytest.fixture()
def cleandir():
newpath = tempfile.mkdtemp()
os.chdir(newpath) @pytest.mark.usefixtures("cleandir")
class TestDirectoryInit:
def test_cwd_starts_empty(self):
assert os.listdir(os.getcwd()) == []
with open("myfile", "w") as f:
f.write("hello")

2)销毁函数addfinalizer

@pytest.fixture()
def smtp(request):
smtp = smtplib.SMTP("smtp.gmail.com")
def fin():
print ("teardown smtp")
smtp.close()
request.addfinalizer(fin)
return smtp # provide the fixture value

获取调用函数信息: request 使用fixture标记函数后,函数将默认接入一个request参数,它将包含使用该fixture函数的函数信息

3)fixture的参数,有时我们需要全面测试多种不同条件下的一个对象,功能是否符合预期。我们可以通过params参数来指定传入的参数。

class SMTP:
def __init__(self, smtp, sender, receiver):
self.smtp = smtp
self.sender = sender
self.receiver = receiver
def __del__(self):
self.smtp.close() @pytest.fixture(params=[["smtp.gmail.com", "from@domain.com", "to@doamin.com"], ["mail.python.org", "from@python.org", "to@python.org"])
def smtp(request):
return SMTP(#param) def test_mail(smtp):
message = "hello"
assert smtp.sendmail(message)

4)fixture的作用域:function、module、session ,autouse=True使得函数将默认执行

work_dir = "/tmp/app"
@pytest.fixture(session="session", autouse=True)
def clean_workdir():
shutil.rmtree(work_dir)
os.mkdir(work_dir)
os.chrdir(work_dir)

fixture的存在使得我们在编写测试函数的准备函数、销毁函数或者多个条件的测试提供了更加灵活的选择。py.test --fixtures 可以查看所有的fixtures,包含目录下及子目录下的conftest.py

pytest.hookimpl这个没太看明白,应该就是个钩子函数,以后弄明白了再说,今天就到这儿了,下一节再说这个参数化的问题

pytest学习笔记(二)的更多相关文章

  1. pytest学习笔记二 fixtrue

    前言 官方文档关于fixture功能的解释如下: The purpose of test fixtures is to provide a fixed baseline upon which test ...

  2. pytest 学习笔记二:兼容unittest、执行方式、生成报告

    1.官方文档上说pytest兼容unittest时,不支持setUpModule 和 tearDownModule,但实际验证是可以的. 验证的场景是py文件中,只有一个测试类, 经验证有多个测试类, ...

  3. [转载]pytest学习笔记

    pytest学习笔记(三)   接着上一篇的内容,这里主要讲下参数化,pytest很好的支持了测试函数中变量的参数化 一.pytest的参数化 1.通过命令行来实现参数化 文档中给了一个简单的例子, ...

  4. WPF的Binding学习笔记(二)

    原文: http://www.cnblogs.com/pasoraku/archive/2012/10/25/2738428.htmlWPF的Binding学习笔记(二) 上次学了点点Binding的 ...

  5. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  6. [Firefly引擎][学习笔记二][已完结]卡牌游戏开发模型的设计

    源地址:http://bbs.9miao.com/thread-44603-1-1.html 在此补充一下Socket的验证机制:socket登陆验证.会采用session会话超时的机制做心跳接口验证 ...

  7. JMX学习笔记(二)-Notification

    Notification通知,也可理解为消息,有通知,必然有发送通知的广播,JMX这里采用了一种订阅的方式,类似于观察者模式,注册一个观察者到广播里,当有通知时,广播通过调用观察者,逐一通知. 这里写 ...

  8. java之jvm学习笔记二(类装载器的体系结构)

    java的class只在需要的时候才内转载入内存,并由java虚拟机的执行引擎来执行,而执行引擎从总的来说主要的执行方式分为四种, 第一种,一次性解释代码,也就是当字节码转载到内存后,每次需要都会重新 ...

  9. Java IO学习笔记二

    Java IO学习笔记二 流的概念 在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候,就要使用输出流完成. 程序中的输入输 ...

  10. 《SQL必知必会》学习笔记二)

    <SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...

随机推荐

  1. jquery导航动画

    经常在网上看到的,鼠标在导航上移动时,导航底部的横条会自动移动到鼠标悬浮的导航项上. 效果如下图: 利用jquery的 animate 函数,很好实现.代码很简单! 代码如下: <!DOCTYP ...

  2. [Freescale]E9学习笔记-LTIB安装配置

    转自:http://blog.csdn.net/girlkoo/article/details/44535979 LTIB: Linux Target Image Builder Freescale提 ...

  3. [tty与uart]2.tty和uart的函数调用流程

    以下是在include/uapi/linux/tty.h中定义了现有的线规号,如果需要定义新的,则需要在后面添加新的 /* line disciplines */ #define N_TTY 0 #d ...

  4. 4. 对list进行sort

    一. sort命令 sort命令可以对list排序 sort命令把字段转先换为double类型在进行比较 sort排序list 127.0.0.1:6379> lrange list2 0 -1 ...

  5. UDP程序设计

        UDP是不可靠的连接,广泛应用于各种聊天工具     使用UDP发送的信息,对方不一定会接收到.所有的信息使用数据报的形式发送出去,这就要求客户端要始终等待服务器发送的信息才能进行接收.在Ja ...

  6. Service代码示例

    package com.homily.training.service; import android.app.Service; import android.content.Intent; impo ...

  7. GL_Oracle Erp常用的报表(汇总)

    2014-06-27 BaoXinjian 1. 总账系统

  8. SG函数

    入门一: 首先来玩个游戏,引用杭电课件上的: (1) 玩家:2人:(2) 道具:23张扑克牌:(3) 规则:游戏双方轮流取牌:每人每次仅限于取1张.2张或3张牌:扑克牌取光,则游戏结束:最后取牌的一方 ...

  9. [Swift]枚举

    1. Swift的枚举的基本用法: 1) 和其它语言枚举的意义相同,就是用有限的一组值(不能是无限的)来表示一些特定的含义: 2) Swift使用关键字enum定义枚举类型,定义体中用case定义成员 ...

  10. 使用t-sql从身份证号中提取生日

    使用t-sql从身份证号中提取生日,一下是转换16位身份证号的例子,仅供参考. create function getDateFromID( ) ) returns datetime as begin ...