【问题标题】:Trouble using django.template Context in unittest在单元测试中使用 django.template 上下文时遇到问题
【发布时间】: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


【解决方案1】:

好的,我找到了解决方案:

from decimal import *

是“坏人”这个库也有一个 Context 对象。 感谢大家阅读!

【讨论】:

  • 干杯:)!很高兴看到它为您节省了一些时间和精力。
猜你喜欢
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
相关资源
最近更新 更多