如何在描述符级别进行模拟?

时间:2019-03-24 17:04:12

标签: python mocking python-unittest

似乎uuid4描述符的初始化程序中未模拟Field,但它在Foo.get_uid中。为什么会这样?

# file.py

from uuid import uuid4


class Field:

    def __init__(self, default):
        print(uuid4)
        self.default = default()

    def __get__(self, instance, owner):
        return self.default


class Foo:
    uid = Field(uuid4)

    def get_uid(self):
        print(uuid4)
        return self.uid
# test_file.py

import unittest
from unittest.mock import patch

from file import Foo


@patch("file.uuid4")
class TestFoo(unittest.TestCase):
    def test_get_uid(self, patched_uuid4):
        self.assertEqual(Foo().get_uid(), patched_uuid4())


if __name__ == "__main__":
    unittest.main()

运行python test_file.py会导致:

<function uuid4 at 0x110923598>
<MagicMock name='uuid4' id='4570221984'>
F
======================================================================
FAIL: test_get_uid (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/peteralisandratos/.pyenv/versions/3.6.6/lib/python3.6/unittest/mock.py", line 1179, in patched
    return func(*args, **keywargs)
  File "test_file.py", line 10, in test_get_uid
    self.assertEqual(Foo().get_uid(), patched_uuid4())
AssertionError: UUID('a8273b4a-5d93-44d1-9041-54476e15fdf7') != <MagicMock name='uuid4()' id='4572959912'>

如何获得Field来尊重补丁?

0 个答案:

没有答案