summaryrefslogtreecommitdiff
path: root/tests/cts/src/android/healthconnect/cts/WeightRecordTest.java
blob: ed79478ebf33ca8e77546f57ce3279d99a4b78b6 (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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
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
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.healthconnect.cts;

import static android.health.connect.datatypes.WeightRecord.WEIGHT_AVG;
import static android.health.connect.datatypes.WeightRecord.WEIGHT_MAX;
import static android.health.connect.datatypes.WeightRecord.WEIGHT_MIN;

import static com.google.common.truth.Truth.assertThat;

import android.content.Context;
import android.health.connect.AggregateRecordsGroupedByDurationResponse;
import android.health.connect.AggregateRecordsGroupedByPeriodResponse;
import android.health.connect.AggregateRecordsRequest;
import android.health.connect.AggregateRecordsResponse;
import android.health.connect.DeleteUsingFiltersRequest;
import android.health.connect.HealthConnectException;
import android.health.connect.LocalTimeRangeFilter;
import android.health.connect.ReadRecordsRequestUsingFilters;
import android.health.connect.ReadRecordsRequestUsingIds;
import android.health.connect.RecordIdFilter;
import android.health.connect.TimeInstantRangeFilter;
import android.health.connect.changelog.ChangeLogTokenRequest;
import android.health.connect.changelog.ChangeLogTokenResponse;
import android.health.connect.changelog.ChangeLogsRequest;
import android.health.connect.changelog.ChangeLogsResponse;
import android.health.connect.datatypes.DataOrigin;
import android.health.connect.datatypes.Device;
import android.health.connect.datatypes.Metadata;
import android.health.connect.datatypes.Record;
import android.health.connect.datatypes.WeightRecord;
import android.health.connect.datatypes.units.Mass;
import android.platform.test.annotations.AppModeFull;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@AppModeFull(reason = "HealthConnectManager is not accessible to instant apps")
@RunWith(AndroidJUnit4.class)
public class WeightRecordTest {
    private static final String TAG = "WeightRecordTest";

    @Before
    public void setUp() {
        // TODO(b/283737434): Update the HC code to use user aware context on permission change.
        // Temporary fix to set firstGrantTime for the correct user in HSUM.
        TestUtils.deleteAllStagedRemoteData();
    }

    @After
    public void tearDown() throws InterruptedException {
        TestUtils.verifyDeleteRecords(
                WeightRecord.class,
                new TimeInstantRangeFilter.Builder()
                        .setStartTime(Instant.EPOCH)
                        .setEndTime(Instant.now())
                        .build());
        TestUtils.deleteAllStagedRemoteData();
    }

    @Test
    public void testInsertWeightRecord() throws InterruptedException {
        List<Record> records = List.of(getBaseWeightRecord(), getCompleteWeightRecord());
        TestUtils.insertRecords(records);
    }

    @Test
    public void testReadWeightRecord_usingIds() throws InterruptedException {
        List<Record> recordList =
                Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord());
        List<Record> insertedRecords = TestUtils.insertRecords(recordList);

        readWeightRecordUsingIds(insertedRecords);
    }

    @Test
    public void testReadWeightRecord_invalidIds() throws InterruptedException {
        ReadRecordsRequestUsingIds<WeightRecord> request =
                new ReadRecordsRequestUsingIds.Builder<>(WeightRecord.class)
                        .addId(UUID.randomUUID().toString())
                        .build();
        List<WeightRecord> result = TestUtils.readRecords(request);
        assertThat(result.size()).isEqualTo(0);
    }

    @Test
    public void testReadWeightRecord_usingClientRecordIds() throws InterruptedException {
        List<Record> recordList =
                Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord());
        List<Record> insertedRecords = TestUtils.insertRecords(recordList);
        readWeightRecordUsingClientId(insertedRecords);
    }

    @Test
    public void testReadWeightRecord_invalidClientRecordIds() throws InterruptedException {
        ReadRecordsRequestUsingIds<WeightRecord> request =
                new ReadRecordsRequestUsingIds.Builder<>(WeightRecord.class)
                        .addClientRecordId("abc")
                        .build();
        List<WeightRecord> result = TestUtils.readRecords(request);
        assertThat(result.size()).isEqualTo(0);
    }

    @Test
    public void testReadWeightRecordUsingFilters_default() throws InterruptedException {
        List<WeightRecord> oldWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class).build());
        WeightRecord testRecord = getCompleteWeightRecord();
        TestUtils.insertRecords(Collections.singletonList(testRecord));
        List<WeightRecord> newWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class).build());
        assertThat(newWeightRecords.size()).isEqualTo(oldWeightRecords.size() + 1);
        assertThat(newWeightRecords.get(newWeightRecords.size() - 1).equals(testRecord)).isTrue();
    }

    @Test
    public void testReadWeightRecordUsingFilters_timeFilter() throws InterruptedException {
        TimeInstantRangeFilter filter =
                new TimeInstantRangeFilter.Builder()
                        .setStartTime(Instant.now())
                        .setEndTime(Instant.now().plusMillis(3000))
                        .build();
        WeightRecord testRecord = getCompleteWeightRecord();
        TestUtils.insertRecords(Collections.singletonList(testRecord));
        List<WeightRecord> newWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class)
                                .setTimeRangeFilter(filter)
                                .build());
        assertThat(newWeightRecords.size()).isEqualTo(1);
        assertThat(newWeightRecords.get(newWeightRecords.size() - 1).equals(testRecord)).isTrue();
    }

    @Test
    public void testReadWeightRecordUsingFilters_dataFilter_correct() throws InterruptedException {
        Context context = ApplicationProvider.getApplicationContext();
        List<WeightRecord> oldWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class)
                                .addDataOrigins(
                                        new DataOrigin.Builder()
                                                .setPackageName(context.getPackageName())
                                                .build())
                                .build());
        WeightRecord testRecord = getCompleteWeightRecord();
        TestUtils.insertRecords(Collections.singletonList(testRecord));
        List<WeightRecord> newWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class)
                                .addDataOrigins(
                                        new DataOrigin.Builder()
                                                .setPackageName(context.getPackageName())
                                                .build())
                                .build());
        assertThat(newWeightRecords.size() - oldWeightRecords.size()).isEqualTo(1);
        WeightRecord newRecord = newWeightRecords.get(newWeightRecords.size() - 1);
        assertThat(newRecord.equals(testRecord)).isTrue();
        assertThat(newRecord.getWeight()).isEqualTo(testRecord.getWeight());
    }

    @Test
    public void testReadWeightRecordUsingFilters_dataFilter_incorrect()
            throws InterruptedException {
        TestUtils.insertRecords(Collections.singletonList(getCompleteWeightRecord()));
        List<WeightRecord> newWeightRecords =
                TestUtils.readRecords(
                        new ReadRecordsRequestUsingFilters.Builder<>(WeightRecord.class)
                                .addDataOrigins(
                                        new DataOrigin.Builder().setPackageName("abc").build())
                                .build());
        assertThat(newWeightRecords.size()).isEqualTo(0);
    }

    @Test
    public void testAggregation_weight() throws Exception {
        Context context = ApplicationProvider.getApplicationContext();
        List<Record> records =
                Arrays.asList(
                        getBaseWeightRecord(5.0),
                        getBaseWeightRecord(10.0),
                        getBaseWeightRecord(15.0));
        AggregateRecordsResponse<Mass> response =
                TestUtils.getAggregateResponse(
                        new AggregateRecordsRequest.Builder<Mass>(
                                        new TimeInstantRangeFilter.Builder()
                                                .setStartTime(Instant.ofEpochMilli(0))
                                                .setEndTime(Instant.now().plus(1, ChronoUnit.DAYS))
                                                .build())
                                .addAggregationType(WEIGHT_AVG)
                                .addAggregationType(WEIGHT_MAX)
                                .addAggregationType(WEIGHT_MIN)
                                .addDataOriginsFilter(
                                        new DataOrigin.Builder()
                                                .setPackageName(context.getPackageName())
                                                .build())
                                .build(),
                        records);
        Mass maxWeight = response.get(WEIGHT_MAX);
        Mass minWeight = response.get(WEIGHT_MIN);
        Mass avgWeight = response.get(WEIGHT_AVG);
        assertThat(maxWeight).isNotNull();
        assertThat(maxWeight.getInGrams()).isEqualTo(15.0);
        assertThat(minWeight).isNotNull();
        assertThat(minWeight.getInGrams()).isEqualTo(5.0);
        assertThat(avgWeight).isNotNull();
        assertThat(avgWeight.getInGrams()).isEqualTo(10.0);
        Set<DataOrigin> dataOrigins = response.getDataOrigins(WEIGHT_AVG);
        for (DataOrigin itr : dataOrigins) {
            assertThat(itr.getPackageName()).isEqualTo("android.healthconnect.cts");
        }
    }

    @Test
    public void testDeleteWeightRecord_no_filters() throws InterruptedException {
        String id = TestUtils.insertRecordAndGetId(getCompleteWeightRecord());
        TestUtils.verifyDeleteRecords(new DeleteUsingFiltersRequest.Builder().build());
        TestUtils.assertRecordNotFound(id, WeightRecord.class);
    }

    @Test
    public void testDeleteWeightRecord_time_filters() throws InterruptedException {
        TimeInstantRangeFilter timeRangeFilter =
                new TimeInstantRangeFilter.Builder()
                        .setStartTime(Instant.now())
                        .setEndTime(Instant.now().plusMillis(1000))
                        .build();
        String id = TestUtils.insertRecordAndGetId(getCompleteWeightRecord());
        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder()
                        .addRecordType(WeightRecord.class)
                        .setTimeRangeFilter(timeRangeFilter)
                        .build());
        TestUtils.assertRecordNotFound(id, WeightRecord.class);
    }

    static WeightRecord getBaseWeightRecord(Instant time, ZoneOffset zoneOffset) {
        return new WeightRecord.Builder(new Metadata.Builder().build(), time, Mass.fromGrams(50))
                .setZoneOffset(zoneOffset)
                .build();
    }

    @Test
    public void testDeleteWeightRecord_time_filters_local() throws InterruptedException {
        LocalDateTime recordTime = LocalDateTime.now(ZoneOffset.MIN);
        LocalTimeRangeFilter timeRangeFilter =
                new LocalTimeRangeFilter.Builder()
                        .setStartTime(recordTime.minus(1, ChronoUnit.SECONDS))
                        .setEndTime(recordTime.plus(1, ChronoUnit.SECONDS))
                        .build();
        String id1 =
                TestUtils.insertRecordAndGetId(
                        getBaseWeightRecord(recordTime.toInstant(ZoneOffset.MIN), ZoneOffset.MIN));
        String id2 =
                TestUtils.insertRecordAndGetId(
                        getBaseWeightRecord(recordTime.toInstant(ZoneOffset.MAX), ZoneOffset.MAX));
        TestUtils.assertRecordFound(id1, WeightRecord.class);
        TestUtils.assertRecordFound(id2, WeightRecord.class);
        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder()
                        .addRecordType(WeightRecord.class)
                        .setTimeRangeFilter(timeRangeFilter)
                        .build());
        TestUtils.assertRecordNotFound(id1, WeightRecord.class);
        TestUtils.assertRecordNotFound(id2, WeightRecord.class);
    }

    @Test
    public void testDeleteWeightRecord_recordId_filters() throws InterruptedException {
        List<Record> records = List.of(getBaseWeightRecord(), getCompleteWeightRecord());
        TestUtils.insertRecords(records);

        for (Record record : records) {
            TestUtils.verifyDeleteRecords(
                    new DeleteUsingFiltersRequest.Builder()
                            .addRecordType(record.getClass())
                            .build());
            TestUtils.assertRecordNotFound(record.getMetadata().getId(), record.getClass());
        }
    }

    @Test
    public void testDeleteWeightRecord_dataOrigin_filters() throws InterruptedException {
        Context context = ApplicationProvider.getApplicationContext();
        String id = TestUtils.insertRecordAndGetId(getCompleteWeightRecord());
        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder()
                        .addDataOrigin(
                                new DataOrigin.Builder()
                                        .setPackageName(context.getPackageName())
                                        .build())
                        .build());
        TestUtils.assertRecordNotFound(id, WeightRecord.class);
    }

    @Test
    public void testDeleteWeightRecord_dataOrigin_filter_incorrect() throws InterruptedException {
        String id = TestUtils.insertRecordAndGetId(getCompleteWeightRecord());
        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder()
                        .addDataOrigin(new DataOrigin.Builder().setPackageName("abc").build())
                        .build());
        TestUtils.assertRecordFound(id, WeightRecord.class);
    }

    @Test
    public void testDeleteWeightRecord_usingIds() throws InterruptedException {
        List<Record> records = List.of(getBaseWeightRecord(), getCompleteWeightRecord());
        List<Record> insertedRecord = TestUtils.insertRecords(records);
        List<RecordIdFilter> recordIds = new ArrayList<>(records.size());
        for (Record record : insertedRecord) {
            recordIds.add(RecordIdFilter.fromId(record.getClass(), record.getMetadata().getId()));
        }

        TestUtils.verifyDeleteRecords(recordIds);
        for (Record record : records) {
            TestUtils.assertRecordNotFound(record.getMetadata().getId(), record.getClass());
        }
    }

    @Test
    public void testDeleteWeightRecord_time_range() throws InterruptedException {
        TimeInstantRangeFilter timeRangeFilter =
                new TimeInstantRangeFilter.Builder()
                        .setStartTime(Instant.now())
                        .setEndTime(Instant.now().plusMillis(1000))
                        .build();
        String id = TestUtils.insertRecordAndGetId(getCompleteWeightRecord());
        TestUtils.verifyDeleteRecords(WeightRecord.class, timeRangeFilter);
        TestUtils.assertRecordNotFound(id, WeightRecord.class);
    }

    @Test
    public void testZoneOffsets() {
        final ZoneOffset defaultZoneOffset =
                ZoneOffset.systemDefault().getRules().getOffset(Instant.now());
        final ZoneOffset zoneOffset = ZoneOffset.UTC;
        WeightRecord.Builder builder =
                new WeightRecord.Builder(
                        new Metadata.Builder().build(), Instant.now(), Mass.fromGrams(10.0));

        assertThat(builder.setZoneOffset(zoneOffset).build().getZoneOffset()).isEqualTo(zoneOffset);
        assertThat(builder.clearZoneOffset().build().getZoneOffset()).isEqualTo(defaultZoneOffset);
    }

    @Test
    public void testUpdateRecords_validInput_dataBaseUpdatedSuccessfully()
            throws InterruptedException {

        List<Record> insertedRecords =
                TestUtils.insertRecords(
                        Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord()));

        // read inserted records and verify that the data is same as inserted.
        readWeightRecordUsingIds(insertedRecords);

        // Generate a new set of records that will be used to perform the update operation.
        List<Record> updateRecords =
                Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord());

        // Modify the uid of the updateRecords to the uuid that was present in the insert records.
        for (int itr = 0; itr < updateRecords.size(); itr++) {
            updateRecords.set(
                    itr,
                    getWeightRecord_update(
                            updateRecords.get(itr),
                            insertedRecords.get(itr).getMetadata().getId(),
                            insertedRecords.get(itr).getMetadata().getClientRecordId()));
        }

        TestUtils.updateRecords(updateRecords);

        // assert the inserted data has been modified by reading the data.
        readWeightRecordUsingIds(updateRecords);
    }

    @Test
    public void testUpdateRecords_invalidInputRecords_noChangeInDataBase()
            throws InterruptedException {
        List<Record> insertedRecords =
                TestUtils.insertRecords(
                        Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord()));

        // read inserted records and verify that the data is same as inserted.
        readWeightRecordUsingIds(insertedRecords);

        // Generate a second set of records that will be used to perform the update operation.
        List<Record> updateRecords =
                Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord());

        // Modify the Uid of the updateRecords to the UUID that was present in the insert records,
        // leaving out alternate records so that they have a new UUID which is not present in the
        // dataBase.
        for (int itr = 0; itr < updateRecords.size(); itr++) {
            updateRecords.set(
                    itr,
                    getWeightRecord_update(
                            updateRecords.get(itr),
                            itr % 2 == 0
                                    ? insertedRecords.get(itr).getMetadata().getId()
                                    : UUID.randomUUID().toString(),
                            itr % 2 == 0
                                    ? insertedRecords.get(itr).getMetadata().getId()
                                    : UUID.randomUUID().toString()));
        }

        try {
            TestUtils.updateRecords(updateRecords);
            Assert.fail("Expected to fail due to invalid records ids.");
        } catch (HealthConnectException exception) {
            assertThat(exception.getErrorCode())
                    .isEqualTo(HealthConnectException.ERROR_INVALID_ARGUMENT);
        }

        // assert the inserted data has not been modified by reading the data.
        readWeightRecordUsingIds(insertedRecords);
    }

    @Test
    public void testUpdateRecords_recordWithInvalidPackageName_noChangeInDataBase()
            throws InterruptedException {
        List<Record> insertedRecords =
                TestUtils.insertRecords(
                        Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord()));

        // read inserted records and verify that the data is same as inserted.
        readWeightRecordUsingIds(insertedRecords);

        // Generate a second set of records that will be used to perform the update operation.
        List<Record> updateRecords =
                Arrays.asList(getCompleteWeightRecord(), getCompleteWeightRecord());

        // Modify the Uuid of the updateRecords to the uuid that was present in the insert records.
        for (int itr = 0; itr < updateRecords.size(); itr++) {
            updateRecords.set(
                    itr,
                    getWeightRecord_update(
                            updateRecords.get(itr),
                            insertedRecords.get(itr).getMetadata().getId(),
                            insertedRecords.get(itr).getMetadata().getClientRecordId()));
            //             adding an entry with invalid packageName.
            updateRecords.set(itr, getCompleteWeightRecord());
        }

        try {
            TestUtils.updateRecords(updateRecords);
            Assert.fail("Expected to fail due to invalid package.");
        } catch (Exception exception) {
            // verify that the testcase failed due to invalid argument exception.
            assertThat(exception).isNotNull();
        }

        // assert the inserted data has not been modified by reading the data.
        readWeightRecordUsingIds(insertedRecords);
    }

    @Test
    public void testInsertAndDeleteRecord_changelogs() throws InterruptedException {
        Context context = ApplicationProvider.getApplicationContext();
        ChangeLogTokenResponse tokenResponse =
                TestUtils.getChangeLogToken(
                        new ChangeLogTokenRequest.Builder()
                                .addDataOriginFilter(
                                        new DataOrigin.Builder()
                                                .setPackageName(context.getPackageName())
                                                .build())
                                .addRecordType(WeightRecord.class)
                                .build());
        ChangeLogsRequest changeLogsRequest =
                new ChangeLogsRequest.Builder(tokenResponse.getToken()).build();
        ChangeLogsResponse response = TestUtils.getChangeLogs(changeLogsRequest);
        assertThat(response.getUpsertedRecords().size()).isEqualTo(0);
        assertThat(response.getDeletedLogs().size()).isEqualTo(0);

        List<Record> testRecord = Collections.singletonList(getCompleteWeightRecord());
        TestUtils.insertRecords(testRecord);
        response = TestUtils.getChangeLogs(changeLogsRequest);
        assertThat(response.getUpsertedRecords().size()).isEqualTo(1);
        assertThat(
                        response.getUpsertedRecords().stream()
                                .map(Record::getMetadata)
                                .map(Metadata::getId)
                                .toList())
                .containsExactlyElementsIn(
                        testRecord.stream().map(Record::getMetadata).map(Metadata::getId).toList());
        assertThat(response.getDeletedLogs().size()).isEqualTo(0);

        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder().addRecordType(WeightRecord.class).build());
        response = TestUtils.getChangeLogs(changeLogsRequest);
        assertThat(response.getDeletedLogs()).isEmpty();
    }

    @Test
    public void testAggregatePeriod_withLocalDateTime_responsesAnswerAndBoundariesCorrect()
            throws Exception {
        testAggregatePeriodForZoneOffset(ZoneOffset.ofHours(4));
        testAggregatePeriodForZoneOffset(ZoneOffset.ofHours(-4));
        testAggregatePeriodForZoneOffset(ZoneOffset.MIN);
        testAggregatePeriodForZoneOffset(ZoneOffset.MAX);
        testAggregatePeriodForZoneOffset(ZoneOffset.UTC);
    }

    void testAggregatePeriodForZoneOffset(ZoneOffset offset) throws Exception {
        Instant endTime = Instant.now();
        LocalDateTime endTimeLocal = LocalDateTime.ofInstant(endTime, offset);
        insertThreeWeightRecordsWithZoneOffset(endTime, offset);

        LocalTimeRangeFilter filter =
                new LocalTimeRangeFilter.Builder()
                        .setStartTime(endTimeLocal.minusDays(3))
                        .setEndTime(endTimeLocal)
                        .build();

        List<AggregateRecordsGroupedByPeriodResponse<Mass>> responses =
                TestUtils.getAggregateResponseGroupByPeriod(
                        new AggregateRecordsRequest.Builder<Mass>(filter)
                                .addAggregationType(WEIGHT_MIN)
                                .build(),
                        Period.ofDays(1));

        assertThat(responses).hasSize(3);
        LocalDateTime groupBoundary = endTimeLocal.minusDays(3);
        for (int i = 0; i < 3; i++) {
            assertThat(responses.get(i).get(WEIGHT_MIN)).isEqualTo(Mass.fromGrams(10.0));
            assertThat(responses.get(i).getZoneOffset(WEIGHT_MIN)).isEqualTo(offset);
            assertThat(responses.get(i).getStartTime().getDayOfYear())
                    .isEqualTo(groupBoundary.getDayOfYear());
            groupBoundary = groupBoundary.plus(1, ChronoUnit.DAYS);
            assertThat(responses.get(i).getEndTime().getDayOfYear())
                    .isEqualTo(groupBoundary.getDayOfYear());
        }

        tearDown();
    }

    @Test
    public void testAggregateDuration_withLocalDateTime_responsesAnswerAndBoundariesCorrect()
            throws Exception {
        testDurationLocalTimeAggregationZoneOffset(ZoneOffset.ofHours(4));
        testDurationLocalTimeAggregationZoneOffset(ZoneOffset.ofHours(-4));
        testDurationLocalTimeAggregationZoneOffset(ZoneOffset.MIN);
        testDurationLocalTimeAggregationZoneOffset(ZoneOffset.MAX);
        testDurationLocalTimeAggregationZoneOffset(ZoneOffset.UTC);
    }

    private void testDurationLocalTimeAggregationZoneOffset(ZoneOffset offset)
            throws InterruptedException {
        Instant endTime = Instant.now();
        LocalDateTime endTimeLocal = LocalDateTime.ofInstant(endTime, offset);
        insertThreeWeightRecordsWithZoneOffset(endTime, offset);

        List<AggregateRecordsGroupedByDurationResponse<Mass>> responses =
                TestUtils.getAggregateResponseGroupByDuration(
                        new AggregateRecordsRequest.Builder<Mass>(
                                        new LocalTimeRangeFilter.Builder()
                                                .setStartTime(endTimeLocal.minusDays(3))
                                                .setEndTime(endTimeLocal)
                                                .build())
                                .addAggregationType(WEIGHT_MAX)
                                .build(),
                        Duration.ofDays(1));

        assertThat(responses).hasSize(3);
        Instant groupBoundary = endTimeLocal.minusDays(3).toInstant(ZoneOffset.UTC);
        for (int i = 0; i < 3; i++) {
            assertThat(responses.get(i).get(WEIGHT_MAX)).isEqualTo(Mass.fromGrams(10.0));
            assertThat(responses.get(i).getZoneOffset(WEIGHT_MAX)).isEqualTo(offset);
            assertThat(responses.get(i).getStartTime().getEpochSecond())
                    .isEqualTo(groupBoundary.getEpochSecond());
            groupBoundary = groupBoundary.plus(1, ChronoUnit.DAYS);
            assertThat(responses.get(i).getEndTime().getEpochSecond())
                    .isEqualTo(groupBoundary.getEpochSecond());
        }

        tearDown();
    }

    private void insertThreeWeightRecordsWithZoneOffset(Instant time, ZoneOffset offset)
            throws InterruptedException {
        TestUtils.insertRecords(
                List.of(
                        getWeightRecordWithTime(time.minus(1, ChronoUnit.HOURS), offset),
                        getWeightRecordWithTime(time.minus(27, ChronoUnit.HOURS), offset),
                        getWeightRecordWithTime(time.minus(55, ChronoUnit.HOURS), offset)));
    }

    @Test
    public void testAggregateLocalFilter_minOffsetRecord() throws Exception {
        LocalDateTime endTimeLocal = LocalDateTime.now(ZoneOffset.UTC);
        Instant endTimeInstant = Instant.now();

        AggregateRecordsResponse<Mass> response =
                TestUtils.getAggregateResponse(
                        new AggregateRecordsRequest.Builder<Mass>(
                                        new LocalTimeRangeFilter.Builder()
                                                .setStartTime(endTimeLocal.minusHours(25))
                                                .setEndTime(endTimeLocal.minusHours(15))
                                                .build())
                                .addAggregationType(WEIGHT_MAX)
                                .addAggregationType(WEIGHT_MIN)
                                .addAggregationType(WEIGHT_AVG)
                                .build(),
                        List.of(
                                new WeightRecord.Builder(
                                                TestUtils.generateMetadata(),
                                                endTimeInstant,
                                                Mass.fromGrams(10.0))
                                        .setZoneOffset(ZoneOffset.MIN)
                                        .build(),
                                new WeightRecord.Builder(
                                                TestUtils.generateMetadata(),
                                                endTimeInstant,
                                                Mass.fromGrams(20.0))
                                        .setZoneOffset(ZoneOffset.MIN)
                                        .build()));

        assertThat(response.get(WEIGHT_MAX)).isNotNull();
        assertThat(response.get(WEIGHT_MAX)).isEqualTo(Mass.fromGrams(20.0));
        assertThat(response.get(WEIGHT_MIN)).isNotNull();
        assertThat(response.get(WEIGHT_MIN)).isEqualTo(Mass.fromGrams(10.0));
        assertThat(response.get(WEIGHT_AVG)).isNotNull();
        assertThat(response.get(WEIGHT_AVG)).isEqualTo(Mass.fromGrams(15.0));
    }

    @Test
    public void testAggregateLocalFilter_offsetRecordAndFilter() throws Exception {
        testOffset(ZoneOffset.MAX);
        testOffset(ZoneOffset.ofHours(1));
        testOffset(ZoneOffset.UTC);
        testOffset(ZoneOffset.ofHours(-1));
        testOffset(ZoneOffset.MIN);
    }

    private void testOffset(ZoneOffset offset) throws InterruptedException {
        Instant endTimeInstant = Instant.now();
        LocalDateTime endTimeLocal = LocalDateTime.ofInstant(endTimeInstant, offset);

        AggregateRecordsResponse<Mass> response =
                TestUtils.getAggregateResponse(
                        new AggregateRecordsRequest.Builder<Mass>(
                                        new LocalTimeRangeFilter.Builder()
                                                .setStartTime(endTimeLocal.minusMinutes(1))
                                                .setEndTime(endTimeLocal.plusMinutes(1))
                                                .build())
                                .addAggregationType(WEIGHT_MAX)
                                .addAggregationType(WEIGHT_MIN)
                                .addAggregationType(WEIGHT_AVG)
                                .build(),
                        List.of(
                                new WeightRecord.Builder(
                                                TestUtils.generateMetadata(),
                                                endTimeInstant,
                                                Mass.fromGrams(10.0))
                                        .setZoneOffset(offset)
                                        .build(),
                                new WeightRecord.Builder(
                                                TestUtils.generateMetadata(),
                                                endTimeInstant,
                                                Mass.fromGrams(20.0))
                                        .setZoneOffset(offset)
                                        .build()));

        assertThat(response.get(WEIGHT_MAX)).isNotNull();
        assertThat(response.get(WEIGHT_MAX)).isEqualTo(Mass.fromGrams(20.0));
        assertThat(response.get(WEIGHT_MIN)).isNotNull();
        assertThat(response.get(WEIGHT_MIN)).isEqualTo(Mass.fromGrams(10.0));
        assertThat(response.get(WEIGHT_AVG)).isNotNull();
        assertThat(response.get(WEIGHT_AVG)).isEqualTo(Mass.fromGrams(15.0));
        TestUtils.verifyDeleteRecords(
                new DeleteUsingFiltersRequest.Builder().addRecordType(WeightRecord.class).build());
    }

    @Test
    public void testAggregateLocalFilter_daysPeriod() throws Exception {
        LocalDateTime endTimeLocal = LocalDateTime.now(ZoneOffset.UTC);
        Instant endTimeInstant = Instant.now();
        TestUtils.insertRecords(
                List.of(
                        new WeightRecord.Builder(
                                TestUtils.generateMetadata(),
                                endTimeInstant.minus(20, ChronoUnit.DAYS),
                                Mass.fromGrams(10.0))
                                .setZoneOffset(ZoneOffset.MIN)
                                .build()));

        List<AggregateRecordsGroupedByPeriodResponse<Mass>> responses =
                TestUtils.getAggregateResponseGroupByPeriod(
                        new AggregateRecordsRequest.Builder<Mass>(
                                new LocalTimeRangeFilter.Builder()
                                        .setStartTime(endTimeLocal.minusDays(30))
                                        .setEndTime(endTimeLocal)
                                        .build())
                                .addAggregationType(WEIGHT_MAX)
                                .build(),
                        Period.ofDays(15));

        assertThat(responses).hasSize(2);
        assertThat(responses.get(0).get(WEIGHT_MAX)).isEqualTo(Mass.fromGrams(10.0));
        assertThat(responses.get(1).get(WEIGHT_MAX)).isNull();
    }

    private void readWeightRecordUsingClientId(List<Record> insertedRecord)
            throws InterruptedException {
        ReadRecordsRequestUsingIds.Builder<WeightRecord> request =
                new ReadRecordsRequestUsingIds.Builder<>(WeightRecord.class);
        for (Record record : insertedRecord) {
            request.addClientRecordId(record.getMetadata().getClientRecordId());
        }
        List<WeightRecord> result = TestUtils.readRecords(request.build());
        assertThat(result.size()).isEqualTo(insertedRecord.size());
        assertThat(result).containsExactlyElementsIn(insertedRecord);
    }

    private void readWeightRecordUsingIds(List<Record> recordList) throws InterruptedException {
        ReadRecordsRequestUsingIds.Builder<WeightRecord> request =
                new ReadRecordsRequestUsingIds.Builder<>(WeightRecord.class);
        for (Record record : recordList) {
            request.addId(record.getMetadata().getId());
        }
        ReadRecordsRequestUsingIds requestUsingIds = request.build();
        assertThat(requestUsingIds.getRecordType()).isEqualTo(WeightRecord.class);
        assertThat(requestUsingIds.getRecordIdFilters()).isNotNull();
        List<WeightRecord> result = TestUtils.readRecords(requestUsingIds);
        assertThat(result).hasSize(recordList.size());
        assertThat(result).containsExactlyElementsIn(recordList);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testCreateWeightRecord_invalidValue() {
        new WeightRecord.Builder(
                        new Metadata.Builder().build(), Instant.now(), Mass.fromGrams(1000000.1))
                .build();
    }

    WeightRecord getWeightRecord_update(Record record, String id, String clientRecordId) {
        Metadata metadata = record.getMetadata();
        Metadata metadataWithId =
                new Metadata.Builder()
                        .setId(id)
                        .setClientRecordId(clientRecordId)
                        .setClientRecordVersion(metadata.getClientRecordVersion())
                        .setDataOrigin(metadata.getDataOrigin())
                        .setDevice(metadata.getDevice())
                        .setLastModifiedTime(metadata.getLastModifiedTime())
                        .build();
        return new WeightRecord.Builder(metadataWithId, Instant.now(), Mass.fromGrams(20.0))
                .setZoneOffset(ZoneOffset.systemDefault().getRules().getOffset(Instant.now()))
                .build();
    }

    private static WeightRecord getBaseWeightRecord() {
        return new WeightRecord.Builder(
                        new Metadata.Builder().build(), Instant.now(), Mass.fromGrams(10.0))
                .build();
    }

    static WeightRecord getBaseWeightRecord(Instant time, double weight) {
        return new WeightRecord.Builder(
                        new Metadata.Builder().build(), time, Mass.fromGrams(weight))
                .build();
    }

    static WeightRecord getBaseWeightRecord(double weight) {
        return new WeightRecord.Builder(
                        new Metadata.Builder().setClientRecordId("WR" + Math.random()).build(),
                        Instant.now(),
                        Mass.fromGrams(weight))
                .build();
    }

    private static WeightRecord getCompleteWeightRecord() {
        return getWeightRecordWithTime(Instant.now());
    }

    private static WeightRecord getWeightRecordWithTime(Instant time) {
        return getWeightRecordWithTime(
                time, ZoneOffset.systemDefault().getRules().getOffset(Instant.now()));
    }

    private static WeightRecord getWeightRecordWithTime(Instant time, ZoneOffset offset) {
        Device device =
                new Device.Builder()
                        .setManufacturer("google")
                        .setModel("Pixel4a")
                        .setType(2)
                        .build();
        DataOrigin dataOrigin =
                new DataOrigin.Builder().setPackageName("android.healthconnect.cts").build();
        Metadata.Builder testMetadataBuilder = new Metadata.Builder();
        testMetadataBuilder.setDevice(device).setDataOrigin(dataOrigin);
        testMetadataBuilder.setClientRecordId("WR" + Math.random());
        testMetadataBuilder.setRecordingMethod(Metadata.RECORDING_METHOD_ACTIVELY_RECORDED);

        return new WeightRecord.Builder(testMetadataBuilder.build(), time, Mass.fromGrams(10.0))
                .setZoneOffset(offset)
                .build();
    }
}