0

我正在尝试测试一个组织为 Python 包的 Django 可重用应用程序。这是目录树:

reusableapp
├── __init__.py
└── submodule
    ├── __init__.py
    └── app
        ├── __init__.py
        ├── models.py
        ├── tests.py
        └── views.py

我的 Django 版本是 1.5。要选择应用程序进行测试,我有以下基于此处公开的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Description: Execute tests from outside Django's project
"""


import os
import sys

from django.conf import settings


DIRNAME = os.path.dirname(__file__)

INSTALLED_APPS = [
    "reusableapp.submodule.app"
]

settings.configure(
    DEBUG=True,
    DATABASES={
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
        }
    },
    INSTALLED_APPS=tuple(INSTALLED_APPS),
    CACHES={
        "default": {
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        }
    },
)


if __name__ == "__main__":

    from django.test.simple import DjangoTestSuiteRunner

    test_runner = DjangoTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(INSTALLED_APPS)
    if failures:
        sys.exit(failures)

但是当我执行它时,我得到了以下错误(使用 virtualenv):

(reusableapp) $ python runtests.py
Traceback (most recent call last):
  File "runtests.py", line 48, in <module>
    failures = test_runner.run_tests(INSTALLED_APPS)
  File "/var/lib/virtualenvs/reusableapp/local/lib/python2.7/site-packages/django/test/simple.py", line 369, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "/var/lib/virtualenvs/reusableapp/local/lib/python2.7/site-packages/django/test/simple.py", line 254, in build_suite
    suite.addTest(build_test(label))
  File "/var/lib/virtualenvs/reusableapp/local/lib/python2.7/site-packages/django/test/simple.py", line 102, in build_test
    app_module = get_app(parts[0])
  File "/var/lib/virtualenvs/reusableapp/local/lib/python2.7/site-packages/django/db/models/loading.py", line 160, in get_app
    raise ImproperlyConfigured("App with label %s could not be found" % app_label)
django.core.exceptions.ImproperlyConfigured: App with label reusableapp could not be found

我在 Django 文档中搜索了有关可重用应用程序和格式的信息,但除了“只是一个专门用于 Django 项目的 Python 包。应用程序还可以使用常见的 Django 约定,例如拥有一个 models.py文件”

你知道一些明确的约定/要求明确可重用的应用程序格式吗?如果没有,您是否遇到过这种情况?有没有办法强制加载应用程序?

感谢你并致以真诚的问候。

4

1 回答 1

0

假设您的应用程序路径是 /parentdir/reusableapp/submodule/app

首先通过在 python 解释器中运行以下命令来确保你的 PYTHONPATH 中有 /parentdir/ :-

>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)

可能你不会看到这个路径,在你的 django 项目 manage.py 文件中添加以下行。

sys.path.append('/parentdir/')

另外-
您是否检查了 TEMPLATE_LOADERS 中的设置 django.template.loaders.app_directories.Loader,如果还没有,请尝试像这样添加它-

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

关于模板子目录的 django 文档 - https://docs.djangoproject.com/en/dev/ref/templates/api/#using-subdirectories

希望它会有所帮助。

于 2013-11-02T17:26:40.340 回答