使用 django 单元测试遇到一些相当奇怪的行为。我有一个从 django.test.testcase 继承的类,它验证注册表会创建一个人员对象和一个用户对象,它确实如此,但我随后可以在测试完成后在管理界面中查找并找到对象。这是测试:
import unittest
import time
from django.test import TestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.contrib.auth.models import User
from apps.persons.models import Person
class NewVisitorTest(TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_can_sign_up_and_login(self):
# User goes to register url
self.browser.get('http://localhost:8000/register/')
# User can see that she has come to the right page on the website
self.assertIn('Register', self.browser.title)
# User can see that there is a sign up form
signup_form = self.browser.find_element_by_id('id_registration_form')
# User can enter text into the first name field
first_name_input = self.browser.find_element_by_id('id_first_name')
first_name_input.send_keys('Jim')
# User can enter text into the last name field
last_name_input = self.browser.find_element_by_id('id_last_name')
last_name_input.send_keys('bob')
# User can enter text into the username field
username_input = self.browser.find_element_by_id('id_username')
username_input.send_keys('jim_bob')
# User can enter text into the email field
email_input = self.browser.find_element_by_id('id_email')
email_input.send_keys('jim_bob@jimbob.com')
# User can enter text into the first password field
password_input = self.browser.find_element_by_id('id_password')
password_input.send_keys('kittensarecute')
# User can enter text into the second password field
password_1_input = self.browser.find_element_by_id('id_password1')
password_1_input.send_keys('kittensarecute')
# Submit form
signup_form.submit()
time.sleep(20)
persons = Person.objects.all()
print persons
self.assertEqual(len(persons), 1)
users = User.objects.all()
print users
self.assertEqual(len(users), 1)
# Deliberately fail
self.fail('Finish the test!')
if __name__ == '__main__':
unittest.main()
代码在 assertEqual(len(persons), 1) 上失败。我可以在浏览器中重现相同的行为并且没有问题。每次运行测试时,我都必须删除它在主本地数据库中创建的用户,所以我假设它将对象保存在设置 ['databases'] 中定义的数据库中,然后在测试数据库中查找它们后面的方法。我在终端中看到测试数据库是在每次测试开始时创建的,所以它肯定存在,这似乎令人困惑。任何帮助将不胜感激。
编辑:一切都在 sqlite 上
File ".../tests/tests.py", line 60, in test_can_sign_up_and_login
self.assertEqual(len(persons), 1)
AssertionError: 0 != 1
编辑2:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/Users/me/github/stage/project/data/db.db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
我有一个包含应用程序的文件夹,因此要运行这些测试并运行:
python manage.py test tests