单元测试输入验证(python)

单元测试输入验证(python),python,unit-testing,validation,testing,python-unittest,Python,Unit Testing,Validation,Testing,Python Unittest,我执行以下输入验证检查: self.path = kwargs.get('path', default_path) if not os.path.isdir(self.path): raise ValueError(msg1) if not os.access(self.path, os.W_OK): raise ValueError(msg2) 最好的测试方法是什么(单元测试) 澄清: 我想检查以下内容: 如果路径不是目录,函数应引发ValueError 如果路

我执行以下输入验证检查:

self.path = kwargs.get('path', default_path) 
if not os.path.isdir(self.path): 
    raise ValueError(msg1)
if not os.access(self.path, os.W_OK):
        raise ValueError(msg2)
最好的测试方法是什么(单元测试)

澄清: 我想检查以下内容:

  • 如果路径不是目录,函数应引发ValueError
  • 如果路径是不可写的目录,则函数应引发ValueError

测试此功能的最简单方法是模拟相应的
os
功能。 假设您的函数如下所示:

class-MyClass:
定义初始化(自):
self.path=None
def get_路径(self、*args、**kwargs):
self.path=kwargs.get('path','default_path')
如果不是os.path.isdir(self.path):
提升值错误(“消息1”)
如果不是os.access(self.path,os.W_OK):
提升值错误('消息2')
如果使用
unittest
,您的测试可以如下所示:

类TestPath(unittest.TestCase):
@mock.patch('os.path.isdir',返回值=False)
def test_path_是_not_dir(自模拟的_isdir):
使用self.assertRaises(ValueError,msg=“message 1”):
inst=MyClass()
指令获取路径(path=“foo”)
@mock.patch('os.path.isdir',返回值=True)
@mock.patch('os.access',返回值=False)
def测试路径不可访问(自访问、模拟访问、模拟isdir):
使用self.assertRaises(ValueError,msg=“msg2”):
inst=MyClass()
指令获取路径(path=“foo”)
@mock.patch('os.path.isdir',返回值=True)
@mock.patch('os.access',返回值=True)
def test_有效_路径(自、模拟_访问、模拟_isdir):
inst=MyClass()
指令获取路径(path=“foo”)
self.assertEqual(“foo”,inst.path)
通过这种方式,您可以在不需要提供任何真实文件的情况下测试功能


除此之外,将参数解析功能与测试代码中的测试功能分开是有意义的。

您试图通过此测试确定什么?如果我提供了有效(现有)路径,那么它不应该导致ValueError,如果我提供了无效路径,它将引发一个值错误这是您正在寻找的吗?我添加了一个关于我要测试的内容的说明。您能否分享一个如何创建一个不可写的目录的示例,该目录将在测试后删除?