diff options
author | Laurent Peuch <cortex@worlddomination.be> | 2020-04-01 00:11:10 +0200 |
---|---|---|
committer | Laurent Peuch <cortex@worlddomination.be> | 2020-04-01 00:11:10 +0200 |
commit | b8899451fa861b04568e2a0bb4e3fe4acc0daee3 (patch) | |
tree | 1446c809e19b5571b31b1999246aa0e50b19f5c8 /test | |
parent | 32cd73810056594f55eff0ffafebbdeb50c7a860 (diff) | |
download | logilab-common-b8899451fa861b04568e2a0bb4e3fe4acc0daee3.tar.gz |
Black the whole code base
Diffstat (limited to 'test')
30 files changed, 1581 insertions, 1115 deletions
diff --git a/test/data/__pkginfo__.py b/test/data/__pkginfo__.py index d1f5731..51f36ec 100644 --- a/test/data/__pkginfo__.py +++ b/test/data/__pkginfo__.py @@ -20,15 +20,15 @@ __docformat__ = "restructuredtext en" import sys import os -distname = 'logilab-common' -modname = 'common' -subpackage_of = 'logilab' +distname = "logilab-common" +modname = "common" +subpackage_of = "logilab" subpackage_master = True numversion = (0, 63, 2) -version = '.'.join([str(num) for num in numversion]) +version = ".".join([str(num) for num in numversion]) -license = 'LGPL' # 2.1 or later +license = "LGPL" # 2.1 or later description = "collection of low-level Python packages and modules used by Logilab projects" web = "http://www.logilab.org/project/%s" % distname mailinglist = "mailto://python-projects@lists.logilab.org" @@ -37,19 +37,21 @@ author_email = "contact@logilab.fr" from os.path import join -scripts = [join('bin', 'logilab-pytest')] -include_dirs = [join('test', 'data')] + +scripts = [join("bin", "logilab-pytest")] +include_dirs = [join("test", "data")] install_requires = [] -tests_require = ['pytz'] +tests_require = ["pytz"] if sys.version_info < (2, 7): - install_requires.append('unittest2 >= 0.5.1') -if os.name == 'nt': - install_requires.append('colorama') - -classifiers = ["Topic :: Utilities", - "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 3", - ] + install_requires.append("unittest2 >= 0.5.1") +if os.name == "nt": + install_requires.append("colorama") + +classifiers = [ + "Topic :: Utilities", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 3", +] diff --git a/test/data/deprecation.py b/test/data/deprecation.py index be3b103..3ef3c0f 100644 --- a/test/data/deprecation.py +++ b/test/data/deprecation.py @@ -1,4 +1,5 @@ # placeholder used by unittest_deprecation + def moving_target(): pass diff --git a/test/data/lmfp/foo.py b/test/data/lmfp/foo.py index 8f7de1e..841ea47 100644 --- a/test/data/lmfp/foo.py +++ b/test/data/lmfp/foo.py @@ -1,5 +1,6 @@ import sys -if not getattr(sys, 'bar', None): + +if not getattr(sys, "bar", None): sys.just_once = [] # there used to be two numbers here because # of a load_module_from_path bug diff --git a/test/data/module.py b/test/data/module.py index 493e676..3b83811 100644 --- a/test/data/module.py +++ b/test/data/module.py @@ -21,11 +21,14 @@ def global_access(key, val): else: break else: - print('!!!') + print("!!!") + class YO: """hehe""" - a=1 + + a = 1 + def __init__(self): try: self.yo = 1 @@ -36,7 +39,8 @@ class YO: except: raise -#print('*****>',YO.__dict__) + +# print('*****>',YO.__dict__) class YOUPI(YO): class_attr = None @@ -51,19 +55,21 @@ class YOUPI(YO): local = None autre = [a for a, b in MY_DICT if b] if b in autre: - print('yo', end=' ') + print("yo", end=" ") elif a in autre: - print('hehe') + print("hehe") global_access(local, val=autre) finally: return local def static_method(): """static method test""" - assert MY_DICT, '???' + assert MY_DICT, "???" + static_method = staticmethod(static_method) def class_method(cls): """class method test""" exec(a, b) + class_method = classmethod(class_method) diff --git a/test/data/module2.py b/test/data/module2.py index 51509f3..7192904 100644 --- a/test/data/module2.py +++ b/test/data/module2.py @@ -1,51 +1,76 @@ from data.module import YO, YOUPI import data -class Specialization(YOUPI, YO): pass -class Metaclass(type): pass +class Specialization(YOUPI, YO): + pass -class Interface: pass -class MyIFace(Interface): pass +class Metaclass(type): + pass -class AnotherIFace(Interface): pass -class MyException(Exception): pass -class MyError(MyException): pass +class Interface: + pass -class AbstractClass(object): +class MyIFace(Interface): + pass + + +class AnotherIFace(Interface): + pass + + +class MyException(Exception): + pass + + +class MyError(MyException): + pass + + +class AbstractClass(object): def to_override(self, whatever): raise NotImplementedError() def return_something(self, param): if param: - return 'toto' + return "toto" return + class Concrete0: __implements__ = MyIFace + + class Concrete1: __implements__ = MyIFace, AnotherIFace + + class Concrete2: - __implements__ = (MyIFace, - AnotherIFace) -class Concrete23(Concrete1): pass + __implements__ = (MyIFace, AnotherIFace) + + +class Concrete23(Concrete1): + pass + del YO.member del YO [SYN1, SYN2] = Concrete0, Concrete1 -assert '1' +assert "1" b = 1 | 2 & 3 ^ 8 -exec('c = 3') -exec('c = 3', {}, {}) +exec("c = 3") +exec("c = 3", {}, {}) + def raise_string(a=2, *args, **kwargs): - raise 'pas glop' - raise Exception('yo') - yield 'coucou' + raise "pas glop" + raise Exception("yo") + yield "coucou" + a = b + 2 c = b * 2 @@ -66,12 +91,14 @@ e = d[a:b:c] raise_string(*args, **kwargs) -print >> stream, 'bonjour' -print >> stream, 'salut', +print >> stream, "bonjour" +print >> stream, "salut", def make_class(any, base=data.module.YO, *args, **kwargs): """check base is correctly resolved to Concrete0""" + class Aaaa(base): """dynamic class""" + return Aaaa diff --git a/test/data/noendingnewline.py b/test/data/noendingnewline.py index 110f902..f309715 100644 --- a/test/data/noendingnewline.py +++ b/test/data/noendingnewline.py @@ -4,11 +4,9 @@ import unittest class TestCase(unittest.TestCase): - def setUp(self): unittest.TestCase.setUp(self) - def tearDown(self): unittest.TestCase.tearDown(self) @@ -16,11 +14,10 @@ class TestCase(unittest.TestCase): self.a = 10 self.xxx() - def xxx(self): if False: pass - print('a') + print("a") if False: pass @@ -28,9 +25,9 @@ class TestCase(unittest.TestCase): if False: pass - print('rara') + print("rara") -if __name__ == '__main__': - print('test2') +if __name__ == "__main__": + print("test2") unittest.main() diff --git a/test/data/nonregr.py b/test/data/nonregr.py index a4b5ef7..a8747a2 100644 --- a/test/data/nonregr.py +++ b/test/data/nonregr.py @@ -11,6 +11,7 @@ except NameError: yield i, val i += 1 + def toto(value): for k, v in value: - print(v.get('yo')) + print(v.get("yo")) diff --git a/test/data/regobjects.py b/test/data/regobjects.py index 6cea558..4ad0e94 100644 --- a/test/data/regobjects.py +++ b/test/data/regobjects.py @@ -1,22 +1,29 @@ """unittest_registry data file""" from logilab.common.registry import yes, RegistrableObject, RegistrableInstance + class Proxy(object): """annoying object should that not be registered, nor cause error""" + def __getattr__(self, attr): return 1 + trap = Proxy() + class AppObjectClass(RegistrableObject): - __registry__ = 'zereg' - __regid__ = 'appobject1' + __registry__ = "zereg" + __regid__ = "appobject1" __select__ = yes() + class AppObjectInstance(RegistrableInstance): - __registry__ = 'zereg' + __registry__ = "zereg" __select__ = yes() + def __init__(self, regid): self.__regid__ = regid -appobject2 = AppObjectInstance('appobject2') + +appobject2 = AppObjectInstance("appobject2") diff --git a/test/data/regobjects2.py b/test/data/regobjects2.py index 091b9f7..b6d5781 100644 --- a/test/data/regobjects2.py +++ b/test/data/regobjects2.py @@ -1,8 +1,10 @@ from logilab.common.registry import RegistrableObject, RegistrableInstance, yes + class MyRegistrableInstance(RegistrableInstance): - __regid__ = 'appobject3' + __regid__ = "appobject3" __select__ = yes() - __registry__ = 'zereg' + __registry__ = "zereg" + instance = MyRegistrableInstance(__module__=__name__) diff --git a/test/data/sub/momo.py b/test/data/sub/momo.py index 746b5d0..ecf4ab5 100644 --- a/test/data/sub/momo.py +++ b/test/data/sub/momo.py @@ -1,3 +1,3 @@ from __future__ import print_function -print('yo') +print("yo") diff --git a/test/test_cache.py b/test/test_cache.py index 459f172..8e169c4 100644 --- a/test/test_cache.py +++ b/test/test_cache.py @@ -20,109 +20,112 @@ from logilab.common.testlib import TestCase, unittest_main, TestSuite from logilab.common.cache import Cache -class CacheTestCase(TestCase): +class CacheTestCase(TestCase): def setUp(self): self.cache = Cache(5) self.testdict = {} def test_setitem1(self): """Checks that the setitem method works""" - self.cache[1] = 'foo' - self.assertEqual(self.cache[1], 'foo', "1:foo is not in cache") + self.cache[1] = "foo" + self.assertEqual(self.cache[1], "foo", "1:foo is not in cache") self.assertEqual(len(self.cache._usage), 1) - self.assertEqual(self.cache._usage[-1], 1, - '1 is not the most recently used key') - self.assertCountEqual(self.cache._usage, - self.cache.keys(), - "usage list and data keys are different") + self.assertEqual(self.cache._usage[-1], 1, "1 is not the most recently used key") + self.assertCountEqual( + self.cache._usage, self.cache.keys(), "usage list and data keys are different" + ) def test_setitem2(self): """Checks that the setitem method works for multiple items""" - self.cache[1] = 'foo' - self.cache[2] = 'bar' - self.assertEqual(self.cache[2], 'bar', - "2 : 'bar' is not in cache.data") - self.assertEqual(len(self.cache._usage), 2, - "lenght of usage list is not 2") - self.assertEqual(self.cache._usage[-1], 2, - '1 is not the most recently used key') - self.assertCountEqual(self.cache._usage, - self.cache.keys())# usage list and data keys are different + self.cache[1] = "foo" + self.cache[2] = "bar" + self.assertEqual(self.cache[2], "bar", "2 : 'bar' is not in cache.data") + self.assertEqual(len(self.cache._usage), 2, "lenght of usage list is not 2") + self.assertEqual(self.cache._usage[-1], 2, "1 is not the most recently used key") + self.assertCountEqual( + self.cache._usage, self.cache.keys() + ) # usage list and data keys are different def test_setitem3(self): """Checks that the setitem method works when replacing an element in the cache""" - self.cache[1] = 'foo' - self.cache[1] = 'bar' - self.assertEqual(self.cache[1], 'bar', "1 : 'bar' is not in cache.data") + self.cache[1] = "foo" + self.cache[1] = "bar" + self.assertEqual(self.cache[1], "bar", "1 : 'bar' is not in cache.data") self.assertEqual(len(self.cache._usage), 1, "lenght of usage list is not 1") - self.assertEqual(self.cache._usage[-1], 1, '1 is not the most recently used key') - self.assertCountEqual(self.cache._usage, - self.cache.keys())# usage list and data keys are different + self.assertEqual(self.cache._usage[-1], 1, "1 is not the most recently used key") + self.assertCountEqual( + self.cache._usage, self.cache.keys() + ) # usage list and data keys are different def test_recycling1(self): """Checks the removal of old elements""" - self.cache[1] = 'foo' - self.cache[2] = 'bar' - self.cache[3] = 'baz' - self.cache[4] = 'foz' - self.cache[5] = 'fuz' - self.cache[6] = 'spam' - self.assertTrue(1 not in self.cache, - 'key 1 has not been suppressed from the cache dictionnary') - self.assertTrue(1 not in self.cache._usage, - 'key 1 has not been suppressed from the cache LRU list') + self.cache[1] = "foo" + self.cache[2] = "bar" + self.cache[3] = "baz" + self.cache[4] = "foz" + self.cache[5] = "fuz" + self.cache[6] = "spam" + self.assertTrue( + 1 not in self.cache, "key 1 has not been suppressed from the cache dictionnary" + ) + self.assertTrue( + 1 not in self.cache._usage, "key 1 has not been suppressed from the cache LRU list" + ) self.assertEqual(len(self.cache._usage), 5, "lenght of usage list is not 5") - self.assertEqual(self.cache._usage[-1], 6, '6 is not the most recently used key') - self.assertCountEqual(self.cache._usage, - self.cache.keys())# usage list and data keys are different + self.assertEqual(self.cache._usage[-1], 6, "6 is not the most recently used key") + self.assertCountEqual( + self.cache._usage, self.cache.keys() + ) # usage list and data keys are different def test_recycling2(self): """Checks that accessed elements get in the front of the list""" - self.cache[1] = 'foo' - self.cache[2] = 'bar' - self.cache[3] = 'baz' - self.cache[4] = 'foz' + self.cache[1] = "foo" + self.cache[2] = "bar" + self.cache[3] = "baz" + self.cache[4] = "foz" a = self.cache[1] - self.assertEqual(a, 'foo') - self.assertEqual(self.cache._usage[-1], 1, '1 is not the most recently used key') - self.assertCountEqual(self.cache._usage, - self.cache.keys())# usage list and data keys are different + self.assertEqual(a, "foo") + self.assertEqual(self.cache._usage[-1], 1, "1 is not the most recently used key") + self.assertCountEqual( + self.cache._usage, self.cache.keys() + ) # usage list and data keys are different def test_delitem(self): """Checks that elements are removed from both element dict and element list. """ - self.cache['foo'] = 'bar' - del self.cache['foo'] - self.assertTrue('foo' not in self.cache.keys(), "Element 'foo' was not removed cache dictionnary") - self.assertTrue('foo' not in self.cache._usage, "Element 'foo' was not removed usage list") - self.assertCountEqual(self.cache._usage, - self.cache.keys())# usage list and data keys are different - + self.cache["foo"] = "bar" + del self.cache["foo"] + self.assertTrue( + "foo" not in self.cache.keys(), "Element 'foo' was not removed cache dictionnary" + ) + self.assertTrue("foo" not in self.cache._usage, "Element 'foo' was not removed usage list") + self.assertCountEqual( + self.cache._usage, self.cache.keys() + ) # usage list and data keys are different def test_nullsize(self): """Checks that a 'NULL' size cache doesn't store anything """ null_cache = Cache(0) - null_cache['foo'] = 'bar' - self.assertEqual(null_cache.size, 0, 'Cache size should be O, not %d' % \ - null_cache.size) - self.assertEqual(len(null_cache), 0, 'Cache should be empty !') + null_cache["foo"] = "bar" + self.assertEqual(null_cache.size, 0, "Cache size should be O, not %d" % null_cache.size) + self.assertEqual(len(null_cache), 0, "Cache should be empty !") # Assert null_cache['foo'] raises a KeyError - self.assertRaises(KeyError, null_cache.__getitem__, 'foo') + self.assertRaises(KeyError, null_cache.__getitem__, "foo") # Deleting element raises a KeyError - self.assertRaises(KeyError, null_cache.__delitem__, 'foo') + self.assertRaises(KeyError, null_cache.__delitem__, "foo") def test_getitem(self): """ Checks that getitem doest not modify the _usage attribute """ try: - self.cache['toto'] + self.cache["toto"] except KeyError: - self.assertTrue('toto' not in self.cache._usage) + self.assertTrue("toto" not in self.cache._usage) else: - self.fail('excepted KeyError') + self.fail("excepted KeyError") if __name__ == "__main__": diff --git a/test/test_changelog.py b/test/test_changelog.py index c2572d7..c251311 100644 --- a/test/test_changelog.py +++ b/test/test_changelog.py @@ -26,7 +26,7 @@ from logilab.common.changelog import ChangeLog class ChangeLogTC(TestCase): cl_class = ChangeLog - cl_file = join(dirname(__file__), 'data', 'ChangeLog') + cl_file = join(dirname(__file__), "data", "ChangeLog") def test_round_trip(self): cl = self.cl_class(self.cl_file) @@ -36,5 +36,5 @@ class ChangeLogTC(TestCase): self.assertMultiLineEqual(stream.read(), out.getvalue()) -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_configuration.py b/test/test_configuration.py index 2dee7d0..d8d0a4b 100644 --- a/test/test_configuration.py +++ b/test/test_configuration.py @@ -26,109 +26,137 @@ from logilab.common import attrdict from logilab.common.compat import StringIO from logilab.common.testlib import TestCase, unittest_main from logilab.common.optik_ext import OptionValueError -from logilab.common.configuration import Configuration, OptionError, \ - OptionsManagerMixIn, OptionsProviderMixIn, Method, read_old_config, \ - merge_options - -DATA = join(dirname(abspath(__file__)), 'data') - -OPTIONS = [('dothis', {'type':'yn', 'action': 'store', 'default': True, 'metavar': '<y or n>'}), - ('value', {'type': 'string', 'metavar': '<string>', 'short': 'v'}), - ('multiple', {'type': 'csv', 'default': ['yop', 'yep'], - 'metavar': '<comma separated values>', - 'help': 'you can also document the option'}), - ('number', {'type': 'int', 'default':2, 'metavar':'<int>', 'help': 'boom'}), - ('bytes', {'type': 'bytes', 'default':'1KB', 'metavar':'<bytes>'}), - ('choice', {'type': 'choice', 'default':'yo', 'choices': ('yo', 'ye'), - 'metavar':'<yo|ye>'}), - ('multiple-choice', {'type': 'multiple_choice', 'default':['yo', 'ye'], - 'choices': ('yo', 'ye', 'yu', 'yi', 'ya'), - 'metavar':'<yo|ye>'}), - ('named', {'type':'named', 'default':Method('get_named'), - 'metavar': '<key=val>'}), - - ('diffgroup', {'type':'string', 'default':'pouet', 'metavar': '<key=val>', - 'group': 'agroup'}), - ('reset-value', {'type': 'string', 'metavar': '<string>', 'short': 'r', - 'dest':'value'}), - - ('opt-b-1', {'type': 'string', 'metavar': '<string>', 'group': 'bgroup'}), - ('opt-b-2', {'type': 'string', 'metavar': '<string>', 'group': 'bgroup'}), - ] +from logilab.common.configuration import ( + Configuration, + OptionError, + OptionsManagerMixIn, + OptionsProviderMixIn, + Method, + read_old_config, + merge_options, +) + +DATA = join(dirname(abspath(__file__)), "data") + +OPTIONS = [ + ("dothis", {"type": "yn", "action": "store", "default": True, "metavar": "<y or n>"}), + ("value", {"type": "string", "metavar": "<string>", "short": "v"}), + ( + "multiple", + { + "type": "csv", + "default": ["yop", "yep"], + "metavar": "<comma separated values>", + "help": "you can also document the option", + }, + ), + ("number", {"type": "int", "default": 2, "metavar": "<int>", "help": "boom"}), + ("bytes", {"type": "bytes", "default": "1KB", "metavar": "<bytes>"}), + ("choice", {"type": "choice", "default": "yo", "choices": ("yo", "ye"), "metavar": "<yo|ye>"}), + ( + "multiple-choice", + { + "type": "multiple_choice", + "default": ["yo", "ye"], + "choices": ("yo", "ye", "yu", "yi", "ya"), + "metavar": "<yo|ye>", + }, + ), + ("named", {"type": "named", "default": Method("get_named"), "metavar": "<key=val>"}), + ( + "diffgroup", + {"type": "string", "default": "pouet", "metavar": "<key=val>", "group": "agroup"}, + ), + ("reset-value", {"type": "string", "metavar": "<string>", "short": "r", "dest": "value"}), + ("opt-b-1", {"type": "string", "metavar": "<string>", "group": "bgroup"}), + ("opt-b-2", {"type": "string", "metavar": "<string>", "group": "bgroup"}), +] + class MyConfiguration(Configuration): """test configuration""" + def get_named(self): - return {'key': 'val'} + return {"key": "val"} -class ConfigurationTC(TestCase): +class ConfigurationTC(TestCase): def setUp(self): - self.cfg = MyConfiguration(name='test', options=OPTIONS, usage='Just do it ! (tm)') + self.cfg = MyConfiguration(name="test", options=OPTIONS, usage="Just do it ! (tm)") def test_default(self): cfg = self.cfg - self.assertEqual(cfg['dothis'], True) - self.assertEqual(cfg['value'], None) - self.assertEqual(cfg['multiple'], ['yop', 'yep']) - self.assertEqual(cfg['number'], 2) - self.assertEqual(cfg['bytes'], 1024) - self.assertIsInstance(cfg['bytes'], int) - self.assertEqual(cfg['choice'], 'yo') - self.assertEqual(cfg['multiple-choice'], ['yo', 'ye']) - self.assertEqual(cfg['named'], {'key': 'val'}) + self.assertEqual(cfg["dothis"], True) + self.assertEqual(cfg["value"], None) + self.assertEqual(cfg["multiple"], ["yop", "yep"]) + self.assertEqual(cfg["number"], 2) + self.assertEqual(cfg["bytes"], 1024) + self.assertIsInstance(cfg["bytes"], int) + self.assertEqual(cfg["choice"], "yo") + self.assertEqual(cfg["multiple-choice"], ["yo", "ye"]) + self.assertEqual(cfg["named"], {"key": "val"}) def test_base(self): cfg = self.cfg - cfg.set_option('number', '0') - self.assertEqual(cfg['number'], 0) - self.assertRaises(OptionValueError, cfg.set_option, 'number', 'youpi') - self.assertRaises(OptionValueError, cfg.set_option, 'choice', 'youpi') - self.assertRaises(OptionValueError, cfg.set_option, 'multiple-choice', ('yo', 'y', 'ya')) - cfg.set_option('multiple-choice', 'yo, ya') - self.assertEqual(cfg['multiple-choice'], ['yo', 'ya']) - self.assertEqual(cfg.get('multiple-choice'), ['yo', 'ya']) - self.assertEqual(cfg.get('whatever'), None) + cfg.set_option("number", "0") + self.assertEqual(cfg["number"], 0) + self.assertRaises(OptionValueError, cfg.set_option, "number", "youpi") + self.assertRaises(OptionValueError, cfg.set_option, "choice", "youpi") + self.assertRaises(OptionValueError, cfg.set_option, "multiple-choice", ("yo", "y", "ya")) + cfg.set_option("multiple-choice", "yo, ya") + self.assertEqual(cfg["multiple-choice"], ["yo", "ya"]) + self.assertEqual(cfg.get("multiple-choice"), ["yo", "ya"]) + self.assertEqual(cfg.get("whatever"), None) def test_load_command_line_configuration(self): cfg = self.cfg - args = cfg.load_command_line_configuration(['--choice', 'ye', '--number', '4', - '--multiple=1,2,3', '--dothis=n', - '--bytes=10KB', - 'other', 'arguments']) - self.assertEqual(args, ['other', 'arguments']) - self.assertEqual(cfg['dothis'], False) - self.assertEqual(cfg['multiple'], ['1', '2', '3']) - self.assertEqual(cfg['number'], 4) - self.assertEqual(cfg['bytes'], 10240) - self.assertEqual(cfg['choice'], 'ye') - self.assertEqual(cfg['value'], None) - args = cfg.load_command_line_configuration(['-v', 'duh']) + args = cfg.load_command_line_configuration( + [ + "--choice", + "ye", + "--number", + "4", + "--multiple=1,2,3", + "--dothis=n", + "--bytes=10KB", + "other", + "arguments", + ] + ) + self.assertEqual(args, ["other", "arguments"]) + self.assertEqual(cfg["dothis"], False) + self.assertEqual(cfg["multiple"], ["1", "2", "3"]) + self.assertEqual(cfg["number"], 4) + self.assertEqual(cfg["bytes"], 10240) + self.assertEqual(cfg["choice"], "ye") + self.assertEqual(cfg["value"], None) + args = cfg.load_command_line_configuration(["-v", "duh"]) self.assertEqual(args, []) - self.assertEqual(cfg['value'], 'duh') - self.assertEqual(cfg['dothis'], False) - self.assertEqual(cfg['multiple'], ['1', '2', '3']) - self.assertEqual(cfg['number'], 4) - self.assertEqual(cfg['bytes'], 10240) - self.assertEqual(cfg['choice'], 'ye') + self.assertEqual(cfg["value"], "duh") + self.assertEqual(cfg["dothis"], False) + self.assertEqual(cfg["multiple"], ["1", "2", "3"]) + self.assertEqual(cfg["number"], 4) + self.assertEqual(cfg["bytes"], 10240) + self.assertEqual(cfg["choice"], "ye") def test_load_configuration(self): cfg = self.cfg - args = cfg.load_configuration(choice='ye', number='4', - multiple='1,2,3', dothis='n', - multiple_choice=('yo', 'ya')) - self.assertEqual(cfg['dothis'], False) - self.assertEqual(cfg['multiple'], ['1', '2', '3']) - self.assertEqual(cfg['number'], 4) - self.assertEqual(cfg['choice'], 'ye') - self.assertEqual(cfg['value'], None) - self.assertEqual(cfg['multiple-choice'], ('yo', 'ya')) + args = cfg.load_configuration( + choice="ye", number="4", multiple="1,2,3", dothis="n", multiple_choice=("yo", "ya") + ) + self.assertEqual(cfg["dothis"], False) + self.assertEqual(cfg["multiple"], ["1", "2", "3"]) + self.assertEqual(cfg["number"], 4) + self.assertEqual(cfg["choice"], "ye") + self.assertEqual(cfg["value"], None) + self.assertEqual(cfg["multiple-choice"], ("yo", "ya")) def test_load_configuration_file_case_insensitive(self): file = tempfile.mktemp() - stream = open(file, 'w') + stream = open(file, "w") try: - stream.write("""[Test] + stream.write( + """[Test] dothis=no @@ -152,13 +180,14 @@ named=key:val [agroup] diffgroup=zou -""") +""" + ) stream.close() self.cfg.load_file_configuration(file) - self.assertEqual(self.cfg['dothis'], False) - self.assertEqual(self.cfg['value'], None) - self.assertEqual(self.cfg['multiple'], ['yop', 'yepii']) - self.assertEqual(self.cfg['diffgroup'], 'zou') + self.assertEqual(self.cfg["dothis"], False) + self.assertEqual(self.cfg["value"], None) + self.assertEqual(self.cfg["multiple"], ["yop", "yepii"]) + self.assertEqual(self.cfg["diffgroup"], "zou") finally: os.remove(file) @@ -167,37 +196,43 @@ diffgroup=zou and not in the order they are defined in the Configuration object. """ file = tempfile.mktemp() - stream = open(file, 'w') + stream = open(file, "w") try: - stream.write("""[Test] + stream.write( + """[Test] reset-value=toto value=tata -""") +""" + ) stream.close() self.cfg.load_file_configuration(file) finally: os.remove(file) - self.assertEqual(self.cfg['value'], 'tata') + self.assertEqual(self.cfg["value"], "tata") def test_unsupported_options(self): file = tempfile.mktemp() - stream = open(file, 'w') + stream = open(file, "w") try: - stream.write("""[Test] + stream.write( + """[Test] whatever=toto value=tata -""") +""" + ) stream.close() self.cfg.load_file_configuration(file) finally: os.remove(file) - self.assertEqual(self.cfg['value'], 'tata') - self.assertRaises(OptionError, self.cfg.__getitem__, 'whatever') + self.assertEqual(self.cfg["value"], "tata") + self.assertRaises(OptionError, self.cfg.__getitem__, "whatever") def test_generate_config(self): stream = StringIO() self.cfg.generate_config(stream) - self.assertMultiLineEqual(stream.getvalue().strip(), """[TEST] + self.assertMultiLineEqual( + stream.getvalue().strip(), + """[TEST] dothis=yes @@ -229,13 +264,16 @@ diffgroup=pouet #opt-b-1= -#opt-b-2=""") +#opt-b-2=""", + ) def test_generate_config_with_space_string(self): - self.cfg['value'] = ' ' + self.cfg["value"] = " " stream = StringIO() self.cfg.generate_config(stream) - self.assertMultiLineEqual(stream.getvalue().strip(), """[TEST] + self.assertMultiLineEqual( + stream.getvalue().strip(), + """[TEST] dothis=yes @@ -267,13 +305,16 @@ diffgroup=pouet #opt-b-1= -#opt-b-2=""") +#opt-b-2=""", + ) def test_generate_config_with_multiline_string(self): - self.cfg['value'] = 'line1\nline2\nline3' + self.cfg["value"] = "line1\nline2\nline3" stream = StringIO() self.cfg.generate_config(stream) - self.assertMultiLineEqual(stream.getvalue().strip(), """[TEST] + self.assertMultiLineEqual( + stream.getvalue().strip(), + """[TEST] dothis=yes @@ -311,47 +352,46 @@ diffgroup=pouet #opt-b-1= -#opt-b-2=""") - +#opt-b-2=""", + ) def test_roundtrip(self): cfg = self.cfg f = tempfile.mktemp() - stream = open(f, 'w') + stream = open(f, "w") try: - self.cfg['dothis'] = False - self.cfg['multiple'] = ["toto", "tata"] - self.cfg['number'] = 3 - self.cfg['bytes'] = 2048 + self.cfg["dothis"] = False + self.cfg["multiple"] = ["toto", "tata"] + self.cfg["number"] = 3 + self.cfg["bytes"] = 2048 cfg.generate_config(stream) stream.close() - new_cfg = MyConfiguration(name='test', options=OPTIONS) + new_cfg = MyConfiguration(name="test", options=OPTIONS) new_cfg.load_file_configuration(f) - self.assertEqual(cfg['dothis'], new_cfg['dothis']) - self.assertEqual(cfg['multiple'], new_cfg['multiple']) - self.assertEqual(cfg['number'], new_cfg['number']) - self.assertEqual(cfg['bytes'], new_cfg['bytes']) - self.assertEqual(cfg['choice'], new_cfg['choice']) - self.assertEqual(cfg['value'], new_cfg['value']) - self.assertEqual(cfg['multiple-choice'], new_cfg['multiple-choice']) + self.assertEqual(cfg["dothis"], new_cfg["dothis"]) + self.assertEqual(cfg["multiple"], new_cfg["multiple"]) + self.assertEqual(cfg["number"], new_cfg["number"]) + self.assertEqual(cfg["bytes"], new_cfg["bytes"]) + self.assertEqual(cfg["choice"], new_cfg["choice"]) + self.assertEqual(cfg["value"], new_cfg["value"]) + self.assertEqual(cfg["multiple-choice"], new_cfg["multiple-choice"]) finally: os.remove(f) def test_setitem(self): - self.assertRaises(OptionValueError, - self.cfg.__setitem__, 'multiple-choice', ('a', 'b')) - self.cfg['multiple-choice'] = ('yi', 'ya') - self.assertEqual(self.cfg['multiple-choice'], ('yi', 'ya')) + self.assertRaises(OptionValueError, self.cfg.__setitem__, "multiple-choice", ("a", "b")) + self.cfg["multiple-choice"] = ("yi", "ya") + self.assertEqual(self.cfg["multiple-choice"], ("yi", "ya")) def test_help(self): - self.cfg.add_help_section('bonus', 'a nice additional help') + self.cfg.add_help_section("bonus", "a nice additional help") help = self.cfg.help().strip() # at least in python 2.4.2 the output is: # ' -v <string>, --value=<string>' # it is not unlikely some optik/optparse versions do print -v<string> # so accept both - help = help.replace(' -v <string>, ', ' -v<string>, ') - help = re.sub('[ ]*(\r?\n)', '\\1', help) + help = help.replace(" -v <string>, ", " -v<string>, ") + help = re.sub("[ ]*(\r?\n)", "\\1", help) USAGE = """Usage: Just do it ! (tm) Options: @@ -378,7 +418,7 @@ Options: a nice additional help""" if version_info < (2, 5): # 'usage' header is not capitalized in this version - USAGE = USAGE.replace('Usage: ', 'usage: ') + USAGE = USAGE.replace("Usage: ", "usage: ") elif version_info < (2, 4): USAGE = """usage: Just do it ! (tm) @@ -398,21 +438,23 @@ options: """ self.assertMultiLineEqual(help, USAGE) - def test_manpage(self): pkginfo = {} - with open(join(DATA, '__pkginfo__.py')) as fobj: + with open(join(DATA, "__pkginfo__.py")) as fobj: exec(fobj.read(), pkginfo) self.cfg.generate_manpage(attrdict(pkginfo), stream=StringIO()) def test_rewrite_config(self): - changes = [('renamed', 'renamed', 'choice'), - ('moved', 'named', 'old', 'test'), - ] - read_old_config(self.cfg, changes, join(DATA, 'test.ini')) + changes = [ + ("renamed", "renamed", "choice"), + ("moved", "named", "old", "test"), + ] + read_old_config(self.cfg, changes, join(DATA, "test.ini")) stream = StringIO() self.cfg.generate_config(stream) - self.assertMultiLineEqual(stream.getvalue().strip(), """[TEST] + self.assertMultiLineEqual( + stream.getvalue().strip(), + """[TEST] dothis=yes @@ -444,22 +486,26 @@ diffgroup=pouet #opt-b-1= -#opt-b-2=""") +#opt-b-2=""", + ) + class Linter(OptionsManagerMixIn, OptionsProviderMixIn): options = ( - ('profile', {'type' : 'yn', 'metavar' : '<y_or_n>', - 'default': False, - 'help' : 'Profiled execution.'}), - ) + ( + "profile", + {"type": "yn", "metavar": "<y_or_n>", "default": False, "help": "Profiled execution."}, + ), + ) + def __init__(self): OptionsManagerMixIn.__init__(self, usage="") OptionsProviderMixIn.__init__(self) self.register_options_provider(self) self.load_provider_defaults() -class RegrTC(TestCase): +class RegrTC(TestCase): def setUp(self): self.linter = Linter() @@ -472,36 +518,51 @@ class RegrTC(TestCase): config = Configuration() self.assertEqual(config.options, ()) new_options = ( - ('option1', {'type': 'string', 'help': '', - 'group': 'g1', 'level': 2}), - ('option2', {'type': 'string', 'help': '', - 'group': 'g1', 'level': 2}), - ('option3', {'type': 'string', 'help': '', - 'group': 'g2', 'level': 2}), + ("option1", {"type": "string", "help": "", "group": "g1", "level": 2}), + ("option2", {"type": "string", "help": "", "group": "g1", "level": 2}), + ("option3", {"type": "string", "help": "", "group": "g2", "level": 2}), ) config.register_options(new_options) self.assertEqual(config.options, new_options) class MergeTC(TestCase): - def test_merge1(self): - merged = merge_options([('dothis', {'type':'yn', 'action': 'store', 'default': True, 'metavar': '<y or n>'}), - ('dothis', {'type':'yn', 'action': 'store', 'default': False, 'metavar': '<y or n>'}), - ]) + merged = merge_options( + [ + ( + "dothis", + {"type": "yn", "action": "store", "default": True, "metavar": "<y or n>"}, + ), + ( + "dothis", + {"type": "yn", "action": "store", "default": False, "metavar": "<y or n>"}, + ), + ] + ) self.assertEqual(len(merged), 1) - self.assertEqual(merged[0][0], 'dothis') - self.assertEqual(merged[0][1]['default'], True) + self.assertEqual(merged[0][0], "dothis") + self.assertEqual(merged[0][1]["default"], True) def test_merge2(self): - merged = merge_options([('dothis', {'type':'yn', 'action': 'store', 'default': True, 'metavar': '<y or n>'}), - ('value', {'type': 'string', 'metavar': '<string>', 'short': 'v'}), - ('dothis', {'type':'yn', 'action': 'store', 'default': False, 'metavar': '<y or n>'}), - ]) + merged = merge_options( + [ + ( + "dothis", + {"type": "yn", "action": "store", "default": True, "metavar": "<y or n>"}, + ), + ("value", {"type": "string", "metavar": "<string>", "short": "v"}), + ( + "dothis", + {"type": "yn", "action": "store", "default": False, "metavar": "<y or n>"}, + ), + ] + ) self.assertEqual(len(merged), 2) - self.assertEqual(merged[0][0], 'value') - self.assertEqual(merged[1][0], 'dothis') - self.assertEqual(merged[1][1]['default'], True) + self.assertEqual(merged[0][0], "value") + self.assertEqual(merged[1][0], "dothis") + self.assertEqual(merged[1][1]["default"], True) + -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_date.py b/test/test_date.py index 9ae444b..cf09b11 100644 --- a/test/test_date.py +++ b/test/test_date.py @@ -20,20 +20,34 @@ Unittests for date helpers """ from logilab.common.testlib import TestCase, unittest_main, tag -from logilab.common.date import (date_range, endOfMonth, add_days_worked, - nb_open_days, get_national_holidays, ustrftime, ticks2datetime, - utcdatetime, datetime2ticks) +from logilab.common.date import ( + date_range, + endOfMonth, + add_days_worked, + nb_open_days, + get_national_holidays, + ustrftime, + ticks2datetime, + utcdatetime, + datetime2ticks, +) from datetime import date, datetime, timedelta from calendar import timegm import pytz try: - from mx.DateTime import Date as mxDate, DateTime as mxDateTime, \ - now as mxNow, RelativeDateTime, RelativeDate + from mx.DateTime import ( + Date as mxDate, + DateTime as mxDateTime, + now as mxNow, + RelativeDateTime, + RelativeDate, + ) except ImportError: mxDate = mxDateTime = RelativeDateTime = mxNow = None + class DateTC(TestCase): datecls = date datetimecls = datetime @@ -65,8 +79,9 @@ class DateTC(TestCase): def test_get_national_holidays(self): holidays = get_national_holidays - yield self.assertEqual, holidays(self.datecls(2008, 4, 29), self.datecls(2008, 5, 2)), \ - [self.datecls(2008, 5, 1)] + yield self.assertEqual, holidays(self.datecls(2008, 4, 29), self.datecls(2008, 5, 2)), [ + self.datecls(2008, 5, 1) + ] yield self.assertEqual, holidays(self.datecls(2008, 5, 7), self.datecls(2008, 5, 8)), [] x = self.datetimecls(2008, 5, 7, 12, 12, 12) yield self.assertEqual, holidays(x, x + self.timedeltacls(days=1)), [] @@ -129,22 +144,26 @@ class DateTC(TestCase): def test_open_days_afternoon(self): self.assertOpenDays(self.datetimecls(2008, 5, 6, 14), self.datetimecls(2008, 5, 7, 14), 1) - @tag('posix', '1900') + @tag("posix", "1900") def test_ustrftime_before_1900(self): date = self.datetimecls(1328, 3, 12, 6, 30) - self.assertEqual(ustrftime(date, '%Y-%m-%d %H:%M:%S'), u'1328-03-12 06:30:00') + self.assertEqual(ustrftime(date, "%Y-%m-%d %H:%M:%S"), "1328-03-12 06:30:00") - @tag('posix', '1900') + @tag("posix", "1900") def test_ticks2datetime_before_1900(self): ticks = -2209075200000 date = ticks2datetime(ticks) - self.assertEqual(ustrftime(date, '%Y-%m-%d'), u'1899-12-31') + self.assertEqual(ustrftime(date, "%Y-%m-%d"), "1899-12-31") def test_month(self): """enumerate months""" - r = list(date_range(self.datecls(2006, 5, 6), self.datecls(2006, 8, 27), - incmonth=True)) - expected = [self.datecls(2006, 5, 6), self.datecls(2006, 6, 1), self.datecls(2006, 7, 1), self.datecls(2006, 8, 1)] + r = list(date_range(self.datecls(2006, 5, 6), self.datecls(2006, 8, 27), incmonth=True)) + expected = [ + self.datecls(2006, 5, 6), + self.datecls(2006, 6, 1), + self.datecls(2006, 7, 1), + self.datecls(2006, 8, 1), + ] self.assertListEqual(expected, r) def test_utcdatetime(self): @@ -155,14 +174,12 @@ class DateTC(TestCase): self.assertEqual(d, self.datetimecls(2014, 11, 26, 12, 0, 0, 57)) self.assertIsNone(d.tzinfo) - d = pytz.timezone('Europe/Paris').localize( - self.datetimecls(2014, 11, 26, 12, 0, 0, 57)) + d = pytz.timezone("Europe/Paris").localize(self.datetimecls(2014, 11, 26, 12, 0, 0, 57)) d = utcdatetime(d) self.assertEqual(d, self.datetimecls(2014, 11, 26, 11, 0, 0, 57)) self.assertIsNone(d.tzinfo) - d = pytz.timezone('Europe/Paris').localize( - self.datetimecls(2014, 7, 26, 12, 0, 0, 57)) + d = pytz.timezone("Europe/Paris").localize(self.datetimecls(2014, 7, 26, 12, 0, 0, 57)) d = utcdatetime(d) self.assertEqual(d, self.datetimecls(2014, 7, 26, 10, 0, 0, 57)) self.assertIsNone(d.tzinfo) @@ -188,7 +205,7 @@ class MxDateTC(DateTC): def check_mx(self): if mxDate is None: - self.skipTest('mx.DateTime is not installed') + self.skipTest("mx.DateTime is not installed") def setUp(self): self.check_mx() @@ -199,8 +216,13 @@ class MxDateTC(DateTC): expected = [self.datecls(2000, 1, 2), self.datecls(2000, 2, 29), self.datecls(2000, 3, 31)] self.assertListEqual(r, expected) r = list(date_range(self.datecls(2000, 11, 30), self.datecls(2001, 2, 3), endOfMonth)) - expected = [self.datecls(2000, 11, 30), self.datecls(2000, 12, 31), self.datecls(2001, 1, 31)] + expected = [ + self.datecls(2000, 11, 30), + self.datecls(2000, 12, 31), + self.datecls(2001, 1, 31), + ] self.assertListEqual(r, expected) -if __name__ == '__main__': + +if __name__ == "__main__": unittest_main() diff --git a/test/test_decorators.py b/test/test_decorators.py index e97a56f..42d8d8f 100644 --- a/test/test_decorators.py +++ b/test/test_decorators.py @@ -21,20 +21,23 @@ import sys import types from logilab.common.testlib import TestCase, unittest_main -from logilab.common.decorators import (monkeypatch, cached, clear_cache, - copy_cache, cachedproperty) +from logilab.common.decorators import monkeypatch, cached, clear_cache, copy_cache, cachedproperty -class DecoratorsTC(TestCase): +class DecoratorsTC(TestCase): def test_monkeypatch_instance_method(self): - class MyClass: pass + class MyClass: + pass + @monkeypatch(MyClass) def meth1(self): return 12 + class XXX(object): @monkeypatch(MyClass) def meth2(self): return 12 + if sys.version_info < (3, 0): self.assertIsInstance(MyClass.meth1, types.MethodType) self.assertIsInstance(MyClass.meth2, types.MethodType) @@ -46,51 +49,66 @@ class DecoratorsTC(TestCase): self.assertEqual(MyClass().meth2(), 12) def test_monkeypatch_property(self): - class MyClass: pass - @monkeypatch(MyClass, methodname='prop1') + class MyClass: + pass + + @monkeypatch(MyClass, methodname="prop1") @property def meth1(self): return 12 + self.assertIsInstance(MyClass.prop1, property) self.assertEqual(MyClass().prop1, 12) def test_monkeypatch_arbitrary_callable(self): - class MyClass: pass + class MyClass: + pass + class ArbitraryCallable(object): def __call__(self): return 12 + # ensure it complains about missing __name__ with self.assertRaises(AttributeError) as cm: monkeypatch(MyClass)(ArbitraryCallable()) - self.assertTrue(str(cm.exception).endswith('has no __name__ attribute: you should provide an explicit `methodname`')) + self.assertTrue( + str(cm.exception).endswith( + "has no __name__ attribute: you should provide an explicit `methodname`" + ) + ) # ensure no black magic under the hood - monkeypatch(MyClass, 'foo')(ArbitraryCallable()) + monkeypatch(MyClass, "foo")(ArbitraryCallable()) self.assertTrue(callable(MyClass.foo)) self.assertEqual(MyClass().foo(), 12) def test_monkeypatch_with_same_name(self): - class MyClass: pass + class MyClass: + pass + @monkeypatch(MyClass) def meth1(self): return 12 - self.assertEqual([attr for attr in dir(MyClass) if attr[:2] != '__'], - ['meth1']) + + self.assertEqual([attr for attr in dir(MyClass) if attr[:2] != "__"], ["meth1"]) inst = MyClass() self.assertEqual(inst.meth1(), 12) def test_monkeypatch_with_custom_name(self): - class MyClass: pass - @monkeypatch(MyClass, 'foo') + class MyClass: + pass + + @monkeypatch(MyClass, "foo") def meth2(self, param): return param + 12 - self.assertEqual([attr for attr in dir(MyClass) if attr[:2] != '__'], - ['foo']) + + self.assertEqual([attr for attr in dir(MyClass) if attr[:2] != "__"], ["foo"]) inst = MyClass() self.assertEqual(inst.foo(4), 16) def test_cannot_cache_generator(self): def foo(): yield 42 + self.assertRaises(AssertionError, cached, foo) def test_cached_preserves_docstrings_and_name(self): @@ -98,85 +116,95 @@ class DecoratorsTC(TestCase): @cached def foo(self): """ what's up doc ? """ + def bar(self, zogzog): """ what's up doc ? """ + bar = cached(bar, 1) + @cached def quux(self, zogzog): """ what's up doc ? """ + self.assertEqual(Foo.foo.__doc__, """ what's up doc ? """) - self.assertEqual(Foo.foo.__name__, 'foo') + self.assertEqual(Foo.foo.__name__, "foo") self.assertEqual(Foo.bar.__doc__, """ what's up doc ? """) - self.assertEqual(Foo.bar.__name__, 'bar') + self.assertEqual(Foo.bar.__name__, "bar") self.assertEqual(Foo.quux.__doc__, """ what's up doc ? """) - self.assertEqual(Foo.quux.__name__, 'quux') + self.assertEqual(Foo.quux.__name__, "quux") def test_cached_single_cache(self): class Foo(object): - @cached(cacheattr=u'_foo') + @cached(cacheattr="_foo") def foo(self): """ what's up doc ? """ + foo = Foo() foo.foo() - self.assertTrue(hasattr(foo, '_foo')) - clear_cache(foo, 'foo') - self.assertFalse(hasattr(foo, '_foo')) + self.assertTrue(hasattr(foo, "_foo")) + clear_cache(foo, "foo") + self.assertFalse(hasattr(foo, "_foo")) def test_cached_multi_cache(self): class Foo(object): - @cached(cacheattr=u'_foo') + @cached(cacheattr="_foo") def foo(self, args): """ what's up doc ? """ + foo = Foo() foo.foo(1) self.assertEqual(foo._foo, {(1,): None}) - clear_cache(foo, 'foo') - self.assertFalse(hasattr(foo, '_foo')) + clear_cache(foo, "foo") + self.assertFalse(hasattr(foo, "_foo")) def test_cached_keyarg_cache(self): class Foo(object): - @cached(cacheattr=u'_foo', keyarg=1) + @cached(cacheattr="_foo", keyarg=1) def foo(self, other, args): """ what's up doc ? """ + foo = Foo() foo.foo(2, 1) self.assertEqual(foo._foo, {2: None}) - clear_cache(foo, 'foo') - self.assertFalse(hasattr(foo, '_foo')) + clear_cache(foo, "foo") + self.assertFalse(hasattr(foo, "_foo")) def test_cached_property(self): class Foo(object): @property - @cached(cacheattr=u'_foo') + @cached(cacheattr="_foo") def foo(self): """ what's up doc ? """ + foo = Foo() foo.foo self.assertEqual(foo._foo, None) - clear_cache(foo, 'foo') - self.assertFalse(hasattr(foo, '_foo')) + clear_cache(foo, "foo") + self.assertFalse(hasattr(foo, "_foo")) def test_copy_cache(self): class Foo(object): - @cached(cacheattr=u'_foo') + @cached(cacheattr="_foo") def foo(self, args): """ what's up doc ? """ + foo = Foo() foo.foo(1) self.assertEqual(foo._foo, {(1,): None}) foo2 = Foo() - self.assertFalse(hasattr(foo2, '_foo')) - copy_cache(foo2, 'foo', foo) + self.assertFalse(hasattr(foo2, "_foo")) + copy_cache(foo2, "foo", foo) self.assertEqual(foo2._foo, {(1,): None}) - def test_cachedproperty(self): class Foo(object): x = 0 + @cachedproperty def bar(self): self.__class__.x += 1 return self.__class__.x + @cachedproperty def quux(self): """ some prop """ @@ -184,15 +212,13 @@ class DecoratorsTC(TestCase): foo = Foo() self.assertEqual(Foo.x, 0) - self.assertFalse('bar' in foo.__dict__) + self.assertFalse("bar" in foo.__dict__) self.assertEqual(foo.bar, 1) - self.assertTrue('bar' in foo.__dict__) + self.assertTrue("bar" in foo.__dict__) self.assertEqual(foo.bar, 1) self.assertEqual(foo.quux, 42) - self.assertEqual(Foo.bar.__doc__, - '<wrapped by the cachedproperty decorator>') - self.assertEqual(Foo.quux.__doc__, - '<wrapped by the cachedproperty decorator>\n some prop ') + self.assertEqual(Foo.bar.__doc__, "<wrapped by the cachedproperty decorator>") + self.assertEqual(Foo.quux.__doc__, "<wrapped by the cachedproperty decorator>\n some prop ") foo2 = Foo() self.assertEqual(foo2.bar, 2) @@ -202,7 +228,9 @@ class DecoratorsTC(TestCase): class Kallable(object): def __call__(self): return 42 + self.assertRaises(TypeError, cachedproperty, Kallable()) -if __name__ == '__main__': + +if __name__ == "__main__": unittest_main() diff --git a/test/test_fileutils.py b/test/test_fileutils.py index 555e73f..49955cd 100644 --- a/test/test_fileutils.py +++ b/test/test_fileutils.py @@ -27,47 +27,48 @@ from logilab.common.testlib import TestCase, unittest_main, unittest from logilab.common.fileutils import * -DATA_DIR = join(os.path.abspath(os.path.dirname(__file__)), 'data') -NEWLINES_TXT = join(DATA_DIR, 'newlines.txt') +DATA_DIR = join(os.path.abspath(os.path.dirname(__file__)), "data") +NEWLINES_TXT = join(DATA_DIR, "newlines.txt") class FirstleveldirectoryTC(TestCase): - def test_known_values_first_level_directory(self): """return the first level directory of a path""" - self.assertEqual(first_level_directory('truc/bidule/chouette'), 'truc', None) - self.assertEqual(first_level_directory('/truc/bidule/chouette'), '/', None) + self.assertEqual(first_level_directory("truc/bidule/chouette"), "truc", None) + self.assertEqual(first_level_directory("/truc/bidule/chouette"), "/", None) + class IsBinaryTC(TestCase): def test(self): - self.assertEqual(is_binary('toto.txt'), 0) - #self.assertEqual(is_binary('toto.xml'), 0) - self.assertEqual(is_binary('toto.bin'), 1) - self.assertEqual(is_binary('toto.sxi'), 1) - self.assertEqual(is_binary('toto.whatever'), 1) + self.assertEqual(is_binary("toto.txt"), 0) + # self.assertEqual(is_binary('toto.xml'), 0) + self.assertEqual(is_binary("toto.bin"), 1) + self.assertEqual(is_binary("toto.sxi"), 1) + self.assertEqual(is_binary("toto.whatever"), 1) + class GetModeTC(TestCase): def test(self): - self.assertEqual(write_open_mode('toto.txt'), 'w') - #self.assertEqual(write_open_mode('toto.xml'), 'w') - self.assertEqual(write_open_mode('toto.bin'), 'wb') - self.assertEqual(write_open_mode('toto.sxi'), 'wb') + self.assertEqual(write_open_mode("toto.txt"), "w") + # self.assertEqual(write_open_mode('toto.xml'), 'w') + self.assertEqual(write_open_mode("toto.bin"), "wb") + self.assertEqual(write_open_mode("toto.sxi"), "wb") + class NormReadTC(TestCase): def test_known_values_norm_read(self): with io.open(NEWLINES_TXT) as f: data = f.read() - self.assertEqual(data.strip(), '\n'.join(['# mixed new lines', '1', '2', '3'])) + self.assertEqual(data.strip(), "\n".join(["# mixed new lines", "1", "2", "3"])) class LinesTC(TestCase): def test_known_values_lines(self): - self.assertEqual(lines(NEWLINES_TXT), - ['# mixed new lines', '1', '2', '3']) + self.assertEqual(lines(NEWLINES_TXT), ["# mixed new lines", "1", "2", "3"]) def test_known_values_lines_comment(self): - self.assertEqual(lines(NEWLINES_TXT, comments='#'), - ['1', '2', '3']) + self.assertEqual(lines(NEWLINES_TXT, comments="#"), ["1", "2", "3"]) + class ExportTC(TestCase): def setUp(self): @@ -76,18 +77,19 @@ class ExportTC(TestCase): def test(self): export(DATA_DIR, self.tempdir, verbose=0) - self.assertTrue(exists(join(self.tempdir, '__init__.py'))) - self.assertTrue(exists(join(self.tempdir, 'sub'))) - self.assertTrue(not exists(join(self.tempdir, '__init__.pyc'))) - self.assertTrue(not exists(join(self.tempdir, 'CVS'))) + self.assertTrue(exists(join(self.tempdir, "__init__.py"))) + self.assertTrue(exists(join(self.tempdir, "sub"))) + self.assertTrue(not exists(join(self.tempdir, "__init__.pyc"))) + self.assertTrue(not exists(join(self.tempdir, "CVS"))) def tearDown(self): shutil.rmtree(self.tempdir) + class ProtectedFileTC(TestCase): def setUp(self): - self.rpath = join(DATA_DIR, 'write_protected_file.txt') - self.rwpath = join(DATA_DIR, 'normal_file.txt') + self.rpath = join(DATA_DIR, "write_protected_file.txt") + self.rwpath = join(DATA_DIR, "normal_file.txt") # Make sure rpath is not writable ! os.chmod(self.rpath, 33060) # Make sure rwpath is writable ! @@ -96,51 +98,53 @@ class ProtectedFileTC(TestCase): def test_mode_change(self): """tests that mode is changed when needed""" # test on non-writable file - #self.assertTrue(not os.access(self.rpath, os.W_OK)) + # self.assertTrue(not os.access(self.rpath, os.W_OK)) self.assertTrue(not os.stat(self.rpath).st_mode & S_IWRITE) - wp_file = ProtectedFile(self.rpath, 'w') + wp_file = ProtectedFile(self.rpath, "w") self.assertTrue(os.stat(self.rpath).st_mode & S_IWRITE) self.assertTrue(os.access(self.rpath, os.W_OK)) # test on writable-file self.assertTrue(os.stat(self.rwpath).st_mode & S_IWRITE) self.assertTrue(os.access(self.rwpath, os.W_OK)) - wp_file = ProtectedFile(self.rwpath, 'w') + wp_file = ProtectedFile(self.rwpath, "w") self.assertTrue(os.stat(self.rwpath).st_mode & S_IWRITE) self.assertTrue(os.access(self.rwpath, os.W_OK)) def test_restore_on_close(self): """tests original mode is restored on close""" # test on non-writable file - #self.assertTrue(not os.access(self.rpath, os.W_OK)) + # self.assertTrue(not os.access(self.rpath, os.W_OK)) self.assertTrue(not os.stat(self.rpath).st_mode & S_IWRITE) - ProtectedFile(self.rpath, 'w').close() - #self.assertTrue(not os.access(self.rpath, os.W_OK)) + ProtectedFile(self.rpath, "w").close() + # self.assertTrue(not os.access(self.rpath, os.W_OK)) self.assertTrue(not os.stat(self.rpath).st_mode & S_IWRITE) # test on writable-file self.assertTrue(os.access(self.rwpath, os.W_OK)) self.assertTrue(os.stat(self.rwpath).st_mode & S_IWRITE) - ProtectedFile(self.rwpath, 'w').close() + ProtectedFile(self.rwpath, "w").close() self.assertTrue(os.access(self.rwpath, os.W_OK)) self.assertTrue(os.stat(self.rwpath).st_mode & S_IWRITE) def test_mode_change_on_append(self): """tests that mode is changed when file is opened in 'a' mode""" - #self.assertTrue(not os.access(self.rpath, os.W_OK)) + # self.assertTrue(not os.access(self.rpath, os.W_OK)) self.assertTrue(not os.stat(self.rpath).st_mode & S_IWRITE) - wp_file = ProtectedFile(self.rpath, 'a') + wp_file = ProtectedFile(self.rpath, "a") self.assertTrue(os.access(self.rpath, os.W_OK)) self.assertTrue(os.stat(self.rpath).st_mode & S_IWRITE) wp_file.close() - #self.assertTrue(not os.access(self.rpath, os.W_OK)) + # self.assertTrue(not os.access(self.rpath, os.W_OK)) self.assertTrue(not os.stat(self.rpath).st_mode & S_IWRITE) if sys.version_info < (3, 0): + def load_tests(loader, tests, ignore): from logilab.common import fileutils + tests.addTests(doctest.DocTestSuite(fileutils)) return tests -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_graph.py b/test/test_graph.py index 9a2e8bc..03ed3ef 100644 --- a/test/test_graph.py +++ b/test/test_graph.py @@ -20,70 +20,70 @@ from logilab.common.testlib import TestCase, unittest_main from logilab.common.graph import get_cycles, has_path, ordered_nodes, UnorderableGraph -class getCyclesTC(TestCase): +class getCyclesTC(TestCase): def test_known0(self): - self.assertEqual(get_cycles({1:[2], 2:[3], 3:[1]}), [[1, 2, 3]]) + self.assertEqual(get_cycles({1: [2], 2: [3], 3: [1]}), [[1, 2, 3]]) def test_known1(self): - self.assertEqual(get_cycles({1:[2], 2:[3], 3:[1, 4], 4:[3]}), [[1, 2, 3], [3, 4]]) + self.assertEqual(get_cycles({1: [2], 2: [3], 3: [1, 4], 4: [3]}), [[1, 2, 3], [3, 4]]) def test_known2(self): - self.assertEqual(get_cycles({1:[2], 2:[3], 3:[0], 0:[]}), []) + self.assertEqual(get_cycles({1: [2], 2: [3], 3: [0], 0: []}), []) class hasPathTC(TestCase): - def test_direct_connection(self): - self.assertEqual(has_path({'A': ['B'], 'B': ['A']}, 'A', 'B'), ['B']) + self.assertEqual(has_path({"A": ["B"], "B": ["A"]}, "A", "B"), ["B"]) def test_indirect_connection(self): - self.assertEqual(has_path({'A': ['B'], 'B': ['A', 'C'], 'C': ['B']}, 'A', 'C'), ['B', 'C']) + self.assertEqual(has_path({"A": ["B"], "B": ["A", "C"], "C": ["B"]}, "A", "C"), ["B", "C"]) def test_no_connection(self): - self.assertEqual(has_path({'A': ['B'], 'B': ['A']}, 'A', 'C'), None) + self.assertEqual(has_path({"A": ["B"], "B": ["A"]}, "A", "C"), None) def test_cycle(self): - self.assertEqual(has_path({'A': ['A']}, 'A', 'B'), None) + self.assertEqual(has_path({"A": ["A"]}, "A", "B"), None) -class ordered_nodesTC(TestCase): +class ordered_nodesTC(TestCase): def test_one_item(self): - graph = {'a':[]} + graph = {"a": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a',)) + self.assertEqual(ordered, ("a",)) def test_single_dependency(self): - graph = {'a':['b'], 'b':[]} + graph = {"a": ["b"], "b": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a','b')) - graph = {'a':[], 'b':['a']} + self.assertEqual(ordered, ("a", "b")) + graph = {"a": [], "b": ["a"]} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('b','a')) + self.assertEqual(ordered, ("b", "a")) def test_two_items_no_dependency(self): - graph = {'a':[], 'b':[]} + graph = {"a": [], "b": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a','b')) + self.assertEqual(ordered, ("a", "b")) def test_three_items_no_dependency(self): - graph = {'a':[], 'b':[], 'c':[]} + graph = {"a": [], "b": [], "c": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a', 'b', 'c')) + self.assertEqual(ordered, ("a", "b", "c")) def test_three_items_one_dependency(self): - graph = {'a': ['c'], 'b': [], 'c':[]} + graph = {"a": ["c"], "b": [], "c": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a', 'b', 'c')) + self.assertEqual(ordered, ("a", "b", "c")) def test_three_items_two_dependencies(self): - graph = {'a': ['b'], 'b': ['c'], 'c':[]} + graph = {"a": ["b"], "b": ["c"], "c": []} ordered = ordered_nodes(graph) - self.assertEqual(ordered, ('a', 'b', 'c')) + self.assertEqual(ordered, ("a", "b", "c")) def test_bad_graph(self): - graph = {'a':['b']} + graph = {"a": ["b"]} self.assertRaises(UnorderableGraph, ordered_nodes, graph) + if __name__ == "__main__": unittest_main() diff --git a/test/test_interface.py b/test/test_interface.py index 1dbed7a..a3c20bf 100644 --- a/test/test_interface.py +++ b/test/test_interface.py @@ -18,31 +18,44 @@ from logilab.common.testlib import TestCase, unittest_main from logilab.common.interface import * -class IFace1(Interface): pass -class IFace2(Interface): pass -class IFace3(Interface): pass + +class IFace1(Interface): + pass + + +class IFace2(Interface): + pass + + +class IFace3(Interface): + pass class A(object): __implements__ = (IFace1,) -class B(A): pass +class B(A): + pass class C1(B): __implements__ = list(B.__implements__) + [IFace3] + class C2(B): __implements__ = B.__implements__ + (IFace2,) + class D(C1): __implements__ = () -class Z(object): pass -class ExtendTC(TestCase): +class Z(object): + pass + +class ExtendTC(TestCase): def setUp(self): global aimpl, c1impl, c2impl, dimpl aimpl = A.__implements__ @@ -73,9 +86,10 @@ class ExtendTC(TestCase): self.assertTrue(C1.__implements__ is c1impl) self.assertTrue(D.__implements__ is dimpl) - def test_nonregr_implements_baseinterface(self): - class SubIFace(IFace1): pass + class SubIFace(IFace1): + pass + class X(object): __implements__ = (SubIFace,) @@ -83,5 +97,5 @@ class ExtendTC(TestCase): self.assertTrue(IFace1.is_implemented_by(X)) -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_pytest.py b/test/test_pytest.py index 48e36ce..02a34d4 100644 --- a/test/test_pytest.py +++ b/test/test_pytest.py @@ -19,6 +19,7 @@ from os.path import join from logilab.common.testlib import TestCase, unittest_main from logilab.common.pytest import * + class ModuleFunctionTC(TestCase): def test_this_is_testdir(self): self.assertTrue(this_is_a_testdir("test")) @@ -82,5 +83,5 @@ class ModuleFunctionTC(TestCase): myfn() -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_shellutils.py b/test/test_shellutils.py index 49b06c7..8cb06ca 100644 --- a/test/test_shellutils.py +++ b/test/test_shellutils.py @@ -24,54 +24,96 @@ from unittest.mock import patch from logilab.common.testlib import TestCase, unittest_main -from logilab.common.shellutils import (globfind, find, ProgressBar, - RawInput) +from logilab.common.shellutils import globfind, find, ProgressBar, RawInput from logilab.common.compat import StringIO -DATA_DIR = join(dirname(abspath(__file__)), 'data', 'find_test') +DATA_DIR = join(dirname(abspath(__file__)), "data", "find_test") class FindTC(TestCase): def test_include(self): - files = set(find(DATA_DIR, '.py')) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['__init__.py', 'module.py', - 'module2.py', 'noendingnewline.py', - 'nonregr.py', join('sub', 'momo.py')]])) - files = set(find(DATA_DIR, ('.py',), blacklist=('sub',))) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['__init__.py', 'module.py', - 'module2.py', 'noendingnewline.py', - 'nonregr.py']])) + files = set(find(DATA_DIR, ".py")) + self.assertSetEqual( + files, + set( + [ + join(DATA_DIR, f) + for f in [ + "__init__.py", + "module.py", + "module2.py", + "noendingnewline.py", + "nonregr.py", + join("sub", "momo.py"), + ] + ] + ), + ) + files = set(find(DATA_DIR, (".py",), blacklist=("sub",))) + self.assertSetEqual( + files, + set( + [ + join(DATA_DIR, f) + for f in [ + "__init__.py", + "module.py", + "module2.py", + "noendingnewline.py", + "nonregr.py", + ] + ] + ), + ) def test_exclude(self): - files = set(find(DATA_DIR, ('.py', '.pyc'), exclude=True)) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['foo.txt', - 'newlines.txt', - 'normal_file.txt', - 'test.ini', - 'test1.msg', - 'test2.msg', - 'spam.txt', - join('sub', 'doc.txt'), - 'write_protected_file.txt', - ]])) + files = set(find(DATA_DIR, (".py", ".pyc"), exclude=True)) + self.assertSetEqual( + files, + set( + [ + join(DATA_DIR, f) + for f in [ + "foo.txt", + "newlines.txt", + "normal_file.txt", + "test.ini", + "test1.msg", + "test2.msg", + "spam.txt", + join("sub", "doc.txt"), + "write_protected_file.txt", + ] + ] + ), + ) def test_globfind(self): - files = set(globfind(DATA_DIR, '*.py')) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['__init__.py', 'module.py', - 'module2.py', 'noendingnewline.py', - 'nonregr.py', join('sub', 'momo.py')]])) - files = set(globfind(DATA_DIR, 'mo*.py')) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['module.py', 'module2.py', - join('sub', 'momo.py')]])) - files = set(globfind(DATA_DIR, 'mo*.py', blacklist=('sub',))) - self.assertSetEqual(files, - set([join(DATA_DIR, f) for f in ['module.py', 'module2.py']])) + files = set(globfind(DATA_DIR, "*.py")) + self.assertSetEqual( + files, + set( + [ + join(DATA_DIR, f) + for f in [ + "__init__.py", + "module.py", + "module2.py", + "noendingnewline.py", + "nonregr.py", + join("sub", "momo.py"), + ] + ] + ), + ) + files = set(globfind(DATA_DIR, "mo*.py")) + self.assertSetEqual( + files, + set([join(DATA_DIR, f) for f in ["module.py", "module2.py", join("sub", "momo.py")]]), + ) + files = set(globfind(DATA_DIR, "mo*.py", blacklist=("sub",))) + self.assertSetEqual(files, set([join(DATA_DIR, f) for f in ["module.py", "module2.py"]])) class ProgressBarTC(TestCase): @@ -79,9 +121,11 @@ class ProgressBarTC(TestCase): pgb_stream = StringIO() expected_stream = StringIO() pgb = ProgressBar(20, stream=pgb_stream) - self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) # nothing print before refresh + self.assertEqual( + pgb_stream.getvalue(), expected_stream.getvalue() + ) # nothing print before refresh pgb.refresh() - expected_stream.write("\r["+' '*20+"]") + expected_stream.write("\r[" + " " * 20 + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) def test_refresh_g_size(self): @@ -89,7 +133,7 @@ class ProgressBarTC(TestCase): expected_stream = StringIO() pgb = ProgressBar(20, 35, stream=pgb_stream) pgb.refresh() - expected_stream.write("\r["+' '*35+"]") + expected_stream.write("\r[" + " " * 35 + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) def test_refresh_l_size(self): @@ -97,27 +141,27 @@ class ProgressBarTC(TestCase): expected_stream = StringIO() pgb = ProgressBar(20, 3, stream=pgb_stream) pgb.refresh() - expected_stream.write("\r["+' '*3+"]") + expected_stream.write("\r[" + " " * 3 + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) - def _update_test(self, nbops, expected, size = None): + def _update_test(self, nbops, expected, size=None): pgb_stream = StringIO() expected_stream = StringIO() if size is None: pgb = ProgressBar(nbops, stream=pgb_stream) - size=20 + size = 20 else: pgb = ProgressBar(nbops, size, stream=pgb_stream) last = 0 for round in expected: - if not hasattr(round, '__int__'): + if not hasattr(round, "__int__"): dots, update = round else: dots, update = round, None pgb.update() if update or (update is None and dots != last): last = dots - expected_stream.write("\r["+('='*dots)+(' '*(size-dots))+"]") + expected_stream.write("\r[" + ("=" * dots) + (" " * (size - dots)) + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) def test_default(self): @@ -125,16 +169,20 @@ class ProgressBarTC(TestCase): def test_nbops_gt_size(self): """Test the progress bar for nbops > size""" + def half(total): - for counter in range(1, total+1): + for counter in range(1, total + 1): yield counter // 2 + self._update_test(40, half(40)) def test_nbops_lt_size(self): """Test the progress bar for nbops < size""" + def double(total): - for counter in range(1, total+1): + for counter in range(1, total + 1): yield counter * 2 + self._update_test(10, double(10)) def test_nbops_nomul_size(self): @@ -147,30 +195,29 @@ class ProgressBarTC(TestCase): def test_update_exact(self): pgb_stream = StringIO() expected_stream = StringIO() - size=20 + size = 20 pgb = ProgressBar(100, size, stream=pgb_stream) last = 0 for dots in range(10, 105, 15): pgb.update(dots, exact=True) dots //= 5 - expected_stream.write("\r["+('='*dots)+(' '*(size-dots))+"]") + expected_stream.write("\r[" + ("=" * dots) + (" " * (size - dots)) + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) def test_update_relative(self): pgb_stream = StringIO() expected_stream = StringIO() - size=20 + size = 20 pgb = ProgressBar(100, size, stream=pgb_stream) last = 0 for dots in range(5, 105, 5): pgb.update(5, exact=False) dots //= 5 - expected_stream.write("\r["+('='*dots)+(' '*(size-dots))+"]") + expected_stream.write("\r[" + ("=" * dots) + (" " * (size - dots)) + "]") self.assertEqual(pgb_stream.getvalue(), expected_stream.getvalue()) class RawInputTC(TestCase): - def auto_input(self, *args): self.input_args = args return self.input_answer @@ -180,61 +227,62 @@ class RawInputTC(TestCase): self.qa = RawInput(self.auto_input, null_printer) def test_ask_using_builtin_input(self): - with patch('builtins.input', return_value='no'): + with patch("builtins.input", return_value="no"): qa = RawInput() - answer = qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'no') + answer = qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "no") def test_ask_default(self): - self.input_answer = '' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'yes') - self.input_answer = ' ' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'yes') + self.input_answer = "" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "yes") + self.input_answer = " " + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "yes") def test_ask_case(self): - self.input_answer = 'no' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'no') - self.input_answer = 'No' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'no') - self.input_answer = 'NO' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'no') - self.input_answer = 'nO' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'no') - self.input_answer = 'YES' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(answer, 'yes') + self.input_answer = "no" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "no") + self.input_answer = "No" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "no") + self.input_answer = "NO" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "no") + self.input_answer = "nO" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "no") + self.input_answer = "YES" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(answer, "yes") def test_ask_prompt(self): - self.input_answer = '' - answer = self.qa.ask('text', ('yes', 'no'), 'yes') - self.assertEqual(self.input_args[0], 'text [Y(es)/n(o)]: ') - answer = self.qa.ask('text', ('y', 'n'), 'y') - self.assertEqual(self.input_args[0], 'text [Y/n]: ') - answer = self.qa.ask('text', ('n', 'y'), 'y') - self.assertEqual(self.input_args[0], 'text [n/Y]: ') - answer = self.qa.ask('text', ('yes', 'no', 'maybe', '1'), 'yes') - self.assertEqual(self.input_args[0], 'text [Y(es)/n(o)/m(aybe)/1]: ') + self.input_answer = "" + answer = self.qa.ask("text", ("yes", "no"), "yes") + self.assertEqual(self.input_args[0], "text [Y(es)/n(o)]: ") + answer = self.qa.ask("text", ("y", "n"), "y") + self.assertEqual(self.input_args[0], "text [Y/n]: ") + answer = self.qa.ask("text", ("n", "y"), "y") + self.assertEqual(self.input_args[0], "text [n/Y]: ") + answer = self.qa.ask("text", ("yes", "no", "maybe", "1"), "yes") + self.assertEqual(self.input_args[0], "text [Y(es)/n(o)/m(aybe)/1]: ") def test_ask_ambiguous(self): - self.input_answer = 'y' - self.assertRaises(Exception, self.qa.ask, 'text', ('yes', 'yep'), 'yes') + self.input_answer = "y" + self.assertRaises(Exception, self.qa.ask, "text", ("yes", "yep"), "yes") def test_confirm(self): - self.input_answer = 'y' - self.assertEqual(self.qa.confirm('Say yes'), True) - self.assertEqual(self.qa.confirm('Say yes', default_is_yes=False), True) - self.input_answer = 'n' - self.assertEqual(self.qa.confirm('Say yes'), False) - self.assertEqual(self.qa.confirm('Say yes', default_is_yes=False), False) - self.input_answer = '' - self.assertEqual(self.qa.confirm('Say default'), True) - self.assertEqual(self.qa.confirm('Say default', default_is_yes=False), False) - -if __name__ == '__main__': + self.input_answer = "y" + self.assertEqual(self.qa.confirm("Say yes"), True) + self.assertEqual(self.qa.confirm("Say yes", default_is_yes=False), True) + self.input_answer = "n" + self.assertEqual(self.qa.confirm("Say yes"), False) + self.assertEqual(self.qa.confirm("Say yes", default_is_yes=False), False) + self.input_answer = "" + self.assertEqual(self.qa.confirm("Say default"), True) + self.assertEqual(self.qa.confirm("Say default", default_is_yes=False), False) + + +if __name__ == "__main__": unittest_main() diff --git a/test/test_table.py b/test/test_table.py index 0c40a7c..5c0ac19 100644 --- a/test/test_table.py +++ b/test/test_table.py @@ -25,8 +25,16 @@ import os from logilab.common.compat import StringIO from logilab.common.testlib import TestCase, unittest_main -from logilab.common.table import Table, TableStyleSheet, DocbookTableWriter, \ - DocbookRenderer, TableStyle, TableWriter, TableCellRenderer +from logilab.common.table import ( + Table, + TableStyleSheet, + DocbookTableWriter, + DocbookRenderer, + TableStyle, + TableWriter, + TableCellRenderer, +) + class TableTC(TestCase): """Table TestCase class""" @@ -36,12 +44,12 @@ class TableTC(TestCase): # from logilab.common import table # reload(table) self.table = Table() - self.table.create_rows(['row1', 'row2', 'row3']) - self.table.create_columns(['col1', 'col2']) + self.table.create_rows(["row1", "row2", "row3"]) + self.table.create_columns(["col1", "col2"]) def test_valeur_scalaire(self): tab = Table() - tab.create_columns(['col1']) + tab.create_columns(["col1"]) tab.append_row([1]) self.assertEqual(tab, [[1]]) tab.append_row([2]) @@ -50,13 +58,13 @@ class TableTC(TestCase): def test_valeur_ligne(self): tab = Table() - tab.create_columns(['col1', 'col2']) + tab.create_columns(["col1", "col2"]) tab.append_row([1, 2]) self.assertEqual(tab, [[1, 2]]) def test_valeur_colonne(self): tab = Table() - tab.create_columns(['col1']) + tab.create_columns(["col1"]) tab.append_row([1]) tab.append_row([2]) self.assertEqual(tab, [[1], [2]]) @@ -77,25 +85,25 @@ class TableTC(TestCase): """tests Table.get_rows()""" self.assertEqual(self.table, [[0, 0], [0, 0], [0, 0]]) self.assertEqual(self.table[:], [[0, 0], [0, 0], [0, 0]]) - self.table.insert_column(1, range(3), 'supp') + self.table.insert_column(1, range(3), "supp") self.assertEqual(self.table, [[0, 0, 0], [0, 1, 0], [0, 2, 0]]) self.assertEqual(self.table[:], [[0, 0, 0], [0, 1, 0], [0, 2, 0]]) def test_get_cells(self): - self.table.insert_column(1, range(3), 'supp') + self.table.insert_column(1, range(3), "supp") self.assertEqual(self.table[0, 1], 0) self.assertEqual(self.table[1, 1], 1) self.assertEqual(self.table[2, 1], 2) - self.assertEqual(self.table['row1', 'supp'], 0) - self.assertEqual(self.table['row2', 'supp'], 1) - self.assertEqual(self.table['row3', 'supp'], 2) - self.assertRaises(KeyError, self.table.__getitem__, ('row1', 'foo')) - self.assertRaises(KeyError, self.table.__getitem__, ('foo', 'bar')) + self.assertEqual(self.table["row1", "supp"], 0) + self.assertEqual(self.table["row2", "supp"], 1) + self.assertEqual(self.table["row3", "supp"], 2) + self.assertRaises(KeyError, self.table.__getitem__, ("row1", "foo")) + self.assertRaises(KeyError, self.table.__getitem__, ("foo", "bar")) def test_shape(self): """tests table shape""" self.assertEqual(self.table.shape, (3, 2)) - self.table.insert_column(1, range(3), 'supp') + self.table.insert_column(1, range(3), "supp") self.assertEqual(self.table.shape, (3, 3)) def test_set_column(self): @@ -109,33 +117,33 @@ class TableTC(TestCase): def test_set_column_by_id(self): """Tests that table.set_column_by_id() works fine. """ - self.table.set_column_by_id('col1', range(3)) + self.table.set_column_by_id("col1", range(3)) self.assertEqual(self.table[0, 0], 0) self.assertEqual(self.table[1, 0], 1) self.assertEqual(self.table[2, 0], 2) - self.assertRaises(KeyError, self.table.set_column_by_id, 'col123', range(3)) + self.assertRaises(KeyError, self.table.set_column_by_id, "col123", range(3)) def test_cells_ids(self): """tests that we can access cells by giving row/col ids""" - self.assertRaises(KeyError, self.table.set_cell_by_ids, 'row12', 'col1', 12) - self.assertRaises(KeyError, self.table.set_cell_by_ids, 'row1', 'col12', 12) + self.assertRaises(KeyError, self.table.set_cell_by_ids, "row12", "col1", 12) + self.assertRaises(KeyError, self.table.set_cell_by_ids, "row1", "col12", 12) self.assertEqual(self.table[0, 0], 0) - self.table.set_cell_by_ids('row1', 'col1', 'DATA') - self.assertEqual(self.table[0, 0], 'DATA') - self.assertRaises(KeyError, self.table.set_row_by_id, 'row12', []) - self.table.set_row_by_id('row1', ['1.0', '1.1']) - self.assertEqual(self.table[0, 0], '1.0') + self.table.set_cell_by_ids("row1", "col1", "DATA") + self.assertEqual(self.table[0, 0], "DATA") + self.assertRaises(KeyError, self.table.set_row_by_id, "row12", []) + self.table.set_row_by_id("row1", ["1.0", "1.1"]) + self.assertEqual(self.table[0, 0], "1.0") def test_insert_row(self): """tests a row insertion""" - tmp_data = ['tmp1', 'tmp2'] - self.table.insert_row(1, tmp_data, 'tmprow') + tmp_data = ["tmp1", "tmp2"] + self.table.insert_row(1, tmp_data, "tmprow") self.assertEqual(self.table[1], tmp_data) - self.assertEqual(self.table['tmprow'], tmp_data) - self.table.delete_row_by_id('tmprow') - self.assertRaises(KeyError, self.table.delete_row_by_id, 'tmprow') + self.assertEqual(self.table["tmprow"], tmp_data) + self.table.delete_row_by_id("tmprow") + self.assertRaises(KeyError, self.table.delete_row_by_id, "tmprow") self.assertEqual(self.table[1], [0, 0]) - self.assertRaises(KeyError, self.table.__getitem__, 'tmprow') + self.assertRaises(KeyError, self.table.__getitem__, "tmprow") def test_get_column(self): """Tests that table.get_column() works fine. @@ -143,7 +151,7 @@ class TableTC(TestCase): self.table.set_cell(0, 1, 12) self.table.set_cell(2, 1, 13) self.assertEqual(self.table[:, 1], [12, 0, 13]) - self.assertEqual(self.table[:, 'col2'], [12, 0, 13]) + self.assertEqual(self.table[:, "col2"], [12, 0, 13]) def test_get_columns(self): """Tests if table.get_columns() works fine. @@ -157,26 +165,25 @@ class TableTC(TestCase): """ self.table.insert_column(1, range(3), "inserted_column") self.assertEqual(self.table[:, 1], [0, 1, 2]) - self.assertEqual(self.table.col_names, - ['col1', 'inserted_column', 'col2']) + self.assertEqual(self.table.col_names, ["col1", "inserted_column", "col2"]) def test_delete_column(self): """Tests that table.delete_column() works fine. """ self.table.delete_column(1) - self.assertEqual(self.table.col_names, ['col1']) + self.assertEqual(self.table.col_names, ["col1"]) self.assertEqual(self.table[:, 0], [0, 0, 0]) - self.assertRaises(KeyError, self.table.delete_column_by_id, 'col2') - self.table.delete_column_by_id('col1') + self.assertRaises(KeyError, self.table.delete_column_by_id, "col2") + self.table.delete_column_by_id("col1") self.assertEqual(self.table.col_names, []) def test_transpose(self): """Tests that table.transpose() works fine. """ - self.table.append_column(range(5, 8), 'col3') + self.table.append_column(range(5, 8), "col3") ttable = self.table.transpose() - self.assertEqual(ttable.row_names, ['col1', 'col2', 'col3']) - self.assertEqual(ttable.col_names, ['row1', 'row2', 'row3']) + self.assertEqual(ttable.row_names, ["col1", "col2", "col3"]) + self.assertEqual(ttable.col_names, ["row1", "row2", "row3"]) self.assertEqual(ttable.data, [[0, 0, 0], [0, 0, 0], [5, 6, 7]]) def test_sort_table(self): @@ -185,22 +192,22 @@ class TableTC(TestCase): self.table.set_column(0, [3, 1, 2]) self.table.set_column(1, [1, 2, 3]) self.table.sort_by_column_index(0) - self.assertEqual(self.table.row_names, ['row2', 'row3', 'row1']) + self.assertEqual(self.table.row_names, ["row2", "row3", "row1"]) self.assertEqual(self.table.data, [[1, 2], [2, 3], [3, 1]]) - self.table.sort_by_column_index(1, 'desc') - self.assertEqual(self.table.row_names, ['row3', 'row2', 'row1']) + self.table.sort_by_column_index(1, "desc") + self.assertEqual(self.table.row_names, ["row3", "row2", "row1"]) self.assertEqual(self.table.data, [[2, 3], [1, 2], [3, 1]]) def test_sort_by_id(self): """tests sort_by_column_id()""" - self.table.set_column_by_id('col1', [3, 1, 2]) - self.table.set_column_by_id('col2', [1, 2, 3]) - self.table.sort_by_column_id('col1') - self.assertRaises(KeyError, self.table.sort_by_column_id, 'col123') - self.assertEqual(self.table.row_names, ['row2', 'row3', 'row1']) + self.table.set_column_by_id("col1", [3, 1, 2]) + self.table.set_column_by_id("col2", [1, 2, 3]) + self.table.sort_by_column_id("col1") + self.assertRaises(KeyError, self.table.sort_by_column_id, "col123") + self.assertEqual(self.table.row_names, ["row2", "row3", "row1"]) self.assertEqual(self.table.data, [[1, 2], [2, 3], [3, 1]]) - self.table.sort_by_column_id('col2', 'desc') - self.assertEqual(self.table.row_names, ['row3', 'row2', 'row1']) + self.table.sort_by_column_id("col2", "desc") + self.assertEqual(self.table.row_names, ["row3", "row2", "row1"]) self.assertEqual(self.table.data, [[2, 3], [1, 2], [3, 1]]) def test_pprint(self): @@ -211,67 +218,74 @@ class TableTC(TestCase): class GroupByTC(TestCase): """specific test suite for groupby()""" + def setUp(self): t = Table() - t.create_columns(['date', 'res', 'task', 'usage']) - t.append_row(['date1', 'ing1', 'task1', 0.3]) - t.append_row(['date1', 'ing2', 'task2', 0.3]) - t.append_row(['date2', 'ing3', 'task3', 0.3]) - t.append_row(['date3', 'ing4', 'task2', 0.3]) - t.append_row(['date1', 'ing1', 'task3', 0.3]) - t.append_row(['date3', 'ing1', 'task3', 0.3]) + t.create_columns(["date", "res", "task", "usage"]) + t.append_row(["date1", "ing1", "task1", 0.3]) + t.append_row(["date1", "ing2", "task2", 0.3]) + t.append_row(["date2", "ing3", "task3", 0.3]) + t.append_row(["date3", "ing4", "task2", 0.3]) + t.append_row(["date1", "ing1", "task3", 0.3]) + t.append_row(["date3", "ing1", "task3", 0.3]) self.table = t def test_single_groupby(self): """tests groupby() on several columns""" - grouped = self.table.groupby('date') + grouped = self.table.groupby("date") self.assertEqual(len(grouped), 3) - self.assertEqual(len(grouped['date1']), 3) - self.assertEqual(len(grouped['date2']), 1) - self.assertEqual(len(grouped['date3']), 2) - self.assertEqual(grouped['date1'], [ - ('date1', 'ing1', 'task1', 0.3), - ('date1', 'ing2', 'task2', 0.3), - ('date1', 'ing1', 'task3', 0.3), - ]) - self.assertEqual(grouped['date2'], [('date2', 'ing3', 'task3', 0.3)]) - self.assertEqual(grouped['date3'], [ - ('date3', 'ing4', 'task2', 0.3), - ('date3', 'ing1', 'task3', 0.3), - ]) + self.assertEqual(len(grouped["date1"]), 3) + self.assertEqual(len(grouped["date2"]), 1) + self.assertEqual(len(grouped["date3"]), 2) + self.assertEqual( + grouped["date1"], + [ + ("date1", "ing1", "task1", 0.3), + ("date1", "ing2", "task2", 0.3), + ("date1", "ing1", "task3", 0.3), + ], + ) + self.assertEqual(grouped["date2"], [("date2", "ing3", "task3", 0.3)]) + self.assertEqual( + grouped["date3"], [("date3", "ing4", "task2", 0.3), ("date3", "ing1", "task3", 0.3),] + ) def test_multiple_groupby(self): """tests groupby() on several columns""" - grouped = self.table.groupby('date', 'task') + grouped = self.table.groupby("date", "task") self.assertEqual(len(grouped), 3) - self.assertEqual(len(grouped['date1']), 3) - self.assertEqual(len(grouped['date2']), 1) - self.assertEqual(len(grouped['date3']), 2) - self.assertEqual(grouped['date1']['task1'], [('date1', 'ing1', 'task1', 0.3)]) - self.assertEqual(grouped['date2']['task3'], [('date2', 'ing3', 'task3', 0.3)]) - self.assertEqual(grouped['date3']['task2'], [('date3', 'ing4', 'task2', 0.3)]) - date3 = grouped['date3'] - self.assertRaises(KeyError, date3.__getitem__, 'task1') - + self.assertEqual(len(grouped["date1"]), 3) + self.assertEqual(len(grouped["date2"]), 1) + self.assertEqual(len(grouped["date3"]), 2) + self.assertEqual(grouped["date1"]["task1"], [("date1", "ing1", "task1", 0.3)]) + self.assertEqual(grouped["date2"]["task3"], [("date2", "ing3", "task3", 0.3)]) + self.assertEqual(grouped["date3"]["task2"], [("date3", "ing4", "task2", 0.3)]) + date3 = grouped["date3"] + self.assertRaises(KeyError, date3.__getitem__, "task1") def test_select(self): """tests Table.select() method""" - rows = self.table.select('date', 'date1') - self.assertEqual(rows, [ - ('date1', 'ing1', 'task1', 0.3), - ('date1', 'ing2', 'task2', 0.3), - ('date1', 'ing1', 'task3', 0.3), - ]) + rows = self.table.select("date", "date1") + self.assertEqual( + rows, + [ + ("date1", "ing1", "task1", 0.3), + ("date1", "ing2", "task2", 0.3), + ("date1", "ing1", "task3", 0.3), + ], + ) + class TableStyleSheetTC(TestCase): """The Stylesheet test case """ + def setUp(self): """Builds a simple table to test the stylesheet """ self.table = Table() - self.table.create_row('row1') - self.table.create_columns(['a', 'b', 'c']) + self.table.create_row("row1") + self.table.create_columns(["a", "b", "c"]) self.stylesheet = TableStyleSheet() # We don't want anything to be printed self.stdout_backup = sys.stdout @@ -283,20 +297,20 @@ class TableStyleSheetTC(TestCase): def test_add_rule(self): """Tests that the regex pattern works as expected. """ - rule = '0_2 = sqrt(0_0**2 + 0_1**2)' + rule = "0_2 = sqrt(0_0**2 + 0_1**2)" self.stylesheet.add_rule(rule) self.table.set_row(0, [3, 4, 0]) self.table.apply_stylesheet(self.stylesheet) self.assertEqual(self.table[0], [3, 4, 5]) self.assertEqual(len(self.stylesheet.rules), 1) - self.stylesheet.add_rule('some bad rule with bad syntax') + self.stylesheet.add_rule("some bad rule with bad syntax") self.assertEqual(len(self.stylesheet.rules), 1, "Ill-formed rule mustn't be added") self.assertEqual(len(self.stylesheet.instructions), 1, "Ill-formed rule mustn't be added") def test_stylesheet_init(self): """tests Stylesheet.__init__""" - rule = '0_2 = 1' - sheet = TableStyleSheet([rule, 'bad rule']) + rule = "0_2 = 1" + sheet = TableStyleSheet([rule, "bad rule"]) self.assertEqual(len(sheet.rules), 1, "Ill-formed rule mustn't be added") self.assertEqual(len(sheet.instructions), 1, "Ill-formed rule mustn't be added") @@ -309,7 +323,6 @@ class TableStyleSheetTC(TestCase): val = self.table[0, 2] self.assertEqual(int(val), 15) - def test_rowsum_rule(self): """Tests that add_rowsum_rule works as expected """ @@ -319,116 +332,114 @@ class TableStyleSheetTC(TestCase): val = self.table[0, 2] self.assertEqual(val, 30) - def test_colavg_rule(self): """Tests that add_colavg_rule works as expected """ self.table.set_row(0, [10, 20, 0]) - self.table.append_row([12, 8, 3], 'row2') - self.table.create_row('row3') + self.table.append_row([12, 8, 3], "row2") + self.table.create_row("row3") self.stylesheet.add_colavg_rule((2, 0), 0, 0, 1) self.table.apply_stylesheet(self.stylesheet) val = self.table[2, 0] self.assertEqual(int(val), 11) - def test_colsum_rule(self): """Tests that add_colsum_rule works as expected """ self.table.set_row(0, [10, 20, 0]) - self.table.append_row([12, 8, 3], 'row2') - self.table.create_row('row3') + self.table.append_row([12, 8, 3], "row2") + self.table.create_row("row3") self.stylesheet.add_colsum_rule((2, 0), 0, 0, 1) self.table.apply_stylesheet(self.stylesheet) val = self.table[2, 0] self.assertEqual(val, 22) - class TableStyleTC(TestCase): """Test suite for TableSuite""" + def setUp(self): self.table = Table() - self.table.create_rows(['row1', 'row2', 'row3']) - self.table.create_columns(['col1', 'col2']) + self.table.create_rows(["row1", "row2", "row3"]) + self.table.create_columns(["col1", "col2"]) self.style = TableStyle(self.table) - self._tested_attrs = (('size', '1*'), - ('alignment', 'right'), - ('unit', '')) + self._tested_attrs = (("size", "1*"), ("alignment", "right"), ("unit", "")) def test_getset(self): """tests style's get and set methods""" for attrname, default_value in self._tested_attrs: - getter = getattr(self.style, 'get_%s' % attrname) - setter = getattr(self.style, 'set_%s' % attrname) - self.assertRaises(KeyError, getter, 'badcol') - self.assertEqual(getter('col1'), default_value) - setter('FOO', 'col1') - self.assertEqual(getter('col1'), 'FOO') + getter = getattr(self.style, "get_%s" % attrname) + setter = getattr(self.style, "set_%s" % attrname) + self.assertRaises(KeyError, getter, "badcol") + self.assertEqual(getter("col1"), default_value) + setter("FOO", "col1") + self.assertEqual(getter("col1"), "FOO") def test_getset_index(self): """tests style's get and set by index methods""" for attrname, default_value in self._tested_attrs: - getter = getattr(self.style, 'get_%s' % attrname) - setter = getattr(self.style, 'set_%s' % attrname) - igetter = getattr(self.style, 'get_%s_by_index' % attrname) - isetter = getattr(self.style, 'set_%s_by_index' % attrname) - self.assertEqual(getter('__row_column__'), default_value) - isetter('FOO', 0) - self.assertEqual(getter('__row_column__'), 'FOO') - self.assertEqual(igetter(0), 'FOO') - self.assertEqual(getter('col1'), default_value) - isetter('FOO', 1) - self.assertEqual(getter('col1'), 'FOO') - self.assertEqual(igetter(1), 'FOO') + getter = getattr(self.style, "get_%s" % attrname) + setter = getattr(self.style, "set_%s" % attrname) + igetter = getattr(self.style, "get_%s_by_index" % attrname) + isetter = getattr(self.style, "set_%s_by_index" % attrname) + self.assertEqual(getter("__row_column__"), default_value) + isetter("FOO", 0) + self.assertEqual(getter("__row_column__"), "FOO") + self.assertEqual(igetter(0), "FOO") + self.assertEqual(getter("col1"), default_value) + isetter("FOO", 1) + self.assertEqual(getter("col1"), "FOO") + self.assertEqual(igetter(1), "FOO") class RendererTC(TestCase): """Test suite for DocbookRenderer""" + def setUp(self): - self.renderer = DocbookRenderer(alignment = True) + self.renderer = DocbookRenderer(alignment=True) self.table = Table() - self.table.create_rows(['row1', 'row2', 'row3']) - self.table.create_columns(['col1', 'col2']) + self.table.create_rows(["row1", "row2", "row3"]) + self.table.create_columns(["col1", "col2"]) self.style = TableStyle(self.table) self.base_renderer = TableCellRenderer() def test_cell_content(self): """test how alignment is rendered""" - entry_xml = self.renderer._render_cell_content('data', self.style, 1) + entry_xml = self.renderer._render_cell_content("data", self.style, 1) self.assertEqual(entry_xml, "<entry align='right'>data</entry>\n") - self.style.set_alignment_by_index('left', 1) - entry_xml = self.renderer._render_cell_content('data', self.style, 1) + self.style.set_alignment_by_index("left", 1) + entry_xml = self.renderer._render_cell_content("data", self.style, 1) self.assertEqual(entry_xml, "<entry align='left'>data</entry>\n") def test_default_content_rendering(self): """tests that default rendering just prints the cell's content""" - rendered_cell = self.base_renderer._render_cell_content('data', self.style, 1) + rendered_cell = self.base_renderer._render_cell_content("data", self.style, 1) self.assertEqual(rendered_cell, "data") def test_replacement_char(self): """tests that 0 is replaced when asked for""" cell_content = self.base_renderer._make_cell_content(0, self.style, 1) self.assertEqual(cell_content, 0) - self.base_renderer.properties['skip_zero'] = '---' + self.base_renderer.properties["skip_zero"] = "---" cell_content = self.base_renderer._make_cell_content(0, self.style, 1) - self.assertEqual(cell_content, '---') + self.assertEqual(cell_content, "---") def test_unit(self): """tests if units are added""" - self.base_renderer.properties['units'] = True - self.style.set_unit_by_index('EUR', 1) + self.base_renderer.properties["units"] = True + self.style.set_unit_by_index("EUR", 1) cell_content = self.base_renderer._make_cell_content(12, self.style, 1) - self.assertEqual(cell_content, '12 EUR') + self.assertEqual(cell_content, "12 EUR") class DocbookTableWriterTC(TestCase): """TestCase for table's writer""" + def setUp(self): self.stream = StringIO() self.table = Table() - self.table.create_rows(['row1', 'row2', 'row3']) - self.table.create_columns(['col1', 'col2']) + self.table.create_rows(["row1", "row2", "row3"]) + self.table.create_columns(["col1", "col2"]) self.writer = DocbookTableWriter(self.stream, self.table, None) self.writer.set_renderer(DocbookRenderer()) @@ -442,5 +453,5 @@ class DocbookTableWriterTC(TestCase): self.assertRaises(NotImplementedError, writer.write_table) -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_taskqueue.py b/test/test_taskqueue.py index d8b6a9e..3e49ade 100644 --- a/test/test_taskqueue.py +++ b/test/test_taskqueue.py @@ -19,53 +19,53 @@ from logilab.common.testlib import TestCase, unittest_main from logilab.common.tasksqueue import * -class TaskTC(TestCase): +class TaskTC(TestCase): def test_eq(self): - self.assertFalse(Task('t1') == Task('t2')) - self.assertTrue(Task('t1') == Task('t1')) + self.assertFalse(Task("t1") == Task("t2")) + self.assertTrue(Task("t1") == Task("t1")) def test_cmp(self): - self.assertTrue(Task('t1', LOW) < Task('t2', MEDIUM)) - self.assertFalse(Task('t1', LOW) > Task('t2', MEDIUM)) - self.assertTrue(Task('t1', HIGH) > Task('t2', MEDIUM)) - self.assertFalse(Task('t1', HIGH) < Task('t2', MEDIUM)) + self.assertTrue(Task("t1", LOW) < Task("t2", MEDIUM)) + self.assertFalse(Task("t1", LOW) > Task("t2", MEDIUM)) + self.assertTrue(Task("t1", HIGH) > Task("t2", MEDIUM)) + self.assertFalse(Task("t1", HIGH) < Task("t2", MEDIUM)) class PrioritizedTasksQueueTC(TestCase): - def test_priority(self): queue = PrioritizedTasksQueue() - queue.put(Task('t1')) - queue.put(Task('t2', MEDIUM)) - queue.put(Task('t3', HIGH)) - queue.put(Task('t4', LOW)) - self.assertEqual(queue.get().id, 't3') - self.assertEqual(queue.get().id, 't2') - self.assertEqual(queue.get().id, 't1') - self.assertEqual(queue.get().id, 't4') + queue.put(Task("t1")) + queue.put(Task("t2", MEDIUM)) + queue.put(Task("t3", HIGH)) + queue.put(Task("t4", LOW)) + self.assertEqual(queue.get().id, "t3") + self.assertEqual(queue.get().id, "t2") + self.assertEqual(queue.get().id, "t1") + self.assertEqual(queue.get().id, "t4") def test_remove_equivalent(self): queue = PrioritizedTasksQueue() - queue.put(Task('t1')) - queue.put(Task('t2', MEDIUM)) - queue.put(Task('t1', HIGH)) - queue.put(Task('t3', MEDIUM)) - queue.put(Task('t2', MEDIUM)) + queue.put(Task("t1")) + queue.put(Task("t2", MEDIUM)) + queue.put(Task("t1", HIGH)) + queue.put(Task("t3", MEDIUM)) + queue.put(Task("t2", MEDIUM)) self.assertEqual(queue.qsize(), 3) - self.assertEqual(queue.get().id, 't1') - self.assertEqual(queue.get().id, 't2') - self.assertEqual(queue.get().id, 't3') + self.assertEqual(queue.get().id, "t1") + self.assertEqual(queue.get().id, "t2") + self.assertEqual(queue.get().id, "t3") self.assertEqual(queue.qsize(), 0) def test_remove(self): queue = PrioritizedTasksQueue() - queue.put(Task('t1')) - queue.put(Task('t2')) - queue.put(Task('t3')) - queue.remove('t2') - self.assertEqual([t.id for t in queue], ['t3', 't1']) - self.assertRaises(ValueError, queue.remove, 't4') + queue.put(Task("t1")) + queue.put(Task("t2")) + queue.put(Task("t3")) + queue.remove("t2") + self.assertEqual([t.id for t in queue], ["t3", "t1"]) + self.assertRaises(ValueError, queue.remove, "t4") + -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_testlib.py b/test/test_testlib.py index d26f2a6..8f95711 100644 --- a/test/test_testlib.py +++ b/test/test_testlib.py @@ -31,10 +31,21 @@ except NameError: __file__ = sys.argv[0] from logilab.common.compat import StringIO -from logilab.common.testlib import (unittest, TestSuite, unittest_main, Tags, - TestCase, mock_object, create_files, InnerTest, with_tempdir, tag, - require_version, require_module) -from logilab.common.pytest import SkipAwareTextTestRunner, NonStrictTestLoader +from logilab.common.testlib import ( + unittest, + TestSuite, + unittest_main, + Tags, + TestCase, + mock_object, + create_files, + InnerTest, + with_tempdir, + tag, + require_version, + require_module, +) +from logilab.common.pytest import SkipAwareTextTestRunner, NonStrictTestLoader class MockTestCase(TestCase): @@ -45,39 +56,38 @@ class MockTestCase(TestCase): def fail(self, msg): raise AssertionError(msg) -class UtilTC(TestCase): +class UtilTC(TestCase): def test_mockobject(self): - obj = mock_object(foo='bar', baz='bam') - self.assertEqual(obj.foo, 'bar') - self.assertEqual(obj.baz, 'bam') + obj = mock_object(foo="bar", baz="bam") + self.assertEqual(obj.foo, "bar") + self.assertEqual(obj.baz, "bam") def test_create_files(self): chroot = tempfile.mkdtemp() path_to = lambda path: join(chroot, path) dircontent = lambda path: sorted(os.listdir(join(chroot, path))) try: - self.assertFalse(isdir(path_to('a/'))) - create_files(['a/b/foo.py', 'a/b/c/', 'a/b/c/d/e.py'], chroot) + self.assertFalse(isdir(path_to("a/"))) + create_files(["a/b/foo.py", "a/b/c/", "a/b/c/d/e.py"], chroot) # make sure directories exist - self.assertTrue(isdir(path_to('a'))) - self.assertTrue(isdir(path_to('a/b'))) - self.assertTrue(isdir(path_to('a/b/c'))) - self.assertTrue(isdir(path_to('a/b/c/d'))) + self.assertTrue(isdir(path_to("a"))) + self.assertTrue(isdir(path_to("a/b"))) + self.assertTrue(isdir(path_to("a/b/c"))) + self.assertTrue(isdir(path_to("a/b/c/d"))) # make sure files exist - self.assertTrue(isfile(path_to('a/b/foo.py'))) - self.assertTrue(isfile(path_to('a/b/c/d/e.py'))) + self.assertTrue(isfile(path_to("a/b/foo.py"))) + self.assertTrue(isfile(path_to("a/b/c/d/e.py"))) # make sure only asked files were created - self.assertEqual(dircontent('a'), ['b']) - self.assertEqual(dircontent('a/b'), ['c', 'foo.py']) - self.assertEqual(dircontent('a/b/c'), ['d']) - self.assertEqual(dircontent('a/b/c/d'), ['e.py']) + self.assertEqual(dircontent("a"), ["b"]) + self.assertEqual(dircontent("a/b"), ["c", "foo.py"]) + self.assertEqual(dircontent("a/b/c"), ["d"]) + self.assertEqual(dircontent("a/b/c/d"), ["e.py"]) finally: shutil.rmtree(chroot) class TestlibTC(TestCase): - def mkdir(self, path): if not exists(path): self._dirs.add(path) @@ -88,13 +98,13 @@ class TestlibTC(TestCase): self._dirs = set() def tearDown(self): - while(self._dirs): + while self._dirs: shutil.rmtree(self._dirs.pop(), ignore_errors=True) def test_dict_equals(self): """tests TestCase.assertDictEqual""" - d1 = {'a' : 1, 'b' : 2} - d2 = {'a' : 1, 'b' : 3} + d1 = {"a": 1, "b": 2} + d2 = {"a": 1, "b": 3} d3 = dict(d1) self.assertRaises(AssertionError, self.tc.assertDictEqual, d1, d2) self.tc.assertDictEqual(d1, d3) @@ -112,8 +122,8 @@ class TestlibTC(TestCase): self.tc.assertListEqual(l3, l1) def test_equality_for_sets(self): - s1 = set('ab') - s2 = set('a') + s1 = set("ab") + s2 = set("a") self.assertRaises(AssertionError, self.tc.assertSetEqual, s1, s2) self.tc.assertSetEqual(s1, s1) self.tc.assertSetEqual(set(), set()) @@ -123,16 +133,20 @@ class TestlibTC(TestCase): self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, "toto", 12) self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, "toto", None) self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, "toto", None) - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 3.12, u"toto") - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 3.12, u"toto") - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, None, u"toto") - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, None, u"toto") - self.tc.assertMultiLineEqual('toto\ntiti', 'toto\ntiti') - self.tc.assertMultiLineEqual('toto\ntiti', 'toto\ntiti') - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 'toto\ntiti', 'toto\n titi\n') - self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 'toto\ntiti', 'toto\n titi\n') - foo = join(dirname(__file__), 'data', 'foo.txt') - spam = join(dirname(__file__), 'data', 'spam.txt') + self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 3.12, "toto") + self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, 3.12, "toto") + self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, None, "toto") + self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, None, "toto") + self.tc.assertMultiLineEqual("toto\ntiti", "toto\ntiti") + self.tc.assertMultiLineEqual("toto\ntiti", "toto\ntiti") + self.assertRaises( + AssertionError, self.tc.assertMultiLineEqual, "toto\ntiti", "toto\n titi\n" + ) + self.assertRaises( + AssertionError, self.tc.assertMultiLineEqual, "toto\ntiti", "toto\n titi\n" + ) + foo = join(dirname(__file__), "data", "foo.txt") + spam = join(dirname(__file__), "data", "spam.txt") with open(foo) as fobj: text1 = fobj.read() self.tc.assertMultiLineEqual(text1, text1) @@ -143,37 +157,41 @@ class TestlibTC(TestCase): self.assertRaises(AssertionError, self.tc.assertMultiLineEqual, text1, text2) def test_default_datadir(self): - expected_datadir = join(dirname(abspath(__file__)), 'data') + expected_datadir = join(dirname(abspath(__file__)), "data") self.assertEqual(self.datadir, expected_datadir) - self.assertEqual(self.datapath('foo'), join(expected_datadir, 'foo')) + self.assertEqual(self.datapath("foo"), join(expected_datadir, "foo")) def test_multiple_args_datadir(self): - expected_datadir = join(dirname(abspath(__file__)), 'data') + expected_datadir = join(dirname(abspath(__file__)), "data") self.assertEqual(self.datadir, expected_datadir) - self.assertEqual(self.datapath('foo', 'bar'), join(expected_datadir, 'foo', 'bar')) + self.assertEqual(self.datapath("foo", "bar"), join(expected_datadir, "foo", "bar")) def test_custom_datadir(self): class MyTC(TestCase): - datadir = 'foo' - def test_1(self): pass + datadir = "foo" + + def test_1(self): + pass # class' custom datadir - tc = MyTC('test_1') - self.assertEqual(tc.datapath('bar'), join('foo', 'bar')) + tc = MyTC("test_1") + self.assertEqual(tc.datapath("bar"), join("foo", "bar")) def test_cached_datadir(self): """test datadir is cached on the class""" + class MyTC(TestCase): - def test_1(self): pass + def test_1(self): + pass - expected_datadir = join(dirname(abspath(__file__)), 'data') - tc = MyTC('test_1') + expected_datadir = join(dirname(abspath(__file__)), "data") + tc = MyTC("test_1") self.assertEqual(tc.datadir, expected_datadir) # changing module should not change the datadir - MyTC.__module__ = 'os' + MyTC.__module__ = "os" self.assertEqual(tc.datadir, expected_datadir) # even on new instances - tc2 = MyTC('test_1') + tc2 = MyTC("test_1") self.assertEqual(tc2.datadir, expected_datadir) def test_is(self): @@ -198,16 +216,15 @@ class TestlibTC(TestCase): def test_in(self): self.assertIn("a", "dsqgaqg") - obj, seq = 'a', ('toto', "azf", "coin") + obj, seq = "a", ("toto", "azf", "coin") self.assertRaises(AssertionError, self.assertIn, obj, seq) def test_not_in(self): - self.assertNotIn('a', ('toto', "azf", "coin")) - self.assertRaises(AssertionError, self.assertNotIn, 'a', "dsqgaqg") + self.assertNotIn("a", ("toto", "azf", "coin")) + self.assertRaises(AssertionError, self.assertNotIn, "a", "dsqgaqg") class GenerativeTestsTC(TestCase): - def setUp(self): output = StringIO() self.runner = SkipAwareTextTestRunner(stream=output) @@ -217,7 +234,8 @@ class GenerativeTestsTC(TestCase): def test_generative(self): for i in range(10): yield self.assertEqual, i, i - result = self.runner.run(FooTC('test_generative')) + + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 0) @@ -226,8 +244,9 @@ class GenerativeTestsTC(TestCase): class FooTC(TestCase): def test_generative(self): for i in range(10): - yield self.assertEqual, i%2, 0 - result = self.runner.run(FooTC('test_generative')) + yield self.assertEqual, i % 2, 0 + + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 5) self.assertEqual(len(result.errors), 0) @@ -237,10 +256,10 @@ class GenerativeTestsTC(TestCase): def test_generative(self): for i in range(10): if i == 5: - raise ValueError('STOP !') + raise ValueError("STOP !") yield self.assertEqual, i, i - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 5) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 1) @@ -252,8 +271,11 @@ class GenerativeTestsTC(TestCase): if i == 5: yield self.ouch yield self.assertEqual, i, i - def ouch(self): raise ValueError('stop !') - result = self.runner.run(FooTC('test_generative')) + + def ouch(self): + raise ValueError("stop !") + + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 11) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 1) @@ -261,12 +283,13 @@ class GenerativeTestsTC(TestCase): def test_generative_setup(self): class FooTC(TestCase): def setUp(self): - raise ValueError('STOP !') + raise ValueError("STOP !") + def test_generative(self): for i in range(10): yield self.assertEqual, i, i - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 1) @@ -281,9 +304,9 @@ class GenerativeTestsTC(TestCase): def test_generative(self): for i in range(10): - yield InnerTest("check_%s"%i, self.check, i) + yield InnerTest("check_%s" % i, self.check, i) - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 0) @@ -299,9 +322,9 @@ class GenerativeTestsTC(TestCase): def test_generative(self): for i in range(10): - yield InnerTest("check_%s"%i, self.check, i) + yield InnerTest("check_%s" % i, self.check, i) - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 0) @@ -317,9 +340,9 @@ class GenerativeTestsTC(TestCase): def test_generative(self): for i in range(10): - yield InnerTest("check_%s"%i, self.check, i) + yield InnerTest("check_%s" % i, self.check, i) - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 1) @@ -329,28 +352,27 @@ class GenerativeTestsTC(TestCase): class FooTC(TestCase): def check(self, val): if val == 5: - self.assertEqual(val, val+1) + self.assertEqual(val, val + 1) else: self.assertEqual(val, val) def test_generative(self): for i in range(10): - yield InnerTest("check_%s"%i, self.check, i) + yield InnerTest("check_%s" % i, self.check, i) - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 10) self.assertEqual(len(result.failures), 1) self.assertEqual(len(result.errors), 0) self.assertEqual(len(result.skipped), 0) - def test_generative_outer_failure(self): class FooTC(TestCase): def test_generative(self): self.fail() yield - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.failures), 1) self.assertEqual(len(result.errors), 0) @@ -359,10 +381,10 @@ class GenerativeTestsTC(TestCase): def test_generative_outer_skip(self): class FooTC(TestCase): def test_generative(self): - self.skipTest('blah') + self.skipTest("blah") yield - result = self.runner.run(FooTC('test_generative')) + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 0) self.assertEqual(len(result.failures), 0) self.assertEqual(len(result.errors), 0) @@ -376,10 +398,16 @@ class ExitFirstTC(TestCase): def test_failure_exit_first(self): class FooTC(TestCase): - def test_1(self): pass - def test_2(self): assert False - def test_3(self): pass - tests = [FooTC('test_1'), FooTC('test_2')] + def test_1(self): + pass + + def test_2(self): + assert False + + def test_3(self): + pass + + tests = [FooTC("test_1"), FooTC("test_2")] result = self.runner.run(TestSuite(tests)) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.failures), 1) @@ -387,10 +415,16 @@ class ExitFirstTC(TestCase): def test_error_exit_first(self): class FooTC(TestCase): - def test_1(self): pass - def test_2(self): raise ValueError() - def test_3(self): pass - tests = [FooTC('test_1'), FooTC('test_2'), FooTC('test_3')] + def test_1(self): + pass + + def test_2(self): + raise ValueError() + + def test_3(self): + pass + + tests = [FooTC("test_1"), FooTC("test_2"), FooTC("test_3")] result = self.runner.run(TestSuite(tests)) self.assertEqual(result.testsRun, 2) self.assertEqual(len(result.failures), 0) @@ -401,7 +435,8 @@ class ExitFirstTC(TestCase): def test_generative(self): for i in range(10): yield self.assertTrue, False - result = self.runner.run(FooTC('test_generative')) + + result = self.runner.run(FooTC("test_generative")) self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.failures), 1) self.assertEqual(len(result.errors), 0) @@ -410,17 +445,26 @@ class ExitFirstTC(TestCase): class TestLoaderTC(TestCase): ## internal classes for test purposes ######## class FooTC(TestCase): - def test_foo1(self): pass - def test_foo2(self): pass - def test_bar1(self): pass + def test_foo1(self): + pass + + def test_foo2(self): + pass + + def test_bar1(self): + pass class BarTC(TestCase): - def test_bar2(self): pass + def test_bar2(self): + pass + ############################################## def setUp(self): self.loader = NonStrictTestLoader() - self.module = TestLoaderTC # mock_object(FooTC=TestLoaderTC.FooTC, BarTC=TestLoaderTC.BarTC) + self.module = ( + TestLoaderTC # mock_object(FooTC=TestLoaderTC.FooTC, BarTC=TestLoaderTC.BarTC) + ) self.output = StringIO() self.runner = SkipAwareTextTestRunner(stream=self.output) @@ -446,114 +490,172 @@ class TestLoaderTC(TestCase): self.assertEqual(len(suite1._tests) + len(suite2._tests), 4) def test_collect_with_classname(self): - self.assertRunCount('FooTC', self.module, 3) - self.assertRunCount('BarTC', self.module, 1) + self.assertRunCount("FooTC", self.module, 3) + self.assertRunCount("BarTC", self.module, 1) def test_collect_with_classname_and_pattern(self): - data = [('FooTC.test_foo1', 1), ('FooTC.test_foo', 2), ('FooTC.test_fo', 2), - ('FooTC.foo1', 1), ('FooTC.foo', 2), ('FooTC.whatever', 0) - ] + data = [ + ("FooTC.test_foo1", 1), + ("FooTC.test_foo", 2), + ("FooTC.test_fo", 2), + ("FooTC.foo1", 1), + ("FooTC.foo", 2), + ("FooTC.whatever", 0), + ] for pattern, expected_count in data: yield self.assertRunCount, pattern, self.module, expected_count def test_collect_with_pattern(self): - data = [('test_foo1', 1), ('test_foo', 2), ('test_bar', 2), - ('foo1', 1), ('foo', 2), ('bar', 2), ('ba', 2), - ('test', 4), ('ab', 0), - ] + data = [ + ("test_foo1", 1), + ("test_foo", 2), + ("test_bar", 2), + ("foo1", 1), + ("foo", 2), + ("bar", 2), + ("ba", 2), + ("test", 4), + ("ab", 0), + ] for pattern, expected_count in data: yield self.assertRunCount, pattern, self.module, expected_count def test_testcase_with_custom_metaclass(self): - class mymetaclass(type): pass + class mymetaclass(type): + pass + class MyMod: class MyTestCase(TestCase): __metaclass__ = mymetaclass - def test_foo1(self): pass - def test_foo2(self): pass - def test_bar(self): pass - data = [('test_foo1', 1), ('test_foo', 2), ('test_bar', 1), - ('foo1', 1), ('foo', 2), ('bar', 1), ('ba', 1), - ('test', 3), ('ab', 0), - ('MyTestCase.test_foo1', 1), ('MyTestCase.test_foo', 2), - ('MyTestCase.test_fo', 2), ('MyTestCase.foo1', 1), - ('MyTestCase.foo', 2), ('MyTestCase.whatever', 0) - ] + + def test_foo1(self): + pass + + def test_foo2(self): + pass + + def test_bar(self): + pass + + data = [ + ("test_foo1", 1), + ("test_foo", 2), + ("test_bar", 1), + ("foo1", 1), + ("foo", 2), + ("bar", 1), + ("ba", 1), + ("test", 3), + ("ab", 0), + ("MyTestCase.test_foo1", 1), + ("MyTestCase.test_foo", 2), + ("MyTestCase.test_fo", 2), + ("MyTestCase.foo1", 1), + ("MyTestCase.foo", 2), + ("MyTestCase.whatever", 0), + ] for pattern, expected_count in data: yield self.assertRunCount, pattern, MyMod, expected_count def test_collect_everything_and_skipped_patterns(self): - testdata = [ (['foo1'], 3), (['foo'], 2), - (['foo', 'bar'], 0), ] + testdata = [ + (["foo1"], 3), + (["foo"], 2), + (["foo", "bar"], 0), + ] for skipped, expected_count in testdata: yield self.assertRunCount, None, self.module, expected_count, skipped def test_collect_specific_pattern_and_skip_some(self): - testdata = [ ('bar', ['foo1'], 2), ('bar', [], 2), - ('bar', ['bar'], 0), ] + testdata = [ + ("bar", ["foo1"], 2), + ("bar", [], 2), + ("bar", ["bar"], 0), + ] for runpattern, skipped, expected_count in testdata: yield self.assertRunCount, runpattern, self.module, expected_count, skipped def test_skip_classname(self): - testdata = [ (['BarTC'], 3), (['FooTC'], 1), ] + testdata = [ + (["BarTC"], 3), + (["FooTC"], 1), + ] for skipped, expected_count in testdata: yield self.assertRunCount, None, self.module, expected_count, skipped def test_skip_classname_and_specific_collect(self): - testdata = [ ('bar', ['BarTC'], 1), ('foo', ['FooTC'], 0), ] + testdata = [ + ("bar", ["BarTC"], 1), + ("foo", ["FooTC"], 0), + ] for runpattern, skipped, expected_count in testdata: yield self.assertRunCount, runpattern, self.module, expected_count, skipped def test_nonregr_dotted_path(self): - self.assertRunCount('FooTC.test_foo', self.module, 2) + self.assertRunCount("FooTC.test_foo", self.module, 2) def test_inner_tests_selection(self): class MyMod: class MyTestCase(TestCase): - def test_foo(self): pass + def test_foo(self): + pass + def test_foobar(self): for i in range(5): - if i%2 == 0: - yield InnerTest('even', lambda: None) + if i % 2 == 0: + yield InnerTest("even", lambda: None) else: - yield InnerTest('odd', lambda: None) + yield InnerTest("odd", lambda: None) yield lambda: None # FIXME InnerTest masked by pattern usage # data = [('foo', 7), ('test_foobar', 6), ('even', 3), ('odd', 2), ] - data = [('foo', 7), ('test_foobar', 6), ('even', 0), ('odd', 0), ] + data = [ + ("foo", 7), + ("test_foobar", 6), + ("even", 0), + ("odd", 0), + ] for pattern, expected_count in data: yield self.assertRunCount, pattern, MyMod, expected_count def test_nonregr_class_skipped_option(self): class MyMod: class MyTestCase(TestCase): - def test_foo(self): pass - def test_bar(self): pass + def test_foo(self): + pass + + def test_bar(self): + pass + class FooTC(TestCase): - def test_foo(self): pass - self.assertRunCount('foo', MyMod, 2) + def test_foo(self): + pass + + self.assertRunCount("foo", MyMod, 2) self.assertRunCount(None, MyMod, 3) - self.assertRunCount('foo', MyMod, 1, ['FooTC']) - self.assertRunCount(None, MyMod, 2, ['FooTC']) + self.assertRunCount("foo", MyMod, 1, ["FooTC"]) + self.assertRunCount(None, MyMod, 2, ["FooTC"]) def test__classes_are_ignored(self): class MyMod: class _Base(TestCase): - def test_1(self): pass + def test_1(self): + pass + class MyTestCase(_Base): - def test_2(self): pass + def test_2(self): + pass + self.assertRunCount(None, MyMod, 2) class DecoratorTC(TestCase): - @with_tempdir def test_tmp_dir_normal_1(self): tempdir = tempfile.gettempdir() # assert temp directory is empty - self.assertListEqual(list(os.walk(tempdir)), - [(tempdir, [], [])]) + self.assertListEqual(list(os.walk(tempdir)), [(tempdir, [], [])]) witness = [] @@ -575,16 +677,13 @@ class DecoratorTC(TestCase): self.assertEqual(tempfile.gettempdir(), tempdir) # assert temp directory is empty - self.assertListEqual(list(os.walk(tempdir)), - [(tempdir, [], [])]) + self.assertListEqual(list(os.walk(tempdir)), [(tempdir, [], [])]) @with_tempdir def test_tmp_dir_normal_2(self): tempdir = tempfile.gettempdir() # assert temp directory is empty - self.assertListEqual(list(os.walk(tempfile.tempdir)), - [(tempfile.tempdir, [], [])]) - + self.assertListEqual(list(os.walk(tempfile.tempdir)), [(tempfile.tempdir, [], [])]) class WitnessException(Exception): pass @@ -606,8 +705,7 @@ class DecoratorTC(TestCase): self.assertEqual(tempfile.gettempdir(), tempdir) # assert temp directory is empty - self.assertListEqual(list(os.walk(tempdir)), - [(tempdir, [], [])]) + self.assertListEqual(list(os.walk(tempdir)), [(tempdir, [], [])]) def test_tmpdir_generator(self): orig_tempdir = tempfile.gettempdir() @@ -629,37 +727,51 @@ class DecoratorTC(TestCase): def test_require_version_good(self): """ should return the same function """ - def func() : + + def func(): pass - sys.version_info = (2, 5, 5, 'final', 4) + + sys.version_info = (2, 5, 5, "final", 4) current = sys.version_info[:3] - compare = ('2.4', '2.5', '2.5.4', '2.5.5') + compare = ("2.4", "2.5", "2.5.4", "2.5.5") for version in compare: decorator = require_version(version) - self.assertEqual(func, decorator(func), '%s =< %s : function \ - return by the decorator should be the same.' % (version, - '.'.join([str(element) for element in current]))) + self.assertEqual( + func, + decorator(func), + "%s =< %s : function \ + return by the decorator should be the same." + % (version, ".".join([str(element) for element in current])), + ) def test_require_version_bad(self): """ should return a different function : skipping test """ - def func() : + + def func(): pass - sys.version_info = (2, 5, 5, 'final', 4) + + sys.version_info = (2, 5, 5, "final", 4) current = sys.version_info[:3] - compare = ('2.5.6', '2.6', '2.6.5') + compare = ("2.5.6", "2.6", "2.6.5") for version in compare: decorator = require_version(version) - self.assertNotEqual(func, decorator(func), '%s >= %s : function \ - return by the decorator should NOT be the same.' - % ('.'.join([str(element) for element in current]), version)) + self.assertNotEqual( + func, + decorator(func), + "%s >= %s : function \ + return by the decorator should NOT be the same." + % (".".join([str(element) for element in current]), version), + ) def test_require_version_exception(self): """ should throw a ValueError exception """ - def func() : + + def func(): pass - compare = ('2.5.a', '2.a', 'azerty') + + compare = ("2.5.a", "2.a", "azerty") for version in compare: decorator = require_version(version) self.assertRaises(ValueError, decorator, func) @@ -667,122 +779,139 @@ class DecoratorTC(TestCase): def test_require_module_good(self): """ should return the same function """ - def func() : + + def func(): pass - module = 'sys' + + module = "sys" decorator = require_module(module) - self.assertEqual(func, decorator(func), 'module %s exists : function \ - return by the decorator should be the same.' % module) + self.assertEqual( + func, + decorator(func), + "module %s exists : function \ + return by the decorator should be the same." + % module, + ) def test_require_module_bad(self): """ should return a different function : skipping test """ - def func() : + + def func(): pass - modules = ('bla', 'blo', 'bli') + + modules = ("bla", "blo", "bli") for module in modules: try: __import__(module) pass except ImportError: decorator = require_module(module) - self.assertNotEqual(func, decorator(func), 'module %s does \ + self.assertNotEqual( + func, + decorator(func), + "module %s does \ not exist : function return by the decorator should \ - NOT be the same.' % module) + NOT be the same." + % module, + ) return - print('all modules in %s exist. Could not test %s' % (', '.join(modules), - sys._getframe().f_code.co_name)) + print( + "all modules in %s exist. Could not test %s" + % (", ".join(modules), sys._getframe().f_code.co_name) + ) -class TagTC(TestCase): +class TagTC(TestCase): def setUp(self): - @tag('testing', 'bob') + @tag("testing", "bob") def bob(a, b, c): return (a + b) * c self.func = bob class TagTestTC(TestCase): - tags = Tags('one', 'two') + tags = Tags("one", "two") def test_one(self): self.assertTrue(True) - @tag('two', 'three') + @tag("two", "three") def test_two(self): self.assertTrue(True) - @tag('three', inherit=False) + @tag("three", inherit=False) def test_three(self): self.assertTrue(True) + self.cls = TagTestTC def test_tag_decorator(self): bob = self.func self.assertEqual(bob(2, 3, 7), 35) - self.assertTrue(hasattr(bob, 'tags')) - self.assertSetEqual(bob.tags, set(['testing', 'bob'])) + self.assertTrue(hasattr(bob, "tags")) + self.assertSetEqual(bob.tags, set(["testing", "bob"])) def test_tags_class(self): tags = self.func.tags - self.assertTrue(tags['testing']) - self.assertFalse(tags['Not inside']) + self.assertTrue(tags["testing"]) + self.assertFalse(tags["Not inside"]) def test_tags_match(self): tags = self.func.tags - self.assertTrue(tags.match('testing')) - self.assertFalse(tags.match('other')) + self.assertTrue(tags.match("testing")) + self.assertFalse(tags.match("other")) - self.assertFalse(tags.match('testing and coin')) - self.assertTrue(tags.match('testing or other')) + self.assertFalse(tags.match("testing and coin")) + self.assertTrue(tags.match("testing or other")) - self.assertTrue(tags.match('not other')) + self.assertTrue(tags.match("not other")) - self.assertTrue(tags.match('not other or (testing and bibi)')) - self.assertTrue(tags.match('other or (testing and bob)')) + self.assertTrue(tags.match("not other or (testing and bibi)")) + self.assertTrue(tags.match("other or (testing and bob)")) def test_tagged_class(self): def options(tags): class Options(object): tags_pattern = tags + return Options() - tc = self.cls('test_one') + tc = self.cls("test_one") runner = SkipAwareTextTestRunner() self.assertTrue(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertTrue(runner.does_match_tags(tc.test_three)) - runner = SkipAwareTextTestRunner(options=options('one')) + runner = SkipAwareTextTestRunner(options=options("one")) self.assertTrue(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertFalse(runner.does_match_tags(tc.test_three)) - runner = SkipAwareTextTestRunner(options=options('two')) + runner = SkipAwareTextTestRunner(options=options("two")) self.assertTrue(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertFalse(runner.does_match_tags(tc.test_three)) - runner = SkipAwareTextTestRunner(options=options('three')) + runner = SkipAwareTextTestRunner(options=options("three")) self.assertFalse(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertTrue(runner.does_match_tags(tc.test_three)) - runner = SkipAwareTextTestRunner(options=options('two or three')) + runner = SkipAwareTextTestRunner(options=options("two or three")) self.assertTrue(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertTrue(runner.does_match_tags(tc.test_three)) - runner = SkipAwareTextTestRunner(options=options('two and three')) + runner = SkipAwareTextTestRunner(options=options("two and three")) self.assertFalse(runner.does_match_tags(tc.test_one)) self.assertTrue(runner.does_match_tags(tc.test_two)) self.assertFalse(runner.does_match_tags(tc.test_three)) - -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_textutils.py b/test/test_textutils.py index 3e9a343..8aa2ded 100644 --- a/test/test_textutils.py +++ b/test/test_textutils.py @@ -29,245 +29,304 @@ from logilab.common import textutils as tu from logilab.common.testlib import TestCase, unittest_main -if linesep != '\n': +if linesep != "\n": import re + LINE_RGX = re.compile(linesep) + def ulines(string): - return LINE_RGX.sub('\n', string) + return LINE_RGX.sub("\n", string) + + else: + def ulines(string): return string -class NormalizeTextTC(TestCase): +class NormalizeTextTC(TestCase): def test_known_values(self): - self.assertEqual(ulines(tu.normalize_text('''some really malformated + self.assertEqual( + ulines( + tu.normalize_text( + """some really malformated text. With some times some veeeeeeeeeeeeeeerrrrryyyyyyyyyyyyyyyyyyy loooooooooooooooooooooong linnnnnnnnnnnes and empty lines! - ''')), - '''some really malformated text. With some times some + """ + ) + ), + """some really malformated text. With some times some veeeeeeeeeeeeeeerrrrryyyyyyyyyyyyyyyyyyy loooooooooooooooooooooong linnnnnnnnnnnes -and empty lines!''') - self.assertMultiLineEqual(ulines(tu.normalize_text('''\ +and empty lines!""", + ) + self.assertMultiLineEqual( + ulines( + tu.normalize_text( + """\ some ReST formated text ======================= With some times some veeeeeeeeeeeeeeerrrrryyyyyyyyyyyyyyyyyyy loooooooooooooooooooooong linnnnnnnnnnnes and normal lines! another paragraph - ''', rest=True)), - '''\ + """, + rest=True, + ) + ), + """\ some ReST formated text ======================= With some times some veeeeeeeeeeeeeeerrrrryyyyyyyyyyyyyyyyyyy loooooooooooooooooooooong linnnnnnnnnnnes and normal lines! -another paragraph''') +another paragraph""", + ) def test_nonregr_unsplitable_word(self): - self.assertEqual(ulines(tu.normalize_text('''petit complement : + self.assertEqual( + ulines( + tu.normalize_text( + """petit complement : http://www.plonefr.net/blog/archive/2005/10/30/tester-la-future-infrastructure-i18n -''', 80)), - '''petit complement : - -http://www.plonefr.net/blog/archive/2005/10/30/tester-la-future-infrastructure-i18n''') +""", + 80, + ) + ), + """petit complement : +http://www.plonefr.net/blog/archive/2005/10/30/tester-la-future-infrastructure-i18n""", + ) def test_nonregr_rest_normalize(self): - self.assertEqual(ulines(tu.normalize_text("""... Il est donc evident que tout le monde doit lire le compte-rendu de RSH et aller discuter avec les autres si c'est utile ou necessaire. - """, rest=True)), """... Il est donc evident que tout le monde doit lire le compte-rendu de RSH et -aller discuter avec les autres si c'est utile ou necessaire.""") + self.assertEqual( + ulines( + tu.normalize_text( + """... Il est donc evident que tout le monde doit lire le compte-rendu de RSH et aller discuter avec les autres si c'est utile ou necessaire. + """, + rest=True, + ) + ), + """... Il est donc evident que tout le monde doit lire le compte-rendu de RSH et +aller discuter avec les autres si c'est utile ou necessaire.""", + ) def test_normalize_rest_paragraph(self): - self.assertEqual(ulines(tu.normalize_rest_paragraph("""**nico**: toto""")), - """**nico**: toto""") + self.assertEqual( + ulines(tu.normalize_rest_paragraph("""**nico**: toto""")), """**nico**: toto""" + ) def test_normalize_rest_paragraph2(self): - self.assertEqual(ulines(tu.normalize_rest_paragraph(""".. _tdm: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf -.. _extrait: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", indent='> ')), - """> .. _tdm: + self.assertEqual( + ulines( + tu.normalize_rest_paragraph( + """.. _tdm: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf +.. _extrait: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", + indent="> ", + ) + ), + """> .. _tdm: > http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf > .. _extrait: -> http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""") +> http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", + ) def test_normalize_paragraph2(self): - self.assertEqual(ulines(tu.normalize_paragraph(""".. _tdm: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf -.. _extrait: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", indent='> ')), - """> .. _tdm: + self.assertEqual( + ulines( + tu.normalize_paragraph( + """.. _tdm: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf +.. _extrait: http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", + indent="> ", + ) + ), + """> .. _tdm: > http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Table-des-matieres/.20_adaa41fb-c125-4919-aece-049601e81c8e_0_0.pdf > .. _extrait: -> http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""") +> http://www.editions-eni.fr/Livres/Python-Les-fondamentaux-du-langage---La-programmation-pour-les-scientifiques-Extrait-du-livre/.20_d6eed0be-0d36-4384-be59-2dd09e081012_0_0.pdf""", + ) class NormalizeParagraphTC(TestCase): - def test_known_values(self): - self.assertEqual(ulines(tu.normalize_text("""This package contains test files shared by the logilab-common package. It isn't + self.assertEqual( + ulines( + tu.normalize_text( + """This package contains test files shared by the logilab-common package. It isn't necessary to install this package unless you want to execute or look at -the tests.""", indent=' ', line_len=70)), - """\ +the tests.""", + indent=" ", + line_len=70, + ) + ), + """\ This package contains test files shared by the logilab-common package. It isn't necessary to install this package unless you want - to execute or look at the tests.""") + to execute or look at the tests.""", + ) class GetCsvTC(TestCase): - def test_known(self): - self.assertEqual(tu.splitstrip('a, b,c '), ['a', 'b', 'c']) + self.assertEqual(tu.splitstrip("a, b,c "), ["a", "b", "c"]) -class UnitsTC(TestCase): +class UnitsTC(TestCase): def setUp(self): self.units = { - 'm': 60, - 'kb': 1024, - 'mb': 1024*1024, - } + "m": 60, + "kb": 1024, + "mb": 1024 * 1024, + } def test_empty_base(self): - self.assertEqual(tu.apply_units('17', {}), 17) + self.assertEqual(tu.apply_units("17", {}), 17) def test_empty_inter(self): def inter(value): return int(float(value)) * 2 - result = tu.apply_units('12.4', {}, inter=inter) + + result = tu.apply_units("12.4", {}, inter=inter) self.assertEqual(result, 12 * 2) self.assertIsInstance(result, float) def test_empty_final(self): # int('12.4') raise value error - self.assertRaises(ValueError, tu.apply_units, '12.4', {}, final=int) + self.assertRaises(ValueError, tu.apply_units, "12.4", {}, final=int) def test_empty_inter_final(self): - result = tu.apply_units('12.4', {}, inter=float, final=int) + result = tu.apply_units("12.4", {}, inter=float, final=int) self.assertEqual(result, 12) self.assertIsInstance(result, int) def test_blank_base(self): - result = tu.apply_units(' 42 ', {}, final=int) + result = tu.apply_units(" 42 ", {}, final=int) self.assertEqual(result, 42) def test_blank_space(self): - result = tu.apply_units(' 1 337 ', {}, final=int) + result = tu.apply_units(" 1 337 ", {}, final=int) self.assertEqual(result, 1337) def test_blank_coma(self): - result = tu.apply_units(' 4,298.42 ', {}) + result = tu.apply_units(" 4,298.42 ", {}) self.assertEqual(result, 4298.42) def test_blank_mixed(self): - result = tu.apply_units('45, 317, 337', {}, final=int) + result = tu.apply_units("45, 317, 337", {}, final=int) self.assertEqual(result, 45317337) def test_unit_singleunit_singleletter(self): - result = tu.apply_units('15m', self.units) - self.assertEqual(result, 15 * self.units['m']) + result = tu.apply_units("15m", self.units) + self.assertEqual(result, 15 * self.units["m"]) def test_unit_singleunit_multipleletter(self): - result = tu.apply_units('47KB', self.units) - self.assertEqual(result, 47 * self.units['kb']) + result = tu.apply_units("47KB", self.units) + self.assertEqual(result, 47 * self.units["kb"]) def test_unit_singleunit_caseinsensitive(self): - result = tu.apply_units('47kb', self.units) - self.assertEqual(result, 47 * self.units['kb']) + result = tu.apply_units("47kb", self.units) + self.assertEqual(result, 47 * self.units["kb"]) def test_unit_multipleunit(self): - result = tu.apply_units('47KB 1.5MB', self.units) - self.assertEqual(result, 47 * self.units['kb'] + 1.5 * self.units['mb']) + result = tu.apply_units("47KB 1.5MB", self.units) + self.assertEqual(result, 47 * self.units["kb"] + 1.5 * self.units["mb"]) def test_unit_with_blank(self): - result = tu.apply_units('1 000 KB', self.units) - self.assertEqual(result, 1000 * self.units['kb']) + result = tu.apply_units("1 000 KB", self.units) + self.assertEqual(result, 1000 * self.units["kb"]) def test_unit_wrong_input(self): - self.assertRaises( - ValueError, tu.apply_units, '', self.units) - self.assertRaises( - ValueError, tu.apply_units, 'wrong input', self.units) - self.assertRaises( - ValueError, tu.apply_units, 'wrong13 input', self.units) - self.assertRaises( - ValueError, tu.apply_units, 'wrong input42', self.units) + self.assertRaises(ValueError, tu.apply_units, "", self.units) + self.assertRaises(ValueError, tu.apply_units, "wrong input", self.units) + self.assertRaises(ValueError, tu.apply_units, "wrong13 input", self.units) + self.assertRaises(ValueError, tu.apply_units, "wrong input42", self.units) with self.assertRaises(ValueError) as cm: - tu.apply_units('42 cakes', self.units) - self.assertIn('invalid unit cakes.', str(cm.exception)) + tu.apply_units("42 cakes", self.units) + self.assertIn("invalid unit cakes.", str(cm.exception)) -RGX = re.compile('abcd') +RGX = re.compile("abcd") class PrettyMatchTC(TestCase): - def test_known(self): - string = 'hiuherabcdef' - self.assertEqual(ulines(tu.pretty_match(RGX.search(string), string)), - 'hiuherabcdef\n ^^^^') + string = "hiuherabcdef" + self.assertEqual( + ulines(tu.pretty_match(RGX.search(string), string)), "hiuherabcdef\n ^^^^" + ) + def test_known_values_1(self): - rgx = re.compile('(to*)') - string = 'toto' + rgx = re.compile("(to*)") + string = "toto" match = rgx.search(string) - self.assertEqual(ulines(tu.pretty_match(match, string)), '''toto -^^''') + self.assertEqual( + ulines(tu.pretty_match(match, string)), + """toto +^^""", + ) def test_known_values_2(self): - rgx = re.compile('(to*)') - string = ''' ... ... to to - ... ... ''' + rgx = re.compile("(to*)") + string = """ ... ... to to + ... ... """ match = rgx.search(string) - self.assertEqual(ulines(tu.pretty_match(match, string)), ''' ... ... to to + self.assertEqual( + ulines(tu.pretty_match(match, string)), + """ ... ... to to ^^ - ... ...''') - + ... ...""", + ) class UnquoteTC(TestCase): def test(self): - self.assertEqual(tu.unquote('"toto"'), 'toto') + self.assertEqual(tu.unquote('"toto"'), "toto") self.assertEqual(tu.unquote("'l'inenarrable toto'"), "l'inenarrable toto") self.assertEqual(tu.unquote("no quote"), "no quote") class ColorizeAnsiTC(TestCase): def test_known(self): - self.assertEqual(tu.colorize_ansi('hello', 'blue', 'strike'), '\x1b[9;34mhello\x1b[0m') - self.assertEqual(tu.colorize_ansi('hello', style='strike, inverse'), '\x1b[9;7mhello\x1b[0m') - self.assertEqual(tu.colorize_ansi('hello', None, None), 'hello') - self.assertEqual(tu.colorize_ansi('hello', '', ''), 'hello') + self.assertEqual(tu.colorize_ansi("hello", "blue", "strike"), "\x1b[9;34mhello\x1b[0m") + self.assertEqual( + tu.colorize_ansi("hello", style="strike, inverse"), "\x1b[9;7mhello\x1b[0m" + ) + self.assertEqual(tu.colorize_ansi("hello", None, None), "hello") + self.assertEqual(tu.colorize_ansi("hello", "", ""), "hello") + def test_raise(self): - self.assertRaises(KeyError, tu.colorize_ansi, 'hello', 'bleu', None) - self.assertRaises(KeyError, tu.colorize_ansi, 'hello', None, 'italique') + self.assertRaises(KeyError, tu.colorize_ansi, "hello", "bleu", None) + self.assertRaises(KeyError, tu.colorize_ansi, "hello", None, "italique") class UnormalizeTC(TestCase): def test_unormalize_no_substitute(self): - data = [(u'\u0153nologie', u'oenologie'), - (u'\u0152nologie', u'OEnologie'), - (u'l\xf8to', u'loto'), - (u'été', u'ete'), - (u'àèùéïîôêç', u'aeueiioec'), - (u'ÀÈÙÉÏÎÔÊÇ', u'AEUEIIOEC'), - (u'\xa0', u' '), # NO-BREAK SPACE managed by NFKD decomposition - (u'\u0154', u'R'), - (u'Pointe d\u2019Yves', u"Pointe d'Yves"), - (u'Bordeaux\u2013Mérignac', u'Bordeaux-Merignac'), - ] + data = [ + ("\u0153nologie", "oenologie"), + ("\u0152nologie", "OEnologie"), + ("l\xf8to", "loto"), + ("été", "ete"), + ("àèùéïîôêç", "aeueiioec"), + ("ÀÈÙÉÏÎÔÊÇ", "AEUEIIOEC"), + ("\xa0", " "), # NO-BREAK SPACE managed by NFKD decomposition + ("\u0154", "R"), + ("Pointe d\u2019Yves", "Pointe d'Yves"), + ("Bordeaux\u2013Mérignac", "Bordeaux-Merignac"), + ] for input, output in data: yield self.assertEqual, tu.unormalize(input), output def test_unormalize_substitute(self): - self.assertEqual(tu.unormalize(u'ab \u8000 cd', substitute='_'), - 'ab _ cd') + self.assertEqual(tu.unormalize("ab \u8000 cd", substitute="_"), "ab _ cd") def test_unormalize_backward_compat(self): - self.assertRaises(ValueError, tu.unormalize, u"\u8000") - self.assertEqual(tu.unormalize(u"\u8000", substitute=''), u'') + self.assertRaises(ValueError, tu.unormalize, "\u8000") + self.assertEqual(tu.unormalize("\u8000", substitute=""), "") def load_tests(loader, tests, ignore): @@ -275,5 +334,5 @@ def load_tests(loader, tests, ignore): return tests -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_tree.py b/test/test_tree.py index ea5af81..58a8ba9 100644 --- a/test/test_tree.py +++ b/test/test_tree.py @@ -23,12 +23,14 @@ squeleton generated by /home/syt/bin/py2tests on Jan 20 at 10:43:25 from logilab.common.testlib import TestCase, unittest_main from logilab.common.tree import * -tree = ('root', ( - ('child_1_1', ( - ('child_2_1', ()), ('child_2_2', ( - ('child_3_1', ()), - )))), - ('child_1_2', (('child_2_3', ()),)))) +tree = ( + "root", + ( + ("child_1_1", (("child_2_1", ()), ("child_2_2", (("child_3_1", ()),)))), + ("child_1_2", (("child_2_3", ()),)), + ), +) + def make_tree(tuple): n = Node(tuple[0]) @@ -36,123 +38,155 @@ def make_tree(tuple): n.append(make_tree(child)) return n + class Node_ClassTest(TestCase): """ a basic tree node, caracterised by an id""" + def setUp(self): """ called before each test from this class """ self.o = make_tree(tree) - def test_flatten(self): result = [r.id for r in self.o.flatten()] - expected = ['root', 'child_1_1', 'child_2_1', 'child_2_2', 'child_3_1', 'child_1_2', 'child_2_3'] + expected = [ + "root", + "child_1_1", + "child_2_1", + "child_2_2", + "child_3_1", + "child_1_2", + "child_2_3", + ] self.assertListEqual(result, expected) def test_flatten_with_outlist(self): resultnodes = [] self.o.flatten(resultnodes) result = [r.id for r in resultnodes] - expected = ['root', 'child_1_1', 'child_2_1', 'child_2_2', 'child_3_1', 'child_1_2', 'child_2_3'] + expected = [ + "root", + "child_1_1", + "child_2_1", + "child_2_2", + "child_3_1", + "child_1_2", + "child_2_3", + ] self.assertListEqual(result, expected) - def test_known_values_remove(self): """ remove a child node """ - self.o.remove(self.o.get_node_by_id('child_1_1')) - self.assertRaises(NodeNotFound, self.o.get_node_by_id, 'child_1_1') + self.o.remove(self.o.get_node_by_id("child_1_1")) + self.assertRaises(NodeNotFound, self.o.get_node_by_id, "child_1_1") def test_known_values_replace(self): """ replace a child node with another """ - self.o.replace(self.o.get_node_by_id('child_1_1'), Node('hoho')) - self.assertRaises(NodeNotFound, self.o.get_node_by_id, 'child_1_1') - self.assertEqual(self.o.get_node_by_id('hoho'), self.o.children[0]) + self.o.replace(self.o.get_node_by_id("child_1_1"), Node("hoho")) + self.assertRaises(NodeNotFound, self.o.get_node_by_id, "child_1_1") + self.assertEqual(self.o.get_node_by_id("hoho"), self.o.children[0]) def test_known_values_get_sibling(self): """ return the sibling node that has given id """ - self.assertEqual(self.o.children[0].get_sibling('child_1_2'), self.o.children[1], None) + self.assertEqual(self.o.children[0].get_sibling("child_1_2"), self.o.children[1], None) def test_raise_get_sibling_NodeNotFound(self): - self.assertRaises(NodeNotFound, self.o.children[0].get_sibling, 'houhou') + self.assertRaises(NodeNotFound, self.o.children[0].get_sibling, "houhou") def test_known_values_get_node_by_id(self): """ return node in whole hierarchy that has given id """ - self.assertEqual(self.o.get_node_by_id('child_1_1'), self.o.children[0]) + self.assertEqual(self.o.get_node_by_id("child_1_1"), self.o.children[0]) def test_raise_get_node_by_id_NodeNotFound(self): - self.assertRaises(NodeNotFound, self.o.get_node_by_id, 'houhou') + self.assertRaises(NodeNotFound, self.o.get_node_by_id, "houhou") def test_known_values_get_child_by_id(self): """ return child of given id """ - self.assertEqual(self.o.get_child_by_id('child_2_1', recurse=1), self.o.children[0].children[0]) + self.assertEqual( + self.o.get_child_by_id("child_2_1", recurse=1), self.o.children[0].children[0] + ) def test_raise_get_child_by_id_NodeNotFound(self): - self.assertRaises(NodeNotFound, self.o.get_child_by_id, nid='child_2_1') - self.assertRaises(NodeNotFound, self.o.get_child_by_id, 'houhou') + self.assertRaises(NodeNotFound, self.o.get_child_by_id, nid="child_2_1") + self.assertRaises(NodeNotFound, self.o.get_child_by_id, "houhou") def test_known_values_get_child_by_path(self): """ return child of given path (path is a list of ids) """ - self.assertEqual(self.o.get_child_by_path(['root', 'child_1_1', 'child_2_1']), self.o.children[0].children[0]) + self.assertEqual( + self.o.get_child_by_path(["root", "child_1_1", "child_2_1"]), + self.o.children[0].children[0], + ) def test_raise_get_child_by_path_NodeNotFound(self): - self.assertRaises(NodeNotFound, self.o.get_child_by_path, ['child_1_1', 'child_2_11']) + self.assertRaises(NodeNotFound, self.o.get_child_by_path, ["child_1_1", "child_2_11"]) def test_known_values_depth_down(self): """ return depth of this node in the tree """ self.assertEqual(self.o.depth_down(), 4) - self.assertEqual(self.o.get_child_by_id('child_2_1', True).depth_down(), 1) + self.assertEqual(self.o.get_child_by_id("child_2_1", True).depth_down(), 1) def test_known_values_depth(self): """ return depth of this node in the tree """ self.assertEqual(self.o.depth(), 0) - self.assertEqual(self.o.get_child_by_id('child_2_1', True).depth(), 2) + self.assertEqual(self.o.get_child_by_id("child_2_1", True).depth(), 2) def test_known_values_width(self): """ return depth of this node in the tree """ self.assertEqual(self.o.width(), 3) - self.assertEqual(self.o.get_child_by_id('child_2_1', True).width(), 1) + self.assertEqual(self.o.get_child_by_id("child_2_1", True).width(), 1) def test_known_values_root(self): """ return the root node of the tree """ - self.assertEqual(self.o.get_child_by_id('child_2_1', True).root(), self.o) + self.assertEqual(self.o.get_child_by_id("child_2_1", True).root(), self.o) def test_known_values_leaves(self): """ return a list with all the leaf nodes descendant from this task """ - self.assertEqual(self.o.leaves(), [self.o.get_child_by_id('child_2_1', True), - self.o.get_child_by_id('child_3_1', True), - self.o.get_child_by_id('child_2_3', True)]) + self.assertEqual( + self.o.leaves(), + [ + self.o.get_child_by_id("child_2_1", True), + self.o.get_child_by_id("child_3_1", True), + self.o.get_child_by_id("child_2_3", True), + ], + ) def test_known_values_lineage(self): - c31 = self.o.get_child_by_id('child_3_1', True) - self.assertEqual(c31.lineage(), [self.o.get_child_by_id('child_3_1', True), - self.o.get_child_by_id('child_2_2', True), - self.o.get_child_by_id('child_1_1', True), - self.o]) + c31 = self.o.get_child_by_id("child_3_1", True) + self.assertEqual( + c31.lineage(), + [ + self.o.get_child_by_id("child_3_1", True), + self.o.get_child_by_id("child_2_2", True), + self.o.get_child_by_id("child_1_1", True), + self.o, + ], + ) class post_order_list_FunctionTest(TestCase): """""" + def setUp(self): """ called before each test from this class """ self.o = make_tree(tree) @@ -162,7 +196,7 @@ class post_order_list_FunctionTest(TestCase): create a list with tree nodes for which the <filter> function returned true in a post order foashion """ - L = ['child_2_1', 'child_3_1', 'child_2_2', 'child_1_1', 'child_2_3', 'child_1_2', 'root'] + L = ["child_2_1", "child_3_1", "child_2_2", "child_1_1", "child_2_3", "child_1_2", "root"] l = [n.id for n in post_order_list(self.o)] self.assertEqual(l, L, l) @@ -171,23 +205,26 @@ class post_order_list_FunctionTest(TestCase): create a list with tree nodes for which the <filter> function returned true in a post order foashion """ + def filter(node): - if node.id == 'child_2_2': + if node.id == "child_2_2": return 0 return 1 - L = ['child_2_1', 'child_1_1', 'child_2_3', 'child_1_2', 'root'] + + L = ["child_2_1", "child_1_1", "child_2_3", "child_1_2", "root"] l = [n.id for n in post_order_list(self.o, filter)] self.assertEqual(l, L, l) class PostfixedDepthFirstIterator_ClassTest(TestCase): """""" + def setUp(self): """ called before each test from this class """ self.o = make_tree(tree) def test_known_values_next(self): - L = ['child_2_1', 'child_3_1', 'child_2_2', 'child_1_1', 'child_2_3', 'child_1_2', 'root'] + L = ["child_2_1", "child_3_1", "child_2_2", "child_1_1", "child_2_3", "child_1_2", "root"] iter = PostfixedDepthFirstIterator(self.o) o = next(iter) i = 0 @@ -199,6 +236,7 @@ class PostfixedDepthFirstIterator_ClassTest(TestCase): class pre_order_list_FunctionTest(TestCase): """""" + def setUp(self): """ called before each test from this class """ self.o = make_tree(tree) @@ -208,7 +246,7 @@ class pre_order_list_FunctionTest(TestCase): create a list with tree nodes for which the <filter> function returned true in a pre order fashion """ - L = ['root', 'child_1_1', 'child_2_1', 'child_2_2', 'child_3_1', 'child_1_2', 'child_2_3'] + L = ["root", "child_1_1", "child_2_1", "child_2_2", "child_3_1", "child_1_2", "child_2_3"] l = [n.id for n in pre_order_list(self.o)] self.assertEqual(l, L, l) @@ -217,23 +255,26 @@ class pre_order_list_FunctionTest(TestCase): create a list with tree nodes for which the <filter> function returned true in a pre order fashion """ + def filter(node): - if node.id == 'child_2_2': + if node.id == "child_2_2": return 0 return 1 - L = ['root', 'child_1_1', 'child_2_1', 'child_1_2', 'child_2_3'] + + L = ["root", "child_1_1", "child_2_1", "child_1_2", "child_2_3"] l = [n.id for n in pre_order_list(self.o, filter)] self.assertEqual(l, L, l) class PrefixedDepthFirstIterator_ClassTest(TestCase): """""" + def setUp(self): """ called before each test from this class """ self.o = make_tree(tree) def test_known_values_next(self): - L = ['root', 'child_1_1', 'child_2_1', 'child_2_2', 'child_3_1', 'child_1_2', 'child_2_3'] + L = ["root", "child_1_1", "child_2_1", "child_2_2", "child_3_1", "child_1_2", "child_2_3"] iter = PrefixedDepthFirstIterator(self.o) o = next(iter) i = 0 @@ -243,5 +284,5 @@ class PrefixedDepthFirstIterator_ClassTest(TestCase): i += 1 -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_umessage.py b/test/test_umessage.py index e70e386..7ae13e6 100644 --- a/test/test_umessage.py +++ b/test/test_umessage.py @@ -23,35 +23,36 @@ from os.path import join, dirname, abspath from logilab.common.testlib import TestCase, unittest_main from logilab.common.umessage import UMessage, decode_QP, message_from_string -DATA = join(dirname(abspath(__file__)), 'data') +DATA = join(dirname(abspath(__file__)), "data") -class UMessageTC(TestCase): +class UMessageTC(TestCase): def setUp(self): if sys.version_info >= (3, 2): import io - msg1 = email.message_from_file(io.open(join(DATA, 'test1.msg'), encoding='utf8')) - msg2 = email.message_from_file(io.open(join(DATA, 'test2.msg'), encoding='utf8')) + + msg1 = email.message_from_file(io.open(join(DATA, "test1.msg"), encoding="utf8")) + msg2 = email.message_from_file(io.open(join(DATA, "test2.msg"), encoding="utf8")) else: - msg1 = email.message_from_file(open(join(DATA, 'test1.msg'))) - msg2 = email.message_from_file(open(join(DATA, 'test2.msg'))) + msg1 = email.message_from_file(open(join(DATA, "test1.msg"))) + msg2 = email.message_from_file(open(join(DATA, "test2.msg"))) self.umessage1 = UMessage(msg1) self.umessage2 = UMessage(msg2) def test_get_subject(self): - subj = self.umessage2.get('Subject') + subj = self.umessage2.get("Subject") self.assertEqual(type(subj), str) - self.assertEqual(subj, u' LA MER') + self.assertEqual(subj, " LA MER") def test_get_all(self): - to = self.umessage2.get_all('To') + to = self.umessage2.get_all("To") self.assertEqual(type(to[0]), str) - self.assertEqual(to, [u'lment accents <alf@logilab.fr>']) + self.assertEqual(to, ["lment accents <alf@logilab.fr>"]) def test_get_payload_no_multi(self): payload = self.umessage1.get_payload() self.assertEqual(type(payload), str) - + def test_get_payload_decode(self): msg = """\ MIME-Version: 1.0 @@ -67,26 +68,26 @@ Date: now dW4gcGV0aXQgY8O2dWNvdQ== """ msg = message_from_string(msg) - self.assertEqual(msg.get_payload(decode=True), u'un petit cucou') + self.assertEqual(msg.get_payload(decode=True), "un petit cucou") def test_decode_QP(self): - test_line = '=??b?UmFwaGHrbA==?= DUPONT<raphael.dupont@societe.fr>' + test_line = "=??b?UmFwaGHrbA==?= DUPONT<raphael.dupont@societe.fr>" test = decode_QP(test_line) self.assertEqual(type(test), str) - self.assertEqual(test, u'Raphal DUPONT<raphael.dupont@societe.fr>') + self.assertEqual(test, "Raphal DUPONT<raphael.dupont@societe.fr>") def test_decode_QP_utf8(self): - test_line = '=?utf-8?q?o=C3=AEm?= <oim@logilab.fr>' + test_line = "=?utf-8?q?o=C3=AEm?= <oim@logilab.fr>" test = decode_QP(test_line) self.assertEqual(type(test), str) - self.assertEqual(test, u'om <oim@logilab.fr>') + self.assertEqual(test, "om <oim@logilab.fr>") def test_decode_QP_ascii(self): - test_line = 'test <test@logilab.fr>' + test_line = "test <test@logilab.fr>" test = decode_QP(test_line) self.assertEqual(type(test), str) - self.assertEqual(test, u'test <test@logilab.fr>') + self.assertEqual(test, "test <test@logilab.fr>") -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_ureports_html.py b/test/test_ureports_html.py index 2298eec..16300c9 100644 --- a/test/test_ureports_html.py +++ b/test/test_ureports_html.py @@ -15,31 +15,31 @@ # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. -'''unit tests for ureports.html_writer -''' +"""unit tests for ureports.html_writer +""" from utils import WriterTC from logilab.common.testlib import TestCase, unittest_main from logilab.common.ureports.html_writer import * -class HTMLWriterTC(TestCase, WriterTC): +class HTMLWriterTC(TestCase, WriterTC): def setUp(self): self.writer = HTMLWriter(1) # Section tests ########################################################### - section_base = '''<div> + section_base = """<div> <h1>Section title</h1> <p>Section\'s description. Blabla bla</p></div> -''' - section_nested = '''<div>\n<h1>Section title</h1>\n<p>Section\'s description.\nBlabla bla</p><div>\n<h2>Subsection</h2>\n<p>Sub section description</p></div>\n</div>\n''' +""" + section_nested = """<div>\n<h1>Section title</h1>\n<p>Section\'s description.\nBlabla bla</p><div>\n<h2>Subsection</h2>\n<p>Sub section description</p></div>\n</div>\n""" # List tests ############################################################## - list_base = '''<ul>\n<li>item1</li>\n<li>item2</li>\n<li>item3</li>\n<li>item4</li>\n</ul>\n''' + list_base = """<ul>\n<li>item1</li>\n<li>item2</li>\n<li>item3</li>\n<li>item4</li>\n</ul>\n""" - nested_list = '''<ul> + nested_list = """<ul> <li><p>blabla<ul> <li>1</li> <li>2</li> @@ -48,16 +48,16 @@ Blabla bla</p></div> </p></li> <li>an other point</li> </ul> -''' +""" # Table tests ############################################################# - table_base = '''<table>\n<tr class="odd">\n<td>head1</td>\n<td>head2</td>\n</tr>\n<tr class="even">\n<td>cell1</td>\n<td>cell2</td>\n</tr>\n</table>\n''' - field_table = '''<table class="field" id="mytable">\n<tr class="odd">\n<td>f1</td>\n<td>v1</td>\n</tr>\n<tr class="even">\n<td>f22</td>\n<td>v22</td>\n</tr>\n<tr class="odd">\n<td>f333</td>\n<td>v333</td>\n</tr>\n</table>\n''' - advanced_table = '''<table class="whatever" id="mytable">\n<tr class="header">\n<th>field</th>\n<th>value</th>\n</tr>\n<tr class="even">\n<td>f1</td>\n<td>v1</td>\n</tr>\n<tr class="odd">\n<td>f22</td>\n<td>v22</td>\n</tr>\n<tr class="even">\n<td>f333</td>\n<td>v333</td>\n</tr>\n<tr class="odd">\n<td> <a href="http://www.perdu.com">toi perdu ?</a></td>\n<td> </td>\n</tr>\n</table>\n''' - + table_base = """<table>\n<tr class="odd">\n<td>head1</td>\n<td>head2</td>\n</tr>\n<tr class="even">\n<td>cell1</td>\n<td>cell2</td>\n</tr>\n</table>\n""" + field_table = """<table class="field" id="mytable">\n<tr class="odd">\n<td>f1</td>\n<td>v1</td>\n</tr>\n<tr class="even">\n<td>f22</td>\n<td>v22</td>\n</tr>\n<tr class="odd">\n<td>f333</td>\n<td>v333</td>\n</tr>\n</table>\n""" + advanced_table = """<table class="whatever" id="mytable">\n<tr class="header">\n<th>field</th>\n<th>value</th>\n</tr>\n<tr class="even">\n<td>f1</td>\n<td>v1</td>\n</tr>\n<tr class="odd">\n<td>f22</td>\n<td>v22</td>\n</tr>\n<tr class="even">\n<td>f333</td>\n<td>v333</td>\n</tr>\n<tr class="odd">\n<td> <a href="http://www.perdu.com">toi perdu ?</a></td>\n<td> </td>\n</tr>\n</table>\n""" # VerbatimText tests ###################################################### - verbatim_base = '''<pre>blablabla</pre>''' + verbatim_base = """<pre>blablabla</pre>""" + -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_ureports_text.py b/test/test_ureports_text.py index dd39dd8..cc602dc 100644 --- a/test/test_ureports_text.py +++ b/test/test_ureports_text.py @@ -15,27 +15,28 @@ # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. -'''unit tests for ureports.text_writer -''' +"""unit tests for ureports.text_writer +""" from utils import WriterTC from logilab.common.testlib import TestCase, unittest_main from logilab.common.ureports.text_writer import TextWriter + class TextWriterTC(TestCase, WriterTC): def setUp(self): self.writer = TextWriter() # Section tests ########################################################### - section_base = ''' + section_base = """ Section title ============= Section\'s description. Blabla bla -''' - section_nested = ''' +""" + section_nested = """ Section title ============= Section\'s description. @@ -46,38 +47,38 @@ Subsection Sub section description -''' +""" # List tests ############################################################## - list_base = ''' + list_base = """ * item1 * item2 * item3 -* item4''' +* item4""" - nested_list = ''' + nested_list = """ * blabla - 1 - 2 - 3 -* an other point''' +* an other point""" # Table tests ############################################################# - table_base = ''' + table_base = """ +------+------+ |head1 |head2 | +------+------+ |cell1 |cell2 | +------+------+ -''' - field_table = ''' +""" + field_table = """ f1 : v1 f22 : v22 f333: v333 -''' - advanced_table = ''' +""" + advanced_table = """ +---------------+------+ |field |value | +===============+======+ @@ -90,15 +91,15 @@ f333: v333 |`toi perdu ?`_ | | +---------------+------+ -''' - +""" # VerbatimText tests ###################################################### - verbatim_base = ''':: + verbatim_base = """:: blablabla -''' +""" + -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() diff --git a/test/test_xmlutils.py b/test/test_xmlutils.py index 3d82da9..92a058d 100644 --- a/test/test_xmlutils.py +++ b/test/test_xmlutils.py @@ -26,7 +26,7 @@ class ProcessingInstructionDataParsingTest(TestCase): """ Tests the parsing of the data of an empty processing instruction. """ - pi_data = u" \t \n " + pi_data = " \t \n " data = parse_pi_data(pi_data) self.assertEqual(data, {}) @@ -35,41 +35,39 @@ class ProcessingInstructionDataParsingTest(TestCase): Tests the parsing of the data of a simple processing instruction using double quotes for embedding the value. """ - pi_data = u""" \t att="value"\n """ + pi_data = """ \t att="value"\n """ data = parse_pi_data(pi_data) - self.assertEqual(data, {u"att": u"value"}) + self.assertEqual(data, {"att": "value"}) def test_simple_pi_with_simple_quotes(self): """ Tests the parsing of the data of a simple processing instruction using simple quotes for embedding the value. """ - pi_data = u""" \t att='value'\n """ + pi_data = """ \t att='value'\n """ data = parse_pi_data(pi_data) - self.assertEqual(data, {u"att": u"value"}) + self.assertEqual(data, {"att": "value"}) def test_complex_pi_with_different_quotes(self): """ Tests the parsing of the data of a complex processing instruction using simple quotes or double quotes for embedding the values. """ - pi_data = u""" \t att='value'\n att2="value2" att3='value3'""" + pi_data = """ \t att='value'\n att2="value2" att3='value3'""" data = parse_pi_data(pi_data) - self.assertEqual(data, {u"att": u"value", u"att2": u"value2", - u"att3": u"value3"}) + self.assertEqual(data, {"att": "value", "att2": "value2", "att3": "value3"}) def test_pi_with_non_attribute_data(self): """ Tests the parsing of the data of a complex processing instruction containing non-attribute data. """ - pi_data = u""" \t keyword att1="value1" """ + pi_data = """ \t keyword att1="value1" """ data = parse_pi_data(pi_data) - self.assertEqual(data, {u"keyword": None, u"att1": u"value1"}) + self.assertEqual(data, {"keyword": None, "att1": "value1"}) # definitions for automatic unit testing -if __name__ == '__main__': +if __name__ == "__main__": unittest_main() - diff --git a/test/utils.py b/test/utils.py index ca1730e..de9bc23 100644 --- a/test/utils.py +++ b/test/utils.py @@ -15,21 +15,24 @@ # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. -'''unit tests utilities for ureports -''' +"""unit tests utilities for ureports +""" from __future__ import print_function import sys from io import StringIO + buffers = [StringIO] if sys.version_info < (3, 0): from cStringIO import StringIO as cStringIO from StringIO import StringIO as pStringIO + buffers += [cStringIO, pStringIO] from logilab.common.ureports.nodes import * + class WriterTC: def _test_output(self, test_id, layout, msg=None): for buffercls in buffers: @@ -40,55 +43,53 @@ class WriterTC: try: self.assertMultiLineEqual(got, expected) except: - print('**** using a %s' % buffer.__class__) - print('**** got for %s' % test_id) + print("**** using a %s" % buffer.__class__) + print("**** got for %s" % test_id) print(got) - print('**** while expected') + print("**** while expected") print(expected) - print('****') + print("****") raise def test_section(self): - layout = Section('Section title', - 'Section\'s description.\nBlabla bla') - self._test_output('section_base', layout) - layout.append(Section('Subsection', 'Sub section description')) - self._test_output('section_nested', layout) + layout = Section("Section title", "Section's description.\nBlabla bla") + self._test_output("section_base", layout) + layout.append(Section("Subsection", "Sub section description")) + self._test_output("section_nested", layout) def test_verbatim(self): - layout = VerbatimText('blablabla') - self._test_output('verbatim_base', layout) - + layout = VerbatimText("blablabla") + self._test_output("verbatim_base", layout) def test_list(self): - layout = List(children=('item1', 'item2', 'item3', 'item4')) - self._test_output('list_base', layout) + layout = List(children=("item1", "item2", "item3", "item4")) + self._test_output("list_base", layout) def test_nested_list(self): - layout = List(children=(Paragraph(("blabla", List(children=('1', "2", "3")))), - "an other point")) - self._test_output('nested_list', layout) - + layout = List( + children=(Paragraph(("blabla", List(children=("1", "2", "3")))), "an other point") + ) + self._test_output("nested_list", layout) def test_table(self): - layout = Table(cols=2, children=('head1', 'head2', 'cell1', 'cell2')) - self._test_output('table_base', layout) + layout = Table(cols=2, children=("head1", "head2", "cell1", "cell2")) + self._test_output("table_base", layout) def test_field_table(self): - table = Table(cols=2, klass='field', id='mytable') - for field, value in (('f1', 'v1'), ('f22', 'v22'), ('f333', 'v333')): + table = Table(cols=2, klass="field", id="mytable") + for field, value in (("f1", "v1"), ("f22", "v22"), ("f333", "v333")): table.append(Text(field)) table.append(Text(value)) - self._test_output('field_table', table) + self._test_output("field_table", table) def test_advanced_table(self): - table = Table(cols=2, klass='whatever', id='mytable', rheaders=1) - for field, value in (('field', 'value'), ('f1', 'v1'), ('f22', 'v22'), ('f333', 'v333')): + table = Table(cols=2, klass="whatever", id="mytable", rheaders=1) + for field, value in (("field", "value"), ("f1", "v1"), ("f22", "v22"), ("f333", "v333")): table.append(Text(field)) table.append(Text(value)) - table.append(Link('http://www.perdu.com', 'toi perdu ?')) - table.append(Text('')) - self._test_output('advanced_table', table) + table.append(Link("http://www.perdu.com", "toi perdu ?")) + table.append(Text("")) + self._test_output("advanced_table", table) ## def test_image(self): |