@Test public void testParameterToPairsWhenValueIsCollection() throws Exception { Map<String, String> collectionFormatMap = new HashMap<String, String>(); collectionFormatMap.put("csv", ","); collectionFormatMap.put("tsv", "\t"); collectionFormatMap.put("ssv", " "); collectionFormatMap.put("pipes", "\\|"); collectionFormatMap.put("", ","); // no format, must default to csv collectionFormatMap.put("unknown", ","); // all other formats, must default to csv String name = "param-a"; List<Object> values = new ArrayList<Object>(); values.add("value-a"); values.add(123); values.add(new Date()); // check for multi separately List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values); assertEquals(values.size(), multiPairs.size()); // all other formats for (String collectionFormat : collectionFormatMap.keySet()) { List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values); assertEquals(1, pairs.size()); String delimiter = collectionFormatMap.get(collectionFormat); String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); // must equal input values assertEquals(values.size(), pairValueSplit.length); } }
@Test public void testSendAndReceive() throws Exception { // Run the main controller ControllerRunner controllerRunner = new ControllerRunner(10, 9090, InetAddress.getLocalHost(), "127.0.0.1", 8008); controllerRunner.run(); System.out.println("Controller running"); Random random = new Random(); int player = random.nextInt(); // Connect a new controller and send test alarm Controller controller = new Controller(10); Socket connection1 = controller.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090); Alarm alarm = new Alarm(player, System.currentTimeMillis(), new PlayerCause(player)); controller.send(alarm, connection1); Controller controller2 = new Controller(10); Socket connection2 = controller2.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090); long alarmtime = System.currentTimeMillis() + 500; Position position1 = new Position(player, System.currentTimeMillis(), 1, 2, 3); Position position2 = new Position(player, alarmtime, 100, 200, 300); controller2.send(position1, connection2); controller2.send(position2, connection2); controller2.send(new Request(player, DataType.ACCEL, -1, -1), connection2); controller2.send(new Request(player, DataType.POS, -1, -1), connection2); Thread.sleep(15000); List<Sendable> received = controller2.receive(connection2); List<Alarm> alarms = new ArrayList<Alarm>(); List<Acceleration> accelerations = new ArrayList<Acceleration>(); List<Position> positions = new ArrayList<Position>(); // Distribute the sendable objects for (Sendable sendable : received) { if (sendable instanceof Alarm) { alarms.add((Alarm) sendable); } else if (sendable instanceof Service) { Service service = (Service) sendable; List<?> data = service.getData(); for (Object o : data) { if (o instanceof Acceleration) { accelerations.add((Acceleration) o); } else if (o instanceof Position) { positions.add((Position) o); } } } } controller.disconnectFromClient(connection1); controller2.disconnectFromClient(connection2); assertTrue("Alarm was not sent from controller", alarms.size() >= 1); assertTrue("Acceleration not received from controller", accelerations.size() >= 1); assertTrue("Position 1 not contained in received positions", positions.contains(position1)); assertTrue("Position 2 not contained in received positions", positions.contains(position2)); }
@Mock public int computeX(Invocation inv, int a, int b) { inputValues.add(a); inputValues.add(b); int x = inv.proceed(); outputValues.add(x); return x; }
@Test public void testResolveSingletonInSameRegions() { List<BundleCapability> collisionCandidates = new ArrayList<BundleCapability>(); collisionCandidates.add(bundleCapability(BUNDLE_B)); collisionCandidates.add(bundleCapability(BUNDLE_C)); collisionCandidates.add(bundleCapability(BUNDLE_D)); this.resolverHook.filterSingletonCollisions(bundleCapability(BUNDLE_A), collisionCandidates); assertEquals("Wrong number of collitions", 0, collisionCandidates.size()); }
@Test public void testResolveSingletonInDifferentRegions() throws BundleException { region(REGION_A).addBundle(bundle(BUNDLE_X)); BundleCapability collision = bundleCapability(BUNDLE_X); List<BundleCapability> collisionCandidates = new ArrayList<BundleCapability>(); collisionCandidates.add(collision); collisionCandidates.add(bundleCapability(BUNDLE_B)); collisionCandidates.add(bundleCapability(BUNDLE_C)); collisionCandidates.add(bundleCapability(BUNDLE_D)); this.resolverHook.filterSingletonCollisions(bundleCapability(BUNDLE_A), collisionCandidates); assertEquals("Wrong number of collitions", 1, collisionCandidates.size()); collisionCandidates.contains(collision); }
@Test public void testWriteJdeeJuciInvokeElispForm() { List eval = new ArrayList(); eval.add(new Symbol("jdee-juci-invoke-elisp")); List form = new ArrayList(); form.add(new Symbol("message")); form.addAll(Arrays.asList("hello %s", "nick")); eval.add(form); lwriter.writeForm(eval); assertEquals("(jdee-juci-invoke-elisp '(message \"hello %s\" \"nick\"))", output.toString()); }
public List<String> getTokenTypes(LexerGrammar lg, ATN atn, CharStream input, boolean adaptive) { LexerATNSimulator interp = new LexerATNSimulator(atn); List<String> tokenTypes = new ArrayList<String>(); int ttype; do { if (adaptive) ttype = interp.match(input, Lexer.DEFAULT_MODE); else ttype = interp.matchATN(input); if (ttype == Token.EOF) tokenTypes.add("EOF"); else { tokenTypes.add(lg.typeToTokenList.get(ttype)); } } while (ttype != Token.EOF); return tokenTypes; }
@Test // Uses of JMockit API: 1 public void verifyAllInvocationsInOrder() { mockedList.add("one"); mockedList.size(); mockedList.add("two"); new FullVerificationsInOrder() { { mockedList.add("one"); mockedList.size(); mockedList.add("two"); } }; }
@Test public void testContainsAll() { final int maxItems = 11; final IQueue q = client.getQueue(randomString()); List trueList = new ArrayList(); List falseList = new ArrayList(); for (int i = 0; i < maxItems; i++) { q.offer(i); trueList.add(i); falseList.add(i + 1); } assertTrue(q.containsAll(trueList)); assertFalse(q.containsAll(falseList)); }
@Test // Uses of JMockit API: 3 public void verifyInOrder( @Mocked final List<String> firstMock, @Mocked final List<String> secondMock) { // Using mocks: firstMock.add("was called first"); secondMock.add("was called second"); new VerificationsInOrder() { { // Verifies that firstMock was called before secondMock: firstMock.add("was called first"); secondMock.add("was called second"); } }; }
private List<String> dependenciesOf(Package source) { List<String> result = new ArrayList<>(); if (source.isAnnotationPresent(DependsUpon.class)) for (Class<?> target : source.getAnnotation(DependsUpon.class).packagesOf()) result.add(target.getPackage().getName()); return result; }
@Test public void should_return_values_of_property() { List<Long> ids = new ArrayList<Long>(); ids.add(yoda.getId()); when(propertySupport.propertyValues(propertyName, Long.class, employees)).thenReturn(ids); assertSame(ids, properties.from(employees)); }
List<ANTLRMessage> getMessagesOfType(List<ANTLRMessage> msgs, Class c) { List<ANTLRMessage> filtered = new ArrayList<ANTLRMessage>(); for (ANTLRMessage m : msgs) { if (m.getClass() == c) filtered.add(m); } return filtered; }
/** * Validate if BusinessObjectQuery returns business objects which are defined in the models * MODEL_NAME2 and MODEL_NAME3. Note: If BusinessObjectsList is executed standalone than * bos.size() == expected.size(). But if it is executed after CheckFiltering2 then bos.size() > * expected.size() because CheckFiltering2 deployes MODEL_NAME3 as a new version. This means that * bos.size() == expected.size()+2 in this case. */ @Test public void BusinessObjectsList() { BusinessObjectQuery query = BusinessObjectQuery.findAll(); query.setPolicy(new BusinessObjectQuery.Policy(BusinessObjectQuery.Option.WITH_DESCRIPTION)); BusinessObjects bos = sf.getQueryService().getAllBusinessObjects(query); List<String> expected = CollectionUtils.newArrayListFromElements( Arrays.asList( new QName(MODEL_NAME2, "Account").toString(), new QName(MODEL_NAME2, "Customer").toString(), new QName(MODEL_NAME2, "Order").toString(), new QName(MODEL_NAME2, "Fund").toString(), new QName(MODEL_NAME2, "FundGroup").toString(), new QName(MODEL_NAME3, "Employee").toString(), new QName(MODEL_NAME3, "Fund").toString())); List<String> removedEntries = CollectionUtils.newArrayList(expected.size()); for (BusinessObject bo : bos) { String qualifiedBOId = new QName(bo.getModelId(), bo.getId()).toString(); if (expected.remove(qualifiedBOId)) { removedEntries.add(qualifiedBOId); } else { Assert.assertTrue( "Not expected entry: " + qualifiedBOId, removedEntries.contains(qualifiedBOId)); } } Assert.assertTrue("Missing business objects: " + expected, expected.isEmpty()); }
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; }
@Test public void testQuoted1() { List l = new ArrayList(); l.add(new Symbol("apply")); l.add(new Quoted(new Symbol("+"))); l.add(1); l.add(2); List inner = new ArrayList(); inner.add(3); inner.add(4); l.add(new Quoted(inner)); lwriter.writeForm(l); assertEquals("(apply '+ 1 2 '(3 4))", output.toString()); reset(); lwriter.writeUnknown(l); assertEquals("'(apply '+ 1 2 '(3 4))", output.toString()); }
static ServerMessage doTxRx(ClientMessage... cms) { List<ClientMessage> cmArray = new ArrayList<ClientMessage>(); for (ClientMessage cm : cms) { cmArray.add(cm); } ServerMessage result = doTxRx(cmArray); return result; }
@Test public void testResolveSingletonConnectedRegions() throws BundleException, InvalidSyntaxException { RegionFilter filter = createBundleFilter(BUNDLE_B, BUNDLE_VERSION); region(REGION_A).connectRegion(region(REGION_B), filter); region(REGION_A).addBundle(bundle(BUNDLE_X)); BundleCapability collisionX = bundleCapability(BUNDLE_X); BundleCapability collisionB = bundleCapability(BUNDLE_B); List<BundleCapability> collisionCandidates = new ArrayList<BundleCapability>(); collisionCandidates.add(collisionX); collisionCandidates.add(collisionB); collisionCandidates.add(bundleCapability(BUNDLE_C)); collisionCandidates.add(bundleCapability(BUNDLE_D)); this.resolverHook.filterSingletonCollisions(bundleCapability(BUNDLE_A), collisionCandidates); assertEquals("Wrong number of collitions", 2, collisionCandidates.size()); collisionCandidates.contains(collisionX); collisionCandidates.contains(collisionB); }
@Test public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { // single empty string List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " "); assertEquals(1, pairs.size()); // list of empty strings List<String> strs = new ArrayList<String>(); strs.add(" "); strs.add(" "); strs.add(" "); List<Pair> concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); assertEquals(1, concatStrings.size()); assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters }
@Test public void test_next() { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); Cursor<Integer> it = new Cursor<Integer>(list); assertEquals("[1,2].next", 1, (Object) it.next()); assertEquals("[2].next", 2, (Object) it.next()); }
public List<Integer> getTokenTypes(String input, LexerATNSimulator lexerATN) { ANTLRStringStream in = new ANTLRStringStream(input); List<Integer> tokenTypes = new ArrayList<Integer>(); int ttype = 0; do { ttype = lexerATN.matchATN(in); tokenTypes.add(ttype); } while (ttype != Token.EOF); return tokenTypes; }
List<Integer> getTypesFromString(Grammar g, String expecting) { List<Integer> expectingTokenTypes = new ArrayList<Integer>(); if (expecting != null && !expecting.trim().equals("")) { for (String tname : expecting.replace(" ", "").split(",")) { int ttype = g.getTokenType(tname); expectingTokenTypes.add(ttype); } } return expectingTokenTypes; }
/** Generates a simple <add><doc>... XML String with no options */ public String adoc(SolrInputDocument sdoc) { List<String> fields = new ArrayList<String>(); for (SolrInputField sf : sdoc) { for (Object o : sf.getValues()) { fields.add(sf.getName()); fields.add(o.toString()); } } return adoc(fields.toArray(new String[fields.size()])); }
protected static List<HRegionInfo> getRegionInfoList(ServerName serverName, String tableName) throws IOException { List<HRegionInfo> onlineRegions = new ArrayList<>(); for (HRegionInfo onlineRegion : CommandAdapter.getOnlineRegions(null, admin, serverName)) { if (onlineRegion.getTableNameAsString().equals(tableName)) { onlineRegions.add(onlineRegion); } } return onlineRegions; }
@Test public void testInventory() throws IOException, ClassNotFoundException { inv.addToInventory(k1); inv.addToInventory(c2); inv.addToInventory(c3); inv.addToInventory(w4); inv.addToInventory(w5); inv.addToInventory(a1); inv.addToInventory(a2); inv.addToInventory(a3); inv.addToInventory(a4); inv.addToInventory(a5); enemyList.add(mazer); // enemyList.add(plucifer); enemyList.add(bullies); fOut = new FileOutputStream("game.dat"); ObjectOutputStream serializer = new ObjectOutputStream(fOut); serializer.writeObject(inv); serializer.writeObject(enemyList); serializer.flush(); inv = null; enemyList = null; fIn = new FileInputStream("game.dat"); ObjectInputStream deserializer = new ObjectInputStream(fIn); inv = (Inventory) deserializer.readObject(); enemyList = (List<Enemy>) deserializer.readObject(); for (int i = 0; i < 10; i++) { player.getPlayerInventory().useItem(); } enemyList.get(0).fight(player); enemyList.get(1).fight(player); // enemyList.get(2).fight(player); System.out.println("You have disengaged from combat."); System.out.println("Player score is now " + player.getPlayerScore()); System.out.println("Player HP is " + player.getPlayerCurrentHP()); }
@Test public void test_clone() { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); Cursor<Integer> it = new Cursor<Integer>(list); it.next(); Cursor<Integer> it2 = it.clone(); assertEquals("clone+hasNext #1", true, (Object) it2.hasNext()); assertEquals("clone+next #1", 2, (Object) it2.next()); }
@Test(expected = UnexpectedInvocation.class) // Uses of JMockit API: 2 public void verifyThatInvocationsNeverHappenedWhenTheyDid(@Mocked List<String> mockTwo) { mockedList.add("one"); mockTwo.size(); new FullVerifications() { { mockedList.add("one"); } }; }
@Test public void test_hasNext_1() { List<Integer> list = new ArrayList<Integer>(); list.add(1); Cursor<Integer> it = new Cursor<Integer>(list); assertEquals("[1].hasNext #1", true, it.hasNext()); assertEquals("[1].hasNext #2", true, it.hasNext()); it.next(); assertEquals("[].hasNext #1", false, it.hasNext()); assertEquals("[].hasNext #2", false, it.hasNext()); }
@Test(expected = MissingInvocation.class) // Uses of JMockit API: 1 public void verifyAllInvocationsInOrderWithOutOfOrderVerifications() { mockedList.add("one"); mockedList.add("two"); new FullVerificationsInOrder() { { mockedList.add("two"); mockedList.add("one"); } }; }
/** Return true if all is ok, no errors */ protected boolean antlr( String fileName, String grammarFileName, String grammarStr, boolean debug) { boolean allIsWell = true; mkdir(tmpdir); writeFile(tmpdir, fileName, grammarStr); try { final List options = new ArrayList(); if (debug) { options.add("-debug"); } options.add("-o"); options.add(tmpdir); options.add("-lib"); options.add(tmpdir); options.add(new File(tmpdir, grammarFileName).toString()); final String[] optionsA = new String[options.size()]; options.toArray(optionsA); ErrorQueue equeue = new ErrorQueue(); Tool antlr = newTool(optionsA); antlr.addListener(equeue); antlr.processGrammarsOnCommandLine(); if (equeue.errors.size() > 0) { allIsWell = false; System.err.println("antlr reports errors from " + options); for (int i = 0; i < equeue.errors.size(); i++) { ANTLRMessage msg = (ANTLRMessage) equeue.errors.get(i); System.err.println(msg); } System.out.println("!!!\ngrammar:"); System.out.println(grammarStr); System.out.println("###"); } } catch (Exception e) { allIsWell = false; System.err.println("problems building grammar: " + e); e.printStackTrace(System.err); } return allIsWell; }