Coverage for Users/vladimirpavlov/PycharmProjects/parameterizable/tests/test_parameterizable.py: 100%

1 import json

2 from typing import Any

3

4 import pytest

5

6 from mixinforge.parameterizable_mixin import ParameterizableMixin

7 from mixinforge.json_processor import dumpjs, loadjs

8

9

10 class MyParam(ParameterizableMixin):

11 def __init__(

12 self,

13 a: int,

14 b: int = 2,

15 c: str = "x",

16 d: Any = None,

17 *,

18 e: int = 5,

19 f: int = 7,

20 **kwargs,

21 ) -> None:

22 # store everything so that get_params can see it

23 self.a = a

24 self.b = b

25 self.c = c

26 self.d = d

27 self.e = e

28 self.f = f

29 # an auxiliary-only parameter (not present among defaults)

30 self.verbose = kwargs.get("verbose", False)

31

32 def get_params(self) -> dict[str, Any]:

33 return {

34 "a": self.a,

35 "b": self.b,

36 "c": self.c,

37 "d": self.d,

38 "e": self.e,

39 "f": self.f,

40 "verbose": self.verbose,

41 }

42

43

44 def test_base_class_defaults_and_jsparams_are_empty():

45 # Base class returns empty params dict

46 base = ParameterizableMixin()

47 assert base.get_params() == {}

48

49 js = base.get_jsparams()

50 assert isinstance(js, str)

51 assert loadjs(js) == {}

52

53

54 def test_get_default_params_collects_init_defaults_and_sorts_keys():

55 # Required-only param 'a' must NOT be in defaults

56 expected_defaults = {"b": 2, "c": "x", "d": None, "e": 5, "f": 7}

57

58 got = MyParam.get_default_params()

59 # Ensure keys are sorted lexicographically

60 assert list(got.keys()) == sorted(expected_defaults.keys())

61 assert got == expected_defaults

62

63 # JSON variant round-trips to the same mapping

64 js = MyParam.get_default_jsparams()

65 assert loadjs(js) == expected_defaults

66

67

68 def test_instance_jsparams_is_dump_of_params_dict():

69 obj = MyParam(a=10, b=20, c="ok", e=50, f=70)

70

71 params = obj.get_params()

72 js = obj.get_jsparams()

73

74 # get_jsparams returns dumpjs of a plain dict → loadjs returns the same dict

75 assert loadjs(js) == params

76

77 # And dumpjs/loadjs are indeed JSON – the payload is a JSON string

78 # Validate it parses with the stdlib json loader too

79 json.loads(js)