@Test public void system_size() throws IOException, CompressorException, ArchiveException { ProcessingManager mgr = new ProcessingManager(); long size = mgr.system_size(sample); Assert.assertEquals(size, 494928); File folder=sample.getParentFile(); File extaction_folder=new File(folder, "unzip"); extaction_folder.mkdirs(); UnZip.unCompress(sample.getAbsolutePath(), extaction_folder.getAbsolutePath()); File tocheck = extaction_folder.listFiles()[0]; size = mgr.system_size(tocheck); Assert.assertEquals(size, SIZE, tocheck.getAbsolutePath()); }
@Test public void testToFromByteArray(){ boolean one = true; boolean two = false; boolean three = false; List<Boolean> booleans = new ArrayList<>(); booleans.add(one); booleans.add(null); booleans.add(null); booleans.add(two); booleans.add(three); byte[] booleanBytes = getBooleanByteArray(booleans); List<Boolean> result = fromBooleanByteArray(booleanBytes, 0); Assert.assertEquals(result, booleans); }
@Test public void successAllTest() throws IOException { ReplaceText replaceText = new ReplaceText("foo").setReplacement("zoo").relative("/src/main/resources/application.properties").setFirstOnly(false); TOExecutionResult executionResult = replaceText.execution(transformedAppFolder, transformationContext); Assert.assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS); assertChangedFile("/src/main/resources/application.properties"); assertSameLineCount("/src/main/resources/application.properties"); Properties properties = getProperties("/src/main/resources/application.properties"); Assert.assertEquals(properties.size(), 3); Assert.assertEquals(properties.getProperty("bar"), "barv"); Assert.assertEquals(properties.getProperty("zoo"), "zoov"); Assert.assertEquals(properties.getProperty("zoozoo"), "zoozoov"); }
@Test(enabled = false) public void testOAuthWithTokenLogin() throws Exception { HttpResponse response = defaultClientTokenRequest("token", TokenSecurity.createSecureToken("AutoTest", "token", "token", null)); String string = EntityUtils.toString(response.getEntity()); Assert.assertTrue(string.contains("oal_allowButton"), "Should be logged in"); response = defaultClientTokenRequestPost("event__", "oal.allowAccess"); Assert.assertTrue(hasAccessToken(response)); // we should be able to make REST calls with this token as the AutoTest // user }
@Test public void testAddElementToGlobalNs() throws Exception { // Create empty SOAP message SOAPMessage msg = createSoapMessage(); SOAPBody body = msg.getSOAPPart().getEnvelope().getBody(); // Add elements SOAPElement parentExplicitNS = body.addChildElement("content", "", TEST_NS); parentExplicitNS.addNamespaceDeclaration("", TEST_NS); SOAPElement childGlobalNS = parentExplicitNS.addChildElement("global-child", "", ""); childGlobalNS.addNamespaceDeclaration("", ""); SOAPElement grandChildGlobalNS = childGlobalNS.addChildElement("global-grand-child"); SOAPElement childDefaultNS = parentExplicitNS.addChildElement("default-child"); // Check namespace URIs Assert.assertNull(childGlobalNS.getNamespaceURI()); Assert.assertNull(grandChildGlobalNS.getNamespaceURI()); Assert.assertEquals(childDefaultNS.getNamespaceURI(), TEST_NS); }
@Test public void testFactoryFind() throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(null)); factory = TransformerFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(new MyClassLoader())); factory = TransformerFactory.newInstance(); if (System.getSecurityManager() == null) Assert.assertTrue(myClassLoaderUsed); else Assert.assertFalse(myClassLoaderUsed); }
@Test() static void checkLastHandler() { if (RUNNING_WITH_Xrs) { return; } Signal signal = new Signal("TERM"); Handler h1 = new Handler(); Handler h2 = new Handler(); SignalHandler orig = Signal.handle(signal, h1); if (orig == SignalHandler.SIG_IGN) { // SIG_IGN for TERM means it cannot be handled return; } try { SignalHandler prev = Signal.handle(signal, h2); Assert.assertSame(prev, h1, "prev handler mismatch"); prev = Signal.handle(signal, h1); Assert.assertSame(prev, h2, "prev handler mismatch"); } finally { if (orig != null && signal != null) { Signal.handle(signal, orig); } } }
public void testSAX(boolean setUseCatalog, boolean useCatalog, String catalog, String xml, MyHandler handler, String expected) throws Exception { SAXParser parser = getSAXParser(setUseCatalog, useCatalog, catalog); parser.parse(xml, handler); Assert.assertEquals(handler.getResult().trim(), expected); }
@Test public void nonStemmedAnalyzeTest() { ModelMetadata metadata = ModelMetadata.createDefault().applyStemmer(0); IndraAnalyzer analyzer = new IndraAnalyzer(LANG, metadata); String loveString = "love"; List<String> res = analyzer.analyze(loveString); Assert.assertEquals(res.size(), 1); Assert.assertEquals(res.get(0), loveString); loveString = "LOVE"; res = analyzer.analyze(loveString); Assert.assertEquals(res.size(), 1); Assert.assertEquals(res.get(0), loveString.toLowerCase()); }
/** * This wrapper method allows for potential post-processing, such as * removing tags that we don't care to compare in {@code returnedTree}. * * @param returnedTree The returned tree from the web service. * @param expectedTree The simulated tree that we expect. */ private void assertEqualTrees(ConsumableTree<TestSpan> returnedTree, ConsumableTree<TestSpan> expectedTree) { // It's okay if the returnedTree has tags other than the ones we // want to compare, so just remove those returnedTree.visitTree(span -> span.getTags().keySet() .removeIf(key -> !key.equals(Tags.SPAN_KIND.getKey()) && !key.equals(Tags.HTTP_METHOD.getKey()) && !key.equals(Tags.HTTP_URL.getKey()) && !key.equals(Tags.HTTP_STATUS.getKey()) && !key.equals(TestServerWebServices.LOCAL_SPAN_TAG_KEY))); // It's okay if the returnedTree has log entries other than the ones we // want to compare, so just remove those returnedTree.visitTree(span -> span.getLogEntries() .removeIf(logEntry -> true)); Assert.assertEquals(returnedTree, expectedTree); }
@Test public void testBoolean(){ ManyFieldBean bean = new ManyFieldBean(); //test true value bean.setBooleanField(true); mapNode.put(bean, null); ManyFieldBean roundTripped = mapNode.get(bean.getKey(), null); Assert.assertNotSame(roundTripped, bean); Assert.assertEquals(roundTripped.getBooleanField(), bean.getBooleanField()); //test false value bean.setBooleanField(false); mapNode.put(bean, null); ManyFieldBean roundTrippedFalse = mapNode.get(bean.getKey(), null); Assert.assertNotSame(roundTrippedFalse, bean); Assert.assertEquals(roundTrippedFalse.getBooleanField(), bean.getBooleanField()); }
@SuppressWarnings("unchecked") @Test(dataProvider = "arrays") public <T> void testCreateByIterable4(Array<T> array) { final List<T> list = array.stream().values().collect(Collectors.toList()); final Index<T> index1 = Index.of((Iterable)list); final Index<T> index2 = Index.of((Collection)list); Assert.assertEquals(index1.size(), list.size(), "Size matches array length"); Assert.assertEquals(index2.size(), list.size(), "Size matches array length"); for (int i=0; i<index1.size(); ++i) { final T key = index1.getKey(i); Assert.assertEquals(key, list.get(i), "Key matches array value at " + i); Assert.assertEquals(index1.getIndexForKey(key), i, "Index matches for ordinal " + i); Assert.assertEquals(index1.getOrdinalForKey(key), i, "Ordinals match"); Assert.assertEquals(index1.getIndexForOrdinal(i), i, "Ordinal and index match"); Assert.assertEquals(index2.getIndexForKey(key), index1.getIndexForKey(key), "Index matches for ordinal " + i); Assert.assertEquals(index2.getOrdinalForKey(key), index1.getOrdinalForKey(key), "Ordinals match"); Assert.assertEquals(index2.getIndexForOrdinal(i), index1.getIndexForOrdinal(i), "Ordinal and index match"); } }
@Test @SuppressWarnings("unchecked") public void testPOSTResourcesMissingIdentifier() throws Exception { List<BaseResource> resources = JSON_UTILS .deserializeFromFile("controller-test/missing-identifier-resources-collection.json", List.class); Assert.assertNotNull(resources); // Append a list of resources MockMvcContext postContext = TEST_UTILS.createWACWithCustomPOSTRequestBuilder(this.wac, this.testZone.getSubdomain(), RESOURCE_BASE_URL); postContext.getMockMvc() .perform(postContext.getBuilder().contentType(MediaType.APPLICATION_JSON) .content(OBJECT_MAPPER.writeValueAsString(resources))) .andExpect(status().isUnprocessableEntity()); }
@Test public void testRepairNotification(){ Notifications noti = new Notifications(); noti.setAntennaClient(antennaClientMock); noti.setCmProcessor(cmProcessorMock); noti.setEnvProcessor(envProcessorMock); EventUtil eventUtil = new EventUtil(); eventUtil.setGson(new Gson()); noti.setEventUtil(eventUtil); CiChangeStateEvent event = getCiChangeEvent(UNHEALTHY, NOTIFY, OPEN, NEW); OpsBaseEvent opsEvent = eventUtil.getOpsEvent(event); NotificationMessage message = noti.sendRepairNotification(event, null); String subject = message.getSubject(); String text = message.getText(); Assert.assertEquals(subject, getSubjPrefix()+opsEvent.getName()+SUBJECT_SUFFIX_OPEN_EVENT); Assert.assertEquals(text, CI_NAME +" is in "+event.getNewState()+" state"+TEXT_NOTE_SEPERATOR+Notifications.REPAIR_IN_PROGRESS); Assert.assertEquals(message.getSource(),"ops"); Assert.assertEquals(message.getPayload().get(Notifications.CLASS_NAME),MOCK_CI_CLASS_NAME); Assert.assertEquals(message.getPayload().get(Notifications.OLD_STATE),NOTIFY); Assert.assertEquals(message.getPayload().get(Notifications.NEW_STATE),UNHEALTHY); Assert.assertEquals(message.getPayload().get(Notifications.STATUS),NEW); Assert.assertEquals(message.getPayload().get(Notifications.STATE),OPEN); Assert.assertEquals(message.getSeverity(), NotificationSeverity.warning); }
@Test() public void testLowerAndHigherValueOnSortedStringArray() { final Array<String> array = Array.of("a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"); Assert.assertEquals(array.previous("e").map(ArrayValue::getValue).get(), "c", "Lower value than e"); Assert.assertEquals(array.previous("g").map(ArrayValue::getValue).get(), "e", "Lower value than g"); Assert.assertEquals(array.previous("i").map(ArrayValue::getValue).get(), "g", "Lower value than i"); Assert.assertEquals(array.previous("q").map(ArrayValue::getValue).get(), "o", "Lower value than q"); Assert.assertEquals(array.previous("b").map(ArrayValue::getValue).get(), "a", "Lower value than e"); Assert.assertEquals(array.previous("f").map(ArrayValue::getValue).get(), "e", "Lower value than g"); Assert.assertEquals(array.previous("h").map(ArrayValue::getValue).get(), "g", "Lower value than i"); Assert.assertEquals(array.previous("p").map(ArrayValue::getValue).get(), "o", "Lower value than q"); Assert.assertEquals(array.next("e").map(ArrayValue::getValue).get(), "g", "Lower value than e"); Assert.assertEquals(array.next("g").map(ArrayValue::getValue).get(), "i", "Lower value than g"); Assert.assertEquals(array.next("i").map(ArrayValue::getValue).get(), "k", "Lower value than i"); Assert.assertEquals(array.next("q").map(ArrayValue::getValue).get(), "s", "Lower value than q"); Assert.assertEquals(array.next("b").map(ArrayValue::getValue).get(), "c", "Lower value than e"); Assert.assertEquals(array.next("f").map(ArrayValue::getValue).get(), "g", "Lower value than g"); Assert.assertEquals(array.next("h").map(ArrayValue::getValue).get(), "i", "Lower value than i"); Assert.assertEquals(array.next("p").map(ArrayValue::getValue).get(), "q", "Lower value than q"); }
public void test() { WxCpXmlOutTextMessage m = new WxCpXmlOutTextMessage(); m.setContent("content"); m.setCreateTime(1122l); m.setFromUserName("from"); m.setToUserName("to"); String expected = "<xml>" + "<ToUserName><![CDATA[to]]></ToUserName>" + "<FromUserName><![CDATA[from]]></FromUserName>" + "<CreateTime>1122</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[content]]></Content>" + "</xml>"; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); }
@RunAsClient @Test(groups = TEST_GROUP_CDI_PROVIDER, description = "Verify that the injected exp claim is as expected") public void verifyInjectedExpiration() throws Exception { Reporter.log("Begin verifyInjectedExpiration\n"); String uri = baseURL.toExternalForm() + "/endp/verifyInjectedExpiration"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam(Claims.exp.name(), expClaim) .queryParam(Claims.auth_time.name(), authTimeClaim); Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK); String replyString = response.readEntity(String.class); JsonReader jsonReader = Json.createReader(new StringReader(replyString)); JsonObject reply = jsonReader.readObject(); Reporter.log(reply.toString()); Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg")); }
@RunAsClient @Test(groups = TEST_GROUP_JWT, description = "Verify that the token sub claim is as expected") public void verifySubClaim() throws Exception { Reporter.log("Begin verifySubClaim"); String uri = baseURL.toExternalForm() + "/endp/verifySUB"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam(Claims.sub.name(), "24400320") .queryParam(Claims.auth_time.name(), authTimeClaim); Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK); String replyString = response.readEntity(String.class); JsonReader jsonReader = Json.createReader(new StringReader(replyString)); JsonObject reply = jsonReader.readObject(); Reporter.log(reply.toString()); Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg")); }
@Test(groups = "License.constructor") public void License_should_return_new_object_of_License_class() { try { License api = new License(config); Assert.assertNotNull(api); Field fConfig = api.getClass().getDeclaredField("mConfig"); fConfig.setAccessible(true); StockConfig mConfig = (StockConfig) fConfig.get(api); Assert.assertNotNull(mConfig); Assert.assertEquals(mConfig.getApiKey(), config.getApiKey()); Assert.assertEquals(mConfig.getProduct(), config.getProduct()); Assert.assertEquals(mConfig.getTargetEnvironment(), config.getTargetEnvironment()); } catch (Exception e) { Assert.fail("Didn't expect the exception here!", e); } }
@RunAsClient @Test(groups = TEST_GROUP_CDI_PROVIDER, description = "Verify that the injected sub claim is as expected") public void verifyInjectedOptionalSubject() throws Exception { Reporter.log("Begin verifyInjectedOptionalSubject\n"); String uri = baseURL.toExternalForm() + "/endp/verifyInjectedOptionalSubject"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam(Claims.sub.name(), "24400320") .queryParam(Claims.auth_time.name(), authTimeClaim); Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK); String replyString = response.readEntity(String.class); JsonReader jsonReader = Json.createReader(new StringReader(replyString)); JsonObject reply = jsonReader.readObject(); Reporter.log(reply.toString()); Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg")); }
/** * Current default namespace is "http://example.org/uniqueURI". * * writeAttribute("p", "http://example.org/uniqueURI", "attrName", "value") * * requires no fixup, but should generate a declaration for "p": * xmlns:p="http://example.org/uniqueURI" if necessary. (Note that this will * potentially produce two namespace bindings with the same URI, xmlns="xxx" * and xmlns:p="xxx", but that's perfectly legal.) */ @Test public void testSpecifiedDefaultSpecifiedPrefixSpecifiedNamespaceURIWriteAttribute() throws Exception { final String EXPECTED_OUTPUT = "<?xml version=\"1.0\" ?>" + "<root xmlns=\"http://example.org/uniqueURI\" attrName=\"value\">" + "requires no fixup" + "</root>"; final String EXPECTED_OUTPUT_2 = "<?xml version=\"1.0\" ?>" + "<root xmlns=\"http://example.org/uniqueURI\" xmlns:p=\"http://example.org/uniqueURI\" p:attrName=\"value\">" + "requires no fixup" + "</root>"; startDocumentSpecifiedDefaultNamespace(xmlStreamWriter); xmlStreamWriter.writeAttribute("p", "http://example.org/uniqueURI", "attrName", "value"); xmlStreamWriter.writeCharacters("requires no fixup"); String actualOutput = endDocumentEmptyDefaultNamespace(xmlStreamWriter); if (DEBUG) { System.out.println("testSpecifiedDefaultSpecifiedPrefixSpecifiedNamespaceURIWriteAttribute: expectedOutput: " + EXPECTED_OUTPUT); System.out.println("testSpecifiedDefaultSpecifiedPrefixSpecifiedNamespaceURIWriteAttribute: expectedOutput: " + EXPECTED_OUTPUT_2); System.out.println("testSpecifiedDefaultSpecifiedPrefixSpecifiedNamespaceURIWriteAttribute: actualOutput: " + actualOutput); } Assert.assertTrue(actualOutput.equals(EXPECTED_OUTPUT) || actualOutput.equals(EXPECTED_OUTPUT_2), "Expected: " + EXPECTED_OUTPUT + "\n" + "Actual: " + actualOutput); }
@RunAsClient @Test(groups = TEST_GROUP_CDI, description = "Verify that the injected token issuer claim using @Claim(standard) is as expected") public void verifyIssuerStandardClaim() throws Exception { Reporter.log("Begin verifyIssuerClaim"); String uri = baseURL.toExternalForm() + "/endp/verifyInjectedIssuerStandard"; WebTarget echoEndpointTarget = ClientBuilder.newClient() .target(uri) .queryParam(Claims.iss.name(), TCKConstants.TEST_ISSUER) .queryParam(Claims.auth_time.name(), authTimeClaim); Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get(); Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK); String replyString = response.readEntity(String.class); JsonReader jsonReader = Json.createReader(new StringReader(replyString)); JsonObject reply = jsonReader.readObject(); Reporter.log(reply.toString()); Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg")); }
@Test public void folderRecursiveOneFoundTest() { FindFiles findFiles = new FindFiles("resources", true).setIncludeFiles(false).setIncludeFolders(true); TUExecutionResult executionResult = findFiles.execution(transformedAppFolder, transformationContext); Assert.assertEquals(executionResult.getType(), TUExecutionResult.Type.VALUE); Assert.assertNotNull(executionResult.getValue()); List<File> files = (List<File>) executionResult.getValue(); Assert.assertEquals(files.size(), 1); Assert.assertTrue(files.contains(new File(transformedAppFolder, "/src/main/resources"))); Assert.assertEquals(findFiles.getNameRegex(), "resources"); Assert.assertNull(findFiles.getPathRegex()); Assert.assertTrue(findFiles.isRecursive()); Assert.assertFalse(findFiles.isIncludeFiles()); Assert.assertTrue(findFiles.isIncludeFolders()); Assert.assertEquals(findFiles.getDescription(), "Find files whose name and/or path match regular expression and are under the root folder and sub-folders"); Assert.assertNull(executionResult.getException()); }
@Test public void testSelfPartialCopy() { CachingGroupData original = sampleSumGroupData(20.0); CachingGroupData copy = original.partialCopy(); copy.groupFields.put("foo", "baz"); copy.metrics.remove(OPERATION); // Group fields are changed Assert.assertEquals(original.groupFields.size(), 1); Assert.assertEquals(original.groupFields.get("foo"), "baz"); Assert.assertEquals(copy.groupFields.size(), 1); Assert.assertEquals(copy.groupFields.get("foo"), "baz"); // Metrics are unchanged Assert.assertEquals(original.metrics.size(), 1); Assert.assertEquals(original.metrics.get(OPERATION), 20.0); Assert.assertEquals(copy.metrics.size(), 0); }
@Test public void testMissingFields() { FilterClause filterClause = new FilterClause(); Assert.assertNull(filterClause.getOperation()); filterClause.setOperation(EQUALS); Assert.assertTrue(filterClause.check(RecordBox.get().getRecord())); filterClause.setField("field"); Assert.assertTrue(filterClause.check(RecordBox.get().add("field", "foo").getRecord())); filterClause.setValues(singletonList("bar")); Assert.assertFalse(filterClause.check(RecordBox.get().add("field", "foo").getRecord())); }
@Test public void testReverseDateLong(){ Date now = new Date(); Long nowTime = now.getTime(); Assert.assertEquals(fromReverseDateLong(toReverseDateLong(now)), now); Assert.assertEquals(toReverseDateLong(fromReverseDateLong(nowTime)), nowTime); Assert.assertNull(fromReverseDateLong(toReverseDateLong(null))); Assert.assertNull(toReverseDateLong(fromReverseDateLong(null))); }
@Test(expectedExceptions = ClassCastException.class) public void testCastingOnGenerics() { Map<String, Object> map = new HashMap<>(); Map<Integer, Long> anotherMap = new HashMap<>(); anotherMap.put(1, 2L); map.put("foo", anotherMap); Map<String, String> incorrect = Utilities.getCasted(map, "foo", Map.class); // It is a map but the generics are incorrect Assert.assertNotNull(incorrect); String value = incorrect.get(1); }
@Test(groups = TEST_GROUP_JWT, description = "validate the aud claim") public void validateAudience() { Set<String> audience = jwt.getAudience(); HashSet<String> actual = new HashSet<>(); actual.add("s6BhdRkqt3"); Assert.assertEquals(actual, audience); Assert.assertEquals(actual, jwt.getClaim(Claims.aud.name())); }
@Test public void testRestApiExceptionWithStatusMessage() { RestApiException apiException = new RestApiException(HttpStatus.OK, "code", "message"); Assert.assertEquals(apiException.getAppErrorCode(), "code"); Assert.assertEquals(apiException.getHttpStatusCode(), HttpStatus.OK); Assert.assertEquals(apiException.getMessage(), "message"); Assert.assertEquals(apiException.getCause(), null); }
@Test public void fileNoneFoundTest() { FindFiles findFiles = new FindFiles("(.*\\.txt)", true).relative(""); TUExecutionResult executionResult = findFiles.execution(transformedAppFolder, transformationContext); Assert.assertEquals(executionResult.getType(), TUExecutionResult.Type.WARNING); Assert.assertNotNull(executionResult.getValue()); List<File> files = (List<File>) executionResult.getValue(); Assert.assertEquals(files.size(), 0); Assert.assertEquals(findFiles.getNameRegex(), "(.*\\.txt)"); Assert.assertNull(findFiles.getPathRegex()); Assert.assertTrue(findFiles.isRecursive()); Assert.assertEquals(findFiles.getDescription(), "Find files whose name and/or path match regular expression and are under the root folder and sub-folders"); Assert.assertNull(executionResult.getException()); Assert.assertEquals(executionResult.getDetails(), "No files have been found"); }
@Test public void hasValidRegularExpression() { GenericErrorsOutputHandler handler = null; String[] validLines = { "[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project butterfly-utilities: There are test failures.", "[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project butterfly-utilities: Compilation failure: Compilation failure:", "[ERROR] The project com.paypal.butterfly:butterfly-utilities:1.0.0-SNAPSHOT (/Users/mcrockett/workspaces/butterfly-mcrockett/butterfly-utilities/pom.xml) has 1 error" }; String[] invalidLines = { "[ERROR] ailed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project butterfly-utilities: There are test failures.", "[ERROR] The project com.paypal.butterfly:butterfly-utilities:1.0.0-SNAPSHOT (/Users/mcrockett/workspaces/butterfly-mcrockett/butterfly-utilities/pom.xml) has error", "[ERROR] The projec com.paypal.butterfly:butterfly-utilities:1.0.0-SNAPSHOT (/Users/mcrockett/workspaces/butterfly-mcrockett/butterfly-utilities/pom.xml) has 1 error" }; for(int i = 0; i < validLines.length; i += 1) { handler = new GenericErrorsOutputHandler(); handler.consumeLine(validLines[i]); handler.consumeLine("some error line"); Assert.assertNotNull(handler.getResult()); } for(int i = 0; i < invalidLines.length; i += 1) { handler = new GenericErrorsOutputHandler(); handler.consumeLine(invalidLines[i]); handler.consumeLine("some error line"); Assert.assertEquals(handler.getResult(), ""); } }
@Test public void getRelativePathTest(){ final Mockery mockery = new Mockery(); final BuildProgressLogger logger = mockery.mock(BuildProgressLogger.class); final AutotoolsTestsReporter testReporter = new AutotoolsTestsReporter(logger, "C:/Users/naduxa/someprojects/teamcity-autotools-plugin/autotools-agent/src/test"); Assert.assertEquals(testReporter.getRelativePath("C:/Users/naduxa/someprojects/teamcity-autotools-plugin/autotools-agent/src/test/resources/testng.xml"), "/resources/testng.xml"); }
@Test public void testRegularSend() { consumer.startRecording(); String text = "{\"deploymentId\":546589,\"releaseId\":546559,\"maxExecOrder\":6,\"nsPath\":\"/local-dev/prod1/dev/bom\",\"deploymentState\":\"paused\",\"processId\":\"87820!87820\",\"createdBy\":\"bannama\",\"updatedBy\":\"bannama\",\"comments\":\"\",\"created\":\"Jan 5, 2016 7:15:37 PM\",\"updated\":\"Jan 8, 2016 3:56:55 PM\"}"; Map<String, String> headers = new HashMap<String, String>(); headers.put("messageId", "1"); headers.put("source", "test"); MessageData data = new MessageData(text, headers); searchPublisher.publish(data); await().atMost(5, TimeUnit.SECONDS).until(() -> (consumer.getCounter() == 1)); Assert.assertEquals(consumer.getMessages().getFirst().getPayload(), text); Assert.assertEquals(consumer.getMessages().getFirst().getHeaders(), headers); }
/** * Checks that the Morpheus OLS model yields the same results as Apache Math * @param actual the Morpheus results * @param expected the Apache results */ private <R,C> void assertResultsMatch(DataFrameLeastSquares<R,C> actual, OLSMultipleLinearRegression expected) { Assert.assertEquals(actual.getResidualSumOfSquares(), expected.calculateResidualSumOfSquares(), 0.0000001, "Residual sum of squares matches"); Assert.assertEquals(actual.getTotalSumOfSquares(), expected.calculateTotalSumOfSquares(), actual.getTotalSumOfSquares() * 0.000001, "Total sum of squares matches"); Assert.assertEquals(actual.getRSquared(), expected.calculateRSquared(), 0.0000001, "R^2 values match"); Assert.assertEquals(actual.getStdError(), expected.estimateRegressionStandardError(), 0.0000001, "Std error matches"); final DataFrame<C,Field> params1 = actual.getBetas(); final double[] params2 = expected.estimateRegressionParameters(); Assert.assertEquals(params1.rows().count(), params2.length-1, "Same number of parameters"); for (int i=0; i<params1.rows().count(); ++i) { final double actualParam = params1.data().getDouble(i, Field.PARAMETER); final double expectedParam = params2[i+1]; Assert.assertEquals(actualParam, expectedParam, 0.000000001, "Parameters match at index " + i); } final double intercept = expected.estimateRegressionParameters()[0]; final double interceptStdError = expected.estimateRegressionParametersStandardErrors()[0]; Assert.assertEquals(actual.getInterceptValue(Field.PARAMETER), intercept, 0.0000001, "The intercepts match"); Assert.assertEquals(actual.getInterceptValue(Field.STD_ERROR), interceptStdError, 0.000000001, "The intercept std errors match"); final DataFrame<R,String> residuals1 = actual.getResiduals(); final double[] residuals2 = expected.estimateResiduals(); Assert.assertEquals(residuals1.rows().count(), residuals2.length, "Same number of residuals"); for (int i=0; i<residuals1.rows().count(); ++i) { Assert.assertEquals(residuals1.data().getDouble(i, 0), residuals2[i], 0.00000001, "Residuals match at index " + i); } final DataFrame<C,Field> stdErrs1 = actual.getBetas().cols().select(c -> c.key() == Field.STD_ERROR); final double[] stdErrs2 = expected.estimateRegressionParametersStandardErrors(); Assert.assertEquals(stdErrs1.rows().count(), stdErrs2.length-1, "Same number of parameter standard errors"); for (int i=0; i<stdErrs1.cols().count(); ++i) { Assert.assertEquals(stdErrs1.data().getDouble(0, i), stdErrs2[i+1], 0.00000001, "Standard errors match at index " + i); } }
@Test(dataProvider= "args3") public void testFilter2(boolean parallel) { final LocalDate start = LocalDate.of(2000, 1, 1); final LocalDate end = start.plusDays(2000); final Range<LocalDate> dates = Range.of(start, end); final Range<String> labels = Range.of(0, 100).map(i -> "Column" + i); final DataFrame<String,LocalDate> frame = DataFrame.ofDoubles(labels, dates).applyDoubles(v -> Math.random() * 100); final DataFrameColumns<String,LocalDate> cols = parallel ? frame.cols().parallel() : frame.cols().sequential(); final DataFrameColumns<String,LocalDate> filter = cols.filter(col -> col.key().getDayOfWeek() == DayOfWeek.MONDAY); final long expectedCount = dates.stream().filter(d -> d.getDayOfWeek() == DayOfWeek.MONDAY).count(); Assert.assertEquals(filter.count(), expectedCount, "Row count matches expected number of mondays"); filter.forEach(row -> Assert.assertEquals(DayOfWeek.MONDAY, row.key().getDayOfWeek())); }
@SuppressWarnings("unchecked") @Test(dataProvider = "ranges") public <T> void testCreateByIterable2(Range<T> range) { final Index<T> index = Index.of(range); final Array<T> array = range.toArray(); Assert.assertEquals(array.length(), index.size(), "Size matches range length"); for (int i=0; i<index.size(); ++i) { final T key = index.getKey(i); Assert.assertEquals(key, array.getValue(i), "Key matches array value at " + i); Assert.assertEquals(index.getIndexForKey(key), i, "Index matches for ordinal " + i); Assert.assertEquals(index.getOrdinalForKey(key), i, "Ordinals match"); Assert.assertEquals(index.getIndexForOrdinal(i), i, "Ordinal and index match"); } }
@Test public void testEncodingInteger() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<StringAttributeValue> stringAttributeValues = new ArrayList<StringAttributeValue>(); stringAttributeValues.add(new StringAttributeValue("value1")); stringAttributeValues.add(new StringAttributeValue("2")); attribute.setValues(stringAttributeValues); encoder.setAsInt(true); JSONObject object = encoder.encode(attribute); Assert.assertEquals(2,object.get("attributeName")); }
@Test(groups = { "Setters" }) void setThumbnailUrl_should_set_media_ThumbnailUrl_ofType_String_StockLicenseHistoryFile() throws NoSuchFieldException, IllegalAccessException { stocklicensehistoryfile.setThumbnailUrl("SomeText"); Field f = stocklicensehistoryfile.getClass().getDeclaredField("mThumbnailUrl"); f.setAccessible(true); Assert.assertTrue(f.get(stocklicensehistoryfile).equals("SomeText")); }
@Test public void testAddElementToGlobalNsNoDeclarations() throws Exception { // Create empty SOAP message SOAPMessage msg = createSoapMessage(); SOAPBody body = msg.getSOAPPart().getEnvelope().getBody(); // Add elements SOAPElement parentExplicitNS = body.addChildElement("content", "", TEST_NS); SOAPElement childGlobalNS = parentExplicitNS.addChildElement("global-child", "", ""); SOAPElement childDefaultNS = parentExplicitNS.addChildElement("default-child"); // Check namespace URIs Assert.assertNull(childGlobalNS.getNamespaceURI()); Assert.assertEquals(childDefaultNS.getNamespaceURI(), TEST_NS); }
@Test public void twoResources() { final DateTime time = service.getLastReloadAttemptInstant(); service.setServiceConfigurations(twoResolvers); service.reload(); Assert.assertNotEquals(time, service.getLastReloadAttemptInstant()); final ServiceableComponent<RefreshableClientInformationResolver> component = service.getServiceableComponent(); final ClientInformationResolver resolver = component.getComponent(); component.unpinComponent(); Assert.assertEquals(getChainSize(resolver), 2); }