【问题标题】:unit test input validation (python)单元测试输入验证(python)
【发布时间】:2020-09-01 18:52:39
【问题描述】:

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

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

【问题讨论】:

  • 你想从这个测试中确定什么?
  • 如果我提供了一个有效的(现有的)路径,那么它不应该导致一个 ValueError,如果我提供一个无效的路径,它会引发一个 ValueError
  • stackoverflow.com/questions/32187967/… 这是你要找的吗?
  • 我添加了对我想要测试的内容的说明
  • 能否分享一个例子,如何创建一个不可写的目录,测试后将被删除?

标签: python unit-testing validation testing python-unittest


【解决方案1】:

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

class MyClass:
    def __init__(self):
        self.path = None

    def get_path(self, *args, **kwargs):
        self.path = kwargs.get('path', 'default_path')
        if not os.path.isdir(self.path):
            raise ValueError('message 1')
        if not os.access(self.path, os.W_OK):
            raise ValueError('message 2')

如果使用unittest,您的测试可能如下所示:

class TestPath(unittest.TestCase):

    @mock.patch('os.path.isdir', return_value=False)
    def test_path_is_not_dir(self, mocked_isdir):
        with self.assertRaises(ValueError, msg="message 1"):
            inst = MyClass()
            inst.get_path(path="foo")

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch('os.access', return_value=False)
    def test_path_not_accessible(self, mocked_access, mocked_isdir):
        with self.assertRaises(ValueError, msg="msg2"):
            inst = MyClass()
            inst.get_path(path="foo")

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch('os.access', return_value=True)
    def test_valid_path(self, mocked_access, mocked_isdir):
        inst = MyClass()
        inst.get_path(path="foo")
        self.assertEqual("foo", inst.path)

这样您就可以测试功能而无需提供任何真实文件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2019-12-18
    • 2011-01-11
    相关资源
    最近更新 更多