PyTest

Modules:

Name Description
conftest

Pytest top-level conftest.py.

test_pyobjson

Pytest test for Python Object JSON Tool code.

conftest

Pytest top-level conftest.py.

Classes:

Name Description
ThirdClass

ThirdClass for testing.

SecondClass

SecondClass for testing.

FirstClass

FirstClass for testing.

Functions:

Name Description
external_function

Function for testing.

mongo_connection_params

Create dictionary of MongoDB connection parameters.

first_class_with_nested_child_classes

Create ParentClass instance for testing.

first_class_to_mongo_with_nested_child_classes

Create FirstClassToMongo instance for testing.

first_class_json_str

Create JSON string from FirstClass instance for testing.

first_class_to_mongo_json_str

Create JSON string from FirstClassToMongo instance for testing.

ThirdClass

Bases: PythonObjectJson

ThirdClass for testing.

Source code in tests/conftest.py
23
24
25
26
27
28
class ThirdClass(PythonObjectJson):
    """ThirdClass for testing."""

    def __init__(self, third_class_param: str):
        super().__init__()
        self.third_class_param: str = third_class_param

SecondClass

Bases: PythonObjectJson

SecondClass for testing.

Source code in tests/conftest.py
31
32
33
34
35
36
37
class SecondClass(PythonObjectJson):
    """SecondClass for testing."""

    def __init__(self, third_class_list: List[ThirdClass]):
        super().__init__()
        self.third_class_list: List[ThirdClass] = third_class_list
        self.third_class_list_dict: Dict[str, List[ThirdClass]] = {"third_class_list_1": third_class_list}

FirstClass

Bases: PythonObjectJson

FirstClass for testing.

Source code in tests/conftest.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class FirstClass(PythonObjectJson):
    """FirstClass for testing."""

    def __init__(
        self,
        second_class_dict: Dict[str, SecondClass],
        second_class_list: List[SecondClass],
        first_class_set: Optional[Set[str]],
        first_class_tuple: Optional[Tuple[str]],
        first_class_bytes: Optional[bytes],
        first_class_file: Optional[Path],
        first_class_external_function: Optional[Callable],
        first_class_datetime: Optional[datetime],
    ):
        super().__init__()
        self.second_class_dict: Dict[str, SecondClass] = second_class_dict
        self.second_class_list: List[SecondClass] = second_class_list
        self.first_class_set: Set[str] = first_class_set
        self.first_class_tuple: Tuple[str] = first_class_tuple
        self.first_class_bytes: bytes = first_class_bytes
        self.first_class_file: Path = first_class_file
        self.first_class_external_function: Optional[Callable] = first_class_external_function
        self.first_class_datetime: datetime = first_class_datetime

external_function

external_function(param1, param2)

Function for testing.

Source code in tests/conftest.py
18
19
20
def external_function(param1: str, param2: str):
    """Function for testing."""
    return f"{param1}.{param2}"

mongo_connection_params

mongo_connection_params()

Create dictionary of MongoDB connection parameters.

Returns:
  • Dict[str, str]

    dict[str, str]: MongoDB connection parameters.

Source code in tests/conftest.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@fixture(scope="module")
def mongo_connection_params() -> Dict[str, str]:
    """Create dictionary of MongoDB connection parameters.

    Returns:
        dict[str, str]: MongoDB connection parameters.

    """
    return {
        "mongo_host": os.environ.get("MONGO_HOST"),
        "mongo_port": int(os.environ.get("MONGO_PORT")),
        "mongo_database": os.environ.get("MONGO_DATABASE"),
        "mongo_user": os.environ.get("MONGO_ADMIN_USER"),
        "mongo_password": os.environ.get("MONGO_ADMIN_PASS"),
    }

first_class_with_nested_child_classes

first_class_with_nested_child_classes()

Create ParentClass instance for testing.

Returns:
  • FirstClass( FirstClass ) –

    Instance of ParentClass.

Source code in tests/conftest.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@fixture(scope="module")
def first_class_with_nested_child_classes() -> FirstClass:
    """Create ParentClass instance for testing.

    Returns:
        FirstClass: Instance of ParentClass.

    """
    return FirstClass(
        {"second_class_1": SecondClass([ThirdClass("test_third_class_argument_in_dict")])},
        [SecondClass([ThirdClass("test_third_class_argument_in_list")])],
        {"test_first_class_collection_element"},
        ("test_first_class_collection_element",),
        b"test_first_class_collection_element",
        Path(__name__),
        external_function,
        datetime(2024, 1, 1, 0, 0, 0),
    )

first_class_to_mongo_with_nested_child_classes

first_class_to_mongo_with_nested_child_classes(
    mongo_connection_params,
)

Create FirstClassToMongo instance for testing.

Returns:
  • FirstClassToMongo( FirstClassToMongo ) –

    Instance of FirstClassToMongo.

Source code in tests/conftest.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@fixture(scope="module")
def first_class_to_mongo_with_nested_child_classes(mongo_connection_params) -> FirstClassToMongo:
    """Create FirstClassToMongo instance for testing.

    Returns:
        FirstClassToMongo: Instance of FirstClassToMongo.

    """
    return FirstClassToMongo(
        {"second_class_1": SecondClass([ThirdClass("test_third_class_argument_in_dict")])},
        [SecondClass([ThirdClass("test_third_class_argument_in_list")])],
        {"test_first_class_collection_element"},
        ("test_first_class_collection_element",),
        b"test_first_class_collection_element",
        Path(__name__),
        external_function,
        datetime(2024, 1, 1, 0, 0, 0),
        **mongo_connection_params,
    )

first_class_json_str

first_class_json_str()

Create JSON string from FirstClass instance for testing.

Returns:
  • str( str ) –

    JSON string derived from serialized FirstClass instance.

Source code in tests/conftest.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@fixture(scope="module")
def first_class_json_str() -> str:
    """Create JSON string from FirstClass instance for testing.

    Returns:
        str: JSON string derived from serialized FirstClass instance.

    """
    return json.dumps(
        {
            "conftest.firstclass": {
                "collection:dict.second_class_dict": {
                    "second_class_1": {
                        "conftest.secondclass": {
                            "collection:list.third_class_list": [
                                {"conftest.thirdclass": {"third_class_param": "test_third_class_argument_in_dict"}}
                            ],
                            "collection:dict.third_class_list_dict": {
                                "third_class_list_1": [
                                    {"conftest.thirdclass": {"third_class_param": "test_third_class_argument_in_dict"}}
                                ]
                            },
                        }
                    }
                },
                "collection:list.second_class_list": [
                    {
                        "conftest.secondclass": {
                            "collection:list.third_class_list": [
                                {"conftest.thirdclass": {"third_class_param": "test_third_class_argument_in_list"}}
                            ],
                            "collection:dict.third_class_list_dict": {
                                "third_class_list_1": [
                                    {"conftest.thirdclass": {"third_class_param": "test_third_class_argument_in_list"}}
                                ]
                            },
                        }
                    }
                ],
                "collection:set.first_class_set": ["test_first_class_collection_element"],
                "collection:tuple.first_class_tuple": ["test_first_class_collection_element"],
                "collection:bytes.first_class_bytes": "dGVzdF9maXJzdF9jbGFzc19jb2xsZWN0aW9uX2VsZW1lbnQ=",
                "path.first_class_file": "conftest",
                "callable.first_class_external_function": "conftest.external_function::param1:str,param2:str",
                "datetime.first_class_datetime": "2024-01-01T00:00:00",
            }
        },
        ensure_ascii=False,
        indent=2,
    )

first_class_to_mongo_json_str

first_class_to_mongo_json_str(first_class_json_str)

Create JSON string from FirstClassToMongo instance for testing.

Returns:
  • str( str ) –

    JSON string derived from serialized FirstClassToMongo instance.

Source code in tests/conftest.py
203
204
205
206
207
208
209
210
211
212
213
214
215
@fixture(scope="module")
def first_class_to_mongo_json_str(first_class_json_str) -> str:
    """Create JSON string from FirstClassToMongo instance for testing.

    Returns:
        str: JSON string derived from serialized FirstClassToMongo instance.

    """
    first_class_json = json.loads(first_class_json_str)

    return json.dumps(
        {"conftest.firstclasstomongo": first_class_json["conftest.firstclass"]}, ensure_ascii=False, indent=2
    )

test_pyobjson

Pytest test for Python Object JSON Tool code.

Note

Tests pyobjson.base module.

Classes:

Name Description
TestPythonObjectJson

Pytest class for PythonObjectJson functionality.

TestPythonObjectJsonToMongo

Pytest class for PythonObjectJsonToMongo functionality.

TestPythonObjectJson

Pytest class for PythonObjectJson functionality.

Source code in tests/test_pyobjson.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class TestPythonObjectJson:
    """Pytest class for PythonObjectJson functionality."""

    def test_serialization_to_json_string(self, first_class_with_nested_child_classes, first_class_json_str):
        # confirm conftest.FirstClass instance as a JSON string is equal to the conftest FirstClass JSON string
        assert first_class_with_nested_child_classes.to_json_str() == first_class_json_str

    def test_deserialization_from_json_string(self, first_class_with_nested_child_classes, first_class_json_str):
        # create new FirstClass instance with all empty/None arguments
        first_class_instance = FirstClass({}, [], None, None, None, None, None, None)

        # confirm new empty FirstClass instance is not equivalent to conftest.FirstClass instance
        assert first_class_instance != first_class_with_nested_child_classes

        # load conftest FirstClass JSON string to new empty FirstClass instance
        first_class_instance.from_json_str(first_class_json_str)

        # confirm newly created FirstClass instance loaded from JSON is equivalent to conftest.FirstClass instance
        assert first_class_instance == first_class_with_nested_child_classes

TestPythonObjectJsonToMongo

Pytest class for PythonObjectJsonToMongo functionality.

Source code in tests/test_pyobjson.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class TestPythonObjectJsonToMongo:
    """Pytest class for PythonObjectJsonToMongo functionality."""

    def test_serialization_to_json_string(
        self, first_class_to_mongo_with_nested_child_classes, first_class_to_mongo_json_str
    ):
        # confirm conftest.FirstClassToMongo instance as a JSON string is equal to the conftest FirstClassToMongo JSON
        # string
        assert first_class_to_mongo_with_nested_child_classes.to_json_str() == first_class_to_mongo_json_str

    def test_deserialization_from_json_string(
        self, first_class_to_mongo_with_nested_child_classes, first_class_to_mongo_json_str, mongo_connection_params
    ):
        # create new FirstClassToMongo instance with all empty/None arguments
        first_class_to_mongo_instance = FirstClassToMongo(
            {}, [], None, None, None, None, None, None, **mongo_connection_params
        )

        # confirm new empty FirstClassToMongo instance is not equivalent to conftest.FirstClassToMongo instance
        assert first_class_to_mongo_instance != first_class_to_mongo_with_nested_child_classes

        # load conftest FirstClassToMongo JSON string to new empty FirstClass instance
        first_class_to_mongo_instance.from_json_str(first_class_to_mongo_json_str)

        # confirm newly created FirstClassToMongo instance loaded from JSON is equivalent to conftest.FirstClassToMongo
        # instance
        assert first_class_to_mongo_instance == first_class_to_mongo_with_nested_child_classes