diff options
| author | whitespace <nobody@nobody> | 2020-10-07 17:22:26 -0400 | 
|---|---|---|
| committer | Quentin Young <qlyoung@nvidia.com> | 2020-10-07 17:22:26 -0400 | 
| commit | 701a01920eee5431d2052aad92aefbdf50ac2139 (patch) | |
| tree | 2bf2339327241f59593b9583b060ebb347db1cea /tests/helpers | |
| parent | bd407b54d26981f30a95bc316ea2ed965d070c53 (diff) | |
*: reformat python files
We are now using black.
Signed-off-by: Quentin Young <qlyoung@nvidia.com>
Diffstat (limited to 'tests/helpers')
| -rw-r--r-- | tests/helpers/python/frrsix.py | 21 | ||||
| -rw-r--r-- | tests/helpers/python/frrtest.py | 100 | 
2 files changed, 74 insertions, 47 deletions
diff --git a/tests/helpers/python/frrsix.py b/tests/helpers/python/frrsix.py index 91714f0c67..df737d92ef 100644 --- a/tests/helpers/python/frrsix.py +++ b/tests/helpers/python/frrsix.py @@ -29,24 +29,29 @@ import sys  PY2 = sys.version_info[0] == 2  PY3 = sys.version_info[0] == 3 +  def add_metaclass(metaclass):      """Class decorator for creating a class with a metaclass.""" +      def wrapper(cls):          orig_vars = cls.__dict__.copy() -        slots = orig_vars.get('__slots__') +        slots = orig_vars.get("__slots__")          if slots is not None:              if isinstance(slots, str):                  slots = [slots]              for slots_var in slots:                  orig_vars.pop(slots_var) -        orig_vars.pop('__dict__', None) -        orig_vars.pop('__weakref__', None) +        orig_vars.pop("__dict__", None) +        orig_vars.pop("__weakref__", None)          return metaclass(cls.__name__, cls.__bases__, orig_vars) +      return wrapper +  if PY3:      import builtins -    exec_ = getattr(builtins,'exec') + +    exec_ = getattr(builtins, "exec")      def reraise(tp, value, tb=None):          try: @@ -59,7 +64,9 @@ if PY3:              value = None              tb = None +  else: +      def exec_(_code_, _globs_=None, _locs_=None):          """Execute code in a namespace."""          if _globs_ is None: @@ -72,9 +79,11 @@ else:              _locs_ = _globs_          exec("""exec _code_ in _globs_, _locs_""") -    exec_("""def reraise(tp, value, tb=None): +    exec_( +        """def reraise(tp, value, tb=None):      try:          raise tp, value, tb      finally:          tb = None -""") +""" +    ) diff --git a/tests/helpers/python/frrtest.py b/tests/helpers/python/frrtest.py index 60bee5c88c..0ac54fd900 100644 --- a/tests/helpers/python/frrtest.py +++ b/tests/helpers/python/frrtest.py @@ -39,35 +39,41 @@ import frrsix  srcbase = os.path.abspath(inspect.getsourcefile(frrsix))  for i in range(0, 3):      srcbase = os.path.dirname(srcbase) + +  def binpath(srcpath):      return os.path.relpath(os.path.abspath(srcpath), srcbase) +  class MultiTestFailure(Exception):      pass +  class MetaTestMultiOut(type):      def __getattr__(cls, name): -        if name.startswith('_'): +        if name.startswith("_"):              raise AttributeError -        internal_name = '_{}'.format(name) +        internal_name = "_{}".format(name)          if internal_name not in dir(cls):              raise AttributeError          def registrar(*args, **kwargs): -            cls._add_test(getattr(cls,internal_name), *args, **kwargs) +            cls._add_test(getattr(cls, internal_name), *args, **kwargs) +          return registrar +  @frrsix.add_metaclass(MetaTestMultiOut)  class _TestMultiOut(object):      def _run_tests(self): -        if 'tests_run' in dir(self.__class__) and self.tests_run: +        if "tests_run" in dir(self.__class__) and self.tests_run:              return          self.__class__.tests_run = True          basedir = os.path.dirname(inspect.getsourcefile(type(self)))          program = os.path.join(basedir, self.program)          proc = subprocess.Popen([binpath(program)], stdout=subprocess.PIPE) -        self.output,_ = proc.communicate('') +        self.output, _ = proc.communicate("")          self.exitcode = proc.wait()          self.__class__.testresults = {} @@ -85,13 +91,14 @@ class _TestMultiOut(object):      @classmethod      def _add_test(cls, method, *args, **kwargs): -        if 'tests' not in dir(cls): -            setattr(cls,'tests',[]) +        if "tests" not in dir(cls): +            setattr(cls, "tests", [])              if method is not cls._exit_cleanly:                  cls._add_test(cls._exit_cleanly)          def matchfunction(self):              method(self, *args, **kwargs) +          cls.tests.append(matchfunction)          def testfunction(self): @@ -100,17 +107,18 @@ class _TestMultiOut(object):              if result is not None:                  frrsix.reraise(*result) -        testname = re.sub(r'[^A-Za-z0-9]', '_', '%r%r' % (args, kwargs)) -        testname = re.sub(r'__*', '_', testname) -        testname = testname.strip('_') +        testname = re.sub(r"[^A-Za-z0-9]", "_", "%r%r" % (args, kwargs)) +        testname = re.sub(r"__*", "_", testname) +        testname = testname.strip("_")          if not testname: -            testname = method.__name__.strip('_') +            testname = method.__name__.strip("_")          if "test_%s" % testname in dir(cls):              index = 2 -            while "test_%s_%d" % (testname,index) in dir(cls): +            while "test_%s_%d" % (testname, index) in dir(cls):                  index += 1              testname = "%s_%d" % (testname, index) -        setattr(cls,"test_%s" % testname, testfunction) +        setattr(cls, "test_%s" % testname, testfunction) +  #  # This class houses the actual TestMultiOut tests types. @@ -127,15 +135,16 @@ class _TestMultiOut(object):  # modified according to consumed content.  # -re_okfail = re.compile(r'(?:[3[12]m|^)?(?P<ret>OK|failed)'.encode('utf8'), -                       re.MULTILINE) +re_okfail = re.compile(r"(?:[3[12]m|^)?(?P<ret>OK|failed)".encode("utf8"), re.MULTILINE) + +  class TestMultiOut(_TestMultiOut):      def _onesimple(self, line):          if type(line) is str: -            line = line.encode('utf8') +            line = line.encode("utf8")          idx = self.output.find(line)          if idx != -1: -            self.output = self.output[idx+len(line):] +            self.output = self.output[idx + len(line) :]          else:              raise MultiTestFailure("%r could not be found" % line) @@ -144,58 +153,67 @@ class TestMultiOut(_TestMultiOut):          m = okfail.search(self.output)          if m is None: -            raise MultiTestFailure('OK/fail not found') -        self.output = self.output[m.end():] +            raise MultiTestFailure("OK/fail not found") +        self.output = self.output[m.end() :] + +        if m.group("ret") != "OK".encode("utf8"): +            raise MultiTestFailure("Test output indicates failure") -        if m.group('ret') != 'OK'.encode('utf8'): -            raise MultiTestFailure('Test output indicates failure')  #  # This class implements a test comparing the output of a program against  # an existing reference output  # +  class TestRefMismatch(Exception):      def __init__(self, _test, outtext, reftext): -        self.outtext = outtext.decode('utf8') if type(outtext) is bytes else outtext -        self.reftext = reftext.decode('utf8') if type(reftext) is bytes else reftext +        self.outtext = outtext.decode("utf8") if type(outtext) is bytes else outtext +        self.reftext = reftext.decode("utf8") if type(reftext) is bytes else reftext      def __str__(self): -        rv = 'Expected output and actual output differ:\n' -        rv += '\n'.join(difflib.unified_diff(self.reftext.splitlines(), -                                             self.outtext.splitlines(), -                                             'outtext', 'reftext', -                                             lineterm='')) +        rv = "Expected output and actual output differ:\n" +        rv += "\n".join( +            difflib.unified_diff( +                self.reftext.splitlines(), +                self.outtext.splitlines(), +                "outtext", +                "reftext", +                lineterm="", +            ) +        )          return rv +  class TestExitNonzero(Exception):      pass +  class TestRefOut(object):      def test_refout(self):          basedir = os.path.dirname(inspect.getsourcefile(type(self)))          program = os.path.join(basedir, self.program) -        if getattr(self, 'built_refin', False): -            refin = binpath(program) + '.in' +        if getattr(self, "built_refin", False): +            refin = binpath(program) + ".in"          else: -            refin = program + '.in' -        if getattr(self, 'built_refout', False): -            refout = binpath(program) + '.refout' +            refin = program + ".in" +        if getattr(self, "built_refout", False): +            refout = binpath(program) + ".refout"          else: -            refout = program + '.refout' +            refout = program + ".refout" -        intext = '' +        intext = ""          if os.path.exists(refin): -            with open(refin, 'rb') as f: +            with open(refin, "rb") as f:                  intext = f.read() -        with open(refout, 'rb') as f: +        with open(refout, "rb") as f:              reftext = f.read() -        proc = subprocess.Popen([binpath(program)], -                                stdin=subprocess.PIPE, -                                stdout=subprocess.PIPE) -        outtext,_ = proc.communicate(intext) +        proc = subprocess.Popen( +            [binpath(program)], stdin=subprocess.PIPE, stdout=subprocess.PIPE +        ) +        outtext, _ = proc.communicate(intext)          if outtext != reftext:              raise TestRefMismatch(self, outtext, reftext)          if proc.wait() != 0:  | 
