单元测试框架之unittest(五)

davieyang 2018-12-26 原文

单元测试框架之unittest(五)

一、摘要

单元测试里很重要的一个部分就是断言,unittest为我们提供了很多断言方法

  • assertEqual(a, b, msg=None)断言 a == b
  • assertNotEqual(a, b, msg=None)断言  a != b
  • assertTrue(expr, msg=None)断言  bool(expr) is True
  • assertFalse(expr, msg=None)断言  bool(expr) is False
  • assertIs(a, b, msg=None)断言  a is b
  • assertIsNot(a, b, msg=None)断言  a is not b
  • assertIsNone(expr, msg=None)断言  expr is None
  • assertIsNotNone(expr, msg=None)断言  expr is not None
  • assertIn(a, b, msg=None)断言  a in b
  • assertNotIn(a, b, msg=None)断言  a not in b
  • assertIsInstance(obj, cls, msg=None)断言 obj  is cls instance
  • assertNotIsInstance(obj, cls, msg=None)断言 obj is not cls instance
  • assertRaises(exc, fun, *args, **kwds)断言  fun(*args, **kwds) raises exc 否则抛出断言异常
  • assertRaisesRegex(exc, r, fun, *args, **kwds) 断言  fun(*args, **kwds) raises exc and the exc message matches regex r 否则抛出断言异常

二、代码实例

# encoding = utf-8
import unittest
import random


#  被测试类
class ToBeTest(object):
    @classmethod
    def sum(cls, a, b):
        return a + b

    @classmethod
    def div(cls, a, b):
        return a/b

    @classmethod
    def return_none(cls):
        return None


#  单元测试类
class TestToBeTest(unittest.TestCase):

    # assertEqual()方法实例
    def test_assertequal(self):
        try:
            a, b = 100, 200
            sum = 300
            # 断言a+b等于sum
            self.assertEqual(a + b, sum, '断言失败,%s+%s != %s ' %(a, b, sum))
        except AssertionError as e:
            print(e)

    # assertNotEqual()方法实例
    def test_assertnotequal(self):
        try:
            a, b = 100, 200
            res = -1000
            # 断言a-b不等于res
            self.assertNotEqual(a - b, res, '断言失败,%s-%s != %s ' %(a, b, res))
        except AssertionError as e:
            print(e)

    # assertTure()方法实例
    def test_asserttrue(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        list3 = list1[::-1]
        print(list3)
        try:
            # 断言表达式为真
            self.assertTrue(list3 == list2, "表达式为假")
        except AssertionError as e:
            print(e)

    # assertFalse()方法实例
    def test_assertfalse(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        list3 = list1[::-1]
        try:
            #  断言表达式为假
            self.assertFalse(list3 == list1, "表达式为真")
        except AssertionError as e:
            print(e)

    # assertIs()方法实例
    def test_assertis(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = list1
        try:
            # 断言list2和list1属于同一个对象
            self.assertIs(list1, list2, "%s 与 %s 不属于同一对象" % (list1, list2))
        except AssertionError as e:
            print(e)

    # assertIsNot()方法实例
    def test_assertisnot(self):
        list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        list2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
        try:
            # 断言list2和list1不属于同一个对象
            self.assertIsNot(list2, list1, "%s 与 %s 属于同一对象" % (list1, list2))
        except AssertionError as e:
            print(e)

    # assertIsNone()方法实例
    def test_assertisnone(self):
        try:
            results = ToBeTest.return_none()
            # 断言表达式结果是none
            self.assertIsNone(results, "is not none")
        except AssertionError as e:
            print(e)

    # assertIsNotNone()方法实例
    def test_assertisnotnone(self):
        try:
            results = ToBeTest.sum(4, 5)
            # 断言表达式结果不是none
            self.assertIsNotNone(results, "is none")
        except AssertionError as e:
            print(e)

    # assertIn()方法实例
    def test_assertin(self):
        try:
            str1 = "this is unit test demo"
            str2 = "demo"
            # 断言str2包含在str1中
            self.assertIn(str2, str1, "%s 不被包含在 %s中" %(str2, str1))
        except AssertionError as e:
            print(e)

    # assertNotIn()方法实例
    def test_assertnotin(self):
        try:
            str1 = "this is unit test demo"
            str2 = "ABC"
            # 断言str2不包含在str1中
            self.assertNotIn(str2, str1, "%s 包含在 %s 中" % (str2, str1))
        except AssertionError as e:
            print(e)

    # assertIsInstance()方法实例
    def test_assertisinstance(self):
        try:
            o = ToBeTest
            k = object
            # 断言测试对象o是k的类型
            self.assertIsInstance(o, k, "%s的类型不是%s" % (o, k))
        except AssertionError as e:
            print(e)

    # assertNotIsInstance()方法实例
    def test_assertnotisinstance(self):
        try:
            o = ToBeTest
            k = int
            # 断言测试对象o不是k的类型
            self.assertNotIsInstance(o, k, "%s 的类型是%s" % (o, k))
        except AssertionError as e:
            print(e)

    # assertRaises()方法实例
    def test_assertraises(self):
        # 测试抛出指定的异常类型
        # assertRaises(exception)
        with self.assertRaises(TypeError) as exc:
            random.sample([1, 2, 3, 4, 5, 6], "j")
        # 打印详细的异常信息
        print(exc.exception)
        # assertRaises(exception, callable, *args, **kwds)
        try:
            self.assertRaises(ZeroDivisionError, ToBeTest.div, 3, 0)
        except ZeroDivisionError as e:
            print(e)

    # assertRaisesRegexp()方法实例
    def test_assertraisesregex(self):
        # 测试抛出指定的异常类型,并用正则表达式去匹配异常信息
        # assertRaisesRegex(exception, regexp)
        with self.assertRaisesRegex(ValueError, "literal") as exc:
            int("abc")
        # 打印详细的异常信息
        print(exc.exception)

        # assertRaisesRegex(exception, regexp, callable, *args, **kwds)
        try:
            self.assertRaisesRegex(ValueError, 'invalid literal for.*\'abc\'$', int, 'abc')
        except AssertionError as e:
            print(e)


if __name__ == '__main__':
    unittest.main()

 

发表于 2018-12-26 23:43 davieyang 阅读() 评论() 编辑 收藏

 

版权声明:本文为davieyang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/davieyang/p/10162485.html

单元测试框架之unittest(五)的更多相关文章

  1. Java&Selenium&TestNG&ZTestReport 自动化测试并生成HTML自动化测试报告

    Java&Selenium&TestNG&ZTestReport 自动化测试并生成HT […]...

  2. 单元测试框架之unittest(六)

    单元测试框架之unittest(六) 一、摘要 本片博文将介绍unittest框架的一些轻便有效的特性,在我们 […]...

  3. python之mock模块基本使用

    mock简介 mock原来是python的第三方库 python3以后mock模块已经整合到了unittest […]...

  4. python工业互联网应用实战13—基于selenium的功能测试

    python工业互联网应用实战13—基于selenium的功能测试 本章节我们再来说说测试,单元测试和功能测试 […]...

  5. Python 中 unittest 单元测试框架中需要知识点

      现在正在使用 unittest 框架,我们来记录下这个框架的知识点;   unittest 框架:我们在写 […]...

  6. Unittest组织用例的姿势

    本文我们将会讲解Python Unittest 里组织用例的5种姿势。 环境准备: python 3.0以上 […]...

  7. Python中的单元测试模块Unittest

    前言 为什么需要单元测试? 如果没有单元测试,我们会遇到这种情况:已有的健康运行的代码在经过改动之后,我们无法 […]...

  8. 基于Python Selenium Unittest PO设计模式详解

    本文章会讲述以下几个内容: 1、什么是PO设计模式(Page Object Model) 2、为什么要使用PO […]...

随机推荐

  1. 动态规划

    动态规划 /*此为动态规划的模板*//*模板可粘贴,题解仅供参考*/#include <bits/std […]...

  2. windows使用批处理bat文件批量打开程序

    windows命令行官网教程: https://docs.microsoft.com/en-us/window […]...

  3. 微信小程序图片宽度100%,高度自适应

       实现图片自适应,按照一般情况只需设置: img { width: 100%; height: auto; […]...

  4. 定义鼠标指针形状

    实现效果:    知识运用:   Label控件的Cursor属性  //表是当鼠标指针位于控件上时显示的光标 […]...

  5. 《Python量化交易教程》第一部分新手入门 第1天:谁来给我讲讲Python?

    一、量化投资视频学习课程 二、Python手把手教学 第1天:谁来给我讲讲Python? PS: 1.注意使用 […]...

  6. 自制蓝牙音箱的手册

    自制蓝牙音箱的手册   综述 本文是蓝牙音箱的手册。 蓝牙音箱作为礼物,面向的是用户,但是这位用户同时又是开发 […]...

  7. cocos2d-x游戏开发系列教程-中国象棋04-摆棋

    cocos2d-x游戏开发系列教程-中国象棋04-摆棋 前情回顾 在之前的学习中,我们已经了解到,下棋主界面是 […]...

  8. 【Excle】动态更新数据下拉菜单

    现在我们制作了一个简单的下拉菜单,如下: 但是随着公司的逐渐扩大,部门也变得多了,目前我是把数据范围写死的 , […]...

展开目录

目录导航