4

Python单元测试-Unittest(一)

 2 years ago
source link: https://blog.51cto.com/summerstone/5141970
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python单元测试-Unittest(一)

原创

SummerStone 2022-03-24 08:42:28 博主文章分类:软件开发 ©著作权

文章标签 单元测试 python 开发人员 文章分类 Python 编程语言 阅读数334

单元测试环节是比较重要的,它是为了保证开发人员交付代码质量的保证方式之一。一般开发人员都要掌握一些这方面的知识,其中unittest模块是python官方维护的模块,比较稳定和好用的单元测试框架。首先来了解下unittest的整体架构组成,从官网介绍不难得出,unittest框架主要分为如下4个部分。

Python单元测试-Unittest(一)_python

test fixture, 它的功能主要是在做测试时,特别是多次测试,在测试执行之前是需要一些准备工作的,比如创建测试用的文件夹,新建测试用的临时数据库,新建特定的测试数据等操作。相当于测试的一些前置工作可以在这里完成。

test case, 它是单元测试的主题或者称为核心。主要是用于验证某段程序在特定输入下是否有特定的输出。多个测试可以创建多个test case文件并设定相应的测试类,并需要继承框架类TestCase,只有继承了它,才可以创建新的测试用例。

test suite, 它从字面上可以翻译成测试集合,它可以将不同的test case或其他的test suite集合到一起。所以test suite是可以嵌套的,一个test suite可以有多个子test suite。目前是为了让这些测试在一起执行。

test runner,可以理解为unittest的执行引擎,它负责管理测试的执行,并负责输出测试结果给用户。

下面用一个简单的例子,先让单元测试跑起来。由于unittest是python自带软件包,所以不用单独安装。首先需要准备被测代码,代码如下。

#this is the python code need to be unit tested.
def login_method(username, password):
if username == "admin" and password == "pwd1":
return "System login successfully."
else:
return "Please check your username and password."


def open_index_page():
return "the index page is opened successfully."

测试代码如下,核心是使用了验证函数assertEqual,并且测试类需要继承类unittest.TestCase。还有一点需要注意的是每个测试函数需要以字符"test"打头。

from code import login_method,open_index_page
import unittest


class TestCodeMethods(unittest.TestCase):
def test_login_method(self):
self.assertEqual(login_method('admin','pwd1'),'System login successfully.')
self.assertEqual(login_method('admin','pwd'),'Please check your username and password.')

def test_open_index_page(self):
self.assertEqual(open_index_page(),'the index page is opened successfully.')


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

执行执行测试代码,测试结果如下所示。

Python单元测试-Unittest(一)_单元测试_02

​如何大家想掌握第一手的资讯更新,请关注公众号“测试DAO”。​


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK