@Test public void shouldSynchronizeConcurrentAddsOfSameElement() { // given: final String element = "Hello World"; replica2.disconnect(replica3); // when: orSet1.add(element); orSet3.add(element); // then: assertThat(orSet1, contains(element)); assertThat(orSet2, equalTo(orSet1)); assertThat(orSet3, equalTo(orSet1)); // when: replica2.connect(replica3); // then: assertThat(orSet1, contains(element)); assertThat(orSet2, equalTo(orSet1)); assertThat(orSet3, equalTo(orSet1)); }
@Test(dataProvider="calendars") public void test_badMinusTemporalUnitChrono(Chronology chrono) { LocalDate refDate = LocalDate.of(2013, 1, 1); ChronoLocalDateTime<?> cdt = chrono.date(refDate).atTime(LocalTime.NOON); for (Chronology[] clist : data_of_calendars()) { Chronology chrono2 = clist[0]; ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON); TemporalUnit adjuster = new FixedTemporalUnit(cdt2); if (chrono != chrono2) { try { cdt.minus(1, adjuster); Assert.fail("TemporalUnit.doPlus minus should have thrown a ClassCastException" + cdt.getClass() + ", can not be cast to " + cdt2.getClass()); } catch (ClassCastException cce) { // Expected exception; not an error } } else { // Same chronology, ChronoLocalDateTime<?> result = cdt.minus(1, adjuster); assertEquals(result, cdt2, "WithAdjuster failed to replace date"); } } }
/** * namespace processing is enabled. namespace-prefix is also is enabled. * So it is a True-True combination. * The test is to test SAXParser with these conditions. * * @throws Exception If any errors occur. */ @Test public void testWithTrueTrue() throws Exception { String outputFile = USER_DIR + "SPNSTableTT.out"; String goldFile = GOLDEN_DIR + "NSTableTTGF.out"; String xmlFile = XML_DIR + "namespace1.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true); try (MyNSContentHandler handler = new MyNSContentHandler(outputFile)) { spf.newSAXParser().parse(new File(xmlFile), handler); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Simple test for record-writer where number of rows are written to Geode, based on * the specified block-size. * The sample file contains 30 lines/rows. Here with block-size 10 total four blocks * are stored each with max 10 records/rows. * * @throws Exception */ @Test public void testWrite_SingleWriter() throws Exception { // System.out.println("MonarchRecordWriterTest.testWrite_SingleWriter"); final List<String> lines = TestHelper.getResourceAsString(resourceFile); final Map<String, Integer> expectedMap = new HashMap<String, Integer>(4) {{ put("0", 10); put("1", 10); put("2", 10); put("3", 1); }}; final int blockSize = 10; assertOnRecordWriter(lines, expectedMap, "", blockSize); Configuration conf = new Configuration(); conf.set("monarch.locator.port", testBase.getLocatorPort()); }
@Test public void returnsResultsFromEveryHandler() { BogusMavenInvocationOutputHandler handler1 = Mockito.mock(BogusMavenInvocationOutputHandler.class); Mockito.doReturn("data0").when(mockHandler).getResult(); Mockito.doReturn("data1").when(handler1).getResult(); multiHandler.register(mockHandler); multiHandler.register(handler1); multiHandler.consumeLine("line1"); multiHandler.consumeLine("line2"); Map<Class<? extends MavenInvocationOutputHandler>, Object> results = multiHandler.getResult(); Assert.assertEquals(2, results.size()); Assert.assertEquals(results.get(mockHandler.getClass()), "data0"); Assert.assertEquals(results.get(handler1.getClass()), "data1"); }
@Test public void test_isBeforeIsAfterIsEqual2nanos() { OffsetTime a = OffsetTime.of(11, 30, 59, 4, ZoneOffset.ofTotalSeconds(OFFSET_PONE.getTotalSeconds() + 1)); OffsetTime b = OffsetTime.of(11, 30, 59, 3, OFFSET_PONE); // a is before b due to offset assertEquals(a.isBefore(b), true); assertEquals(a.isEqual(b), false); assertEquals(a.isAfter(b), false); assertEquals(b.isBefore(a), false); assertEquals(b.isEqual(a), false); assertEquals(b.isAfter(a), true); assertEquals(a.isBefore(a), false); assertEquals(b.isBefore(b), false); assertEquals(a.isEqual(a), true); assertEquals(b.isEqual(b), true); assertEquals(a.isAfter(a), false); assertEquals(b.isAfter(b), false); }
@Test public void testIndexedCorola() throws IOException, SAXException, ParserConfigurationException, GGSException { IndexedLuceneCorpus t; try { t = new IndexedLuceneCorpus(new File("TestData/inputCorpora/corola.index")); } catch (IOException e) { throw new SkipException("indexed corola not present"); } Grammar g = new Grammar(); //g.load(new FileInputStream("TestData/inputGrammars/roNPchunker_grammar.ggf")); //g.load(new FileInputStream("TestData/inputGrammars/npexample.ggf")); g.load(new FileInputStream("TestData/inputGrammars/verysimplegrammar.ggf")); SparseBitSet.compressionPolicy = SparseBitSet.SparseBitSetCompressionPolicy.none; CompiledGrammar compiledGrammar = new CompiledGrammar(g); List<Match> matches = compiledGrammar.GetMatches(t, true); assert (matches.size() == matches.size()); }
@Test public void testTransformer() throws TransformerException { String xml = "<?xml version='1.0'?><root/>"; ReaderStub.used = false; TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); InputSource in = new InputSource(new StringReader(xml)); SAXSource source = new SAXSource(in); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); assertTrue(ReaderStub.used); }
@Test public void testSubtraction() { b1 = rampdouble(-1,1,n1); assertEqual(b1,sub(a1,1)); b2 = rampdouble(-1,1,10,n1,n2); assertEqual(b2,sub(a2,1)); b3 = rampdouble(-1,1,10,100,n1,n2,n3); assertEqual(b3,sub(a3,1)); b1 = rampdouble(1,-1,n1); assertEqual(b1,sub(1,a1)); b2 = rampdouble(1,-1,-10,n1,n2); assertEqual(b2,sub(1,a2)); b3 = rampdouble(1,-1,-10,-100,n1,n2,n3);assertEqual(b3,sub(1,a3)); zero(b1); assertEqual(b1,sub(a1,a1)); zero(b2); assertEqual(b2,sub(a2,a2)); zero(b3); assertEqual(b3,sub(a3,a3)); sub(a1,a1,a1); assertEqual(b1,a1); sub(a2,a2,a2); assertEqual(b2,a2); sub(a3,a3,a3); assertEqual(b3,a3); }
@Deprecated @Test(enabled = false) public void testResourceMonthDetailDAOCount() throws Exception { String environemntName = environemntNames[0]; long statusOnlineCount = aggregatedStatusDAO.getStatusCount(environemntName, resource.getId(), Status.Online, startDate, endDate); Assert.assertTrue(statusOnlineCount > 0); Assert.assertEquals(statusOnlineCount, 100); long statusUnavailableCount = aggregatedStatusDAO.getStatusCount(environemntName, resource.getId(), Status.Unavailable, startDate, endDate); Assert.assertTrue(statusUnavailableCount > 0); Assert.assertEquals(statusUnavailableCount, 100); long statusUnknownCount = aggregatedStatusDAO.getStatusCount(environemntName, resource.getId(), Status.Unknown, startDate, endDate); Assert.assertTrue(statusUnknownCount > 0); Assert.assertEquals(statusUnknownCount, 100); }
@Test public void testGetSecretsGroupIdentifiers() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); Policy policyUS1 = new Policy().withPolicyName("strongbox_us-west-1_test-group1_admin"); Policy policyUS2 = new Policy().withPolicyName("strongbox_us-west-1_test-group2_admin"); Policy policyEU1 = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_admin"); Policy policyEU1readonly = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_readonly"); ListPoliciesResult result = new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly)); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPolicyManager.getSecretsGroupIdentifiers(); assertEquals(identifiers.size(), 3); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group1"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group1"))); verify(mockClient, times(1)).listPolicies(request); }
@Test public void test_next() { for (Month month : Month.values()) { for (int i = 1; i <= month.length(false); i++) { LocalDate date = date(2007, month, i); for (DayOfWeek dow : DayOfWeek.values()) { LocalDate test = (LocalDate) TemporalAdjusters.next(dow).adjustInto(date); assertSame(test.getDayOfWeek(), dow, date + " " + test); if (test.getYear() == 2007) { int dayDiff = test.getDayOfYear() - date.getDayOfYear(); assertTrue(dayDiff > 0 && dayDiff < 8); } else { assertSame(month, Month.DECEMBER); assertTrue(date.getDayOfMonth() > 24); assertEquals(test.getYear(), 2008); assertSame(test.getMonth(), Month.JANUARY); assertTrue(test.getDayOfMonth() < 8); } } } } }
@Test public void testNotEqualsHashCode() throws Exception { final Route route1 = ImmutableRoute.builder() .targetPrefix(GLOBAL_TARGET_PREFIX) .nextHopLedgerAccount(DEFAULT_CONNECTOR_ACCOUNT) .build(); final Route route2 = ImmutableRoute.builder() .targetPrefix(GLOBAL_TARGET_PREFIX) .nextHopLedgerAccount(DEFAULT_CONNECTOR_ACCOUNT) .sourcePrefixRestrictionRegex(ACCEPT_NO_SOURCES_PATTERN) .build(); assertThat(route1, is(not(route2))); assertThat(route2, is(not(route1))); assertThat(route1.hashCode(), is(not(route2.hashCode()))); }
@Test(expectedExceptions = AssertionError.class) public void performTestResultsVerificationFailTest() { Map<String, String> testResults = new HashMap<>(); testResults. put("SomeField:", "TestMe"); testResults. put("Status:", "QWE"); performTestResultsVerification( generateVerificationEntities( UI_COMMON_RULES), testResults, UI_COMMON.name()); }
@Test public void testUriVariablePositive() { HashSet<Attribute> attributes = new HashSet<Attribute>( Arrays.asList(new Attribute("acs", "site", "boston"), new Attribute("acs", "department", "sales"))); ResourceHandler handler = new ResourceHandler(attributes, "http://assets.predix.io/site/boston/department/sales", "site/{site_id}/department/{department_id}"); Assert.assertEquals("boston", handler.uriVariable("site_id")); Assert.assertEquals("sales", handler.uriVariable("department_id")); Assert.assertNotEquals("hr", handler.uriVariable("department_id")); }
@Test(expectedExceptions = NullPointerException.class) public void testGetNullProperty() throws SAXNotRecognizedException, SAXNotSupportedException { ValidatorHandler validatorHandler = getValidatorHandler(); assertNotNull(validatorHandler); validatorHandler.getProperty(null); }
@Test public void test_plusMonths_zero() { LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 23, 30, 59, 0); ZonedDateTime base = ZonedDateTime.of(ldt, ZONE_0100); ZonedDateTime test = base.plusMonths(0); assertEquals(test, base); }
@Test public void equals() { // Wrong type. assertFalse(rawSecretEntry.equals(secretIdentifier)); // Doesn't equal RawSecretEntry rawSecretEntry2 = new RawSecretEntry( secretIdentifier, version, state, Optional.empty(), Optional.empty(), secret); assertFalse(rawSecretEntry.equals(rawSecretEntry2)); // Equals RawSecretEntry rawSecretEntry3 = new RawSecretEntry( secretIdentifier, version, state, Optional.empty(), Optional.empty(), secret); assertTrue(rawSecretEntry2.equals(rawSecretEntry3)); }
@Test public void accessStaticFieldByteBoxing() throws ScriptException { e.eval("var ps_byte = SharedObject.publicStaticByte;"); assertEqualsDouble(SharedObject.publicStaticByte, "ps_byte"); e.eval("SharedObject.publicStaticByte = 16;"); assertEquals(16, SharedObject.publicStaticByte); }
@Test(groups = { "Getters" }) void getDuration_should_return_duration_of_video_in_ms_of_Type_Integer_StockFile() throws NoSuchFieldException, IllegalAccessException { Field f = stockFile.getClass().getDeclaredField("mDuration"); f.setAccessible(true); f.set(stockFile, 100); Assert.assertEquals(100, stockFile.getDuration().intValue()); }
@Test public void testWithDefaultArgumentValues() { ReadXml readXml = new ReadXml(); String xml = "<root attr1=\"value1\"><child1 attr1=\"value1\">child1 text</child1></root>"; readXml.writeArgument("xml", xml); readXml.run(); assertEquals(readXml.readOutputValue("value"), "child1 text"); assertEquals(readXml.readOutputValue("object"), null); }
/** * Validate that the ordering of the returned SQLWarning is correct using * for-each loop */ @Test public void test13() { SQLWarning ex = new SQLWarning("Warning 1", t1); SQLWarning ex1 = new SQLWarning("Warning 2"); SQLWarning ex2 = new SQLWarning("Warning 3", t2); ex.setNextWarning(ex1); ex.setNextWarning(ex2); int num = 0; for (Throwable e : ex) { assertTrue(warnings[num++].equals(e.getMessage())); } }
@Test public void testGetWithCacheMissForPolicyEvaluation() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey.Builder().zoneId(ZONE_NAME) .request(request).build(); assertNull(this.cache.get(key)); }
@Test public void test_get_TemporalField() { Instant test = TEST_12345_123456789; assertEquals(test.get(ChronoField.NANO_OF_SECOND), 123456789); assertEquals(test.get(ChronoField.MICRO_OF_SECOND), 123456); assertEquals(test.get(ChronoField.MILLI_OF_SECOND), 123); }
@Test public void test_withOffsetSameInstant() { OffsetDateTime base = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30, 59), OFFSET_PONE); OffsetDateTime test = base.withOffsetSameInstant(OFFSET_PTWO); OffsetDateTime expected = OffsetDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(12, 30, 59), OFFSET_PTWO); assertEquals(test, expected); }
@Test public void testReadDeprecatedOutputValue() { TestAction instance = new TestActionImpl(); instance.writeOutput("output1", "value1"); instance.markOutputAsDeprecated("output1"); Object result = instance.readOutputValue("output1"); assertEquals(result, "value1"); assertEquals(instance.isOutputDeprecated("output1"), true); }
@Test public void userEngineScopeBindingsNoLeakTest() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final ScriptContext newContext = new SimpleScriptContext(); newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE); e.eval("function foo() {}", newContext); // in the default context's ENGINE_SCOPE, 'foo' shouldn't exist assertTrue(e.eval("typeof foo").equals("undefined")); }
@Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class) public void testOps(String name, TestData.OfInt data) { exerciseTerminalOps(data, s -> s.sum()); withData(data). terminal(s -> (long) s.sum()). expectedResult(data.stream().asLongStream().reduce(0, LambdaTestHelpers.lrPlus)). exercise(); }
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("thrift.client.transport", "HEADER") .put("thrift.client.protocol", "COMPACT") .put("thrift.client.connect-timeout", "99ms") .put("thrift.client.request-timeout", "33m") .put("thrift.client.socks-proxy", "localhost:11") .put("thrift.client.max-frame-size", "55MB") .put("thrift.client.max-string-size", "66MB") .put("thrift.client.ssl.enabled", "true") .put("thrift.client.ssl.trust-certificate", "trust") .put("thrift.client.ssl.key", "key") .put("thrift.client.ssl.key-password", "key_password") .build(); ApacheThriftClientConfig expected = new ApacheThriftClientConfig() .setTransport(HEADER) .setProtocol(COMPACT) .setConnectTimeout(new Duration(99, MILLISECONDS)) .setRequestTimeout(new Duration(33, MINUTES)) .setSocksProxy(HostAndPort.fromParts("localhost", 11)) .setMaxFrameSize(new DataSize(55, MEGABYTE)) .setMaxStringSize(new DataSize(66, MEGABYTE)) .setSslEnabled(true) .setTrustCertificate(new File("trust")) .setKey(new File("key")) .setKeyPassword("key_password"); assertFullMapping(properties, expected); }
@Test public void json_multiple_secret_entries() throws IOException { outputStream.reset(); Renderer renderer = new Renderer(OutputFormat.JSON, printStream, null, null); renderer.render(Arrays.asList(secretEntryView, secretEntryViewBinary)); String expected = String.format("[ %s, %s ]\n", loadExpectedValue("expected_secret_entry.json"), loadExpectedValue("expected_secret_entry_binary.json")); assertThat(outputStream.toString(), equalTo(expected)); }
@Test(expectedExceptions = IllegalArgumentException.class) public void postNullMessageTest() { svc.setBotName("postMessageExerciseTest"); svc.setTimeout(1); XMPPSubscriber sub = new XMPPSubscriber(); sub.setChatServer("notarealaddressOK"); sub.setChatPort(9); svc.postMessage(null, sub); }
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class) public void testGroupingByWithMapping(String name, TestData.OfRef<Integer> data) throws ReflectiveOperationException { Function<Integer, Integer> classifier = i -> i % 3; Function<Integer, Integer> mapper = i -> i * 2; exerciseMapCollection(data, groupingBy(classifier, mapping(mapper, toList())), new GroupingByAssertion<>(classifier, HashMap.class, new MappingAssertion<>(mapper, new ToListAssertion<>()))); }
@Test public void testGetFundingNegativeThreshold() throws Exception { assertEquals(target.getFundingNegativeThreshold(site, inst), new BigDecimal("0.0")); // Specific doReturn(new BigDecimal("2.3456")).when(conf).getBigDecimal(FUNDING_NEGATIVE_THRESHOLD.getKey()); assertEquals(target.getFundingNegativeThreshold(site, inst), new BigDecimal("2.3456")); // Ceiling doReturn(valueOf(Integer.MAX_VALUE)).when(conf).getBigDecimal(FUNDING_NEGATIVE_THRESHOLD.getKey()); assertEquals(target.getFundingNegativeThreshold(site, inst), valueOf(Integer.MAX_VALUE)); // Floor doReturn(valueOf(Integer.MIN_VALUE)).when(conf).getBigDecimal(FUNDING_NEGATIVE_THRESHOLD.getKey()); assertEquals(target.getFundingNegativeThreshold(site, inst), valueOf(Integer.MIN_VALUE)); // Error doThrow(new RuntimeException("test")).when(conf).getBigDecimal(FUNDING_NEGATIVE_THRESHOLD.getKey()); assertEquals(target.getFundingNegativeThreshold(site, inst), ONE); reset(conf); // Override target.setFundingNegativeThreshold(site, inst, TEN); assertEquals(target.getFundingNegativeThreshold(site, inst), TEN); // Clear target.setFundingNegativeThreshold(site, inst, null); assertEquals(target.getFundingNegativeThreshold(site, inst), new BigDecimal("0.0")); }
/** * Test the functionality of setFeature and getFeature methods * for namespaces property. * @throws Exception If any errors occur. */ @Test public void testFeature02() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature(NAMESPACES, true); assertTrue(spf.getFeature(NAMESPACES)); spf.setFeature(NAMESPACES, false); assertFalse(spf.getFeature(NAMESPACES)); }
@Test(dataProvider="minusSeconds_fromZero") public void test_minusSeconds_fromZero(int seconds, int hour, int min, int sec) { LocalTime base = LocalTime.MIDNIGHT; LocalTime t = base.minusSeconds(seconds); assertEquals(t.getHour(), hour); assertEquals(t.getMinute(), min); assertEquals(t.getSecond(), sec); }
@Test public void testInstantTypeConversionWithString(){ InstantTypeConversion instantTypeConversion = new InstantTypeConversion(); String instantStr = new String("2014-12-03T10:15:30.00Z"); InstantFormat obj = new InstantFormat(instantStr); Instant convertedInstant = instantTypeConversion.convert(obj); assertEquals(convertedInstant.getNano(), Instant.parse(instantStr).getNano()); }
@Test public void testFieldWithMatchingIdlAnnotationMaps() throws Exception { // Single field with matching IDL annotation maps on setter vs getter: should be okay ThriftStructMetadata metadata = testStructMetadataBuild(BeanWithMatchingIdlAnnotationsMapsForField.class, 0, 1); Map<String, String> idlAnnotations = metadata.getField(2).getIdlAnnotations(); assertEquals(idlAnnotations.size(), 2); assertEquals(idlAnnotations.get("testkey1"), "testvalue1"); assertEquals(idlAnnotations.get("testkey2"), "testvalue2"); }
@Test public void testOrderByReturnsResultsInStableOrder() throws Exception { Map<String, Object> vars = buildVariableMap(ORDERED_TYPE_NAME); vars.put("orderBy", OrderBy.UPDATE_DATE.getFieldName()); vars.put("orderByDirection", OrderByDirection.DESC); List<Long> updateDates1 = fetchUpdateDates(vars); List<Long> updateDates2 = fetchUpdateDates(vars); assertEquals(updateDates1, updateDates2); }
@Test(dataProvider="sample_isoLocalTime") public void test_parse_isoLocalTime( Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId, String input, Class<?> invalid) { if (input != null) { Expected expected = createTime(hour, min, sec, nano); // offset/zone not expected to be parsed assertParseMatch(DateTimeFormatter.ISO_LOCAL_TIME.parseUnresolved(input, new ParsePosition(0)), expected); } }
@Test public void stringArrayToStringTest(){ final String text = "DejaGnu version 1.6\n" + "Expect version 5.45\n" + "Tcl version 8.6"; Assert.assertEquals(AutotoolsToolProvider.stringArrayToString(text.split("\n")), text); }