📕
innohub
  • KEEP LEARNING
  • WebInfo
    • JS 部分运算符操作
    • javascript 中的object array
    • 错误处理以及异常捕获
    • JavaScript Bases
    • LaoZi & Confucius
  • PyInfo
    • Python3 输入与输出
    • Python3OS
    • python 修饰器的使用
    • python3 与mysql数据库连接使用实例
    • Format-specifier
    • CGI初学踩坑
    • Django 项目测试
    • Assert-info
    • 使用ngnix和uWSGI配置Django
    • write|SVN​
    • Matplotlib 基本使用
    • 重读 Python 官方文档
    • Python3 Base
    • python3 多线程
    • Python3 函数解析
    • python3 str 对象的基本操作
    • protocl buffers
    • Iterator-Generator
    • Django base
    • Decorator 2
    • Export to wheel or egg-info
    • 三. 运算、数据及逻辑
  • GoInfo
    • Info
      • Select 语句使用
      • First class function
      • Work Pools
      • StructTag
      • Go struct
      • 常用函数
      • Strings操作
      • Golang Bases
      • 数组以及切片
      • 文件操作
      • Golang 中的指针类型
      • Golang Map 类型
      • Reflection
      • 函数闭包
      • 接口
      • Panic and Recover
      • Go中的错误处理
      • 并发
      • defer usage
      • Method in golang
      • Object-oriented Programming
      • Goalng 包管理机制
  • RustInfo
    • Info
      • 包、crate、模块
      • Rust 中的错误处理
      • 智能指针
      • 泛型 generics
      • 数据布局与内存对齐
      • Functions and methods
      • 无畏并发
      • Actix-web 基本使用
      • Got from guessing game
      • 结构体的使用
      • Rust 中的函数式语言功能
      • 集合类型
      • 枚举以及模式匹配
      • Slice 类型
      • 生命周期
      • 测试
      • Rust 中的所有权
      • trait
      • 不安全 Rust
      • Format_print
      • Rust 通用编程概念
      • Macro
  • OS
    • info
      • 内存屏障 -- Part 1
      • 内存屏障 -- Part 2
      • CPU 上下文切换
      • 文件读写与零拷贝
      • ELF 文件
  • MySql
    • info
      • MySql 架构与历史
      • 02-key
  • kubernetes
    • 第二章 k8s 基本概念
    • 第一章 Kubernetes -- 伟大舵手
  • Redis
    • info
      • Redis 总览
      • 02-underline-ds
  • Shell&CInfo
    • GCC 与make的使用
    • C++ 中 malloc 与 new
    • 位运算符操作
    • Base of C macro
    • C 语言中 extern 关键字的用法
  • Distributed
    • info
      • 分布式理论概述
  • Java
    • info
      • Java 内存模型
  • Prometheus
    • Prometheus -- 不灭之火
Powered by GitBook
On this page
  • Assert 断言函数
  • 简介:
  • 用法:
  • 使用误区:

Was this helpful?

  1. PyInfo

Assert-info

Assert 断言函数

简介:

  • pthon assert 断言是声明其布尔值必须为真的判定,如果为假则抛出异常AssertionError

    assert用法:

          assert expression [, arguments]
  • 使用assert断言是学习python一个非常好的习惯,python assert 断言句语格式及用法很简单。在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行最崩溃,不如在出现错误条件时就崩溃,这时候就需要assert断言的帮助。

用法:

>>assert 1==1
>> assert 1 == 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>assert 2+2==2*2
>>assert len(['my boy',12])<10
>>assert range(4)==[0,1,2,3]
>>> mylist = ['item']
>>assert len(mylist) >= 1
>>mylist.pop()
'item'
>>assert len(mylist) >= 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

使用误区:

1. 以assert方式作为参数异常

if not isinstance(x, int)
    raise AssertionError('not an int')
#    不应该抛出断言异常应该是TypeError
#    但是,更危险的是,有一个关于assert的困扰:它可以被编译好然后从来不执行,如果你用 –O 或 –      oo 选项运行Python,结果不保证assert表达式会运行到。当适当的使用assert时,这是未来,但      是当assert不恰当的使用时,它会让代码用-O执行时出错。

2.适用情形

  • 防御性编程

  • 运行时检查程序逻辑

  • 检查约定

  • 检查常量

  • 检查文档

    在测试代码的时候使用断言也是可接受的,是一种很方便的单元测试方法,你接受这些测试在用-O标志运行时不会做任何事。我有时在代码里使用assert False来标记没有写完的代码分支,我希望这些代码运行失败。尽管抛出NotImplementedError可能会更好。

3.以断言代替不必要注释

例如函数希望在执行过程中一直有数据库连接,作为不变量可以采用断言

def some_fun(args):
    assert not DB.cloesd()
...
    # code goes here

    assert not DB.closed()
    return result

断言也是一种防御型编程,为了防止以后版本的升级可能带来的错误理想情况下,单元测试可以完成这样的工作,可是需要面对的现实是,它们通常是没有完成的。人们可能在提交代码前会忘了运行测试代码。有一个内部检查是另一个阻挡错误的防线,尤其是那些不明显的错误,却导致了代码出问题并且返回错误的结果。

假如现有以下语句:

#target isexpected to be one of x, y, or z, and nothing else.

if target == x:
    run_x_code()
elif
    target == y:
    run_y_code()
else:
    run_z_code()

可以以断言代替注释,在违反时返回一个干净的错误:

assert target in (x, y, z)

if target == x:
    run_x_code()
elif target == y:
    run_y_code()
else:
    assert target == z
    run_z_code()

还有更好的方案:

if target == x:
    run_x_code()
elif target == y:
    run_y_code()
elif  target == z:
    run_z_code()
else:
    # This can never happen. But just incase it does...
    raise RuntimeError("anunexpected error occurred")
PreviousDjango 项目测试Next使用ngnix和uWSGI配置Django

Last updated 5 years ago

Was this helpful?