【问题标题】:Override pathlib.Path.exists for a conditional test为条件测试覆盖 pathlib.Path.exists
【发布时间】:2020-07-26 03:56:49
【问题描述】:

我想让 Path.exists() 仅在测试特定路径时返回 True:

    from unittest import TestCase
    from mock import patch
    import pathlib

    def fn(names):
      for index, name in enumerate(names):
        if pathlib.Path(name).exists():
          return index

    class T(TestCase):
      @patch.object(pathlib.Path, 'exists', side_effect=lambda: self.name == "countme")
      def test_fn(self, exists_mock):
        self.assertEqual(2, fn(["not", "not", "countme", "not"]))

我也试过

      @patch.object(pathlib.Path, 'exists', side_effect=lambda self: self.name == "countme")

【问题讨论】:

    标签: python-3.x python-unittest.mock


    【解决方案1】:

    您的代码几乎是正确的。这是一个工作版本:

    class T(TestCase):
       @patch.object(pathlib.Path, 'exists', lambda self: self.name == "countme")
        def test_fn(self):
            self.assertEqual(2, fn(["not", "not", "countme", "not"]))
    

    您对 lambda 的使用错过了 lambda 参数,而不是使用 side_effect,您只需替换函数即可。
    问题是 side_effect 只是一个独立于实际函数调用的返回值(或返回值列表),因此使用 lambda 将不起作用 - 它不会以 self 作为参数调用。代替使用的new 参数替换了实际函数,因此将使用正确的参数调用它。

    使用patch 的类似版本如下所示:

    class T(TestCase):
        @patch('pathlib.Path.exists', lambda self: self.name == "countme")
        def test_fn(self):
            self.assertEqual(2, fn(["not", "not", "countme", "not"]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      相关资源
      最近更新 更多