Unittest Python:如何通过添加注释和装饰器来修改源代码
Unittest Python: how to modify a source code by adding comments and decorators
在测试阶段,我想修改我的部分源代码。比如我不需要作图,负责作图的代码可以注释掉。 unittest 模块中是否有合适的工具可以这样做?
另一个问题是关于装饰器@patch。有没有办法在测试期间将它们放入运行时的源代码中?
尝试使用 mock,
听起来它模拟了您的代码并且可以通过测试进行操作。
您可以模拟方法返回的 val 或对象实例等。
https://www.toptal.com/python/an-introduction-to-mocking-in-python
正如小伙子 Ohad 所说,模拟会为您提供帮助。
有多种方法可以模拟一个函数,但一般来说,您将装饰您的测试函数——而不是要模拟的函数!
在您的情况下,代码可能如下所示:
# your_file.py
from ... import ... as plt #depends on the class you use
class MyPlotter(object):
def draw_calling_method(self):
....
plt.draw()
...
return something
# test.py
import mock
from unittest import TestCase
from your_file import MyPlotter
from ... import ... as plt # same import as in the your_file.py
class TestMyPlotter(TestCase):
@mock.patch.object(plt, 'draw')
def test_draw_calling_method_returns_something(self, draw):
plotter = MyPlotter()
plotter_return = plotter.draw_calling_method()
self.assertEqual(plotter_return, something)
这将用 MagicMocks 替换对 plt.draw()
的所有调用并阻碍绘制执行。如果您所有的测试方法都需要模拟绘制调用,则模拟装饰器也可以应用于 class。然后你只需要确保你所有的测试方法都接受模拟作为第二个参数(就像 test_draw_calling_mehtod_returns_something
那样)。此外,您可以通过在测试方法中设置 draw.return_value = ...
来模拟 draw() 函数可能具有的任何 return 值。 注意:这必须在调用模拟的函数调用之前发生,否则将不会应用 return 值。
有关模拟的更多信息,请参阅文档 python-docs。内容很全面。
最后一件事;正如 Jonathon Reinhart 已经提到的,如果您觉得编写测试有困难,那么之前重构您的代码可能会很好。这不仅会使它更易于测试,而且也更具可读性!
在测试阶段,我想修改我的部分源代码。比如我不需要作图,负责作图的代码可以注释掉。 unittest 模块中是否有合适的工具可以这样做?
另一个问题是关于装饰器@patch。有没有办法在测试期间将它们放入运行时的源代码中?
尝试使用 mock,
听起来它模拟了您的代码并且可以通过测试进行操作。
您可以模拟方法返回的 val 或对象实例等。
https://www.toptal.com/python/an-introduction-to-mocking-in-python
正如小伙子 Ohad 所说,模拟会为您提供帮助。
有多种方法可以模拟一个函数,但一般来说,您将装饰您的测试函数——而不是要模拟的函数!
在您的情况下,代码可能如下所示:
# your_file.py
from ... import ... as plt #depends on the class you use
class MyPlotter(object):
def draw_calling_method(self):
....
plt.draw()
...
return something
# test.py
import mock
from unittest import TestCase
from your_file import MyPlotter
from ... import ... as plt # same import as in the your_file.py
class TestMyPlotter(TestCase):
@mock.patch.object(plt, 'draw')
def test_draw_calling_method_returns_something(self, draw):
plotter = MyPlotter()
plotter_return = plotter.draw_calling_method()
self.assertEqual(plotter_return, something)
这将用 MagicMocks 替换对 plt.draw()
的所有调用并阻碍绘制执行。如果您所有的测试方法都需要模拟绘制调用,则模拟装饰器也可以应用于 class。然后你只需要确保你所有的测试方法都接受模拟作为第二个参数(就像 test_draw_calling_mehtod_returns_something
那样)。此外,您可以通过在测试方法中设置 draw.return_value = ...
来模拟 draw() 函数可能具有的任何 return 值。 注意:这必须在调用模拟的函数调用之前发生,否则将不会应用 return 值。
有关模拟的更多信息,请参阅文档 python-docs。内容很全面。
最后一件事;正如 Jonathon Reinhart 已经提到的,如果您觉得编写测试有困难,那么之前重构您的代码可能会很好。这不仅会使它更易于测试,而且也更具可读性!