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_list
在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): 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.
进一步学习的有用资源! (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测试驱动开发