草庐IT

Django 在单独的数据库上测试给出 "OperationalError: no such table: auth_user"

coder 2023-07-21 原文

我的问题是我想建立一个单独的测试数据库,与我的开发数据库分开。应用程序本身与 Django-Rest-Framework 快速入门教程几乎相同,只是我使用 LDAP 后端。我的开发数据库使用 MySQL。我有单独的设置文件用于测试。

我在此处放置的完整错误回溯:http://dpaste.com/1W3TX1E ,但有趣的部分是:

sqlite3.OperationalError: no such table: auth_user

完整的测试设置在这里:http://dpaste.com/1K7KHK4 .我的相关设置是(安装的应用程序中缺少 pyldap 和 django-ldap-auth,它们是使用 pip 手动安装的):

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'njord',
    'permissions',
]
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

目前,该应用程序基本上只使用 LDAP 进行身份验证。我认为这就是我出现错误的原因 - 当我进行测试时,我的数据库中没有任何内容 - 没有用户,没有组。如果用户通过 LDAP 服务器进行身份验证,则会在数据库中创建用户以及他/她所在的所有组,因此它是按需发生的。

什么有效:我的应用程序的开发版本适用于外部 LDAP,测试也适用于开发数据库。

什么不起作用:使用 sqllite3 内存数据库进行测试(我重复一遍,使用开发数据库和模拟 ldap 进行测试)。

我测试的代码在这里:

from django.test import TestCase, Client
import django
import ldap

from mockldap import MockLdap

class AuthenticationTests(TestCase):
    """
    Set Up the structure  ( Accounts, Groups ) and try authentication
    """
    # Top level hierarchy
    top = ('dc=ee', {'dc': ['ee']})
    test = ('dc=test,dc=ee', {'dc': ['test']})

    # Top level groups
    people = ('ou=people,dc=test,dc=ee', {'ou': ['people'], 'objectClass': ['organizationalUnit', 'top']})
    groups = ('ou=groups,dc=test,dc=ee', {'ou': ['groups'], 'objectClass': ['organizationalUnit', 'top']})

    # Groups
    admins = ('cn=admins,ou=groups,dc=test,dc=ee', {'cn': ['admins'], 'memberUid': ['admin'],
                                                'objectClass': ['sambaGroupMapping', 'posixGroup', 'top'],
                                                'gidNumber': ['1']})

    group1 = ('cn=group1,ou=groups,dc=test,dc=ee', {'cn': ['group1'],
                                                'memberUid': ['alice', 'bob'],
                                      'objectClass': ['sambaGroupMapping', 'posixGroup', 'top']})

    group2 = ('cn=group2,ou=groups,dc=test,dc=ee', {'cn': ['group2'], 'memberUid': ['admin', 'bob', 'karl'],
                                      'objectClass': ['sambaGroupMapping', 'posixGroup', 'top']})

    # Users
    admin = ('uid=admin,ou=people,dc=test,dc=ee', {'uid': ['admin'], 'userPassword': ['ldaptest'], 'sn': ['Joe'],
                                               'cn': ['Admin Joe'], 'mail': ['admin.joe@test.ee'],
                                               'givenName': ['Admin'], 'objectClass':
                                                   ['top', 'person', 'posixAccount', 'shadowAccount',
                                                    'inetOrgPerson', 'sambaSamAccount']})

    alice = ('uid=alice,ou=people,dc=test,dc=ee', {'uid': ['alice'], 'userPassword': ['ldaptest'], 'sn': ['Cooper'],
                                               'cn': ['Alice Cooper'], 'mail': ['alice.cooper@test.ee'],
                                               'givenName': ['Alice'], 'objectClass':
                                                   ['top', 'person', 'posixAccount', 'shadowAccount',
                                                    'inetOrgPerson', 'sambaSamAccount']})

    bob = ('uid=bob,ou=people,dc=test,dc=ee', {'uid': ['bob'], 'userPassword': ['ldaptest'], 'sn': ['Marley'],
                                           'cn': ['Bob Marley'], 'mail': ['bob.marley@test.ee'],
                                           'givenName': ['Bob'], 'objectClass':
                                               ['top', 'person', 'posixAccount', 'shadowAccount',
                                                'inetOrgPerson', 'sambaSamAccount']})

    karl = ('uid=karl,ou=people,dc=test,dc=ee', {'uid': ['karl'], 'userPassword': ['ldaptest'], 'sn': ['Suur'],
                                             'cn': ['Karl Suur'], 'mail': ['karl.suur@test.ee'],
                                             'givenName': ['Karl'], 'objectClass':
                                                 ['top', 'person', 'posixAccount', 'shadowAccount',
                                                  'inetOrgPerson', 'sambaSamAccount']})

    # This is the content of our mock LDAP directory. It takes the form
    # {dn: {attr: [value, ...], ...}, ...}.
    directory = dict([top, test, people, groups, admins, group1, group2, admin, alice, bob, karl])

    @classmethod
    def setUpTestData(cls):
        # We only need to create the MockLdap instance once. The content we
        # pass in will be used for all LDAP connections.
        cls.mockldap = MockLdap(cls.directory)

    @classmethod
    def tearDownClass(cls):
        del cls.mockldap

    def setUp(self):
        # Patch ldap.initialize
        django.setup()
        self.mockldap.start()
        self.ldapobj = self.mockldap['ldap://localhost/']

    def tearDown(self):
        # Stop patching ldap.initialize and reset state.
        self.mockldap.stop()
        del self.ldapobj

    def test_some_basic_mockldap_auth(self):
        searchStr = 'uid=alice,ou=people,dc=test,dc=ee'
        results = _do_simple_ldap_search(searchStr)
        ldapName = results[0][0]
        ldapPropDict = results[0][1]
        self.assertEqual(searchStr, ldapName)
        self.assertEqual(len(ldapPropDict), 7)

    def test_index_visible_for_all(self):
        c = Client()
        response = c.get("/")
        self.assertContains(response, "/users/", 1)
        self.assertContains(response, "/groups/", 1)

    def test_login(self):
        c = Client()
        response = c.post("/api-auth/login/", {'username': 'bob', 'password': 'ldaptest'})
        print(response.status_code)
        response = c.get("/users/")
        print(response._container)

def _do_simple_ldap_search(searchStr):
    conn = ldap.initialize('ldap://localhost/')
    conn.simple_bind_s(searchStr, 'ldaptest')
    results = conn.search_s(searchStr, ldap.SCOPE_SUBTREE, )

    return results

代码也可在此处获得:http://dpaste.com/3D2H4NK (语法高亮)。

我不确定是什么问题。我唯一能想到的是,因为创建时数据库中没有用户,所以没有创建数据库,但我不确定。任何帮助深表感谢。

我已经完成了所有的迁移。

(venv)user@box:~/workspace/fileshare/njord$ python manage.py showmigrationsadmin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial
(venv)user@box:~/workspace/fileshare/njord$ python manage.py makemigrationsNo changes detected
(venv)user@box:~/workspace/fileshare/njord$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, sessions, auth, contenttypes
Running migrations:
  No migrations to apply.

最佳答案

运行
python manage.py makemigrations <appname>
对于 INSTALLED_APPS 中的每个应用程序.(特别是在 auth_user 上有 ForeignKey 字段的应用程序)

我遇到了不同的错误让我来到这里,但我认为原因是一样的。
django.db.utils.OperationalError: (1005, "Can't create table '<test_db>.#sql-3821_1c9' (errno: 150)")

在这两种情况下,所有表都与 auth 相关模块仅在测试时不创建,不执行 makemigrations命令。
我从 here 找到了解决方案

关于Django 在单独的数据库上测试给出 "OperationalError: no such table: auth_user",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38390997/

有关Django 在单独的数据库上测试给出 "OperationalError: no such table: auth_user"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  9. ruby - RVM "ERROR: Unable to checkout branch ."单用户 - 2

    我在新的Debian6VirtualBoxVM上安装RVM时遇到问题。我已经安装了所有需要的包并使用下载了安装脚本(curl-shttps://rvm.beginrescueend.com/install/rvm)>rvm,但以单个用户身份运行时bashrvm我收到以下错误消息:ERROR:Unabletocheckoutbranch.安装在这里停止,并且(据我所知)没有安装RVM的任何文件。如果我以root身份运行脚本(对于多用户安装),我会收到另一条消息:Successfullycheckedoutbranch''安装程序继续并指示成功,但未添加.rvm目录,甚至在修改我的.bas

  10. ruby - 如何关闭 ruby​​ gem "Spreadsheet?"中的文件 - 2

    下面的代码在我第一次运行它时就可以正常工作:require'rubygems'require'spreadsheet'book=Spreadsheet.open'/Users/me/myruby/Mywks.xls'sheet=book.worksheet0row=sheet.row(1)putsrow[1]book.write'/Users/me/myruby/Mywks.xls'当我再次运行它时,我会收到更多消息,例如:/Library/Ruby/Gems/1.8/gems/spreadsheet-0.6.5.9/lib/spreadsheet/excel/reader.rb:11

随机推荐