【发布时间】:2011-06-15 05:35:39
【问题描述】:
我正在尝试为一些 Django json_view 视图编写一些单元测试,但我无法将 json_string 传递给视图。我昨天发布了一个有关从 JS 将 json 字符串传递给 Django 视图的相关问题,问题是在我的 JS 中我只是传递了 json 字符串,我需要将字符串作为对象的属性传递,因为我未能做到这一点,字符串被视为结果查询字典的键。我又遇到了类似的问题,只是这次它是对 Django View 的 Django 单元测试。这是我的代码的简化版本,它产生相同的结果。
class MyTestCase(TestCase):
def setUp(self):
self.u = User.objects.create_user('test','test','test')
self.u.is_active = True
self.u.save()
self.client.login(username='test',password='test')
def test_create_object_from_form(self):
"""Test the creation of the Instance from the form data."""
import json
json_string json.dumps({'resource':{'type':'book','author':'John Doe'}})
print(json_string)
response = self.client.post(reverse('ajax_view'),
{'form':json_string},'json')
self.assetNotContains(response,'error')
视图看起来像这样
@json_view
def ajax_view(request):
"""Process the incoming form data."""
if request.method == 'POST':
print(request.POST)
form_data = json.loads(request.POST['form'])
resource_data = form_data['resource']
form = MyUserForm(resource_data)
if form.is_valid():
...
这是运行测试时两个打印语句产生的结果。 json_string 是
{"resource": {"type": "book", "author": "John Doe"}}
查询字典看起来像
<QueryDict: {u'{\'form\': \'{"resource": {"type": "book", "author": "John Doe"}}\'}': [u'']}>
我完全是 JS 和 ajax 的新手,所以不要担心伤害我的自尊心,答案可能很接近它可能会跳起来咬我。
【问题讨论】:
标签: python json ajax django unit-testing