Skip to content

Commit c84f25c

Browse files
committed
Merge pull request #123 from asottile/improve_exceptions_py3
Improve the formatting of CompileErrors in py3
2 parents ae0f92e + 5155854 commit c84f25c

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

sass.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import sys
2323
import warnings
2424

25-
from six import string_types, text_type
25+
from six import string_types, text_type, PY2, PY3
2626

2727
from _sass import OUTPUT_STYLES, compile_filename, compile_string
2828

@@ -48,10 +48,20 @@
4848
MODES = set(['string', 'filename', 'dirname'])
4949

5050

51+
def to_native_s(s):
52+
if isinstance(s, bytes) and PY3: # pragma: no cover (py3)
53+
s = s.decode('UTF-8')
54+
elif isinstance(s, text_type) and PY2: # pragma: no cover (py2)
55+
s = s.encode('UTF-8')
56+
return s
57+
58+
5159
class CompileError(ValueError):
5260
"""The exception type that is raised by :func:`compile()`.
5361
It is a subtype of :exc:`exceptions.ValueError`.
5462
"""
63+
def __init__(self, msg):
64+
super(CompileError, self).__init__(to_native_s(msg))
5565

5666

5767
def mkdirp(path):

sasstests.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import subprocess
1414
import sys
1515
import tempfile
16+
import traceback
1617
import unittest
1718
import warnings
1819

@@ -914,7 +915,7 @@ def test_error(self):
914915
assert False, 'Expected to raise'
915916
except sass.CompileError as e:
916917
msg, = e.args
917-
assert msg.decode('UTF-8').startswith(
918+
assert msg.startswith(
918919
'Error: Invalid CSS after '
919920
), msg
920921
return
@@ -1182,7 +1183,7 @@ def assert_raises_compile_error(expected):
11821183
with pytest.raises(sass.CompileError) as excinfo:
11831184
yield
11841185
msg, = excinfo.value.args
1185-
assert msg.decode('UTF-8') == expected, (msg, expected)
1186+
assert msg == expected, (msg, expected)
11861187

11871188

11881189
class RegexMatcher(object):
@@ -1417,3 +1418,17 @@ def test_map_with_map_key(self):
14171418
),
14181419
'a{content:baz}\n',
14191420
)
1421+
1422+
1423+
def test_stack_trace_formatting():
1424+
try:
1425+
sass.compile(string=u'a{☃')
1426+
assert False, 'expected to raise CompileError'
1427+
except sass.CompileError:
1428+
tb = traceback.format_exc()
1429+
assert tb.endswith(
1430+
'CompileError: Error: Invalid CSS after "a{☃": expected "{", was ""\n'
1431+
' on line 1 of stdin\n'
1432+
'>> a{☃\n'
1433+
' --^\n\n'
1434+
)

0 commit comments

Comments
 (0)