test_tsio.py 37.1 KB
Newer Older
1
from datetime import datetime, timedelta
2
3
from pathlib import Path
import pytz
4

5
from dateutil import parser
6
import pytest
7
8
import numpy as np
import pandas as pd
9

10
from tshistory.snapshot import Snapshot
11
from tshistory.util import rename_series
12
13
14
15
16
17
from tshistory.testutil import (
    assert_df,
    assert_group_equals,
    genserie,
    tempattr
)
18

19
DATADIR = Path(__file__).parent / 'data'
20

Aurélien Campéas's avatar
Aurélien Campéas committed
21

22
23
24
25
def utcdt(*dt):
    return pd.Timestamp(datetime(*dt), tz='UTC')


26
def test_tstamp_roundtrip(engine, tsh):
27
28
    ts = genserie(datetime(2017, 10, 28, 23),
                  'H', 4, tz='UTC')
29
30
31
32
33
34
35
36
37
38
    ts.index = ts.index.tz_convert('Europe/Paris')

    assert_df("""
2017-10-29 01:00:00+02:00    0
2017-10-29 02:00:00+02:00    1
2017-10-29 02:00:00+01:00    2
2017-10-29 03:00:00+01:00    3
Freq: H
    """, ts)

39
40
    tsh.insert(engine, ts, 'tztest', 'Babar')
    back = tsh.get(engine, 'tztest')
41
42
43

    # though un localized we understand it's been normalized to utc
    assert_df("""
44
45
46
47
2017-10-28 23:00:00+00:00    0.0
2017-10-29 00:00:00+00:00    1.0
2017-10-29 01:00:00+00:00    2.0
2017-10-29 02:00:00+00:00    3.0
48
49
50
""", back)

    assert (ts.index == back.index).all()
51
    assert str(back.index.dtype) == 'datetime64[ns, UTC]'
52
53


54
def test_differential(engine, tsh):
55
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10)
56
    tsh.insert(engine, ts_begin, 'ts_test', 'test')
57

58
59
    assert tsh.exists(engine, 'ts_test')
    assert not tsh.exists(engine, 'this_does_not_exist')
60

61
    assert_df("""
62
63
64
65
66
67
68
69
70
71
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    3.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
72
""", tsh.get(engine, 'ts_test'))
73
74

    # we should detect the emission of a message
75
    tsh.insert(engine, ts_begin, 'ts_test', 'babar')
76

77
    assert_df("""
78
79
80
81
82
83
84
85
86
87
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    3.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
88
""", tsh.get(engine, 'ts_test'))
89
90
91
92

    ts_slight_variation = ts_begin.copy()
    ts_slight_variation.iloc[3] = 0
    ts_slight_variation.iloc[6] = 0
93
    tsh.insert(engine, ts_slight_variation, 'ts_test', 'celeste')
94

95
    assert_df("""
96
97
98
99
100
101
102
103
104
105
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    0.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    0.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
106
""", tsh.get(engine, 'ts_test'))
107

108
    ts_longer = genserie(datetime(2010, 1, 3), 'D', 15)
109
110
111
112
    ts_longer.iloc[1] = 2.48
    ts_longer.iloc[3] = 3.14
    ts_longer.iloc[5] = ts_begin.iloc[7]

113
    tsh.insert(engine, ts_longer, 'ts_test', 'test')
114

115
    assert_df("""
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
2010-01-01     0.00
2010-01-02     1.00
2010-01-03     0.00
2010-01-04     2.48
2010-01-05     2.00
2010-01-06     3.14
2010-01-07     4.00
2010-01-08     7.00
2010-01-09     6.00
2010-01-10     7.00
2010-01-11     8.00
2010-01-12     9.00
2010-01-13    10.00
2010-01-14    11.00
2010-01-15    12.00
2010-01-16    13.00
2010-01-17    14.00
133
""", tsh.get(engine, 'ts_test'))
134
135

    # start testing manual overrides
136
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5, initval=[2])
137
    ts_begin.loc['2010-01-04'] = -1
138
    tsh.insert(engine, ts_begin, 'ts_mixte', 'test')
139
140

    # -1 represents bogus upstream data
141
    assert_df("""
142
143
144
145
146
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
147
""", tsh.get(engine, 'ts_mixte'))
148
149

    # refresh all the period + 1 extra data point
150
    ts_more = genserie(datetime(2010, 1, 2), 'D', 5, [2])
151
    ts_more.loc['2010-01-04'] = -1
152
    tsh.insert(engine, ts_more, 'ts_mixte', 'test')
153

154
    assert_df("""
155
156
157
158
159
160
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
161
""", tsh.get(engine, 'ts_mixte'))
162
163

    # just append an extra data point
164
165
    # with no intersection with the previous ts
    ts_one_more = genserie(datetime(2010, 1, 7), 'D', 1, [3])
166
    tsh.insert(engine, ts_one_more, 'ts_mixte', 'test')
167

168
    assert_df("""
169
170
171
172
173
174
175
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    3.0
176
""", tsh.get(engine, 'ts_mixte'))
177

178
    with engine.connect() as cn:
179
        cn.execute('set search_path to "{0}.timeserie", {0}, public'.format(tsh.namespace))
180
181
        allts = pd.read_sql("select seriename, table_name from registry "
                            "where seriename in ('ts_test', 'ts_mixte')",
182
                            cn)
183

184
        assert_df("""
185
186
187
seriename table_name
0   ts_test    ts_test
1  ts_mixte   ts_mixte
188
""".format(tsh.namespace), allts)
189

190
        assert_df("""
191
192
193
194
195
196
197
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    3.0
198
""", tsh.get(cn, 'ts_mixte',
199
             revision_date=datetime.now()))
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
def test_serie_metadata(engine, tsh):
    serie = genserie(datetime(2010, 1, 1), 'D', 1, initval=[1])
    tsh.insert(engine, serie, 'ts-metadata', 'babar')

    initialmeta = tsh.metadata(engine, 'ts-metadata')
    assert initialmeta == {
        'tzaware': False,
        'index_type': 'datetime64[ns]',
        'value_type': 'float64',
        'index_names': []
    }

    tsh.update_metadata(engine, 'ts-metadata',
                        {'topic': 'banana spot price'}
    )
    assert tsh.metadata(engine, 'ts-metadata')['topic'] == 'banana spot price'

    with pytest.raises(AssertionError):
        tsh.update_metadata(engine, 'ts-metadata', {'tzaware': True})

    tsh.update_metadata(engine, 'ts-metadata', {'tzaware': True}, internal=True)
    assert tsh.metadata(engine, 'ts-metadata') == {
        'tzaware': True,
        'index_type': 'datetime64[ns]',
        'value_type': 'float64',
        'index_names': [],
        'topic': 'banana spot price'
    }
    # unbreak the serie for the second test pass :o
    tsh.update_metadata(engine, 'ts-metadata', initialmeta, internal=True)


234
235
def test_changeset_metadata(engine, tsh):
    serie = genserie(datetime(2010, 1, 1), 'D', 1, initval=[1])
236
    tsh.insert(engine, serie, 'ts-cs-metadata', 'babar',
237
238
               {'foo': 'A', 'bar': 42})

239
    log = tsh.log(engine, names=['ts-cs-metadata'])
240
241
242
243
    meta = tsh.changeset_metadata(engine, log[0]['rev'])
    assert meta == {'foo': 'A', 'bar': 42}


244
def test_bad_import(engine, tsh):
245
    # the data were parsed as date by pd.read_json()
Aurélien Campéas's avatar
Aurélien Campéas committed
246
    df_result = pd.read_csv(str(DATADIR / 'test_data.csv'))
247
248
249
    df_result['Gas Day'] = df_result['Gas Day'].apply(parser.parse, dayfirst=True, yearfirst=False)
    df_result.set_index('Gas Day', inplace=True)
    ts = df_result['SC']
250

251
252
    tsh.insert(engine, ts, 'SND_SC', 'test')
    result = tsh.get(engine, 'SND_SC')
253
    assert result.dtype == 'float64'
254
255
256

    # insertion of empty ts
    ts = pd.Series(name='truc', dtype='object')
257
258
    tsh.insert(engine, ts, 'empty_ts', 'test')
    assert tsh.get(engine, 'empty_ts') is None
259
260
261

    # nan in ts
    # all na
262
    ts = genserie(datetime(2010, 1, 10), 'D', 10, [np.nan], name='truc')
263
    tsh.insert(engine, ts, 'test_nan', 'test')
264
265
    assert len(tsh.get(engine, 'test_nan')) == 0
    assert len(tsh.get(engine, 'test_nan', _keep_nans=True)) == 10
266
267
268
269
270

    # mixe na
    ts = pd.Series([np.nan] * 5 + [3] * 5,
                   index=pd.date_range(start=datetime(2010, 1, 10),
                                       freq='D', periods=10), name='truc')
271
272
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
273

274
275
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
276
    assert_df("""
277
278
279
280
281
2010-01-15    3.0
2010-01-16    3.0
2010-01-17    3.0
2010-01-18    3.0
2010-01-19    3.0
282
""", result)
283
284

    # get_ts with name not in database
285
    assert tsh.get(engine, 'inexisting_name', 'test') is None
286
287


288
def test_revision_date(engine, tsh):
289
    # we prepare a good joke for the end of the test
290
291
    # ival = Snapshot._interval
    # Snapshot._interval = 3
292
293
294

    for i in range(1, 5):
        with engine.connect() as cn:
295
296
            tsh.insert(cn, genserie(datetime(2017, 1, i), 'D', 3, [i]), 'revdate',
                       'test', _insertion_date=utcdt(2016, 1, i))
297
298

    # end of prologue, now some real meat
299
    idate0 = pd.Timestamp('2015-1-1 00:00:00', tz='UTC')
300
301
302
303
    ts = genserie(datetime(2010, 1, 4), 'D', 4, [0], name='truc')
    tsh.insert(engine, ts, 'ts_through_time',
               'test', _insertion_date=idate0)
    assert idate0 == tsh.latest_insertion_date(engine, 'ts_through_time')
304

305
    idate1 = pd.Timestamp('2015-1-1 15:45:23', tz='UTC')
306
307
308
309
    ts = genserie(datetime(2010, 1, 4), 'D', 4, [1], name='truc')
    tsh.insert(engine, ts, 'ts_through_time',
               'test', _insertion_date=idate1)
    assert idate1 == tsh.latest_insertion_date(engine, 'ts_through_time')
310

311
    idate2 = pd.Timestamp('2015-1-2 15:43:23', tz='UTC')
312
313
314
315
    ts = genserie(datetime(2010, 1, 4), 'D', 4, [2], name='truc')
    tsh.insert(engine, ts, 'ts_through_time',
               'test', _insertion_date=idate2)
    assert idate2 == tsh.latest_insertion_date(engine, 'ts_through_time')
316

317
    idate3 = pd.Timestamp('2015-1-3', tz='UTC')
318
319
320
321
    ts = genserie(datetime(2010, 1, 4), 'D', 4, [3], name='truc')
    tsh.insert(engine, ts, 'ts_through_time',
               'test', _insertion_date=idate3)
    assert idate3 == tsh.latest_insertion_date(engine, 'ts_through_time')
322

323
    ts = tsh.get(engine, 'ts_through_time')
324

325
    assert_df("""
326
327
328
329
2010-01-04    3.0
2010-01-05    3.0
2010-01-06    3.0
2010-01-07    3.0
330
""", ts)
331

332
    ts = tsh.get(engine, 'ts_through_time',
Aurélien Campéas's avatar
Aurélien Campéas committed
333
                 revision_date=datetime(2015, 1, 2, 18, 43, 23))
334

335
    assert_df("""
336
337
338
339
2010-01-04    2.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    2.0
340
""", ts)
341

342
    ts = tsh.get(engine, 'ts_through_time',
343
                 revision_date=datetime(2015, 1, 1, 18, 43, 23))
344

345
    assert_df("""
346
347
348
349
2010-01-04    1.0
2010-01-05    1.0
2010-01-06    1.0
2010-01-07    1.0
350
""", ts)
351

352
    ts = tsh.get(engine, 'ts_through_time',
353
                 revision_date=datetime(2014, 1, 1, 18, 43, 23))
354
355
356

    assert ts is None

357
358
359
360
361
362
363
364
365
366
    # epilogue: back to the revdate issue
    assert_df("""
2017-01-01    1.0
2017-01-02    2.0
2017-01-03    3.0
2017-01-04    4.0
2017-01-05    4.0
2017-01-06    4.0
""", tsh.get(engine, 'revdate'))

367
    oldstate = tsh.get(engine, 'revdate', revision_date=datetime(2016, 1, 2))
368
369
370
    assert_df("""
2017-01-01    1.0
2017-01-02    2.0
371
372
373
2017-01-03    2.0
2017-01-04    2.0
""", oldstate)
374

375

376
def test_deletion(engine, tsh):
377
378
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 11)
    ts_begin.iloc[-1] = np.nan
379
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
380

381
    _, ts = Snapshot(engine, tsh, 'ts_del').find()
382
    assert ts.iloc[-2] == 9.0
383

384
    ts_begin.iloc[0] = np.nan
385
    ts_begin.iloc[3] = np.nan
386

387
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
388

389
    assert_df("""
390
391
392
393
394
395
396
2010-01-02    1.0
2010-01-03    2.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
397
2010-01-10    9.0
398
""", tsh.get(engine, 'ts_del'))
399

400
    ts2 = tsh.get(engine, 'ts_del',
401
402
                 # force snapshot reconstruction feature
                 revision_date=datetime(2038, 1, 1))
403
    assert (tsh.get(engine, 'ts_del') == ts2).all()
404

405
406
407
    ts_begin.iloc[0] = 42
    ts_begin.iloc[3] = 23

408
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
409

410
    assert_df("""
411
412
413
414
415
416
417
418
419
2010-01-01    42.0
2010-01-02     1.0
2010-01-03     2.0
2010-01-04    23.0
2010-01-05     4.0
2010-01-06     5.0
2010-01-07     6.0
2010-01-08     7.0
2010-01-09     8.0
420
2010-01-10     9.0
421
""", tsh.get(engine, 'ts_del'))
422
423
424

    # now with string!

425
    ts_string = genserie(datetime(2010, 1, 1), 'D', 10, ['machin'])
426
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
427
428
429
430

    ts_string[4] = None
    ts_string[5] = None

431
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
432
    assert_df("""
433
434
435
436
437
438
439
440
2010-01-01    machin
2010-01-02    machin
2010-01-03    machin
2010-01-04    machin
2010-01-07    machin
2010-01-08    machin
2010-01-09    machin
2010-01-10    machin
441
""", tsh.get(engine, 'ts_string_del'))
442
443
444
445

    ts_string[4] = 'truc'
    ts_string[6] = 'truc'

446
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
447
    assert_df("""
448
449
450
451
452
453
454
455
2010-01-01    machin
2010-01-02    machin
2010-01-03    machin
2010-01-04    machin
2010-01-05      truc
2010-01-07      truc
2010-01-08    machin
2010-01-09    machin
456
2010-01-10    machin
457
""", tsh.get(engine, 'ts_string_del'))
458

459
    ts_string[ts_string.index] = np.nan
460
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
461

462
    erased = tsh.get(engine, 'ts_string_del')
463
464
    assert len(erased) == 0

465
466
    # first insertion with only nan

467
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10, [np.nan])
468
    tsh.insert(engine, ts_begin, 'ts_null', 'test')
469

470
    assert len(tsh.get(engine, 'ts_null')) == 0
471

472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    # exhibit issue with nans handling
    ts_repushed = genserie(datetime(2010, 1, 1), 'D', 11)
    ts_repushed[0:3] = np.nan

    assert_df("""
2010-01-01     NaN
2010-01-02     NaN
2010-01-03     NaN
2010-01-04     3.0
2010-01-05     4.0
2010-01-06     5.0
2010-01-07     6.0
2010-01-08     7.0
2010-01-09     8.0
2010-01-10     9.0
2010-01-11    10.0
Freq: D
""", ts_repushed)

491
492
    tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
    diff = tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
493
494
    assert diff is None

495
    # there is no difference
496
    assert 0 == len(tsh.diff(ts_repushed, ts_repushed))
497
498
499
500
501

    ts_add = genserie(datetime(2010, 1, 1), 'D', 15)
    ts_add.iloc[0] = np.nan
    ts_add.iloc[13:] = np.nan
    ts_add.iloc[8] = np.nan
502
    diff = tsh.diff(ts_repushed, ts_add)
503
504
505
506
507
508

    assert_df("""
2010-01-02     1.0
2010-01-03     2.0
2010-01-09     NaN
2010-01-12    11.0
509
2010-01-13    12.0""", diff.sort_index())
510
511
512
513
    # value on nan => value
    # nan on value => nan
    # nan on nan => Nothing
    # nan on nothing=> Nothing
514

Aurélien Campéas's avatar
Aurélien Campéas committed
515
    # full erasing
516
517
    # numeric
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4)
518
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
519

Aurélien Campéas's avatar
Aurélien Campéas committed
520
    ts_begin.iloc[:] = np.nan
521
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
522
523

    ts_end = genserie(datetime(2010, 1, 1), 'D', 4)
524
    tsh.insert(engine, ts_end, 'ts_full_del', 'test')
525
526
527
528

    # string

    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4, ['text'])
529
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
530
531

    ts_begin.iloc[:] = np.nan
532
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
533
534

    ts_end = genserie(datetime(2010, 1, 1), 'D', 4, ['text'])
535
    tsh.insert(engine, ts_end, 'ts_full_del_str', 'test')
536

Aurélien Campéas's avatar
Aurélien Campéas committed
537

538
def test_get_history(engine, tsh):
539
540
    for numserie in (1, 2, 3):
        with engine.connect() as cn:
541
542
543
            tsh.insert(cn, genserie(datetime(2017, 1, 1), 'D', numserie), 'smallserie',
                       'aurelien.campeas@pythonian.fr',
                       _insertion_date=utcdt(2017, 2, numserie))
544
545
546
547
548
549
550
551
552
553
554

    ts = tsh.get(engine, 'smallserie')
    assert_df("""
2017-01-01    0.0
2017-01-02    1.0
2017-01-03    2.0
""", ts)

    logs = tsh.log(engine, names=['smallserie'])
    assert [
        {'author': 'aurelien.campeas@pythonian.fr',
555
         'meta': {},
556
         'date': pd.Timestamp('2017-02-01 00:00:00+0000', tz='UTC'),
557
558
559
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
560
         'meta': {},
561
         'date': pd.Timestamp('2017-02-02 00:00:00+0000', tz='UTC'),
562
563
564
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
565
         'meta': {},
566
         'date': pd.Timestamp('2017-02-03 00:00:00+0000', tz='UTC'),
567
568
569
570
571
         'names': ['smallserie']
        }
    ] == [{k: v for k, v in log.items() if k != 'rev'}
          for log in logs]
    histts = tsh.get_history(engine, 'smallserie')
572
    assert histts.name == 'smallserie'
573
574

    assert_df("""
575
576
577
578
579
580
581
insertion_date             value_date
2017-02-01 00:00:00+00:00  2017-01-01    0.0
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
2017-02-03 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
                           2017-01-03    2.0
582
583
""", histts)

584
    for idate in histts.index.get_level_values('insertion_date').unique():
585
        with engine.connect() as cn:
586
            idate = idate.replace(tzinfo=pytz.timezone('UTC'))
587
588
            tsh.insert(cn, histts[idate], 'smallserie2',
                       'aurelien.campeas@pythonian.f', _insertion_date=idate)
589
590
591
592
593
594
595
596
597

    # this is perfectly round-tripable
    assert (tsh.get(engine, 'smallserie2') == ts).all()
    assert (tsh.get_history(engine, 'smallserie2') == histts).all()

    # get history ranges
    tsa = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 2))
    assert_df("""
598
599
600
601
602
603
insertion_date             value_date
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
2017-02-03 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
                           2017-01-03    2.0
604
605
606
607
608
""", tsa)

    tsb = tsh.get_history(engine, 'smallserie',
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
609
610
611
612
insertion_date             value_date
2017-02-01 00:00:00+00:00  2017-01-01    0.0
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
613
614
615
616
617
618
""", tsb)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 2),
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
619
620
621
insertion_date             value_date
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
622
623
""", tsc)

624
625
626
627
628
629
630
631
632
    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 4),
                          to_insertion_date=datetime(2017, 2, 4))
    assert tsc is None

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2016, 2, 1),
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
633
634
635
636
insertion_date             value_date
2017-02-01 00:00:00+00:00  2017-01-01    0.0
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
637
638
639
640
641
642
643
""", tsc)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2016, 2, 1),
                          to_insertion_date=datetime(2016, 12, 31))
    assert tsc is None

644
645
646
647
648
    # restrictions on value dates
    tsc = tsh.get_history(engine, 'smallserie',
                          from_value_date=datetime(2017, 1, 1),
                          to_value_date=datetime(2017, 1, 2))
    assert_df("""
649
650
651
652
653
654
insertion_date             value_date
2017-02-01 00:00:00+00:00  2017-01-01    0.0
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
2017-02-03 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
655
656
657
658
659
""", tsc)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_value_date=datetime(2017, 1, 2))
    assert_df("""
660
661
662
663
insertion_date             value_date
2017-02-02 00:00:00+00:00  2017-01-02    1.0
2017-02-03 00:00:00+00:00  2017-01-02    1.0
                           2017-01-03    2.0
664
665
666
667
668
""", tsc)

    tsc = tsh.get_history(engine, 'smallserie',
                          to_value_date=datetime(2017, 1, 2))
    assert_df("""
669
670
671
672
673
674
insertion_date             value_date
2017-02-01 00:00:00+00:00  2017-01-01    0.0
2017-02-02 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
2017-02-03 00:00:00+00:00  2017-01-01    0.0
                           2017-01-02    1.0
675
676
""", tsc)

677

678
679
680
681
682
683
684
685
686
def test_history_delta(engine, tsh):
    for d in range(1, 3):
        idate = utcdt(2018, 1, d)
        serie = genserie(idate - timedelta(hours=1), 'H', 6, initval=[d])
        tsh.insert(engine, serie, 'hd', 'aurelien.campeas@pythonian.fr',
                   _insertion_date=idate)

    assert_df("""
insertion_date             value_date               
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
2018-01-01 00:00:00+00:00  2017-12-31 23:00:00+00:00    1.0
                           2018-01-01 00:00:00+00:00    1.0
                           2018-01-01 01:00:00+00:00    1.0
                           2018-01-01 02:00:00+00:00    1.0
                           2018-01-01 03:00:00+00:00    1.0
                           2018-01-01 04:00:00+00:00    1.0
2018-01-02 00:00:00+00:00  2017-12-31 23:00:00+00:00    1.0
                           2018-01-01 00:00:00+00:00    1.0
                           2018-01-01 01:00:00+00:00    1.0
                           2018-01-01 02:00:00+00:00    1.0
                           2018-01-01 03:00:00+00:00    1.0
                           2018-01-01 04:00:00+00:00    1.0
                           2018-01-01 23:00:00+00:00    2.0
                           2018-01-02 00:00:00+00:00    2.0
                           2018-01-02 01:00:00+00:00    2.0
                           2018-01-02 02:00:00+00:00    2.0
                           2018-01-02 03:00:00+00:00    2.0
                           2018-01-02 04:00:00+00:00    2.0
    """, tsh.get_history(engine, 'hd'))

    assert_df("""
insertion_date             value_date               
709
710
2018-01-01 00:00:00+00:00  2017-12-31 23:00:00+00:00    1.0
                           2018-01-01 00:00:00+00:00    1.0
711
712
                           2018-01-01 01:00:00+00:00    1.0
                           2018-01-01 02:00:00+00:00    1.0
713
714
715
716
717
718
719
720
2018-01-02 00:00:00+00:00  2017-12-31 23:00:00+00:00    1.0
                           2018-01-01 00:00:00+00:00    1.0
                           2018-01-01 01:00:00+00:00    1.0
                           2018-01-01 02:00:00+00:00    1.0
                           2018-01-01 03:00:00+00:00    1.0
                           2018-01-01 04:00:00+00:00    1.0
                           2018-01-01 23:00:00+00:00    2.0
                           2018-01-02 00:00:00+00:00    2.0
721
722
723
724
725
726
                           2018-01-02 01:00:00+00:00    2.0
                           2018-01-02 02:00:00+00:00    2.0
""",  tsh.get_history(engine, 'hd', deltaafter=timedelta(hours=2)))

    assert_df("""
insertion_date             value_date               
727
2018-01-01 00:00:00+00:00  2018-01-01 00:00:00+00:00    1.0
728
                           2018-01-01 01:00:00+00:00    1.0
729
2018-01-02 00:00:00+00:00  2018-01-02 00:00:00+00:00    2.0
730
731
                           2018-01-02 01:00:00+00:00    2.0
""",  tsh.get_history(engine, 'hd',
732
                      deltabefore=timedelta(hours=0),
733
734
735
                      deltaafter=timedelta(hours=1)))


736
737
738
739
740
741
742
743
744
745
746
def test_nr_gethistory(engine, tsh):
    s0 = pd.Series([-1, 0, 0, -1],
                   index=pd.DatetimeIndex(start=datetime(2016, 12, 29),
                                          end=datetime(2017, 1, 1),
                                          freq='D'))
    tsh.insert(engine, s0, 'foo', 'zogzog')

    s1 = pd.Series([1, 0, 0, 1],
                   index=pd.DatetimeIndex(start=datetime(2017, 1, 1),
                                          end=datetime(2017, 1, 4),
                                          freq='D'))
747
    idate = utcdt(2016, 1, 1)
748
749
    for i in range(5):
        with engine.connect() as cn:
750
751
752
            tsh.insert(cn, s1 * i, 'foo',
                       'aurelien.campeas@pythonian.f',
                       _insertion_date=idate + timedelta(days=i))
753
754
755
756
757
758
759
760

    df = tsh.get_history(engine, 'foo',
                         datetime(2016, 1, 3),
                         datetime(2016, 1, 4),
                         datetime(2017, 1, 1),
                         datetime(2017, 1, 4))

    assert_df("""
761
762
763
764
765
766
767
768
769
insertion_date             value_date
2016-01-03 00:00:00+00:00  2017-01-01    2.0
                           2017-01-02    0.0
                           2017-01-03    0.0
                           2017-01-04    2.0
2016-01-04 00:00:00+00:00  2017-01-01    3.0
                           2017-01-02    0.0
                           2017-01-03    0.0
                           2017-01-04    3.0
770
771
772
""", df)


773
def test_add_na(engine, tsh):
774
775
776
777
778
    # a serie of NaNs won't be insert in base
    # in case of first insertion
    ts_nan = genserie(datetime(2010, 1, 1), 'D', 5)
    ts_nan[[True] * len(ts_nan)] = np.nan

779
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
780
    assert len(diff) == 5
781
    result = tsh.get(engine, 'ts_add_na')
782
783
784
785
786
787
788
789
790
791
    assert len(result) == 0

    result = tsh.get(engine, 'ts_add_na', _keep_nans=True)
    assert_df("""
2010-01-01   NaN
2010-01-02   NaN
2010-01-03   NaN
2010-01-04   NaN
2010-01-05   NaN
""", result)
792
793
794

    # in case of insertion in existing data
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5)
795
    tsh.insert(engine, ts_begin, 'ts_add_na', 'test')
796
797
798
799
800

    ts_nan = genserie(datetime(2010, 1, 6), 'D', 5)
    ts_nan[[True] * len(ts_nan)] = np.nan
    ts_nan = pd.concat([ts_begin, ts_nan])

801
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
802
803
    assert diff is None

804
    result = tsh.get(engine, 'ts_add_na')
805
    assert len(result) == 5
806
807


808
def test_dtype_mismatch(engine, tsh):
809
    tsh.insert(engine,
810
811
812
813
814
               genserie(datetime(2015, 1, 1), 'D', 11).astype('str'),
               'error1',
               'test')

    with pytest.raises(Exception) as excinfo:
815
        tsh.insert(engine,
816
817
818
819
820
821
                   genserie(datetime(2015, 1, 1), 'D', 11),
                   'error1',
                   'test')

    assert 'Type error when inserting error1, new type is float64, type in base is object' == str(excinfo.value)

822
    tsh.insert(engine,
823
824
825
826
827
               genserie(datetime(2015, 1, 1), 'D', 11),
               'error2',
               'test')

    with pytest.raises(Exception) as excinfo:
828
        tsh.insert(engine,
829
830
831
832
833
                   genserie(datetime(2015, 1, 1), 'D', 11).astype('str'),
                   'error2',
                   'test')

    assert 'Type error when inserting error2, new type is object, type in base is float64' == str(excinfo.value)
834
835


836
837
838
839
840
841
842
843
844
def test_precision(engine, tsh):
    floaty = 0.123456789123456789
    ts = genserie(datetime(2015, 1, 1), 'D', 5, initval=[floaty])

    tsh.insert(engine, ts, 'precision', 'test')
    ts_round = tsh.get(engine, 'precision')
    assert 0.12345678912346 == ts_round.iloc[0]

    diff = tsh.insert(engine, ts_round, 'precision', 'test')
Aurélien Campéas's avatar
Aurélien Campéas committed
845
    assert diff is None  # the roundtriped series does not produce a diff when reinserted
846

Aurélien Campéas's avatar
Aurélien Campéas committed
847
    diff = tsh.insert(engine, ts, 'precision', 'test')  # neither does the original series
848
849
850
    assert diff is None


851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def test_strip(engine, tsh):
    for i in range(1, 5):
        pubdate = utcdt(2017, 1, i)
        ts = genserie(datetime(2017, 1, 10), 'H', 1 + i)
        tsh.insert(engine, ts, 'xserie', 'babar', _insertion_date=pubdate)
        # also insert something completely unrelated
        tsh.insert(engine, genserie(datetime(2018, 1, 1), 'D', 1 + i), 'yserie', 'celeste')

    csida = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3))
    assert csida is not None
    csidb = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3, 1), mode='before')
    csidc = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3, 1), mode='after')
    assert csidb < csida < csidc

    log = tsh.log(engine, names=['xserie', 'yserie'])
    assert [(idx, l['author']) for idx, l in enumerate(log, start=1)
    ] == [
        (1, 'babar'),
        (2, 'celeste'),
        (3, 'babar'),
        (4, 'celeste'),
        (5, 'babar'),
        (6, 'celeste'),
        (7, 'babar'),
        (8, 'celeste')
    ]

    h = tsh.get_history(engine, 'xserie')
    assert_df("""
insertion_date             value_date         
2017-01-01 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
2017-01-02 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
                           2017-01-10 02:00:00    2.0
2017-01-03 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
                           2017-01-10 02:00:00    2.0
                           2017-01-10 03:00:00    3.0
2017-01-04 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
                           2017-01-10 02:00:00    2.0
                           2017-01-10 03:00:00    3.0
                           2017-01-10 04:00:00    4.0
""", h)

    csid = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3))
    with engine.connect() as cn:
        tsh.strip(cn, 'xserie', csid)

    assert_df("""
insertion_date             value_date         
2017-01-01 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
2017-01-02 00:00:00+00:00  2017-01-10 00:00:00    0.0
                           2017-01-10 01:00:00    1.0
                           2017-01-10 02:00:00    2.0
""", tsh.get_history(engine, 'xserie'))

    assert_df("""
2017-01-10 00:00:00    0.0
2017-01-10 01:00:00    1.0
2017-01-10 02:00:00    2.0
""", tsh.get(engine, 'xserie'))

    log = tsh.log(engine, names=['xserie', 'yserie'])
    # 5 and 7 have disappeared
    assert [l['author'] for l in log
    ] == ['babar', 'celeste', 'babar', 'celeste', 'celeste', 'celeste']

    log = tsh.log(engine, stripped=True, names=['xserie', 'yserie'])
922
923
924
925
926
927
    for l in log:
        if l['meta']:
            meta = l['meta']
            stripinfo = meta.get('tshistory.info')
            if stripinfo:
                assert stripinfo.startswith('got stripped from')
928
929
930
931
932
933
934
935
936
937
938
939


def test_prepend(engine, tsh):
    serie = genserie(datetime(2010, 1, 1), 'D', 40)

    assert 40 == len(serie)
    ts_insert = serie[2:]
    tsh.insert(engine, ts_insert, 'prepend', 'test')
    assert 38 == len(tsh.get(engine, 'prepend'))

    tsh.insert(engine, serie, 'prepend', 'test')
    assert 40 == len(tsh.get(engine, 'prepend'))
940
941
942
943
944


def test_long_name(engine, tsh):
    serie = genserie(datetime(2010, 1, 1), 'D', 40)

945
946
947
    name = 'a' * 64
    tsh.insert(engine, serie, name, 'babar')
    assert tsh.get(engine, name) is not None
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090


def test_get_delta(engine, tsh):
    for idate in pd.DatetimeIndex(start=utcdt(2015, 1, 1),
                                  end=utcdt(2015, 1, 1, 3),
                                  freq='H'):
        ts = genserie(start=idate, freq='H', repeat=7)
        tsh.insert(engine, ts, 'republication', 'test',
                   _insertion_date=idate)

    hist = tsh.get_history(engine, 'republication')
    assert_df("""
insertion_date             value_date               
2015-01-01 00:00:00+00:00  2015-01-01 00:00:00+00:00    0.0
                           2015-01-01 01:00:00+00:00    1.0
                           2015-01-01 02:00:00+00:00    2.0
                           2015-01-01 03:00:00+00:00    3.0
                           2015-01-01 04:00:00+00:00    4.0
                           2015-01-01 05:00:00+00:00    5.0
                           2015-01-01 06:00:00+00:00    6.0
2015-01-01 01:00:00+00:00  2015-01-01 00:00:00+00:00    0.0
                           2015-01-01 01:00:00+00:00    0.0
                           2015-01-01 02:00:00+00:00    1.0
                           2015-01-01 03:00:00+00:00    2.0
                           2015-01-01 04:00:00+00:00    3.0
                           2015-01-01 05:00:00+00:00    4.0
                           2015-01-01 06:00:00+00:00    5.0
                           2015-01-01 07:00:00+00:00    6.0
2015-01-01 02:00:00+00:00  2015-01-01 00:00:00+00:00    0.0
                           2015-01-01 01:00:00+00:00    0.0
                           2015-01-01 02:00:00+00:00    0.0
                           2015-01-01 03:00:00+00:00    1.0
                           2015-01-01 04:00:00+00:00    2.0
                           2015-01-01 05:00:00+00:00    3.0
                           2015-01-01 06:00:00+00:00    4.0
                           2015-01-01 07:00:00+00:00    5.0
                           2015-01-01 08:00:00+00:00    6.0
2015-01-01 03:00:00+00:00  2015-01-01 00:00:00+00:00    0.0
                           2015-01-01 01:00:00+00:00    0.0
                           2015-01-01 02:00:00+00:00    0.0
                           2015-01-01 03:00:00+00:00    0.0
                           2015-01-01 04:00:00+00:00    1.0
                           2015-01-01 05:00:00+00:00    2.0
                           2015-01-01 06:00:00+00:00    3.0
                           2015-01-01 07:00:00+00:00    4.0
                           2015-01-01 08:00:00+00:00    5.0
                           2015-01-01 09:00:00+00:00    6.0
""", hist)

    deltas = tsh.get_delta(engine,  'republication', delta=timedelta(hours=3))

    assert_df("""
2015-01-01 03:00:00+00:00    3.0
2015-01-01 04:00:00+00:00    3.0
2015-01-01 05:00:00+00:00    3.0
2015-01-01 06:00:00+00:00    3.0
2015-01-01 07:00:00+00:00    4.0
2015-01-01 08:00:00+00:00    5.0
2015-01-01 09:00:00+00:00    6.0
""", deltas)

    deltas = tsh.get_delta(engine,  'republication', delta=timedelta(hours=5))
    assert_df("""
2015-01-01 05:00:00+00:00    5.0
2015-01-01 06:00:00+00:00    5.0
2015-01-01 07:00:00+00:00    5.0
2015-01-01 08:00:00+00:00    5.0
2015-01-01 09:00:00+00:00    6.0
""", deltas)

    hist = tsh.get_history(engine, 'republication',
                           deltabefore=-timedelta(hours=3),
                           deltaafter=timedelta(hours=3))
    assert_df("""
insertion_date             value_date               
2015-01-01 00:00:00+00:00  2015-01-01 03:00:00+00:00    3.0
2015-01-01 01:00:00+00:00  2015-01-01 04:00:00+00:00    3.0
2015-01-01 02:00:00+00:00  2015-01-01 05:00:00+00:00    3.0
2015-01-01 03:00:00+00:00  2015-01-01 06:00:00+00:00    3.0
""", hist)

    hist = tsh.get_history(engine, 'republication',
                           deltabefore=-timedelta(hours=5),
                           deltaafter=timedelta(hours=5))

    assert_df("""
insertion_date             value_date               
2015-01-01 00:00:00+00:00  2015-01-01 05:00:00+00:00    5.0
2015-01-01 01:00:00+00:00  2015-01-01 06:00:00+00:00    5.0
2015-01-01 02:00:00+00:00  2015-01-01 07:00:00+00:00    5.0
2015-01-01 03:00:00+00:00  2015-01-01 08:00:00+00:00    5.0
""", hist)


    # maybe a more interesting example, each days we insert 7 data points
    for idx, idate in enumerate(pd.DatetimeIndex(start=utcdt(2015, 1, 1),
                                                 end=utcdt(2015, 1, 4),
                                                 freq='D')):
        ts = genserie(start=idate, freq='H', repeat=7)
        tsh.insert(engine, ts, 'repu2', 'test', _insertion_date=idate)

    deltas = tsh.get_delta(engine, 'repu2', delta=timedelta(hours=3))
    assert_df("""
2015-01-01 03:00:00+00:00    3.0
2015-01-01 04:00:00+00:00    4.0
2015-01-01 05:00:00+00:00    5.0
2015-01-01 06:00:00+00:00    6.0
2015-01-02 03:00:00+00:00    3.0
2015-01-02 04:00:00+00:00    4.0
2015-01-02 05:00:00+00:00    5.0
2015-01-02 06:00:00+00:00    6.0
2015-01-03 03:00:00+00:00    3.0
2015-01-03 04:00:00+00:00    4.0
2015-01-03 05:00:00+00:00    5.0
2015-01-03 06:00:00+00:00    6.0
2015-01-04 03:00:00+00:00    3.0
2015-01-04 04:00:00+00:00    4.0
2015-01-04 05:00:00+00:00    5.0
2015-01-04 06:00:00+00:00    6.0
""", deltas)

    # which is basically the same as below
    hist = tsh.get_history(engine, 'repu2',
                           deltabefore=-timedelta(hours=3))
    assert_df("""
insertion_date             value_date               
2015-01-01 00:00:00+00:00  2015-01-01 03:00:00+00:00    3.0
                           2015-01-01 04:00:00+00:00    4.0
                           2015-01-01 05:00:00+00:00    5.0
                           2015-01-01 06:00:00+00:00    6.0
2015-01-02 00:00:00+00:00  2015-01-02 03:00:00+00:00    3.0
                           2015-01-02 04:00:00+00:00    4.0
                           2015-01-02 05:00:00+00:00    5.0
                           2015-01-02 06:00:00+00:00    6.0
2015-01-03 00:00:00+00:00  2015-01-03 03:00:00+00:00    3.0
                           2015-01-03 04:00:00+00:00    4.0
                           2015-01-03 05:00:00+00:00    5.0
                           2015-01-03 06:00:00+00:00    6.0
2015-01-04 00:00:00+00:00  2015-01-04 03:00:00+00:00    3.0
                           2015-01-04 04:00:00+00:00    4.0
                           2015-01-04 05:00:00+00:00    5.0
                           2015-01-04 06:00:00+00:00    6.0
""", hist)
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114


def test_rename(engine, tsh):
    if tsh.namespace == 'zzz':
        return  # this test can only run once

    serie = genserie(datetime(2020, 1, 1), 'D', 3)

    tsh.insert(engine, serie, 'foo', 'Babar')
    tsh.insert(engine, serie, 'bar', 'Babar')
    tsh.insert(engine, serie, 'quux', 'Babar')

    rename_series(engine, {
        'foo': 'new-foo',
        'bar': 'new-bar'
    })

    tsh.resetcaches()

    assert tsh.get(engine, 'foo') is None
    assert tsh.get(engine, 'bar') is None

    for name in ('quux', 'new-foo', 'new-bar'):
        assert tsh.get(engine, name) is not None