gpt4 book ai didi

python - 在 python 中测试 while 循环

转载 作者:行者123 更新时间:2023-11-28 20:42:43 25 4
gpt4 key购买 nike

测试像这样的方法的最佳方法是什么

class Foo(object):

is_running = False
def run(self):
self.is_running = True
while self.is_running:
do_some_work()

这是消费者的标准代码,在设置 is_running 标志时工作。

但这很难测试,因为它将进入循环并且永远不会出来,除非我创建第二个线程将 is_running 更改为 false。

有没有什么好的策略可以在不启动单独的线程来运行代码的情况下进行测试?

我什么都没看到,但我在想也许模拟库会提供每次读取 is_running 时都可以返回 [True, True, False] 的功能但这是否需要我将 is_running 从成员变量更改为属性或方法?

最佳答案

正如我在评论中提到的,我认为使用线程测试此方法是一种完全可行的方法,并且可能是最佳解决方案。但是,如果你真的想避免线程,你可以将 is_running 转换为 property 然后使用 mock.PropertyMock模拟属性:

import mock
import time

class Foo(object):

def __init__(self):
self._is_running = False

@property
def is_running(self):
return self._is_running

@is_running.setter
def is_running(self, val):
self._is_running = val

def run(self):
self._is_running = True # Don't go through the property here.
while self.is_running:
print("in here")
time.sleep(.5)


with mock.patch('__main__.Foo.is_running', new_callable=mock.PropertyMock,
side_effect=[True, True, False]) as m:
f = Foo()
f.run()

输出:

in here
in here
<done>

不过,我要说的是,仅仅为了启用特定的测试方法而对您的生产实现进行如此大的更改是不值得的。只需让您的测试函数创建一个线程以在一段时间后设置 is_running

关于python - 在 python 中测试 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com