sqlite3 db缺少表的单元测试Django项目 - python

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')

参考方案

我也有这个问题。原来,我必须在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'),
        }
    }

'ManyToManyDescriptor'类型的参数不可迭代 - python

我有模式:class Subscribe(models.Model): class Meta: verbose_name_plural = 'sunscribes' id=models.AutoField(primary_key=True) name=models.CharField(max_length=30,null=False); …

为什么使用'=='或'is'比较字符串有时会产生不同的结果? - python

我有一个Python程序,其中将两个变量设置为'public'值。在条件表达式中,我有比较var1 is var2失败,但如果将其更改为var1 == var2,它将返回True。现在,如果我打开Python解释器并进行相同的“是”比较,则此操作成功。>>> s1 = 'public' >>…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

如何修复AttributeError:模块'numpy'没有属性'square' - python

Improve this question 我已经将numpy更新为1.14.0。我使用Windows10。我尝试运行我的代码,但出现此错误: AttributeError:模块“ numpy”没有属性“ square”这是我的进口商品:%matplotlib inline import matplotlib.pyplot as plt import ten…