Skip to content

Commit f996f4a

Browse files
author
Sylvain MARIE
committed
Fixed most flake8 errors and updated documentation to use genbadge. Slightly improved coverage too. Fixes #223
1 parent 1ea6e85 commit f996f4a

12 files changed

+95
-62
lines changed

pytest_cases/__init__.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,10 @@
55
from .common_pytest_lazy_values import lazy_value, is_lazy
66
from .common_others import unfold_expected_err, assert_exception, AUTO
77

8-
AUTO2 = AUTO
9-
"""Deprecated symbol, for retrocompatibility. Will be dropped soon."""
10-
118
from .fixture_core1_unions import fixture_union, NOT_USED, unpack_fixture, ignore_unused
129
from .fixture_core2 import pytest_fixture_plus, fixture_plus, fixture, param_fixtures, param_fixture
1310
from .fixture_parametrize_plus import pytest_parametrize_plus, parametrize_plus, parametrize, fixture_ref
1411

15-
1612
from .case_funcs import case, copy_case_info, set_case_id, get_case_id, get_case_marks, \
1713
get_case_tags, matches_tag_query, is_case_class, is_case_function
1814
from .case_parametrizer_new import parametrize_with_cases, THIS_MODULE, get_all_cases, get_parametrize_args, \
@@ -29,6 +25,11 @@
2925
from os import path as _path
3026
__version__ = _gv(_path.join(_path.dirname(__file__), _path.pardir))
3127

28+
29+
AUTO2 = AUTO
30+
"""Deprecated symbol, for retrocompatibility. Will be dropped soon."""
31+
32+
3233
__all__ = [
3334
'__version__',
3435
# the submodules

pytest_cases/case_funcs.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from decopatch import function_decorator, DECORATED
77

88
try: # python 3.5+
9-
from typing import Type, Callable, Union, Optional, Any, Tuple, Dict, Iterable, List, Set
9+
from typing import Callable, Union, Optional, Any, Tuple, Iterable, List, Set
1010
except ImportError:
1111
pass
1212

@@ -275,10 +275,16 @@ def matches_tag_query(case_fun, # type: Callable
275275
return selected
276276

277277

278+
try:
279+
SeveralMarkDecorators = Union[Tuple[MarkDecorator, ...], List[MarkDecorator], Set[MarkDecorator]]
280+
except: # noqa
281+
pass
282+
283+
278284
@function_decorator
279285
def case(id=None, # type: str # noqa
280286
tags=None, # type: Union[Any, Iterable[Any]]
281-
marks=(), # type: Union[MarkDecorator, Tuple[MarkDecorator, ...], List[MarkDecorator], Set[MarkDecorator]]
287+
marks=(), # type: Union[MarkDecorator, SeveralMarkDecorators]
282288
case_func=DECORATED # noqa
283289
):
284290
"""

pytest_cases/case_parametrizer_new.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from .common_others import get_code_first_line, AUTO, qname, funcopy, needs_binding, get_function_host, \
2323
in_same_module, get_host_module, get_class_that_defined_method
2424
from .common_pytest_marks import copy_pytest_marks, make_marked_parameter_value, remove_pytest_mark, filter_marks, \
25-
get_param_argnames_as_list
25+
get_param_argnames_as_list, Mark
2626
from .common_pytest_lazy_values import LazyValue, LazyTuple, LazyTupleItem
2727
from .common_pytest import safe_isclass, MiniMetafunc, is_fixture, get_fixture_name, inject_host, add_fixture_params, \
2828
list_all_fixtures_in, get_pytest_request_and_item, safe_isinstance
@@ -269,8 +269,8 @@ def get_all_cases(parametrization_target, # type: Callable
269269
for c in cases:
270270
# load case or cases depending on type
271271
if safe_isclass(c):
272-
# class
273-
new_cases = extract_cases_from_class(c, case_fun_prefix=prefix, check_name=False) # do not check name, it was explicitly passed
272+
# class - do not check name, it was explicitly passed
273+
new_cases = extract_cases_from_class(c, case_fun_prefix=prefix, check_name=False)
274274
cases_funs += new_cases
275275
elif callable(c):
276276
# function
@@ -303,7 +303,7 @@ def get_parametrize_args(host_class_or_module, # type: Union[Type, ModuleType
303303
import_fixtures=False, # type: bool
304304
debug=False # type: bool
305305
):
306-
# type: (...) -> List[Union[lazy_value, fixture_ref]]
306+
# type: (...) -> List[CaseParamValue]
307307
"""
308308
Transforms a list of cases (obtained from `get_all_cases`) into a list of argvalues for `@parametrize`.
309309
Each case function `case_fun` is transformed into one or several `lazy_value`(s) or a `fixture_ref`:
@@ -387,7 +387,7 @@ def case_to_argvalues(host_class_or_module, # type: Union[Type, ModuleType]
387387
import_fixtures=False, # type: bool
388388
debug=False # type: bool
389389
):
390-
# type: (...) -> Tuple[lazy_value]
390+
# type: (...) -> Tuple[CaseParamValue, ...]
391391
"""Transform a single case into one or several `lazy_value`(s) or a `fixture_ref` to be used in `@parametrize`
392392
393393
If `case_fun` requires at least on fixture, a fixture will be created if not yet present, and a `fixture_ref` will
@@ -464,7 +464,7 @@ def get_or_create_case_fixture(case_id, # type: str
464464
import_fixtures=False, # type: bool
465465
debug=False # type: bool
466466
):
467-
# type: (...) -> Tuple[str, Tuple[MarkInfo]]
467+
# type: (...) -> Tuple[str, Tuple[Mark]]
468468
"""
469469
When case functions require fixtures, we want to rely on pytest to inject everything. Therefore
470470
we create a "case fixture" wrapping the case function. Since a case function may not be located in the same place
@@ -529,8 +529,8 @@ def get_or_create_case_fixture(case_id, # type: str
529529
for f in list_all_fixtures_in(true_case_func_host, recurse_to_module=False, return_names=False):
530530
f_name = get_fixture_name(f)
531531
if (f_name in existing_fixture_names) or (f.__name__ in existing_fixture_names):
532-
raise ValueError("Cannot import fixture %r from %r as it would override an existing symbol in "
533-
"%r. Please set `@parametrize_with_cases(import_fixtures=False)`"
532+
raise ValueError("Cannot import fixture %r from %r as it would override an existing symbol "
533+
"in %r. Please set `@parametrize_with_cases(import_fixtures=False)`"
534534
"" % (f, from_module, target_host))
535535
target_host_module = target_host if not target_in_class else get_host_module(target_host)
536536
setattr(target_host_module, f.__name__, f)
@@ -786,7 +786,8 @@ def _of_interest(x): # noqa
786786
for m_name, m in getmembers(container, _of_interest):
787787
if is_case_class(m):
788788
co_firstlineno = get_code_first_line(m)
789-
cls_cases = extract_cases_from_class(m, case_fun_prefix=case_fun_prefix, _case_param_factory=_case_param_factory)
789+
cls_cases = extract_cases_from_class(m, case_fun_prefix=case_fun_prefix,
790+
_case_param_factory=_case_param_factory)
790791
for _i, _m_item in enumerate(cls_cases):
791792
gen_line_nb = co_firstlineno + (_i / len(cls_cases))
792793
cases_dct[gen_line_nb] = _m_item

pytest_cases/common_mini_six.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
if PY3:
1111
string_types = str,
1212
else:
13-
string_types = basestring,
13+
string_types = basestring, # noqa
1414

1515

1616
# if PY3:
@@ -49,17 +49,17 @@
4949
# """)
5050

5151

52-
def with_metaclass(meta, *bases):
53-
"""Create a base class with a metaclass."""
54-
# This requires a bit of explanation: the basic idea is to make a dummy
55-
# metaclass for one level of class instantiation that replaces itself with
56-
# the actual metaclass.
57-
class metaclass(type):
58-
59-
def __new__(cls, name, this_bases, d):
60-
return meta(name, bases, d)
61-
62-
@classmethod
63-
def __prepare__(cls, name, this_bases):
64-
return meta.__prepare__(name, bases)
65-
return type.__new__(metaclass, 'temporary_class', (), {})
52+
# def with_metaclass(meta, *bases):
53+
# """Create a base class with a metaclass."""
54+
# # This requires a bit of explanation: the basic idea is to make a dummy
55+
# # metaclass for one level of class instantiation that replaces itself with
56+
# # the actual metaclass.
57+
# class metaclass(type):
58+
#
59+
# def __new__(cls, name, this_bases, d):
60+
# return meta(name, bases, d)
61+
#
62+
# @classmethod
63+
# def __prepare__(cls, name, this_bases):
64+
# return meta.__prepare__(name, bases)
65+
# return type.__new__(metaclass, 'temporary_class', (), {})

pytest_cases/common_others.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def get_code_first_line(f):
3838
raise ValueError("Cannot get code information for function or class %r" % f)
3939

4040

41-
# Below is the beginning of a switch from our code scanning tool above to the same one than pytest. See `case_parametrizer_new`
41+
# Below is the beginning of a switch from our scanning code to the same one than pytest. See `case_parametrizer_new`
4242
# from _pytest.compat import get_real_func as compat_get_real_func
4343
#
4444
# try:
@@ -49,13 +49,19 @@ def get_code_first_line(f):
4949
try:
5050
ExpectedError = Optional[Union[Type[Exception], str, Exception, Callable[[Exception], Optional[bool]]]]
5151
"""The expected error in case failure is expected. An exception type, instance, or a validation function"""
52+
53+
ExpectedErrorType = Optional[Type[BaseException]]
54+
ExpectedErrorPattern = Optional[re.Pattern]
55+
ExpectedErrorInstance = Optional[BaseException]
56+
ExpectedErrorValidator = Optional[Callable[[BaseException], Optional[bool]]]
57+
5258
except: # noqa
5359
pass
5460

5561

5662
def unfold_expected_err(expected_e # type: ExpectedError
5763
):
58-
# type: (...) -> Tuple[Optional[Type[BaseException]], Optional[re.Pattern], Optional[BaseException], Optional[Callable[[BaseException], Optional[bool]]]]
64+
# type: (...) -> Tuple[ExpectedErrorType, ExpectedErrorPattern, ExpectedErrorInstance, ExpectedErrorValidator]
5965
"""
6066
'Unfolds' the expected error `expected_e` to return a tuple of
6167
- expected error type
@@ -132,7 +138,7 @@ class MyErr(ValueError):
132138
raise TypeError()
133139
134140
# good repr pattern - ok
135-
with assert_exception(r"ValueError\('hello'[,]+\)"):
141+
with assert_exception(r"ValueError\\('hello'[,]+\\)"):
136142
raise ValueError("hello")
137143
138144
# good instance equality check - ok

pytest_cases/common_pytest.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,10 @@
1616
except ImportError:
1717
from funcsigs import signature, Parameter # noqa
1818

19-
from distutils.version import LooseVersion
2019
from inspect import isgeneratorfunction, isclass
2120

2221
try:
23-
from typing import Union, Callable, Any, Optional, Tuple, Type # noqa
22+
from typing import Union, Callable, Any, Optional, Tuple, Type, Iterable, Sized, List # noqa
2423
except ImportError:
2524
pass
2625

pytest_cases/common_pytest_lazy_values.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __eq__(self, other):
5555
"""Default equality method based on the _field_names"""
5656
try:
5757
return all(getattr(self, k) == getattr(other, k) for k in self._field_names)
58-
except:
58+
except Exception: # noqa
5959
return False
6060

6161
def __repr__(self):
@@ -85,7 +85,7 @@ def _unwrap(obj):
8585
Note: maybe from inspect import unwrap could do the same?
8686
"""
8787
start_obj = obj
88-
for i in range(100):
88+
for _ in range(100):
8989
# __pytest_wrapped__ is set by @pytest.fixture when wrapping the fixture function
9090
# to trigger a warning if it gets called directly instead of by pytest: we don't
9191
# want to unwrap further than this otherwise we lose useful wrappings like @mock.patch (#3774)
@@ -303,9 +303,16 @@ def __hash__(self):
303303

304304
def __repr__(self):
305305
"""Override the inherited method to avoid infinite recursion"""
306+
307+
# lazy value tuple or cached tuple
308+
if self.host.has_cached_value(raise_if_no_context=False):
309+
tuple_to_represent = self.host.cached_value
310+
else:
311+
tuple_to_represent = self.host._lazyvalue # noqa
312+
306313
vals_to_display = (
307314
('item', self.item), # item number first for easier debug
308-
('tuple', self.host.cached_value if self.host.has_cached_value(raise_if_no_context=False) else self.host._lazyvalue), # lazy value tuple or cached tuple
315+
('tuple', tuple_to_represent),
309316
)
310317
return "%s(%s)" % (self.__class__.__name__, ", ".join("%s=%r" % (k, v) for k, v in vals_to_display))
311318

@@ -506,7 +513,7 @@ def is_lazy_value(argval):
506513
try:
507514
# note: we use the private and not public class here on purpose
508515
return isinstance(argval, _LazyValue)
509-
except:
516+
except Exception: # noqa
510517
return False
511518

512519

@@ -519,7 +526,7 @@ def is_lazy(argval):
519526
try:
520527
# note: we use the private and not public classes here on purpose
521528
return isinstance(argval, (_LazyValue, LazyTuple, _LazyTupleItem))
522-
except:
529+
except Exception: # noqa
523530
return False
524531

525532

pytest_cases/filters.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# Authors: Sylvain MARIE <[email protected]>
2+
# + All contributors to <https://github.com/smarie/python-pytest-cases>
3+
#
4+
# License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE>
15
import re
26

37
from .case_funcs import get_case_id, get_case_tags

pytest_cases/fixture_core2.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,8 @@ def _root_fixture(**_kwargs):
230230
def _create_fixture(_param_idx):
231231

232232
if debug:
233-
print("Creating nonparametrized 'view' fixture %r returning %r[%s]" % (argname, root_fixture_name, _param_idx))
233+
print("Creating nonparametrized 'view' fixture %r returning %r[%s]"
234+
% (argname, root_fixture_name, _param_idx))
234235

235236
@fixture(name=argname, scope=scope, autouse=autouse, hook=hook, **kwargs)
236237
@with_signature("%s(%s)" % (argname, root_fixture_name))
@@ -338,7 +339,7 @@ class CombinedFixtureParamValue(object):
338339
__slots__ = 'param_defs', 'argvalues',
339340

340341
def __init__(self,
341-
param_defs, # type: Iterable[FixtureParam]
342+
param_defs, # type: Iterable[FixtureParam]
342343
argvalues):
343344
self.param_defs = param_defs
344345
self.argvalues = argvalues

pytest_cases/fixture_parametrize_plus.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
from collections.abc import Iterable
1616
except ImportError: # noqa
1717
from collections import Iterable
18-
19-
try:
20-
from typing import Union, Callable, List, Any, Sequence, Optional # noqa
2118

19+
try:
20+
from typing import Union, Callable, List, Any, Sequence, Optional, Type # noqa
21+
from types import ModuleType # noqa
2222
except ImportError:
2323
pass
2424

@@ -643,10 +643,11 @@ def parametrize(argnames=None, # type: str
643643
(3) new possibilities in argvalues:
644644
645645
- one can include references to fixtures with `fixture_ref(<fixture>)` where <fixture> can be the fixture name or
646-
fixture function. When such a fixture reference is detected in the argvalues, a new function-scope "union" fixture
647-
will be created with a unique name, and the test function will be wrapped so as to be injected with the correct
648-
parameters from this fixture. Special test ids will be created to illustrate the switching between the various
649-
normal parameters and fixtures. You can see debug print messages about all fixtures created using `debug=True`
646+
fixture function. When such a fixture reference is detected in the argvalues, a new function-scope "union"
647+
fixture will be created with a unique name, and the test function will be wrapped so as to be injected with the
648+
correct parameters from this fixture. Special test ids will be created to illustrate the switching between the
649+
various normal parameters and fixtures. You can see debug print messages about all fixtures created using
650+
`debug=True`
650651
651652
- one can include lazy argvalues with `lazy_value(<valuegetter>, [id=..., marks=...])`. A `lazy_value` is the same
652653
thing than a function-scoped fixture, except that the value getter function is not a fixture and therefore can
@@ -762,7 +763,7 @@ def _make_ids(**args):
762763
for n, v in args.items():
763764
yield "%s=%s" % (n, mini_idval(val=v, argname='', idx=v))
764765

765-
idgen = lambda **args: "-".join(_make_ids(**args))
766+
idgen = lambda **args: "-".join(_make_ids(**args)) # noqa
766767

767768
# generate id
768769
if idgen is not None:
@@ -1118,7 +1119,7 @@ def _get_argnames_argvalues(argnames=None, argvalues=None, **args):
11181119
argvalues = kw_argvalues
11191120
# simplify if needed to comply with pytest.mark.parametrize
11201121
if len(argnames) == 1:
1121-
argvalues = [l[0] if not is_marked_parameter_value(l) else l for l in argvalues]
1122+
argvalues = [_l[0] if not is_marked_parameter_value(_l) else _l for _l in argvalues]
11221123
return argnames, argvalues
11231124

11241125
if isinstance(argnames, string_types):
@@ -1165,6 +1166,7 @@ def _gen_ids(argnames, argvalues, idgen):
11651166
raise TypeError("idgen should be a callable or a string, found: %r" % idgen)
11661167

11671168
_formatter = idgen
1169+
11681170
def gen_id_using_str_formatter(**params):
11691171
try:
11701172
# format using the idgen template

0 commit comments

Comments
 (0)