TypeError: unicode argument expected, got 'str'

今天在作mock模塊中的patch()方法只在運行測試的上下文中才替換對象時,使用了io.StringIO結果出現報錯:python

wKioL1i347HC-pKgAABSS5Hc9jM703.png


經確認是字符集的問題,考慮使用io.BytesIO解決了此問題dom


具體代碼以下:python2.7

# -*- coding:utf-8 -*-

#
# from io import StringIO
from io import BytesIO
from unittest import TestCase
from mock import patch
import url

class TestUrlPrint(TestCase):
    def test_url_gets_to_stdout(self):
        protocol = 'http'
        host = 'www'
        domain = 'example.com'
        expected_url = '{}://{}.{}\n'.format(protocol, host, domain)

        with patch('sys.stdout', new=BytesIO()) as fake_out:
            url.urlprint(protocol, host, domain)
            self.assertEqual(fake_out.getvalue(), expected_url)


python2.7的字符轉換問題,須要多加註意。ide

相關文章
相關標籤/搜索