Example #1
0
 def test_json2str(self):
     # json to str 测试,要求保持 list 顺序,中文兼容,双引号括起字符串(字符串里面的双引号前面有斜杠转移)
     value = {
         'a': [1, 2, '呵xx呵', u'哈"哈',
               str_util.to_str('智汇云', encode='GBK')]
     }
     json_value = '{"a": [1, 2, "\\u5475xx\\u5475", "\\u54c8\\"\\u54c8", "\\u667a\\u6c47\\u4e91"]}'
     assert str_util.json2str(value) == json_value
     assert str_util.to_json(json_value) == str_util.deep_str(value)
     # 加入时间测试
     value2 = {
         'a': [
             1, 2, '呵xx呵', u'哈"哈',
             str_util.to_str('智汇云', encode='GBK'),
             time.strptime('2014/03/25 19:05:33', '%Y/%m/%d %H:%M:%S')
         ],
         u'eff_time':
         datetime.datetime(2015, 6, 28, 14, 19, 41),
     }
     value3 = {
         'a': [
             1, 2, '呵xx呵', u'哈"哈',
             str_util.to_str('智汇云', encode='GBK'), "2014-03-25 19:05:33"
         ],
         u'eff_time':
         "2015-06-28 14:19:41"
     }
     json_value2 = '{"a": [1, 2, "\\u5475xx\\u5475", "\\u54c8\\"\\u54c8", "\\u667a\\u6c47\\u4e91", "2014-03-25 19:05:33"], "eff_time": "2015-06-28 14:19:41"}'
     assert str_util.json2str(value2) == json_value2
     assert str_util.to_json(json_value2) == str_util.deep_str(value3)
     # eval 能将非标准json的内容转换过来
     json_value = u"{'a': [1, 2, '\\u5475xx\\u5475', '\\xE5\\x8C\\x85']}"
     assert str_util.to_json(json_value) == eval(json_value)
Example #2
0
    def test_toString(self):
        # 处理 utf-8 编码
        a = "哈哈"
        assert isinstance(str_util.to_unicode(a), unicode)
        str_util.to_str(a).decode("utf-8")  # 可正常运行即可
        assert isinstance(str_util.to_str(a), str)

        # 处理 unicode 编码
        a = u"哈哈"
        assert isinstance(str_util.to_unicode(a), unicode)
        str_util.to_str(a).decode("utf-8")  # 可正常运行即可
        assert isinstance(str_util.to_str(a), str)

        # 编码转成人能阅读的
        b = "eval 处理是为了让“\u65f6”,“\xE5\x8C\x85”等字符转为人可以阅读的文字"
        assert b != "eval 处理是为了让“时”,“包”等字符转为人可以阅读的文字"
        assert str_util.to_unicode(
            b, to_read=True) == u"eval 处理是为了让“时”,“包”等字符转为人可以阅读的文字"
        assert str_util.to_str(
            b, to_read=True) == "eval 处理是为了让“时”,“包”等字符转为人可以阅读的文字"

        # 截取最大长度
        d = "eval 处理是为了让“时”,“包”等字符转为人可以阅读的文字"
        assert str_util.to_unicode(b, max=10) == u"eval 处理是为了..."
        assert str_util.to_str(b, max='10') == "eval 处理是为了..."
Example #3
0
 def test_zlib(self):
     value = {'a': [1, 2, '呵xx呵', u'哈"哈', str_util.to_str('智汇云', encode='GBK')]}
     json_value = '{"a": [1, 2, "\\u5475xx\\u5475", "\\u54c8\\"\\u54c8", "\\u667a\\u6c47\\u4e91"]}'
     zlib_value = str_util.zlib_encode(value)
     value2 = str_util.zlib_decode(zlib_value)
     assert value2 == json_value  # 压缩之后会将 dict 转码成字符串
     assert len(zlib_value) < len(value2)