python manage.py测试:django.db.utils.OperationalError:没有这样的表:account_user

时间:2019-07-18 10:52:56

标签: python django unit-testing

我在测试方面还很陌生,尝试使用python manage.py test为django项目运行测试时,我最终得到了django.db.utils.OperationalError: no such table: accounts_user

我在accounts应用程序中具有User模型,并且在我的settings.py中已将accounts应用程序添加到已安装的应用程序中。

我已经为所有项目应用程序运行了makemgirations并进行了迁移,我也进入了项目外壳,并尝试在accounts应用程序中通过User模型创建用户,所有这些方法都很好,但是当我运行测试时出现错误。

以下是我正在尝试运行的测试,该测试会产生错误

from django.test import TestCase
from django.contrib.auth import get_user_model

class UserTestCase(TestCase):
    def setUp(self):
        USER = get_user_model()
        USER.objects.create(
            email="johndoe@example.com", first_name="John", last_name="Doe"
        )
        USER.objects.create(
            email="janedoe@example.com", first_name="Jane", last_name="Doe"
        )

    def test_user_full_name(self):
        """ A user's fullname correctly identified """
        jane = USER.objects.get(email="janedoe@example.com")
        john = USER.objects.get(email="johndoe@example.com")

        self.assertEqual(jane.get_full_name(), "Jane Doe")
        self.assertEqual(john.get_full_name(), "John Doe")

和下面是我在项目外壳中运行的代码

from django.contrib.auth import get_user_model
USER = get_user_model()
USER.objects.create(
     email="johndoe@example.com", first_name="John", last_name="Doe"
)
USER.objects.create(
     email="janedoe@example.com", first_name="Jane", last_name="Doe"
)

USER.objects.all()

# returns both object that has been added

以下是我的数据库设置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'TEST': {
            'test_NAME': 'test_db',
        }
    }
}

请问如何解决

下面是完整的堆栈跟踪

$ python manage.py test
Creating test database for alias 'default'...
Traceback (most recent call last):
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
    return self.cursor.execute(sql)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: no such table: accounts_user

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv
    super().run_from_argv(argv)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\commands\test.py", line 53, in handle
    failures = test_runner.run_tests(test_labels)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\test\runner.py", line
629, in run_tests
    old_config = self.setup_databases(aliases=databases)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\test\runner.py", line
554, in setup_databases
    self.parallel, **kwargs
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\test\utils.py", line 174, in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\base\creation.py", line 72, in create_test_db
    run_syncdb=True,
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\__init__.py", line 148, in call_command
    return command.execute(*args, **defaults)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
    self.sync_apps(connection, executor.loader.unmigrated_apps)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\core\management\commands\migrate.py", line 341, in sync_apps
    self.stdout.write("    Running deferred SQL...\n")
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\sqlite3\schema.py", line 34, in __exit__
    self.connection.check_constraints()
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\sqlite3\base.py", line 341, in check_constraints
    column_name, referenced_column_name,
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
    return self.cursor.execute(sql)
  File "C:\Users\i-am-prinx\.virtualenvs\ProjectName-2t3W9LfY\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute
    return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: no such table: accounts_user

工具和版本 django v 2.2 python v 3.6

3 个答案:

答案 0 :(得分:3)

这对我有用;

删除所有迁移文件,然后运行

python .\manage.py migrate --run-syncdb

应该可以。

答案 1 :(得分:0)

尝试像这样设置数据库设置(这取决于您使用的Django版本):

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

答案 2 :(得分:0)

此问题的主要原因是因为项目中的一个应用程序具有一个模型,该模型具有一个User模型的外键字段,并且该应用程序没有migrations文件夹,并且该应用程序中的模型(包括那些引用了User模型的外键的人)尚未迁移(请注意,该应用位于已安装的应用中)。 我按照以下步骤解决了这个问题

**步骤和我注意到的内容的说明**

  • 我删除了项目根目录上的db.sqlite3文件

    • 我删除了所有应用程序上的迁移目录(尽管我运行python manage.py makemigrations,但并非所有应用程序都具有迁移文件夹,原因我真的不知道)。唯一具有迁移文件夹的应用是accounts应用。

    • 然后我为所有应用程序显式运行makemigrations(即使未显式运行migration命令,测试仍然有效,到目前为止makemigrations已运行),然后我运行了python manage.py migrate命令< / p>

**上面的代码**

class UserTestCase(TestCase):
    def setUp(self):

        USER = get_user_model()  # <---  doing this here generates error when using USER.get() in the test_... methods
        USER.objects.create(
            email="johndoe@example.com", first_name="John", last_name="Doe"
        )
        USER.objects.create(
            email="janedoe@example.com", first_name="Jane", last_name="Doe"
        )

    def test_user_full_name(self):
        """ A user's fullname correctly identified """
        jane = USER.objects.get(email="janedoe@example.com")
        john = USER.objects.get(email="johndoe@example.com")

        self.assertEqual(jane.get_full_name(), "Jane Doe")
        self.assertEqual(john.get_full_name(), "John Doe")

上面的代码将失败,并且正确的代码应该是

USER = get_user_model() 
class UserTestCase(TestCase):
    def setUp(self):
        USER.objects.create(
            email="johndoe@example.com", first_name="John", last_name="Doe"
        )
        USER.objects.create(
            email="janedoe@example.com", first_name="Jane", last_name="Doe"
        )

    def test_user_full_name(self):
        """ A user's fullname correctly identified """
        jane = USER.objects.get(email="janedoe@example.com")
        john = USER.objects.get(email="johndoe@example.com")

        self.assertEqual(jane.get_full_name(), "Jane Doe")
        self.assertEqual(john.get_full_name(), "John Doe")

我希望这可以帮助某人