【发布时间】:2012-04-19 09:22:07
【问题描述】:
当我使用 django.template 中的 Context 时,我遇到了一些令人困惑的情况。
以下在 python shell 中工作:
>>> from django.template import Context, Template
>>> b=Template('TEST').render(Context())
>>> print b
TEST
当我在单元测试中使用相同的代码时,我得到以下错误:
Traceback (most recent call last):
File "/newsletterapi/tests.py", line 25, in setUp
b = Template('TEST').render(Context())
File "/opt/python2.7/lib/python2.7/site-packages/django/template/base.py", line 121, in render
context.render_context.push()
AttributeError: 'Context' object has no attribute 'render_context'
单元测试如下所示:
from django.test import TestCase
from myproject.newsletterapi.models import Newsletter
from django.utils.termcolors import colorize
from django.db import IntegrityError
from django.template import Template, Context
import random
import datetime
from decimal import *
import string
class NewsletterTest(TestCase):
def setUp(self):
b = Template('TEST').render(Context()) # this is line 25
self.newsletter = Newsletter(body=b)
self.newsletter.save()
### ... continues here
有谁知道为什么这在 shell 中有效,但在单元测试中无效?我很感激每一个提示。
【问题讨论】:
-
第一个例子在什么样的shell中运行?这需要设置才能工作(DJANGO_SETTINGS_MODULE),所以也许这就是您在单元测试中缺少的内容。
-
我在我的项目目录中为 shell 使用了这个命令:python2.7 manage.py shell
-
单元测试呢?您需要在相同的上下文中运行它
-
python2.7 manage.py test newsletterapi
标签: python django unit-testing django-1.3