aboutsummaryrefslogtreecommitdiff
path: root/tests/incite/test_collection_base.py
blob: 497e5ab298eb5d40b2b6eb5c9edd0a0f44092c4b (plain)
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
from datetime import datetime, timezone, timedelta
from os.path import exists as pexists, join as pjoin
from pathlib import Path
from uuid import uuid4

import numpy as np
import pandas as pd
import pytest
from _pytest._code.code import ExceptionInfo

from generalresearch.incite.base import CollectionBase
from test_utils.incite.conftest import mnt_filepath

AGO_15min = (datetime.now(tz=timezone.utc) - timedelta(minutes=15)).replace(
    microsecond=0
)
AGO_1HR = (datetime.now(tz=timezone.utc) - timedelta(hours=1)).replace(microsecond=0)
AGO_2HR = (datetime.now(tz=timezone.utc) - timedelta(hours=2)).replace(microsecond=0)


class TestCollectionBase:
    def test_init(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.df.empty is True

    def test_init_df(self, mnt_filepath):
        # Only an empty pd.DataFrame can ever be provided
        instance = CollectionBase(
            df=pd.DataFrame({}), archive_path=mnt_filepath.data_src
        )
        assert isinstance(instance.df, pd.DataFrame)

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(
                df=pd.DataFrame(columns=[0, 1, 2]), archive_path=mnt_filepath.data_src
            )
        assert "Do not provide a pd.DataFrame" in str(cm.value)

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(
                df=pd.DataFrame(np.random.randint(100, size=(1000, 1)), columns=["A"]),
                archive_path=mnt_filepath.data_src,
            )
        assert "Do not provide a pd.DataFrame" in str(cm.value)

    def test_init_start(self, mnt_filepath):
        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(
                start=datetime.now(tz=timezone.utc) - timedelta(days=10),
                archive_path=mnt_filepath.data_src,
            )
        assert "Collection.start must not have microseconds" in str(cm.value)

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            tz = timezone(timedelta(hours=-5), "EST")

            CollectionBase(
                start=datetime(year=2000, month=1, day=1, tzinfo=tz),
                archive_path=mnt_filepath.data_src,
            )
        assert "Timezone is not UTC" in str(cm.value)

        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.start == datetime(
            year=2018, month=1, day=1, tzinfo=timezone.utc
        )

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(
                start=AGO_2HR, offset="3h", archive_path=mnt_filepath.data_src
            )
        assert "Offset must be equal to, or smaller the start timestamp" in str(
            cm.value
        )

    def test_init_archive_path(self, mnt_filepath):
        """DirectoryPath is apparently smart enough to confirm that the
        directory path exists.
        """

        # (1) Basic, confirm an existing path works
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.archive_path == mnt_filepath.data_src

        # (2) It can't point to a file
        file_path = Path(pjoin(mnt_filepath.data_src, f"{uuid4().hex}.zip"))
        assert not pexists(file_path)
        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(archive_path=file_path)
        assert "Path does not point to a directory" in str(cm.value)

        # (3) It doesn't create the directory if it doesn't exist
        new_path = Path(pjoin(mnt_filepath.data_src, f"{uuid4().hex}/"))
        assert not pexists(new_path)
        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(archive_path=new_path)
        assert "Path does not point to a directory" in str(cm.value)

    def test_init_offset(self, mnt_filepath):
        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(offset="1:X", archive_path=mnt_filepath.data_src)
        assert "Invalid offset alias provided. Please review:" in str(cm.value)

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(offset=f"59sec", archive_path=mnt_filepath.data_src)
        assert "Must be equal to, or longer than 1 min" in str(cm.value)

        with pytest.raises(expected_exception=ValueError) as cm:
            cm: ExceptionInfo
            CollectionBase(offset=f"{365 * 101}d", archive_path=mnt_filepath.data_src)
        assert "String should have at most 5 characters" in str(cm.value)


class TestCollectionBaseProperties:

    def test_items(self, mnt_filepath):
        with pytest.raises(expected_exception=NotImplementedError) as cm:
            cm: ExceptionInfo
            instance = CollectionBase(archive_path=mnt_filepath.data_src)
            x = instance.items
        assert "Must override" in str(cm.value)

    def test_interval_range(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        # Private method requires the end parameter
        with pytest.raises(expected_exception=AssertionError) as cm:
            cm: ExceptionInfo
            instance._interval_range(end=None)
        assert "an end value must be provided" in str(cm.value)

        # End param must be same as started (which forces utc)
        tz = timezone(timedelta(hours=-5), "EST")
        with pytest.raises(expected_exception=AssertionError) as cm:
            cm: ExceptionInfo
            instance._interval_range(end=datetime.now(tz=tz))
        assert "Timezones must match" in str(cm.value)

        res = instance._interval_range(end=datetime.now(tz=timezone.utc))
        assert isinstance(res, pd.IntervalIndex)
        assert res.closed_left
        assert res.is_non_overlapping_monotonic
        assert res.is_monotonic_increasing
        assert res.is_unique

    def test_interval_range2(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert isinstance(instance.interval_range, list)

        # 1 hrs ago has 2 x 30min + the future 30min
        OFFSET = "30min"
        instance = CollectionBase(
            start=AGO_1HR, offset=OFFSET, archive_path=mnt_filepath.data_src
        )
        assert len(instance.interval_range) == 3
        assert instance.interval_range[0][0] == AGO_1HR

        # 1 hrs ago has 1 x 60min + the future 60min
        OFFSET = "60min"
        instance = CollectionBase(
            start=AGO_1HR, offset=OFFSET, archive_path=mnt_filepath.data_src
        )
        assert len(instance.interval_range) == 2

    def test_progress(self, mnt_filepath):
        with pytest.raises(expected_exception=NotImplementedError) as cm:
            cm: ExceptionInfo
            instance = CollectionBase(
                start=AGO_15min, offset="3min", archive_path=mnt_filepath.data_src
            )
            x = instance.progress
        assert "Must override" in str(cm.value)

    def test_progress2(self, mnt_filepath):
        instance = CollectionBase(
            start=AGO_2HR,
            offset="15min",
            archive_path=mnt_filepath.data_src,
        )
        assert instance.df.empty

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            df = instance.progress
        assert "Must override" in str(cm.value)

    def test_items2(self, mnt_filepath):
        """There can't be a test for this because the Items need a path whic
        isn't possible in the generic form
        """
        instance = CollectionBase(
            start=AGO_1HR, offset="5min", archive_path=mnt_filepath.data_src
        )

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            cm: ExceptionInfo
            items = instance.items
        assert "Must override" in str(cm.value)

        # item = items[-3]
        # ddf = instance.ddf(items=[item], include_partial=True, force_rr_latest=False)
        # df = item.validate_ddf(ddf=ddf)
        # assert isinstance(df, pd.DataFrame)
        # assert len(df.columns) == 16
        # assert str(df.product_id.dtype) == "object"
        # assert str(ddf.product_id.dtype) == "string"

    def test_items3(self, mnt_filepath):
        instance = CollectionBase(
            start=AGO_2HR,
            offset="15min",
            archive_path=mnt_filepath.data_src,
        )
        with pytest.raises(expected_exception=NotImplementedError) as cm:
            item = instance.items[0]
        assert "Must override" in str(cm.value)


class TestCollectionBaseMethodsCleanup:
    def test_fetch_force_rr_latest(self, mnt_filepath):
        coll = CollectionBase(archive_path=mnt_filepath.data_src)

        with pytest.raises(expected_exception=Exception) as cm:
            cm: ExceptionInfo
            coll.fetch_force_rr_latest(sources=[])
        assert "Must override" in str(cm.value)

    def test_fetch_all_paths(self, mnt_filepath):
        coll = CollectionBase(archive_path=mnt_filepath.data_src)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            cm: ExceptionInfo
            coll.fetch_all_paths(
                items=None, force_rr_latest=False, include_partial=False
            )
        assert "Must override" in str(cm.value)


class TestCollectionBaseMethodsCleanup:
    @pytest.mark.skip
    def test_cleanup_partials(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.cleanup_partials() is None  # it doesn't return anything

    def test_clear_tmp_archives(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.clear_tmp_archives() is None  # it doesn't return anything

    @pytest.mark.skip
    def test_clear_corrupt_archives(self, mnt_filepath):
        """TODO: expand this so it actually has corrupt archives that we
        check to see if they're removed
        """
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.clear_corrupt_archives() is None  # it doesn't return anything

    @pytest.mark.skip
    def test_rebuild_symlinks(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        assert instance.rebuild_symlinks() is None


class TestCollectionBaseMethodsSourceTiming:

    def test_get_item(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)
        i = pd.Interval(left=1, right=2, closed="left")

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_item(interval=i)
        assert "Must override" in str(cm.value)

    def test_get_item_start(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)

        dt = datetime.now(tz=timezone.utc)
        start = pd.Timestamp(dt)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_item_start(start=start)
        assert "Must override" in str(cm.value)

    def test_get_items(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)

        dt = datetime.now(tz=timezone.utc)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_items(since=dt)
        assert "Must override" in str(cm.value)

    def test_get_items_from_year(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_items_from_year(year=2020)
        assert "Must override" in str(cm.value)

    def test_get_items_last90(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_items_last90()
        assert "Must override" in str(cm.value)

    def test_get_items_last365(self, mnt_filepath):
        instance = CollectionBase(archive_path=mnt_filepath.data_src)

        with pytest.raises(expected_exception=NotImplementedError) as cm:
            instance.get_items_last365()
        assert "Must override" in str(cm.value)