appium python 断言中何时使用断言

Python中何时使用断言_百度知道
Python中何时使用断言
提问者采纳
eggplant'  断言指的是break吗:  
if i == &#39.  A orange is fruit:  
print &#39, ' %
i  ----------------打印结果如下-------------------  A apple is fruit.'eggplant'A %s is not fruit:  A]  for i in lis, 'orange'pear&#39.    当把if中的break条件去掉后打印结果如下;, &#39.  A pear is fruit.  Abanana':  lis = [&#39?如果是break的话就看我下面写的程序.  A eggplant is not fruit, &#39.'apple';.  A eA % %
print &#39.  A banana is fruit
来自团队:
其他类似问题
为您推荐:
python的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁下次自动登录
现在的位置:
Python BDD自动化测试框架初探
全称Behavior Driven Development,译作"",是基于 (Test Driven Development 测试驱动开发)的软件开发过程和方法。
BDD可以让项目成员(甚至是不懂编程的)使用自然语言来描述系统功能和场景,从而根据这些描述步骤进行系统自动化的测试。(详见附录4.1)
2. 常用BDD框架介绍
目前常用的BDD测试框架有Ruby中的Cucumber,中的Behave、Lettuce及Freshen等。
基本的流程如下图所示(Lettuce官方图):
简单来说就是"写用例-&跑测试-&看结果-&写实现-&看结果"这样的一个循环。
Behave网站列出了上面提到的几个框架的对比(详见附录4.2),基于此原因,本文选择来介绍 BDD框架。
3. Behave示例
3.1 Behave安装
pip install behave # 全新安装
pip install -U behave # 更新
3.2 基础知识
3.2.1 语法
上文提到的几种BDD框架均使用 语法,这是一种简单易懂的语言,使用关键字来定义系统特征和测试。
使用Gherkin语法编写的feature文件基本结构如下:
Title (one line describing the story/feature)
Scenario: Title1 (for Behaviour 1)
[context or setup]
[some more context]...
[event occurs]
[expected outcome]
[another outcome]...
Scenario: Title2 (for Behaviour 2)
3.2.2 断言模块
使用BDD测试框架前,需要选择一个好用的断言模块。有很多可用的断言模块(下表),本文我们选择hamcrest模块为例。
3.2.3 目录结构
Behave项目的目录格式如下:
+-- features/
-- Contains all feature files.
+-- steps/
+-- step_*.py
-- Step definitions for features.
+-- environment.py
-- Environment for global setup...
+-- tutorial*.feature
-- Feature files.
3.3 Behave示例
我们以fibnacci数列计算为例,来了解下框架结构及如何使用(网上基本都是以阶乘或WEB页面为例,为显示本文的原创性,我们以fib数列为例)
首先,比较pythonic的实现fib数列的代码如下:
# -*- coding:utf-8 -*-
def fibs(num):
for i in range(num):
print list(fibs(10))
使用behave的详细步骤如下:
1. 新建目录fib,在此目录下新建文件fib.feature,内容如下
Feature:Calc Fib
In order to introduce Behave
We calc fib as example
Scenario: Calc fib number
Given we have the number 10
when we calc the fib
then we get the fib number 55
2. 新建目录fib/steps,在此目录下新建文件fib.py,内容如下
from behave import *
from hamcrest import *
def fibs(num):
for i in range(num):
@given('we have the number {number}')
def have_number(context,number):
context.fib_number = int(number)
@when('we calc the fib')
def calc_fib(context):
context.fib_number=list(fibs(context.fib_number))[-1]
@then('we get the fib number {number}')
def get_number(context,number):
context.expected_number = int(number)
assert_that(context.fib_number, equal_to(context.expected_number),&Calc fib number: %d& %context.fib_number)
这段Python代码主要分为三部分:
@given部分将输入的number=10转为整形并存入变量中
@when部分调用fib函数,计算fib数列值
@then 部分将计算出的fib值与预期值进行断言比较,判断结果是否相等
3. 切换到fib目录,执行behave命令,结果如下
4. Scenario Outlines场景大纲
有时相同的一个Scenario需要在很多不同的参数情况下运行,为了避免写过多重复的Scenario ,我们需要使用Scenario Outlines,如fib.feature文件内容可以修改如下:
Feature:Calc Fib
In order to introduce Behave
We calc fib as example
Scenario Outline: Calc fib number
Given we have the number &number&
when we calc the fib
then we get the fib number &fib_number&
Examples: Some Numbers
| fib_number |
执行结果如下:
5. 更多的beahve示例可以参考附录4.4
作者只对Python BDD自动化测试框架进行了简单了解和学习,没有在实际的项目中进行实践,本文只算是一篇BDD自动化测试的入门。
各位若想更深入了解BDD,可参考如下网页资料:
4.1 BDD详细介绍:
4.2 常用测试框架对比:
4.3 Hamcrest断言模块:
4.4 Behave示例:
【上篇】【下篇】
您可能还会对这些文章感兴趣!
百度站内搜索Python 使用断言的最佳时机 - 开源中国社区
当前访客身份:游客 [
Python 使用断言的最佳时机
英文原文:
The question of when to use the assert statement comes up occasionally,
usually in response to somebody misusing it, so I thought I'd write a
post describing when and why to use assertions, and when not to.
For those who aren't aware of it, Python's &assert& checks a condition,
if it is true it does nothing, and if it is false it raises an
AssertionError with an optional error message. For example:
py& x = 23
py& assert x & 0, &x is not zero or negative&
py& assert x%2 == 0, &x is not an even number&
Traceback (most recent call last):
& File &&stdin&&, line 1, in &module&
AssertionError: x is not an even number
使用断言的最佳时机偶尔会被提起,通常是因为有人误用,因此我觉得有必要写一篇文章来阐述一下什么时候应该用断言,为什么应该用,什么时候不该用。
对那些没有意识到用断言的最佳时机的人来说,Python的断言就是检测一个条件,如果条件为真,它什么都不做;反之它触发一个带可选错误信息的AssertionError。如下例所示:
py& x = 23
py& assert x & 0, &x is not zero or negative&
py& assert x%2 == 0, &x is not an even number&
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
AssertionError: x is not an even number
Many people use asserts as a quick and easy way to raise an exception if
an argument is given the wrong value. But this is wrong, dangerously
wrong, for two reasons. The first is that AssertionError is usually the
wrong error to give when testing function arguments. You wouldn't write
code like this:
if not isinstance(x, int):
&&& raise AssertionError(&not an int&)
you'd raise TypeError instead. &assert& raises the wrong sort of
exception.
But, and more dangerously, there's a twist with assert: it can be
compiled away and never executed, if you run Python with the -O or -OO
optimization flags, and consequently there is no guarantee that assert
statements will actually be run. When using assert properly, this is a
feature, but when assert is used inappropriately, it leads to code that
is completely broken when running with the -O flag.
很多人将断言作为当传递了错误的参数值时的一种快速而简便的触发异常的方式。但实际上这是错误的,而且是非常危险的错误,原因有两点。首先,AssertionError通常是在测试函数参数时给出的错误。你不会像下面这样编码:
if not isinstance(x, int):
raise AssertionError(&not and int&) 你应该用TypeError来替代,“断言”解决了错误的异常类型。
但是对断言来说更危险也更纠结的是:如果你执行Python时使用了-O或-OO优化标识,这能够通过编译却从来不会被执行,实际上就是说并不能保证断言会被执行。当恰当地使用了断言,这非常好的,但当不恰当地使用了断言,在使用-O标识执行时它将导致代码被彻底中断。
When should use assert? In no particular order, assertions should be used
* runtime che
* checking contracts (e.g. pre-conditions and post-conditions);
* checked documentation.
(It's also acceptable to use assert when testing code, as a sort of quick-
and-dirty poor man's unit testing, so long as you accept that the tests
simply won't do anything if you run with the -O flag. And I sometimes use
&assert False& in code to mark code branches that haven't been written
yet, and I want them to fail. Although &raise NotImplementedError& is
probably better for that, if a little more verbose.)
那么我们什么时候应该使用断言呢?如果没有特别的目的,断言应该用于如下情况:
防御性的编程
运行时对程序逻辑的检测
合约性检查(比如前置条件,后置条件)
程序中的常量
(断言也可以用于代码测试,用作一个做事毛手毛脚的开发人员的单元测试,只要能你接受当使用-O标志时这个测试什么都不做。我有时也会在代码中用&assert Fasle&来对还没有实现的分支作标记,当然我希望他们失败。如果稍微更细节一些,或许触发NotImplementedError是更好的选择)
Opinions on assertions vary, because they can be a statement of
confidence about the correctness of the code. If you're certain that the
code is correct, then assertions are pointless, since they will never
fail and you can safely remove them. If you're certain the checks can
fail (e.g. when testing input data provided by the user), then you dare
not use assert since it may be compiled away and then your checks will be
It's the situations in between those two that are interesting, times when
you're certain the code is correct but not *quite* absolutely certain.
Perhaps you've missed some odd corner case (we're all only human). In
this case an extra runtime check helps reassure you that any errors will
be caught as early as possible rather than in distant parts of the code.
因为程序员是对于代码正确性表现出的信心不同,因此对于什么时候使用断言的意见各不相同。如果你确信代码是正确的,那么断言没有任何意义,因为它们从不会失败,因此你可以放心地移除它们。如果你确信它们会失败(例如对用户输入的数据的检测),你不敢用断言,这样编译就能通过,但你跳过了你的检查。
在以上两种情况之间的情况就显得特别有趣了,那就是当你相信代码是正确的,但又不是特别确定的时候。或许你忘记了一些奇怪的边角情况(因为我们都是人),在这种情况下,额外的运行时检查将帮助你尽可能早地捕获错误,而不是写了一大堆代码之后。
(This is why assert can be divisive. Since we vary in our confidence
about the correctness of code, one person's useful assert is another
person's useless runtime test.)
Another good use for asserts is checking program invariants. An invariant
is some condition which you can rely on to be true unless a bug causes it
to become false. If there's a bug, better to find out as early as
possible, so we make a test for it, but we don't want to slow the code
down with such tests. Hence assert, which can be turned on in development
and off in production.
(这就是为什么使用断言的时机会不同。因为我们对代码正确性的信息不同,对于一个人有用的断言,对于另一个人来说却是无用的运行时测试。)
另一个断言用得好的地方就是检查程序中的不变量。一个不变量是一些你能相信为真的条件,除非一个缺陷导致它变成假。如果有一个缺陷,越早发现越好,因此我们需要对其进行测试,但我们不想因为这些测试而影响代码执行速度。因此采用断言,它能在开发时生效而在产品中失效。
An example of an invariant might be, if your function expects a database
connection to be open when it starts, and promises that it will still be
open when it returns, that's an invariant of the function:
def some_function(arg):
&&& assert not DB.closed()
&&& ... # code goes here
&&& assert not DB.closed()
&&& return result
Assertions also make good checked comments. Instead of writing a comment:
# when we reach here, we know that n & 2
you can ensure it is checked at runtime by turning it into an assert:
assert n & 2
一个关于不变量的例子可能是这样的情况。如果你的函数在开始的时候期望一个打开的数据库连接,并且在函数返回后该数据库连接依然是打开的,这是一个函数的不变量:
def some_function(arg):
assert not DB.closed()
... # code goes here
assert not DB.closed()
return result 断言也是一个很好的检查点注释。为了替代如下注释:
#当我们执行到这里,我们知道n&2
你可以确保在运行时用以下断言:
assert n & 2
Assertions are also a form of defensive programming. You're not
protecting against errors in the code as it is now, but protecting
against changes which introduce errors later. Ideally, unit tests will
pick those up, but let's face it, even when tests exist at all, they're
often incomplete. Build-bots can be down and nobody notices for weeks, or
people forget to run tests before committing code. Having an internal
check is another line of defence against errors sneaking in, especially
those which don't noisily fail but cause the code to malfunction and
return incorrect results.
Suppose you have a series of if...elif blocks, where you know ahead of
time what values some variable is expected to have:
# target is expected to be one of x, y, or z, and nothing else.
if target == x:
&&& run_x_code()
elif target == y:
&&& run_y_code()
&&& run_z_code()
断言也是一种防御性的编程形式。你不是在防范当前代码发生错误,而防范由于以后的代码变更发生错误。理想情况下,单元测试应该直到这个作用,但是让我们面对这样一个现实:即使存在单元测试,他们在通常情况下也不是很完备。内建的机器人可能没有工作,但数周以来也没有人注意到它,或者人们在提交代码之前忘记了执行测试。内部检查将是防止错误渗入的另一道防线,尤其对于那些悄悄地失败,但会引起代码功能错误并返回错误结果的情况有效。
假设你有一系列的if...elif代码块,你预先知道变量期望的值:
# target期望x, y或z中的一个值
if target == x:
run_x_code()
elif target == y:
run_y_code()
run_z_code()
Assume that this code is completely correct now. But will it stay
correct? Requirements change. Code changes. What happens if the
requirements change to allow target = w, with associated action
run_w_code? If we change the code that sets target, but neglect to change
this block of code, it will wrongly call run_z_code() and Bad Things will
occur. It would be good to write this block of code defensively, so that
it will either be correct, or fail immediately, even in the face of
future changes.
The comment at the start of the block is a good first step, but people
are notorious for failing to read and update comments. Chances are it
will soon be obsolete. But with an assertion, we can both document the
assumptions of this block, and cause a clean, immediate failure if they
are violated:
assert target in (x, y, z)
if target == x:
&&& run_x_code()
elif target == y:
&&& run_y_code()
&&& assert target == z
&&& run_z_code()
假设这段代码现在完全正确。但它会一直正确吗?需求变更,代码变更。如果需求变为允许target = w,并关联到run_w_code,那将会发生什么情况?如果我们变更了设置target的代码,但是忘记了改变这个代码块,它就会错误地调用run_z_code(),错误就会发生。对于这段代码最好的方法就是编写一些防御性的检查,这样它的执行,即使在变更以后,要么正确,要么马上失败。
在代码开始添加注释是个好的开端,但是人们都不太喜欢读和更新这些注释,这些注释会很快变得过时。但对于断言,我们可以同时对这块代码编写文档,如果这些断言被违反了,会直接引起一个简单而又直接的失败。
assert target in (x, y, z)
if target == x:
run_x_code()
elif target == y:
run_y_code()
assert target == z
run_z_code()
Here, the assertions are both defensive programming and checked
documentation. I consider this to be a far superior solution than this:
if target == x:
&&& run_x_code()
elif target == y:
&&& run_y_code()
elif target == z:
&&& run_z_code()
&&& # This can never happen. But just in case it does...
&&& raise RuntimeError(&an unexpected error occurred&)
This tempts some helpful developer to &clean it up& by removing the
&unnecessary& test for value==c and removing the &dead code& of the
RuntimeError. Besides, &unexpected error& messages are embarrassing when
they occur, and they will.
Design by contract is another good use of assertions. In design by
contract, we consider that functions make &contracts& with their callers.
E.g. something like this:
&If you pass me an non-empty string, I guarantee to return the first
character of that string converted to uppercase.&
这里的断言同时用于防御性编程和检查文档。我认为这是最优的解决方案:
if target == x:
run_x_code()
elif target == y:
run_y_code()
elif target == z:
run_z_code()
# 这个不会发生,但是以防万一
raise RuntimeError(&an unexpected error occurred&)
这诱使开发者去不理代码,移除像value ==c这类不必要的测试,以及RuntimeError的“死代码”。另外,当&unexpected error&错误发生时这个消息将非常窘迫,确实会发生。
合约式设计是断言另一个用得好的地方。在合约式设计中,我们认为函数与其他调用者遵循合约,例如像这样的情况:
“如果你传给我一个非空字符串,我保证返回转换成大写的首字母。”
If the contract is broken by either the function or the code calling it,
the code is buggy. We say that functions have pre-conditions (the
constraints that arguments are expected to have) and post-conditions (the
constraints on the return result). So this function might be coded as:
def first_upper(astring):
&&& assert isinstance(astring, str) and len(astring) & 0
&&& result = astring[0].upper()
&&& assert isinstance(result, str) and len(result) == 1
&&& assert result == result.upper()
&&& return result
The aim of Design By Contract is that in a correct program, the pre-
conditions and post-conditions will always hold. Assertions are typically
used, since (so the idea goes) by the time we release the bug-free
program and put it into production, the program will be correct and we
can safely remove the checks.
如果合约被破坏了,不管是被函数本身还是调用者,这都会产生缺陷。我们说这个函数需要有前置条件(对期望的参数的限制)和后置条件(对返回结果的约束)。因此这个函数可能是这样的:
def first_upper(astring):
assert isinstance(astring, str) and len(astring) & 0
result = astring[0].upper()
assert isinstance(result, str) and len(result) == 1
assert result == result.upper()
return result
合约式设计的目的是,在一个正确的程序里,所有的前置条件和后置条件都将得到处理。这是断言的经典应用,自(这个想法持续)我们发布无缺陷的程序并且将其放入产品,程序将是正确的并且我们可以放心地移除检查。重定向科技
简体中文帮助
python selenium自动化测试班python selenium自动化测试班
虫师高级测试工程师;
《selenium2 自动化测试实战--基于Python语言》一书作者。
博客:/fnng/python selenium自动化测试班第十二期火热报名中,名额有限2016年9月份左右开课,秋高气爽,给自己一个蜕变的起点。课程咨询及报名请联系QQ:在线登记地址:本期内容有更新,一份价格,双份收获!恭喜虫师,新书出版,购买地址:理念低回报,帮助更多人* 上课时间:基础部分周日半天或一天,实战每周一次课,一次课1个多小时。为期3个月。* 上课内容:selenium webdriver的python版本的入门提高及实战* 上课方式: yy授课,重视互动与练习* 学习目标:使学员完成课程后马上具备实操能力。* 学习费用:2000元,需要开具发票的为2200元&技术交流+selenium 进阶群:(已满),selenium进阶2群: (已满)&selenium进阶3群:独家原创教材&保证教学质量。零基础都能学会。一期实在学不会,下期免费继续学,学会为止。超多的实战练习,让你在烧脑和欲罢不能中完成蜕变。第一部分教材大纲预览课程重点:(虫师授课)自动化测试环境搭建webdriver 元素定位方法webdriver API (常见元素定位技巧)自动化测试模型模块化参数化(txt文件,函数,字典,CSV文件, xml文件)自动化测试用例设计原则与技巧python 异常与断言selenium IDE 介绍unitest测试框架介绍整合HTMLTestRunner测试报告测试报告发邮件功能多线程执行用例webdriver 方法的封装selenium grid2 (多平台执行用例)介绍一下目前的xx自动化测试结构第二部分实战课程(乙醇授课)1,如何使用原生selenium实现wordpress登陆功能;2,开发wordpress创建post功能;3,数据驱动及behave框架介绍4,使用behave重构登录及创建post用例+作业讲解;5,page object设计模式及代码重构;6,重构及完成自动化测试框架;7,框架的ci集成;当前所在位置: >
热门微信号:
Python 使用断言的最佳时机(喵喵)
作者: 浏览数:0 用手机扫描二维码
阅读,只需一秒。精彩,尽在掌握!断言也是一种防御性的编程形式.你不是在防范当前代码发生错误,而防范由于以后的代码变更发生错误.理想情况下,单元测试应该...
断言也是一种防御性的编程形式。你不是在防范当前代码发生错误,而防范由于以后的代码变更发生错误。理想情况下,单元测试应该直到这个作用,但是让我们面对这样一个现实:即使存在单元测试,他们在通常情况下也不是很完备。内建的机器人可能没有工作,但数周以来也没有人注意到它,或者人们在提交代码之前忘记了执行测试。内部检查将是防止错误渗入的另一道防线,尤其对于那些悄悄地失败,但会引起代码功能错误并返回错误结果的情况有效。假设你有一系列的if...elif代码块,你预先知道变量期望的值:1234567if target == x:
run_x_code() elif target == y:
run_y_code() else:
run_z_code()假设这段代码现在完全正确。但它会一直正确吗?需求变更,代码变更。如果需求变为允许target =w,并关联到run_w_code,那将会发生什么情况?如果我们变更了设置target的代码,但是忘记了改变这个代码块,它就会错误地调用run_z_code(),错误就会发生。对于这段代码最好的方法就是编写一些防御性的检查,这样它的执行,即使在变更以后,要么正确,要么马上失败。在代码开始添加注释是个好的开端,但是人们都不太喜欢读和更新这些注释,这些注释会很快变得过时。但对于断言,我们可以同时对这块代码编写文档,如果这些断言被违反了,会直接引起一个简单而又直接的失败。12345678assert target in (x, y, z) if target == x:
run_x_code() elif target == y:
run_y_code() else:
assert target == z
run_z_code()这里的断言同时用于防御性编程和检查文档。我认为这是最优的解决方案:123456789if target == x:
run_x_code() elif target == y:
run_y_code() elif target == z:
run_z_code() else:
raise RuntimeError(&an unexpected error occurred&)这诱使开发者去不理代码,移除像value ==c这类不必要的测试,以及RuntimeError的“死代码”。另外,当&unexpected error&错误发生时这个消息将非常窘迫,确实会发生。合约式设计是断言另一个用得好的地方。在合约式设计中,我们认为函数与其他调用者遵循合约,例如像这样的情况:“如果你传给我一个非空字符串,我保证返回转换成大写的首字母。”如果合约被破坏了,不管是被函数本身还是调用者,这都会产生缺陷。我们说这个函数需要有前置条件(对期望的参数的限制)和后置条件(对返回结果的约束)。因此这个函数可能是这样的:123456def first_upper(astring):
assert isinstance(astring, str) and len(astring) & 0
result = astring[0].upper()
assert isinstance(result, str) and len(result) == 1
assert result == result.upper()
return result合约式设计的目的是,在一个正确的程序里,所有的前置条件和后置条件都将得到处理。这是断言的经典应用,自(这个想法持续)我们发布无缺陷的程序并且将其放入产品,程序将是正确的并且我们可以放心地移除检查。这里是我建议不使用断言的情况:*不要用于测试用户提供的数据,或者那些需要在所有情况下需要改变检查的地方*不要用于检查你认为在通常使用中可能失败的地方。断言用于非常特别的失败条件。你的用户绝不看到一个AssertionError,如果看到了,那就是个必须修复的缺陷。*特别地不要因为断言只是比一个明确的测试加一个触发异常矮小而使用它。断言不是懒惰的代码编写者的捷径。*不要将断言用于公共函数库输入参数的检查,因为你不能控制调用者,并且不能保证它不破坏函数的合约。*不要将断言用于你期望修改的任何错误。换句话,你没有任何理由在产品代码捕获一个AssertionError异常。*不要太多使用断言,它们使代码变得晦涩难懂。(原文来源:https://mail.python.org/pipermail/python-list/2013-November/660401.html)(译者:晴风晓月 译文来源:http://www.oschina.net/translate/when-to-use-assert)一字一句当思来之不易,感谢作者,传播测试技能与正能量!光荣之路软件测试培训官网:/微信公众号:gloryroadtrain性能测试QQ群:软件测试招聘QQ群: 自动化3群QQ:
手机版地址:
微信号:GloryRoadTrain
关注光荣之路软件技术培训账号,即时收取测试开发技术的免费公开课信息,各大公司测试及开发招聘信息、最新的技术咨询、线下测试技术分享沙龙信息
TA的热门文章
推荐其它微信帐号
热门文章排行
(), All rights reserved 京ICP备号-12

我要回帖

更多关于 python unittest 断言 的文章

 

随机推荐