python测试驱动开发

by Dmitry Rastorguev

德米特里·拉斯托格夫(Dmitry Rastorguev)

使用Python进行测试驱动开发的简单介绍 (A simple introduction to Test Driven Development with Python)

I am a self-taught beginning developer who is able to write simple apps. But I have a confession to make. It’s impossible to remember how everything is interconnected in my head.

我是一位自学成才的开发人员,能够编写简单的应用程序。 但是我要坦白。 不可能记住我脑子里所有事物是如何相互联系的。

This situation is made worse if I come back to the code I’ve written after a few days. Turns out that this problem could be overcome by following a Test Driven Development (TDD) methodology.

如果几天后回到我编写的代码,这种情况会变得更糟。 事实证明,遵循测试驱动开发 (TDD)方法可以解决此问题。

什么是TDD?为什么重要? (What is TDD and why is it important?)

In layman’s terms, TDD recommends writing tests that would check the functionality of your code prior to your writing the actual code. Only when you are happy with your tests and the features it tests, do you begin to write the actual code in order to satisfy the conditions imposed by the test that would allow them to pass.

用外行的话来说,TDD建议编写测试,以在编写实际代码之前检查代码的功能。 仅当您对测试及其测试的功能感到满意时,才开始编写实际的代码,以满足测试所施加的条件,使它们可以通过。

Following this process ensures that you careful plan the code you write in order to pass these tests. This also prevents the possibility of writing tests being postponed to a later date, as they might not be deemed as necessary compared to additional features that could be created during that time.

执行此过程可确保您仔细计划编写的代码,以通过这些测试。 这也避免了将编写测试推迟到以后的可能性,因为与在此期间可能创建的其他功能相比,这些测试可能被认为不是必需的。

Tests also give you confidence when you begin to refactor code, as you are more likely to catch bugs due to the instant feedback when tests are executed.

当您开始重构代码时,测试还使您充满信心,因为执行测试时会得到即时反馈,因此更有可能捕获错误。

如何开始? (How to get started?)

To begin writing tests in Python we will use the unittest module that comes with Python. To do this we create a new file mytests.py, which will contain all our tests.

要开始使用Python编写测试,我们将使用Python随附的unittest 模块 。 为此,我们创建一个新文件mytests.py ,其中将包含所有测试。

Let’s begin with the usual “hello world”:

让我们从通常的“ hello world”开始:

import unittestfrom mycode import *
class MyFirstTests(unittest.TestCase):
def test_hello(self):        self.assertEqual(hello_world(), 'hello world')

Notice that we are importing helloworld() function from mycode file. In the file mycode.py we will initially just include the code below, which creates the function but doesn’t return anything at this stage:

注意,我们正在从mycode文件导入helloworld()函数。 在文件mycode.py我们最初将仅包含以下代码,该代码创建函数但在此阶段不返回任何内容:

def hello_world():    pass

Running python mytests.py will generate the following output in the command line:

运行python mytests.py将在命令行中生成以下输出:

F
====================================================================
FAIL: test_hello (__main__.MyFirstTests)
--------------------------------------------------------------------
Traceback (most recent call last):
File "mytests.py", line 7, in test_hello
self.assertEqual(hello_world(), 'hello world')
AssertionError: None != 'hello world'
--------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)

This clearly indicates that the test failed, which was expected. Fortunately, we have already written the tests, so we know that it will always be there to check this function, which gives us confidence in spotting potential bugs in the future.

这清楚表明测试失败,这是预期的。 幸运的是,我们已经编写了测试,因此我们知道它将一直在这里检查该功能,这使我们有信心在将来发现潜在的错误。

To ensure the code passes, lets change mycode.py to the following:

为了确保代码能够通过, mycode.py更改为以下内容:

def hello_world():    return 'hello world'

Running python mytests.py again we get the following output in the command line:

再次运行python mytests.py ,我们在命令行中获得以下输出:

.
--------------------------------------------------------------------
Ran 1 test in 0.000s
OK

Congrats! You’ve have just written your first test. Let’s now move on to a slightly more difficult challenge. We’ll create a function that would allow us to create a custom numeric list comprehension in Python.

恭喜! 您刚刚编写了第一个测试。 现在让我们继续面对一个稍微困难一点的挑战。 我们将创建一个函数,该函数将允许我们在Python中创建自定义数字列表理解 。

Let’s begin by writing a test for a function that would create a list of specific length.

让我们从编写针对将创建特定长度列表的函数的测试开始。

In the file mytests.py this would be a method test_custom_num_list:

在文件mytests.py这将是test_custom_num_list方法:

import unittestfrom mycode import *
class MyFirstTests(unittest.TestCase):
def test_hello(self):        self.assertEqual(hello_world(), 'hello world')        def test_custom_num_list(self):        self.assertEqual(len(create_num_list(10)), 10)

This would test that the function create_num_list returns a list of length 10. Let’s create function create_num_list in mycode.py:

这将测试函数create_num_list返回长度为10的列表。让我们在mycode.py创建函数create_num_list

def hello_world():    return 'hello world'
def create_num_list(length):    pass

Running python mytests.py will generate the following output in the command line:

运行python mytests.py将在命令行中生成以下输出:

E.
====================================================================
ERROR: test_custom_num_list (__main__.MyFirstTests)
--------------------------------------------------------------------
Traceback (most recent call last):
File "mytests.py", line 14, in test_custom_num_list
self.assertEqual(len(create_num_list(10)), 10)
TypeError: object of type 'NoneType' has no len()
--------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (errors=1)

This is as expected, so let’s go ahead and change function create_num_list in mytest.py in order to pass the test:

这是预期的,所以让我们继续并在mytest.py中更改函数create_num_list以便通过测试:

def hello_world():    return 'hello world'
def create_num_list(length):    return [x for x in range(length)]

Executing python mytests.py on the command line demonstrates that the second test has also now passed:

在命令行上执行python mytests.py演示了第二个测试现在也通过了:

..
--------------------------------------------------------------------
Ran 2 tests in 0.000s
OK

Let’s now create a custom function that would transform each value in the list like this: const * ( X ) ^ power . First let’s write the test for this, using method test_custom_func_ that would take value 3 as X, take it to the power of 3, and multiply by a constant of 2, resulting in the value 54:

现在让我们创建一个自定义函数,该函数将转换列表中的每个值,如下所示: const * ( X ) ^ power 。 首先,让我们使用方法test_custom_func_编写测试,该方法将值3作为X,将其乘以3的幂,然后乘以2的常数,得出值54:

import unittestfrom mycode import *
class MyFirstTests(unittest.TestCase):
def test_hello(self):        self.assertEqual(hello_world(), 'hello world')
def test_custom_num_list(self):        self.assertEqual(len(create_num_list(10)), 10)        def test_custom_func_x(self):        self.assertEqual(custom_func_x(3,2,3), 54)

Let’s create the function custom_func_x in the file mycode.py:

让我们在mycode.py文件中创建函数custom_func_x

def hello_world():    return 'hello world'
def create_num_list(length):    return [x for x in range(length)]
def custom_func_x(x, const, power):    pass

As expected, we get a fail:

不出所料,我们失败了:

F..
====================================================================
FAIL: test_custom_func_x (__main__.MyFirstTests)
--------------------------------------------------------------------
Traceback (most recent call last):
File "mytests.py", line 17, in test_custom_func_x
self.assertEqual(custom_func_x(3,2,3), 54)
AssertionError: None != 54
--------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (failures=1)

Updating function custom_func_x to pass the test, we have the following:

更新函数custom_func_x以通过测试,我们具有以下内容:

def hello_world():    return 'hello world'
def create_num_list(length):    return [x for x in range(length)]
def custom_func_x(x, const, power):    return const * (x) ** power

Running the tests again we get a pass:

再次运行测试,我们通过了:

...
--------------------------------------------------------------------
Ran 3 tests in 0.000s
OK

Finally, let’s create a new function that would incorporate custom_func_x function into the list comprehension. As usual, let’s begin by writing the test. Note that just to be certain, we include two different cases:

最后,让我们创建一个新函数,它将custom_func_x函数合并到列表custom_func_x 。 和往常一样,让我们​​开始编写测试。 请注意,可以肯定的是,我们包括两种不同的情况:

import unittestfrom mycode import *
class MyFirstTests(unittest.TestCase):
def test_hello(self):        self.assertEqual(hello_world(), 'hello world')
def test_custom_num_list(self):        self.assertEqual(len(create_num_list(10)), 10)
def test_custom_func_x(self):        self.assertEqual(custom_func_x(3,2,3), 54)
def test_custom_non_lin_num_list(self):        self.assertEqual(custom_non_lin_num_list(5,2,3)[2], 16)        self.assertEqual(custom_non_lin_num_list(5,3,2)[4], 48)

Now let’s create the function custom_non_lin_num_list in mycode.py:

现在,让我们创建函数custom_non_lin_num_listmycode.py

def hello_world():    return 'hello world'
def create_num_list(length):    return [x for x in range(length)]
def custom_func_x(x, const, power):    return const * (x) ** power
def custom_non_lin_num_list(length, const, power):    pass

As before, we get a fail:

和以前一样,我们失败了:

.E..
====================================================================
ERROR: test_custom_non_lin_num_list (__main__.MyFirstTests)
--------------------------------------------------------------------
Traceback (most recent call last):
File "mytests.py", line 20, in test_custom_non_lin_num_list
self.assertEqual(custom_non_lin_num_list(5,2,3)[2], 16)
TypeError: 'NoneType' object has no attribute '__getitem__'
--------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (errors=1)

In order to pass the test, let’s update the mycode.py file to the following:

为了通过测试,让我们将mycode.py文件更新为以下内容:

def hello_world():    return 'hello world'
def create_num_list(length):    return [x for x in range(length)]
def custom_func_x(x, const, power):    return const * (x) ** power
def custom_non_lin_num_list(length, const, power):    return [custom_func_x(x, const, power) for x in range(length)]

Running the tests for the final time, we pass all of them!

在最后一次运行测试,我们都通过了所有测试!

....
--------------------------------------------------------------------
Ran 4 tests in 0.000s
OK

Congrats! This concludes this introduction to testing in Python. Make sure you check out the resources below for more information on testing in general.

恭喜! 到此结束了对Python测试的介绍。 确保检查以下资源,以获取有关常规测试的更多信息。

The code is available here on GitHub.

该代码可在GitHub上找到 。

进一步学习的有用资源! (Useful resources for further learning!)

网络资源 (Web resources)

Below are links to some of the libraries focusing on testing in Python

以下是一些库的链接,这些库专注于Python测试

25.3. unittest - Unit testing framework - Python 2.7.14 documentationThe Python unit testing framework, sometimes referred to as "PyUnit," is a Python language version of JUnit, by Kent…docs.python.orgpytest: helps you write better programs - pytest documentationThe framework makes it easy to write small tests, yet scales to support complex functional testing for applications and…docs.pytest.orgWelcome to Hypothesis! - Hypothesis 3.45.2 documentationIt works by generating random data matching your specification and checking that your guarantee still holds in that…hypothesis.readthedocs.iounittest2 1.1.0 : Python Package IndexThe new features in unittest backported to Python 2.4+.pypi.python.org

25.3。 unittest-单元测试框架-Python 2.7.14文档 Python单元测试框架(有时也称为“ PyUnit”)是Kent的JUnit的Python语言版本 。docs.python.org pytest:可帮助您编写更好的程序-pytest文档 该框架使编写小型测试变得容易,但可以扩展以支持应用程序和...的复杂功能测试 。docs.pytest.org 欢迎来到假设! -假设3.45.2文档 它的工作原理是生成与您的规范匹配的随机数据,并检查您的保证是否仍然适用于… hypothesis.readthedocs.io unittest2 1.1.0:Python包索引 unittest的新功能已反向移植到Python 2.4+。 pypi.python.org

YouTube视频 (YouTube videos)

If you prefer not to read, I recommend watching the following videos on YouTube.

如果您不想阅读,建议您在YouTube上观看以下视频。

翻译自: https://www.freecodecamp.org/news/learning-to-test-with-python-997ace2d8abe/

python测试驱动开发

python测试驱动开发_使用Python进行测试驱动开发的简单介绍相关推荐

  1. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  2. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  3. python爬电影_使用Python多线程爬虫爬取电影天堂资源

    最近花些时间学习了一下Python,并写了一个多线程的爬虫程序来获取电影天堂上资源的迅雷下载地址,代码已经上传到GitHub上了,需要的同学可以自行下载.刚开始学习python希望可以获得宝贵的意见. ...

  4. 利用Python进行数据分析(7) pandas基础: Series和DataFrame的简单介绍 一、pandas 是什么 pandas 是基于 NumPy 的一个 Python 数据分析包,主

    利用Python进行数据分析(7) pandas基础: Series和DataFrame的简单介绍 一.pandas 是什么 pandas 是基于 NumPy 的一个 Python 数据分析包,主要目 ...

  5. Python 框架 之 Django MVT 下的 T 的 模板简单介绍和使用

    Python 框架 之 Django MVT 下的 T 的 模板简单介绍和使用 目录

  6. Python 框架 之 Django MVT 下的 V 的 视图简单介绍和使用

    Python 框架 之 Django MVT 下的 V 的 视图简单介绍和使用 目录

  7. 用python写情书_用Python给喜欢人的发一封邮件吧(群发)

    你好,我是goldsunC 让我们一起进步吧! 利用Python发送邮件 相信我们每个人都用过邮箱,虽然其它社交聊天软件已经非常普及,并且这些社交软件大多都具有文件发送的功能,但很多时候我们仍然离不开 ...

  8. python global用法_【python测试开发栈】python基础语法大盘点

    周边很多同学在用python,但是偶尔会发现有人对python的基础语法还不是特别了解,所以帮大家梳理了python的基础语法(文中的介绍以python3为例).如果你已然是python大牛,可以跳过 ...

  9. python网页版_经典python学习教程:20行代码打造一个微信群聊助手,解放双手

    今天的Python学习教程教大家如何用20行Python代码实现微信群聊助手,可以用来活跃群气氛,好多群主创建完群后,拉完一群人,之后就一片寂静,有个群聊助手,就可以帮忙活跃群里气氛,通过今天在自己的 ...

最新文章

  1. 配置内网邮件和外网邮件互发
  2. 计算机网络基础(路由原理)
  3. 关于c语言的数据类型常量的理解
  4. AIX学习笔记-第一天简介
  5. 卷积神经网络(CNN)之池化层的实现
  6. mysql主库从库在同一台服务器_MySQL_MySQL 数据库两台主机同步实战(linux),当一个从服务器连接到主服务 - phpStudy...
  7. YAML_01 YAML语法和playbook写法
  8. Java 8 中的 Map 骚操作,学习下
  9. 提高openfire最大连接数
  10. H265H264视频流播放
  11. 路由器和交换机的区别
  12. Groundhog Chasing Death 2020牛客多校第九场(质因子分解+欧拉降幂)
  13. NetBeans工具学习之道:NetBeans IDE Java 快速入门教程
  14. Win11安卓应用使用及环境配置教程
  15. CCF计算机软件能力认证试题练习:201903-1 小中大
  16. 3万字智慧工业园区整体解决方案
  17. QQ空间点赞源码,基于autojs的安卓免root全自动脚本
  18. java netty wss_netty实现websocket客户端(支持wss安全连接)
  19. altera FPGA介紹
  20. 立此存照,万一哪天迈不过坎,回头看看

热门文章

  1. SQL消费表中查找所有用户最后一条消费记录
  2. 2018年考研真题计算机专业,2018年计算机考研真题及参考答案.pdf
  3. python使用h5py读取mat文件数据
  4. 【图像压缩】DCT图像无损压缩【含GUI Matlab源码 726期】
  5. BOM:04-BOM有哪些形式?(按用途划分)
  6. 一箭穿心程序编码c语言,一个简单的一箭穿心程序
  7. NAO学习第二周——NAOqi Audio
  8. RangerClient简介
  9. 假期培训日记(数论)
  10. 谈谈CANopen协议的机制