【问题标题】:Patching default value of the field修补字段的默认值
【发布时间】:2019-10-10 10:27:00
【问题描述】:

我有一个带有 uuid 字段的模型,该字段具有默认值作为函数。

from uuid import uuid4

def _new_uid():
    return uuid4()


class A(models.Model):
    name = models.CharField()
    uid = models.UUIDField(unique=True, default=_new_uid, editable=False)

在测试中我想修补 _new_uid 方法返回 11111111-1111-1111-1111-111111111111

@patch('module.foo._new_uid',
       Mock(return_value='11111111-1111-1111-1111-111111111111'))
def test_create_A():
    response = api_client.post('/api/a-list/', {
        'name': 'test',
    })

    assert response.json() == {
        '_uid': '11111111-1111-1111-1111-111111111111',
        'name': 'test'
    }

但它仍然返回一些随机的 uuid。我想这是因为模型初始化在测试开始运行之前就已经结束了。

我可以通过将默认选项更改为:

uid = models.UUIDField(unique=True, default=lambda: _new_uid(), editable=False)

不把default改成lambda调用可以吗?

【问题讨论】:

  • _new_uidA 在文件 module.foo.py 中吗?
  • @DipenDadhaniya 是的

标签: python django django-models python-unittest


【解决方案1】:

我发现了如何解决这个问题。

需要更改uuid4的import语句

import uuid

def _new_uid():
    return uuid.uuid4()

现在我可以修补 uuid

@patch('module.foo._new_uid',
       Mock(**{'uuid4.return_value': '11111111-1111-1111-1111-111111111111'}))
def test_create_A():
    response = api_client.post('/api/v1/a-list/', {
        'name': 'test',
    })

   assert response.json() == {
        '_uid': '11111111-1111-1111-1111-111111111111',
        'name': 'test'
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-21
    • 2022-01-02
    • 1970-01-01
    • 2017-04-04
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多