-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathfeathub_it_test_base.py
More file actions
307 lines (264 loc) · 10.9 KB
/
feathub_it_test_base.py
File metadata and controls
307 lines (264 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# Copyright 2022 The FeatHub Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import shutil
import tempfile
import unittest
import uuid
from abc import abstractmethod
from datetime import timedelta
from typing import Optional, List, Dict, Type, cast
from unittest import TestLoader
import pandas as pd
from testcontainers.mysql import MySqlContainer
from feathub.common import types
from feathub.common.exceptions import FeathubException
from feathub.common.utils import from_json
from feathub.feathub_client import FeathubClient
from feathub.feature_tables.format_config import DataFormat
from feathub.feature_tables.sources.file_system_source import FileSystemSource
from feathub.online_stores.memory_online_store import MemoryOnlineStore
from feathub.registries.local_registry import LocalRegistry
from feathub.registries.registry import Registry
from feathub.table.schema import Schema
from feathub.table.table_descriptor import TableDescriptor
def _merge_nested_dict(a, b) -> None:
"""
Merges dict b into dict a. a and b might be nested dict.
"""
for key in b:
if key not in a:
a[key] = b[key]
elif isinstance(a[key], dict) and isinstance(b[key], dict):
_merge_nested_dict(a[key], b[key])
elif a[key] != b[key]:
raise FeathubException(
f"Mismatch value {a[key]} and {b[key]} found for key {key}"
)
# A wrapper class for Registry that verifies the to/from json methods for
# every saved table descriptor.
# TODO: remove Sinks' to_json() implementations or add tests that covers
# these methods.
class RegistryWithJsonCheck(Registry):
def __init__(self, registry: Registry):
super().__init__("", {})
self.registry = registry
def build_features(
self,
feature_descriptors: List[TableDescriptor],
force_update: bool = False,
props: Optional[Dict] = None,
) -> List[TableDescriptor]:
feature_descriptors = [
self._save_and_reload_through_json(x) for x in feature_descriptors
]
return self.registry.build_features(feature_descriptors, force_update, props)
def register_features(
self, feature_descriptors: List[TableDescriptor], force_update: bool = False
) -> List[bool]:
feature_descriptors = [
self._save_and_reload_through_json(x) for x in feature_descriptors
]
return self.registry.register_features(feature_descriptors, force_update)
def get_features(
self, name: str, force_update: bool = False, is_resolved: bool = True
) -> TableDescriptor:
return self.registry.get_features(name, force_update, is_resolved)
def delete_features(self, name: str) -> bool:
return self.delete_features(name)
@staticmethod
def _save_and_reload_through_json(features: TableDescriptor):
json_bytes = json.dumps(features.to_json())
return from_json(json.loads(json_bytes))
class FeathubITTestBase(unittest.TestCase):
"""
Abstract base class for all FeatHub integration tests. A child class of
this class must instantiate the corresponding FeathubClient instance and
have its test cases use FeatHub public APIs to get and write features.
This class also provides utility variables and methods to assist the construction
of test cases.
"""
# By setting this attribute to false, it prevents pytest from discovering
# this class as a test when searching up from its child classes.
__test__ = False
# A dict holding the base test class for each inherited test method.
_base_class_mapping: Dict[str, Type[unittest.TestCase]] = None
mysql_container: Optional[MySqlContainer] = None
def setUp(self) -> None:
self.temp_dir = tempfile.mkdtemp()
self.input_data, self.schema = self.create_input_data_and_schema()
self.client = self.get_client()
def tearDown(self) -> None:
MemoryOnlineStore.get_instance().reset()
shutil.rmtree(self.temp_dir, ignore_errors=True)
registry: Registry = cast(RegistryWithJsonCheck, self.client.registry).registry
if isinstance(registry, LocalRegistry):
registry.clear_features()
@abstractmethod
def get_client(self, extra_config: Optional[Dict] = None) -> FeathubClient:
"""
Returns a FeathubClient instance for test cases.
"""
pass
@staticmethod
def get_client_with_local_registry(
processor_config: Dict, extra_config: Optional[Dict] = None
) -> FeathubClient:
props = {
"processor": processor_config,
"online_store": {
"types": ["memory"],
"memory": {},
},
"registry": {
"type": "local",
"local": {
"namespace": "default",
},
},
"feature_service": {
"type": "local",
"local": {},
},
}
if extra_config is not None:
_merge_nested_dict(props, extra_config)
client = FeathubClient(props)
client.registry = RegistryWithJsonCheck(client.registry)
return client
def create_file_source(
self,
df: pd.DataFrame,
keys: Optional[List[str]] = None,
schema: Optional[Schema] = None,
timestamp_field: Optional[str] = "time",
timestamp_format: str = "%Y-%m-%d %H:%M:%S",
name: str = None,
data_format: str = "csv",
max_out_of_orderness: timedelta = timedelta(0),
) -> FileSystemSource:
path = tempfile.NamedTemporaryFile(dir=self.temp_dir, suffix=".csv").name
if schema is None:
schema = self._create_input_schema()
if data_format == DataFormat.CSV:
df.to_csv(path, index=False, header=False)
elif data_format == DataFormat.JSON:
df.to_json(path, orient="records", lines=True)
else:
raise FeathubException(f"Unsupported format: {data_format}.")
if name is None:
name = self.generate_random_name("source")
return FileSystemSource(
name=name,
path=path,
data_format=data_format,
schema=schema,
keys=keys,
timestamp_field=timestamp_field,
timestamp_format=timestamp_format,
max_out_of_orderness=max_out_of_orderness,
)
# TODO: only invoke the corresponding base class's setUpClass()
# method to reduce resource consumption.
@classmethod
def invoke_all_base_class_setupclass(cls):
for base_class in cls.__bases__:
if issubclass(base_class, unittest.TestCase):
base_class.setUpClass()
@classmethod
def invoke_all_base_class_teardownclass(cls):
for base_class in cls.__bases__:
if issubclass(base_class, unittest.TestCase):
base_class.tearDownClass()
def invoke_base_class_setup(self):
self._get_base_test_class().setUp(self)
def invoke_base_class_teardown(self):
self._get_base_test_class().tearDown(self)
def _get_base_test_class(self) -> Type[unittest.TestCase]:
if self._base_class_mapping is None:
self._base_class_mapping = dict()
for base_class in self.__class__.__bases__:
if not issubclass(base_class, unittest.TestCase):
continue
for func in dir(base_class):
if not (
callable(getattr(base_class, func))
and func.startswith(TestLoader.testMethodPrefix)
):
continue
if func in self._base_class_mapping:
raise FeathubException(
f"Duplicated test case name {func} detected in integration "
f"test base class {self._base_class_mapping[func]} and "
f"{base_class}."
)
self._base_class_mapping[func] = base_class
if self._testMethodName in self._base_class_mapping:
return self._base_class_mapping[self._testMethodName]
return FeathubITTestBase
@classmethod
def generate_random_name(cls, root_name: str) -> str:
random_name = f"{root_name}_{str(uuid.uuid4()).replace('-', '')}"
return random_name
@classmethod
def create_input_data_and_schema(cls):
input_data = pd.DataFrame(
[
["Alex", 100, 100, "2022-01-01 08:01:00"],
["Emma", 400, 250, "2022-01-01 08:02:00"],
["Alex", 300, 200, "2022-01-02 08:03:00"],
["Emma", 200, 250, "2022-01-02 08:04:00"],
["Jack", 500, 500, "2022-01-03 08:05:00"],
["Alex", 600, 800, "2022-01-03 08:06:00"],
],
columns=["name", "cost", "distance", "time"],
)
schema = cls._create_input_schema()
return input_data, schema
@classmethod
def create_input_data_and_schema_with_millis_time_span(cls):
input_data = pd.DataFrame(
[
["Alex", 100, 100, "2022-01-01 08:00:00.001"],
["Emma", 400, 250, "2022-01-01 08:00:00.002"],
["Alex", 300, 200, "2022-01-01 08:00:00.003"],
["Emma", 200, 250, "2022-01-01 08:00:00.004"],
["Jack", 500, 500, "2022-01-01 08:00:00.005"],
["Alex", 600, 800, "2022-01-01 08:00:00.006"],
],
columns=["name", "cost", "distance", "time"],
)
schema = cls._create_input_schema()
return input_data, schema
@classmethod
def _create_input_schema(cls):
return (
Schema.new_builder()
.column("name", types.String)
.column("cost", types.Int64)
.column("distance", types.Int64)
.column("time", types.String)
.build()
)
@staticmethod
def setup_mysql_container():
if FeathubITTestBase.mysql_container is None:
FeathubITTestBase.mysql_container = MySqlContainer(image="mysql:8.0")
FeathubITTestBase.mysql_container.start()
pass
@staticmethod
def teardown_mysql_container():
if FeathubITTestBase.mysql_container is not None:
FeathubITTestBase.mysql_container.stop()
FeathubITTestBase.mysql_container = None