TypeError: unicode argument expected, got 'str'

简介:

今天在做mock模块中的patch()方法只在运行测试的上下文中才替换对象时,使用了io.StringIO结果出现报错:

wKioL1i347HC-pKgAABSS5Hc9jM703.png


经确认是字符集的问题,考虑使用io.BytesIO解决了此问题


具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- 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的字符转换问题,需要多加注意。



本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1902730,如需转载请自行联系原作者

相关文章
成功解决TypeError: ‘encoding’ is an invalid keyword argument for this function
成功解决TypeError: ‘encoding’ is an invalid keyword argument for this function
|
9月前
|
数据安全/隐私保护 Python
TypeError: a bytes-like object is required, not ‘str‘,如何解决?
TypeError: a bytes-like object is required, not ‘str‘,如何解决?
72 0
成功解决ValueError: ‘usecols‘ must either be list-like of all strings, all unicode, all integers or a ca
成功解决ValueError: ‘usecols‘ must either be list-like of all strings, all unicode, all integers or a ca
TypeError: custom() got an unexpected keyword argument ‘path‘
TypeError: custom() got an unexpected keyword argument ‘path‘
114 0
|
计算机视觉
成功解决TypeError: __init__() got an unexpected keyword argument 'n_iterations'
成功解决TypeError: __init__() got an unexpected keyword argument 'n_iterations'
Python报错:TypeError: a bytes-like object is required, not ‘str‘
Python报错:TypeError: a bytes-like object is required, not ‘str‘
Python报错:TypeError: a bytes-like object is required, not ‘str‘
Python typeError: a bytes-like object is required, not ‘str’ Solution
Python typeError: a bytes-like object is required, not ‘str’ Solution
python TypeError: missing 1 required positional argument:'self'
python TypeError: missing 1 required positional argument:'self'
python TypeError: missing 1 required positional argument:'self'
TypeError: 'encoding' is an invalid keyword argument for this function
TypeError: 'encoding' is an invalid keyword argument for this function
230 0
|
Python
SyntaxError: Missing parentheses in call to 'print'
SyntaxError: Missing parentheses in call to 'print'
111 0