问题描述
我有以下要测试的python代码:
I have the following python code which I want to test:
def find_or_make_logfolder(self):
if not path.isdir(self.logfolder):
try:
makedirs(self.logfolder)
except OSError:
if not path.isdir(self.logfolder):
raise
我想在单元测试中执行以下操作。
I want to do something like the following in my unittest.
def test_find_or_make_logfolder_pre_existing(self):
with self.assertRaises(OSError):
makedirs(self.logfolder)
find_or_make_logfolder()
但是,如果不是path.isdir(self.logfolder) :
正在检查目录是否已经存在,以便 OSError
除外,仅在程序或人员成功执行的情况下抛出使目录在 if try
之前几毫秒。
However, if not path.isdir(self.logfolder):
is checking if the directory already exists or not so that the except OSError
will only be thrown in some edge case where a program or person succeeds in making the directory a few milliseconds after the if
and before the try
.
如何o我对此进行测试,还是真的需要对此进行测试?
How do I test this, or do I really need to test this?
当覆盖率达到100%时,我倾向于喜欢它。
I tend to like it when coverage says 100%.
推荐答案
您可以采用更Python化的方法来实现这一目标。在Python中,哲学是
You could go a more Pythonic route to achieve this. In Python the philosophy is
请参见
请记住,您的代码可以编写如下:
With that in mind, your code could be written as follows:
def find_or_make_logfolder(self):
try:
makedirs(self.logfolder)
except OSError:
#self.logfolder was already a directory, continue on.
pass
现在要覆盖此代码的100%,您只需创建目录已经存在的测试案例。
Now to get 100% of this code covered, you will just need to create a test case where the directory already exists.
这篇关于如何编写OSError的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!