我的问题是我想建立一个单独的测试数据库,与我的开发数据库分开。 App本身几乎与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.
答案 0 :(得分:1)
运行
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
答案 1 :(得分:0)
必须要做的是将这些行添加到manage.py:
if __name__ == "__main__":
if 'test' in sys.argv:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.test_settings")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
添加后如果&#39; test&#39;对于manage.py的主要方法的东西,应用程序开始正常工作,之后python manage.py测试和python manage.py runserver都使用正确的设置。
但是,我没有让它与PyCharm合作并立即进行测试,如何让它发挥作用。