From ffb2107703ac4f9463625ddf46adbf52c4029a98 Mon Sep 17 00:00:00 2001 From: Diana Clarke Date: Mon, 19 Nov 2012 20:19:39 -0500 Subject: [PATCH] just a pep8 pass of lib/sqlalchemy/testing/ --- lib/sqlalchemy/testing/pickleable.py | 33 ++++++++++++- lib/sqlalchemy/testing/profiling.py | 47 ++++++++++--------- lib/sqlalchemy/testing/requirements.py | 7 +-- lib/sqlalchemy/testing/runner.py | 1 + lib/sqlalchemy/testing/schema.py | 3 +- lib/sqlalchemy/testing/suite/test_ddl.py | 4 +- lib/sqlalchemy/testing/suite/test_insert.py | 5 +- .../testing/suite/test_reflection.py | 4 +- lib/sqlalchemy/testing/suite/test_types.py | 16 +++++-- .../testing/suite/test_update_delete.py | 6 +-- lib/sqlalchemy/testing/util.py | 10 ++-- lib/sqlalchemy/testing/warnings.py | 4 ++ 12 files changed, 93 insertions(+), 47 deletions(-) diff --git a/lib/sqlalchemy/testing/pickleable.py b/lib/sqlalchemy/testing/pickleable.py index f5b8b827cd..09d51b5faf 100644 --- a/lib/sqlalchemy/testing/pickleable.py +++ b/lib/sqlalchemy/testing/pickleable.py @@ -1,43 +1,59 @@ -"""Classes used in pickling tests, need to be at the module level for unpickling.""" +"""Classes used in pickling tests, need to be at the module level for +unpickling. +""" from . import fixtures + class User(fixtures.ComparableEntity): pass + class Order(fixtures.ComparableEntity): pass + class Dingaling(fixtures.ComparableEntity): pass + class EmailUser(User): pass + class Address(fixtures.ComparableEntity): pass + # TODO: these are kind of arbitrary.... class Child1(fixtures.ComparableEntity): pass + class Child2(fixtures.ComparableEntity): pass + class Parent(fixtures.ComparableEntity): pass + class Screen(object): + def __init__(self, obj, parent=None): self.obj = obj self.parent = parent + class Foo(object): + def __init__(self, moredata): self.data = 'im data' self.stuff = 'im stuff' self.moredata = moredata + __hash__ = object.__hash__ + def __eq__(self, other): return other.data == self.data and \ other.stuff == self.stuff and \ @@ -45,40 +61,53 @@ class Foo(object): class Bar(object): + def __init__(self, x, y): self.x = x self.y = y + __hash__ = object.__hash__ + def __eq__(self, other): return other.__class__ is self.__class__ and \ other.x == self.x and \ other.y == self.y + def __str__(self): return "Bar(%d, %d)" % (self.x, self.y) + class OldSchool: + def __init__(self, x, y): self.x = x self.y = y + def __eq__(self, other): return other.__class__ is self.__class__ and \ other.x == self.x and \ other.y == self.y + class OldSchoolWithoutCompare: + def __init__(self, x, y): self.x = x self.y = y + class BarWithoutCompare(object): + def __init__(self, x, y): self.x = x self.y = y + def __str__(self): return "Bar(%d, %d)" % (self.x, self.y) class NotComparable(object): + def __init__(self, data): self.data = data @@ -93,6 +122,7 @@ class NotComparable(object): class BrokenComparable(object): + def __init__(self, data): self.data = data @@ -104,4 +134,3 @@ class BrokenComparable(object): def __ne__(self, other): raise NotImplementedError - diff --git a/lib/sqlalchemy/testing/profiling.py b/lib/sqlalchemy/testing/profiling.py index a22e83cbc7..ae9d176b74 100644 --- a/lib/sqlalchemy/testing/profiling.py +++ b/lib/sqlalchemy/testing/profiling.py @@ -22,6 +22,7 @@ from ..util.compat import jython, pypy, win32 _current_test = None + def profiled(target=None, **target_opts): """Function profiling. @@ -69,13 +70,13 @@ def profiled(target=None, **target_opts): else: stats.print_stats() - print_callers = target_opts.get('print_callers', - profile_config['print_callers']) + print_callers = target_opts.get( + 'print_callers', profile_config['print_callers']) if print_callers: stats.print_callers() - print_callees = target_opts.get('print_callees', - profile_config['print_callees']) + print_callees = target_opts.get( + 'print_callees', profile_config['print_callees']) if print_callees: stats.print_callees() @@ -92,10 +93,14 @@ class ProfileStatsFile(object): """ def __init__(self, filename): - self.write = config.options is not None and config.options.write_profiles + self.write = ( + config.options is not None and + config.options.write_profiles + ) self.fname = os.path.abspath(filename) self.short_fname = os.path.split(self.fname)[-1] - self.data = collections.defaultdict(lambda: collections.defaultdict(dict)) + self.data = collections.defaultdict( + lambda: collections.defaultdict(dict)) self._read() if self.write: # rewrite for the case where features changed, @@ -124,7 +129,10 @@ class ProfileStatsFile(object): def has_stats(self): test_key = _current_test - return test_key in self.data and self.platform_key in self.data[test_key] + return ( + test_key in self.data and + self.platform_key in self.data[test_key] + ) def result(self, callcount): test_key = _current_test @@ -153,7 +161,6 @@ class ProfileStatsFile(object): per_platform['current_count'] += 1 return result - def _header(self): return \ "# %s\n"\ @@ -165,8 +172,8 @@ class ProfileStatsFile(object): "# assertions are raised if the counts do not match.\n"\ "# \n"\ "# To add a new callcount test, apply the function_call_count \n"\ - "# decorator and re-run the tests using the --write-profiles option - \n"\ - "# this file will be rewritten including the new count.\n"\ + "# decorator and re-run the tests using the --write-profiles \n"\ + "# option - this file will be rewritten including the new count.\n"\ "# \n"\ "" % (self.fname) @@ -183,7 +190,8 @@ class ProfileStatsFile(object): test_key, platform_key, counts = line.split() per_fn = self.data[test_key] per_platform = per_fn[platform_key] - per_platform['counts'] = [int(count) for count in counts.split(",")] + c = [int(count) for count in counts.split(",")] + per_platform['counts'] = c per_platform['lineno'] = lineno + 1 per_platform['current_count'] = 0 profile_f.close() @@ -198,16 +206,13 @@ class ProfileStatsFile(object): profile_f.write("\n# TEST: %s\n\n" % test_key) for platform_key in sorted(per_fn): per_platform = per_fn[platform_key] - profile_f.write( - "%s %s %s\n" % ( - test_key, - platform_key, ",".join(str(count) for count in per_platform['counts']) - ) - ) + c = ",".join(str(count) for count in per_platform['counts']) + profile_f.write("%s %s %s\n" % (test_key, platform_key, c)) profile_f.close() from sqlalchemy.util.compat import update_wrapper + def function_call_count(variance=0.05): """Assert a target for a test case's function call count. @@ -222,7 +227,6 @@ def function_call_count(variance=0.05): def decorate(fn): def wrap(*args, **kw): - if cProfile is None: raise SkipTest("cProfile is not installed") @@ -237,7 +241,6 @@ def function_call_count(variance=0.05): gc_collect() - timespent, load_stats, fn_result = _profile( fn, *args, **kw ) @@ -263,8 +266,9 @@ def function_call_count(variance=0.05): if abs(callcount - expected_count) > deviance: raise AssertionError( "Adjusted function call count %s not within %s%% " - "of expected %s. (Delete line %d of file %s to regenerate " - "this callcount, when tests are run with --write-profiles.)" + "of expected %s. (Delete line %d of file %s to " + "regenerate this callcount, when tests are run " + "with --write-profiles.)" % ( callcount, (variance * 100), expected_count, line_no, @@ -288,4 +292,3 @@ def _profile(fn, *args, **kw): ended = time.time() return ended - began, load_stats, locals()['result'] - diff --git a/lib/sqlalchemy/testing/requirements.py b/lib/sqlalchemy/testing/requirements.py index d58538db91..68659a855a 100644 --- a/lib/sqlalchemy/testing/requirements.py +++ b/lib/sqlalchemy/testing/requirements.py @@ -10,6 +10,7 @@ to provide specific inclusion/exlusions. from . import exclusions + class Requirements(object): def __init__(self, db, config): self.db = db @@ -178,7 +179,6 @@ class SuiteRequirements(Requirements): """ return exclusions.open() - @property def datetime(self): """target dialect supports representation of Python @@ -237,8 +237,10 @@ class SuiteRequirements(Requirements): @property def empty_strings_varchar(self): - """target database can persist/return an empty string with a varchar.""" + """target database can persist/return an empty string with a + varchar. + """ return exclusions.open() @property @@ -248,7 +250,6 @@ class SuiteRequirements(Requirements): return exclusions.open() - @property def update_from(self): """Target must support UPDATE..FROM syntax""" diff --git a/lib/sqlalchemy/testing/runner.py b/lib/sqlalchemy/testing/runner.py index 1a4ba52125..6ec73d7c83 100644 --- a/lib/sqlalchemy/testing/runner.py +++ b/lib/sqlalchemy/testing/runner.py @@ -28,5 +28,6 @@ from sqlalchemy.testing.plugin.noseplugin import NoseSQLAlchemy import nose + def main(): nose.main(addplugins=[NoseSQLAlchemy()]) diff --git a/lib/sqlalchemy/testing/schema.py b/lib/sqlalchemy/testing/schema.py index 5dfdc0e072..ad233ec22a 100644 --- a/lib/sqlalchemy/testing/schema.py +++ b/lib/sqlalchemy/testing/schema.py @@ -7,6 +7,7 @@ __all__ = 'Table', 'Column', table_options = {} + def Table(*args, **kw): """A schema.Table wrapper/hook for dialect-specific tweaks.""" @@ -76,10 +77,10 @@ def Column(*args, **kw): event.listen(col, 'after_parent_attach', add_seq, propagate=True) return col + def _truncate_name(dialect, name): if len(name) > dialect.max_identifier_length: return name[0:max(dialect.max_identifier_length - 6, 0)] + \ "_" + hex(hash(name) % 64)[2:] else: return name - diff --git a/lib/sqlalchemy/testing/suite/test_ddl.py b/lib/sqlalchemy/testing/suite/test_ddl.py index 466429aa5e..c5b162413f 100644 --- a/lib/sqlalchemy/testing/suite/test_ddl.py +++ b/lib/sqlalchemy/testing/suite/test_ddl.py @@ -25,7 +25,6 @@ class TableDDLTest(fixtures.TestBase): (1, 'some data') ) - @requirements.create_table @util.provide_metadata def test_create_table(self): @@ -35,7 +34,6 @@ class TableDDLTest(fixtures.TestBase): ) self._simple_roundtrip() - @requirements.drop_table @util.provide_metadata def test_drop_table(self): @@ -48,4 +46,4 @@ class TableDDLTest(fixtures.TestBase): ) -__all__ = ('TableDDLTest', ) \ No newline at end of file +__all__ = ('TableDDLTest', ) diff --git a/lib/sqlalchemy/testing/suite/test_insert.py b/lib/sqlalchemy/testing/suite/test_insert.py index 3cd7d39bca..b2b2a0aa8b 100644 --- a/lib/sqlalchemy/testing/suite/test_insert.py +++ b/lib/sqlalchemy/testing/suite/test_insert.py @@ -8,6 +8,7 @@ from sqlalchemy import Integer, String, select, util from ..schema import Table, Column + class LastrowidTest(fixtures.TablesTest): run_deletes = 'each' @@ -88,7 +89,6 @@ class InsertBehaviorTest(fixtures.TablesTest): else: engine = config.db - r = engine.execute( self.tables.autoinc_pk.insert(), data="some data" @@ -107,6 +107,7 @@ class InsertBehaviorTest(fixtures.TablesTest): assert r.is_insert assert not r.returns_rows + class ReturningTest(fixtures.TablesTest): run_deletes = 'each' __requires__ = 'returning', 'autoincrement_insert' @@ -162,5 +163,3 @@ class ReturningTest(fixtures.TablesTest): __all__ = ('LastrowidTest', 'InsertBehaviorTest', 'ReturningTest') - - diff --git a/lib/sqlalchemy/testing/suite/test_reflection.py b/lib/sqlalchemy/testing/suite/test_reflection.py index a7c814db7e..b9894347ad 100644 --- a/lib/sqlalchemy/testing/suite/test_reflection.py +++ b/lib/sqlalchemy/testing/suite/test_reflection.py @@ -18,6 +18,7 @@ from sqlalchemy import event metadata, users = None, None + class HasTableTest(fixtures.TablesTest): @classmethod def define_tables(cls, metadata): @@ -31,6 +32,7 @@ class HasTableTest(fixtures.TablesTest): assert config.db.dialect.has_table(conn, "test_table") assert not config.db.dialect.has_table(conn, "nonexistent_table") + class HasSequenceTest(fixtures.TestBase): __requires__ = 'sequences', @@ -425,4 +427,4 @@ class ComponentReflectionTest(fixtures.TablesTest): self._test_get_table_oid('users', schema='test_schema') -__all__ = ('ComponentReflectionTest', 'HasSequenceTest', 'HasTableTest') \ No newline at end of file +__all__ = ('ComponentReflectionTest', 'HasSequenceTest', 'HasTableTest') diff --git a/lib/sqlalchemy/testing/suite/test_types.py b/lib/sqlalchemy/testing/suite/test_types.py index 74cb52c6e8..8d0500d71d 100644 --- a/lib/sqlalchemy/testing/suite/test_types.py +++ b/lib/sqlalchemy/testing/suite/test_types.py @@ -8,6 +8,7 @@ from sqlalchemy import Date, DateTime, Time, MetaData, String from ..schema import Table, Column import datetime + class _UnicodeFixture(object): __requires__ = 'unicode_data', @@ -70,7 +71,6 @@ class _UnicodeFixture(object): for row in rows: assert isinstance(row[0], unicode) - def _test_empty_strings(self): unicode_table = self.tables.unicode_table @@ -83,16 +83,17 @@ class _UnicodeFixture(object): ).first() eq_(row, (u'',)) + class UnicodeVarcharTest(_UnicodeFixture, fixtures.TablesTest): __requires__ = 'unicode_data', datatype = Unicode(255) - @requirements.empty_strings_varchar def test_empty_strings_varchar(self): self._test_empty_strings() + class UnicodeTextTest(_UnicodeFixture, fixtures.TablesTest): __requires__ = 'unicode_data', 'text_type' @@ -114,6 +115,7 @@ class StringTest(fixtures.TestBase): foo.create(config.db) foo.drop(config.db) + class _DateFixture(object): compare = None @@ -165,37 +167,44 @@ class DateTimeTest(_DateFixture, fixtures.TablesTest): datatype = DateTime data = datetime.datetime(2012, 10, 15, 12, 57, 18) + class DateTimeMicrosecondsTest(_DateFixture, fixtures.TablesTest): __requires__ = 'datetime_microseconds', datatype = DateTime data = datetime.datetime(2012, 10, 15, 12, 57, 18, 396) + class TimeTest(_DateFixture, fixtures.TablesTest): __requires__ = 'time', datatype = Time data = datetime.time(12, 57, 18) + class TimeMicrosecondsTest(_DateFixture, fixtures.TablesTest): __requires__ = 'time_microseconds', datatype = Time data = datetime.time(12, 57, 18, 396) + class DateTest(_DateFixture, fixtures.TablesTest): __requires__ = 'date', datatype = Date data = datetime.date(2012, 10, 15) + class DateTimeCoercedToDateTimeTest(_DateFixture, fixtures.TablesTest): __requires__ = 'date', datatype = Date data = datetime.datetime(2012, 10, 15, 12, 57, 18) compare = datetime.date(2012, 10, 15) + class DateTimeHistoricTest(_DateFixture, fixtures.TablesTest): __requires__ = 'datetime_historic', datatype = DateTime data = datetime.datetime(1850, 11, 10, 11, 52, 35) + class DateHistoricTest(_DateFixture, fixtures.TablesTest): __requires__ = 'date_historic', datatype = Date @@ -207,6 +216,3 @@ __all__ = ('UnicodeVarcharTest', 'UnicodeTextTest', 'DateTimeHistoricTest', 'DateTimeCoercedToDateTimeTest', 'TimeMicrosecondsTest', 'TimeTest', 'DateTimeMicrosecondsTest', 'DateHistoricTest', 'StringTest') - - - diff --git a/lib/sqlalchemy/testing/suite/test_update_delete.py b/lib/sqlalchemy/testing/suite/test_update_delete.py index e73b05485b..a3456ac2ad 100644 --- a/lib/sqlalchemy/testing/suite/test_update_delete.py +++ b/lib/sqlalchemy/testing/suite/test_update_delete.py @@ -1,9 +1,7 @@ from .. import fixtures, config -from ..config import requirements from ..assertions import eq_ -from .. import engines -from sqlalchemy import Integer, String, select +from sqlalchemy import Integer, String from ..schema import Table, Column @@ -61,4 +59,4 @@ class SimpleUpdateDeleteTest(fixtures.TablesTest): ] ) -__all__ = ('SimpleUpdateDeleteTest', ) \ No newline at end of file +__all__ = ('SimpleUpdateDeleteTest', ) diff --git a/lib/sqlalchemy/testing/util.py b/lib/sqlalchemy/testing/util.py index 41b0a30b39..2592c341e3 100644 --- a/lib/sqlalchemy/testing/util.py +++ b/lib/sqlalchemy/testing/util.py @@ -26,9 +26,11 @@ elif pypy: else: # assume CPython - straight gc.collect, lazy_gc() is a pass gc_collect = gc.collect + def lazy_gc(): pass + def picklers(): picklers = set() # Py2K @@ -56,6 +58,7 @@ def round_decimal(value, prec): ).to_integral(decimal.ROUND_FLOOR) / \ pow(10, prec) + class RandomSet(set): def __iter__(self): l = list(set.__iter__(self)) @@ -80,6 +83,7 @@ class RandomSet(set): def copy(self): return RandomSet(self) + def conforms_partial_ordering(tuples, sorted_elements): """True if the given sorting conforms to the given partial ordering.""" @@ -93,6 +97,7 @@ def conforms_partial_ordering(tuples, sorted_elements): else: return True + def all_partial_orderings(tuples, elements): edges = defaultdict(set) for parent, child in tuples: @@ -131,7 +136,6 @@ def function_named(fn, name): return fn - def run_as_contextmanager(ctx, fn, *arg, **kw): """Run the given function under the given contextmanager, simulating the behavior of 'with' to support older @@ -152,6 +156,7 @@ def run_as_contextmanager(ctx, fn, *arg, **kw): else: return raise_ + def rowset(results): """Converts the results of sql execution into a plain set of column tuples. @@ -182,6 +187,7 @@ def provide_metadata(fn, *args, **kw): metadata.drop_all() self.metadata = prev_meta + class adict(dict): """Dict keys available as attributes. Shadows.""" def __getattribute__(self, key): @@ -192,5 +198,3 @@ class adict(dict): def get_all(self, *keys): return tuple([self[key] for key in keys]) - - diff --git a/lib/sqlalchemy/testing/warnings.py b/lib/sqlalchemy/testing/warnings.py index 7afcc63c5a..41f3dbfed3 100644 --- a/lib/sqlalchemy/testing/warnings.py +++ b/lib/sqlalchemy/testing/warnings.py @@ -4,6 +4,7 @@ import warnings from .. import exc as sa_exc from .. import util + def testing_warn(msg, stacklevel=3): """Replaces sqlalchemy.util.warn during tests.""" @@ -14,6 +15,7 @@ def testing_warn(msg, stacklevel=3): else: warnings.warn_explicit(msg, filename, lineno) + def resetwarnings(): """Reset warning behavior to testing defaults.""" @@ -24,6 +26,7 @@ def resetwarnings(): warnings.filterwarnings('error', category=sa_exc.SADeprecationWarning) warnings.filterwarnings('error', category=sa_exc.SAWarning) + def assert_warnings(fn, warnings): """Assert that each of the given warnings are emitted by fn.""" @@ -31,6 +34,7 @@ def assert_warnings(fn, warnings): canary = [] orig_warn = util.warn + def capture_warnings(*args, **kw): orig_warn(*args, **kw) popwarn = warnings.pop(0) -- 2.47.3