forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBTest.java
More file actions
594 lines (492 loc) · 23.1 KB
/
DBTest.java
File metadata and controls
594 lines (492 loc) · 23.1 KB
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
/*
* Copyright (c) 2008-2014 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.util.TestCase;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Ignore;
import org.junit.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import static com.mongodb.ReadPreference.primary;
import static com.mongodb.ReadPreference.primaryPreferred;
import static com.mongodb.ReadPreference.secondary;
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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
public class DBTest extends TestCase {
@Test
public void shouldIgnoreCaseWhenCheckingIfACollectionExists() {
// Given
getDatabase().getCollection("foo1").drop();
assertFalse(getDatabase().collectionExists("foo1"));
// When
getDatabase().createCollection("foo1", new BasicDBObject());
// Then
assertTrue(getDatabase().collectionExists("foo1"));
assertTrue(getDatabase().collectionExists("FOO1"));
assertTrue(getDatabase().collectionExists("fOo1"));
// Finally
getDatabase().getCollection("foo1").drop();
}
@Test
public void shouldReturnCorrectValueForReadPreferenceDependingUponTheCommand() throws UnknownHostException {
assumeTrue(isReplicaSet(getMongoClient()));
Mongo mongo = new MongoClient(new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019"));
DB db = mongo.getDB(getDatabase().getName());
DBObject obj = new BasicDBObject("mapreduce", 1).append("out", "myColl");
assertEquals(primary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("mapreduce", 1).append("out", new BasicDBObject("replace", "myColl"));
assertEquals(primary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("mapreduce", 1).append("out", new BasicDBObject("inline", 1));
assertEquals(secondary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("mapreduce", 1).append("out", new BasicDBObject("inline", null));
assertEquals(primary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("getnonce", 1);
assertEquals(primaryPreferred(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("authenticate", 1);
assertEquals(primaryPreferred(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("count", 1);
assertEquals(secondary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("count", 1);
assertEquals(secondary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("serverStatus", 1);
assertEquals(primary(), db.getCommandReadPreference(obj, secondary()));
obj = new BasicDBObject("count", 1);
assertEquals(primary(), db.getCommandReadPreference(obj, null));
obj = new BasicDBObject("collStats", 1);
assertEquals(ReadPreference.secondaryPreferred(), db.getCommandReadPreference(obj, ReadPreference.secondaryPreferred()));
obj = new BasicDBObject("text", 1);
assertEquals(ReadPreference.secondaryPreferred(), db.getCommandReadPreference(obj, ReadPreference.secondaryPreferred()));
obj = new BasicDBObject("parallelCollectionScan", 1);
assertEquals(ReadPreference.secondaryPreferred(), db.getCommandReadPreference(obj, ReadPreference.secondaryPreferred()));
}
@Test
public void shouldNotThrowAnErrorWhenEnsureConnectionCalledAfterRequestStart() throws UnknownHostException {
Mongo m = new MongoClient(Arrays.asList(new ServerAddress("localhost")));
assumeFalse(isStandalone(cleanupMongo));
try {
DB db = m.getDB("com_mongodb_unittest_DBTest");
db.requestStart();
try {
db.requestEnsureConnection();
} finally {
db.requestDone();
}
} finally {
m.close();
}
}
@Test
public void shouldReleaseConnectionOnLastCallToRequestEndWhenRequestStartCallsAreNested() throws UnknownHostException {
Mongo m = new MongoClient(Arrays.asList(new ServerAddress("localhost")),
MongoClientOptions.builder().connectionsPerHost(1).maxWaitTime(10000).build());
DB db = m.getDB("com_mongodb_unittest_DBTest");
try {
db.requestStart();
try {
db.command(new BasicDBObject("ping", 1));
db.requestStart();
try {
db.command(new BasicDBObject("ping", 1));
} finally {
db.requestDone();
}
} finally {
db.requestDone();
}
} finally {
m.close();
}
}
@Test
public void shouldReturnFailureWithErrorMessageWhenExecutingInvalidCommand() {
// mongos 2.2 sets the query failure bit for unrecognized commands
assumeFalse(isSharded(getMongoClient()) && !serverIsAtLeastVersion(2.4));
// Given
DB database = getDatabase();
// When
CommandResult commandResult = database.command(new BasicDBObject("NotRealCommandName", 1));
// Then
assertThat(commandResult.ok(), is(false));
assertThat(commandResult.getErrorMessage(), is("no such cmd: NotRealCommandName"));
}
@Test
public void shouldReturnOKWhenASimpleCommandExecutesSuccessfully() {
// Given
DB database = getDatabase();
// When
CommandResult commandResult = database.command(new BasicDBObject("isMaster", 1));
// Then
assertThat(commandResult.ok(), is(true));
assertThat((Boolean) commandResult.get("ismaster"), is(true));
}
@Test
@SuppressWarnings("deprecation") // this functionality needs testing, but the tests will be removed/replaced in 3.0
public void shouldRunCommandAgainstSecondaryWhenSlaveOkOrReadPreferenceSecondaryOrBothAreBothSet() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
try {
//Sadly yes, this does test more than one thing. But the overall goal is the same
// When
CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), Bytes.QUERYOPTION_SLAVEOK, secondary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
// When
commandResult = database.command(new BasicDBObject("dbstats", 1), 0, secondary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
// When
commandResult = database.command(new BasicDBObject("dbstats", 1), Bytes.QUERYOPTION_SLAVEOK, primary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
} finally {
database.dropDatabase();
}
}
@Test
public void shouldRunCommandAgainstSecondaryWhenOnlySecondaryReadPreferenceSpecified() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
// 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
@SuppressWarnings("deprecation") // this functionality needs testing, but the tests will be removed/replaced in 3.0
@Ignore("Intermittent, not sure this is doing what it thinks it is")
public void shouldRunStringCommandAgainstSecondaryWhenSlaveOkOptionSpecified() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
// When
CommandResult commandResult = database.command("dbstats", Bytes.QUERYOPTION_SLAVEOK);
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), not(containsString(":27017")));
}
@Test
public void shouldRunStringCommandAgainstSecondaryWhenSecondaryReadPreferenceSpecified() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
// 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() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
// 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 shouldRunCommandAgainstPrimaryWhenOnlyPrimaryReadPreferenceSpecified() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
// When
CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), primary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), containsString(":27017"));
}
@Test
public void shouldOverrideDefaultReadPreferenceWhenCommandReadPreferenceSpecified() throws UnknownHostException {
// Given
assumeTrue(isReplicaSet(cleanupMongo));
DB database = getReplicaSetDB();
database.setReadPreference(secondary());
// When
CommandResult commandResult = database.command(new BasicDBObject("dbstats", 1), primary());
// Then
assertThat(commandResult.ok(), is(true));
assertThat((String) commandResult.get("serverUsed"), containsString(":27017"));
}
@Test
public void shouldNotThrowAnExceptionwhenRequestDoneIsCalledWithoutFirstCallingRequestStart() throws UnknownHostException {
getDatabase().requestDone();
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowAnExceptionWhenDBNameContainsSpaces() {
cleanupMongo.getDB("foo bar");
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowAnExceptionWhenDBNameIsEmpty() {
cleanupMongo.getDB("");
}
@Test
public void shouldGetDefaultWriteConcern() {
assertEquals(WriteConcern.ACKNOWLEDGED, getDatabase().getWriteConcern());
}
@Test
public void shouldGetDefaultReadPreference() {
assertEquals(ReadPreference.primary(), getDatabase().getReadPreference());
}
@Test
public void shouldReturnCachedCollectionObjectIfExists() {
DBCollection collection1 = getDatabase().getCollection("test");
DBCollection collection2 = getDatabase().getCollection("test");
assertThat("Checking that references are equal", collection1, sameInstance(collection2));
}
@Test
public void shouldDropItself() {
// given
String databaseName = "drop-test-" + System.nanoTime();
DB db = getMongoClient().getDB(databaseName);
// creates the database in a much faster way than inserting something into it
db.getStats();
assertThat(cleanupMongo.getDatabaseNames(), hasItem(databaseName));
// when
db.dropDatabase();
// then
assertThat(cleanupMongo.getDatabaseNames(), not(hasItem(databaseName)));
}
@Test
public void shouldGetCollectionNames() {
getDatabase().dropDatabase();
String[] collectionNames = {"c1", "c2", "c3"};
for (final String name : collectionNames) {
getDatabase().createCollection(name, new BasicDBObject());
}
assertThat(getDatabase().getCollectionNames(), hasItems(collectionNames));
}
@Test(expected = MongoException.class)
public void shouldReceiveAnErrorIfCreatingCappedCollectionWithoutSize() {
getDatabase().createCollection("someName", new BasicDBObject("capped", true));
}
@Test
public void shouldCreateCappedCollection() {
collection.drop();
String collectionName = collection.getName();
getDatabase().createCollection(collection.getName(), new BasicDBObject("capped", true)
.append("size", 242880));
assertTrue(getDatabase().getCollection(collectionName).isCapped());
}
@Test
public void shouldCreateCappedCollectionWithMaxNumberOfDocuments() {
collection.drop();
String collectionName = collection.getName();
DBCollection cappedCollectionWithMax = getDatabase().createCollection(collectionName, new BasicDBObject("capped", true)
.append("size", 242880)
.append("max", 10));
// assertThat((Boolean) cappedCollectionWithMax.getStats().get("capped"), is(true));
assertThat((Integer) cappedCollectionWithMax.getStats().get("max"), is(10));
for (int i = 0; i < 11; i++) {
cappedCollectionWithMax.insert(new BasicDBObject("x", i));
}
assertThat(cappedCollectionWithMax.find().count(), is(10));
}
@Test(expected = CommandFailureException.class)
public void shouldThrowErrorIfCreatingACappedCollectionWithANegativeSize() {
collection.drop();
DBObject creationOptions = BasicDBObjectBuilder.start().add("capped", true)
.add("size", -20).get();
getDatabase().createCollection(collection.getName(), creationOptions);
}
@Test
public void shouldCreateUncappedCollection() {
collection.drop();
String collectionName = collection.getName();
BasicDBObject creationOptions = new BasicDBObject("capped", false);
getDatabase().createCollection(collectionName, creationOptions);
assertFalse(getDatabase().getCollection(collectionName).isCapped());
}
@Test
@SuppressWarnings("deprecation")
public void shouldDoEval() {
assumeFalse(getDatabase().isAuthenticated());
String code = "function(name, incAmount) {\n"
+ "var doc = db.myCollection.findOne( { name : name } );\n"
+ "doc = doc || { name : name , num : 0 , total : 0 , avg : 0 , _id: 1 };\n"
+ "doc.num++;\n"
+ "doc.total += incAmount;\n"
+ "doc.avg = doc.total / doc.num;\n"
+ "db.myCollection.save( doc );\n"
+ "return doc;\n"
+ "}";
getDatabase().doEval(code, "eliot", 5);
assertEquals(getDatabase().getCollection("myCollection").findOne(), new BasicDBObject("_id", 1.0)
.append("avg", 5.0)
.append("num", 1.0)
.append("name", "eliot")
.append("total", 5.0));
}
@Test(expected = MongoException.class)
public void shouldThrowErrorwhileDoingEval() {
String code = "function(a, b) {\n"
+ "var doc = db.myCollection.findOne( { name : b } );\n"
+ "}";
getDatabase().eval(code, 1);
}
@Test
public void shouldGetStats() {
assumeFalse(isSharded(getMongoClient()));
assertThat(getDatabase().getStats(), hasFields(new String[]{"collections", "avgObjSize",
"indexes", "db", "indexSize", "storageSize"}));
}
@Test
public void shouldExecuteCommand() {
CommandResult commandResult = getDatabase().command(new BasicDBObject("isMaster", 1));
assertThat(commandResult, hasFields(new String[]{"ismaster", "maxBsonObjectSize", "ok", "serverUsed"}));
}
@Test
public void shouldNotThrowAnExceptionOnCommandFailure() {
CommandResult commandResult = getDatabase().command(new BasicDBObject("collStats", "a" + System.currentTimeMillis()));
assertThat(commandResult, hasFields(new String[]{"serverUsed", "ok", "errmsg"}));
}
@Test
public void shouldAddReadOnlyUser() {
String userName = "newUser";
String pwd = "pwd";
getDatabase().addUser(userName, pwd.toCharArray(), true);
try {
assertCorrectUserExists(userName, pwd, true, getDatabase());
} finally {
getDatabase().removeUser(userName);
}
}
@Test
public void shouldAddReadWriteUser() {
String userName = "newUser";
String pwd = "pwd";
getDatabase().addUser(userName, pwd.toCharArray(), false);
try {
assertCorrectUserExists(userName, pwd, false, getDatabase());
} finally {
getDatabase().removeUser(userName);
}
}
@Test
public void shouldAddReadWriteAdminUser() throws UnknownHostException {
String userName = "newUser";
String pwd = "pwd";
MongoClient mongoClient = new MongoClient(getMongoClientURI());
DB adminDB = mongoClient.getDB("admin");
adminDB.addUser(userName, pwd.toCharArray(), false);
try {
assertTrue(adminDB.authenticate(userName, pwd.toCharArray()));
assertCorrectUserExists(userName, pwd, false, adminDB);
} finally {
adminDB.removeUser(userName);
mongoClient.close();
}
}
@Test
public void shouldAddReadOnlyAdminUser() throws UnknownHostException {
String readWriteUserName = "newUserReadWrite";
String readOnlyUserName = "newUser";
String pwd = "pwd";
MongoClient mongoClient = new MongoClient(getMongoClientURI());
DB adminDB = mongoClient.getDB("admin");
adminDB.addUser(readWriteUserName, pwd.toCharArray(), false);
adminDB.authenticate(readWriteUserName, pwd.toCharArray());
adminDB.addUser(readOnlyUserName, pwd.toCharArray(), true);
try {
assertCorrectUserExists(readOnlyUserName, pwd, true, adminDB);
} finally {
adminDB.removeUser(readOnlyUserName);
adminDB.removeUser(readWriteUserName);
mongoClient.close();
}
}
@Test
public void shouldRemoveUser() {
String userName = "newUser";
getDatabase().addUser(userName, "pwd".toCharArray(), true);
getDatabase().removeUser(userName);
assertThatUserIsRemoved(userName, getDatabase());
}
private void assertThatUserIsRemoved(final String userName, final DB database) {
if (serverIsAtLeastVersion(2.6)) {
CommandResult usersInfo = database.command(new BasicDBObject("usersInfo", userName));
assertEquals(0, ((List) usersInfo.get("users")).size());
}
else {
assertNull(database.getCollection("system.users").findOne(new BasicDBObject("user", userName)));
}
}
private void assertCorrectUserExists(final String userName, final String password, final boolean isReadOnly, final DB database) {
if (serverIsAtLeastVersion(2.6, database.getMongo())) {
CommandResult usersInfo = database.command(new BasicDBObject("usersInfo", userName));
DBObject user = (DBObject) ((List) usersInfo.get("users")).get(0);
assertEquals(userName, user.get("user"));
assertEquals(database.getName(), user.get("db"));
assertEquals(getExpectedRole(isReadOnly, database), ((DBObject) ((List) user.get("roles")).get(0)).get("role"));
}
else {
assertEquals(new BasicDBObject("user", userName).append("readOnly", isReadOnly)
.append("pwd", getDatabase()._hash(userName, password.toCharArray())),
database.getCollection("system.users").findOne(new BasicDBObject("user", userName),
new BasicDBObject("_id", 0)));
}
}
private String getExpectedRole(final boolean isReadOnly, final DB database) {
if (database.getName().equals("admin")) {
return isReadOnly ? "readAnyDatabase" : "root";
} else {
return isReadOnly ? "read" : "dbOwner";
}
}
private DB getReplicaSetDB() throws UnknownHostException {
Mongo mongo = new MongoClient(Arrays.asList(new ServerAddress("127.0.0.1"), new ServerAddress("127.0.0.1", 27018)));
return mongo.getDB("database-" + System.nanoTime());
}
private static Matcher<DBObject> hasFields(final String[] fields) {
return new TypeSafeMatcher<DBObject>() {
@Override
protected boolean matchesSafely(final DBObject item) {
for (final String fieldName : fields) {
if (!item.containsField(fieldName)) {
return false;
}
}
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText(" has fields ")
.appendValue(fields);
}
};
}
}