【发布时间】:2016-06-12 10:12:25
【问题描述】:
我需要测试我的 Django 模型的表示是否与 Unicode 一起使用,因为用户可能会在其中插入 ü 或 ¼ 之类的字符。为此,我有这个 Django tests.py
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import timezone
from .models import *
from .views import *
class CategoryTestCase(TestCase):
""" Test to check whether category name is printed correctly.
If there is a parent, it should be also printed seperated by a : """
def setUp(self):
self.cat1 = Category.objects.create(name=u'Category 1')
self.cat2 = Category.objects.create(name=u'Category ü', parent=self.cat1)
self.cat3 = Category.objects.create(name=u'Category 3', parent=self.cat2)
def test_category_name(self):
cat_result1 = u'Category 1'
cat_result2 = u'Category 1' + settings.PARENT_DELIMITER + u'Category ü'
cat_result3 = u'Category 1' + settings.PARENT_DELIMITER + u'Category ü' + settings.PARENT_DELIMITER + u'Category 3'
self.assertEqual(self.cat1.__str__(), cat_result1)
self.assertEqual(self.cat2.__str__(), cat_result2)
self.assertEqual(self.cat3.__str__(), cat_result3)
这是为了测试这个小模型:
#...
from django.utils.encoding import python_2_unicode_compatible
#....
@python_2_unicode_compatible
class Category(models.Model):
""" Representing a category a part might contains to.
E.g. resistor """
name = models.CharField(
max_length=50,
help_text=_("Name of the category.")
)
parent = models.ForeignKey(
"self",
null=True,
blank=True,
help_text=_("If having a subcateogry, the parent.")
)
description = models.TextField(
_("Description"),
blank=True,
null=True,
help_text=_("A chance to summarize usage of category.")
)
def __str__(self):
if self.parent is None:
return ('{}'.format(self.name))
else:
return ('%s%s%s' % (
self.parent.__str__(),
settings.PARENT_DELIMITER,
self.name)
)
def get_parents(self):
""" Returns a list with parants of that StoragePare incl itself"""
result = []
next = self
while True:
if next.id in result:
raise(CircleDetectedException(
_('There seems to be a circle inside ancestors of %s.' % self.id)))
else:
result.append(next.id)
if next.parent is not None:
next = next.parent
else:
break
return result
def clean(self):
pass
(剥去一点)
当通过 Python 3 运行此代码并进行测试或将 Python2/3 作为应用程序执行时,它正在工作。只有 Python2 的测试失败了,所以我认为我的想法有问题如何测试它。根据错误消息,似乎 Unicode 字符串在某处未正确编码和解码。
======================================================================
FAIL: test_category_name (partsmanagement.tests.CategoryTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/frlan/quellen/partuniverse/partuniverse/partsmanagement/tests.py", line 31, in test_category_name
self.assertEqual(self.cat2.__str__(), cat_result2)
AssertionError: 'Category 1->Category \xc3\xbc' != u'Category 1->Category \xfc'
所以我的问题是:如何使用 Django 进行正确的 Unicode 表示测试。
【问题讨论】:
-
装饰器假装在模型端这样做。事实上,它似乎在应用程序运行时工作。但是在使用 Python 2 的测试中并检查 __str__() 并没有像 __unicode__() 一样正常工作。
-
'Category 1->Category \xc3\xbc'是一个 utf-8 编码的 python 2 字符串。为什么不到处使用 unicode 对象呢?我在之前的评论中链接到的文档中对此进行了解释。如果你想编写同时适用于 python 2 和 3 的代码,你应该阅读整个页面。 -
可能是一个转储,但尝试应用文档迫使我在 Python 2 上创建具有相同内容的 __str__() 和 __unicode__(),即使文档说只是创建 __unciode__()。与上述相同的错误。当我想测试真正的 UTF 时,使用 Bytestring 编码的 UTF 也感觉不对。
-
只要将 utf-8 编码的字符串与真正的 unicode 进行比较,您的测试就不会通过。你可以解码。
'\xc3\xbc'.decode('utf-8') == u'\xfc'
标签: python django testing unicode