簡體   English   中英

單元測試輸入驗證(python)

[英]unit test input validation (python)

我執行以下輸入驗證檢查:

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)

測試它的最佳方法是什么(在單元測試中)?

澄清:我想檢查以下內容:

  • 如果路徑不是目錄,function 應該引發 ValueError
  • 如果路徑是不可寫的目錄,function 應該引發 ValueError

測試此功能的最簡單方法是模擬相應的os功能。 假設您的 function 如下所示:

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)

這樣您就可以測試功能而無需提供任何真實文件。

除此之外,將參數解析功能與測試代碼中的測試功能分開是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM