/
SQLiteDatabaseTest.java
240 lines (214 loc) · 7.9 KB
/
SQLiteDatabaseTest.java
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
package android.database;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.google.common.truth.Truth.assertThat;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertThrows;
import android.content.ContentValues;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SdkSuppress;
import com.google.common.base.Ascii;
import com.google.common.base.Throwables;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.internal.DoNotInstrument;
/** Compatibility test for {@link android.database.sqlite.SQLiteDatabase} */
@DoNotInstrument
@RunWith(AndroidJUnit4.class)
public class SQLiteDatabaseTest {
private SQLiteDatabase database;
private File databasePath;
@Before
public void setUp() {
databasePath = ApplicationProvider.getApplicationContext().getDatabasePath("database.db");
databasePath.getParentFile().mkdirs();
database = SQLiteDatabase.openOrCreateDatabase(databasePath, null);
database.execSQL(
"CREATE TABLE table_name (\n"
+ " id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
+ " first_column VARCHAR(255),\n"
+ " second_column BINARY,\n"
+ " name VARCHAR(255),\n"
+ " big_int INTEGER\n"
+ ");");
}
@After
public void tearDown() {
database.close();
assertThat(databasePath.delete()).isTrue();
}
@Test
public void shouldGetBlobFromString() {
String s = "this is a string";
ContentValues values = new ContentValues();
values.put("first_column", s);
database.insert("table_name", null, values);
try (Cursor data =
database.query("table_name", new String[] {"first_column"}, null, null, null, null, null)) {
assertThat(data.getCount()).isEqualTo(1);
data.moveToFirst();
byte[] columnBytes = data.getBlob(0);
byte[] expected = Arrays.copyOf(s.getBytes(), s.length() + 1); // include zero-terminal
assertThat(columnBytes).isEqualTo(expected);
}
}
@Test
public void shouldGetBlobFromNullString() {
ContentValues values = new ContentValues();
values.put("first_column", (String) null);
database.insert("table_name", null, values);
try (Cursor data =
database.query("table_name", new String[] {"first_column"}, null, null, null, null, null)) {
assertThat(data.getCount()).isEqualTo(1);
data.moveToFirst();
assertThat(data.getBlob(0)).isEqualTo(null);
}
}
@Test
public void shouldGetBlobFromEmptyString() {
ContentValues values = new ContentValues();
values.put("first_column", "");
database.insert("table_name", null, values);
try (Cursor data =
database.query("table_name", new String[] {"first_column"}, null, null, null, null, null)) {
assertThat(data.getCount()).isEqualTo(1);
data.moveToFirst();
assertThat(data.getBlob(0)).isEqualTo(new byte[] {0});
}
}
@Test
public void shouldThrowWhenForeignKeysConstraintIsViolated() {
database.execSQL(
"CREATE TABLE artist(\n"
+ " artistid INTEGER PRIMARY KEY, \n"
+ " artistname TEXT\n"
+ ");\n");
database.execSQL(
"CREATE TABLE track(\n"
+ " trackid INTEGER, \n"
+ " trackname TEXT, \n"
+ " trackartist INTEGER,\n"
+ " FOREIGN KEY(trackartist) REFERENCES artist(artistid)\n"
+ ");");
database.execSQL("PRAGMA foreign_keys=ON");
database.execSQL("INSERT into artist (artistid, artistname) VALUES (1, 'Kanye')");
database.execSQL(
"INSERT into track (trackid, trackname, trackartist) VALUES (1, 'Good Life', 1)");
SQLiteConstraintException ex =
assertThrows(SQLiteConstraintException.class, () -> database.execSQL("delete from artist"));
assertThat(Ascii.toLowerCase(Throwables.getStackTraceAsString(ex))).contains("foreign key");
}
@Test
public void shouldDeleteWithLikeEscape() {
ContentValues values = new ContentValues();
values.put("first_column", "test");
database.insert("table_name", null, values);
String select = "first_column LIKE ? ESCAPE ?";
String[] selectArgs = {
"test", Character.toString('\\'),
};
assertThat(database.delete("table_name", select, selectArgs)).isEqualTo(1);
}
@Test
public void shouldThrowsExceptionWhenQueryingUsingExecSQL() {
SQLiteException e = assertThrows(SQLiteException.class, () -> database.execSQL("select 1"));
assertThat(e)
.hasMessageThat()
.contains("Queries can be performed using SQLiteDatabase query or rawQuery methods only.");
}
@Test
public void close_withExclusiveLockingMode() {
database.rawQuery("PRAGMA locking_mode = EXCLUSIVE", new String[0]).close();
ContentValues values = new ContentValues();
values.put("first_column", "");
database.insert("table_name", null, values);
database.close();
database = SQLiteDatabase.openOrCreateDatabase(databasePath, null);
database.insert("table_name", null, values);
}
static class MyCursorWindow extends CursorWindow {
public MyCursorWindow(String name) {
super(name);
}
/** Make the finalize method public */
@Override
public void finalize() throws Throwable {
super.finalize();
}
}
// TODO(hoisie): This test crashes in emulators, enable when it is fixed in Android.
@SdkSuppress(minSdkVersion = 34)
@Test
public void cursorWindow_finalize_concurrentStressTest() throws Throwable {
final PrintStream originalErr = System.err;
// discard stderr output for this test to prevent CloseGuard logspam.
System.setErr(new PrintStream(ByteStreams.nullOutputStream()));
try {
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 1000; i++) {
final MyCursorWindow cursorWindow = new MyCursorWindow(String.valueOf(i));
for (int j = 0; j < 4; j++) {
executor.execute(
() -> {
try {
cursorWindow.finalize();
} catch (Throwable e) {
throw new AssertionError(e);
}
});
}
}
executor.shutdown();
executor.awaitTermination(100, SECONDS);
} finally {
System.setErr(originalErr);
}
}
@Test
@Config(minSdk = LOLLIPOP)
@SdkSuppress(minSdkVersion = LOLLIPOP)
public void collate_unicode() {
String[] names = new String[] {"aaa", "abc", "ABC", "bbb"};
for (String name : names) {
ContentValues values = new ContentValues();
values.put("name", name);
database.insert("table_name", null, values);
}
Cursor c =
database.rawQuery("SELECT name from table_name ORDER BY name COLLATE UNICODE ASC", null);
c.moveToFirst();
ArrayList<String> sorted = new ArrayList<>();
while (!c.isAfterLast()) {
sorted.add(c.getString(0));
c.moveToNext();
}
c.close();
assertThat(sorted).containsExactly("aaa", "abc", "ABC", "bbb").inOrder();
}
@Test
@Config(minSdk = LOLLIPOP)
@SdkSuppress(minSdkVersion = LOLLIPOP)
public void regex_selection() {
ContentValues values = new ContentValues();
values.put("first_column", "test");
database.insert("table_name", null, values);
String select = "first_column regexp ?";
String[] selectArgs = {
"test",
};
assertThat(database.delete("table_name", select, selectArgs)).isEqualTo(1);
}
}