@Test public void canFollowLogfile() throws IOException { File tempFile = File.createTempFile("commons-io", "", new File(System.getProperty("java.io.tmpdir"))); tempFile.deleteOnExit(); System.out.println("Temp file = " + tempFile.getAbsolutePath()); PrintStream log = new PrintStream(tempFile); LogfileFollower follower = new LogfileFollower(tempFile); List<String> lines; // Empty file: lines = follower.newLines(); assertEquals(0, lines.size()); // Write two lines: log.println("Line 1"); log.println("Line 2"); lines = follower.newLines(); assertEquals(2, lines.size()); assertEquals("Line 2", lines.get(1)); // Write one more line: log.println("Line 3"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 3", lines.get(0)); // Write one and a half line and finish later: log.println("Line 4"); log.print("Line 5 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); // End last line and start a new one: log.println(" end"); log.print("Line 6 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 5 begin end", lines.get(0)); // End last line: log.println(" end"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 6 begin end", lines.get(0)); // A line only missing a newline: log.print("Line 7"); lines = follower.newLines(); assertEquals(0, lines.size()); log.println(); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 7", lines.get(0)); // Delete: log.close(); lines = follower.newLines(); assertEquals(0, lines.size()); }
@Test public void postComments() { // Create a new user and save it User bob = new User("*****@*****.**", "secret", "Bob").save(); // Create a new post Post bobPost = new Post(bob, "My first post", "Hello world").save(); // Post a first comment new Comment(bobPost, "Jeff", "Nice Post").save(); new Comment(bobPost, "Tom", "I knew that !").save(); // Retrieve all comments List<Comment> bobPostComments = Comment.find("byPost", bobPost).fetch(); // Tests assertEquals(2, bobPostComments.size()); Comment firstComment = bobPostComments.get(0); assertNotNull(firstComment); assertEquals("Jeff", firstComment.author); assertEquals("Nice Post", firstComment.content); assertNotNull(firstComment.postedAt); Comment secondComment = bobPostComments.get(1); assertNotNull(secondComment); assertEquals("Tom", secondComment.author); assertEquals("I knew that !", secondComment.content); assertNotNull(secondComment.postedAt); }
private void doControlTask() throws IOException, ClassNotFoundException { BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler(); client.getTasksAssignedAsPotentialOwner("control", "en-UK", handler); List<TaskSummary> sums = handler.getResults(); assertNotNull(sums); assertEquals(1, sums.size()); BlockingTaskOperationResponseHandler startTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.start(sums.get(0).getId(), "control", startTaskOperationHandler); BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler(); client.getTask(sums.get(0).getId(), getTaskHandler); Task controlTask = getTaskHandler.getTask(); BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler(); client.getContent(controlTask.getTaskData().getDocumentContentId(), getContentHandler); Content content = getContentHandler.getContent(); assertNotNull(content); ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent()); ObjectInputStream ois = new ObjectInputStream(bais); Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject(); Emergency retrivedEmergency = (Emergency) deserializedContent.get("emergency"); assertNotNull(retrivedEmergency); ActivePatients retrivedActivePatients = (ActivePatients) deserializedContent.get("activePatients"); assertNotNull(retrivedActivePatients); assertEquals(1, retrivedActivePatients.size()); SuggestedProcedures retrivedSuggestedProcedures = (SuggestedProcedures) deserializedContent.get("suggestedProcedures"); assertNotNull(retrivedSuggestedProcedures); assertEquals( "[DefaultHeartAttackProcedure: ]", retrivedSuggestedProcedures.getSuggestedProceduresString()); Map<String, Object> info = new HashMap<String, Object>(); SelectedProcedures selectedProcedures = new SelectedProcedures(retrivedEmergency.getId()); selectedProcedures.addSelectedProcedureName("DefaultHeartAttackProcedure"); info.put("selectedProcedures", selectedProcedures); ContentData result = new ContentData(); result.setAccessType(AccessType.Inline); result.setType("java.util.Map"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(info); out.close(); result.setContent(bos.toByteArray()); BlockingTaskOperationResponseHandler completeTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.complete(sums.get(0).getId(), "control", result, completeTaskOperationHandler); }
private void assertResultFromTextFileParsing(List<String[]> result) { assertEquals(2, result.size()); String[] line1 = result.get(0); assertEquals(1, line1.length); assertEquals("line1", line1[0]); String[] line2 = result.get(1); assertEquals(2, line2.length); assertEquals("another", line2[0]); assertEquals("line", line2[1]); }
private void doOperatorTask() throws ClassNotFoundException, IOException { BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler(); client.getTasksAssignedAsPotentialOwner("operator", "en-UK", handler); List<TaskSummary> sums = handler.getResults(); assertNotNull(sums); assertEquals(1, sums.size()); BlockingTaskOperationResponseHandler startTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.start(sums.get(0).getId(), "operator", startTaskOperationHandler); BlockingGetTaskResponseHandler getTaskHandler = new BlockingGetTaskResponseHandler(); client.getTask(sums.get(0).getId(), getTaskHandler); Task operatorTask = getTaskHandler.getTask(); BlockingGetContentResponseHandler getContentHandler = new BlockingGetContentResponseHandler(); client.getContent(operatorTask.getTaskData().getDocumentContentId(), getContentHandler); Content content = getContentHandler.getContent(); assertNotNull(content); ByteArrayInputStream bais = new ByteArrayInputStream(content.getContent()); ObjectInputStream ois = new ObjectInputStream(bais); Map<String, Object> deserializedContent = (Map<String, Object>) ois.readObject(); Call restoredCall = (Call) deserializedContent.get("call"); persistenceService.storeCall(restoredCall); Emergency emergency = new Emergency(); emergency.setCall(restoredCall); emergency.setLocation(new Location(1, 2)); emergency.setType(Emergency.EmergencyType.HEART_ATTACK); emergency.setNroOfPeople(1); persistenceService.storeEmergency(emergency); trackingService.attachEmergency(restoredCall.getId(), emergency.getId()); Map<String, Object> info = new HashMap<String, Object>(); info.put("emergency", emergency); ContentData result = new ContentData(); result.setAccessType(AccessType.Inline); result.setType("java.util.Map"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(info); out.close(); result.setContent(bos.toByteArray()); BlockingTaskOperationResponseHandler completeTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.complete(sums.get(0).getId(), "operator", result, completeTaskOperationHandler); }
@Test public void testGetAllPartitionKeys() throws Exception { CloudTableClient tableClient = createTableClient(); assumeNotNull(tableClient); t = createTable(tableClient); insertRow(t, "p1", "r1"); insertRow(t, "p1", "r2"); insertRow(t, "p2", "r1"); insertRow(t, "p3", "r1"); List<String> partitionKeys = DefaultTablePartitioner.getAllPartitionKeys(t); assertEquals(3, partitionKeys.size()); assertEquals("p1", partitionKeys.get(0)); assertEquals("p2", partitionKeys.get(1)); assertEquals("p3", partitionKeys.get(2)); }
@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 // Uses of JMockit API: 8 public void useArgumentMatchers() { new Expectations() { { // Using built-in matchers: mockedList.get(anyInt); result = "element"; // Using Hamcrest matchers: mockedList.get(withArgThat(is(equalTo(5)))); result = new IllegalArgumentException(); minTimes = 0; mockedList.contains(withArgThat(hasProperty("bytes"))); result = true; mockedList.containsAll(withArgThat(hasSize(2))); result = true; } }; assertEquals("element", mockedList.get(999)); assertTrue(mockedList.contains("abc")); assertTrue(mockedList.containsAll(asList("a", "b"))); new Verifications() { { mockedList.get(anyInt); } }; }
@Test // Uses of JMockit API: 3 public void returningElementsFromAList() { final List<String> list = asList("a", "b", "c"); new Expectations() { { mockedList.get(anyInt); result = list; } }; assertEquals("a", mockedList.get(0)); assertEquals("b", mockedList.get(1)); assertEquals("c", mockedList.get(2)); assertEquals("c", mockedList.get(3)); }
@Before public void setup() { for (int customerId = 1; customerId <= 5; customerId++) { ProcessInstance pi = sf.getWorkflowService() .startProcess(new QName(MODEL_NAME2, "OrderCreation").toString(), null, true); List<ActivityInstance> w = getWorklist(); Assert.assertEquals("worklist", 1, w.size()); ActivityInstance ai = w.get(0); Assert.assertEquals("process instance", pi.getOID(), ai.getProcessInstanceOID()); Assert.assertEquals("activity instance", "EnterOrderData", ai.getActivity().getId()); Map<String, Object> order = CollectionUtils.newMap(); order.put("date", new Date()); order.put("customerId", customerId); ai = complete( ai, PredefinedConstants.DEFAULT_CONTEXT, Collections.singletonMap("Order", order)); try { ProcessInstanceStateBarrier.instance().await(pi.getOID(), ProcessInstanceState.Completed); } catch (Exception e) { } w = getWorklist(); } }
@Test public void findRepostByAccounts_String_複数_降順_00() { List<RepostBase> lst = RepostBase.findRepostByAccounts("usr-goro", "usr-jiro") .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(24)); assertThat(lst.get(0).contributor.loginUser.screenName, is("goro_san")); }
@Test @SuppressWarnings("unchecked") public void parse_object() throws IOException { List<Object> members = (List<Object>) parser.parse(resources.sourceFile(Paths.get("_data", "members.yml"))); assertThat(members).hasSize(3); assertThat((Map<String, Object>) members.get(0)) .containsExactly(entry("name", "Tom Preston-Werner"), entry("github", "mojombo")); }
@Test public void testParameterToPairsWhenValueIsNotCollection() throws Exception { String name = "param-a"; Integer value = 1; List<Pair> pairs = apiClient.parameterToPairs("csv", name, value); assertEquals(1, pairs.size()); assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); }
// -------------------------------------+ @Test public void findRepostByAccounts_Entity_単数_降順_00() { Account acnt1 = Account.findByLoginName("goro_san").first(); List<RepostBase> lst = RepostBase.findRepostByAccounts(acnt1) .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(17)); assertThat(lst.get(0).contributor.loginUser.screenName, is("goro_san")); }
@Test public void findRepostByTweets_String_複数_投稿者_降順_00() { Account acnt = Account.findByLoginName("goro_san").first(); List<RepostBase> lst = RepostBase.findRepostByTweets("twt-goro2", "twt-jiro1") .contributor(acnt) .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(5)); assertThat(lst.get(0).getItem().serialCode, is("twt-jiro1")); }
@Test public void findRepostByCategories_String_複数_投稿者_降順_00() { Account acnt = Account.findByLoginName("goro_san").first(); List<RepostBase> lst = RepostBase.findRepostByCategories("cat-biz", "cat-enta") .contributor(acnt) .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(3)); assertThat(lst.get(0).getLabel().serialCode, is("cat-biz")); }
@Test public void testCollectToList() { Observable<List<Integer>> o = Observable.just(1, 2, 3).collect(ArrayList::new, (list, v) -> list.add(v)); List<Integer> list = o.toBlocking().last(); assertEquals(3, list.size()); assertEquals(1, list.get(0).intValue()); assertEquals(2, list.get(1).intValue()); assertEquals(3, list.get(2).intValue()); // test multiple subscribe List<Integer> list2 = o.toBlocking().last(); assertEquals(3, list2.size()); assertEquals(1, list2.get(0).intValue()); assertEquals(2, list2.get(1).intValue()); assertEquals(3, list2.get(2).intValue()); }
@Test public void findRepostByTags_String_複数_投稿者_降順_00() { Account acnt = Account.findByLoginName("goro_san").first(); List<RepostBase> lst = RepostBase.findRepostByTags("tag-goro-red", "tag-jiro-hello") .contributor(acnt) .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(3)); assertThat(lst.get(0).getLabel().serialCode, is("tag-goro-red")); }
private void doGarageTask() { BlockingTaskSummaryResponseHandler handler = new BlockingTaskSummaryResponseHandler(); client.getTasksAssignedAsPotentialOwner("garage_emergency_service", "en-UK", handler); List<TaskSummary> sums = handler.getResults(); assertNotNull(sums); assertEquals(1, sums.size()); BlockingTaskOperationResponseHandler startTaskOperationHandler = new BlockingTaskOperationResponseHandler(); client.start(sums.get(0).getId(), "garage_emergency_service", startTaskOperationHandler); }
// -------------------------------------+ @Test public void findRepostByUsers_Entity_単数_投稿者_降順_00() { User usr1 = User.findBySerialCode("usr-goro").first(); Account acnt = Account.findByLoginName("goro_san").first(); List<RepostBase> lst = RepostBase.findRepostByUsers(usr1) .contributor(acnt) .orderBy(RepostBase.OrderBy.DATE_OF_REPOST_DESC) .fetch(); assertThat(lst.size(), is(2)); assertThat(lst.get(0).getItem().serialCode, is("usr-goro")); }
@Test public void receiveAnOrder() throws Exception { when(request.getMethod()).thenReturn("POST"); when(request.getRequestURI()).thenReturn("/orders"); when(request.getParameter("order_code")).thenReturn("1234"); when(request.getParameter("article_code")).thenReturn("ABCD"); when(request.getParameter("address")).thenReturn("Some Place"); ordersController.service(); assertEquals(1, orders.size()); assertEquals(new Order("1234", "ABCD", "Some Place"), orders.get(0)); }
@Ignore // don't care for any reordering @Test(timeout = 10000) public void flatMapRangeAsyncLoop() { for (int i = 0; i < 2000; i++) { if (i % 10 == 0) { System.out.println("flatMapRangeAsyncLoop > " + i); } TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 1000) .flatMap( new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t) { return Observable.just(t); } }) .observeOn(Schedulers.computation()) .subscribe(ts); ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); if (ts.getOnCompletedEvents().isEmpty()) { System.out.println(ts.getOnNextEvents().size()); } ts.assertTerminalEvent(); ts.assertNoErrors(); List<Integer> list = ts.getOnNextEvents(); assertEquals(1000, list.size()); boolean f = false; for (int j = 0; j < list.size(); j++) { if (list.get(j) != j) { System.out.println(j + " " + list.get(j)); f = true; } } if (f) { Assert.fail("Results are out of order!"); } } }
@Test // Uses of JMockit API: 3 public void stubAndVerifyInvocationWithoutRepeatingItInExpectationAndVerificationBlocks() { new Expectations() { { // Notice that this can't be done in Mockito, which requires the repetition of // "mockedList.get(0);" in the verification phase. mockedList.get(0); result = "first"; times = 1; } }; assertEquals("first", mockedList.get(0)); }
/** * Execute a query contained in the given named file. This methods tries to find the given file * within the directory src/test/resources/results/<i>ClassName</i>. * * @param queryFileName The file name to be used to execute a query. * @return ResultSet of query execution. */ public ResultSet executeFile(String queryFileName) throws Exception { Path queryFilePath = getQueryFilePath(queryFileName); FileSystem fs = currentQueryPath.getFileSystem(testBase.getTestingCluster().getConfiguration()); assertTrue(queryFilePath.toString() + " existence check", fs.exists(queryFilePath)); List<ParsedResult> parsedResults = SimpleParser.parseScript(FileUtil.readTextFile(new File(queryFilePath.toUri()))); if (parsedResults.size() > 1) { assertNotNull("This script \"" + queryFileName + "\" includes two or more queries"); } ResultSet result = client.executeQueryAndGetResult(parsedResults.get(0).getStatement()); assertNotNull("Query succeeded test", result); return result; }
@Test public void createTransactionReturnsOk() { // create "cars" transaction Response response = client .path("/transactionservice/transaction/10") .request() .put(Entity.json(new Transaction("cars", new BigDecimal(5000), 0l))); assertEquals(200, response.getStatus()); assertEquals( TransactionService.OperationResult.OK, response.readEntity(TransactionService.OperationResult.class)); // create "shopping" transaction response = client .path("/transactionservice/transaction/11") .request() .put(Entity.json(new Transaction("shopping", new BigDecimal(10000), 10l))); assertEquals(200, response.getStatus()); assertEquals( TransactionService.OperationResult.OK, response.readEntity(TransactionService.OperationResult.class)); // get "cars" transactions response = client.path("/transactionservice/type/cars").request().get(); assertEquals(200, response.getStatus()); @SuppressWarnings("unchecked") List<Integer> ids = response.readEntity(List.class); assertEquals(1, ids.size()); assertEquals(10, ids.get(0).intValue()); // get "sum" for transaction 10 response = client.path("/transactionservice/sum/10").request().get(); assertEquals(200, response.getStatus()); AggregatorService.Sum sum = response.readEntity(AggregatorService.Sum.class); assertEquals(15000, sum.getSum().intValue()); // get "sum" for transaction 11 response = client.path("/transactionservice/sum/11").request().get(); assertEquals(200, response.getStatus()); sum = response.readEntity(AggregatorService.Sum.class); assertEquals(10000, sum.getSum().intValue()); }
@Test // Uses of JMockit API: 3 public void stubAndVerifyInvocation() { // A recorded expectation is expected to occur at least once, by default. new Expectations() { { mockedList.get(0); result = "first"; } }; assertEquals("first", mockedList.get(0)); // Note that verifying a stubbed invocation isn't "just redundant" if the test cares that the // invocation occurs at least once. If this is the case, then it's not safe to expect the test // to break without an explicit verification, because the method under test may never call the // stubbed one, and that would be a bug that the test should detect. }
@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 reads_a_list_of_entries() throws Exception { ZipContents zipContents = new ZipContents(new File("./src/test/resource/test.zip")); try { zipContents.open(); List<ZipContentsEntry> entries = zipContents.entries(); assertThat(entries.size(), is(6)); ZipContentsEntry firstEntry = entries.get(0); assertThat(firstEntry.directory(), is("/")); assertThat(firstEntry.name(), is("file_1.txt")); assertThat(firstEntry.type(), is("txt")); } finally { zipContents.close(); } }
@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 testTopologicalSort() { final Set<Object> nodes = new HashSet<Object>(); final Object centerNode = "centerNode"; nodes.add(centerNode); final Object topNode = "topNode"; nodes.add(topNode); final Object leftNode = "leftNode"; nodes.add(leftNode); final Object leftiestNode = "leftiestNode"; nodes.add(leftiestNode); final Object rightNode = "rightNode"; nodes.add(rightNode); final Set<DirectedEdge<Object>> edges = new HashSet<DirectedEdge<Object>>(); final DirectedEdge<Object> centerTopEdge = new ImmutableDirectedEdge<Object>(centerNode, topNode); edges.add(centerTopEdge); final DirectedEdge<Object> centerLeftEdge = new ImmutableDirectedEdge<Object>(centerNode, leftNode); edges.add(centerLeftEdge); final DirectedEdge<Object> leftLeftiestEdge = new ImmutableDirectedEdge<Object>(leftNode, leftiestNode); edges.add(leftLeftiestEdge); final DirectedEdge<Object> centerRightEdge = new ImmutableDirectedEdge<Object>(centerNode, rightNode); edges.add(centerRightEdge); final BidirectedGraph<Object, DirectedEdge<Object>> graph = new ImmutableDirectedAdjacencyGraph<Object, DirectedEdge<Object>>(nodes, edges); final TopologicalSorter<Object> sorter = new SimpleTopologicalRanker<Object>(); final List<Object> sortedNodes = sorter.sort(graph); Assert.assertTrue("center node is not the first node!", sortedNodes.get(0) == centerNode); Assert.assertTrue( "left node is not before leftiest node!", sortedNodes.indexOf(leftNode) < sortedNodes.indexOf(leftiestNode)); }