我是tests in Django的新手。我需要写几个。
Django 1.9.7版。
操作系统:Linux version 4.2.0-42-generic (buildd@lgw01-54) (gcc version 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2) ) #49-Ubuntu SMP Tue Jun 28 21:26:26 UTC 2016
我的简单测试代码是:
cat animal/tests.py
from django.test import TestCase
from animal.models import Animal
class AnimalTestCase(TestCase):
def say_hello(self):
print('Hello, World!')
我以这种方式执行./manage.py test animal
出现以下错误:
Traceback (most recent call last):
File "./manage.py", line 13, in <module>
execute_from_command_line(sys.argv)
File "/path-to-venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/path-to-venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
File "/path-to-venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/path-to-venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/path-to-venv/local/lib/python2.7/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/path-to-venv/local/lib/python2.7/site-packages/autofixture/__init__.py", line 5, in <module>
from autofixture.base import AutoFixture
File "/path-to-venv/local/lib/python2.7/site-packages/autofixture/base.py", line 7, in <module>
from django.contrib.contenttypes.generic import GenericRelation
ImportError: No module named generic
我做错了什么?
答案 0 :(得分:2)
导入错误,正确导入来自
django.contrib.contenttypes.fields import GenericRelation
但这似乎实际上来自django自动装置,而不是来自你自己的代码。好消息是你不需要自动装置进行这种简单的测试。再说再见吧。
答案 1 :(得分:1)
您安装的django-autofixture版本不支持Django 1.9,因为它有GenericRelation
的过时导入。
尝试升级到最新版本。该项目的changelist表示在版本0.11.0中添加了Django 1.9支持。
为了让Django在您的AnimalTestCase
中运行您的方法,您需要将其重命名为以test_
开头:
class AnimalTestCase(TestCase):
def test_say_hello(self):
print('Hello, World!')