为什么Django看不到我的测试?

12 投票
7 回答
14131 浏览
提问于 2025-04-16 03:48

我创建了一个叫 test.py 的模块,里面填充了一些内容

from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.contrib.sites.models import Site

from forum.models import *

class SimpleTest(TestCase):


    def setUp(self):
        u = User.objects.create_user("ak", "ak@abc.org", "pwd")
        Forum.objects.create(title="forum")
        Site.objects.create(domain="test.org", name="test.org")

    def content_test(self, url, values):
        """Get content of url and test that each of items in `values` list is present."""
        r = self.c.get(url)
        self.assertEquals(r.status_code, 200)
        for v in values:
            self.assertTrue(v in r.content)

    def test(self):
        self.c = Client()
        self.c.login(username="ak", password="pwd")

        self.content_test("/forum/", ['<a href="/forum/forum/1/">forum</a>'])
        ....

然后把它放在了我的应用程序的文件夹里。

当我通过

python manage.py test forum

运行测试并创建测试数据库后,我得到了一个回应:“Ran 0 tests in 0.000s”。

我到底哪里做错了呢?

附注:这是我的项目结构:

MyProj:
    forum (it's my app):
        manage.py
        models.py
        views.py
        tests.py
        ...

我把 test.py 重命名为 tests.py。Eclipse 识别到这个模块是用来测试的,但回应仍然是“Ran 0 tests in 0.000s”。

7 个回答

21

总结

  1. 尝试只为你的应用程序运行:

    python manage.py test YOUR_APP
    
  2. 检查一下你的 settings.py 文件,看看 INSTALLED_APPS 配置里是否有你的应用名(YOUR_APP)。

  3. 测试方法的名字应该以 test_ 开头,比如:

    def test_something(self):
        self.assertEquals(1, 2)
    
  4. 如果你用的是一个叫 tests 的文件夹,而不是 tests.py 文件,检查一下里面是否有一个 __init__.py 文件。

  5. 如果你用的是 tests 文件夹,记得删除 tests.pyctests.pyo 文件。(对于 Python3,这些文件会在 __pycache__ 文件夹里)

41

你需要在每个测试方法前面加上前缀 test_

3

如果你把文件改名为 tests.py 后,结果还是一样,那就说明有些地方不对劲。你是怎么运行测试的呢?是通过命令行运行,还是在Eclipse里设置了自定义的运行目标?如果还没试过,建议你先从命令行试一下。

另外,打开Django的命令行工具(输入 python manage.py shell),然后导入你的测试模块。

from MyProj.forum.tests import SimpleTest

导入成功了吗?

撰写回答