简体   繁体   English

Django测试使用新ID创建表单

[英]Django Test Creating Forms with New IDs

I have just moved all of my AJAX validation code over to Django Forms. 我刚刚将所有AJAX验证代码移至Django Forms。 I need some help updating my tests. 我需要一些帮助更新测试。 I basically have some test data, declared as constants, that are used across all suites. 我基本上有一些声明为常量的测试数据,可在所有套件中使用。 I am then this data repeatedly throughout my tests. 在整个测试过程中,我会反复获得这些数据。

As part of the setup I create some users and login the user that I need: 作为设置的一部分,我创建了一些用户并登录所需的用户:

def setUp(self):
    self.client = Client()
    create_user(username='staff', email='staff@staff.com',
                password='staff', staff=True)
    create_user(username='agent', email='agent@agent.com',
                password='agent', staff=False)
    ShiftType.objects.create(type_id='SI', description='Sales Inbox')
    self.client.login(username='staff', password='staff')

The tear down deletes this data (or it used to): 拆解将删除此数据(或曾经删除):

def tearDown(self):
    # Clean up the DB
    self.client.logout()
    ShiftType.objects.all().delete()
    User.objects.all().delete()
    Event.objects.all().delete()
    RecurrentEvent.objects.all().delete()

This was working fine, but now the form does not validate because the form value id given by the users is incremented each time. 这工作正常,但是现在表单无法验证,因为用户给定的表单值ID每次都会增加。 For example: 例如:

 ERROR: <ul class="errorlist"><li>employee_id<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

Printing the form allows me to see that the ids are being incremented each time. 打印表格可以让我看到id每次都在增加。

Why is this happening even though I am deleting all employees? 即使我要删除所有员工,为什么仍会发生这种情况?

I would look into using text fixtures rather than creating and deleting the data every time. 我会考虑使用文本固定装置,而不是每次都创建和删除数据。 This is pretty easy to do in Django. 这在Django中很容易做到。 In your tests.py it would look something like this 在您的tests.py中,它看起来像这样

class BlogTest(TestCase):
    fixtures = ['core/fixtures/test.json']

When you do this django will build you a test database, load the fixture into it, run your tests, and then blow away the database after the tests are done. 当您执行此操作时,django将为您构建一个测试数据库,将夹具加载到其中,运行测试,然后在测试完成后销毁数据库。 If you want to even use a different database engine (we do this to have our tests use sqlite because it is fast) you can throw something like this into your settings.py 如果您甚至想使用其他数据库引擎(我们这样做是为了使我们的测试使用sqlite,因为它很快),那么您可以在您的settings.py中添加类似的内容

This will make it so the ID's are the same every single time which would fix your problem. 这样可以使ID每次都相同,从而解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM