[PATCH 2 of 2 eac] extract ctx_assert from the tests

Denis Laxalde denis.laxalde at logilab.fr
Thu Sep 5 09:53:18 CEST 2019


Frank Bessou a écrit :
> # HG changeset patch
> # User Frank Bessou <frank.bessou at logilab.fr>
> # Date 1567608525 -7200
> #      Wed Sep 04 16:48:45 2019 +0200
> # Node ID 283e2fe96d57eaae4a98c9aec0c0515de403a994
> # Parent  850a27100121faf395d73dec6436f9ad7c4f10da
> # Available At http://hg.logilab.org/review/cubes/eac
> #              hg pull http://hg.logilab.org/review/cubes/eac -r 283e2fe96d57
> extract ctx_assert from the tests
> 
> diff --git a/test/test_dataimport.py b/test/test_dataimport.py
> --- a/test/test_dataimport.py
> +++ b/test/test_dataimport.py
> @@ -69,6 +69,17 @@ def datapath(*fname):
>      return join(dirname(__file__), 'data', *fname)
>  
>  
> +def ctx_assert(assert_method, actual, expected, ctx, msg=None):
> +    """Wrap assertion method with a context message"""
> +    try:
> +        assert_method(actual, expected, msg=msg)
> +    except AssertionError as exc:
> +        msg = str(exc)
> +        if ctx:
> +            msg = ('[%s] ' % ctx) + msg
> +        reraise(AssertionError, AssertionError(msg), sys.exc_info()[-1])


I wonder if this couldn't be implemented as a context manager, e.g.
(untested):

@contextmanager
def ctx_assert(ctx):
    try:
        yield
    except AssertionError as exc:
        msg = '%s %s' % (exc, exc)
        reraise(AssertionError, AssertionError(msg), sys.exc_info()[-1])

This way "ctx_assert" doesn't need to know about the assertion logic
(method / values); see example usage below.

> +
> +
>  class EACXMLParserTC(unittest.TestCase):
>  
>      if sys.version_info < (3, 2):
> @@ -763,21 +774,11 @@ class EACXMLParserTC(unittest.TestCase):
>          self.assertIn(expected, [x.values['parts'].pop() for x in entities
>                                   if x.etype == 'NameEntry'])
>  
> -    def ctx_assert(self, method, actual, expected, ctx, msg=None):
> -        """Wrap assertion method with a context message"""
> -        try:
> -            getattr(self, method)(actual, expected, msg=msg)
> -        except AssertionError as exc:
> -            msg = str(exc)
> -            if ctx:
> -                msg = ('[%s] ' % ctx) + msg
> -            reraise(AssertionError, AssertionError(msg), sys.exc_info()[-1])
> -
>      def check_external_entities(self, entities, expected):
>          entities = extentities2dict(entities)
>          expected = extentities2dict(expected)
>          etypes, expected_etypes = list(entities), list(expected)
> -        self.ctx_assert('assertCountEqual', etypes, expected_etypes, ctx='etypes')
> +        ctx_assert(self.assertCountEqual, etypes, expected_etypes, ctx='etypes')

with ctx_assert('etypes'):
    self.assertCountEqual(etypes, expected_etypes)

>  
>          def safe_int(value):
>              try:



More information about the saem-devel mailing list