Ejemplo n.º 1
0
def run_script(path):
  if "benchmark" in path: return

  global passed
  global failed
  global num_skipped

  if (splitext(path)[1] != '.lox'):
    return

  # Check if we are just running a subset of the tests.
  if filter_path:
    this_test = relpath(path, join(REPO_DIR, 'test'))
    if not this_test.startswith(filter_path):
      return

  # Make a nice short path relative to the working directory.

  # Normalize it to use "/" since, among other things, the interpreters expect
  # the argument to use that.
  path = relpath(path).replace("\\", "/")

  # Update the status line.
  term.print_line('Passed: {} Failed: {} Skipped: {} {}'.format(
      term.green(passed),
      term.red(failed),
      term.yellow(num_skipped),
      term.gray('({})'.format(path))))

  # Read the test and parse out the expectations.
  test = Test(path)

  if not test.parse():
    # It's a skipped or non-test file.
    return

  test.run()

  # Display the results.
  if len(test.failures) == 0:
    passed += 1
  else:
    failed += 1
    term.print_line(term.red('FAIL') + ': ' + path)
    print('')
    for failure in test.failures:
      print('      ' + term.pink(failure))
    print('')
Ejemplo n.º 2
0
def run_suite():
    global passed
    global failed
    global num_skipped
    global expectations

    passed = 0
    failed = 0
    num_skipped = 0
    expectations = 0

    start_time = time.time()
    walk(join(REPO_DIR, 'clox', 'test', 'lox'), run_script)
    time_passed = time.time() - start_time

    term.print_line()
    
    print()

    if failed == 0:
        print('All {} tests passed ({} expectations) in {:.2f} seconds.'.format(
            term.green(passed), str(expectations), time_passed))
    else:
        print('{} tests passed and {} tests failed in {:.2f} seconds.'.format(
            term.green(passed), term.red(failed), time_passed))

    return failed == 0
Ejemplo n.º 3
0
def run_suite(name):
    global interpreter
    global passed
    global failed
    global num_skipped
    global expectations

    interpreter = INTERPRETERS[name]

    passed = 0
    failed = 0
    num_skipped = 0
    expectations = 0

    walk(join(REPO_DIR, 'test'), run_script)
    term.print_line()

    if failed == 0:
        print('All {} tests passed ({} expectations).'.format(
            term.green(passed), str(expectations)))
    else:
        print('{} tests passed. {} tests failed.'.format(
            term.green(passed), term.red(failed)))

    return failed == 0
Ejemplo n.º 4
0
    def _get_attrib(self, attr, convert_to_str=False):
        """
        Given an attribute name, looks it up on the entry. Names that
        start with ``tags.`` are looked up in the ``tags`` dictionary.

        :param attr: Name of attribute to look up.
        :type attr: ``str``
        :param convert_to_str: Convert result to a string.
        :type convert_to_str: ``bool``

        :rtype: ``object``
        """
        if attr.startswith('tags.'):
            tag = attr[len('tags.'):]
            if tag in self.tags and self.tags[tag] != '':
                return self.tags[tag]
            elif convert_to_str is True:
                return '<not set>'
            else:
                return self.tags.get(tag)
        elif not hasattr(self, attr):
            raise AttributeError('Invalid attribute: {0}. Perhaps you meant '
                                 '{1}?'.format(red(attr),
                                               green('tags.' + attr)))
        else:
            result = getattr(self, attr)
            if convert_to_str is True and not result:
                return '<none>'
            elif convert_to_str is True and isinstance(result, list):
                return ', '.join(result)
            elif convert_to_str is True:
                return str(result)
            else:
                return result
Ejemplo n.º 5
0
 def render(self) -> str:
     guess = self.guess if self.is_filled() else ' '
     assert guess is not None
     if self.status is Status.PENCILLED_IN:
         guess = term.dim(guess)
     elif self.status is Status.MARKED_WRONG:
         guess = term.red(guess)
     elif self.status is Status.MARKED_RIGHT:
         guess = term.green(guess)
     elif self.status is Status.REVEALED:
         guess = term.blue(guess)
     return f' {guess} '
Ejemplo n.º 6
0
def print_exc(etype, value, tb):
    """Exception handler based on the code in O'Reilly's Python cookbook.
    This function receives the same arguments with traceback.print_exc: i.e.,
    exception type ETYA, exception value VALUE, and traceback object TB."""
    if issubclass(etype, SyntaxError):
        sys.__excepthook__(etype, value, tb)
    elif issubclass(etype, BrokenPipeError):
        sys.__excepthook__(etype, value, tb)
    else:
        # dump all frames
        while True:
            print_tb(tb)
            tb = tb.tb_next
            if not tb:
                break

        # display info on exception
        lines = traceback.format_exception_only(etype, value)
        for line in lines:
            _print(term.red(line))

        # invoke debugger if possible
        if sys.stderr.isatty() and sys.stdin.isatty():
            pdb.pm()
  for snippet_name in snippets:
    snippet = source_code.snippet_tags[chapter][snippet_name]
    split_chapters.split_chapter(chapter, snippet)

    build_name = "{}-{:02}-{}".format(chapter_dir, snippet.index, snippet_name)
    snippet_dir = "{:02}-{}".format(snippet.index, snippet_name)
    source_dir = os.path.join("gen", "snippets", chapter_dir, snippet_dir)

    args = [
      "make",
      "-f", "util/c.make",
      "NAME=" + build_name,
      "MODE=release",
      "SOURCE_DIR=" + source_dir,
      "SNIPPET=true"
    ]
    proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()

    if proc.returncode != 0:
      print("{} {} / {}".format(term.red("FAIL"), chapter, snippet_name))
      print(out.decode('utf-8'))
      print(err.decode('utf-8'))
      print()
      all_passed = False
    else:
      print("{} {} / {}".format(term.green("PASS"), chapter, snippet_name))

if not all_passed:
  sys.exit(1)
Ejemplo n.º 8
0
def print_tb(tb, nlines=5, ncols=80):
    """Pretty print the traceback TB.  NLINES of Python source lines are
    displayed.  All output lines are fitted within NCOLS column."""
    f = tb.tb_frame
    lineno = tb.tb_lineno
    co = f.f_code
    filename = co.co_filename
    name = co.co_name

    # display frame header
    name_str = term.blue(name, True)
    filename_str = term.green(filename)
    _print('----', name_str, filename_str)

    # display source lines
    linecache.checkcache(filename)
    errline = ''
    for n in range(lineno - nlines + 1, lineno + 1):
        line = linecache.getline(filename, n, f.f_globals).rstrip()
        if line is not None:
            lineno_str = term.gray('{:5} '.format(n))
            _print(lineno_str, end='')
            if n == lineno:
                line_str = term.red(line)
                errline = line
            else:
                line_str = term.reset(line)
            _print(line_str)

    def _by_location(key):
        pos = errline.find(key)
        if 0 <= pos <= 255:
            # keys matching the error line come first
            return chr(pos)
        elif key.startswith('__'):
            # keys starting with __ come last
            return '~' + key
        else:
            # sorted in the alphabetical order
            return key

    # dump all local variables in the frame
    keys = sorted(f.f_locals.keys(), key=_by_location)
    for key in keys:
        key_str = term.yellow('{:>20}'.format(key))
        if key in set([
                'linecache', 'pdb', 'sys', 'os', 're', 'term', 'traceback',
                '__builtins__'
        ]):
            _print(key_str, '= ...')
            continue
        else:
            val_str = trimmed_str(repr(f.f_locals[key]), ncols - 20)
            _print(key_str, '=', val_str)

        # dump all attributes for objects
        attr = getattr(f.f_locals[key], '__dict__', None)
        if attr:
            keys = sorted(attr.keys(), key=_by_location)
            for key in keys:
                key_str = term.cyan('{:>28}'.format(key))
                val_str = trimmed_str(repr(attr[key]), ncols - 28)
                _print(key_str, val_str)