55import subprocess
66import re
77import warnings
8+ import io
89if not hasattr (unittest , 'skip' ):
910 import unittest2 as unittest
1011from textwrap import dedent
@@ -172,10 +173,17 @@ def compare(self, output, expected, ignore_imports=True):
172173
173174 If ignore_imports is True, passes the code blocks into the
174175 strip_future_imports method.
176+
177+ If one code block is a unicode string and the other a
178+ byte-string, it assumes the byte-string is encoded as utf-8.
175179 """
176180 if ignore_imports :
177181 output = self .strip_future_imports (output )
178182 expected = self .strip_future_imports (expected )
183+ if isinstance (output , bytes ) and not isinstance (expected , bytes ):
184+ output = output .decode ('utf-8' )
185+ if isinstance (expected , bytes ) and not isinstance (output , bytes ):
186+ expected = expected .decode ('utf-8' )
179187 self .assertEqual (order_future_lines (output .rstrip ()),
180188 expected .rstrip ())
181189
@@ -236,7 +244,7 @@ def convert_check(self, before, expected, stages=(1, 2), all_imports=False,
236244 headers = ''
237245
238246 self .compare (output , reformat_code (headers + expected ),
239- ignore_imports = ignore_imports )
247+ ignore_imports = ignore_imports )
240248
241249 def unchanged (self , code , ** kwargs ):
242250 """
@@ -250,11 +258,14 @@ def _write_test_script(self, code, filename='mytestscript.py'):
250258 Dedents the given code (a multiline string) and writes it out to
251259 a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py.
252260 """
253- with open (self .tempdir + filename , 'w' ) as f :
261+ if isinstance (code , bytes ):
262+ code = code .decode ('utf-8' )
263+ # Be explicit about encoding the temp file as UTF-8 (issue #63):
264+ with io .open (self .tempdir + filename , 'wt' , encoding = 'utf-8' ) as f :
254265 f .write (dedent (code ))
255266
256267 def _read_test_script (self , filename = 'mytestscript.py' ):
257- with open (self .tempdir + filename ) as f :
268+ with io . open (self .tempdir + filename , 'rt' , encoding = 'utf-8' ) as f :
258269 newsource = f .read ()
259270 return newsource
260271
0 commit comments