Skip to content

Commit dd8f6d4

Browse files
committed
Converted % format strings to fstrings
1 parent f030486 commit dd8f6d4

11 files changed

Lines changed: 182 additions & 189 deletions

src/pytest_cases/case_funcs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __init__(self,
5454
self.add_tags(tags)
5555

5656
def __repr__(self):
57-
return "_CaseInfo(id=%r,marks=%r,tags=%r)" % (self.id, self.marks, self.tags)
57+
return f"_CaseInfo(id={self.id!r},marks={self.marks!r},tags={self.tags!r})"
5858

5959
@classmethod
6060
def get_from(cls,

src/pytest_cases/case_parametrizer_new.py

Lines changed: 38 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ def get_all_cases(parametrization_target=None, # type: Callable
250250

251251
# validate prefix
252252
if not isinstance(prefix, str):
253-
raise TypeError("`prefix` should be a string, found: %r" % prefix)
253+
raise TypeError(f"`prefix` should be a string, found: {prefix} ({type(prefix)})")
254254

255255
# validate glob and filter and merge them in a single tuple of callables
256256
filters = ()
@@ -276,7 +276,7 @@ def get_all_cases(parametrization_target=None, # type: Callable
276276
elif callable(parametrization_target):
277277
caller_module_name = getattr(parametrization_target, '__module__', None)
278278
else:
279-
raise ValueError("Can't handle parametrization_target=%s" % parametrization_target)
279+
raise ValueError(f"Can't handle parametrization_target={parametrization_target}")
280280

281281
parent_pkg_name = '.'.join(caller_module_name.split('.')[:-1]) if caller_module_name is not None else None
282282

@@ -295,7 +295,7 @@ def get_all_cases(parametrization_target=None, # type: Callable
295295
shall_bind, bound_c = needs_binding(c, return_bound=True)
296296
cases_funs.append(bound_c)
297297
else:
298-
raise ValueError("Unsupported case function: %r" % c)
298+
raise ValueError(f"Unsupported case function: {c!r}")
299299
else:
300300
# module
301301
if c is AUTO:
@@ -306,9 +306,8 @@ def get_all_cases(parametrization_target=None, # type: Callable
306306
# import_default_cases_module. See #309.
307307
if not caller_module_name.split('.')[-1].startswith('test_'):
308308
raise ValueError(
309-
'Cannot use `cases=AUTO` in file "%s". `cases=AUTO` is '
309+
f'Cannot use `cases=AUTO` in file "{caller_module_name}". `cases=AUTO` is '
310310
'only allowed in files whose name starts with "test_" '
311-
% caller_module_name
312311
)
313312
# First try `test_<name>_cases.py` Then `cases_<name>.py`
314313
c = import_default_cases_module(caller_module_name)
@@ -447,8 +446,8 @@ def case_to_argvalues(host_class_or_module, # type: Union[Type, ModuleType]
447446
# single unparametrized case function
448447
if debug:
449448
case_fun_str = qname(case_fun.func if isinstance(case_fun, functools.partial) else case_fun)
450-
print("Case function %s > 1 lazy_value() with id %s and additional marks %s"
451-
% (case_fun_str, case_id, case_marks))
449+
print(f"Case function {case_fun_str} > 1 lazy_value() with id {case_id} "
450+
f"and additional marks {case_marks}")
452451
return (_LazyValueCaseParamValue(case_fun, id=case_id, marks=case_marks),)
453452
# else:
454453
# THIS WAS A PREMATURE OPTIMIZATION WITH MANY SHORTCOMINGS. For example what if the case function is
@@ -459,11 +458,12 @@ def case_to_argvalues(host_class_or_module, # type: Union[Type, ModuleType]
459458
# # do not forget to merge the marks !
460459
# if debug:
461460
# case_fun_str = qname(case_fun.func if isinstance(case_fun, functools.partial) else case_fun)
462-
# print("Case function %s > tuple of lazy_value() with ids %s and additional marks %s"
463-
# % (case_fun_str, ["%s-%s" % (case_id, c.id) for c in meta._calls],
464-
# [case_marks + tuple(c.marks) for c in meta._calls]))
461+
# ids = [f"{case_id}-{case_id}" for c in meta._calls]
462+
# additional_marks = [case_marks + tuple(c.marks) for c in meta._calls]
463+
# print(f"Case function {case_fun_str} > tuple of lazy_value() with ids {ids} "
464+
# f" and additional marks {additional_marks}")
465465
# return tuple(lazy_value(functools.partial(case_fun, **c.funcargs),
466-
# id="%s-%s" % (case_id, c.id), marks=case_marks + tuple(c.marks))
466+
# id=f"{case_id}-{c.id}", marks=case_marks + tuple(c.marks))
467467
# for c in meta._calls)
468468
else:
469469
# at least 1 required fixture (direct req or through @pytest.mark.usefixtures ), OR parametrized.
@@ -480,7 +480,7 @@ def case_to_argvalues(host_class_or_module, # type: Union[Type, ModuleType]
480480
argvalues = _FixtureRefCaseParamValue(fix_name, id=case_id)
481481
if debug:
482482
case_fun_str = qname(case_fun.func if isinstance(case_fun, functools.partial) else case_fun)
483-
print("Case function %s > fixture_ref(%r) with marks %s" % (case_fun_str, fix_name, remaining_marks))
483+
print(f"Case function {case_fun_str} > fixture_ref({fix_name!r}) with marks {remaining_marks}")
484484
# return a length-1 tuple because there is a single case created
485485
return (make_marked_parameter_value((argvalues,), marks=remaining_marks) if remaining_marks else argvalues,)
486486

@@ -518,8 +518,8 @@ def get_or_create_case_fixture(case_id, # type: str
518518
"""
519519
if is_fixture(case_fun):
520520
raise ValueError("A case function can not be decorated as a `@fixture`. This seems to be the case for"
521-
" %s. If you did not decorate it but still see this error, please report this issue"
522-
% case_fun)
521+
f" {case_fun}. If you did not decorate it but still see this error, please report this issue"
522+
)
523523

524524
# source: detect a functools.partial wrapper created by us because of a host class
525525
true_case_func, case_in_class = _get_original_case_func(case_fun)
@@ -537,7 +537,7 @@ def get_or_create_case_fixture(case_id, # type: str
537537
try:
538538
fix_name, marks = fix_cases_dct[(true_case_func, scope)]
539539
if debug:
540-
print("Case function %s > Reusing fixture %r and marks %s" % (qname(true_case_func), fix_name, marks))
540+
print(f"Case function {qname(true_case_func)} > Reusing fixture {fix_name!r} and marks {marks}")
541541
return fix_name, marks
542542
except KeyError:
543543
pass
@@ -558,9 +558,9 @@ def get_or_create_case_fixture(case_id, # type: str
558558
for f in list_all_fixtures_in(true_case_func_host, recurse_to_module=False, return_names=False):
559559
f_name = get_fixture_name(f)
560560
if (f_name in existing_fixture_names) or (f.__name__ in existing_fixture_names):
561-
raise ValueError("Cannot import fixture %r from %r as it would override an existing symbol "
562-
"in %r. Please set `@parametrize_with_cases(import_fixtures=False)`"
563-
"" % (f, from_module, target_host))
561+
raise ValueError(f"Cannot import fixture {f!r} from {from_module!r} as it would override "
562+
f"an existing symbol in {target_host!r}. "
563+
"Please set `@parametrize_with_cases(import_fixtures=False)`")
564564
target_host_module = target_host if not target_in_class else get_host_module(target_host)
565565
setattr(target_host_module, f.__name__, f)
566566

@@ -592,7 +592,7 @@ def name_changer(name, i):
592592
if_name_exists=CHANGE, name_changer=name_changer)
593593

594594
if debug:
595-
print("Case function %s > Creating fixture %r in %s" % (qname(true_case_func), fix_name, target_host))
595+
print(f"Case function {qname(true_case_func)} > Creating fixture {fix_name!r} in {target_host}")
596596

597597
if case_in_class:
598598
if target_in_class:
@@ -687,23 +687,22 @@ def import_default_cases_module(test_module_name):
687687
:return:
688688
"""
689689
# First try `test_<name>_cases.py`
690-
cases_module_name1 = "%s_cases" % test_module_name
690+
cases_module_name1 = f"{test_module_name}_cases"
691691

692692
try:
693693
cases_module = import_module(cases_module_name1)
694694
except ModuleNotFoundError:
695695
# Then try `cases_<name>.py`
696696
parts = test_module_name.split('.')
697697
assert parts[-1][0:5] == 'test_'
698-
cases_module_name2 = "%s.cases_%s" % ('.'.join(parts[:-1]), parts[-1][5:])
698+
cases_module_name2 = f"{'.'.join(parts[:-1])}.cases_{parts[-1][5:]}"
699699
try:
700700
cases_module = import_module(cases_module_name2)
701701
except ModuleNotFoundError:
702702
# Nothing worked
703-
raise ValueError("Error importing test cases module to parametrize %r: unable to import AUTO "
704-
"cases module %r nor %r. Maybe you wish to import cases from somewhere else ? In that case"
705-
" please specify `cases=...`."
706-
% (test_module_name, cases_module_name1, cases_module_name2))
703+
raise ValueError(f"Error importing test cases module to parametrize {test_module_name}: unable to import "
704+
f"AUTO cases module {cases_module_name1!r} nor {cases_module_name2!r}. Maybe you wish "
705+
"to import cases from somewhere else ? In that case please specify `cases=...`.")
707706

708707
return cases_module
709708

@@ -763,18 +762,16 @@ def extract_cases_from_class(cls,
763762
if hasinit(cls):
764763
warn(
765764
CasesCollectionWarning(
766-
"cannot collect cases class %r because it has a "
765+
f"cannot collect cases class {cls.__name__!r} because it has a "
767766
"__init__ constructor"
768-
% (cls.__name__, )
769767
)
770768
)
771769
return []
772770
elif hasnew(cls):
773771
warn(
774772
CasesCollectionWarning(
775-
"cannot collect test class %r because it has a "
773+
f"cannot collect test class {cls.__name__!r} because it has a "
776774
"__new__ constructor"
777-
% (cls.__name__, )
778775
)
779776
)
780777
return []
@@ -826,8 +823,8 @@ def extract_cases_from_module(module, # type: Union[st
826823
module = import_module(module, package=package_name)
827824
except ModuleNotFoundError as e:
828825
raise ModuleNotFoundError(
829-
"Error loading cases from module. `import_module(%r, package=%r)` raised an error: %r"
830-
% (module, package_name, e)
826+
f"Error loading cases from module. `import_module({module!r}, package={package_name!r})` "
827+
f"raised an error: {e!r}"
831828
)
832829

833830
return _extract_cases_from_module_or_class(module=module, _case_param_factory=_case_param_factory,
@@ -905,9 +902,9 @@ def _of_interest(x): # noqa
905902
else:
906903
# currently we only support replacing inside the same module
907904
if m_for_placing.__module__ != m.__module__:
908-
raise ValueError("Unsupported value for 'place_as' special pytest attribute on case function %s: %s"
909-
". Virtual placing in another module is not supported yet by pytest-cases."
910-
% (m, m_for_placing))
905+
raise ValueError("Unsupported value for 'place_as' special pytest attribute on case function "
906+
f"{m}: {m_for_placing}. Virtual placing in another module is not supported yet "
907+
"by pytest-cases.")
911908
co_firstlineno = get_code_first_line(m_for_placing)
912909

913910
if cls is not None:
@@ -926,7 +923,7 @@ def _of_interest(x): # noqa
926923
pass
927924
else:
928925
if len(s.parameters) < 1 or (tuple(s.parameters.keys())[0] != "self"):
929-
raise TypeError("case method is missing 'self' argument but is not static: %s" % m)
926+
raise TypeError(f"case method is missing 'self' argument but is not static: {m}")
930927
# partialize the function to get one without the 'self' argument
931928
new_m = functools.partial(m, cls())
932929

@@ -944,8 +941,8 @@ def _of_interest(x): # noqa
944941
if _case_param_factory is None:
945942
# Nominal usage: put the case in the dictionary
946943
if co_firstlineno in cases_dct:
947-
raise ValueError("Error collecting case functions, line number used by %r is already used by %r !"
948-
% (m, cases_dct[co_firstlineno]))
944+
raise ValueError(f"Error collecting case functions, line number used by {m!r} is already used by "
945+
f"{cases_dct[co_firstlineno]!r} !")
949946
cases_dct[co_firstlineno] = m
950947
else:
951948
# Not used anymore
@@ -1115,7 +1112,7 @@ def get_current_param(value, argname_or_fixturename, mp_fix_to_args):
11151112
if len(argnames) == 1 and not isinstance(value, FixtureParamAlternative):
11161113
actual_value = actual_value[0]
11171114
else:
1118-
raise TypeError("Unsupported type, please report: %r" % type(value))
1115+
raise TypeError(f"Unsupported type, please report: {type(value)!r}")
11191116
else:
11201117
# (3) "normal" parameter: each (argname, value) pair is received independently
11211118
argnames = (argname_or_fixturename,)
@@ -1349,7 +1346,7 @@ def get_current_case_id(request_or_item,
13491346
# """ An adapted copy of _pytest.python.pytest_pycollect_makeitem """
13501347
# if safe_isclass(obj):
13511348
# if self.iscaseclass(obj, name):
1352-
# raise ValueError("Case classes are not yet supported: %r" % obj)
1349+
# raise ValueError(f"Case classes are not yet supported: {obj!r}")
13531350
# elif self.iscasefunction(obj, name):
13541351
# # mock seems to store unbound methods (issue473), normalize it
13551352
# obj = getattr(obj, "__func__", obj)
@@ -1360,7 +1357,7 @@ def get_current_case_id(request_or_item,
13601357
# filename, lineno = compat_getfslineno(obj)
13611358
# warn_explicit(
13621359
# message=PytestCasesCollectionWarning(
1363-
# "cannot collect %r because it is not a function." % name
1360+
# f"cannot collect {name!r} because it is not a function."
13641361
# ),
13651362
# category=None,
13661363
# filename=str(filename),
@@ -1371,7 +1368,7 @@ def get_current_case_id(request_or_item,
13711368
# filename, lineno = compat_getfslineno(obj)
13721369
# warn_explicit(
13731370
# message=PytestCasesCollectionWarning(
1374-
# "cannot collect %r because it is a generator function." % name
1371+
# f"cannot collect {name!r} because it is a generator function."
13751372
# ),
13761373
# category=None,
13771374
# filename=str(filename),

src/pytest_cases/common_others.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def get_code_first_line(f):
3636
_, lineno = findsource(f)
3737
return lineno
3838
except: # noqa
39-
raise ValueError("Cannot get code information for function or class %r" % f)
39+
raise ValueError(f"Cannot get code information for function or class {f!r}")
4040

4141

4242
# Below is the beginning of a switch from our scanning code to the same one than pytest. See `case_parametrizer_new`
@@ -187,27 +187,27 @@ def __exit__(self, exc_type, exc_val, exc_tb):
187187

188188
# Type check
189189
if not isinstance(exc_val, self.err_type):
190-
raise ExceptionCheckingError("Caught exception %r is not an instance of expected type %r"
191-
% (exc_val, self.err_type))
190+
raise ExceptionCheckingError(f"Caught exception {exc_val!r} is not an instance of "
191+
f"expected type {self.err_type!r}")
192192

193193
# Optional - pattern matching
194194
if self.err_ptrn is not None:
195195
if not self.err_ptrn.match(repr(exc_val)):
196-
raise ExceptionCheckingError("Caught exception %r does not match expected pattern %r"
197-
% (exc_val, self.err_ptrn))
196+
raise ExceptionCheckingError(f"Caught exception {exc_val!r} does not match expected "
197+
f"pattern {self.err_ptrn!r}")
198198

199199
# Optional - Additional Exception instance check with equality
200200
if self.err_inst is not None:
201201
# note: do not use != because in python 2 that is not equivalent
202202
if not (exc_val == self.err_inst):
203-
raise ExceptionCheckingError("Caught exception %r does not equal expected instance %r"
204-
% (exc_val, self.err_inst))
203+
raise ExceptionCheckingError(f"Caught exception {exc_val!r} does not equal "
204+
f"expected instance {self.err_inst!r}")
205205

206206
# Optional - Additional Exception instance check with custom checker
207207
if self.err_checker is not None:
208208
if self.err_checker(exc_val) is False:
209-
raise ExceptionCheckingError("Caught exception %r is not valid according to %r"
210-
% (exc_val, self.err_checker))
209+
raise ExceptionCheckingError(f"Caught exception {exc_val!r} is not valid "
210+
f"according to {self.err_checker!r}")
211211

212212
# Suppress the exception since it is valid.
213213
# See https://docs.python.org/2/reference/datamodel.html#object.__exit__
@@ -446,8 +446,8 @@ def get_class_that_defined_method(meth):
446446
# non-resolvable __qualname__
447447
raise HostNotConstructedYet(
448448
"__qualname__ is not resolvable, this can happen if the host class of this method "
449-
"%r has not yet been created. PEP3155 does not seem to tell us what we should do "
450-
"in this case." % meth
449+
f"{meth!r} has not yet been created. PEP3155 does not seem to tell us what we should do "
450+
"in this case."
451451
)
452452
if host is None:
453453
raise ValueError("__qualname__ leads to `None`, this is strange and not PEP3155 compliant, please "
@@ -553,7 +553,7 @@ def make_identifier(name # type: str
553553
):
554554
"""Transform the given name into a valid python identifier"""
555555
if not isinstance(name, string_types):
556-
raise TypeError("name should be a string, found : %r" % name)
556+
raise TypeError(f"name should be a string, found : {name!r}")
557557

558558
if iskeyword(name) or (not PY3 and name == "None"):
559559
# reserved keywords: add an underscore

0 commit comments

Comments
 (0)