Django 找不到嵌套测试



我有以下文件结构:

project -
- resources
-__init__.py
- core
__init__.py
tests.py

我的测试代码如下所示:

class TestEmailHelper(TestCase):
def test_send_mail(self):
EmailHelper.send_email(EmailHelper.SLUGS.ORDER_COMPLETED, 'lee@lee.com', {})
assert len(mail.outbox) == 1, "Inbox is not empty"

以下是应用程序 apps.py 文件中的配置:

class CoreConfig(AppConfig):
name = 'resources.core'

而且,当然,这是我INSTALLED_APPS,除了找到测试之外,工作得很好。

如果我尝试运行所有测试,则得到响应"未运行测试,请检查测试的配置设置。

如果我使用此命令,它可以工作:

python3 manage.py test resources/core

如果我使用此命令,则在查找"core"时会出现"找不到模块"的错误:

python3 manage.py test core

在我看来,这可能与嵌套我的应用程序有关,因为当我没有在拍子后面附加"资源"时会导致错误。但我不确定如何解决这个问题。

在python中,缩进很重要,您必须在class下缩进def声明:

class TestEmailHelper(TestCase):
def test_send_mail(self):
EmailHelper.send_email(EmailHelper.SLUGS.ORDER_COMPLETED, 'lee@lee.com', {})
assert len(mail.outbox) == 1, "Inbox is not empty"

我遇到了同样的问题。 我所有的应用程序都在嵌套在项目主目录中的"apps"目录中,带有设置、WSGI 和 .ect。 所以我得出的结论是使用这样的命令(执行我所有的嵌套应用程序测试(:

python manage.py test project/apps

,或者创建一个从内置的"test"命令继承的自定义测试命令,并覆盖其"handle"方法,将路径传输到我的应用程序目录。

from django.core.management.commands import test

class Command(test.Command):
def handle(self, *args, **options):
test_labels = 'project/apps'
super().handle(test_labels, **options)

关于如何在 Django 中创建命令的文档:https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/

最新更新