我已经创建了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”
我做错了什么?
P.S。 这是我的项目层次结构:
MyProj:
forum (it's my app):
manage.py
models.py
views.py
tests.py
...
我将test.py重命名为tests.py。 Eclipse得到了这个模块的测试,但答案仍然是“在0.000s内进行0测试”
答案 0 :(得分:33)
您需要为每种测试方法使用前缀test_
。
答案 1 :(得分:11)
要点:
0)尝试仅针对您的应用运行:
python manage.py test YOUR_APP
1)如果YOUR_APP在INSTALLED_APP配置中,请检入 settings.py 文件
2)测试方法应以单词&#34; test&#34;开头,例如:
def test_something(self):
self.assertEquals(1, 2)
3)如果您使用名为 tests 的目录而不是 tests.py 文件,请检查它是否有 init .py里面的文件。
4)如果您使用的是测试目录,请删除 tests.pyc 和 tests.pyo 文件。 ( pycache dir for Python3)
答案 2 :(得分:6)
尝试将您的方法test
重命名为test_content
。
我相信测试运行器将运行名为test_*
的所有方法(请参阅organising test code的python文档.Django的TestCase
是unittest.TestCase
的子类,所以相同的规则应该适用。
答案 3 :(得分:5)
您必须将其命名为tests.py
。
答案 4 :(得分:3)
如果在将文件重命名为tests.py
后获得相同的结果,则有些不太正确。你是如何运行测试的?您是从命令行执行此操作还是使用Eclipse设置自定义运行目标?如果您还没有,请从命令行尝试。
同时启动Django shell(python manage.py shell
)并导入测试模块。
from MyProj.forum.tests import SimpleTest
导入是否正常?
答案 5 :(得分:1)
我已经尝试了所有这些东西,但是我忽略了在我创建的tests目录中添加__init__.py文件以保存我的所有测试而Django无法找到它。
答案 6 :(得分:0)
经过一段时间的搜索,我没有发现有人建议这样做,因此我将其分享为最新答案。
就我而言,我的manage.py
位于根目录中,例如
.
...
├── dir
│ ├── project_name
│ ├── manage.py
│ ├── media
│ ├── app1
│ ├── static
│ ├── staticfiles
│ ├── templates
│ └── app2
...
所以我发现the test command可以选择提供要运行测试的项目。就我而言,我必须这样做
python project_name/manage.py test ./project_name/
这成功运行了我的测试。