From b02f506cc3f6360c25881819996dbacc93702aea Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Tue, 11 Nov 2014 18:38:10 +0100 Subject: Fix and test the "lex(class)" and "format(class)" handlers. --- pygments/__init__.py | 9 +++++---- tests/test_basic_api.py | 19 ++++++++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/pygments/__init__.py b/pygments/__init__.py index 8170d5f0..dc377369 100644 --- a/pygments/__init__.py +++ b/pygments/__init__.py @@ -45,7 +45,8 @@ def lex(code, lexer): return lexer.get_tokens(code) except TypeError as err: if isinstance(err.args[0], str) and \ - 'unbound method get_tokens' in err.args[0]: + ('unbound method get_tokens' in err.args[0] or + 'missing 1 required positional argument' in err.args[0]): raise TypeError('lex() argument must be a lexer instance, ' 'not a class') raise @@ -61,15 +62,15 @@ def format(tokens, formatter, outfile=None): """ try: if not outfile: - #print formatter, 'using', formatter.encoding - realoutfile = formatter.encoding and BytesIO() or StringIO() + realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO() formatter.format(tokens, realoutfile) return realoutfile.getvalue() else: formatter.format(tokens, outfile) except TypeError as err: if isinstance(err.args[0], str) and \ - 'unbound method format' in err.args[0]: + ('unbound method format' in err.args[0] or + 'missing 1 required positional argument' in err.args[0]): raise TypeError('format() argument must be a formatter instance, ' 'not a class') raise diff --git a/tests/test_basic_api.py b/tests/test_basic_api.py index 7485df1a..84dd49bb 100644 --- a/tests/test_basic_api.py +++ b/tests/test_basic_api.py @@ -12,7 +12,7 @@ from __future__ import print_function import random import unittest -from pygments import lexers, formatters, filters, format +from pygments import lexers, formatters, lex, format from pygments.token import _TokenType, Text from pygments.lexer import RegexLexer from pygments.formatters.img import FontNotFound @@ -254,6 +254,23 @@ def test_styles(): HtmlFormatter(style="pastie") +def test_bare_class_handler(): + from pygments.formatters import HtmlFormatter + from pygments.lexers import PythonLexer + try: + lex('test\n', PythonLexer) + except TypeError as e: + assert 'lex() argument must be a lexer instance' in str(e) + else: + assert False, 'nothing raised' + try: + format([], HtmlFormatter) + except TypeError as e: + assert 'format() argument must be a formatter instance' in str(e) + else: + assert False, 'nothing raised' + + class FiltersTest(unittest.TestCase): def test_basic(self): -- cgit v1.2.1