forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDBTest.java
361 lines (300 loc) · 13.9 KB
/
DBTest.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
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
/*
* Copyright 2008-present MongoDB, Inc.
*
* 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.mongodb;
import com.mongodb.client.model.Collation;
import com.mongodb.client.model.CollationAlternate;
import com.mongodb.client.model.CollationCaseFirst;
import com.mongodb.client.model.CollationMaxVariable;
import com.mongodb.client.model.CollationStrength;
import com.mongodb.internal.operation.ListCollectionsOperation;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.UuidRepresentation;
import org.bson.codecs.BsonDocumentCodec;
import org.junit.Test;
import java.util.Locale;
import java.util.UUID;
import static com.mongodb.ClusterFixture.disableMaxTimeFailPoint;
import static com.mongodb.ClusterFixture.enableMaxTimeFailPoint;
import static com.mongodb.ClusterFixture.getBinding;
import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet;
import static com.mongodb.ClusterFixture.isSharded;
import static com.mongodb.DBObjectMatchers.hasFields;
import static com.mongodb.DBObjectMatchers.hasSubdocument;
import static com.mongodb.Fixture.getDefaultDatabaseName;
import static com.mongodb.Fixture.getMongoClient;
import static com.mongodb.ReadPreference.secondary;
import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import static org.junit.Assume.assumeTrue;
@SuppressWarnings("deprecation")
public class DBTest extends DatabaseTestCase {
static final String LEGACY_HELLO = "isMaster";
static final String LEGACY_HELLO_LOWER = LEGACY_HELLO.toLowerCase(Locale.ROOT);
@Test
public void shouldGetDefaultWriteConcern() {
assertEquals(WriteConcern.ACKNOWLEDGED, database.getWriteConcern());
}
@Test
public void shouldGetDefaultReadPreference() {
assertEquals(ReadPreference.primary(), database.getReadPreference());
}
@Test
public void shouldGetMongoClient() {
assertEquals(getMongoClient(), database.getMongoClient());
}
@Test
public void shouldReturnCachedCollectionObjectIfExists() {
DBCollection collection1 = database.getCollection("test");
DBCollection collection2 = database.getCollection("test");
assertThat("Checking that references are equal", collection1, sameInstance(collection2));
}
@Test
public void shouldDropItself() {
// when
String databaseName = "drop-test-" + System.nanoTime();
DB db = getMongoClient().getDB(databaseName);
db.createCollection(collectionName, new BasicDBObject());
// then
assertThat(getMongoClient().listDatabaseNames(), hasItem(databaseName));
// when
db.dropDatabase();
// then
assertThat(getMongoClient().listDatabaseNames(), not(hasItem(databaseName)));
}
@Test
public void shouldGetCollectionNames() {
database.dropDatabase();
String[] collectionNames = {"c1", "c2", "c3"};
for (final String name : collectionNames) {
database.createCollection(name, new BasicDBObject());
}
assertThat(database.getCollectionNames(), hasItems(collectionNames));
}
@Test
public void shouldDeferCollectionCreationIfOptionsIsNull() {
collection.drop();
database.createCollection(collectionName, null);
assertFalse(database.getCollectionNames().contains(collectionName));
}
@Test
public void shouldCreateCappedCollection() {
collection.drop();
database.createCollection(collectionName, new BasicDBObject("capped", true)
.append("size", 242880));
assertTrue(isCapped(database.getCollection(collectionName)));
}
@Test
public void shouldCreateCappedCollectionWithMaxNumberOfDocuments() {
collection.drop();
DBCollection cappedCollectionWithMax = database.createCollection(collectionName, new BasicDBObject("capped", true)
.append("size", 242880)
.append("max", 10));
assertThat(storageStats(cappedCollectionWithMax), hasSubdocument(new BasicDBObject("capped", true).append("max", 10)));
for (int i = 0; i < 11; i++) {
cappedCollectionWithMax.insert(new BasicDBObject("x", i));
}
assertThat(cappedCollectionWithMax.find().count(), is(10));
}
@Test
public void shouldCreateUncappedCollection() {
collection.drop();
BasicDBObject creationOptions = new BasicDBObject("capped", false);
database.createCollection(collectionName, creationOptions);
assertFalse(isCapped(database.getCollection(collectionName)));
}
@Test(expected = MongoCommandException.class)
public void shouldThrowErrorIfCreatingACappedCollectionWithANegativeSize() {
collection.drop();
DBObject creationOptions = BasicDBObjectBuilder.start().add("capped", true)
.add("size", -20).get();
database.createCollection(collectionName, creationOptions);
}
@Test
public void shouldCreateCollectionWithTheSetCollation() {
// Given
collection.drop();
Collation collation = Collation.builder()
.locale("en")
.caseLevel(true)
.collationCaseFirst(CollationCaseFirst.OFF)
.collationStrength(CollationStrength.IDENTICAL)
.numericOrdering(true)
.collationAlternate(CollationAlternate.SHIFTED)
.collationMaxVariable(CollationMaxVariable.SPACE)
.backwards(true)
.build();
DBObject options = BasicDBObject.parse("{ collation: { locale: 'en', caseLevel: true, caseFirst: 'off', strength: 5,"
+ "numericOrdering: true, alternate: 'shifted', maxVariable: 'space', backwards: true }}");
// When
database.createCollection(collectionName, options);
BsonDocument collectionCollation = getCollectionInfo(collectionName).getDocument("options").getDocument("collation");
// Then
BsonDocument collationDocument = collation.asDocument();
for (String key: collationDocument.keySet()) {
assertEquals(collationDocument.get(key), collectionCollation.get(key));
}
// When - collation set on the database
database.getCollection(collectionName).drop();
database.createCollection(collectionName, new BasicDBObject("collation", BasicDBObject.parse(collation.asDocument().toJson())));
collectionCollation = getCollectionInfo(collectionName).getDocument("options").getDocument("collation");
// Then
collationDocument = collation.asDocument();
for (String key: collationDocument.keySet()) {
assertEquals(collationDocument.get(key), collectionCollation.get(key));
}
}
@Test(expected = DuplicateKeyException.class)
public void shouldGetDuplicateKeyException() {
DBObject doc = new BasicDBObject("_id", 1);
collection.insert(doc);
collection.insert(doc, WriteConcern.ACKNOWLEDGED);
}
@Test
public void shouldExecuteCommand() {
CommandResult commandResult = database.command(new BasicDBObject(LEGACY_HELLO, 1));
assertThat(commandResult, hasFields(new String[]{LEGACY_HELLO_LOWER, "maxBsonObjectSize", "ok"}));
}
@Test(expected = MongoExecutionTimeoutException.class)
public void shouldTimeOutCommand() {
assumeThat(isSharded(), is(false));
enableMaxTimeFailPoint();
try {
database.command(new BasicDBObject(LEGACY_HELLO, 1).append("maxTimeMS", 1));
} finally {
disableMaxTimeFailPoint();
}
}
@Test
public void shouldExecuteCommandWithReadPreference() {
assumeTrue(isDiscoverableReplicaSet());
CommandResult commandResult = database.command(new BasicDBObject("dbStats", 1).append("scale", 1), secondary());
assertThat(commandResult, hasFields(new String[]{"collections", "avgObjSize", "indexes", "db", "indexSize", "storageSize"}));
}
@Test
public void shouldNotThrowAnExceptionOnCommandFailure() {
CommandResult commandResult = database.command(new BasicDBObject("nonExistentCommand", 1));
assertThat(commandResult, hasFields(new String[]{"ok", "errmsg"}));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowAnExceptionWhenDBNameContainsSpaces() {
getMongoClient().getDB("foo bar");
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowAnExceptionWhenDBNameIsEmpty() {
getMongoClient().getDB("");
}
@Test
public void shouldIgnoreCaseWhenCheckingIfACollectionExists() {
// Given
database.getCollection("foo1").drop();
assertFalse(database.collectionExists("foo1"));
// When
database.createCollection("foo1", new BasicDBObject());
// Then
assertTrue(database.collectionExists("foo1"));
assertTrue(database.collectionExists("FOO1"));
assertTrue(database.collectionExists("fOo1"));
// Finally
database.getCollection("foo1").drop();
}
@Test
public void shouldReturnFailureWithErrorMessageWhenExecutingInvalidCommand() {
assumeTrue(!isSharded());
// When
CommandResult commandResult = database.command(new BasicDBObject("NotRealCommandName", 1));
// Then
assertThat(commandResult.ok(), is(false));
assertThat(commandResult.getErrorMessage(), containsString("no such"));
}
@Test
public void shouldReturnOKWhenASimpleCommandExecutesSuccessfully() {
// When
CommandResult commandResult = database.command(new BasicDBObject(LEGACY_HELLO, 1));
// Then
assertThat(commandResult.ok(), is(true));
assertThat((Boolean) commandResult.get(LEGACY_HELLO_LOWER), is(true));
}
@Test
public void shouldRunCommandAgainstSecondaryWhenOnlySecondaryReadPreferenceSpecified() {
assumeTrue(isDiscoverableReplicaSet());
// When
CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), secondary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
}
@Test
public void shouldRunStringCommandAgainstSecondaryWhenSecondaryReadPreferenceSpecified() {
assumeTrue(isDiscoverableReplicaSet());
// When
CommandResult commandResult = database.command("dbstats", secondary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
}
@Test
public void shouldRunCommandAgainstSecondaryWhenOnlySecondaryReadPreferenceSpecifiedAlongWithEncoder() {
assumeTrue(isDiscoverableReplicaSet());
// When
CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), secondary(), DefaultDBEncoder.FACTORY.create());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
}
@Test
public void shouldApplyUuidRepresentationToCommandEncodingAndDecoding() {
try (MongoClient client = new MongoClient(getMongoClientSettingsBuilder()
.uuidRepresentation(UuidRepresentation.STANDARD)
.build())) {
// given
UUID id = UUID.randomUUID();
DB db = client.getDB(getDefaultDatabaseName());
db.getCollection(collectionName).insert(new BasicDBObject("_id", id));
// when
DBObject reply = db.command(new BasicDBObject("findAndModify", collectionName)
.append("query", new BasicDBObject("_id", id))
.append("remove", true));
// then
assertThat((UUID) ((DBObject) reply.get("value")).get("_id"), is(id));
}
}
BsonDocument getCollectionInfo(final String collectionName) {
return new ListCollectionsOperation<>(getDefaultDatabaseName(), new BsonDocumentCodec())
.filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding()).next().get(0);
}
private boolean isCapped(final DBCollection collection) {
return Boolean.TRUE.equals(storageStats(collection).get("capped"));
}
private DBObject storageStats(final DBCollection collection) {
try (Cursor cursor = collection.aggregate(singletonList(
new BasicDBObject("$collStats", new BasicDBObject("storageStats", new BasicDBObject()))),
AggregationOptions.builder().build())) {
return (DBObject) cursor.next().get("storageStats");
}
}
}