Werkzeug测试客户端和utf-8

时间:2014-02-05 17:37:22

标签: flask werkzeug python-unicode

这是代码。当我发送两个字段时,它会失败。

import unittest

class UnicodeTestCase(unittest.TestCase):
    def test_unicode(self):
        from cStringIO import StringIO
        from flask import Flask, request

        app = Flask(__name__)
        app.config['TESTING'] = True

        @app.route('/', methods=["POST"])
        def test_view():
            print request.values, request.files
            return "OK"

        file = (StringIO("0" * 1000), "filename.txt")
        string = u"∆_∆"

        client = app.test_client(use_cookies=False)
        self.assertEquals(200, client.post('/', data={'file': file}).status_code)
        self.assertEquals(200, client.post('/', data={'string': string}).status_code)
        self.assertEquals(200, client.post('/', data={'file': file, 'string': string}).status_code)

在最后一个断言中,它失败了:

Error
Traceback (most recent call last):
  File "/Users/user1/tests/test_uni.py", line 108, in test_unicode
    self.assertEquals(200, client.post('/', data={'file': file, 'string': string}).status_code)
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 771, in post
    return self.open(*args, **kw)
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/flask/testing.py", line 108, in open
    follow_redirects=follow_redirects)
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 725, in open
    environ = args[0].get_environ()
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 535, in get_environ
    stream_encode_multipart(values, charset=self.charset)
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 104, in stream_encode_multipart
    write('\r\n\r\n' + value)
  File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 71, in write
    write_binary(string.encode(charset))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4: ordinal not in range(128)

当我使用Postman(Google Chrome扩展程序)发送这两个字段时,它可以正常工作。

是否可以,我应该使用带有base64或其他东西的unicode包装字段吗?或者它是werkzeug测试客户端中的错误?

1 个答案:

答案 0 :(得分:0)

看起来像测试客户端错误,当直接请求工作正常时,我已经有了测试客户端的另一个错误,但是测试客户端有意想不到的结果。

对于我https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/test.py#L71,我string类型为str。对于字符串,仅此方法未被调用,仅对于文件,此方法不会使用您的字符串调用。您可以尝试使用next for python 2临时更新此方法:

def write(string):
    if isinstance(string, str):
        write_binary(string)
    else:
        write_binary(string.encode(charset))

我为您的示例创建了错误:https://github.com/mitsuhiko/flask/issues/973