diff --git a/jsonargparse_tests/__main__.py b/jsonargparse_tests/__main__.py index 49d136d4..f72776f3 100644 --- a/jsonargparse_tests/__main__.py +++ b/jsonargparse_tests/__main__.py @@ -1,4 +1,5 @@ """Run all unit tests in package.""" +# pragma: no cover import os import sys diff --git a/jsonargparse_tests/argparse_tests_generate.py b/jsonargparse_tests/argparse_tests_generate.py index 28566f04..7a3060e8 100755 --- a/jsonargparse_tests/argparse_tests_generate.py +++ b/jsonargparse_tests/argparse_tests_generate.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +# pragma: no cover """Generate argparse compatibility tests from CPython's test_argparse.py. This script downloads the test_argparse.py file from the CPython repository, diff --git a/jsonargparse_tests/conftest.py b/jsonargparse_tests/conftest.py index 22d6d41b..7201a9bf 100644 --- a/jsonargparse_tests/conftest.py +++ b/jsonargparse_tests/conftest.py @@ -271,12 +271,12 @@ def get_parse_args_stderr(parser: ArgumentParser, args: List[str]) -> str: class BaseClass: def __init__(self): - pass + pass # pragma: no cover def wrap_fn(fn): @wraps(fn) def wrapped_fn(*args, **kwargs): - return fn(*args, **kwargs) + return fn(*args, **kwargs) # pragma: no cover return wrapped_fn diff --git a/jsonargparse_tests/test_cli.py b/jsonargparse_tests/test_cli.py index e7cf37a0..13521119 100644 --- a/jsonargparse_tests/test_cli.py +++ b/jsonargparse_tests/test_cli.py @@ -34,7 +34,7 @@ def get_cli_stderr(*args, **kwargs) -> str: def simple_main(a1: int = 0, a2: bool = False): - pass + pass # pragma: no cover def test_auto_parser(): @@ -54,7 +54,7 @@ def test_unexpected_components(cli_fn, components): class ConflictingSubcommandKey: def subcommand(self, x: int = 0): - return x + return x # pragma: no cover def test_conflicting_subcommand_key(): @@ -167,14 +167,14 @@ def test_function_in_list_with_config_parameter(): def conditionalA(foo: int = 1): - return foo + return foo # pragma: no cover def conditionalB(bar: int = 2): - return bar + return bar # pragma: no cover -def conditional_function(fn: "Literal['A', 'B']", *args, **kwargs): +def conditional_function(fn: "Literal['A', 'B']", *args, **kwargs): # pragma: no cover if fn == "A": return conditionalA(*args, **kwargs) elif fn == "B": diff --git a/jsonargparse_tests/test_core.py b/jsonargparse_tests/test_core.py index 9e5ad6c5..28837896 100644 --- a/jsonargparse_tests/test_core.py +++ b/jsonargparse_tests/test_core.py @@ -787,7 +787,7 @@ def rm_out_files(): class ListItem: - def __init__(self, a: int, b: str): + def __init__(self, a: int, b: str): # pragma: no cover self.a = a self.b = b diff --git a/jsonargparse_tests/test_dataclasses.py b/jsonargparse_tests/test_dataclasses.py index 8ccacbfd..03848f08 100644 --- a/jsonargparse_tests/test_dataclasses.py +++ b/jsonargparse_tests/test_dataclasses.py @@ -191,7 +191,7 @@ def __init__(self, a1: DataClassB = DataClassB()): class RootClass: - def __init__(self, c1: SubBaseClass): + def __init__(self, c1: SubBaseClass): # pragma: no cover """RootClass description""" self.c1 = c1 @@ -486,7 +486,7 @@ class DataWithOptionalA: def data_with_optional(a: DataWithOptionalA): - pass + pass # pragma: no cover def test_dataclass_with_optional_default(parser): diff --git a/jsonargparse_tests/test_deprecated.py b/jsonargparse_tests/test_deprecated.py index b61bed0a..771b64c2 100644 --- a/jsonargparse_tests/test_deprecated.py +++ b/jsonargparse_tests/test_deprecated.py @@ -98,7 +98,7 @@ def suppress_stderr(): def assert_deprecation_warn(warns, message, code): assert message in str(warns[-1].message) if code is None: - return + return # pragma: no cover assert pathlib.Path(warns[-1].filename).name == pathlib.Path(__file__).name assert code in source[warns[-1].lineno - 1] @@ -119,7 +119,7 @@ class MyEnum(Enum): def func(a1: MyEnum = MyEnum["A"]): - return a1 + return a1 # pragma: no cover def test_ActionEnum(): @@ -310,7 +310,7 @@ def test_add_instantiator_method_deprecated(parser): def function(a1: float): - return a1 + return a1 # pragma: no cover def test_single_function_cli(): @@ -325,11 +325,11 @@ def test_single_function_cli(): def cmd1(a1: int): - return a1 + return a1 # pragma: no cover def cmd2(a2: str = "X"): - return a2 + return a2 # pragma: no cover def test_multiple_functions_cli(): @@ -447,7 +447,7 @@ def test_error_handler_parameter(): with catch_warnings(record=True) as w: parser = ArgumentParser(error_handler=usage_and_exit_error_handler) code = "ArgumentParser(error_handler=usage_" - if not is_posix: + if not is_posix: # pragma: no cover code = None # for some reason the stack trace differs in windows assert_deprecation_warn( w, diff --git a/jsonargparse_tests/test_from_config.py b/jsonargparse_tests/test_from_config.py index f0e98953..737c0812 100644 --- a/jsonargparse_tests/test_from_config.py +++ b/jsonargparse_tests/test_from_config.py @@ -110,7 +110,7 @@ class DefaultsOverrideRequiredNotAllowed(FromConfigMixin): __from_config_init_defaults__ = config_path def __init__(self, param1: int): - self.param1 = param1 + self.param1 = param1 # pragma: no cover def test_init_defaults_override_class_with_init_subclass(tmp_cwd): @@ -300,7 +300,7 @@ def __init__(self, param1: str, param2: str): def test_from_config_method_partial_config_with_required_parameter(): class FromConfigMethodPartial(FromConfigMixin): - def __init__(self, required_param: str, optional_param: str = "default_value"): + def __init__(self, required_param: str, optional_param: str = "default_value"): # pragma: no cover self.required_param = required_param self.optional_param = optional_param diff --git a/jsonargparse_tests/test_jsonnet.py b/jsonargparse_tests/test_jsonnet.py index 9a053e70..9a1c180b 100644 --- a/jsonargparse_tests/test_jsonnet.py +++ b/jsonargparse_tests/test_jsonnet.py @@ -115,7 +115,7 @@ def test_parser_mode_jsonnet_import_libsonnet(parser, tmp_cwd): def test_parser_mode_jsonnet_subconfigs(parser, tmp_cwd): class Class: def __init__(self, name: str = "Lucky", prize: int = 100): - pass + pass # pragma: no cover parser.parser_mode = "jsonnet" parser.add_class_arguments(Class, "group", sub_configs=True) diff --git a/jsonargparse_tests/test_link_arguments.py b/jsonargparse_tests/test_link_arguments.py index 139f05cb..dd62fad9 100644 --- a/jsonargparse_tests/test_link_arguments.py +++ b/jsonargparse_tests/test_link_arguments.py @@ -38,15 +38,16 @@ def test_on_parse_shallow_print_config(parser): assert json_or_yaml_load(out) == {"a": 0} -def test_on_parse_subcommand_failing_compute_fn(parser, subparser, subtests): - def to_str(value): - if not value: - raise ValueError("value is empty") - return str(value) +def _to_str_empty_error(value): + if not value: + raise ValueError("value is empty") + return str(value) # pragma: no cover + +def test_on_parse_subcommand_failing_compute_fn(parser, subparser, subtests): subparser.add_argument("--a", type=int, default=0) subparser.add_argument("--b", type=str) - subparser.link_arguments("a", "b", to_str) + subparser.link_arguments("a", "b", _to_str_empty_error) subparser.add_argument("--config", action="config") subcommands = parser.add_subcommands() subcommands.add_subcommand("sub", subparser) @@ -54,7 +55,7 @@ def to_str(value): with subtests.test("parse_args"): with pytest.raises(ArgumentError) as ctx: parser.parse_args(["sub"]) - ctx.match("Call to compute_fn of link 'to_str.*failed: value is empty") + ctx.match("Call to compute_fn of link '_to_str_empty_error.*failed: value is empty") with subtests.test("print_config"): out = get_parse_args_stdout(parser, ["sub", "--print_config"]) @@ -120,15 +121,15 @@ def test_on_parse_compute_fn_subclass_spec(parser, subtests): class ClassA: def __init__(self, v1: int = 2, v2: int = 3): - pass + pass # pragma: no cover class ClassB: def __init__(self, v1: int = -1, v2: int = 4, v3: int = 2): - pass + pass # pragma: no cover -def parser_classes_links_on_parse(): +def _parser_classes_links_on_parse(): def add(*args): return sum(args) @@ -141,7 +142,7 @@ def add(*args): def test_on_parse_add_class_arguments(subtests): - parser = parser_classes_links_on_parse() + parser = _parser_classes_links_on_parse() with subtests.test("without defaults"): with pytest.raises(ArgumentError) as ctx: @@ -175,12 +176,12 @@ def __init__( v1: Union[int, str] = 1, v2: Union[int, str] = 2, ): - pass + pass # pragma: no cover class ClassS2: def __init__(self, v3: int): - self.v3 = v3 + self.v3 = v3 # pragma: no cover def test_on_parse_add_subclass_arguments(parser, subtests): @@ -218,7 +219,7 @@ def add(v1, v2): class Logger: def __init__(self, save_dir: Optional[str] = None): - pass + pass # pragma: no cover class TrainerLoggerUnion: @@ -227,7 +228,7 @@ def __init__( save_dir: Optional[str] = None, logger: Union[bool, Logger] = False, ): - pass + pass # pragma: no cover def test_on_parse_subclass_target_in_union(parser): @@ -246,7 +247,7 @@ def __init__( save_dir: Optional[str] = None, logger: List[Logger] = [], ): - pass + pass # pragma: no cover def test_on_parse_subclass_target_in_list(parser): @@ -269,7 +270,7 @@ def __init__( save_dir: Optional[str] = None, logger: Union[bool, Logger, List[Logger]] = False, ): - pass + pass # pragma: no cover def test_on_parse_subclass_target_in_union_list(parser): @@ -291,7 +292,7 @@ def __init__( save_dir: Optional[str] = None, logger: Optional[List[Logger]] = None, ): - pass + pass # pragma: no cover def test_on_parse_subclass_target_in_optional_list(parser): @@ -420,7 +421,7 @@ def test_on_parse_within_subcommand(parser, subparser): class RequiredTargetA: def __init__(self, a: int): - pass + pass # pragma: no cover @dataclass @@ -430,7 +431,7 @@ class RequiredTargetB: class RequiredTargetC: def __init__(self, b: RequiredTargetB): - pass + pass # pragma: no cover def test_on_parse_save_required_target_subclass_param(parser, tmp_cwd): @@ -459,7 +460,7 @@ def test_on_parse_save_required_target_entire_dataclass(parser, tmp_cwd): class Optimizer: - def __init__(self, params: List[int], lr: float): + def __init__(self, params: List[int], lr: float): # pragma: no cover self.params = params self.lr = lr @@ -608,23 +609,18 @@ def __init__(self, a: int = 0): class FailingComputeFn2: def __init__(self, b: str): - self.b = b + self.b = b # pragma: no cover def test_on_instantiate_failing_compute_fn(parser): - def to_str(value): - if not value: - raise ValueError("value is empty") - return str(value) - parser.add_class_arguments(FailingComputeFn1, "c1") parser.add_class_arguments(FailingComputeFn2, "c2") - parser.link_arguments("c1.a", "c2.b", compute_fn=to_str, apply_on="instantiate") + parser.link_arguments("c1.a", "c2.b", compute_fn=_to_str_empty_error, apply_on="instantiate") with pytest.raises(ValueError) as ctx: cfg = parser.parse_args([]) parser.instantiate(cfg) - ctx.match("Call to compute_fn of link 'to_str.*failed: value is empty") + ctx.match("Call to compute_fn of link '_to_str_empty_error.*failed: value is empty") def test_on_instantiate_link_from_subclass_with_compute_fn(): @@ -641,7 +637,7 @@ def test_on_instantiate_link_from_subclass_with_compute_fn(): class ClassN: def __init__(self, calendar: Calendar): - self.calendar = calendar + self.calendar = calendar # pragma: no cover def test_on_parse_and_instantiate_link_entire_instance(parser): @@ -963,11 +959,6 @@ def __init__(self, batch_size: int = 6): self.num_classes = 7 -class CustomOptimizer(Optimizer): - def __init__(self, params: List[int], num_classes: int, **kwargs): - super().__init__(params, **kwargs) - - def custom_instantiator(class_type, *args, applied_instantiation_links: dict, **kwargs): init = class_type(*args, **kwargs) init.applied_instantiation_links = applied_instantiation_links @@ -1056,28 +1047,28 @@ def test_on_parse_link_failure_previous_source_as_target(parser): def test_on_parse_link_failure_already_linked(): - parser = parser_classes_links_on_parse() + parser = _parser_classes_links_on_parse() with pytest.raises(ValueError) as ctx: parser.link_arguments("a.v2", "b.v1") ctx.match('Target "b.v1" is already a target of another link') def test_on_parse_link_failure_non_existing_source(): - parser = parser_classes_links_on_parse() + parser = _parser_classes_links_on_parse() with pytest.raises(ValueError) as ctx: parser.link_arguments("x", "b.v3") ctx.match('No action for key "x"') def test_on_parse_link_failure_non_existing_target(): - parser = parser_classes_links_on_parse() + parser = _parser_classes_links_on_parse() with pytest.raises(ValueError) as ctx: parser.link_arguments("a.v1", "x") ctx.match('No action for key "x"') def test_on_parse_link_failure_multi_source_missing_compute_fn(): - parser = parser_classes_links_on_parse() + parser = _parser_classes_links_on_parse() with pytest.raises(ValueError) as ctx: parser.link_arguments(("a.v1", "a.v2"), "b.v3") ctx.match("Multiple source keys requires a compute function") diff --git a/jsonargparse_tests/test_loaders_dumpers.py b/jsonargparse_tests/test_loaders_dumpers.py index fcbfa82f..e3042135 100644 --- a/jsonargparse_tests/test_loaders_dumpers.py +++ b/jsonargparse_tests/test_loaders_dumpers.py @@ -40,7 +40,7 @@ def test_yaml_implicit_mapping_values_disabled(parser): class Bar: def __init__(self, x: str): - pass + pass # pragma: no cover def test_yaml_implicit_null_disabled(parser): @@ -104,7 +104,7 @@ class CustomData: class CustomContainer: def __init__(self, data: CustomData): - self.data = data + self.data = data # pragma: no cover def custom_loader(data): diff --git a/jsonargparse_tests/test_omegaconf.py b/jsonargparse_tests/test_omegaconf.py index cb43daa2..adc50baa 100644 --- a/jsonargparse_tests/test_omegaconf.py +++ b/jsonargparse_tests/test_omegaconf.py @@ -245,7 +245,7 @@ def test_omegaconf_absolute_to_relative_paths(): assert omegaconf_absolute_to_relative_paths(data) == expected -def parse_in_spawned_process(queue, parser, args): +def parse_in_spawned_process(queue, parser, args): # pragma: no cover try: cfg = parser.parse_args(args) queue.put(cfg) diff --git a/jsonargparse_tests/test_parameter_resolvers.py b/jsonargparse_tests/test_parameter_resolvers.py index 6fcbf868..7bb46e84 100644 --- a/jsonargparse_tests/test_parameter_resolvers.py +++ b/jsonargparse_tests/test_parameter_resolvers.py @@ -42,7 +42,7 @@ def __init__(self, pkb1: str, kb1: int = 3, kb2: str = "4", **kwargs): kb1: help for kb1 kb2: help for kb2 """ - super().__init__(ka2=True, **kwargs) + super().__init__(ka2=True, **kwargs) # pragma: no cover @classmethod def make(cls, pkcm1: str, kcm1: bool = False, **kws): @@ -51,7 +51,7 @@ def make(cls, pkcm1: str, kcm1: bool = False, **kws): pkcm1: help for pkcm1 kcm1: help for kcm1 """ - return ClassB(pkcm1, **kws) + return ClassB(pkcm1, **kws) # pragma: no cover class ClassC(ClassB): @@ -60,11 +60,11 @@ def __init__(self, kc1: str = "-", **kargs): Args: kc1: help for kc1 """ - super().__init__(**kargs) + super().__init__(**kargs) # pragma: no cover class ClassN: - def __init__(self, kn1: int = 1, **kargs): + def __init__(self, kn1: int = 1, **kargs): # pragma: no cover """ Args: kn1: help for kn1 @@ -82,7 +82,7 @@ def __init__(self, kd1: bool = False, **kwargs): Args: kd1: help for kd1 """ - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover def method_d(self, pmd1: int, *args, kmd1: int = 2, **kws): """ @@ -90,7 +90,7 @@ def method_d(self, pmd1: int, *args, kmd1: int = 2, **kws): pmd1: help for pmd1 kmd1: help for kmd1 """ - return super().method_a(*args, **kws) + return super().method_a(*args, **kws) # pragma: no cover @staticmethod def staticmethod_d(ksmd1: str = "z", **kw): @@ -98,7 +98,7 @@ def staticmethod_d(ksmd1: str = "z", **kw): Args: ksmd1: help for ksmd1 """ - return function_return_class_c(ksmd1, k2=2, **kw) + return function_return_class_c(ksmd1, k2=2, **kw) # pragma: no cover class ClassE1: @@ -108,26 +108,26 @@ class ClassE1: """ def __init__(self, ke1: int = 1, **kwargs): - self._kwd = dict(k2=3, **kwargs) + self._kwd = dict(k2=3, **kwargs) # pragma: no cover def start(self): - return function_no_args_no_kwargs(**self._kwd) + return function_no_args_no_kwargs(**self._kwd) # pragma: no cover class ClassE2: - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pragma: no cover self._kwd = dict(**kwargs) self.fn = lambda **kw: None def start(self): - return self.fn(**self._kwd) + return self.fn(**self._kwd) # pragma: no cover class AttributeLocalImport1: def __init__(self, **kwargs): - self._kwd = dict(**kwargs) + self._kwd = dict(**kwargs) # pragma: no cover - def run(self): + def run(self): # pragma: no cover from jsonargparse import set_loader return set_loader(**self._kwd) @@ -135,9 +135,9 @@ def run(self): class AttributeLocalImport2: def __init__(self, **kwargs): - self._kwd = dict(**kwargs) + self._kwd = dict(**kwargs) # pragma: no cover - def run(self): + def run(self): # pragma: no cover import jsonargparse as ja return ja.set_loader(**self._kwd) @@ -145,9 +145,9 @@ def run(self): class AttributeLocalImport3: def __init__(self, **kwargs): - self._kwd = dict(**kwargs) + self._kwd = dict(**kwargs) # pragma: no cover - def run(self): + def run(self): # pragma: no cover from jsonargparse import set_loader return set_loader(**self._kwd) @@ -155,9 +155,9 @@ def run(self): class AttributeLocalImport4: def __init__(self, **kwargs): - self._kwd = dict(**kwargs) + self._kwd = dict(**kwargs) # pragma: no cover - def run(self): + def run(self): # pragma: no cover from jsonargparse import set_loader as sl return sl(**self._kwd) @@ -165,21 +165,21 @@ def run(self): class AttributeLocalImportFailure: def __init__(self, **kwargs): - self._kwd = dict(**kwargs) + self._kwd = dict(**kwargs) # pragma: no cover - def run(self): + def run(self): # pragma: no cover from jsonargparse import does_not_exist return does_not_exist(**self._kwd) class ClassF1: - def __init__(self, **kw): + def __init__(self, **kw): # pragma: no cover self._ini = dict(k2=4) self._ini.update(**kw) def _run(self): - self.staticmethod_f(**self._ini) + self.staticmethod_f(**self._ini) # pragma: no cover @staticmethod def staticmethod_f(ksmf1: str = "w", **kw): @@ -187,16 +187,16 @@ def staticmethod_f(ksmf1: str = "w", **kw): Args: ksmf1: help for ksmf1 """ - return function_no_args_no_kwargs(**kw) + return function_no_args_no_kwargs(**kw) # pragma: no cover class ClassF2: - def __init__(self, **kw): + def __init__(self, **kw): # pragma: no cover self._ini: Dict[str, Any] = {"k2": 4} self._ini.update(**kw) def _run(self): - self.staticmethod_f(**self._ini) + self.staticmethod_f(**self._ini) # pragma: no cover @staticmethod def staticmethod_f(ksmf1: str = "w", **kw): @@ -204,7 +204,7 @@ def staticmethod_f(ksmf1: str = "w", **kw): Args: ksmf1: help for ksmf1 """ - return function_no_args_no_kwargs(**kw) + return function_no_args_no_kwargs(**kw) # pragma: no cover class ClassG: @@ -255,7 +255,7 @@ def __init__(self, km2: int = 2, **kwargs): Args: km2: help for km2 """ - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class ClassM3(ClassM1): @@ -264,12 +264,12 @@ def __init__(self, km3: int = 0, **kwargs): Args: km3: help for km3 """ - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class ClassM4(ClassM2, ClassM3): def __init__(self, **kwargs): - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class ClassM5(ClassM2): @@ -278,7 +278,7 @@ def __init__(self, km5: int = 5, **kwargs): Args: km5: help for km5 """ - super(ClassM2, self).__init__(**kwargs) + super(ClassM2, self).__init__(**kwargs) # pragma: no cover class ClassP: @@ -287,11 +287,11 @@ def __init__(self, kp1: int = 1, **kw): Args: kp1: help for kp1 """ - self._kw = kw + self._kw = kw # pragma: no cover @property def data(self): - return function_no_args_no_kwargs(**self._kw) + return function_no_args_no_kwargs(**self._kw) # pragma: no cover class ClassS1: @@ -300,63 +300,63 @@ def __init__(self, ks1: int = 2, **kw): Args: ks1: help for ks1 """ - self.ks1 = ks1 + self.ks1 = ks1 # pragma: no cover @classmethod def classmethod_s(cls, **kwargs): - return cls(**kwargs) + return cls(**kwargs) # pragma: no cover class ClassS2: def __init__(self, **kwargs): - self.kwargs = kwargs + self.kwargs = kwargs # pragma: no cover def run_classmethod_s(self): - return ClassS1.classmethod_s(**self.kwargs) + return ClassS1.classmethod_s(**self.kwargs) # pragma: no cover class ClassU1: - def __init__(self, k1: int = 1, **ka): + def __init__(self, k1: int = 1, **ka): # pragma: no cover data = Namespace() data.ka = ka class ClassU2: def __init__(self, k1: int = 1, **ka): - self.method_u2(ka=ka) + self.method_u2(ka=ka) # pragma: no cover def method_u2(self, ka: dict): - pass + pass # pragma: no cover class ClassU3(ClassU1, ClassU2): - def __init__(self, **ka): + def __init__(self, **ka): # pragma: no cover super(ClassA, self).__init__(**ka) # pylint: disable=bad-super-call class ClassU4: def __init__(self, k1: int = 1, **ka): - self._ka = ka + self._ka = ka # pragma: no cover class ClassU5: def __init__(self, **kws): - self.kws = kws + self.kws = kws # pragma: no cover def _run(self): - self.method1(kws=self.kws) + self.method1(kws=self.kws) # pragma: no cover def method1(self, kws: dict): - pass + pass # pragma: no cover class Optimizer: def __init__(self, params: List[int]): - self.params = params + self.params = params # pragma: no cover class SGD(Optimizer): - def __init__(self, params: List[int], lr: float, **kwargs): + def __init__(self, params: List[int], lr: float, **kwargs): # pragma: no cover super().__init__(params, **kwargs) self.lr = lr @@ -396,7 +396,7 @@ def __init__( class ConditionalGlobalConstant(BaseClass): @wrap_fn - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pragma: no cover super().__init__() kwargs.get("p1", "x") if GLOBAL_CONSTANT: @@ -418,7 +418,7 @@ def function_with_kwargs(k1: bool = True, **kwds): Args: k1: help for k1 """ - return function_no_args_no_kwargs(**kwds) + return function_no_args_no_kwargs(**kwds) # pragma: no cover def function_return_class_c(pk1: str, k2: int = 1, **ka): @@ -427,7 +427,7 @@ def function_return_class_c(pk1: str, k2: int = 1, **ka): pk1: help for pk1 k2: help for k2 """ - return ClassC(pk1, kb1=k2, **ka) + return ClassC(pk1, kb1=k2, **ka) # pragma: no cover def function_make_class_b(*args, k1: str = "-", **kwargs): @@ -435,10 +435,10 @@ def function_make_class_b(*args, k1: str = "-", **kwargs): Args: k1: help for k1 """ - return ClassB.make(*args, **kwargs) + return ClassB.make(*args, **kwargs) # pragma: no cover -def function_pop_get_from_kwargs(kn1: int = 0, **kw): +def function_pop_get_from_kwargs(kn1: int = 0, **kw): # pragma: no cover """ Args: k2: help for k2 @@ -456,7 +456,7 @@ def function_pop_get_from_kwargs(kn1: int = 0, **kw): kw.pop("pk1", "") -def function_pop_get_conditional(p1: str, **kw): +def function_pop_get_conditional(p1: str, **kw): # pragma: no cover """ Args: p1: help for p1 @@ -471,21 +471,21 @@ def function_pop_get_conditional(p1: str, **kw): kw.get("p3", "y") -def function_with_bug(**kws): +def function_with_bug(**kws): # pragma: no cover return does_not_exist(**kws) # noqa: F821 -def function_unsupported_component(**kwds): +def function_unsupported_component(**kwds): # pragma: no cover select = ["Text", "HTML", ""] shuffle(select) getattr(calendar, f"{select[0]}Calendar")(**kwds) -def function_module_class(**kwds): +def function_module_class(**kwds): # pragma: no cover return calendar.Calendar(**kwds) -def function_local_import(**kwds): +def function_local_import(**kwds): # pragma: no cover from jsonargparse import set_loader return set_loader(**kwds) @@ -495,7 +495,7 @@ def function_local_import(**kwds): constant_boolean_2 = False -def function_constant_boolean(**kwargs): +def function_constant_boolean(**kwargs): # pragma: no cover if constant_boolean_1: return function_with_kwargs(**kwargs) elif not constant_boolean_2: @@ -532,7 +532,7 @@ def cond_3(kc: int = 1, kn3: int = 2, kn4: float = 0.1): """ -def conditional_calls(**kwargs): +def conditional_calls(**kwargs): # pragma: no cover if "kn1" in kwargs: cond_1(kn0="y", **kwargs) elif "kn2" in kwargs: @@ -546,7 +546,7 @@ def function_optional_callable(p1: Optional[Callable] = None, **kw): Args: p1: help for p1 """ - function_no_args_no_kwargs(**kw) + function_no_args_no_kwargs(**kw) # pragma: no cover def assert_params(params, expected, origins={}, help=True): @@ -672,15 +672,15 @@ def test_get_params_class_from_function(): class ClassMethod: def __init__(self, pi: int): - self.pi = pi + self.pi = pi # pragma: no cover @classmethod def from_str(cls, ps: str): - return cls(1) + return cls(1) # pragma: no cover @classmethod def from_untyped(cls, pu): - return cls(2) + return cls(2) # pragma: no cover ClassMethodFromStr = class_from_function(ClassMethod.from_str, ClassMethod, name="ClassMethodFromStr") @@ -843,7 +843,7 @@ def test_get_params_function_local_import(): assert ["mode", "loader_fn", "exceptions", "json_superset"] == [p.name for p in params] -def function_nested_module_attr(**kwargs): +def function_nested_module_attr(**kwargs): # pragma: no cover import xml.dom.minidom return xml.dom.minidom.parseString(**kwargs) @@ -857,7 +857,7 @@ def test_get_params_function_nested_module_attr(): class ClassNestedModuleAttr: - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pragma: no cover import xml.dom.minidom self.doc = xml.dom.minidom.parseString(**kwargs) @@ -871,7 +871,7 @@ def test_get_params_class_nested_module_attr(): class ClassNestedLocalFromImport: - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pragma: no cover from xml.dom import minidom self.result = minidom.parseString(**kwargs) @@ -919,10 +919,10 @@ def test_get_params_optional_callable(): def func_several_params(p1: int = 1, p2: int = 2, p3: int = 3, p4: int = 4): - pass + pass # pragma: no cover -def func_given_kwargs(p: int, **kwargs): +def func_given_kwargs(p: int, **kwargs): # pragma: no cover func_several_params(p2=0, **kwargs) func_several_params(p4=0, **kwargs) diff --git a/jsonargparse_tests/test_paths.py b/jsonargparse_tests/test_paths.py index 3be4bf6e..94601cea 100644 --- a/jsonargparse_tests/test_paths.py +++ b/jsonargparse_tests/test_paths.py @@ -688,7 +688,7 @@ def test_sub_configs_list_path_fr_default_stdin(parser, tmp_cwd, validate_defaul class ClassListPath: def __init__(self, files: list[Path_fr]): - self.files = files + self.files = files # pragma: no cover def test_add_class_list_path(parser, tmp_cwd): @@ -709,7 +709,7 @@ def test_add_class_list_path(parser, tmp_cwd): class DataOptionalPath: def __init__(self, path: Optional[os.PathLike] = None): - pass + pass # pragma: no cover def test_sub_configs_optional_pathlike_subclass_parameter(parser, tmp_cwd): @@ -729,7 +729,7 @@ class Base: class DataUnionPath: def __init__(self, path: Union[Base, os.PathLike, str] = ""): - pass + pass # pragma: no cover def test_sub_configs_union_subclass_and_pathlike(parser, tmp_cwd): diff --git a/jsonargparse_tests/test_postponed_annotations.py b/jsonargparse_tests/test_postponed_annotations.py index 9c505404..90c6d4d4 100644 --- a/jsonargparse_tests/test_postponed_annotations.py +++ b/jsonargparse_tests/test_postponed_annotations.py @@ -32,7 +32,7 @@ def function_pep604(p1: str | None, p2: int | float | bool = 1): - return p1 + return p1 # pragma: no cover def test_get_types_pep604(): @@ -42,15 +42,15 @@ def test_get_types_pep604(): class NeedsBackport: def __init__(self, p1: list | set): - self.p1 = p1 + self.p1 = p1 # pragma: no cover @staticmethod def static_method(p1: str | int): - return p1 + return p1 # pragma: no cover @classmethod def class_method(cls, p1: float | None): - return p1 + return p1 # pragma: no cover @pytest.mark.parametrize( @@ -67,7 +67,7 @@ def test_get_types_methods(method, expected): def function_forward_ref(cls: "NeedsBackport", p1: "int"): - return cls + return cls # pragma: no cover def test_get_types_forward_ref(): @@ -76,7 +76,7 @@ def test_get_types_forward_ref(): def function_undefined_type(p1: not_defined | None, p2: int): # type: ignore # noqa: F821 - return p1 + return p1 # pragma: no cover def test_get_types_undefined_type(): @@ -90,7 +90,7 @@ def test_get_types_undefined_type(): def function_all_types_fail(p1: not_defined | None, p2: not_defined): # type: ignore # noqa: F821 - return p1 + return p1 # pragma: no cover def test_get_types_all_types_fail(): @@ -107,7 +107,7 @@ def test_evaluate_postponed_annotations_all_types_fail(logger): def function_missing_type(p1, p2: str | int): - return p1 + return p1 # pragma: no cover def test_get_types_missing_type(): @@ -156,7 +156,7 @@ def test_type_checking_visitor_failure(logger): assert "Failed to execute 'TYPE_CHECKING' block" in logs.getvalue() -if TYPE_CHECKING: +if TYPE_CHECKING: # pragma: no cover import xml.dom class TypeCheckingClass1: @@ -169,7 +169,7 @@ class TypeCheckingClass2: def function_type_checking_nested_attr(p1: str, p2: Optional["xml.dom.Node"]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_nested_attr(): @@ -180,7 +180,7 @@ def test_get_types_type_checking_nested_attr(): def function_type_checking_union(p1: Union[bool, TypeCheckingClass1, int], p2: Union[float, "TypeCheckingClass2"]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_union(): @@ -195,7 +195,7 @@ def test_get_types_type_checking_union(): def function_type_checking_alias(p1: type_checking_alias, p2: "type_checking_alias"): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_alias(): @@ -210,7 +210,7 @@ def test_get_types_type_checking_alias(): def function_type_checking_optional_alias(p1: type_checking_alias | None, p2: Optional["type_checking_alias"]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_optional_alias(): @@ -225,7 +225,7 @@ def test_get_types_type_checking_optional_alias(): def function_type_checking_list(p1: List[Union["TypeCheckingClass1", TypeCheckingClass2]]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_list(): @@ -239,7 +239,7 @@ def test_get_types_type_checking_list(): def function_type_checking_tuple(p1: Tuple[TypeCheckingClass1, "TypeCheckingClass2"]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_tuple(): @@ -250,7 +250,7 @@ def test_get_types_type_checking_tuple(): def function_type_checking_type(p1: Type["TypeCheckingClass2"]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_type(): @@ -261,7 +261,7 @@ def test_get_types_type_checking_type(): def function_type_checking_dict(p1: Dict[str, Union[TypeCheckingClass1, "TypeCheckingClass2"]]): - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_dict(): @@ -278,7 +278,7 @@ def test_get_types_type_checking_dict(): def function_type_checking_undefined_forward_ref(p1: List["Undefined"], p2: bool): # type: ignore # noqa: F821 - return p1 + return p1 # pragma: no cover def test_get_types_type_checking_undefined_forward_ref(logger): @@ -303,7 +303,7 @@ def test_get_types_type_checking_dataclass_init_forward_ref(): def function_source_unavailable(p1: List["TypeCheckingClass1"]): - return p1 + return p1 # pragma: no cover def test_get_types_source_unavailable(logger): @@ -330,7 +330,7 @@ def test_get_types_dataclass_pep585(parser): @dataclasses.dataclass class DataWithInit585(Data585): def __init__(self, b: Path_drw, **kwargs): - super().__init__(b=os.fspath(b), **kwargs) + super().__init__(b=os.fspath(b), **kwargs) # pragma: no cover def test_add_dataclass_with_init_pep585(parser, tmp_cwd): @@ -511,7 +511,7 @@ class ForwardReferencedB: _TRIGGER_MODULE_CACHE[id(mod.OtherType)] = {"ForwardReferencedB": mod.ForwardReferencedB} class NoScanModules(dict): - def items(self): + def items(self): # pragma: no cover raise AssertionError("sys.modules should not be scanned when trigger bindings are warm") monkeypatch.setattr(postponed_annotations, "sys", SimpleNamespace(modules=NoScanModules({}))) @@ -536,7 +536,7 @@ def test_reuses_cached_bindings_before_scanning_sys_modules(self, monkeypatch, f _enrich_globals_for_string_forward_refs({"NT": fwdref_origin_mod.NamedType}) class NoScanModules(dict): - def items(self): + def items(self): # pragma: no cover raise AssertionError("sys.modules should not be scanned when the trigger cache is warm") monkeypatch.setattr( diff --git a/jsonargparse_tests/test_pydantic.py b/jsonargparse_tests/test_pydantic.py index abdb7467..f42a7ff3 100644 --- a/jsonargparse_tests/test_pydantic.py +++ b/jsonargparse_tests/test_pydantic.py @@ -183,7 +183,7 @@ class PydanticHelp(pydantic.BaseModel): class OptionalPydantic: def __init__(self, a: Optional[PydanticModel] = None): - self.a = a + self.a = a # pragma: no cover class NestedModel(pydantic.BaseModel): inputs: List[str] @@ -252,8 +252,6 @@ def test_pydantic_types(self, valid_value, invalid_value, cast, type_str, monkey pydantic_type = eval(f"pydantic.{type_str}") self.num_models += 1 Model = pydantic.create_model(f"Model{self.num_models}", param=(pydantic_type, ...)) - if pydantic_support == 1: - monkeypatch.setitem(Model.__init__.__globals__, "pydantic_type", pydantic_type) parser = ArgumentParser(exit_on_error=False) parser.add_argument("--model", type=Model) diff --git a/jsonargparse_tests/test_shtab.py b/jsonargparse_tests/test_shtab.py index 95ac891f..9b65e69c 100644 --- a/jsonargparse_tests/test_shtab.py +++ b/jsonargparse_tests/test_shtab.py @@ -29,7 +29,7 @@ def skip_if_wsl_message(): popen = subprocess.Popen(["bash", "-c", "echo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, _ = popen.communicate() if "Windows Subsystem for Linux has no installed distributions" in out.decode().replace("\x00", ""): - pytest.skip(out.decode().replace("\x00", "")) + pytest.skip(out.decode().replace("\x00", "")) # pragma: no cover @pytest.fixture(autouse=True, scope="module") @@ -291,7 +291,7 @@ def test_bash_optional_file(parser, path_type): class Base: def __init__(self, p1: int): - pass + pass # pragma: no cover def test_bash_class_config(parser): @@ -302,12 +302,12 @@ def test_bash_class_config(parser): class SubA(Base): def __init__(self, p1: int, p2: AXEnum): - pass + pass # pragma: no cover class SubB(Base): def __init__(self, p1: int, p3: float): - pass + pass # pragma: no cover def test_bash_subclasses_fail_get_perams(parser, logger): @@ -352,7 +352,7 @@ def test_bash_subclasses(parser, subtests): class Other: def __init__(self, o1: bool): - pass + pass # pragma: no cover def test_bash_union_subclasses(parser, subtests): @@ -372,12 +372,12 @@ def test_bash_union_subclasses(parser, subtests): class SupBase: def __init__(self, s1: Base): - pass + pass # pragma: no cover class SupA(SupBase): def __init__(self, s1: Optional[Base]): - pass + pass # pragma: no cover def test_bash_nested_subclasses(parser, subtests): diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py index 6940665e..cafc82fb 100644 --- a/jsonargparse_tests/test_signatures.py +++ b/jsonargparse_tests/test_signatures.py @@ -157,7 +157,7 @@ def test_add_class_default_group_title(parser): class WithDefault: def __init__(self, p1: int = 1, p2: str = "-"): - pass + pass # pragma: no cover def test_add_class_with_default(parser): @@ -222,7 +222,7 @@ def test_add_class_nested_with_and_without_parameters(parser): class SkippedUnderscoreParam: def __init__(self, _a0=None): - pass + pass # pragma: no cover def test_add_class_skipped_underscore_parameter(parser): @@ -230,7 +230,7 @@ def test_add_class_skipped_underscore_parameter(parser): class WithNew: - def __new__(cls, a1: int = 1, a2: float = 2.3): + def __new__(cls, a1: int = 1, a2: float = 2.3): # pragma: no cover obj = object.__new__(cls) obj.a1 = a1 # type: ignore[attr-defined] obj.a2 = a2 # type: ignore[attr-defined] @@ -325,12 +325,12 @@ def test_add_class_conditional_kwargs(parser): class Debug1: def __init__(self, c1_a1: float, c1_a2: int = 1): - pass + pass # pragma: no cover class Debug2(Debug1): def __init__(self, *args, c2_a1: int = 2, c2_a2: float = 0.2, **kwargs): - pass + pass # pragma: no cover def test_add_class_skip_parameter_debug_logging(parser, logger): @@ -416,7 +416,7 @@ def instantiate(cls, **kwargs): class WithGenerics(Generic[X, Y]): - def __init__(self, a: X, b: Y): + def __init__(self, a: X, b: Y): # pragma: no cover self.a = a self.b = b @@ -527,7 +527,7 @@ def test_add_method_normal_and_static(parser): class SubWithMethod(WithMethods): - def normal_method(self, *args, p2: int = 2, **kwargs): + def normal_method(self, *args, p2: int = 2, **kwargs): # pragma: no cover p1 = super().normal_method(**kwargs) return p1, p2 @@ -612,7 +612,7 @@ def test_add_function_arguments(parser): def func_skip_params(a1="1", a2: float = 2.0, a3: bool = False, a4: int = 4): - return a1 + return a1 # pragma: no cover def test_add_function_skip_names(parser): @@ -632,7 +632,7 @@ def test_add_function_skip_positionals_invalid(parser): def func_invalid_type(a1: None): - return a1 + return a1 # pragma: no cover def test_add_function_invalid_type(parser): @@ -642,7 +642,7 @@ def test_add_function_invalid_type(parser): def func_implicit_optional(a1: int = None): # type: ignore[assignment] - return a1 + return a1 # pragma: no cover def test_add_function_implicit_optional(parser): @@ -651,7 +651,7 @@ def test_add_function_implicit_optional(parser): def func_type_as_string(a2: "int"): - return a2 + return a2 # pragma: no cover def test_add_function_fail_untyped_true_str_type(parser): @@ -660,7 +660,7 @@ def test_add_function_fail_untyped_true_str_type(parser): def func_untyped_params(a1, a2=None): - return a1 + return a1 # pragma: no cover def test_add_function_fail_untyped_true_untyped_params(parser): @@ -676,7 +676,7 @@ def test_add_function_fail_untyped_false(parser): def func_untyped_optional(a1: str, a2=None): - return a1 + return a1 # pragma: no cover def test_add_function_fail_untyped_true_untyped_optional(parser): @@ -685,10 +685,6 @@ def test_add_function_fail_untyped_true_untyped_optional(parser): assert Namespace(a1="x", a2=None) == parser.parse_args(["--a1=x"]) -def func_config(a1="1", a2: float = 2.0, a3: bool = False): - return a1 - - def test_add_function_group_config(parser, tmp_cwd): parser.add_function_arguments(func, "func") @@ -722,7 +718,7 @@ def test_add_function_group_config_within_config(parser, tmp_cwd): def func_param_conflict(p1: int, cfg: dict): - pass + pass # pragma: no cover def test_add_function_param_conflict(parser): @@ -733,7 +729,7 @@ def test_add_function_param_conflict(parser): def func_positional_and_keyword_only(a: int, /, b: int, *, c: int, d: int = 1): - pass + pass # pragma: no cover def test_add_function_positional_and_keyword_only_parameters(parser): diff --git a/jsonargparse_tests/test_stubs_resolver.py b/jsonargparse_tests/test_stubs_resolver.py index 0dcd92fa..83354970 100644 --- a/jsonargparse_tests/test_stubs_resolver.py +++ b/jsonargparse_tests/test_stubs_resolver.py @@ -10,7 +10,6 @@ from ipaddress import ip_network from random import Random, SystemRandom, uniform from tarfile import TarFile -from typing import Optional from unittest.mock import patch from uuid import UUID, uuid5 @@ -26,9 +25,6 @@ skip_if_requests_unavailable, ) -torch_available = bool(find_spec("torch")) -torchvision_available = bool(find_spec("torchvision")) - @pytest.fixture(autouse=True, scope="module") def skip_if_typeshed_client_unavailable(): @@ -42,15 +38,6 @@ def clear_stubs_resolver(): _stubs_resolver.stubs_resolver = None -@pytest.fixture -def allow_py_files(): - with patch.dict("jsonargparse._common.parsing_settings"): - clear_stubs_resolver() - set_parsing_settings(stubs_resolver_allow_py_files=True) - yield - clear_stubs_resolver() - - @pytest.fixture(params=["allow-py-files-true", "allow-py-files-false"]) def parametrize_allow_py_files(request): allow_py_files = request.param == "allow-py-files-true" @@ -81,7 +68,7 @@ def inspect_signature_failure(mock_obj): def inspect_signature(obj): if obj is mock_obj: raise ValueError("inspect_signature failed") - return original_inspect_signature(obj) + return original_inspect_signature(obj) # pragma: no cover with patch("inspect.signature", side_effect=inspect_signature) as mock_signature: yield @@ -353,99 +340,3 @@ def test_get_params_inspect_signature_failure_missing_type(logger): assert "int | str | bytes | ipaddress.IPv4Address | " in str(params[0].annotation) assert "get_parameters_from_ast failed" in logs.getvalue() assert "get_parameters_by_assumptions failed" not in logs.getvalue() - - -# pytorch tests - - -torch_optimizers_schedulers = torch_available -if torch_available: - import importlib.metadata - - torch_version = tuple(int(v) for v in importlib.metadata.version("torch").split(".", 2)[:2]) - - if torch_version < (2, 1) or torch_version >= (2, 4): - torch_optimizers_schedulers = False - else: - import torch.optim # pylint: disable=import-error - import torch.optim.lr_scheduler # pylint: disable=import-error - - -@pytest.mark.skipif(not torch_optimizers_schedulers, reason="only for torch>=2.1,<2.4") -@pytest.mark.parametrize( - "class_name", - [ - "Adadelta", - "Adagrad", - "Adamax", - "ASGD", - "LBFGS", - "NAdam", - "RAdam", - "RMSprop", - "Rprop", - "SGD", - "SparseAdam", - ], -) -def test_get_params_torch_optimizer(class_name): - cls = getattr(torch.optim, class_name) - params = get_params(cls) - assert all(p.annotation is not inspect._empty for p in params) - with mock_stubs_missing_types(): - params = get_params(cls) - assert any(p.annotation is inspect._empty for p in params) - - -@pytest.mark.skipif(not torch_optimizers_schedulers, reason="only for torch>=2.1,<2.4") -@pytest.mark.parametrize( - "class_name", - [ - "_LRScheduler", - "LambdaLR", - "MultiplicativeLR", - "StepLR", - "MultiStepLR", - "ConstantLR", - "LinearLR", - "ExponentialLR", - "ChainedScheduler", - "SequentialLR", - "CosineAnnealingLR", - "ReduceLROnPlateau", - "CyclicLR", - "CosineAnnealingWarmRestarts", - "OneCycleLR", - "PolynomialLR", - ], -) -def test_get_params_torch_lr_scheduler(class_name): - cls = getattr(torch.optim.lr_scheduler, class_name) - params = get_params(cls) - assert all(p.annotation is not inspect._empty for p in params) - with mock_stubs_missing_types(): - params = get_params(cls) - assert any(p.annotation is inspect._empty for p in params) - - -@pytest.mark.skipif(not torch_available, reason="torch package is required") -def test_get_params_torch_function_argmax(allow_py_files): - import torch - - params = get_params(torch.argmax) - assert ["input", "dim", "keepdim", "out"] == get_param_names(params) - assert params[0].annotation is torch.Tensor - assert params[1].annotation == Optional[int] - assert params[2].annotation is bool - assert params[3].annotation == Optional[torch.Tensor] - with mock_stubs_missing_resolver(): - assert [] == get_params(torch.argmax) - - -@pytest.mark.skipif(not torchvision_available, reason="torchvision package is required") -def test_get_params_torchvision_class_resize(allow_py_files): - from torchvision.transforms import Resize - - params = get_params(Resize) - assert ["size", "interpolation", "max_size", "antialias"] == get_param_names(params) - assert all(p.annotation is inspect._empty for p in params) diff --git a/jsonargparse_tests/test_subclasses.py b/jsonargparse_tests/test_subclasses.py index 91b95892..683bdf11 100644 --- a/jsonargparse_tests/test_subclasses.py +++ b/jsonargparse_tests/test_subclasses.py @@ -54,12 +54,12 @@ def test_subclass_basics(parser, type): class BaseClassDefault: def __init__(self, param: str = "base_default"): - self.param = param + self.param = param # pragma: no cover class SubClassDefault(BaseClassDefault): def __init__(self, param: str = "sub_default"): - super().__init__(param=param) + super().__init__(param=param) # pragma: no cover def test_subclass_defaults(parser): @@ -97,7 +97,7 @@ def __init__(self, a1: Optional[int] = 1, a2: Optional[float] = 2.3): class Instantiate2: def __init__(self, c1: Optional[Instantiate1]): - self.c1 = c1 + self.c1 = c1 # pragma: no cover def test_subclass_within_class_instantiate(parser): @@ -115,7 +115,7 @@ def test_subclass_within_class_instantiate(parser): class SetDefaults: def __init__(self, p1: int = 1, p2: str = "x", p3: bool = False): - pass + pass # pragma: no cover def test_subclass_set_defaults(parser): @@ -182,7 +182,7 @@ def test_subclass_union_help(parser): class DefaultsDisabled: def __init__(self, p1: int = 1, p2: str = "2"): - pass + pass # pragma: no cover def test_subclass_parse_defaults_disabled(parser): @@ -215,11 +215,11 @@ def test_subclass_known_subclasses_multiple_bases(parser): class UntypedParams: def __init__(self, a1, a2=None): - self.a1 = a1 + self.a1 = a1 # pragma: no cover def func_subclass_untyped(c1: Union[int, UntypedParams]): - return c1 + return c1 # pragma: no cover def test_subclass_allow_untyped_parameters_help(parser): @@ -231,7 +231,7 @@ def test_subclass_allow_untyped_parameters_help(parser): class MergeInitArgs(Calendar): def __init__(self, param_a: int = 1, param_b: str = "x", **kwargs): - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover def test_subclass_merge_init_args_global_config(parser): @@ -281,7 +281,7 @@ def test_subclass_init_args_without_class_path_dict(parser): class DefaultConfig: def __init__(self, cal: Optional[Calendar] = None, val: int = 2): - self.cal = cal + self.cal = cal # pragma: no cover def test_subclass_with_default_config_files(parser, tmp_cwd, logger, subtests): @@ -319,7 +319,7 @@ def test_subclass_with_default_config_files(parser, tmp_cwd, logger, subtests): class DefaultConfigSubcommands: def __init__(self, foo: int): - self.foo = foo + self.foo = foo # pragma: no cover def test_subclass_in_subcommand_with_global_default_config_file(parser, subparser, tmp_cwd): @@ -399,7 +399,7 @@ def test_function_instantiator(parser): def function_undefined_return(p1: int) -> "Undefined": # type: ignore[name-defined] # noqa: F821 - return FunctionInstantiator(p1, "x") + return FunctionInstantiator(p1, "x") # pragma: no cover def test_instantiator_undefined_return(parser, logger): @@ -542,7 +542,7 @@ def test_subclass_env_config(parser): class Nested: def __init__(self, cal: Calendar, p1: int = 0): - self.cal = cal + self.cal = cal # pragma: no cover @pytest.mark.parametrize("prefix", ["", ".init_args"], ids=lambda v: f"prefix={v}") @@ -578,12 +578,12 @@ def test_subclass_nested_help(parser): class RequiredParamSubModule: def __init__(self, p1: int, p2: int = 2, p3: int = 3): - pass + pass # pragma: no cover class RequiredParamModel: def __init__(self, sub_module: RequiredParamSubModule): - pass + pass # pragma: no cover def test_subclass_required_parameter_with_default_config_files(parser, tmp_cwd): @@ -674,7 +674,7 @@ def test_subclass_class_name_then_invalid_init_args(parser): class DictParam: def __init__(self, param: Dict[str, int]): - pass + pass # pragma: no cover @pytest.mark.parametrize("prefix", ["", ".init_args"]) @@ -740,12 +740,12 @@ class Module: class Network(Module): def __init__(self, sub_network: Module, some_dict: Dict[str, Any] = {}): - pass + pass # pragma: no cover class Model: def __init__(self, encoder: Module): - pass + pass # pragma: no cover def test_subclass_dict_parameter_deep(parser): @@ -781,7 +781,7 @@ def test_subclass_dict_parameter_deep(parser): class ListAppend: def __init__(self, p1: int = 0, p2: int = 0): - pass + pass # pragma: no cover @pytest.mark.parametrize("list_type", [List, Iterable]) @@ -797,7 +797,7 @@ def test_subclass_list_append_single(parser, list_type): @final class IterableAppendCalendars: def __init__(self, cal: Union[Calendar, Iterable[Calendar], bool] = True): - self.cal = cal + self.cal = cal # pragma: no cover def test_subclass_list_append_nonclass_default(parser): @@ -815,7 +815,7 @@ def test_subclass_list_append_nonclass_default(parser): class ListAppendCalendars: def __init__(self, cals: Optional[Union[Calendar, List[Calendar]]] = None): - self.cals = cals + self.cals = cals # pragma: no cover def test_subclass_list_append_multiple(parser): @@ -959,12 +959,12 @@ def test_type_any_dict_of_subclasses(parser): class OverrideA(Calendar): def __init__(self, pa: str = "a", pc: str = "", **kwds): - super().__init__(**kwds) + super().__init__(**kwds) # pragma: no cover class OverrideB(Calendar): def __init__(self, pb: str = "b", pc: int = 4, **kwds): - super().__init__(**kwds) + super().__init__(**kwds) # pragma: no cover def test_subclass_discard_init_args(parser, logger): @@ -994,17 +994,17 @@ class OverrideChildBase: class OverrideChildA(OverrideChildBase): def __init__(self, a: int = 0): - pass + pass # pragma: no cover class OverrideChildB(OverrideChildBase): def __init__(self, b: int = 0): - pass + pass # pragma: no cover class OverrideParent: def __init__(self, c: OverrideChildBase): - pass + pass # pragma: no cover def test_subclass_discard_init_args_nested(parser, logger): @@ -1030,12 +1030,12 @@ def test_subclass_discard_init_args_nested(parser, logger): class OverrideMixed(Calendar): def __init__(self, *args, param: int = 0, **kwargs): - super().__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # pragma: no cover class OverrideMixedMain: def __init__(self, cal: Union[Calendar, bool] = lazy_instance(OverrideMixed, param=1)): - self.cal = cal + self.cal = cal # pragma: no cover def test_subclass_discard_init_args_mixed_type(parser, logger): @@ -1049,17 +1049,17 @@ def test_subclass_discard_init_args_mixed_type(parser, logger): class OverrideBase: def __init__(self, b: int = 1): - pass + pass # pragma: no cover class OverrideSub1(OverrideBase): def __init__(self, s1: str = "-"): - pass + pass # pragma: no cover class OverrideSub2(OverrideBase): def __init__(self, s2: str = "-"): - pass + pass # pragma: no cover def test_subclass_discard_init_args_config_with_default(parser, logger): @@ -1108,17 +1108,17 @@ def test_subclass_discard_init_args_with_default_config_files(parser, tmp_cwd, l class Arch: def __init__(self, a: int = 1): - pass + pass # pragma: no cover class ArchB(Arch): def __init__(self, a: int = 2, b: int = 3): - pass + pass # pragma: no cover class ArchC(Arch): def __init__(self, a: int = 4, c: int = 5): - pass + pass # pragma: no cover def test_subclass_subcommand_set_defaults_discard_init_args(parser, subparser, logger): @@ -1145,7 +1145,7 @@ def __init__(self, b: float = 0.5): class ConfigDiscardSub1(ConfigDiscardBase): def __init__(self, s1: str = "x", **kwargs): - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class ConfigDiscardSub2(ConfigDiscardBase): @@ -1197,17 +1197,17 @@ def test_discard_init_args_config_nested(parser, logger, tmp_cwd, method): class DictDiscardBase: def __init__(self, b: float = 0.5): - pass + pass # pragma: no cover class DictDiscardSub1(DictDiscardBase): def __init__(self, s1: int = 3, **kwargs): - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class DictDiscardSub2(DictDiscardBase): def __init__(self, s2: int = 4, **kwargs): - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover class DictDiscardMain: @@ -1303,7 +1303,7 @@ def test_subclass_unresolved_parameters(parser, subtests): class UnresolvedNameClash: def __init__(self, dict_kwargs: int = 1, **kwargs): - self.kwargs = kwargs + self.kwargs = kwargs # pragma: no cover def test_subclass_unresolved_parameters_name_clash(parser): @@ -1396,12 +1396,12 @@ def test_add_subclass_not_required_group(parser): class ListUnionA: - def __init__(self, pa1: int): + def __init__(self, pa1: int): # pragma: no cover self.pa1 = pa1 class ListUnionB: - def __init__(self, pb1: str, pb2: float): + def __init__(self, pb1: str, pb2: float): # pragma: no cover self.pb1 = pb1 self.pb2 = pb2 @@ -1447,7 +1447,7 @@ def test_add_argument_subclass_instance_default(parser): class InstanceDefault: def __init__(self, cal: Calendar = Calendar(firstweekday=2)): - pass + pass # pragma: no cover def test_subclass_signature_instance_default(parser): @@ -1480,25 +1480,25 @@ def predict(self, items: List[float]) -> List[float]: class SubclassImplementsInterface(Interface): def __init__(self, max_items: int): - self.max_items = max_items + self.max_items = max_items # pragma: no cover def predict(self, items: List[float]) -> List[float]: - return items + return items # pragma: no cover class NotImplementsInterface1: def predict(self, items: str) -> List[float]: - return [] + return [] # pragma: no cover class NotImplementsInterface2: def predict(self, items: List[float], extra: int) -> List[float]: - return items + return items # pragma: no cover class NotImplementsInterface3: def predict(self, items: List[float]) -> None: - return + return # pragma: no cover @pytest.mark.parametrize( @@ -1573,17 +1573,17 @@ def __call__(self, items: List[float]) -> List[float]: class NotImplementsCallableInterface1: def __call__(self, items: str) -> List[float]: - return [] + return [] # pragma: no cover class NotImplementsCallableInterface2: def __call__(self, items: List[float], extra: int) -> List[float]: - return items + return items # pragma: no cover class NotImplementsCallableInterface3: def __call__(self, items: List[float]) -> None: - return + return # pragma: no cover @pytest.mark.parametrize( @@ -1626,13 +1626,13 @@ def test_parse_implements_callable_protocol(parser): class ParamSkipBase: - def __init__(self, a1: int = 1, a2: float = 2.3): + def __init__(self, a1: int = 1, a2: float = 2.3): # pragma: no cover self.a1 = a1 self.a2 = a2 class ParamSkipSub(ParamSkipBase): - def __init__(self, b1: float = 4.5, b2: int = 6, **kwargs): + def __init__(self, b1: float = 4.5, b2: int = 6, **kwargs): # pragma: no cover super().__init__(**kwargs) self.b1 = b1 self.b2 = b2 @@ -1647,14 +1647,14 @@ def test_add_subclass_parameter_skip(parser): class ParamSkip1: - def __init__(self, a1: int = 1, a2: float = 2.3, a3: str = "4"): + def __init__(self, a1: int = 1, a2: float = 2.3, a3: str = "4"): # pragma: no cover self.a1 = a1 self.a2 = a2 self.a3 = a3 class ParamSkip2: - def __init__(self, c1: ParamSkip1, c2: int = 5, c3: float = 6.7): + def __init__(self, c1: ParamSkip1, c2: int = 5, c3: float = 6.7): # pragma: no cover pass @@ -1687,17 +1687,17 @@ def test_subclass_print_config(parser): class PrintConfigRequired: def __init__(self, arg1: float): - pass + pass # pragma: no cover class PrintConfigRequiredBase: def __init__(self): - pass + pass # pragma: no cover class PrintConfigRequiredSub(PrintConfigRequiredBase): def __init__(self, arg1: int, arg2: int = 1): - pass + pass # pragma: no cover def test_subclass_print_config_required_parameters_as_null(parser): @@ -1782,7 +1782,7 @@ def test_subclass_invalid_init_args_in_yaml(parser): class RequiredParamsMissing: def __init__(self, p1: int, p2: str): - pass + pass # pragma: no cover def test_subclass_required_parameters_missing(parser): @@ -1825,7 +1825,7 @@ def test_subclass_help_not_subclass(parser): class Implicit: def __init__(self, a: int = 1, b: str = ""): - pass + pass # pragma: no cover def test_subclass_implicit_class_path(parser): @@ -1845,7 +1845,7 @@ def test_subclass_implicit_class_path(parser): class ErrorIndentation1: def __init__(self, val: Optional[Union[int, dict]] = None): - pass + pass # pragma: no cover def test_subclass_error_indentation_invalid_init_arg(parser): @@ -1868,7 +1868,7 @@ def test_subclass_error_indentation_invalid_init_arg(parser): class ErrorIndentation2: def __init__(self, val: int): - pass + pass # pragma: no cover def test_subclass_error_indentation_in_union_invalid_value(parser): diff --git a/jsonargparse_tests/test_typehints.py b/jsonargparse_tests/test_typehints.py index 505f6f3d..34f4ffe4 100644 --- a/jsonargparse_tests/test_typehints.py +++ b/jsonargparse_tests/test_typehints.py @@ -536,7 +536,7 @@ def __init__( self, nested: List[Dict[str, str]] = [{"a": "random_crop"}, {"b": "random_blur"}], ) -> None: - self.nested = nested + self.nested = nested # pragma: no cover def test_list_append_dicts_nested_with_default(parser): @@ -750,7 +750,7 @@ def test_unpack_support(parser): MyTestUnpackDict = TypedDict("MyTestUnpackDict", {"a": Required[int], "b": NotRequired[int]}, total=True) class UnpackClass: - def __init__(self, **kwargs: Unpack[MyTestUnpackDict]) -> None: + def __init__(self, **kwargs: Unpack[MyTestUnpackDict]) -> None: # pragma: no cover self.a = kwargs["a"] self.b = kwargs.get("b") @@ -760,7 +760,7 @@ class MyTestUnpackClass: class MyTestInheritedUnpackClass(UnpackClass): def __init__(self, **kwargs) -> None: - super().__init__(**kwargs) + super().__init__(**kwargs) # pragma: no cover @pytest.mark.skipif(not Unpack, reason="Unpack introduced in python 3.11 or backported in typing_extensions") @@ -1016,11 +1016,11 @@ def test_callable_class_path_short_init_args(parser, callable_type): def int_to_str(p: int) -> str: - return str(p) + return str(p) # pragma: no cover def str_to_int(p: str) -> int: - return int(p) + return int(p) # pragma: no cover def test_callable_args_function_path(parser): @@ -1269,7 +1269,7 @@ def test_callable_return_class_default_class_override_init_arg(parser): class SkipCallableInitArg: def __init__(self, optimizer: Callable[[List[float]], Optimizer] = SGD): - self.optimizer = optimizer + self.optimizer = optimizer # pragma: no cover def test_add_class_arguments_skip_callable_init_arg(parser): @@ -1289,7 +1289,7 @@ def test_add_class_arguments_skip_callable_init_arg(parser): class SkipCallableMergedWithPartial: def __init__(self, optimizer: Callable[[List[float], float], Optimizer] = SGD): - self.optimizer = optimizer + self.optimizer = optimizer # pragma: no cover def test_add_class_arguments_skip_callable_init_arg_and_partial_skip(parser): @@ -1366,7 +1366,7 @@ def test_callable_args_return_type_union_of_classes(parser, subtests): def optional_callable_args_return_type_class( scheduler: Optional[Callable[[Optimizer], StepLR]] = lambda o: StepLR(o, last_epoch=1), ): - return scheduler + return scheduler # pragma: no cover def test_optional_callable_args_return_type_class(parser, subtests): @@ -1476,7 +1476,7 @@ def __init__( self, scheduler: Callable[[Optimizer], ReduceLROnPlateau] = lambda o: ReduceLROnPlateau(o, monitor="acc"), ): - self.scheduler = scheduler + self.scheduler = scheduler # pragma: no cover def test_callable_return_class_required_arg_from_default(parser): @@ -1510,7 +1510,7 @@ def __init__( self, schedulers: List[Callable[[Optimizer], Union[StepLR, ReduceLROnPlateau]]] = [], ): - self.schedulers = schedulers + self.schedulers = schedulers # pragma: no cover def test_list_callable_return_class(parser): @@ -1562,7 +1562,7 @@ def __init__(self, *args, **kwargs): class IntParam: def __init__(self, param: int = 1): - pass + pass # pragma: no cover def test_lazy_instance_invalid_init_value(): @@ -1644,7 +1644,7 @@ def test_is_optional(typehint, ref_type, expected): class SkipDefault(Calendar): def __init__(self, *args, param: str = "0", **kwargs): - super().__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # pragma: no cover def test_dump_skip_default(parser): @@ -1680,7 +1680,7 @@ def test_get_all_subclass_paths_import_error(): def mocked_get_import_path(cls): if cls is ImportClass: raise ImportError("Failed to import ImportClass") - return get_import_path(cls) + return get_import_path(cls) # pragma: no cover with mock.patch("jsonargparse._typehints.get_import_path", mocked_get_import_path): with catch_warnings(record=True) as w: diff --git a/jsonargparse_tests/test_typing.py b/jsonargparse_tests/test_typing.py index 023a2732..08a2e90a 100644 --- a/jsonargparse_tests/test_typing.py +++ b/jsonargparse_tests/test_typing.py @@ -525,7 +525,7 @@ def test_class_from_function_name_clash(): def get_unknown() -> "Unknown": # type: ignore # noqa: F821 - return None + return None # pragma: no cover def test_invalid_class_from_function(): @@ -569,7 +569,7 @@ def test_add_class_from_function_arguments(parser): def without_return_type(): - pass + pass # pragma: no cover def test_class_from_function_missing_return(): diff --git a/jsonargparse_tests/test_util.py b/jsonargparse_tests/test_util.py index 3be35ba9..30a9c1cb 100644 --- a/jsonargparse_tests/test_util.py +++ b/jsonargparse_tests/test_util.py @@ -142,7 +142,7 @@ def test_get_import_path(): class _StaticMethods: @staticmethod def static_method(): - pass + pass # pragma: no cover static_method = _StaticMethods.static_method @@ -157,7 +157,7 @@ class ParentClassmethod: @classmethod def class_method(cls): - pass + pass # pragma: no cover class ChildClassmethod(ParentClassmethod): @@ -170,7 +170,7 @@ def test_get_import_path_classpath_inheritance(): def unresolvable_import(): - pass + pass # pragma: no cover @patch.dict("jsonargparse._util.unresolvable_import_paths") @@ -184,10 +184,10 @@ def test_register_unresolvable_import_paths(): class Class: @staticmethod def method1(): - pass + pass # pragma: no cover def method2(self): - pass + pass # pragma: no cover def test_object_path_serializer_class_method(): diff --git a/pyproject.toml b/pyproject.toml index 60637302..c7cb49f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,7 +91,8 @@ test = [ "jsonargparse[shtab]", "jsonargparse[argcomplete]", "types-PyYAML>=6.0.11", - "types-requests>=2.28.9", + "types-requests>=2.28.9,<2.34", + "requests<2.34", "responses>=0.12.0", "pydantic>=2.3.0", "attrs>=22.2.0", @@ -209,8 +210,11 @@ usedevelop = true [testenv:omegaconf] extras = test,coverage,all +changedir = jsonargparse_tests setenv = JSONARGPARSE_OMEGACONF_FULL_TEST = true +commands = + python -m pytest {posargs} [testenv:pydantic-v1] extras = coverage