Python Django 测试两个异常之一
Python Django Test for One of Two Exceptions
我正在尝试测试模型的某个实例是否会引发两个异常之一,但我不知道如何让它工作。这是我拥有的:
型号
class AvailablePermissions(models.Model):
# Main Checkbox.
category = models.CharField(
max_length=100,
)
# Checkboxes under Main Checkbox.
subcategory = models.CharField(
max_length=100,
)
# The view to grant permission to.
view_name= models.CharField(
max_length=255,
unique=True,
)
def full_clean_save(self):
try:
name = resolve(reverse(f'{self.view_name}'))
self.full_clean()
self.save()
except NoReverseMatch as nrme:
raise nrme
except ValidationError as ve:
raise ve
return self
测试
# Default permission object "(**permission)"
permission = {
'category': 'Category',
'subcategory': 'Subcategory',
'view_name': 'employee:create_profile',
}
available_permission = AvailablePermissions(**permission)
class AvailablePermissionsValidationTest(TestCase):
def test_AvailablePermissions_will_not_save_blank_permissions(self):
for field in permission:
original_value = permission[field]
permission[field] = ''
with self.assertRaises(ValidationError or NoReverseMatch):
AvailablePermissions(
**permission
).full_clean_save()
permission[field] = original_value
它抛出 NoReverseMatch
错误,但我不知道如何查找 "either or" 异常。
这可能有效:
with self.assertRaises(ValidationError):
try:
AvailablePermissions(
**permission
).full_clean_save()
except NoReverseMatch:
raise ValidationError
但你真的想这么做吗?通常,单元测试的目的是测试所有可能的路径。这只会保证两条路径之一被测试。
我正在尝试测试模型的某个实例是否会引发两个异常之一,但我不知道如何让它工作。这是我拥有的:
型号
class AvailablePermissions(models.Model):
# Main Checkbox.
category = models.CharField(
max_length=100,
)
# Checkboxes under Main Checkbox.
subcategory = models.CharField(
max_length=100,
)
# The view to grant permission to.
view_name= models.CharField(
max_length=255,
unique=True,
)
def full_clean_save(self):
try:
name = resolve(reverse(f'{self.view_name}'))
self.full_clean()
self.save()
except NoReverseMatch as nrme:
raise nrme
except ValidationError as ve:
raise ve
return self
测试
# Default permission object "(**permission)"
permission = {
'category': 'Category',
'subcategory': 'Subcategory',
'view_name': 'employee:create_profile',
}
available_permission = AvailablePermissions(**permission)
class AvailablePermissionsValidationTest(TestCase):
def test_AvailablePermissions_will_not_save_blank_permissions(self):
for field in permission:
original_value = permission[field]
permission[field] = ''
with self.assertRaises(ValidationError or NoReverseMatch):
AvailablePermissions(
**permission
).full_clean_save()
permission[field] = original_value
它抛出 NoReverseMatch
错误,但我不知道如何查找 "either or" 异常。
这可能有效:
with self.assertRaises(ValidationError):
try:
AvailablePermissions(
**permission
).full_clean_save()
except NoReverseMatch:
raise ValidationError
但你真的想这么做吗?通常,单元测试的目的是测试所有可能的路径。这只会保证两条路径之一被测试。