修补字段的默认值
Patching default value of the field
我有一个模型,其中 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
方法 return 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'
}
但它仍然 return 是一些随机的 uuid。我猜这是因为模型初始化在测试开始前就结束了 运行.
我可以通过将默认选项更改为来避免它:
uid = models.UUIDField(unique=True, default=lambda: _new_uid(), editable=False)
不将 default
改为 lambda 调用就可以完成吗?
我找到了解决这个问题的方法。
需要更改 uuid4
的导入语句
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'
}
我有一个模型,其中 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
方法 return 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'
}
但它仍然 return 是一些随机的 uuid。我猜这是因为模型初始化在测试开始前就结束了 运行.
我可以通过将默认选项更改为来避免它:
uid = models.UUIDField(unique=True, default=lambda: _new_uid(), editable=False)
不将 default
改为 lambda 调用就可以完成吗?
我找到了解决这个问题的方法。
需要更改 uuid4
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'
}