使用sqlite3 db缺少表对django项目进行单元测试

时间:2012-05-31 19:33:35

标签: python django unit-testing sqlite

Missing Table When Running Django Unittest with Sqlite3

我已经查看了这篇文章,并且正在尝试设置我的项目进行测试。每当我尝试运行任何数据库命令时,我都会收到错误消息。我遇到的问题是当我尝试执行manage.py syncdb时,我得到一个数据库错误,表示即使它当前在模型文件和生产数据库中也没有这样的表。

这是追溯。

brandon@Brandon-PC:~/course-management$ ./manage.py test Testing.SimpleTest
Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_manager(settings)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/South-0.7.3-py2.7.egg/south/management/commands/test.py", line 8, in handle
    super(Command, self).handle(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
    failures = test_runner.run_tests(test_labels)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 245, in build_suite
    suite.addTest(build_test(label))
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 107, in build_test
    app_module = get_app(parts[0])
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 129, in get_app
    self._populate()
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/home/brandon/course-management/Course/models.py", line 223, in <module>
    class CourseDelivery(models.Model):
  File "/home/brandon/course-management/Course/models.py", line 262, in CourseDelivery
    Language = models.ForeignKey('Utilities.Language', default=Language.objects.get(Code='en'))
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/manager.py", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 344, in get
    num = len(clone)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 82, in __len__
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 273, in iterator
    for row in compiler.results_iter():
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 680, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 735, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 234, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.DatabaseError: no such table: Utilities_language

这是在我的settings.py文件中

if 'test' in sys.argv or 'jenkins' in sys.argv:
DATABASES = {
             'default': {
                         'ENGINE': 'django.db.backends.sqlite3',
                         'NAME': 'test_ndptc'
                         }
             }

如果我将上面的if语句设置为true并尝试运行manage.py syncdb,也会出现同样的错误。

以下是造成问题的模型。

class CourseDelivery(models.Model):
"""
"""
Course = models.ForeignKey(Course)
TrainingMethod = models.ForeignKey(TrainingMethod)
DeliveryType = models.ForeignKey(DeliveryType)
Location = models.ForeignKey(Address, null=True)
Lat = models.FloatField()
Lon = models.FloatField()
StartDate = models.DateTimeField()
EndDate = models.DateTimeField()
FinishDate = models.DateField(null=True)
ConfirmationCode = models.CharField(max_length=8, editable=False, unique=True)
Reported = models.BooleanField()
ReportedDate = models.DateField(null=True)
SequenceNumber = models.IntegerField(null=True)
Status = models.IntegerField()
HostingAgency = models.TextField(null=True, blank=True)
MaximumEnrollment = models.IntegerField(null=True, blank=True)
ContactInformation = models.TextField(null=True, blank=True)
ArrivalTime = models.TextField(null=True, blank=True)
CourseMaterials = models.TextField(null=True, blank=True)
Internet = models.TextField(null=True, blank=True)
Food = models.TextField(null=True, blank=True)
Parking = models.TextField(null=True, blank=True)
Requirements = models.TextField(null=True, blank=True)
AdditionalInformation = models.TextField(null=True, blank=True)
ReadingMaterials = models.TextField(null=True, blank=True)
SpecialNote = models.TextField(null=True, blank=True)
CertificateEmailsSent = models.BooleanField(default=False)
RegistrationCloseDate = models.DateTimeField(null=True, blank=True)
ReminderDate = models.DateTimeField(null=True, blank=True)
PreTestCloseDate = models.DateTimeField(null=True, blank=True)
PostTestCloseDate = models.DateTimeField(null=True, blank=True)
EvaluationCloseDate = models.DateTimeField(null=True, blank=True)
ParticipantGuide = models.ForeignKey('Course.Document', null=True, blank=True)
Flyer = models.FileField(upload_to='flyers/%Y/%m', null=True, blank=True)
UpdateUser = models.ForeignKey(User, null=True)
UpdateDate = models.DateField(null=True)
Language = models.ForeignKey('Utilities.Language', default=Language.objects.get(Code='en'))

def save(self):
    # If this is the first time around, or AUTO_COMPUTE_DATES is true, compute the dates.
    if self.Status & CourseDeliveryStatus.AUTO_COMPUTE_DATES:
        self.RegistrationCloseDate   = self.StartDate - datetime.timedelta(days=REGISTRATION_CLOSE_DATE)
        self.ReminderDate            = self.StartDate - datetime.timedelta(days=REMINDER_DATE)
        self.PreTestCloseDate        = self.StartDate - datetime.timedelta(days=PRE_TEST_CLOSE_DATE)
        self.PostTestCloseDate       = self.EndDate   + datetime.timedelta(days=POST_TEST_CLOSE_DATE)
        self.EvaluationCloseDate     = self.EndDate   + datetime.timedelta(days=EVALUATION_CLOSE_DATE)
        self.FinishDate              = self.EndDate   + datetime.timedelta(days=FINISH_DATE)
    elif self.id == None:
        if not self.RegistrationCloseDate:
            self.RegistrationCloseDate   = self.StartDate - datetime.timedelta(days=REGISTRATION_CLOSE_DATE)
        if not self.ReminderDate:
            self.ReminderDate            = self.StartDate - datetime.timedelta(days=REMINDER_DATE)
        if not self.PreTestCloseDate:
            self.PreTestCloseDate        = self.StartDate - datetime.timedelta(days=PRE_TEST_CLOSE_DATE)
        if not self.PostTestCloseDate:
            self.PostTestCloseDate       = self.EndDate   + datetime.timedelta(days=POST_TEST_CLOSE_DATE)
        if not self.EvaluationCloseDate:
            self.EvaluationCloseDate     = self.EndDate   + datetime.timedelta(days=EVALUATION_CLOSE_DATE)
        if not self.FinishDate:
            self.FinishDate              = self.EndDate   + datetime.timedelta(days=FINISH_DATE)

    # If the course does not have a code, create one.
    if not self.ConfirmationCode:
        self.ConfirmationCode = ''.join(Random().sample(string.digits, 5))
    #Course.functions.geocode_course_delivery(self)
    super(CourseDelivery, self).save()

def __unicode__(self):
    return unicode(self.StartDate.strftime('%m/%d/%Y')) + ' - ' + self.Course.CourseName \
        + ' (' + unicode(self.Location.City) + ', ' + unicode(self.Location.State) + ')'

def registration_date_passed(self):
    today = datetime.date.today()
    if today > self.RegistrationCloseDate.date():
        return True
    return False

def registration_open(self):
    # Do not allow registrations after the course has been reported.
    if self.Reported:
        return False

    # Check that the closing dates and enrollment are good.
    today = datetime.date.today()
    if self.Status & CourseDeliveryStatus.ONLINE_REGISTRATION:
        if self.RegistrationCloseDate.date() < today:
            return False

        # Make sure that the MaximumEnrollment is greater than the participant count
        if not self.wait_list_enabled() and self.MaximumEnrollment:
            participant_count = Participant.objects.filter(CourseDelivery=self).count()
            if not self.MaximumEnrollment - participant_count > 0:
                return False
        return True
    return False

def wait_list_enabled(self):
    if self.Status & CourseDeliveryStatus.WAIT_LIST:
        return True
    return False

def get_form(self, form_type):
    package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
    __import__(package.FormModule)
    return eval(package.FormName)

def get_model(self, form_type):
    package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
    __import__(package.ModelModule)
    return eval(package.ModelName)

def get_template(self, form_type):
    package = CourseDeliveryForms.objects.filter(CourseDelivery=self.id).get(FormType=form_type).FormPackage
    return package.Template

def default_language(self):
    return Language.objects.get(Code='en')

2 个答案:

答案 0 :(得分:2)

我也有这个问题。原来我必须在settings.py文件中添加TEST_NAME属性才能正确识别测试数据库。它解决了我的问题:

if 'test' in sys.argv:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(os.path.dirname(__file__), 'test.db'),
            'TEST_NAME': os.path.join(os.path.dirname(__file__), 'test.db'),
        }
    }

答案 1 :(得分:0)

对于具有单元测试的db NAME,我建议始终使用“:memory:”。我曾经错误地指定了一个实际的数据库路径,我的单元测试需要45分钟才能运行。当我指定“:memory:”时,它们在不到一分钟的时间内运行。

if 'test' in sys.argv:
    DATABASES = {
        'default':{
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
            'TEST_NAME': ':memory:',
        },
    }