File: test_BaseData.py

package info (click to toggle)
python-libpyvinyl 1.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,020 kB
  • sloc: python: 3,213; makefile: 11
file content (423 lines) | stat: -rw-r--r-- 15,268 bytes parent folder | download
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import pytest
import numpy as np
import h5py
from libpyvinyl.BaseData import BaseData, DataCollection
from libpyvinyl.BaseFormat import BaseFormat


class NumberData(BaseData):
    def __init__(
        self,
        key,
        data_dict=None,
        filename=None,
        file_format_class=None,
        file_format_kwargs=None,
    ):
        ### DataClass developer's job start
        expected_data = {}
        expected_data["number"] = None
        ### DataClass developer's job end

        super().__init__(
            key,
            expected_data,
            data_dict,
            filename,
            file_format_class,
            file_format_kwargs,
        )

    @classmethod
    def supported_formats(self):
        format_dict = {}
        ### DataClass developer's job start
        self._add_ioformat(format_dict, TXTFormat)
        self._add_ioformat(format_dict, H5Format)
        ### DataClass developer's job end
        return format_dict


class TXTFormat(BaseFormat):
    def __init__(self) -> None:
        super().__init__()

    @classmethod
    def format_register(self):
        key = "TXT"
        desciption = "TXT format for NumberData"
        file_extension = ".txt"
        read_kwargs = [""]
        write_kwargs = [""]
        return self._create_format_register(
            key, desciption, file_extension, read_kwargs, write_kwargs
        )

    @classmethod
    def read(cls, filename: str) -> dict:
        """Read the data from the file with the `filename` to a dictionary. The dictionary will
        be used by its corresponding data class."""
        number = float(np.loadtxt(filename))
        data_dict = {"number": number}
        return data_dict

    @classmethod
    def write(cls, object: NumberData, filename: str, key: str = None):
        """Save the data with the `filename`."""
        data_dict = object.get_data()
        arr = np.array([data_dict["number"]])
        np.savetxt(filename, arr, fmt="%.3f")
        if key is None:
            original_key = object.key
            key = original_key + "_to_TXTFormat"
            return object.from_file(filename, cls, key)
        else:
            return object.from_file(filename, cls, key)

    @staticmethod
    def direct_convert_formats():
        # Assume the format can be converted directly to the formats supported by these classes:
        # AFormat, BFormat
        # Redefine this `direct_convert_formats` for a concrete format class
        return [H5Format]

    @classmethod
    def convert(
        cls, obj: NumberData, output: str, output_format_class: str, key=None, **kwargs
    ):
        """Direct convert method, if the default converting would be too slow or not suitable for the output_format"""
        if output_format_class is H5Format:
            cls.convert_to_H5Format(obj.filename, output)
        else:
            raise TypeError(
                "Direct converting to format {} is not supported".format(
                    output_format_class
                )
            )
        # Set the key of the returned object
        if key is None:
            original_key = obj.key
            key = original_key + "_from_TXTFormat"
            return obj.from_file(output, output_format_class, key)
        else:
            return obj.from_file(output, output_format_class, key)

    @classmethod
    def convert_to_H5Format(cls, input: str, output: str):
        """The engine of convert method."""
        print("Directly converting TXTFormat to H5Format")
        number = float(np.loadtxt(input))
        with h5py.File(output, "w") as h5:
            h5["number"] = number


class H5Format(BaseFormat):
    def __init__(self) -> None:
        super().__init__()

    @classmethod
    def format_register(self):
        key = "H5"
        desciption = "H5 format for NumberData"
        file_extension = ".h5"
        read_kwargs = [""]
        write_kwargs = [""]
        return self._create_format_register(
            key, desciption, file_extension, read_kwargs, write_kwargs
        )

    @classmethod
    def read(cls, filename: str) -> dict:
        """Read the data from the file with the `filename` to a dictionary. The dictionary will
        be used by its corresponding data class."""
        with h5py.File(filename, "r") as h5:
            number = h5["number"][()]
        data_dict = {"number": number}
        return data_dict

    @classmethod
    def write(cls, object: NumberData, filename: str, key: str = None):
        """Save the data with the `filename`."""
        data_dict = object.get_data()
        number = data_dict["number"]
        with h5py.File(filename, "w") as h5:
            h5["number"] = number
        if key is None:
            original_key = object.key
            key = original_key + "_to_H5Format"
            return object.from_file(filename, cls, key)
        else:
            return object.from_file(filename, cls, key)

    @staticmethod
    def direct_convert_formats():
        # Assume the format can be converted directly to the formats supported by these classes:
        # AFormat, BFormat
        # Redefine this `direct_convert_formats` for a concrete format class
        return []


@pytest.fixture()
def txt_file(tmp_path_factory):
    fn_path = tmp_path_factory.mktemp("test_data") / "test.txt"
    txt_file = str(fn_path)
    with open(txt_file, "w") as f:
        f.write("4")
    return txt_file


# Data class section
def test_list_formats(capsys):
    """Test listing registered format classes"""
    NumberData.list_formats()
    captured = capsys.readouterr()
    assert "Key: TXT" in captured.out
    assert "Key: H5" in captured.out


def test_create_empty_data_instance():
    """Test creating an empty data instance"""
    with pytest.raises(TypeError):
        number_data = NumberData()
    test_data = NumberData(key="test_data")
    assert isinstance(test_data, NumberData)


def test_create_data_with_set_dict():
    """Test set dict after in an empty data instance"""
    test_data = NumberData(key="test_data")
    my_dict = {"number": 4}
    test_data.set_dict(my_dict)
    assert test_data.get_data()["number"] == 4


def test_create_data_with_set_file(txt_file):
    """Test set file after in an empty data instance"""
    test_data = NumberData(key="test_data")
    test_data.set_file(txt_file, TXTFormat)
    assert test_data.get_data()["number"] == 4


def test_create_data_with_set_file_inconsistensy(txt_file):
    """Test set dict and file for one data object: expecting an error"""
    test_data = NumberData(key="test_data")
    my_dict = {"number": 4}
    test_data.set_dict(my_dict)
    with pytest.raises(RuntimeError):
        test_data.set_file(txt_file, TXTFormat)


def test_create_data_with_set_file_wrong_param(txt_file):
    """Test set file after in an empty data instance with wrong `format_class` param"""
    test_data = NumberData(key="test_data")
    with pytest.raises(TypeError):
        test_data.set_file(txt_file, "txt")


def test_create_data_with_set_file_wrong_format(txt_file):
    """Test set file after in an empty data instance with wrong `format_class`"""
    test_data = NumberData(key="test_data")
    test_data.set_file(txt_file, H5Format)
    with pytest.raises(OSError):
        test_data.get_data()


def test_create_data_with_file():
    """Test set dict after in  an empty data instance"""
    test_data = NumberData(key="test_data")
    assert isinstance(test_data, NumberData)
    my_dict = {"number": 4}
    test_data.set_dict(my_dict)
    assert test_data.get_data()["number"] == 4


def test_create_data_from_dict():
    """Test creating a data instance from a dict"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")


def test_check_key_from_dict():
    """Test checking expected data key from dict"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    test_data.get_data()
    my_dict = {"numberr": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    with pytest.raises(KeyError):
        test_data.get_data()


def test_create_data_from_file_wrong_param(txt_file):
    """Test creating a data instance from a file in a wrong file format type"""
    with pytest.raises(TypeError):
        test_data = NumberData.from_file(txt_file, "txt", "test_data")


def test_create_data_from_TXTFormat(txt_file):
    """Test creating a data instance from a file in TXTFormat"""
    test_data = NumberData.from_file(txt_file, TXTFormat, "test_data")
    assert test_data.get_data()["number"] == 4


def test_create_data_from_wrong_format(txt_file):
    """Test creating a data instance from a file in TXTFormat"""
    test_data = NumberData.from_file(txt_file, H5Format, "test_data")
    with pytest.raises(OSError):
        test_data.get_data()


def test_duplicate_data_TXTFormat(txt_file, tmpdir, capsys):
    """Test creating a data instance from a file in TXTFormat"""
    test_data = NumberData.from_file(txt_file, TXTFormat, "test_data")
    test_data.write(str(tmpdir / "new_data.txt"), TXTFormat)
    captured = capsys.readouterr()
    assert "data already existed" in captured.out


def test_save_dict_data_in_TXTFormat(tmpdir):
    """Test saving a dict data in TXTFormat"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    fn = str(tmpdir / "test.txt")
    test_data.write(fn, TXTFormat)
    read_data = NumberData.from_file(fn, TXTFormat, "read_data")
    assert read_data.get_data()["number"] == 4


def test_save_dict_data_in_TXTFormat_return_data_object(tmpdir):
    """Test saving a dict data in TXTFormat returning data object with default key"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    fn = str(tmpdir / "test.txt")
    return_data = test_data.write(fn, TXTFormat)
    assert return_data.get_data()["number"] == 4
    assert return_data.key == "test_data_to_TXTFormat"


def test_save_dict_data_in_TXTFormat_return_data_object_key(tmpdir):
    """Test saving a dict data in TXTFormat returning data object with custom key"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    print(test_data)
    # assert False
    fn = str(tmpdir / "test.txt")
    return_data = test_data.write(fn, TXTFormat, "custom")
    assert return_data.get_data()["number"] == 4
    assert return_data.key == "custom"


def test_save_file_data_in_another_format_direct(txt_file, tmpdir, capsys):
    """Test directly converting a TXTFormat data to H5Format"""
    test_data = NumberData.from_file(txt_file, TXTFormat, "test_data")
    # print(test_data)
    fn = str(tmpdir / "test.h5")
    return_data = test_data.write(fn, H5Format)
    captured = capsys.readouterr()
    assert "Directly converting TXTFormat to H5Format" in captured.out
    assert return_data.get_data()["number"] == 4
    assert return_data.key == "test_data_from_TXTFormat"
    return_data = test_data.write(fn, H5Format, "txt2h5")
    assert return_data.key == "txt2h5"
    # print(return_data)
    # assert False


def test_save_file_data_in_another_format_indirect(tmpdir):
    """Test directly converting a TXTFormat data to H5Format"""
    my_dict = {"number": 4}
    test_data = NumberData.from_dict(my_dict, "test_data")
    fn = str(tmpdir / "test.h5")
    h5_data = test_data.write(fn, H5Format, "test_data")
    fn = str(tmpdir / "test.txt")
    return_data = h5_data.write(fn, TXTFormat)
    print(return_data)
    assert return_data.get_data()["number"] == 4
    assert return_data.key == "test_data_to_TXTFormat"
    return_data = test_data.write(fn, H5Format, "txt2h5")
    assert return_data.key == "txt2h5"
    # print(return_data)
    # assert False


# Data collection section
def test_DataCollection_instance():
    """Test creating a DataCollection instance"""
    collection = DataCollection()
    assert isinstance(collection, DataCollection)


def test_DataCollection_one_data(txt_file):
    """Test a DataCollection instance with one dataset"""
    test_data = NumberData.from_file(txt_file, TXTFormat, "test_data")
    collection = DataCollection(test_data)
    data_in_collection = collection["test_data"]
    assert collection.get_data() == data_in_collection.get_data()


def test_DataCollection_one_data_write(txt_file, tmpdir):
    """Test a DataCollection instance with one dataset"""
    test_data = NumberData.from_file(txt_file, TXTFormat, "test_data")
    collection = DataCollection(test_data)
    fn = str(tmpdir / "data.h5")
    written_data = collection.write(fn, H5Format)
    assert written_data.mapping_type == H5Format
    assert written_data.get_data()["number"] == 4


def test_DataCollection_two_data(txt_file):
    """Test creating a DataCollection instance with two datasets"""
    my_dict = {"number": 5}
    test_data_txt = NumberData.from_file(txt_file, TXTFormat, "test_txt")
    test_data_dict = NumberData.from_dict(my_dict, "test_dict")
    collection = DataCollection(test_data_txt, test_data_dict)
    assert collection["test_dict"].get_data()["number"] == 5
    assert collection["test_txt"].get_data()["number"] == 4
    value_collection = collection.get_data()
    assert value_collection["test_dict"]["number"] == 5
    assert value_collection["test_txt"]["number"] == 4


def test_DataCollection_two_data_write(txt_file, tmpdir):
    """Test writing a DataCollection instance with two datasets"""
    my_dict = {"number": 5}
    test_data_txt = NumberData.from_file(txt_file, TXTFormat, "test_txt")
    test_data_dict = NumberData.from_dict(my_dict, "test_dict")
    collection = DataCollection(test_data_txt, test_data_dict)
    fn_txt = str(tmpdir / "data_new.txt")
    fn_h5 = str(tmpdir / "data_new.h5")
    filenames = {"test_txt": fn_h5, "test_dict": fn_txt}
    format_classes = {"test_txt": H5Format, "test_dict": TXTFormat}
    keys = {"test_txt": None, "test_dict": None}
    written_collection = collection.write(filenames, format_classes, keys)
    # Create a new data collection from the collection dict
    new_collection = DataCollection(*written_collection.values())
    assert new_collection["test_dict_to_TXTFormat"].get_data()["number"] == 5


def test_DataCollection_add_data(txt_file):
    """Test adding data to a DataCollection instance"""
    my_dict = {"number": 5}
    test_data_dict = NumberData.from_dict(my_dict, "test_dict")
    test_data_txt = NumberData.from_file(txt_file, TXTFormat, "test_txt")
    collection = DataCollection()
    collection.add_data(test_data_dict, test_data_txt)
    print(collection)


def test_DataCollection_add_wrong_data_type():
    """Test adding data in wrong type to a DataCollection instance"""
    collection = DataCollection()
    with pytest.raises(AssertionError):
        collection.add_data(0)


def test_DataCollection_to_list(txt_file):
    """Test returning a DataCollection as a list"""
    my_dict = {"number": 5}
    test_data_dict = NumberData.from_dict(my_dict, "test_dict")
    test_data_txt = NumberData.from_file(txt_file, TXTFormat, "test_txt")
    collection = DataCollection(test_data_dict, test_data_txt)
    my_list = collection.to_list()
    assert my_list[0].get_data()["number"] == 5
    assert my_list[1].get_data()["number"] == 4