2012-04-05 25 views
4

當我使用django.template的上下文時,我在這裏遇到了一些令人困惑的情況。在單元測試中使用django.template上下文時遇到的問題

在Python程序中運行以下工作:

>>> from django.template import Context, Template 
>>> b=Template('TEST').render(Context()) 
>>> print b 
TEST 

當我使用同樣的代碼在單元測試時,我得到follwing錯誤:

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中,但不是在單元測試?我欣賞每一個提示。

+0

第一個例子運行在什麼樣的shell中?這需要設置才能工作(DJANGO_SETTINGS_MODULE),所以也許這就是你在單元測試中缺少的。 – 2012-04-05 16:07:50

+0

我在我的項目裏面使用這個命令dir爲shell: python2.7 manage.py shell – Jingo 2012-04-05 16:10:40

+0

和單元測試?你需要運行在相同的上下文 – 2012-04-05 16:14:16

回答

7

OK,我得到了解決辦法:

from decimal import * 

是 「壞」 這個LIB有一個上下文對象了。 謝謝任何​​人閱讀!

+1

保存我的時間,男人 – 2012-07-18 19:07:47

+0

乾杯:)!很高興看到它爲你節省了一些時間和精力。 – Jingo 2012-07-19 17:22:41