以下两个测试之一注定要失败,因为 @override_settings(....) 只在测试中执行一次。数据库被倒回以保持一致,但模型不会根据设置重新配置。所以如果默认设置为True,第二个testCaseFalse会失败,如果默认设置为False,testCaseTrue会失败。
我如何在以下代码中强制重新加载 Patient 模型,以便两个单元测试用例都可以工作。我希望这是我只需要在一个地方做的事情,而不是下面的 2 种注释掉的可能性,应该是某种干燥的方式并且仍然可以完成这项工作。
class Patient(models.Model):
x = models.IntegerField(null=True, blank=not settings.REQUIRE_X_FOR_PATIENT)
class PatientForm(forms.ModelForm):
#x = forms.CharField(required=settings.REQUIRE_X_FOR_PATIENT) Don't want to have to do this
class Meta:
model = Patient
#def __init__(self, *args, **kwargs): #Don't want to have to do this either
#super(PatientForm, self).__init__(*args, **kwargs)
#self.fields['x'].required = settings.REQUIRE_X_FOR_PATIENT
@override_settings(REQUIRE_X_FOR_PATIENT=True)
def testCaseTrue...
form = PatientForm()
self.assertTrue(form.fields['x'].required, "X should be required")
@override_settings(REQUIRE_X_FOR_PATIENT=False)
def testCaseFalse...
form = PatientForm()
self.assertTrue(form.fields['x'].required, "X should NOT be required")