summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/testing
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2013-04-27 19:53:57 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2013-04-27 19:53:57 -0400
commit4b614b9b35cd2baddb7ca67c04bee5d70ec6a172 (patch)
tree7483cd269f5823f903f96709eb864fff9b6d9383 /lib/sqlalchemy/testing
parent9716a5c45e6185c5871555722d8495880f0e8c7a (diff)
downloadsqlalchemy-4b614b9b35cd2baddb7ca67c04bee5d70ec6a172.tar.gz
- the raw 2to3 run
- went through examples/ and cleaned out excess list() calls
Diffstat (limited to 'lib/sqlalchemy/testing')
-rw-r--r--lib/sqlalchemy/testing/__init__.py2
-rw-r--r--lib/sqlalchemy/testing/assertions.py31
-rw-r--r--lib/sqlalchemy/testing/assertsql.py10
-rw-r--r--lib/sqlalchemy/testing/engines.py43
-rw-r--r--lib/sqlalchemy/testing/entities.py4
-rw-r--r--lib/sqlalchemy/testing/exclusions.py10
-rw-r--r--lib/sqlalchemy/testing/fixtures.py16
-rw-r--r--lib/sqlalchemy/testing/plugin/noseplugin.py10
-rw-r--r--lib/sqlalchemy/testing/profiling.py10
-rw-r--r--lib/sqlalchemy/testing/schema.py4
-rw-r--r--lib/sqlalchemy/testing/suite/test_ddl.py2
-rw-r--r--lib/sqlalchemy/testing/suite/test_reflection.py4
-rw-r--r--lib/sqlalchemy/testing/suite/test_types.py18
-rw-r--r--lib/sqlalchemy/testing/util.py18
-rw-r--r--lib/sqlalchemy/testing/warnings.py4
15 files changed, 94 insertions, 92 deletions
diff --git a/lib/sqlalchemy/testing/__init__.py b/lib/sqlalchemy/testing/__init__.py
index e571a5045..d5522213d 100644
--- a/lib/sqlalchemy/testing/__init__.py
+++ b/lib/sqlalchemy/testing/__init__.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
from .warnings import testing_warn, assert_warnings, resetwarnings
diff --git a/lib/sqlalchemy/testing/assertions.py b/lib/sqlalchemy/testing/assertions.py
index ebd10b130..e01948f9c 100644
--- a/lib/sqlalchemy/testing/assertions.py
+++ b/lib/sqlalchemy/testing/assertions.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
from . import util as testutil
from sqlalchemy import pool, orm, util
@@ -63,7 +63,7 @@ def emits_warning_on(db, *warnings):
@decorator
def decorate(fn, *args, **kw):
- if isinstance(db, basestring):
+ if isinstance(db, str):
if not spec(config.db):
return fn(*args, **kw)
else:
@@ -171,9 +171,9 @@ def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
try:
callable_(*args, **kwargs)
assert False, "Callable did not raise an exception"
- except except_cls, e:
- assert re.search(msg, unicode(e), re.UNICODE), u"%r !~ %s" % (msg, e)
- print unicode(e).encode('utf-8')
+ except except_cls as e:
+ assert re.search(msg, str(e), re.UNICODE), "%r !~ %s" % (msg, e)
+ print(str(e).encode('utf-8'))
class AssertsCompiledSQL(object):
@@ -190,12 +190,12 @@ class AssertsCompiledSQL(object):
dialect = default.DefaultDialect()
elif dialect is None:
dialect = config.db.dialect
- elif isinstance(dialect, basestring):
+ elif isinstance(dialect, str):
dialect = create_engine("%s://" % dialect).dialect
kw = {}
if params is not None:
- kw['column_keys'] = params.keys()
+ kw['column_keys'] = list(params.keys())
if isinstance(clause, orm.Query):
context = clause._compile_context()
@@ -205,10 +205,11 @@ class AssertsCompiledSQL(object):
c = clause.compile(dialect=dialect, **kw)
param_str = repr(getattr(c, 'params', {}))
- # Py3K
- #param_str = param_str.encode('utf-8').decode('ascii', 'ignore')
+# start Py3K
+ param_str = param_str.encode('utf-8').decode('ascii', 'ignore')
+# end Py3K
- print "\nSQL String:\n" + str(c) + param_str
+ print("\nSQL String:\n" + str(c) + param_str)
cc = re.sub(r'[\n\t]', '', str(c))
@@ -262,7 +263,7 @@ class ComparesTables(object):
class AssertsExecutionResults(object):
def assert_result(self, result, class_, *objects):
result = list(result)
- print repr(result)
+ print(repr(result))
self.assert_list(result, class_, objects)
def assert_list(self, result, class_, list):
@@ -275,7 +276,7 @@ class AssertsExecutionResults(object):
def assert_row(self, class_, rowobj, desc):
self.assert_(rowobj.__class__ is class_,
"item class is not " + repr(class_))
- for key, value in desc.iteritems():
+ for key, value in desc.items():
if isinstance(value, tuple):
if isinstance(value[1], list):
self.assert_list(getattr(rowobj, key), value[0], value[1])
@@ -300,7 +301,7 @@ class AssertsExecutionResults(object):
found = util.IdentitySet(result)
expected = set([immutabledict(e) for e in expected])
- for wrong in itertools.ifilterfalse(lambda o: type(o) == cls, found):
+ for wrong in itertools.filterfalse(lambda o: type(o) == cls, found):
fail('Unexpected type "%s", expected "%s"' % (
type(wrong).__name__, cls.__name__))
@@ -311,7 +312,7 @@ class AssertsExecutionResults(object):
NOVALUE = object()
def _compare_item(obj, spec):
- for key, value in spec.iteritems():
+ for key, value in spec.items():
if isinstance(value, tuple):
try:
self.assert_unordered_result(
@@ -352,7 +353,7 @@ class AssertsExecutionResults(object):
for rule in rules:
if isinstance(rule, dict):
newrule = assertsql.AllOf(*[
- assertsql.ExactSQL(k, v) for k, v in rule.iteritems()
+ assertsql.ExactSQL(k, v) for k, v in rule.items()
])
else:
newrule = assertsql.ExactSQL(*rule)
diff --git a/lib/sqlalchemy/testing/assertsql.py b/lib/sqlalchemy/testing/assertsql.py
index 0e250f356..a6b63b2c3 100644
--- a/lib/sqlalchemy/testing/assertsql.py
+++ b/lib/sqlalchemy/testing/assertsql.py
@@ -127,7 +127,7 @@ class RegexSQL(SQLMatchRule):
# do a positive compare only
for param, received in zip(params, _received_parameters):
- for k, v in param.iteritems():
+ for k, v in param.items():
if k not in received or received[k] != v:
equivalent = False
break
@@ -180,7 +180,7 @@ class CompiledSQL(SQLMatchRule):
all_received = list(_received_parameters)
while params:
param = dict(params.pop(0))
- for k, v in context.compiled.params.iteritems():
+ for k, v in context.compiled.params.items():
param.setdefault(k, v)
if param not in _received_parameters:
equivalent = False
@@ -195,9 +195,9 @@ class CompiledSQL(SQLMatchRule):
all_received = []
self._result = equivalent
if not self._result:
- print 'Testing for compiled statement %r partial params '\
+ print('Testing for compiled statement %r partial params '\
'%r, received %r with params %r' % (self.statement,
- all_params, _received_statement, all_received)
+ all_params, _received_statement, all_received))
self._errmsg = \
'Testing for compiled statement %r partial params %r, '\
'received %r with params %r' % (self.statement,
@@ -262,7 +262,7 @@ def _process_engine_statement(query, context):
# oracle+zxjdbc passes a PyStatement when returning into
- query = unicode(query)
+ query = str(query)
if context.engine.name == 'mssql' \
and query.endswith('; select scope_identity()'):
query = query[:-25]
diff --git a/lib/sqlalchemy/testing/engines.py b/lib/sqlalchemy/testing/engines.py
index 26f561016..46bf76fad 100644
--- a/lib/sqlalchemy/testing/engines.py
+++ b/lib/sqlalchemy/testing/engines.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
import types
import weakref
@@ -31,18 +31,18 @@ class ConnectionKiller(object):
fn()
except (SystemExit, KeyboardInterrupt):
raise
- except Exception, e:
+ except Exception as e:
warnings.warn(
"testing_reaper couldn't "
"rollback/close connection: %s" % e)
def rollback_all(self):
- for rec in self.proxy_refs.keys():
+ for rec in list(self.proxy_refs.keys()):
if rec is not None and rec.is_valid:
self._safe(rec.rollback)
def close_all(self):
- for rec in self.proxy_refs.keys():
+ for rec in list(self.proxy_refs.keys()):
if rec is not None:
self._safe(rec._close)
@@ -66,7 +66,7 @@ class ConnectionKiller(object):
self.conns = set()
- for rec in self.testing_engines.keys():
+ for rec in list(self.testing_engines.keys()):
if rec is not config.db:
rec.dispose()
@@ -75,7 +75,7 @@ class ConnectionKiller(object):
for conn in self.conns:
self._safe(conn.close)
self.conns = set()
- for rec in self.testing_engines.keys():
+ for rec in list(self.testing_engines.keys()):
rec.dispose()
def assert_all_closed(self):
@@ -160,7 +160,7 @@ class ReconnectFixture(object):
fn()
except (SystemExit, KeyboardInterrupt):
raise
- except Exception, e:
+ except Exception as e:
warnings.warn(
"ReconnectFixture couldn't "
"close connection: %s" % e)
@@ -353,23 +353,24 @@ class ReplayableSession(object):
Callable = object()
NoAttribute = object()
- # Py3K
- #Natives = set([getattr(types, t)
- # for t in dir(types) if not t.startswith('_')]). \
- # union([type(t) if not isinstance(t, type)
- # else t for t in __builtins__.values()]).\
- # difference([getattr(types, t)
- # for t in ('FunctionType', 'BuiltinFunctionType',
- # 'MethodType', 'BuiltinMethodType',
- # 'LambdaType', )])
- # Py2K
+# start Py3K
Natives = set([getattr(types, t)
for t in dir(types) if not t.startswith('_')]). \
+ union([type(t) if not isinstance(t, type)
+ else t for t in list(__builtins__.values())]).\
difference([getattr(types, t)
- for t in ('FunctionType', 'BuiltinFunctionType',
- 'MethodType', 'BuiltinMethodType',
- 'LambdaType', 'UnboundMethodType',)])
- # end Py2K
+ for t in ('FunctionType', 'BuiltinFunctionType',
+ 'MethodType', 'BuiltinMethodType',
+ 'LambdaType', )])
+# end Py3K
+# start Py2K
+# Natives = set([getattr(types, t)
+# for t in dir(types) if not t.startswith('_')]). \
+# difference([getattr(types, t)
+# for t in ('FunctionType', 'BuiltinFunctionType',
+# 'MethodType', 'BuiltinMethodType',
+# 'LambdaType', 'UnboundMethodType',)])
+# end Py2K
def __init__(self):
self.buffer = deque()
diff --git a/lib/sqlalchemy/testing/entities.py b/lib/sqlalchemy/testing/entities.py
index 5c5e69154..221c23c56 100644
--- a/lib/sqlalchemy/testing/entities.py
+++ b/lib/sqlalchemy/testing/entities.py
@@ -7,7 +7,7 @@ _repr_stack = set()
class BasicEntity(object):
def __init__(self, **kw):
- for key, value in kw.iteritems():
+ for key, value in kw.items():
setattr(self, key, value)
def __repr__(self):
@@ -67,7 +67,7 @@ class ComparableEntity(BasicEntity):
a = self
b = other
- for attr in a.__dict__.keys():
+ for attr in list(a.__dict__.keys()):
if attr.startswith('_'):
continue
value = getattr(a, attr)
diff --git a/lib/sqlalchemy/testing/exclusions.py b/lib/sqlalchemy/testing/exclusions.py
index 2c0679e1d..93f444eb9 100644
--- a/lib/sqlalchemy/testing/exclusions.py
+++ b/lib/sqlalchemy/testing/exclusions.py
@@ -1,4 +1,4 @@
-from __future__ import with_statement
+
import operator
from nose import SkipTest
@@ -23,10 +23,10 @@ class skip_if(object):
def fail_if(self, name='block'):
try:
yield
- except Exception, ex:
+ except Exception as ex:
if self.predicate():
- print ("%s failed as expected (%s): %s " % (
- name, self.predicate, str(ex)))
+ print(("%s failed as expected (%s): %s " % (
+ name, self.predicate, str(ex))))
else:
raise
else:
@@ -92,7 +92,7 @@ class Predicate(object):
return OrPredicate([cls.as_predicate(pred) for pred in predicate])
elif isinstance(predicate, tuple):
return SpecPredicate(*predicate)
- elif isinstance(predicate, basestring):
+ elif isinstance(predicate, str):
return SpecPredicate(predicate, None, None)
elif util.callable(predicate):
return LambdaPredicate(predicate)
diff --git a/lib/sqlalchemy/testing/fixtures.py b/lib/sqlalchemy/testing/fixtures.py
index 5c587cb2f..08b2361f2 100644
--- a/lib/sqlalchemy/testing/fixtures.py
+++ b/lib/sqlalchemy/testing/fixtures.py
@@ -125,9 +125,9 @@ class TablesTest(TestBase):
for table in reversed(self.metadata.sorted_tables):
try:
table.delete().execute().close()
- except sa.exc.DBAPIError, ex:
- print >> sys.stderr, "Error emptying table %s: %r" % (
- table, ex)
+ except sa.exc.DBAPIError as ex:
+ print("Error emptying table %s: %r" % (
+ table, ex), file=sys.stderr)
def setup(self):
self._setup_each_tables()
@@ -187,10 +187,10 @@ class TablesTest(TestBase):
def _load_fixtures(cls):
"""Insert rows as represented by the fixtures() method."""
headers, rows = {}, {}
- for table, data in cls.fixtures().iteritems():
+ for table, data in cls.fixtures().items():
if len(data) < 2:
continue
- if isinstance(table, basestring):
+ if isinstance(table, str):
table = cls.tables[table]
headers[table] = data[0]
rows[table] = data[1:]
@@ -199,7 +199,7 @@ class TablesTest(TestBase):
continue
cls.bind.execute(
table.insert(),
- [dict(zip(headers[table], column_values))
+ [dict(list(zip(headers[table], column_values)))
for column_values in rows[table]])
@@ -284,8 +284,8 @@ class MappedTest(_ORMTest, TablesTest, assertions.AssertsExecutionResults):
cls_registry[classname] = cls
return type.__init__(cls, classname, bases, dict_)
- class _Base(object):
- __metaclass__ = FindFixture
+ class _Base(object, metaclass=FindFixture):
+ pass
class Basic(BasicEntity, _Base):
pass
diff --git a/lib/sqlalchemy/testing/plugin/noseplugin.py b/lib/sqlalchemy/testing/plugin/noseplugin.py
index 5bd7ff3cd..7ad61c7b9 100644
--- a/lib/sqlalchemy/testing/plugin/noseplugin.py
+++ b/lib/sqlalchemy/testing/plugin/noseplugin.py
@@ -9,10 +9,10 @@ When third party libraries use this plugin, it can be imported
normally as "from sqlalchemy.testing.plugin import noseplugin".
"""
-from __future__ import absolute_import
+
import os
-import ConfigParser
+import configparser
from nose.plugins import Plugin
from nose import SkipTest
@@ -55,9 +55,9 @@ def _log(option, opt_str, value, parser):
def _list_dbs(*args):
- print "Available --db options (use --dburi to override)"
+ print("Available --db options (use --dburi to override)")
for macro in sorted(file_config.options('db')):
- print "%20s\t%s" % (macro, file_config.get('db', macro))
+ print("%20s\t%s" % (macro, file_config.get('db', macro)))
sys.exit(0)
@@ -318,7 +318,7 @@ class NoseSQLAlchemy(Plugin):
opt("--write-profiles", action="store_true", dest="write_profiles", default=False,
help="Write/update profiling data.")
global file_config
- file_config = ConfigParser.ConfigParser()
+ file_config = configparser.ConfigParser()
file_config.read(['setup.cfg', 'test.cfg'])
def configure(self, options, conf):
diff --git a/lib/sqlalchemy/testing/profiling.py b/lib/sqlalchemy/testing/profiling.py
index 19a9731be..bda44d80c 100644
--- a/lib/sqlalchemy/testing/profiling.py
+++ b/lib/sqlalchemy/testing/profiling.py
@@ -60,9 +60,9 @@ def profiled(target=None, **target_opts):
if report:
sort_ = target_opts.get('sort', profile_config['sort'])
limit = target_opts.get('limit', profile_config['limit'])
- print ("Profile report for target '%s' (%s)" % (
+ print(("Profile report for target '%s' (%s)" % (
target, filename)
- )
+ ))
stats = load_stats()
stats.sort_stats(*sort_)
@@ -198,7 +198,7 @@ class ProfileStatsFile(object):
profile_f.close()
def _write(self):
- print("Writing profile file %s" % self.fname)
+ print(("Writing profile file %s" % self.fname))
profile_f = open(self.fname, "w")
profile_f.write(self._header())
for test_key in sorted(self.data):
@@ -253,11 +253,11 @@ def function_call_count(variance=0.05):
else:
line_no, expected_count = expected
- print("Pstats calls: %d Expected %s" % (
+ print(("Pstats calls: %d Expected %s" % (
callcount,
expected_count
)
- )
+ ))
stats.print_stats()
#stats.print_callers()
diff --git a/lib/sqlalchemy/testing/schema.py b/lib/sqlalchemy/testing/schema.py
index 325d74f1e..6f3e87cc9 100644
--- a/lib/sqlalchemy/testing/schema.py
+++ b/lib/sqlalchemy/testing/schema.py
@@ -11,7 +11,7 @@ table_options = {}
def Table(*args, **kw):
"""A schema.Table wrapper/hook for dialect-specific tweaks."""
- test_opts = dict([(k, kw.pop(k)) for k in kw.keys()
+ test_opts = dict([(k, kw.pop(k)) for k in list(kw.keys())
if k.startswith('test_')])
kw.update(table_options)
@@ -58,7 +58,7 @@ def Table(*args, **kw):
def Column(*args, **kw):
"""A schema.Column wrapper/hook for dialect-specific tweaks."""
- test_opts = dict([(k, kw.pop(k)) for k in kw.keys()
+ test_opts = dict([(k, kw.pop(k)) for k in list(kw.keys())
if k.startswith('test_')])
if not config.requirements.foreign_key_ddl.enabled:
diff --git a/lib/sqlalchemy/testing/suite/test_ddl.py b/lib/sqlalchemy/testing/suite/test_ddl.py
index fc1c19362..28251b807 100644
--- a/lib/sqlalchemy/testing/suite/test_ddl.py
+++ b/lib/sqlalchemy/testing/suite/test_ddl.py
@@ -1,4 +1,4 @@
-from __future__ import with_statement
+
from .. import fixtures, config, util
from ..config import requirements
diff --git a/lib/sqlalchemy/testing/suite/test_reflection.py b/lib/sqlalchemy/testing/suite/test_reflection.py
index 7cae48572..ff76bd2cd 100644
--- a/lib/sqlalchemy/testing/suite/test_reflection.py
+++ b/lib/sqlalchemy/testing/suite/test_reflection.py
@@ -1,4 +1,4 @@
-from __future__ import with_statement
+
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc
@@ -386,7 +386,7 @@ class ComponentReflectionTest(fixtures.TablesTest):
self.tables.email_addresses, self.tables.dingalings
insp = inspect(meta.bind)
oid = insp.get_table_oid(table_name, schema)
- self.assert_(isinstance(oid, (int, long)))
+ self.assert_(isinstance(oid, int))
def test_get_table_oid(self):
self._test_get_table_oid('users')
diff --git a/lib/sqlalchemy/testing/suite/test_types.py b/lib/sqlalchemy/testing/suite/test_types.py
index 0716b1b91..4dd3884ed 100644
--- a/lib/sqlalchemy/testing/suite/test_types.py
+++ b/lib/sqlalchemy/testing/suite/test_types.py
@@ -15,9 +15,9 @@ import datetime
class _UnicodeFixture(object):
__requires__ = 'unicode_data',
- data = u"Alors vous imaginez ma surprise, au lever du jour, "\
- u"quand une drôle de petite voix m’a réveillé. Elle "\
- u"disait: « S’il vous plaît… dessine-moi un mouton! »"
+ data = "Alors vous imaginez ma surprise, au lever du jour, "\
+ "quand une drôle de petite voix m’a réveillé. Elle "\
+ "disait: « S’il vous plaît… dessine-moi un mouton! »"
@classmethod
def define_tables(cls, metadata):
@@ -47,7 +47,7 @@ class _UnicodeFixture(object):
row,
(self.data, )
)
- assert isinstance(row[0], unicode)
+ assert isinstance(row[0], str)
def test_round_trip_executemany(self):
unicode_table = self.tables.unicode_table
@@ -58,7 +58,7 @@ class _UnicodeFixture(object):
{
'unicode_data': self.data,
}
- for i in xrange(3)
+ for i in range(3)
]
)
@@ -69,22 +69,22 @@ class _UnicodeFixture(object):
).fetchall()
eq_(
rows,
- [(self.data, ) for i in xrange(3)]
+ [(self.data, ) for i in range(3)]
)
for row in rows:
- assert isinstance(row[0], unicode)
+ assert isinstance(row[0], str)
def _test_empty_strings(self):
unicode_table = self.tables.unicode_table
config.db.execute(
unicode_table.insert(),
- {"unicode_data": u''}
+ {"unicode_data": ''}
)
row = config.db.execute(
select([unicode_table.c.unicode_data])
).first()
- eq_(row, (u'',))
+ eq_(row, ('',))
class UnicodeVarcharTest(_UnicodeFixture, fixtures.TablesTest):
diff --git a/lib/sqlalchemy/testing/util.py b/lib/sqlalchemy/testing/util.py
index d9ff14eaf..5facd2f06 100644
--- a/lib/sqlalchemy/testing/util.py
+++ b/lib/sqlalchemy/testing/util.py
@@ -32,13 +32,13 @@ else:
def picklers():
picklers = set()
- # Py2K
- try:
- import cPickle
- picklers.add(cPickle)
- except ImportError:
- pass
- # end Py2K
+# start Py2K
+# try:
+# import cPickle
+# picklers.add(cPickle)
+# except ImportError:
+# pass
+# end Py2K
import pickle
picklers.add(pickle)
@@ -130,8 +130,8 @@ def function_named(fn, name):
try:
fn.__name__ = name
except TypeError:
- fn = types.FunctionType(fn.func_code, fn.func_globals, name,
- fn.func_defaults, fn.func_closure)
+ fn = types.FunctionType(fn.__code__, fn.__globals__, name,
+ fn.__defaults__, fn.__closure__)
return fn
diff --git a/lib/sqlalchemy/testing/warnings.py b/lib/sqlalchemy/testing/warnings.py
index 41f3dbfed..9546945eb 100644
--- a/lib/sqlalchemy/testing/warnings.py
+++ b/lib/sqlalchemy/testing/warnings.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
import warnings
from .. import exc as sa_exc
@@ -10,7 +10,7 @@ def testing_warn(msg, stacklevel=3):
filename = "sqlalchemy.testing.warnings"
lineno = 1
- if isinstance(msg, basestring):
+ if isinstance(msg, str):
warnings.warn_explicit(msg, sa_exc.SAWarning, filename, lineno)
else:
warnings.warn_explicit(msg, filename, lineno)