@Test public void test_2GB_over() throws IOException { Assume.assumeTrue(CC.FULL_TEST); byte[] data = new byte[51111]; int dataHash = Arrays.hashCode(data); Set<Long> recids = new TreeSet<Long>(); for (int i = 0; i < 1e5; i++) { long recid = engine.recordPut(data, Serializer.BYTE_ARRAY_SERIALIZER); recids.add(recid); // if(i%10000==0){ // System.out.println(recid); // for(Long l:recids){ // byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER); // int hash = Arrays.hashCode(b); // assertEquals(l,dataHash, hash); // } // } } engine.commit(); for (Long l : recids) { byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER); int hash = Arrays.hashCode(b); assertEquals(dataHash, hash); } }
@Test public void testPutRemoveGet() { Map<Integer, Integer> myMap = new MyMap<>(); Map<Integer, Integer> control = new HashMap<>(); for (int i = 0; i < N; i++) { int k = random.nextInt(); int v = random.nextInt(); myMap.put(k, v); control.put(k, v); } Set<Integer> keysToRemove = new HashSet<>(); for (int k : control.keySet()) { if (random.nextBoolean()) { keysToRemove.add(k); } } for (int k : keysToRemove) { control.remove(k); myMap.remove(k); } assertEquals(myMap.size(), control.size()); for (int k : control.keySet()) { assertEquals(myMap.get(k), control.get(k)); int r = random.nextInt(); assertEquals(myMap.get(r), control.get(r)); } }
@Test public void mustBeAbleToUseFlatMapMerge() throws Exception { final JavaTestKit probe = new JavaTestKit(system); final Iterable<Integer> input1 = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); final Iterable<Integer> input2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19); final Iterable<Integer> input3 = Arrays.asList(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); final Iterable<Integer> input4 = Arrays.asList(30, 31, 32, 33, 34, 35, 36, 37, 38, 39); final List<Source<Integer, NotUsed>> mainInputs = new ArrayList<Source<Integer, NotUsed>>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); mainInputs.add(Source.from(input3)); mainInputs.add(Source.from(input4)); CompletionStage<List<Integer>> future = Source.from(mainInputs) .flatMapMerge(3, ConstantFun.<Source<Integer, NotUsed>>javaIdentityFunction()) .grouped(60) .runWith(Sink.<List<Integer>>head(), materializer); List<Integer> result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); final Set<Integer> set = new HashSet<Integer>(); for (Integer i : result) { set.add(i); } final Set<Integer> expected = new HashSet<Integer>(); for (int i = 0; i < 40; ++i) { expected.add(i); } assertEquals(expected, set); }
// FIXME: fails! needs MarcCombiningReader for mhld or at least a diff version of RawRecordReader @Test public void testMultMHLDsWithSameID() throws IOException { // bib134, multMhlds1 String bibFilePath = testDataParentPath + File.separator + "mhldMergeBibs134.mrc"; String mhldFilePath = testDataParentPath + File.separator + "mhldMergeMhlds1Mult.mrc"; Map<String, Record> mergedRecs = MergeSummaryHoldings.mergeMhldsIntoBibRecordsAsMap(bibFilePath, mhldFilePath); Record mergedRec = mergedRecs.get("a1"); assertEquals("Expected three 852", 3, mergedRec.getVariableFields("852").size()); Set<String> expectedVals = new HashSet<String>(); expectedVals.add("Location1"); expectedVals.add("Location2"); RecordTestingUtils.assertSubfieldHasExpectedValues(mergedRec, "852", 'b', expectedVals); expectedVals.clear(); expectedVals.add("(month)"); expectedVals.add("(season)"); RecordTestingUtils.assertSubfieldHasExpectedValues(mergedRec, "853", 'b', expectedVals); assertEquals("Expected one 863", 2, mergedRec.getVariableFields("863").size()); assertEquals("Expected one 866", 1, mergedRec.getVariableFields("866").size()); // fail("Implement me"); System.out.println("Test testMultMHLDsWithSameID() successful"); }
@Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length == 2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2 == div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length == 3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); }
private static void assertDeepChildrenEquals(SNode expectedNode, SNode actualNode) { Set<String> roles = new HashSet<String>(); for (SNode child : expectedNode.getChildren()) { roles.add(child.getRoleInParent()); } for (SNode child : actualNode.getChildren()) { roles.add(child.getRoleInParent()); } for (String role : roles) { Iterable<? extends SNode> expectedChildren = expectedNode.getChildren(role); Iterable<? extends SNode> actualChildren = actualNode.getChildren(role); int esize = IterableUtil.asCollection(expectedChildren).size(); int asize = IterableUtil.asCollection(actualChildren).size(); assertEquals( getErrorString("child count in role " + role, expectedNode, actualNode), esize, asize); Iterator<? extends SNode> actualIterator = actualChildren.iterator(); for (SNode expectedChild : expectedChildren) { SNode actualChild = actualIterator.next(); assertEquals( getErrorString("children in role " + role, expectedNode, actualNode), expectedChild.getNodeId(), actualChild.getNodeId()); assertDeepNodeEquals(expectedChild, actualChild); } } }
@Test public void testInit_NonEmptyCollection() throws Exception { // Mock ConnectionManager connectionManager = mock(ConnectionManager.class); Connection connection = mock(Connection.class); Connection connection1 = mock(Connection.class); Statement statement = mock(Statement.class); PreparedStatement preparedStatement = mock(PreparedStatement.class); when(connection1.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);")) .thenReturn(preparedStatement); when(connectionManager.getConnection(any(SQLiteIndex.class))) .thenReturn(connection) .thenReturn(connection1); when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true); when(connection.createStatement()).thenReturn(statement); when(preparedStatement.executeBatch()).thenReturn(new int[] {2}); // The objects to add Set<Car> initWithObjects = new HashSet<Car>(2); initWithObjects.add( new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"))); initWithObjects.add( new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"))); SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>( Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager); carFeaturesOffHeapIndex.init(initWithObjects, new QueryOptions()); // Verify verify(statement, times(1)) .executeUpdate( "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;"); verify(statement, times(1)) .executeUpdate( "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);"); verify(statement, times(2)).close(); verify(connection, times(1)).close(); verify(preparedStatement, times(2)).setObject(1, 1); verify(preparedStatement, times(1)).setObject(1, 2); verify(preparedStatement, times(1)).setObject(2, "abs"); verify(preparedStatement, times(1)).setObject(2, "gps"); verify(preparedStatement, times(1)).setObject(2, "airbags"); verify(preparedStatement, times(3)).addBatch(); verify(preparedStatement, times(1)).executeBatch(); verify(preparedStatement, times(1)).close(); verify(connection1, times(1)).close(); }
@Test public void testNotifyObjectsRemoved() throws Exception { // Mock ConnectionManager connectionManager = mock(ConnectionManager.class); Connection connection = mock(Connection.class); Connection connection1 = mock(Connection.class); Statement statement = mock(Statement.class); PreparedStatement preparedStatement = mock(PreparedStatement.class); // Behaviour when(connectionManager.getConnection(any(SQLiteIndex.class))) .thenReturn(connection) .thenReturn(connection1); when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true); when(connection.createStatement()).thenReturn(statement); when(connection1.prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE objectKey = ?;")) .thenReturn(preparedStatement); when(preparedStatement.executeBatch()).thenReturn(new int[] {1}); // The objects to add Set<Car> removedObjects = new HashSet<Car>(2); removedObjects.add( new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps"))); removedObjects.add( new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags"))); @SuppressWarnings({"unchecked", "unused"}) SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex = new SQLiteIndex<String, Car, Integer>( Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager); carFeaturesOffHeapIndex.removeAll(removedObjects, new QueryOptions()); // Verify verify(statement, times(1)) .executeUpdate( "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;"); verify(statement, times(1)) .executeUpdate( "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);"); verify(connection, times(1)).close(); verify(preparedStatement, times(1)).setObject(1, 1); verify(preparedStatement, times(1)).setObject(1, 2); verify(preparedStatement, times(2)).addBatch(); verify(preparedStatement, times(1)).executeBatch(); verify(connection1, times(1)).close(); }
/** * Тестирование на коллекции HashSet * * @throws Exception */ @Test public void testOnHashSet() throws Exception { Set<UserHashcode> users = new HashSet<>(); users.add(user1); assertTrue(users.contains(user1)); // user3 копия user1 но не содержится в Set. Поиск идет по equals, а он не переопределен assertFalse(users.contains(user3)); users.add(user2); users.add(user3); // user3 не перезатирает user1, т.к. не только должны совпадать hashCode, но и equals // Совпадение hashCode не гарантирует равенство equals, поэтому и нет перезатирания assertEquals(3, users.size()); }
@Test public void scanTest() { Map<String, Map<String, ByteIterator>> keyMap = new HashMap<>(); for (int i = 0; i < 5; i++) { String insertKey = KEY_PREFIX + i; keyMap.put(insertKey, insertRow(insertKey)); } Set<String> fieldSet = new HashSet<>(); fieldSet.add("FIELD0"); fieldSet.add("FIELD1"); int startIndex = 1; int resultRows = 3; Vector<HashMap<String, ByteIterator>> resultVector = new Vector<>(); orientDBClient.scan(CLASS, KEY_PREFIX + startIndex, resultRows, fieldSet, resultVector); // Check the resultVector is the correct size assertEquals( "Assert the correct number of results rows were returned", resultRows, resultVector.size()); // Check each vector row to make sure we have the correct fields int testIndex = startIndex; for (HashMap<String, ByteIterator> result : resultVector) { assertEquals( "Assert that this row has the correct number of fields", fieldSet.size(), result.size()); for (String field : fieldSet) { assertEquals( "Assert this field is correct in this row", keyMap.get(KEY_PREFIX + testIndex).get(field).toString(), result.get(field).toString()); } testIndex++; } }
@Test public void testClonesClassnames() { Document doc = Jsoup.parse("<div class='one two'></div>"); Element div = doc.select("div").first(); Set<String> classes = div.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("one")); assertTrue(classes.contains("two")); Element copy = div.clone(); Set<String> copyClasses = copy.classNames(); assertEquals(2, copyClasses.size()); assertTrue(copyClasses.contains("one")); assertTrue(copyClasses.contains("two")); copyClasses.add("three"); copyClasses.remove("one"); assertTrue(classes.contains("one")); assertFalse(classes.contains("three")); assertFalse(copyClasses.contains("one")); assertTrue(copyClasses.contains("three")); assertEquals("", div.html()); assertEquals("", copy.html()); }
private List<String> executeDDL( String ddlFileName, @Nullable String dataFileName, boolean isLocalTable, @Nullable String[] args) throws Exception { Path ddlFilePath = new Path(currentQueryPath, ddlFileName); FileSystem fs = ddlFilePath.getFileSystem(conf); assertTrue(ddlFilePath + " existence check", fs.exists(ddlFilePath)); String template = FileUtil.readTextFile(new File(ddlFilePath.toUri())); String dataFilePath = null; if (dataFileName != null) { dataFilePath = getDataSetFile(dataFileName).toString(); } String compiled = compileTemplate(template, dataFilePath, args); List<ParsedResult> parsedResults = SimpleParser.parseScript(compiled); List<String> createdTableNames = new ArrayList<String>(); for (ParsedResult parsedResult : parsedResults) { // parse a statement Expr expr = sqlParser.parse(parsedResult.getStatement()); assertNotNull(ddlFilePath + " cannot be parsed", expr); if (expr.getType() == OpType.CreateTable) { CreateTable createTable = (CreateTable) expr; String tableName = createTable.getTableName(); assertTrue("Table creation is failed.", client.updateQuery(parsedResult.getStatement())); TableDesc createdTable = client.getTableDesc(tableName); String createdTableName = createdTable.getName(); assertTrue( "table '" + createdTableName + "' creation check", client.existTable(createdTableName)); if (isLocalTable) { createdTableGlobalSet.add(createdTableName); createdTableNames.add(tableName); } } else if (expr.getType() == OpType.DropTable) { DropTable dropTable = (DropTable) expr; String tableName = dropTable.getTableName(); assertTrue( "table '" + tableName + "' existence check", client.existTable(CatalogUtil.buildFQName(currentDatabase, tableName))); assertTrue("table drop is failed.", client.updateQuery(parsedResult.getStatement())); assertFalse( "table '" + tableName + "' dropped check", client.existTable(CatalogUtil.buildFQName(currentDatabase, tableName))); if (isLocalTable) { createdTableGlobalSet.remove(tableName); } } else { assertTrue(ddlFilePath + " is not a Create or Drop Table statement", false); } } return createdTableNames; }
public void workerSetTest() { Set<Worker> workerSet = new HashSet<Worker>(); Worker worker1 = new Worker("张三", 18); worker1.setWorkerId(1); workerSet.add(worker1); Worker worker2 = new Worker("李四", 8); worker2.setWorkerId(2); System.out.println(workerSet.contains(worker2)); }
private void visit(Set<String> names, String prefix, File file) { for (File child : file.listFiles()) { if (child.isFile()) { names.add(prefix + child.getName()); } else if (child.isDirectory()) { visit(names, prefix + child.getName() + "/", child); } } }
@Test public void testHash() { Set<Integer> set = new HashSet<Integer>(); for (WordNgram w : myNgrams) { set.add(w.hashCode()); } assertTrue("hash code test", set.size() > 8); }
public void afterExecute(Task task, TaskState state) { String taskPath = path(task); if (taskPath.startsWith(":buildSrc:")) { return; } if (state.getSkipped()) { skippedTasks.add(taskPath); } }
// Failing test due to equals() contract violation @Test public void testCollectionEquals() { Set<String> p = new HashSet<String>(); InstrumentedCollection<String> t = new InstrumentedCollection<String>(p); p.add("cat"); p.add("dog"); assertTrue(p.equals(t)); assertTrue(t.equals(p)); }
@Test public void testRemoveService() { ServiceHolder tested = new ServiceHolder(); Object service = new Object(); // Get the hash set. Set<Object> servicesSet = getField(tested, Set.class); servicesSet.add(service); tested.removeService(service); assertTrue("Set should be empty after removeal.", servicesSet.isEmpty()); }
public void afterExecute(Task task, TaskState state) { assertThat(task, sameInstance(current)); current = null; String taskPath = path(task); if (taskPath.startsWith(":buildSrc:")) { return; } if (state.getSkipped()) { skippedTasks.add(taskPath); } }
Base3() throws GoraException, TException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { final User user = new User(); user.setId(userId); final ByteBuffer b = ByteBuffer.wrap("".getBytes()); b.mark(); user.setBlind(b); user.setIdentities(new ArrayList<>()); user.setSentRequests(new ArrayList<>()); final Map<CharSequence, Client> clients = new HashMap<>(2); final VerificationKey verificationKey = new VerificationKey(); verificationKey.setAlgorithm(com.kareebo.contacts.server.gora.SignatureAlgorithm.Fake); verificationKey.setBuffer(b); clients.put( TypeConverter.convert(clientId0.getClient()), createClient(clientId0, verificationKey)); clients.put( TypeConverter.convert(clientId1.getClient()), createClient(clientId1, verificationKey)); user.setClients(clients); userDatastore.put(userId, user); final com.kareebo.contacts.thrift.EncryptedBuffer encryptedBuffer0 = new com.kareebo.contacts.thrift.EncryptedBuffer( b, com.kareebo.contacts.thrift.EncryptionAlgorithm.Fake, clientId0); final EncryptedBufferSigned encryptedBufferSigned0 = new EncryptedBufferSigned(encryptedBuffer0, sign(encryptedBuffer0, clientId)); encryptedBufferSignedSet.add(encryptedBufferSigned0); e0 = new EncryptedBufferSignedWithVerificationKey( encryptedBufferSigned0, TypeConverter.convert(this.verificationKey)); final com.kareebo.contacts.thrift.EncryptedBuffer encryptedBuffer1 = new com.kareebo.contacts.thrift.EncryptedBuffer( b, com.kareebo.contacts.thrift.EncryptionAlgorithm.Fake, clientId1); final EncryptedBufferSigned encryptedBufferSigned1 = new EncryptedBufferSigned(encryptedBuffer1, sign(encryptedBuffer1, clientId)); encryptedBufferSignedSet.add(encryptedBufferSigned1); e1 = new EncryptedBufferSignedWithVerificationKey( encryptedBufferSigned1, TypeConverter.convert(this.verificationKey)); }
@Test public void testAddAndDelIndex() throws Exception { TableDesc desc = prepareTable(); prepareIndexDescs(); catalog.createTable(desc); assertFalse(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc1.getName())); assertFalse( catalog.existIndexByColumnNames(DEFAULT_DATABASE_NAME, "indexed", new String[] {"id"})); catalog.createIndex(desc1); assertTrue(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc1.getName())); assertTrue( catalog.existIndexByColumnNames(DEFAULT_DATABASE_NAME, "indexed", new String[] {"id"})); assertFalse(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc2.getName())); assertFalse( catalog.existIndexByColumnNames(DEFAULT_DATABASE_NAME, "indexed", new String[] {"score"})); catalog.createIndex(desc2); assertTrue(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc2.getName())); assertTrue( catalog.existIndexByColumnNames(DEFAULT_DATABASE_NAME, "indexed", new String[] {"score"})); Set<IndexDesc> indexDescs = new HashSet<>(); indexDescs.add(desc1); indexDescs.add(desc2); indexDescs.add(desc3); for (IndexDesc index : catalog.getAllIndexesByTable(DEFAULT_DATABASE_NAME, "indexed")) { assertTrue(indexDescs.contains(index)); } catalog.dropIndex(DEFAULT_DATABASE_NAME, desc1.getName()); assertFalse(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc1.getName())); catalog.dropIndex(DEFAULT_DATABASE_NAME, desc2.getName()); assertFalse(catalog.existIndexByName(DEFAULT_DATABASE_NAME, desc2.getName())); catalog.dropTable(desc.getName()); assertFalse(catalog.existsTable(desc.getName())); }
public Set<Integer> deleteKeys(int every) { Set<Integer> removed = new HashSet<Integer>(); for (int i = 0; i < numKeys; i++) { if (i % every == 0) { removed.add(i); List<ByteBuffer> deletions = new ArrayList<ByteBuffer>(); for (int j = 0; j < numColumns; j++) { deletions.add(KeyValueStoreUtil.getBuffer(j)); } store.mutate(KeyValueStoreUtil.getBuffer(i), null, deletions, tx); } } return removed; }
@Test public void testCompoundsWithSameStart() { BufferedReader br = new BufferedReader(new StringReader("my cat my dog my chicken")); Set<String> compounds = new HashSet<String>(); compounds.add("my cat"); compounds.add("my dog"); CompoundWordIterator it = new CompoundWordIterator(br, compounds); assertEquals("my cat", it.next()); assertEquals("my dog", it.next()); assertEquals("my", it.next()); assertEquals("chicken", it.next()); assertFalse(it.hasNext()); }
/** @see java.lang.Runnable#run() */ public void run() { final Thread thread = Thread.currentThread(); while (!Thread.interrupted()) { m_set.add(m_touchable); m_list.add(m_touchable); try { synchronized (thread) { thread.wait(); } } catch (InterruptedException e) { // propagate interrupt thread.interrupt(); } } }
public Set<KeyColumn> deleteValues(int every) { Set<KeyColumn> removed = new HashSet<KeyColumn>(); int counter = 0; for (int i = 0; i < numKeys; i++) { List<ByteBuffer> deletions = new ArrayList<ByteBuffer>(); for (int j = 0; j < numColumns; j++) { counter++; if (counter % every == 0) { // remove removed.add(new KeyColumn(i, j)); deletions.add(KeyValueStoreUtil.getBuffer(j)); } } store.mutate(KeyValueStoreUtil.getBuffer(i), null, deletions, tx); } return removed; }
@Test public void keySet() throws InterruptedException { HazelcastClient hClient = getHazelcastClient(); MultiMap<String, String> multiMap = hClient.getMultiMap("keySet"); int count = 100; for (int i = 0; i < count; i++) { for (int j = 0; j <= i; j++) { multiMap.put(String.valueOf(i), String.valueOf(j)); } } assertEquals(count * (count + 1) / 2, multiMap.size()); Set<String> set = multiMap.keySet(); assertEquals(count, set.size()); Set<String> s = new HashSet<String>(); for (int i = 0; i < count; i++) { s.add(String.valueOf(i)); } assertEquals(s, set); }
@Test public void putAll() { HazelcastClient hClient = getHazelcastClient(); IMap map = hClient.getMap("putAll"); int counter = 100; Set keys = new HashSet(counter); for (int i = 0; i < counter; i++) { keys.add(i); } Map all = map.getAll(keys); assertEquals(0, all.size()); Map tempMap = new HashMap(); for (int i = 0; i < counter; i++) { tempMap.put(i, i); } map.putAll(tempMap); for (int i = 0; i < counter; i++) { assertEquals(i, map.get(i)); } all = map.getAll(keys); assertEquals(counter, all.size()); }
@Test public void iterateOverMapKeys() { HazelcastClient hClient = getHazelcastClient(); Map<String, String> map = hClient.getMap("iterateOverMapKeys"); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); Set<String> keySet = map.keySet(); assertEquals(3, keySet.size()); Set<String> s = new HashSet<String>(); for (String string : keySet) { s.add(string); assertTrue(Arrays.asList("1", "2", "3").contains(string)); } assertEquals(3, s.size()); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } assertEquals(0, map.size()); }
@Test public void testInvalidClasses() { Set<String> exceptionMessages = new HashSet<String>(); for (Triplet<HBRecord, String, Class<? extends IllegalArgumentException>> p : invalidRecordsAndErrorMessages) { HBRecord record = p.getValue0(); Class recordClass = record.getClass(); assertFalse( "Object mapper couldn't detect invalidity of class " + recordClass.getName(), hbMapper.isValid(recordClass)); String errorMessage = p.getValue1() + " (" + recordClass.getName() + ") should have thrown an " + IllegalArgumentException.class.getName(); String exMsgObjToResult = null, exMsgObjToPut = null, exMsgResultToObj = null, exMsgPutToObj = null; try { hbMapper.writeValueAsResult(record); fail(errorMessage + " while converting bean to Result"); } catch (IllegalArgumentException ex) { assertEquals( "Mismatch in type of exception thrown for " + recordClass.getSimpleName(), p.getValue2(), ex.getClass()); exMsgObjToResult = ex.getMessage(); } try { hbMapper.writeValueAsPut(record); fail(errorMessage + " while converting bean to Put"); } catch (IllegalArgumentException ex) { assertEquals( "Mismatch in type of exception thrown for " + recordClass.getSimpleName(), p.getValue2(), ex.getClass()); exMsgObjToPut = ex.getMessage(); } try { hbMapper.readValue(someResult, recordClass); fail(errorMessage + " while converting Result to bean"); } catch (IllegalArgumentException ex) { assertEquals( "Mismatch in type of exception thrown for " + recordClass.getSimpleName(), p.getValue2(), ex.getClass()); exMsgResultToObj = ex.getMessage(); } try { hbMapper.readValue( new ImmutableBytesWritable(someResult.getRow()), someResult, recordClass); fail(errorMessage + " while converting Result to bean"); } catch (IllegalArgumentException ex) { assertEquals( "Mismatch in type of exception thrown for " + recordClass.getSimpleName(), p.getValue2(), ex.getClass()); } try { hbMapper.readValue(somePut, recordClass); fail(errorMessage + " while converting Put to bean"); } catch (IllegalArgumentException ex) { assertEquals( "Mismatch in type of exception thrown for " + recordClass.getSimpleName(), p.getValue2(), ex.getClass()); exMsgPutToObj = ex.getMessage(); } try { hbMapper.readValue(new ImmutableBytesWritable(somePut.getRow()), somePut, recordClass); fail(errorMessage + " while converting row key and Put combo to bean"); } catch (IllegalArgumentException ex) { assertEquals("Mismatch in type of exception thrown", p.getValue2(), ex.getClass()); } assertEquals( "Validation for 'conversion to Result' and 'conversion to Put' differ in code path", exMsgObjToResult, exMsgObjToPut); assertEquals( "Validation for 'conversion from Result' and 'conversion from Put' differ in code path", exMsgResultToObj, exMsgPutToObj); assertEquals( "Validation for 'conversion from bean' and 'conversion to bean' differ in code path", exMsgObjToResult, exMsgResultToObj); System.out.printf( "%s threw below Exception as expected:\n%s\n%n", p.getValue1(), exMsgObjToResult); if (!exceptionMessages.add(exMsgObjToPut)) { fail("Same error message for different invalid inputs"); } } }
public TestCompoundWordIterator() { myCat = new HashSet<String>(); myCat.add("my cat"); }