创建要测试的对象的一些 Django 最佳实践是什么
What are some Django best practice for creating objects to test on
我一直在测试需要创建临时对象的代码的方式似乎很混乱。我希望有一种更简洁、更直观的方法。
在设置时,我 运行 函数 setUpTestData 负责创建我的测试稍后可能使用的临时对象。由于 ForeignKey 关系,我必须在其中创建嵌套对象,这变得有点混乱。
这是我正在使用的示例:
class Test_query_alarm(TestCase):
@classmethod
def setUpTestData(cls):
Device.objects.create(
site=Site.objects.create(
group=Group.objects.create(
name='TestGroup'
),
name='TestSiteName',
address='TestAddress',
gps_coordinates='TestGpsCoordinates',
contact=Contact.objects.create(
first_name='TestFirstName',
last_name='TestLastName',
phone='TestPhoneNumber',
email='test@gmail.com'
)
),
ip_address='ip-here',
snmp_port_number='port-here',
http_port_number='port-here',
location='Houston',
snmp_version='SNMPV2',
type='Modem',
manufacturer='Commscope'
)
如您所见,我正在生成设备对象。但它还需要与它一起创建三个其他对象。有没有人可以在这里给我任何建议,无论是数据库设计、测试设计还是其他方面。
我使用django-autofixture,你可以用它来快速创建对象,它会根据字段类型用随机数据填充你的字段,或者可以指定你希望创建的对象在某些字段中具有的数据.
如果您告诉它这样做,它也会遵循关系。它有很多功能。
感谢@HåkenLid 的帮助link:https://djangopackages.org/grids/g/fixtures/
测试愉快。
我一直在测试需要创建临时对象的代码的方式似乎很混乱。我希望有一种更简洁、更直观的方法。
在设置时,我 运行 函数 setUpTestData 负责创建我的测试稍后可能使用的临时对象。由于 ForeignKey 关系,我必须在其中创建嵌套对象,这变得有点混乱。
这是我正在使用的示例:
class Test_query_alarm(TestCase):
@classmethod
def setUpTestData(cls):
Device.objects.create(
site=Site.objects.create(
group=Group.objects.create(
name='TestGroup'
),
name='TestSiteName',
address='TestAddress',
gps_coordinates='TestGpsCoordinates',
contact=Contact.objects.create(
first_name='TestFirstName',
last_name='TestLastName',
phone='TestPhoneNumber',
email='test@gmail.com'
)
),
ip_address='ip-here',
snmp_port_number='port-here',
http_port_number='port-here',
location='Houston',
snmp_version='SNMPV2',
type='Modem',
manufacturer='Commscope'
)
如您所见,我正在生成设备对象。但它还需要与它一起创建三个其他对象。有没有人可以在这里给我任何建议,无论是数据库设计、测试设计还是其他方面。
我使用django-autofixture,你可以用它来快速创建对象,它会根据字段类型用随机数据填充你的字段,或者可以指定你希望创建的对象在某些字段中具有的数据.
如果您告诉它这样做,它也会遵循关系。它有很多功能。
感谢@HåkenLid 的帮助link:https://djangopackages.org/grids/g/fixtures/
测试愉快。