0

我正在尝试创建一个UserFactory,运行时出现此错误./manage.py test

OperationalError: no such table: auth_user

这是我的factories.py文件的样子:

import factory
import django.contrib.auth.models as auth_models
from wacep.weatherroulette.models import (
    GameState, Puzzle
)


class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = auth_models.User

    username = factory.Sequence(lambda n: "user_%d" % n)


class PuzzleFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Puzzle

    display_name = factory.Sequence(lambda n: 'Test Puzzle {0}'.format(n))
    description = factory.Sequence(lambda n: 'Description {0}'.format(n))


class GameStateFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = GameState

    user = UserFactory()
    current_inventory = 300

有人知道这里发生了什么吗?

4

4 回答 4

2

Actually, the error occurs because django.contrib.auth is not part of your settings.INSTALLED_APPS.

The error you see happens when factory_boy tries to create a django.contrib.auth.models.User and doesn't find the related table in the database.

That table should have been automatically created at the beginning of the test by Django's test runner ; the fact that it wasn't created means that you didn't add django.contrib.auth to your INSTALLED_APPS.

于 2014-10-23T08:56:52.770 回答
2

factory.Factory哦..从而不是继承factory.django.DjangoModelFactory似乎可以解决错误。

于 2014-10-07T20:19:38.610 回答
1

我实际上遇到了这个问题,因为我自己也遇到了同样的问题,经过一番研究,我想我知道问题出在哪里。正如您可能已经猜到的那样,它与这一行有关:

user = UserFactory()

您在此处实际执行的操作将尝试在未正确使用 Django ORM 的情况下创建 User 对象。作为旁注:我还没有完全解析这里出了什么问题——它要么在设置测试数据库之前尝试在导入期间创建一个用户对象,要么它实际上没有与适当的数据库通信。至少结果是它需要一点 Django 魔法来创建你的对象。factory_boy 提供了这种魔力。

将此行更改为:

user = UserFactory.create()

应该解决你的错误。

于 2015-05-13T15:54:39.813 回答
0

This is really a late answer, but I have suffered this issue today and want to share my solution.

Using django, my develop setting settings.local uses Postgresql but the test setting settings.test uses sqlite3. Running the test under settings.test resulted in no such table error, as below.

$ DJANGO_SETTINGS_MODULE=myproject.settings.test python manage.py test
OperationalError: no such table: ...

This seems because the sqlite3 database has no schema as I have never used sqlite3 for developing. So I migrate for sqlite

$ DJANGO_SETTINGS_MODULE=myproject.settings.test python manage.py migrate
# ... migration running for sqlite3 ...

As the migration finished, I could run the tests with the sqlite3 test database as intended.

于 2017-11-08T02:28:09.507 回答