test_tsio.py 26.9 KB
Newer Older
1
2
3
4
5
6
7
# coding: utf-8
from pathlib import Path
from datetime import datetime
from dateutil import parser

import pandas as pd
import numpy as np
8
import pytest
9
from mock import patch
10
11
12
13
14


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


15
16
17
18
19
20
21
def assert_group_equals(g1, g2):
    for (n1, s1), (n2, s2) in zip(sorted(g1.items()),
                                  sorted(g2.items())):
        assert n1 == n2
        assert s1.equals(s2)


22
23
24
25
def assert_df(expected, df):
    assert expected.strip() == df.to_string().strip()


26
27
28
29
30
31
32
33
34
35
36
37
def genserie(start, freq, repeat, initval=None, tz=None, name=None):
    if initval is None:
        values = range(repeat)
    else:
        values = initval * repeat
    return pd.Series(values,
                     name=name,
                     index=pd.date_range(start=start,
                                         freq=freq,
                                         periods=repeat,
                                         tz=tz))

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

39
def test_changeset(engine, tsh):
40
    index = pd.date_range(start=datetime(2017, 1, 1), freq='D', periods=3)
41
    data = [1., 2., 3.]
42

43
44
    with patch('tshistory.tsio.datetime') as mock_date:
        mock_date.now.return_value = datetime(2020, 1, 1)
45
        with engine.connect() as cn:
46
47
48
            with tsh.newchangeset(cn, 'babar'):
                tsh.insert(cn, pd.Series(data, index=index), 'ts_values')
                tsh.insert(cn, pd.Series(['a', 'b', 'c'], index=index), 'ts_othervalues')
49

50
51
        g = tsh.get_group(engine, 'ts_values')
        g2 = tsh.get_group(engine, 'ts_othervalues')
52
        assert_group_equals(g, g2)
53

54
        with pytest.raises(AssertionError):
55
            tsh.insert(engine, pd.Series([2, 3, 4], index=index), 'ts_values')
56

57
        with engine.connect() as cn:
58
            data.append(data.pop(0))
59
60
            with tsh.newchangeset(cn, 'celeste'):
                tsh.insert(cn, pd.Series(data, index=index), 'ts_values')
61
                # below should be a noop
62
                tsh.insert(cn, pd.Series(['a', 'b', 'c'], index=index), 'ts_othervalues')
63

64
    g = tsh.get_group(engine, 'ts_values')
65
66
    assert ['ts_values'] == list(g.keys())

67
    assert_df("""
68
69
70
2017-01-01    2.0
2017-01-02    3.0
2017-01-03    1.0
71
""", tsh.get(engine, 'ts_values'))
72

73
    assert_df("""
74
75
76
2017-01-01    a
2017-01-02    b
2017-01-03    c
77
""", tsh.get(engine, 'ts_othervalues'))
78

79
    log = tsh.log(engine)
80
81
82
83
84
85
86
87
88
89
90
    assert [
        {'author': 'babar',
         'rev': 1,
         'date': datetime(2020, 1, 1, 0, 0),
         'names': ['ts_values', 'ts_othervalues']},
        {'author': 'celeste',
         'rev': 2,
         'date': datetime(2020, 1, 1, 0, 0),
         'names': ['ts_values']}
    ] == log

91
    log = tsh.log(engine, names=['ts_othervalues'])
92
93
    assert len(log) == 1
    assert log[0]['rev'] == 1
94
    assert log[0]['names'] == ['ts_values', 'ts_othervalues']
95

96
    log = tsh.log(engine, fromrev=2)
97
98
    assert len(log) == 1

99
    log = tsh.log(engine, torev=1)
100
101
    assert len(log) == 1

102
    info = tsh.info(engine)
103
104
105
106
107
108
    assert {
        'changeset count': 2,
        'serie names': ['ts_othervalues', 'ts_values'],
        'series count': 2
    } == info

109

110
def test_tstamp_roundtrip(engine, tsh):
111
112
    ts = genserie(datetime(2017, 10, 28, 23),
                  'H', 4, tz='UTC')
113
114
115
116
117
118
119
120
121
122
    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)

123
124
    tsh.insert(engine, ts, 'tztest', 'Babar')
    back = tsh.get(engine, 'tztest')
125
126
127
128
129
130
131
132
133
134
135
136
137

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

    back.index = back.index.tz_localize('UTC')
    assert (ts.index == back.index).all()


138
def test_differential(engine, tsh):
139
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10)
140
    tsh.insert(engine, ts_begin, 'ts_test', 'test')
141

142
143
    assert tsh.exists(engine, 'ts_test')
    assert not tsh.exists(engine, 'this_does_not_exist')
144

145
    assert_df("""
146
147
148
149
150
151
152
153
154
155
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
156
""", tsh.get(engine, 'ts_test'))
157
158

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

161
    assert_df("""
162
163
164
165
166
167
168
169
170
171
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
172
""", tsh.get(engine, 'ts_test'))
173
174
175
176

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

179
    assert_df("""
180
181
182
183
184
185
186
187
188
189
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
190
""", tsh.get(engine, 'ts_test'))
191

192
    ts_longer = genserie(datetime(2010, 1, 3), 'D', 15)
193
194
195
196
    ts_longer.iloc[1] = 2.48
    ts_longer.iloc[3] = 3.14
    ts_longer.iloc[5] = ts_begin.iloc[7]

197
    tsh.insert(engine, ts_longer, 'ts_test', 'test')
198

199
    assert_df("""
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
217
""", tsh.get(engine, 'ts_test'))
218
219

    # start testing manual overrides
220
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5, initval=[2])
221
    ts_begin.loc['2010-01-04'] = -1
222
    tsh.insert(engine, ts_begin, 'ts_mixte', 'test')
223
224

    # -1 represents bogus upstream data
225
    assert_df("""
226
227
228
229
230
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
231
""", tsh.get(engine, 'ts_mixte'))
232
233

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

238
    assert_df("""
239
240
241
242
243
244
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
245
""", tsh.get(engine, 'ts_mixte'))
246
247

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

252
    assert_df("""
253
254
255
256
257
258
259
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
260
""", tsh.get(engine, 'ts_mixte'))
261

262
    hist = pd.read_sql('select id, parent from timeserie.ts_test order by id',
Aurélien Campéas's avatar
Aurélien Campéas committed
263
                       engine)
264
    assert_df("""
265
266
267
268
   id  parent
0   1     NaN
1   2     1.0
2   3     2.0
269
""", hist)
270

271
    hist = pd.read_sql('select id, parent from timeserie.ts_mixte order by id',
Aurélien Campéas's avatar
Aurélien Campéas committed
272
                       engine)
273
    assert_df("""
274
275
276
277
   id  parent
0   1     NaN
1   2     1.0
2   3     2.0
278
""", hist)
279

280
    allts = pd.read_sql("select name, table_name from registry "
281
                        "where name in ('ts_test', 'ts_mixte')",
282
283
                        engine)

284
    assert_df("""
285
286
287
       name          table_name
0   ts_test   timeserie.ts_test
1  ts_mixte  timeserie.ts_mixte
288
""", allts)
289

290
    assert_df("""
291
292
293
294
295
296
297
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
298
""", tsh.get(engine, 'ts_mixte',
299
             revision_date=datetime.now()))
300
301


302
def test_bad_import(engine, tsh):
303
304
305
306
307
    # the data were parsed as date by pd.read_json()
    df_result = pd.read_csv(DATADIR / 'test_data.csv')
    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']
308

309
310
    tsh.insert(engine, ts, 'SND_SC', 'test')
    result = tsh.get(engine, 'SND_SC')
311
    assert result.dtype == 'float64'
312
313
314

    # insertion of empty ts
    ts = pd.Series(name='truc', dtype='object')
315
316
    tsh.insert(engine, ts, 'empty_ts', 'test')
    assert tsh.get(engine, 'empty_ts') is None
317
318
319

    # nan in ts
    # all na
320
    ts = genserie(datetime(2010, 1, 10), 'D', 10, [np.nan], name='truc')
321
322
    tsh.insert(engine, ts, 'test_nan', 'test')
    assert tsh.get(engine, 'test_nan') is None
323
324
325
326
327

    # 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')
328
329
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
330

331
332
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
333
    assert_df("""
334
335
336
337
338
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
339
""", result)
340
341
342

    # get_ts with name not in database

343
    tsh.get(engine, 'inexisting_name', 'test')
344
345


346
def test_revision_date(engine, tsh):
347
    idate1 = datetime(2015, 1, 1, 15, 43, 23)
348
    with tsh.newchangeset(engine, 'test', _insertion_date=idate1):
349

350
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [1], name='truc')
351
352
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate1 == tsh.latest_insertion_date(engine, 'ts_through_time')
353

354
    idate2 = datetime(2015, 1, 2, 15, 43, 23)
355
    with tsh.newchangeset(engine, 'test', _insertion_date=idate2):
356

357
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [2], name='truc')
358
359
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate2 == tsh.latest_insertion_date(engine, 'ts_through_time')
360

361
    idate3 = datetime(2015, 1, 3, 15, 43, 23)
362
    with tsh.newchangeset(engine, 'test', _insertion_date=idate3):
363

364
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [3], name='truc')
365
366
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate3 == tsh.latest_insertion_date(engine, 'ts_through_time')
367

368
    ts = tsh.get(engine, 'ts_through_time')
369

370
    assert_df("""
371
372
373
374
2010-01-04    3.0
2010-01-05    3.0
2010-01-06    3.0
2010-01-07    3.0
375
""", ts)
376

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

380
    assert_df("""
381
382
383
384
2010-01-04    2.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    2.0
385
""", ts)
386

387
    ts = tsh.get(engine, 'ts_through_time',
388
                 revision_date=datetime(2015, 1, 1, 18, 43, 23))
389

390
    assert_df("""
391
392
393
394
2010-01-04    1.0
2010-01-05    1.0
2010-01-06    1.0
2010-01-07    1.0
395
""", ts)
396

397
    ts = tsh.get(engine, 'ts_through_time',
398
                 revision_date=datetime(2014, 1, 1, 18, 43, 23))
399
400
401

    assert ts is None

402

403
def test_snapshots(engine, tsh):
404
    tsh._snapshot_interval = 4
405

406
    with engine.connect() as cn:
407
        for tscount in range(1, 11):
408
            ts = genserie(datetime(2015, 1, 1), 'D', tscount, [1])
409
            diff = tsh.insert(cn, ts, 'growing', 'babar')
410
411
            assert diff.index[0] == diff.index[-1] == ts.index[-1]

412
    diff = tsh.insert(engine, ts, 'growing', 'babar')
413
    assert diff is None
414

415
416
    df = pd.read_sql("select id from timeserie.growing where snapshot is not null",
                     engine)
417
    assert_df("""
418
419
   id
0   1
420
421
422
1   4
2   8
3  10
423
""", df)
424

425
    ts = tsh.get(engine, 'growing')
426
    assert_df("""
427
428
429
430
431
432
433
434
435
436
2015-01-01    1.0
2015-01-02    1.0
2015-01-03    1.0
2015-01-04    1.0
2015-01-05    1.0
2015-01-06    1.0
2015-01-07    1.0
2015-01-08    1.0
2015-01-09    1.0
2015-01-10    1.0
437
""", ts)
438

439
    df = pd.read_sql("select id, diff, snapshot from timeserie.growing order by id", engine)
440
441
442
    for attr in ('diff', 'snapshot'):
        df[attr] = df[attr].apply(lambda x: 0 if x is None else len(x))

443
    assert_df("""
444
   id  diff  snapshot
Arnaud Campeas's avatar
Arnaud Campeas committed
445
446
447
448
449
450
451
452
453
454
0   1     0        32
1   2    32         0
2   3    32         0
3   4    32       125
4   5    32         0
5   6    32         0
6   7    32         0
7   8    32       249
8   9    32         0
9  10    32       311
455
""", df)
456

457
458
    table = tsh._get_ts_table(engine, 'growing')
    snapid, snap = tsh._find_snapshot(engine, table, ())
459
460
    assert snapid == 10
    assert (ts == snap).all()
461
462


463
def test_deletion(engine, tsh):
464
465
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 11)
    ts_begin.iloc[-1] = np.nan
466
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
467

468
    ts = tsh._build_snapshot_upto(engine, tsh._get_ts_table(engine, 'ts_del'))
469
    assert ts.iloc[-1] == 9.0
470

471
    ts_begin.iloc[0] = np.nan
472
    ts_begin.iloc[3] = np.nan
473

474
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
475

476
    assert_df("""
477
478
479
480
481
482
483
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
484
2010-01-10    9.0
485
""", tsh.get(engine, 'ts_del'))
486

487
    ts2 = tsh.get(engine, 'ts_del',
488
489
                 # force snapshot reconstruction feature
                 revision_date=datetime(2038, 1, 1))
490
    assert (tsh.get(engine, 'ts_del') == ts2).all()
491

492
493
494
    ts_begin.iloc[0] = 42
    ts_begin.iloc[3] = 23

495
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
496

497
    assert_df("""
498
499
500
501
502
503
504
505
506
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
507
2010-01-10     9.0
508
""", tsh.get(engine, 'ts_del'))
509
510
511

    # now with string!

512
    ts_string = genserie(datetime(2010, 1, 1), 'D', 10, ['machin'])
513
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
514
515
516
517

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

518
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
519
    assert_df("""
520
521
522
523
524
525
526
527
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
528
""", tsh.get(engine, 'ts_string_del'))
529
530
531
532

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

533
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
534
    assert_df("""
535
536
537
538
539
540
541
542
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
543
2010-01-10    machin
544
""", tsh.get(engine, 'ts_string_del'))
545

546
    ts_string[ts_string.index] = np.nan
547
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
548

549
    erased = tsh.get(engine, 'ts_string_del')
550
551
    assert len(erased) == 0

552
553
    # first insertion with only nan

554
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10, [np.nan])
555
    tsh.insert(engine, ts_begin, 'ts_null', 'test')
556

557
    assert tsh.get(engine, 'ts_null') is None
558

559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    # 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)

578
579
    tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
    diff = tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
580
581
    assert diff is None

582
    # there is no difference
583
    assert 0 == len(tsh._compute_diff(ts_repushed, ts_repushed))
584
585
586
587
588

    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
589
    diff = tsh._compute_diff(ts_repushed, ts_add)
590
591
592
593
594
595

    assert_df("""
2010-01-02     1.0
2010-01-03     2.0
2010-01-09     NaN
2010-01-12    11.0
596
2010-01-13    12.0""", diff.sort_index())
597
598
599
600
    # value on nan => value
    # nan on value => nan
    # nan on nan => Nothing
    # nan on nothing=> Nothing
601

Aurélien Campéas's avatar
Aurélien Campéas committed
602
    # full erasing
603
604
    # numeric
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4)
605
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
606

Aurélien Campéas's avatar
Aurélien Campéas committed
607
    ts_begin.iloc[:] = np.nan
608
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
609
610

    ts_end = genserie(datetime(2010, 1, 1), 'D', 4)
611
    tsh.insert(engine, ts_end, 'ts_full_del', 'test')
612
613
614
615

    # string

    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4, ['text'])
616
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
617
618

    ts_begin.iloc[:] = np.nan
619
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
620
621

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

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

625
def test_multi_index(engine, tsh):
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    appdate_0 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 2),
                                 freq='D').values
    pubdate_0 = [pd.datetime(2015, 1, 11, 12, 0, 0)] * 2
    insertion_date_0 = [pd.datetime(2015, 1, 11, 12, 30, 0)] * 2

    multi = [
        appdate_0,
        np.array(pubdate_0),
        np.array(insertion_date_0)
    ]

    ts_multi = pd.Series(range(2), index=multi)
    ts_multi.index.rename(['b', 'c', 'a'], inplace=True)

641
    tsh.insert(engine, ts_multi, 'ts_multi_simple', 'test')
642

643
    ts = tsh.get(engine, 'ts_multi_simple')
644
645
646
    assert_df("""
                                                    ts_multi_simple
a                   b          c                                   
647
648
2015-01-11 12:30:00 2015-01-01 2015-01-11 12:00:00              0.0
                    2015-01-02 2015-01-11 12:00:00              1.0
649
650
""", pd.DataFrame(ts))

651
    diff = tsh.insert(engine, ts_multi, 'ts_multi_simple', 'test')
652
653
654
655
656
    assert diff is None

    ts_multi_2 = pd.Series([0, 2], index=multi)
    ts_multi_2.index.rename(['b', 'c', 'a'], inplace=True)

657
658
    tsh.insert(engine, ts_multi_2, 'ts_multi_simple', 'test')
    ts = tsh.get(engine, 'ts_multi_simple')
659
660
661
662

    assert_df("""
                                                    ts_multi_simple
a                   b          c                                   
663
664
2015-01-11 12:30:00 2015-01-01 2015-01-11 12:00:00              0.0
                    2015-01-02 2015-01-11 12:00:00              2.0
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
""", pd.DataFrame(ts))

    # bigger ts
    appdate_0 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values
    pubdate_0 = [pd.datetime(2015, 1, 11, 12, 0, 0)] * 4
    insertion_date_0 = [pd.datetime(2015, 1, 11, 12, 30, 0)] * 4

    appdate_1 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values

    pubdate_1 = [pd.datetime(2015, 1, 21, 12, 0, 0)] * 4
    insertion_date_1 = [pd.datetime(2015, 1, 21, 12, 30, 0)] * 4

    multi = [
        np.concatenate([appdate_0, appdate_1]),
        np.array(pubdate_0 + pubdate_1),
        np.array(insertion_date_0 + insertion_date_1)
    ]

    ts_multi = pd.Series(range(8), index=multi)
    ts_multi.index.rename(['a', 'c', 'b'], inplace=True)

690
691
    tsh.insert(engine, ts_multi, 'ts_multi', 'test')
    ts = tsh.get(engine, 'ts_multi')
692
693
694
695

    assert_df("""
                                                    ts_multi
a          b                   c                            
696
697
698
699
700
701
702
703
2015-01-01 2015-01-11 12:30:00 2015-01-11 12:00:00       0.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
2015-01-02 2015-01-11 12:30:00 2015-01-11 12:00:00       1.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       5.0
2015-01-03 2015-01-11 12:30:00 2015-01-11 12:00:00       2.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       6.0
2015-01-04 2015-01-11 12:30:00 2015-01-11 12:00:00       3.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       7.0
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    """, pd.DataFrame(ts.sort_index()))
    # Note: the columnns are returned according to the alphabetic order

    appdate_2 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values
    pubdate_2 = [pd.datetime(2015, 1, 31, 12, 0, 0)] * 4
    insertion_date_2 = [pd.datetime(2015, 1, 31, 12, 30, 0)] * 4

    multi_2 = [
        np.concatenate([appdate_1, appdate_2]),
        np.array(pubdate_1 + pubdate_2),
        np.array(insertion_date_1 + insertion_date_2)
    ]

    ts_multi_2 = pd.Series([4] * 8, index=multi_2)
    ts_multi_2.index.rename(['a', 'c', 'b'], inplace=True)

    # A second ts is inserted with some index in common with the first
    # one: appdate_1, pubdate_1,and insertion_date_1. The value is set
    # at 4, which matches the previous value of the "2015-01-01" point.

726
    diff = tsh.insert(engine, ts_multi_2, 'ts_multi', 'test')
727
728
729
730
731
732
733
734
735
736
737
738
739
740
    assert_df("""
                                                    ts_multi
a          b                   c                            
2015-01-01 2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-02 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-03 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-04 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
        """, pd.DataFrame(diff.sort_index()))
    # the differential skips a value for "2015-01-01"
    # which does not change from the previous ts

741
    ts = tsh.get(engine, 'ts_multi')
742
743
744
    assert_df("""
                                                    ts_multi
a          b                   c                            
745
746
747
748
749
750
751
752
753
754
755
756
2015-01-01 2015-01-11 12:30:00 2015-01-11 12:00:00       0.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-02 2015-01-11 12:30:00 2015-01-11 12:00:00       1.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-03 2015-01-11 12:30:00 2015-01-11 12:00:00       2.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-04 2015-01-11 12:30:00 2015-01-11 12:00:00       3.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
757
758
759
        """, pd.DataFrame(ts.sort_index()))

    # the result ts have now 3 values for each point in 'a'
760
761


762
def test_get_history(engine, tsh):
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
    for numserie in (1, 2, 3):
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'aurelien.campeas@pythonian.fr',
                                  _insertion_date=datetime(2017, 2, numserie)):
                tsh.insert(cn, genserie(datetime(2017, 1, 1), 'D', numserie), 'smallserie')

    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',
         'date': datetime(2017, 2, 1, 0, 0),
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
         'date': datetime(2017, 2, 2, 0, 0),
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
         'date': datetime(2017, 2, 3, 0, 0),
         'names': ['smallserie']
        }
    ] == [{k: v for k, v in log.items() if k != 'rev'}
          for log in logs]
    histts = tsh.get_history(engine, 'smallserie')

    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
                2017-01-03    2.0
""", histts)

    for idx, idate in enumerate(histts.groupby('insertion_date').groups):
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'aurelien.campeas@pythonian.f',
                                  _insertion_date=idate):
                tsh.insert(cn, histts[idate], 'smallserie2')

    # 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("""
insertion_date  value_date
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
                2017-01-03    2.0
""", tsa)

    tsb = tsh.get_history(engine, 'smallserie',
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
""", tsb)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 2),
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
""", tsc)


845
def test_add_na(engine, tsh):
846
847
848
849
850
    # 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

851
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
852
    assert diff is None
853
    result = tsh.get(engine, 'ts_add_na')
854
855
856
857
    assert result is None

    # in case of insertion in existing data
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5)
858
    tsh.insert(engine, ts_begin, 'ts_add_na', 'test')
859
860
861
862
863

    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])

864
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
865
866
    assert diff is None

867
    result = tsh.get(engine, 'ts_add_na')
868
    assert len(result) == 5
869
870


871
def test_dtype_mismatch(engine, tsh):
872
    tsh.insert(engine,
873
874
875
876
877
               genserie(datetime(2015, 1, 1), 'D', 11).astype('str'),
               'error1',
               'test')

    with pytest.raises(Exception) as excinfo:
878
        tsh.insert(engine,
879
880
881
882
883
884
                   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)

885
    tsh.insert(engine,
886
887
888
889
890
               genserie(datetime(2015, 1, 1), 'D', 11),
               'error2',
               'test')

    with pytest.raises(Exception) as excinfo:
891
        tsh.insert(engine,
892
893
894
895
896
                   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)