aboutsummaryrefslogtreecommitdiff
path: root/tests/src/com/android/providers/contacts/BaseContactsProvider2Test.java
blob: 7c9f9d8d5fe395c1b4f388039a72b47bdc3de571 (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
/*
 * Copyright (C) 2009 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 com.android.providers.contacts;

import static com.android.providers.contacts.ContactsActor.PACKAGE_GREY;

import android.accounts.Account;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Entity;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.AggregationExceptions;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.Presence;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.Settings;
import android.provider.ContactsContract.StatusUpdates;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.test.AndroidTestCase;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

/**
 * A common superclass for {@link ContactsProvider2}-related tests.
 */
@LargeTest
public abstract class BaseContactsProvider2Test extends AndroidTestCase {

    protected static final String PACKAGE = "ContactsProvider2Test";

    protected ContactsActor mActor;
    protected MockContentResolver mResolver;
    protected Account mAccount = new Account("account1", "account type1");
    protected Account mAccountTwo = new Account("account2", "account type2");

    private byte[] mTestPhoto;

    protected final static Long NO_LONG = new Long(0);
    protected final static String NO_STRING = new String("");
    protected final static Account NO_ACCOUNT = new Account("a", "b");

    protected Class<? extends ContentProvider> getProviderClass() {
        return SynchronousContactsProvider2.class;
    }

    protected String getAuthority() {
        return ContactsContract.AUTHORITY;
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mActor = new ContactsActor(getContext(), PACKAGE_GREY, getProviderClass(), getAuthority());
        mResolver = mActor.resolver;
        if (mActor.provider instanceof SynchronousContactsProvider2) {
            ((SynchronousContactsProvider2) mActor.provider)
                    .getDatabaseHelper(mActor.context).wipeData();
        }
    }

    public Context getMockContext() {
        return mActor.context;
    }

    public void addAuthority(String authority) {
        mActor.addAuthority(authority);
    }

    public ContentProvider addProvider(Class<? extends ContentProvider> providerClass,
            String authority) throws Exception {
        return mActor.addProvider(providerClass, authority);
    }

    public ContentProvider getProvider() {
        return mActor.provider;
    }

    protected Uri maybeAddAccountQueryParameters(Uri uri, Account account) {
        if (account == null) {
            return uri;
        }
        return uri.buildUpon()
                .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
                .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
                .build();
    }

    protected long createRawContact() {
        return createRawContact(null);
    }

    protected long createRawContactWithName() {
        return createRawContactWithName("John", "Doe");
    }

    protected long createRawContactWithName(String firstName, String lastName) {
        long rawContactId = createRawContact(null);
        insertStructuredName(rawContactId, firstName, lastName);
        return rawContactId;
    }

    protected long createRawContact(Account account, String... extras) {
        ContentValues values = new ContentValues();
        for (int i = 0; i < extras.length; ) {
            values.put(extras[i], extras[i + 1]);
            i += 2;
        }
        final Uri uri = maybeAddAccountQueryParameters(RawContacts.CONTENT_URI, account);
        Uri contactUri = mResolver.insert(uri, values);
        return ContentUris.parseId(contactUri);
    }

    protected long createGroup(Account account, String sourceId, String title) {
        return createGroup(account, sourceId, title, 1);
    }

    protected long createGroup(Account account, String sourceId, String title, int visible) {
        ContentValues values = new ContentValues();
        values.put(Groups.SOURCE_ID, sourceId);
        values.put(Groups.TITLE, title);
        values.put(Groups.GROUP_VISIBLE, visible);
        final Uri uri = maybeAddAccountQueryParameters(Groups.CONTENT_URI, account);
        return ContentUris.parseId(mResolver.insert(uri, values));
    }

    protected void createSettings(Account account, String shouldSync, String ungroupedVisible) {
        ContentValues values = new ContentValues();
        values.put(Settings.ACCOUNT_NAME, account.name);
        values.put(Settings.ACCOUNT_TYPE, account.type);
        values.put(Settings.SHOULD_SYNC, shouldSync);
        values.put(Settings.UNGROUPED_VISIBLE, ungroupedVisible);
        mResolver.insert(Settings.CONTENT_URI, values);
    }

    protected Uri insertStructuredName(long rawContactId, String givenName, String familyName) {
        ContentValues values = new ContentValues();
        StringBuilder sb = new StringBuilder();
        if (givenName != null) {
            sb.append(givenName);
        }
        if (givenName != null && familyName != null) {
            sb.append(" ");
        }
        if (familyName != null) {
            sb.append(familyName);
        }
        values.put(StructuredName.DISPLAY_NAME, sb.toString());
        values.put(StructuredName.GIVEN_NAME, givenName);
        values.put(StructuredName.FAMILY_NAME, familyName);

        return insertStructuredName(rawContactId, values);
    }

    protected Uri insertStructuredName(long rawContactId, ContentValues values) {
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertOrganization(long rawContactId, ContentValues values) {
        return insertOrganization(rawContactId, values, false);
    }

    protected Uri insertOrganization(long rawContactId, ContentValues values, boolean primary) {
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE);
        values.put(Organization.TYPE, Organization.TYPE_WORK);
        if (primary) {
            values.put(Data.IS_PRIMARY, true);
        }

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertPhoneNumber(long rawContactId, String phoneNumber) {
        return insertPhoneNumber(rawContactId, phoneNumber, false);
    }

    protected Uri insertPhoneNumber(long rawContactId, String phoneNumber, boolean primary) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, phoneNumber);
        values.put(Phone.TYPE, Phone.TYPE_HOME);
        if (primary) {
            values.put(Data.IS_PRIMARY, true);
        }

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertEmail(long rawContactId, String email) {
        return insertEmail(rawContactId, email, false);
    }

    protected Uri insertEmail(long rawContactId, String email, boolean primary) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
        values.put(Email.DATA, email);
        values.put(Email.TYPE, Email.TYPE_HOME);
        if (primary) {
            values.put(Data.IS_PRIMARY, true);
        }

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertNickname(long rawContactId, String nickname) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE);
        values.put(Nickname.NAME, nickname);
        values.put(Nickname.TYPE, Nickname.TYPE_OTHER_NAME);

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertPostalAddress(long rawContactId, String formattedAddress) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE);
        values.put(StructuredPostal.FORMATTED_ADDRESS, formattedAddress);

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertPhoto(long rawContactId) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
        values.put(Photo.PHOTO, loadTestPhoto());
        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertGroupMembership(long rawContactId, String sourceId) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
        values.put(GroupMembership.GROUP_SOURCE_ID, sourceId);
        return mResolver.insert(Data.CONTENT_URI, values);
    }

    protected Uri insertGroupMembership(long rawContactId, Long groupId) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
        values.put(GroupMembership.GROUP_ROW_ID, groupId);
        return mResolver.insert(Data.CONTENT_URI, values);
    }

    protected Uri insertStatusUpdate(int protocol, String customProtocol, String handle,
            int presence, String status) {
        return insertStatusUpdate(protocol, customProtocol, handle, presence, status, 0);
    }

    protected Uri insertStatusUpdate(int protocol, String customProtocol, String handle,
            int presence, String status, long timestamp) {
        ContentValues values = new ContentValues();
        values.put(StatusUpdates.PROTOCOL, protocol);
        values.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol);
        values.put(StatusUpdates.IM_HANDLE, handle);
        if (presence != 0) {
            values.put(StatusUpdates.PRESENCE, presence);
        }
        if (status != null) {
            values.put(StatusUpdates.STATUS, status);
        }
        if (timestamp != 0) {
            values.put(StatusUpdates.STATUS_TIMESTAMP, timestamp);
        }

        Uri resultUri = mResolver.insert(StatusUpdates.CONTENT_URI, values);
        return resultUri;
    }

    protected Uri insertImHandle(long rawContactId, int protocol, String customProtocol,
            String handle) {
        ContentValues values = new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
        values.put(Im.PROTOCOL, protocol);
        values.put(Im.CUSTOM_PROTOCOL, customProtocol);
        values.put(Im.DATA, handle);
        values.put(Im.TYPE, Im.TYPE_HOME);

        Uri resultUri = mResolver.insert(Data.CONTENT_URI, values);
        return resultUri;
    }

    protected void setContactAccountName(long rawContactId, String accountName) {
        ContentValues values = new ContentValues();
        values.put(RawContacts.ACCOUNT_NAME, accountName);

        mResolver.update(ContentUris.withAppendedId(
                RawContacts.CONTENT_URI, rawContactId), values, null, null);
    }

    protected void setAggregationException(int type, long rawContactId1, long rawContactId2) {
        ContentValues values = new ContentValues();
        values.put(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1);
        values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2);
        values.put(AggregationExceptions.TYPE, type);
        assertEquals(1, mResolver.update(AggregationExceptions.CONTENT_URI, values, null, null));
    }

    protected Cursor queryRawContact(long rawContactId) {
        return mResolver.query(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
                null, null, null, null);
    }

    protected Cursor queryContact(long contactId) {
        return mResolver.query(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId),
                null, null, null, null);
    }

    protected Cursor queryContact(long contactId, String[] projection) {
        return mResolver.query(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId),
                projection, null, null, null);
    }

    protected long queryContactId(long rawContactId) {
        Cursor c = queryRawContact(rawContactId);
        assertTrue(c.moveToFirst());
        long contactId = c.getLong(c.getColumnIndex(RawContacts.CONTACT_ID));
        c.close();
        return contactId;
    }

    protected long queryPhotoId(long contactId) {
        Cursor c = queryContact(contactId);
        assertTrue(c.moveToFirst());
        long photoId = c.getInt(c.getColumnIndex(Contacts.PHOTO_ID));
        c.close();
        return photoId;
    }

    protected String queryDisplayName(long contactId) {
        Cursor c = queryContact(contactId);
        assertTrue(c.moveToFirst());
        String displayName = c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME));
        c.close();
        return displayName;
    }

    protected void assertAggregated(long rawContactId1, long rawContactId2) {
        forceAggregation();
        long contactId1 = queryContactId(rawContactId1);
        long contactId2 = queryContactId(rawContactId2);
        assertTrue(contactId1 == contactId2);
    }

    protected void assertAggregated(long rawContactId1, long rawContactId2,
            String expectedDisplayName) {
        forceAggregation();

        long contactId1 = queryContactId(rawContactId1);
        long contactId2 = queryContactId(rawContactId2);
        assertTrue(contactId1 == contactId2);

        String displayName = queryDisplayName(contactId1);
        assertEquals(expectedDisplayName, displayName);
    }

    protected void assertNotAggregated(long rawContactId1, long rawContactId2) {
        forceAggregation();

        long contactId1 = queryContactId(rawContactId1);
        long contactId2 = queryContactId(rawContactId2);
        assertTrue(contactId1 != contactId2);
    }

    protected void assertStructuredName(long rawContactId, String prefix, String givenName,
            String middleName, String familyName, String suffix) {
        Uri uri =
                Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
                RawContacts.Data.CONTENT_DIRECTORY);

        final String[] projection = new String[] {
                StructuredName.PREFIX, StructuredName.GIVEN_NAME, StructuredName.MIDDLE_NAME,
                StructuredName.FAMILY_NAME, StructuredName.SUFFIX
        };

        Cursor c = mResolver.query(uri, projection, Data.MIMETYPE + "='"
                + StructuredName.CONTENT_ITEM_TYPE + "'", null, null);

        assertTrue(c.moveToFirst());
        assertEquals(prefix, c.getString(0));
        assertEquals(givenName, c.getString(1));
        assertEquals(middleName, c.getString(2));
        assertEquals(familyName, c.getString(3));
        assertEquals(suffix, c.getString(4));
        c.close();
    }

    protected long assertSingleGroup(Long rowId, Account account, String sourceId, String title) {
        Cursor c = mResolver.query(Groups.CONTENT_URI, null, null, null, null);
        try {
            assertTrue(c.moveToNext());
            long actualRowId = assertGroup(c, rowId, account, sourceId, title);
            assertFalse(c.moveToNext());
            return actualRowId;
        } finally {
            c.close();
        }
    }

    protected long assertSingleGroupMembership(Long rowId, Long rawContactId, Long groupRowId,
            String sourceId) {
        Cursor c = mResolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
        try {
            assertTrue(c.moveToNext());
            long actualRowId = assertGroupMembership(c, rowId, rawContactId, groupRowId, sourceId);
            assertFalse(c.moveToNext());
            return actualRowId;
        } finally {
            c.close();
        }
    }

    protected long assertGroupMembership(Cursor c, Long rowId, Long rawContactId, Long groupRowId,
            String sourceId) {
        assertNullOrEquals(c, rowId, Data._ID);
        assertNullOrEquals(c, rawContactId, GroupMembership.RAW_CONTACT_ID);
        assertNullOrEquals(c, groupRowId, GroupMembership.GROUP_ROW_ID);
        assertNullOrEquals(c, sourceId, GroupMembership.GROUP_SOURCE_ID);
        return c.getLong(c.getColumnIndexOrThrow("_id"));
    }

    protected long assertGroup(Cursor c, Long rowId, Account account, String sourceId, String title) {
        assertNullOrEquals(c, rowId, Groups._ID);
        assertNullOrEquals(c, account);
        assertNullOrEquals(c, sourceId, Groups.SOURCE_ID);
        assertNullOrEquals(c, title, Groups.TITLE);
        return c.getLong(c.getColumnIndexOrThrow("_id"));
    }

    private void assertNullOrEquals(Cursor c, Account account) {
        if (account == NO_ACCOUNT) {
            return;
        }
        if (account == null) {
            assertTrue(c.isNull(c.getColumnIndexOrThrow(Groups.ACCOUNT_NAME)));
            assertTrue(c.isNull(c.getColumnIndexOrThrow(Groups.ACCOUNT_TYPE)));
        } else {
            assertEquals(account.name, c.getString(c.getColumnIndexOrThrow(Groups.ACCOUNT_NAME)));
            assertEquals(account.type, c.getString(c.getColumnIndexOrThrow(Groups.ACCOUNT_TYPE)));
        }
    }

    private void assertNullOrEquals(Cursor c, Long value, String columnName) {
        if (value != NO_LONG) {
            if (value == null) assertTrue(c.isNull(c.getColumnIndexOrThrow(columnName)));
            else assertEquals((long) value, c.getLong(c.getColumnIndexOrThrow(columnName)));
        }
    }

    private void assertNullOrEquals(Cursor c, String value, String columnName) {
        if (value != NO_STRING) {
            if (value == null) assertTrue(c.isNull(c.getColumnIndexOrThrow(columnName)));
            else assertEquals(value, c.getString(c.getColumnIndexOrThrow(columnName)));
        }
    }

    protected void assertDataRow(ContentValues actual, String expectedMimetype,
            Object... expectedArguments) {
        assertEquals(actual.toString(), expectedMimetype, actual.getAsString(Data.MIMETYPE));
        for (int i = 0; i < expectedArguments.length; i += 2) {
            String columnName = (String) expectedArguments[i];
            Object expectedValue = expectedArguments[i + 1];
            if (expectedValue instanceof Uri) {
                expectedValue = ContentUris.parseId((Uri) expectedValue);
            }
            if (expectedValue == null) {
                assertNull(actual.toString(), actual.get(columnName));
            }
            if (expectedValue instanceof Long) {
                assertEquals("mismatch at " + columnName + " from " + actual.toString(),
                        expectedValue, actual.getAsLong(columnName));
            } else if (expectedValue instanceof Integer) {
                assertEquals("mismatch at " + columnName + " from " + actual.toString(),
                        expectedValue, actual.getAsInteger(columnName));
            } else if (expectedValue instanceof String) {
                assertEquals("mismatch at " + columnName + " from " + actual.toString(),
                        expectedValue, actual.getAsString(columnName));
            } else {
                assertEquals("mismatch at " + columnName + " from " + actual.toString(),
                        expectedValue, actual.get(columnName));
            }
        }
    }

    protected static class IdComparator implements Comparator<ContentValues> {
        public int compare(ContentValues o1, ContentValues o2) {
            long id1 = o1.getAsLong(ContactsContract.Data._ID);
            long id2 = o2.getAsLong(ContactsContract.Data._ID);
            if (id1 == id2) return 0;
            return (id1 < id2) ? -1 : 1;
        }
    }

    protected ContentValues[] asSortedContentValuesArray(
            ArrayList<Entity.NamedContentValues> subValues) {
        ContentValues[] result = new ContentValues[subValues.size()];
        int i = 0;
        for (Entity.NamedContentValues subValue : subValues) {
            result[i] = subValue.values;
            i++;
        }
        Arrays.sort(result, new IdComparator());
        return result;
    }

    protected void assertDirty(Uri uri, boolean state) {
        Cursor c = mResolver.query(uri, new String[]{"dirty"}, null, null, null);
        assertTrue(c.moveToNext());
        assertEquals(state, c.getLong(0) != 0);
        assertFalse(c.moveToNext());
        c.close();
    }

    protected long getVersion(Uri uri) {
        Cursor c = mResolver.query(uri, new String[]{"version"}, null, null, null);
        assertTrue(c.moveToNext());
        long version = c.getLong(0);
        assertFalse(c.moveToNext());
        c.close();
        return version;
    }

    protected void clearDirty(Uri uri) {
        ContentValues values = new ContentValues();
        values.put("dirty", 0);
        mResolver.update(uri, values, null, null);
    }

    protected void storeValue(Uri contentUri, long id, String column, String value) {
        ContentValues values = new ContentValues();
        values.put(column, value);

        mResolver.update(ContentUris.withAppendedId(contentUri, id), values, null, null);
    }

    protected void assertStoredValue(Uri rowUri, String column, Object expectedValue) {
        String value = getStoredValue(rowUri, column);
        if (expectedValue == null) {
            assertNull("Column value " + column, value);
        } else {
            assertEquals("Column value " + column, String.valueOf(expectedValue), value);
        }
    }

    protected void assertStoredValue(Uri rowUri, String selection, String[] selectionArgs,
            String column, Object expectedValue) {
        String value = getStoredValue(rowUri, selection, selectionArgs, column);
        if (expectedValue == null) {
            assertNull("Column value " + column, value);
        } else {
            assertEquals("Column value " + column, String.valueOf(expectedValue), value);
        }
    }

    protected String getStoredValue(Uri rowUri, String column) {
        return getStoredValue(rowUri, null, null, column);
    }

    protected String getStoredValue(Uri uri, String selection, String[] selectionArgs,
            String column) {
        String value = null;
        Cursor c = mResolver.query(uri, new String[] { column }, selection, selectionArgs, null);
        try {
            if (c.moveToFirst()) {
                value = c.getString(c.getColumnIndex(column));
            }
        } finally {
            c.close();
        }
        return value;
    }

    protected void assertStoredValues(Uri rowUri, ContentValues expectedValues) {
        assertStoredValues(rowUri, null, null, expectedValues);
    }

    protected void assertStoredValues(Uri rowUri, String selection, String[] selectionArgs,
            ContentValues expectedValues) {
        Cursor c = mResolver.query(rowUri, null, selection, selectionArgs, null);
        try {
            assertEquals("Record count", 1, c.getCount());
            c.moveToFirst();
            assertCursorValues(c, expectedValues);
        } finally {
            c.close();
        }
    }

    protected void assertStoredValuesWithProjection(Uri rowUri, ContentValues expectedValues) {
        Cursor c = mResolver.query(rowUri, buildProjection(expectedValues), null, null, null);
        try {
            assertEquals("Record count", 1, c.getCount());
            c.moveToFirst();
            assertCursorValues(c, expectedValues);
        } finally {
            c.close();
        }
    }

    /**
     * Constructs a selection (where clause) out of all supplied values, uses it
     * to query the provider and verifies that a single row is returned and it
     * has the same values as requested.
     */
    protected void assertSelection(Uri uri, ContentValues values, String idColumn, long id) {
        assertSelection(uri, values, idColumn, id, null);
    }

    public void assertSelectionWithProjection(Uri uri, ContentValues values, String idColumn,
            long id) {
        assertSelection(uri, values, idColumn, id, buildProjection(values));
    }

    private void assertSelection(Uri uri, ContentValues values, String idColumn, long id,
            String[] projection) {
        StringBuilder sb = new StringBuilder();
        ArrayList<String> selectionArgs = new ArrayList<String>(values.size());
        if (idColumn != null) {
            sb.append(idColumn).append("=").append(id);
        }
        Set<Map.Entry<String, Object>> entries = values.valueSet();
        for (Map.Entry<String, Object> entry : entries) {
            String column = entry.getKey();
            Object value = entry.getValue();
            if (sb.length() != 0) {
                sb.append(" AND ");
            }
            sb.append(column);
            if (value == null) {
                sb.append(" IS NULL");
            } else {
                sb.append("=?");
                selectionArgs.add(String.valueOf(value));
            }
        }

        Cursor c = mResolver.query(uri, projection, sb.toString(), selectionArgs.toArray(new String[0]),
                null);
        try {
            assertEquals("Record count", 1, c.getCount());
            c.moveToFirst();
            assertCursorValues(c, values);
        } finally {
            c.close();
        }
    }

    protected void assertCursorValues(Cursor cursor, ContentValues expectedValues) {
        Set<Map.Entry<String, Object>> entries = expectedValues.valueSet();
        for (Map.Entry<String, Object> entry : entries) {
            String column = entry.getKey();
            int index = cursor.getColumnIndex(column);
            assertTrue("No such column: " + column, index != -1);
            Object expectedValue = expectedValues.get(column);
            String value;
            if (expectedValue instanceof byte[]) {
                expectedValue = Hex.encodeHex((byte[])expectedValue, false);
                value = Hex.encodeHex(cursor.getBlob(index), false);
            } else {
                expectedValue = expectedValues.getAsString(column);
                value = cursor.getString(index);
            }
            assertEquals("Column value " + column, expectedValue, value);
        }
    }

    private String[] buildProjection(ContentValues values) {
        String[] projection = new String[values.size()];
        Iterator<Entry<String, Object>> iter = values.valueSet().iterator();
        for (int i = 0; i < projection.length; i++) {
            projection[i] = iter.next().getKey();
        }
        return projection;
    }

    protected int getCount(Uri uri, String selection, String[] selectionArgs) {
        Cursor c = mResolver.query(uri, null, selection, selectionArgs, null);
        try {
            return c.getCount();
        } finally {
            c.close();
        }
    }

    protected byte[] loadTestPhoto() {
        if (mTestPhoto == null) {
            final Resources resources = getContext().getResources();
            InputStream is = resources
                    .openRawResource(com.android.internal.R.drawable.ic_contact_picture);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] buffer = new byte[1000];
            int count;
            try {
                while ((count = is.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            mTestPhoto = os.toByteArray();
        }
        return mTestPhoto;
    }

    public static void dump(ContentResolver resolver, boolean aggregatedOnly) {
        String[] projection = new String[] {
                Contacts._ID,
                Contacts.DISPLAY_NAME
        };
        String selection = null;
        if (aggregatedOnly) {
            selection = Contacts._ID
                    + " IN (SELECT contact_id" +
                    		" FROM raw_contacts GROUP BY contact_id HAVING count(*) > 1)";
        }

        Cursor c = resolver.query(Contacts.CONTENT_URI, projection, selection, null,
                Contacts.DISPLAY_NAME);
        while(c.moveToNext()) {
            long contactId = c.getLong(0);
            Log.i("Contact   ", String.format("%5d %s", contactId, c.getString(1)));
            dumpRawContacts(resolver, contactId);
            Log.i("          ", ".");
        }
        c.close();
    }

    private static void dumpRawContacts(ContentResolver resolver, long contactId) {
        String[] projection = new String[] {
                RawContacts._ID,
        };
        Cursor c = resolver.query(RawContacts.CONTENT_URI, projection, RawContacts.CONTACT_ID + "="
                + contactId, null, null);
        while(c.moveToNext()) {
            long rawContactId = c.getLong(0);
            Log.i("RawContact", String.format("      %-5d", rawContactId));
            dumpData(resolver, rawContactId);
        }
        c.close();
    }

    private static void dumpData(ContentResolver resolver, long rawContactId) {
        String[] projection = new String[] {
                Data.MIMETYPE,
                Data.DATA1,
                Data.DATA2,
                Data.DATA3,
        };
        Cursor c = resolver.query(Data.CONTENT_URI, projection, Data.RAW_CONTACT_ID + "="
                + rawContactId, null, Data.MIMETYPE);
        while(c.moveToNext()) {
            String mimetype = c.getString(0);
            if (Photo.CONTENT_ITEM_TYPE.equals(mimetype)) {
                Log.i("Photo     ", "");
            } else {
                mimetype = mimetype.substring(mimetype.indexOf('/') + 1);
                Log.i("Data      ", String.format("            %-10s %s,%s,%s", mimetype,
                        c.getString(1), c.getString(2), c.getString(3)));
            }
        }
        c.close();
    }

    protected void forceAggregation() {
        ((SynchronousContactsProvider2) mActor.provider).aggregate();
    }

    protected void assertNetworkNotified(boolean expected) {
        assertEquals(expected, ((SynchronousContactsProvider2)mActor.provider).isNetworkNotified());
    }
}