Adding py3k support

This commit is contained in:
Steve Pulec 2013-01-13 19:56:51 -05:00
parent 928aedce5c
commit b383d5e1cd
12 changed files with 457 additions and 30 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
dist/ dist/
steadymark-0.1.4.tar.gz steadymark-0.1.4.tar.gz
*egg-info *egg-info
*.tox
*.pyc *.pyc
build build
steadymark-*.*.*.tar.gz steadymark-*.*.*.tar.gz

View File

@ -27,8 +27,8 @@ it will be used as title for your test.
## unicode.lower transforms string into lowercase ## unicode.lower transforms string into lowercase
```python ```python
from sure import that from sure import expect
assert that(u"Gabriel Falcao".lower()).equals(u"gabriel falcao") assert expect(u"Gabriel Falcao".lower()).equals(u"gabriel falcao")
``` ```
## python can add numbers ## python can add numbers
@ -67,7 +67,7 @@ $ steadymark README.md
# Steadymark is on version 0.4.3 # Steadymark is on version 0.4.3
```python ```python
>>> from sure import this >>> from sure import expect
>>> from steadymark import version >>> from steadymark import version
>>> assert this(version).should.equal("0.4.3") >>> assert expect(version).should.equal("0.4.3")
``` ```

View File

@ -6,5 +6,7 @@ ipdb==0.7
ipython==0.13 ipython==0.13
misaka==1.0.2 misaka==1.0.2
nose==1.1.2 nose==1.1.2
sure==1.0.5 #sure==1.0.5
-e git+git://github.com/spulec/sure.git@py3k#egg=sure
tox==1.4.2
wsgiref==0.1.2 wsgiref==0.1.2

View File

@ -26,6 +26,7 @@
import os import os
from setuptools import setup from setuptools import setup
from steadymark.six import PY3
from steadymark.version import version from steadymark.version import version
@ -38,6 +39,14 @@ def get_packages():
return packages return packages
requirements = [
'misaka==1.0.2',
]
if not PY3:
# Couleur is not py3 compatible.
requirements.append('couleur>=0.4.1')
setup(name='steadymark', setup(name='steadymark',
version=version, version=version,
description=(u'Markdown-based test runner for python. ' description=(u'Markdown-based test runner for python. '
@ -46,10 +55,7 @@ setup(name='steadymark',
author_email='gabriel@nacaolivre.org', author_email='gabriel@nacaolivre.org',
url='http://github.com/gabrielfalcao/steadymark', url='http://github.com/gabrielfalcao/steadymark',
packages=get_packages(), packages=get_packages(),
install_requires=[ install_requires=requirements,
'misaka',
'couleur>=0.4.1',
],
entry_points={ entry_points={
'console_scripts': ['steadymark = steadymark:main'], 'console_scripts': ['steadymark = steadymark:main'],
}, },

View File

@ -23,13 +23,15 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
from optparse import OptionParser from optparse import OptionParser
from steadymark.six import text_type
from steadymark.version import version from steadymark.version import version
try: try:
from steadymark.runner import Runner from steadymark.runner import Runner
except ImportError, e: except ImportError as e:
if 'misaka' in unicode(e): if 'misaka' in text_type(e):
Runner = None Runner = None
else: else:
raise raise

View File

@ -23,6 +23,8 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
import re import re
import sys import sys
@ -39,6 +41,7 @@ from misaka import (
EXT_FENCED_CODE, EXT_FENCED_CODE,
EXT_NO_INTRA_EMPHASIS, EXT_NO_INTRA_EMPHASIS,
) )
from steadymark.six import text_type
class SteadyMarkDoctestRunner(DebugRunner): class SteadyMarkDoctestRunner(DebugRunner):
@ -102,11 +105,11 @@ class MarkdownTest(object):
class SteadyMark(BaseRenderer): class SteadyMark(BaseRenderer):
title_regex = re.compile(ur'(?P<title>[^#]+)(?:[#]+(?P<index>\d+))?') title_regex = re.compile(r'(?P<title>[^#]+)(?:[#]+(?P<index>\d+))?')
def preprocess(self, text): def preprocess(self, text):
self._tests = [{}] self._tests = [{}]
return unicode(text) return text_type(text)
def block_code(self, code, language): def block_code(self, code, language):
if language != 'python': if language != 'python':
@ -135,16 +138,16 @@ class SteadyMark(BaseRenderer):
item = self._tests[-1] item = self._tests[-1]
else: else:
item[u'code'] = unicode(code).strip() item[u'code'] = text_type(code).strip()
if 'title' not in item: if 'title' not in item:
item[u'title'] = u'Test #{0}'.format(len(self._tests)) item[u'title'] = u'Test #{0}'.format(len(self._tests))
self._tests.append({}) self._tests.append({})
def header(self, title, level): def header(self, title, level):
t = unicode(title) t = text_type(title)
t = re.sub(ur'^[# ]*(.*)', '\g<1>', t) t = re.sub(r'^[# ]*(.*)', '\g<1>', t)
t = re.sub(ur'`([^`]*)`', '\033[1;33m\g<1>\033[0m', t) t = re.sub(r'`([^`]*)`', '\033[1;33m\g<1>\033[0m', t)
self._tests.append({ self._tests.append({
u'title': t, u'title': t,
u'level': int(level), u'level': int(level),
@ -156,8 +159,8 @@ class SteadyMark(BaseRenderer):
globs = globals() globs = globals()
locs = locals() locs = locals()
for test in filter(lambda x: 'code' in x, self._tests): for test in filter(lambda x: 'code' in x, self._tests):
raw_code = str(test['code'].encode('utf-8')) raw_code = test['code']
title = str(test['title'].encode('utf-8')) title = test['title']
tests.append(MarkdownTest(title, raw_code, globs=globs, locs=locs)) tests.append(MarkdownTest(title, raw_code, globs=globs, locs=locs))
self.tests = tests self.tests = tests

View File

@ -23,6 +23,8 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
import os import os
import sys import sys
import traceback import traceback
@ -37,17 +39,22 @@ from steadymark.core import (
SteadyMark, SteadyMark,
DocTestFailure, DocTestFailure,
) )
from steadymark.six import text_type, PY3
if not PY3:
# We do this so that redirecting to pipes will work
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
class Runner(object): class Runner(object):
def __init__(self, filename=None, text=u''): def __init__(self, filename=None, text=u''):
if filename and not os.path.exists(filename): if filename and not os.path.exists(filename):
print 'steadymark could not find {0}'.format(filename) print('steadymark could not find {0}'.format(filename))
sys.exit(1) sys.exit(1)
if filename: if filename:
raw_md = codecs.open(filename, 'rb', 'utf-8').read() raw_md = codecs.open(filename, 'rb', 'utf-8').read()
text = unicode(raw_md) text = text_type(raw_md)
self.steadymark = SteadyMark.inspect(text) self.steadymark = SteadyMark.inspect(text)
self.filename = filename self.filename = filename
@ -59,8 +66,8 @@ class Runner(object):
False: u'', False: u'',
} }
for line in text.splitlines(): for line in text.splitlines():
print "{1}{2}{0}\033[0m".format( print("{1}{2}{0}\033[0m".format(
line, ' ' * indentation, white[SUPPORTS_ANSI]) line, ' ' * indentation, white[SUPPORTS_ANSI]))
def __getattr__(self, attr): def __getattr__(self, attr):
if attr not in ( if attr not in (
@ -86,8 +93,8 @@ class Runner(object):
def printer(text, indentation=0): def printer(text, indentation=0):
for line in text.splitlines(): for line in text.splitlines():
print "{1}{2}{0}{3}".format( print("{1}{2}{0}{3}".format(
line, ' ' * indentation, color, no_color) line, ' ' * indentation, color, no_color))
return printer return printer
@ -109,7 +116,7 @@ class Runner(object):
u'In the test "{0}"'.format(test.title), u'In the test "{0}"'.format(test.title),
) )
formatted_tb = formatted_tb.replace( formatted_tb = formatted_tb.replace(
u'@STEADYMARK@', unicode(test.title)) u'@STEADYMARK@', text_type(test.title))
if SUPPORTS_ANSI: if SUPPORTS_ANSI:
color = '\033[1;36m' color = '\033[1;36m'
@ -168,13 +175,13 @@ class Runner(object):
def run(self): def run(self):
if self.filename: if self.filename:
print "Running tests from {0}".format(self.filename) print("Running tests from {0}".format(self.filename))
exit_status = 0 exit_status = 0
for test in self.steadymark.tests: for test in self.steadymark.tests:
title = "{0} ".format(test.title) title = "{0} ".format(test.title)
title_length = len(title) title_length = len(title)
print "." * title_length print("." * title_length)
sys.stdout.write(title) sys.stdout.write(title)
result, failure, before, after = test.run() result, failure, before, after = test.run()
if failure: if failure:

390
steadymark/six.py Normal file
View File

@ -0,0 +1,390 @@
"""Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2012 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.2.0"
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result)
# This is a bit ugly, but it avoids running this again.
delattr(tp, self.name)
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _MovedItems(types.ModuleType):
"""Lazy loading of moved objects"""
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
del attr
moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_iterkeys = "keys"
_itervalues = "values"
_iteritems = "items"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_code = "func_code"
_func_defaults = "func_defaults"
_iterkeys = "iterkeys"
_itervalues = "itervalues"
_iteritems = "iteritems"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
if PY3:
def get_unbound_function(unbound):
return unbound
Iterator = object
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
else:
def get_unbound_function(unbound):
return unbound.im_func
class Iterator(object):
def next(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
def iterkeys(d):
"""Return an iterator over the keys of a dictionary."""
return iter(getattr(d, _iterkeys)())
def itervalues(d):
"""Return an iterator over the values of a dictionary."""
return iter(getattr(d, _itervalues)())
def iteritems(d):
"""Return an iterator over the (key, value) pairs of a dictionary."""
return iter(getattr(d, _iteritems)())
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
int2byte = chr
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if PY3:
import builtins
exec_ = getattr(builtins, "exec")
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
print_ = getattr(builtins, "print")
del builtins
else:
def exec_(code, globs=None, locs=None):
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
def print_(*args, **kwargs):
"""The new-style print function."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
_add_doc(reraise, """Reraise an exception.""")
def with_metaclass(meta, base=object):
"""Create a base class with a metaclass."""
return meta("NewBase", (base,), {})

View File

@ -23,5 +23,6 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
version = '0.4.3' version = '0.4.3'

View File

@ -23,6 +23,8 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
from sure import this from sure import this
from steadymark.core import SteadyMark from steadymark.core import SteadyMark

View File

@ -23,7 +23,10 @@
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE. # OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
from steadymark.core import SteadyMark from steadymark.core import SteadyMark
from steadymark.six import text_type
def test_find_doctest_code_with_titles(): def test_find_doctest_code_with_titles():
@ -44,7 +47,7 @@ a paragraph
test1.title.should.equal("test 1") test1.title.should.equal("test 1")
failure.should.be.a(TypeError) failure.should.be.a(TypeError)
"boom".should.be.within(unicode(failure)) "boom".should.be.within(text_type(failure))
def test_find_python_code_with_titles(): def test_find_python_code_with_titles():
@ -65,7 +68,7 @@ raise ValueError('boom')
test1.title.should.equal("test 1") test1.title.should.equal("test 1")
failure.should.be.a(ValueError) failure.should.be.a(ValueError)
"boom".should.be.within(unicode(failure)) "boom".should.be.within(text_type(failure))
def test_keeps_scope_from_test_to_test(): def test_keeps_scope_from_test_to_test():

10
tox.ini Normal file
View File

@ -0,0 +1,10 @@
[tox]
envlist =
py26 , py27, py33
[testenv]
commands =
make test
deps =
nose==1.1.2
git+git://github.com/spulec/sure.git@py3k#egg=sure