如何在没有文件系统访问权限的情况下对“mkdir"功能进行单元测试? [英] How to Unit Test 'mkdir' function without file system access?
问题描述
我使用 py.test 进行单元测试.我有这样的事情:
I use py.test for unit testing. I have something just like this:
Class Site(object):
def set_path(self):
"""Checks if the blog folder exists. Creates new folder if necessary."""
if not os.path.isdir(self.user_dir):
print "Creating new directory:", self.user_dir
os.mkdir(self.user_dir)
else:
print "\n**", self.user, "directory already exists."
如何在不接触文件系统的情况下对其进行单元测试?
在处理此类问题时是否有一般的经验法则?
Is there a general rule of thumb when dealing with such problems?
想了很久,还是想不出解决办法.
I've thought about it for a long time, and I cannot think of a solution.
我的应用程序将包含许多文件系统访问,我不知道如何在单元测试时合并这些方法.
My application will contain many file system accesses, and I don't know how to incorporate those methods when unit testing.
我想专门测试一个文件夹是否在正确的路径中创建.路径是self.user_dir
.
I want to specifically test that a folder is created in the correct path. The path is self.user_dir
.
我还有一个下载功能,可以将图像下载到 self.user_dir
.我想测试图像是否已下载.将如何进行测试?
I also have a download function, that downloads an image into self.user_dir
. I want to test that the image is downloaded. How would one go about testing this?
推荐答案
您可以使用两种方法,模拟(首选)或隔离:
There are two approaches you could use, mocking (preferred) or isolation:
模拟:
在测试时,将 os.mkdir 替换为模拟"版本:
At test time, replace os.mkdir with a "mock" version:
class MockMkdir(object):
def __init__(self):
self.received_args = None
def __call__(*args):
self.received_args = args
class MyTest(unittest.TestCase):
def setUp():
self._orig_mkdir = os.mkdir
os.mkdir = MockMkdir()
def tearDown():
os.mkdir = self._orig_mkdir
def test_set_path(self):
site = Site()
site.set_path('foo/bar')
self.assertEqual(os.mkdir.received_args[0], 'foo/bar')
Mock 是一个库,可帮助您以更少的代码行更优雅地完成此类事情.
Mock is a library that helps you do this kind of thing more elegantly and with fewer lines of code.
隔离
使用 chroot 在隔离的文件系统中运行单元测试.运行每个测试用例后,将文件系统恢复到干净状态.这是一种大锤的方法,但对于测试非常复杂的库,使用这种方法可能更容易.
Use chroot to run your unittests within an isolated filesystem. After running each test case, revert the filesystem to a clean state. This is something of a sledgehammer approach but for testing very complicated libraries it might be easier to get this approach to work.
这篇关于如何在没有文件系统访问权限的情况下对“mkdir"功能进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!