33import random
44import re
55import sys
6- import tokenize
6+ from tokenize import tokenize , COMMENT , STRING
7+ from io import BytesIO
78
89import six
910# the run library should overwrite this with a particular random seed for the test.
@@ -238,11 +239,7 @@ def _tokens(code):
238239 A wrapper around tokenize.generate_tokens.
239240 """
240241 # Protect against pathological inputs: http://bugs.python.org/issue16152
241- code = code .rstrip () + "\n "
242- if isinstance (code , str ):
243- code = code .encode ('utf8' )
244- code = "# coding: utf8\n " + code
245- toks = tokenize .generate_tokens (six .BytesIO (code ).readline )
242+ toks = tokenize (BytesIO (code .encode ('utf-8' )).readline )
246243 return toks
247244
248245def _count_tokens (code , string ):
@@ -253,7 +250,7 @@ def _count_tokens(code, string):
253250
254251 try :
255252 for ttyp , ttok , __ , __ , __ in _tokens (code ):
256- if ttyp in (tokenize . COMMENT , tokenize . STRING ):
253+ if ttyp in (COMMENT , STRING ):
257254 continue
258255 if ttok == string :
259256 count += 1
@@ -353,7 +350,7 @@ def count_non_comment_lines(at_least=None, at_most=None, exactly=None, error_msg
353350 def check (code ):
354351 linenums = set ()
355352 for ttyp , ttok , (srow , __ ), __ , __ in _tokens (code ):
356- if ttyp in (tokenize . COMMENT , tokenize . STRING ):
353+ if ttyp in (COMMENT , STRING ):
357354 # Comments and strings don't count toward line count. If a string
358355 # is the only thing on a line, then it's probably a docstring, so
359356 # don't count it.
@@ -530,7 +527,7 @@ def invoke_student_function(fn_name, args, environment=None, output_writer=None)
530527 """
531528 output_writer = output_writer or repr
532529 def doit (submission_module ):
533- for name , value in environment or {}.items ():
530+ for name , value in ( environment or {}) .items ():
534531 setattr (submission_module , name , value )
535532 fn = getattr (submission_module , fn_name )
536533 print (output_writer (fn (* args )))
0 commit comments