下面列出了org.testng.Assert#assertTrue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testCompositionPlaylist() throws Exception
{
IMFErrorLogger imfErrorLogger = new IMFErrorLoggerImpl();
File inputFile = TestHelper.findResourceByPath("test_mapped_file_set/CPL_682feecb-7516-4d93-b533-f40d4ce60539.xml");
ApplicationComposition applicationComposition = ApplicationCompositionFactory.getApplicationComposition(inputFile, imfErrorLogger);
Assert.assertTrue(ApplicationComposition.isCompositionPlaylist(new FileByteRangeProvider(inputFile)));
Assert.assertTrue(applicationComposition.toString().length() > 0);
Assert.assertEquals(applicationComposition.getEditRate().getNumerator().longValue(), 24);
Assert.assertEquals(applicationComposition.getEditRate().getDenominator().longValue(), 1);
Assert.assertEquals(applicationComposition.getUUID(), UUID.fromString("682feecb-7516-4d93-b533-f40d4ce60539"));
UUID uuid = UUID.fromString("586286d2-c45f-4b2f-ad76-58eecd0202b4");
Assert.assertEquals(applicationComposition.getVirtualTracks().size(), 2);
Composition.VirtualTrack virtualTrack = applicationComposition.getVideoVirtualTrack();
Assert.assertEquals(virtualTrack.getSequenceTypeEnum(), Composition.SequenceTypeEnum.MainImageSequence);
Assert.assertTrue(applicationComposition.getAnnotation().length() > 0);
Assert.assertTrue(applicationComposition.getIssuer().length() > 0);
Assert.assertTrue(applicationComposition.getCreator().length() > 0);
Assert.assertTrue(applicationComposition.getContentOriginator().length() > 0);
Assert.assertTrue(applicationComposition.getContentTitle().length() > 0);
}
private void verifyUserDefinedPreferenceLists(String db,
Map<String, List<String>> userDefinedPreferenceLists, List<String> userDefinedPartitions)
throws InterruptedException {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
for (String p : userDefinedPreferenceLists.keySet()) {
List<String> userDefined = userDefinedPreferenceLists.get(p);
List<String> preferenceListInIs = is.getPreferenceList(p);
if (userDefinedPartitions.contains(p)) {
Assert.assertTrue(userDefined.equals(preferenceListInIs));
} else {
if (userDefined.equals(preferenceListInIs)) {
Assert.fail("Something is not good!");
}
Assert.assertFalse(userDefined.equals(preferenceListInIs), String
.format("Partition %s, List in Is: %s, List as defined in config: %s", p, preferenceListInIs,
userDefined));
}
}
}
@Test
public void withExtensions() throws IOException {
final String resource = "/io/jenetics/jpx/extensions-track.gpx";
final GPX gpx;
try (InputStream in = getClass().getResourceAsStream(resource)) {
gpx = GPX.read(in);
}
Assert.assertEquals(gpx.getTracks().size(), 1);
Assert.assertEquals(
gpx.getTracks().get(0),
Track.builder()
.name("name_97")
.cmt("comment_69")
.build()
);
Assert.assertTrue(XML.equals(
gpx.getTracks().get(0).getExtensions().orElseThrow(),
XML.parse("<extensions xmlns=\"http://www.topografix.com/GPX/1/1\"><foo>asdf</foo><foo>asdf</foo></extensions>")
));
}
@Test
public void testClear() throws Exception {
JsonEventConventions jec = new JsonEventConventions();
IdProviderImpl idProvider = new IdProviderImpl(new OrderIdProviderImpl(new ConstantWriterIdProvider(100)));
EventBuilder eventBuilder = EventBuilder.create(idProvider, EventBuilderTest.class.getSimpleName(), tenantId, actorId);
eventBuilder.set("key", "value");
Event has = eventBuilder.build();
ObjectNode hasNode = jec.getInstanceNode(has.toJson(), EventBuilderTest.class.getSimpleName());
Assert.assertTrue(hasNode.has("key"));
eventBuilder.clear("key");
Event hasNot = eventBuilder.build();
ObjectNode hasNotNode = jec.getInstanceNode(hasNot.toJson(), EventBuilderTest.class.getSimpleName());
Assert.assertFalse(hasNotNode.has("key"));
}
private void assertWithin(LocalDataCenterEndPointProvider provider, Duration timeLimit, Function<Collection<EndPoint>, Void> function) {
AtomicBoolean called = new AtomicBoolean(false);
Stopwatch stopwatch = Stopwatch.createStarted();
do {
provider.withEndPoints(endPoints -> {
try {
function.apply(endPoints);
called.set(true);
} catch (AssertionError e) {
// Yield and try again until time is expired
Thread.yield();
}
return null;
});
} while (!called.get() && stopwatch.elapsed(TimeUnit.MILLISECONDS) < timeLimit.toMillis());
Assert.assertTrue(called.get());
}
private void listProduct() throws Exception {
HttpClientUtil httpClient = new HttpClientUtil();
OMElement result = httpClient.get(serviceEndPoint + "_getproducts");
Assert.assertNotNull(result, "Response null");
for (int i = 1; i < 6; i++) {
Assert.assertTrue(result.toString().contains("<productCode>" + i + "</productCode>"), "Expected result not found");
}
}
@Test
public void testOnPartitionReadComplete() throws InterruptedException {
Assert.assertEquals(this.extractorStatsTracker.getStatsMap().get(kafkaPartitions.get(1)).getReadRecordTime(), 0);
long readStartTime = System.nanoTime();
Thread.sleep(1);
this.extractorStatsTracker.onPartitionReadComplete(1, readStartTime);
Assert.assertTrue(this.extractorStatsTracker.getStatsMap().get(kafkaPartitions.get(1)).getReadRecordTime() > 0);
}
@Test
public void testLongListInjection() {
Assert.assertEquals(myLongList.size(), 2);
Assert.assertTrue( myLongList.contains(1234567890L));
Assert.assertTrue( myLongList.contains(1999999999L));
}
@Test
public void immediates() throws SVNException {
checkout("a/b", SVNDepth.IMMEDIATES);
Assert.assertTrue(Files.exists(wc.resolve("c")));
Assert.assertFalse(Files.exists(wc.resolve("c/d")));
Assert.assertTrue(Files.exists(wc.resolve("e")));
update("", null);
Assert.assertTrue(Files.exists(wc.resolve("c")));
Assert.assertFalse(Files.exists(wc.resolve("c/d")));
Assert.assertTrue(Files.exists(wc.resolve("e")));
update("", SVNDepth.INFINITY);
Assert.assertTrue(Files.exists(wc.resolve("c/d")));
}
@Test(groups = { "wso2.dss" }, dependsOnMethods = { "getRequestWithParam" })
public void putRequest() throws Exception {
editProduct();
OMElement response;
for (int i = productId; i < productId + 10; i++) {
response = getProductByCode(i + "");
Assert.assertTrue(response.toString().contains("<productName>product" + i + " edited</productName>"),
"Expected result not found");
Assert.assertTrue(response.toString().contains("<buyPrice>15.0</buyPrice>"), "Expected result not found");
}
log.info("PUT Request verified");
}
@Test
public void getProductIds ()
{
String cid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1";
String uid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2";
User user = udao.read (uid);
List<Long> pids = dao.getProductIds (cid, user);
Assert.assertNotNull (pids);
Assert.assertEquals (pids.size (), 5);
Assert.assertTrue (pids.contains (0L));
Assert.assertTrue (pids.contains (2L));
Assert.assertTrue (pids.contains (3L));
Assert.assertTrue (pids.contains (5L));
}
@Test
public void testDeleteRecursively() throws IOException {
final Path dir = Files.createTempDirectory("test-dir").normalize();
final Path file = dir.resolve("new-file");
Files.createFile(file);
Assert.assertTrue(Files.exists(file));
IOUtils.deleteRecursively(dir);
Assert.assertFalse(Files.exists(dir));
Assert.assertFalse(Files.exists(file));
}
@BeforeClass
public void setUp() throws IOException {
this.eventBus.register(this);
// Prepare the test job configuration files
Assert.assertTrue(this.jobConfigFileDir.mkdirs(), "Failed to create " + this.jobConfigFileDir);
Closer closer = Closer.create();
try {
for (int i = 0; i < NUM_JOB_CONFIG_FILES; i++) {
File jobConfigFile = new File(this.jobConfigFileDir, "test" + i + ".job");
Assert.assertTrue(jobConfigFile.createNewFile());
Properties properties = new Properties();
properties.setProperty("foo", "bar" + i);
properties.store(closer.register(Files.newWriter(jobConfigFile, ConfigurationKeys.DEFAULT_CHARSET_ENCODING)),
"");
}
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
Config config = ConfigFactory.empty().withValue(GobblinClusterConfigurationKeys.JOB_CONF_PATH_KEY,
ConfigValueFactory.fromAnyRef(JOB_CONFIG_DIR_NAME));
this.jobConfigurationManager = new JobConfigurationManager(this.eventBus, config);
this.jobConfigurationManager.startAsync().awaitRunning();
}
@Test(groups = "wso2.esb",
description = "ESBRegistry cachableDuration 0 property test")
public void testCachableDuration() throws Exception {
carbonLogReader.start();
clearLogsAndSendRequest();
Assert.assertTrue(Utils.checkForLog(carbonLogReader, OLD_VALUE, 10),
"Expected value : " + OLD_VALUE + " not found in logs.");
updateResourcesInConfigRegistry();
Assert.assertEquals(NEW_VALUE, registryManager.getProperty(PATH, RESOURCE_PATH, NAME));
clearLogsAndSendRequest();
Assert.assertTrue(Utils.checkForLog(carbonLogReader, NEW_VALUE, 10),
"Expected value : " + NEW_VALUE + " not found in logs.");
}
/**
* This action only applies to DB_ID_RANGE Sharding method.
* This test verifies expected result when using another deployment
* @throws Exception
*/
@Test(priority = 20, groups = {TestGroup.CONFIG_SHARDING})
public void testRangeCheck() throws Exception
{
String coreName = "alfresco";
RestResponse response = restClient.withParams("coreName=" + coreName).withSolrAdminAPI().getAction("rangeCheck");
checkResponseStatusOk(response);
Integer expand = response.getResponse().body().jsonPath().get("expand");
// RangeCheck action only applies to DB_ID_RANGE Sharding method, so expect error in other sharding methods and success for DB_ID_RANGE
if (ShardingMethod.DB_ID_RANGE.toString().equalsIgnoreCase(getShardMethod()))
{
// This assertion replicates: testRangeCheckSharding, priority = 21, hence deleting that test as duplicate
// Value -1 is expected when the next shard already has nodes indexed.
Assert.assertTrue((expand == Integer.valueOf(-1) || expand == Integer.valueOf(0)), "RangeCheck should not have been allowed when not using Shard DB_ID_RANGE method,");
Integer minDbid = response.getResponse().body().jsonPath().get("minDbid");
Assert.assertTrue(minDbid > 0, "RangeCheck is not successful when not using Shard DB_ID_RANGE method,");
}
else
{
Assert.assertEquals(expand, Integer.valueOf(-1), "RangeCheck should not have been allowed when not using Shard DB_ID_RANGE method,");
String exception = response.getResponse().body().jsonPath().get("exception");
Assert.assertEquals(exception, "ERROR: Wrong document router type:DBIDRouter", "Expansion should not have been allowed when not using Shard DB_ID_RANGE method,");
}
}
@Test
public void testBadMaxMapEntries() {
FrequentItemsSketchingStrategy topK = makeTopK(makeConfiguration(ErrorType.NO_FALSE_NEGATIVES, -1), singletonMap("A", "foo"),
BulletConfig.DEFAULT_TOP_K_AGGREGATION_SKETCH_ENTRIES, COUNT_NAME, null, null);
int uniqueGroups = BulletConfig.DEFAULT_TOP_K_AGGREGATION_SKETCH_ENTRIES / 4;
IntStream.range(0, uniqueGroups).mapToObj(i -> RecordBox.get().add("A", i).getRecord())
.forEach(topK::consume);
Clip result = topK.getResult();
Assert.assertNull(result.getMeta().asMap().get("meta"));
List<BulletRecord> records = result.getRecords();
Assert.assertEquals(records.size(), uniqueGroups);
for (BulletRecord actual : records) {
Assert.assertEquals(actual.fieldCount(), 2);
int fieldA = Integer.valueOf((String) actual.typedGet("foo").getValue());
Assert.assertTrue(fieldA < uniqueGroups);
Assert.assertEquals(actual.typedGet(COUNT_NAME).getValue(), 1L);
}
Assert.assertEquals(topK.getRecords(), records);
Assert.assertEquals(topK.getMetadata().asMap(), result.getMeta().asMap());
// Not a power of 2
FrequentItemsSketchingStrategy another = makeTopK(makeConfiguration(ErrorType.NO_FALSE_NEGATIVES, 5), singletonMap("A", "foo"),
BulletConfig.DEFAULT_TOP_K_AGGREGATION_SKETCH_ENTRIES, COUNT_NAME, null, null);
IntStream.range(0, uniqueGroups).mapToObj(i -> RecordBox.get().add("A", i).getRecord())
.forEach(another::consume);
result = another.getResult();
Assert.assertNull(result.getMeta().asMap().get("meta"));
records = result.getRecords();
Assert.assertEquals(records.size(), uniqueGroups);
Assert.assertEquals(another.getRecords(), records);
Assert.assertEquals(another.getMetadata().asMap(), result.getMeta().asMap());
}
protected File getTestApplicationFile() {
String dir = System.getProperty("hawkular.agent.itest.staging.dir"); // the maven build put our test app here
File app = new File(dir, "hawkular-javaagent-helloworld-war.war");
Assert.assertTrue(app.isFile(), "Missing test application - build is bad: " + app.getAbsolutePath());
return app;
}
public void testMapHasWrappedObject(final Map<?, ?> m, final Object key) {
Assert.assertEquals(m.size(), 1);
Assert.assertTrue(key instanceof ScriptObjectMirror);
Assert.assertTrue(m.get(key) instanceof ScriptObjectMirror);
Assert.assertEquals(((ScriptObjectMirror)m.get(key)).get("bar"), 12);
}
/**
* Tests Bayesian inference of a toy copy-ratio model via MCMC.
* <p>
* Recovery of input values for the variance global parameter and the segment-level mean parameters is checked.
* In particular, the mean and standard deviation of the posterior for the variance must be recovered to within
* a relative error of 1% and 5%, respectively, in 500 samples (after 250 burn-in samples have been discarded).
* </p>
* <p>
* Furthermore, the number of truth values for the segment-level means falling outside confidence intervals of
* 1-sigma, 2-sigma, and 3-sigma given by the posteriors in each segment should be roughly consistent with
* a normal distribution (i.e., ~32, ~5, and ~0, respectively; we allow for errors of 10, 5, and 2).
* Finally, the mean of the standard deviations of the posteriors for the segment-level means should be
* recovered to within a relative error of 5%.
* </p>
* <p>
* With these specifications, this unit test is not overly brittle (i.e., it should pass for a large majority
* of randomly generated data sets), but it is still brittle enough to check for correctness of the sampling
* (for example, specifying a sufficiently incorrect likelihood will cause the test to fail).
* </p>
*/
@Test
public void testRunMCMCOnCopyRatioSegmentedGenome() {
//Create new instance of the Modeller helper class, passing all quantities needed to initialize state and data.
final CopyRatioModeller modeller =
new CopyRatioModeller(VARIANCE_INITIAL, MEAN_INITIAL, COVERAGES_FILE, NUM_TARGETS_PER_SEGMENT_FILE);
//Create a GibbsSampler, passing the total number of samples (including burn-in samples)
//and the model held by the Modeller.
final GibbsSampler<CopyRatioParameter, CopyRatioState, CopyRatioDataCollection> gibbsSampler =
new GibbsSampler<>(NUM_SAMPLES, modeller.model);
//Run the MCMC.
gibbsSampler.runMCMC();
//Check that the statistics---i.e., the mean and standard deviation---of the variance posterior
//agree with those found by emcee/analytically to a relative error of 1% and 5%, respectively.
final double[] varianceSamples =
Doubles.toArray(gibbsSampler.getSamples(CopyRatioParameter.VARIANCE, Double.class, NUM_BURN_IN));
final double variancePosteriorCenter = new Mean().evaluate(varianceSamples);
final double variancePosteriorStandardDeviation = new StandardDeviation().evaluate(varianceSamples);
Assert.assertEquals(relativeError(variancePosteriorCenter, VARIANCE_TRUTH),
0., RELATIVE_ERROR_THRESHOLD_FOR_CENTERS);
Assert.assertEquals(relativeError(variancePosteriorStandardDeviation, VARIANCE_POSTERIOR_STANDARD_DEVIATION_TRUTH),
0., RELATIVE_ERROR_THRESHOLD_FOR_STANDARD_DEVIATIONS);
//Check statistics---i.e., the mean and standard deviation---of the segment-level mean posteriors.
//In particular, check that the number of segments where the true mean falls outside confidence intervals
//is roughly consistent with a normal distribution.
final List<Double> meansTruth = loadList(MEANS_TRUTH_FILE, Double::parseDouble);
final int numSegments = meansTruth.size();
final List<SegmentMeans> meansSamples =
gibbsSampler.getSamples(CopyRatioParameter.SEGMENT_MEANS, SegmentMeans.class, NUM_BURN_IN);
int numMeansOutsideOneSigma = 0;
int numMeansOutsideTwoSigma = 0;
int numMeansOutsideThreeSigma = 0;
final List<Double> meanPosteriorStandardDeviations = new ArrayList<>();
for (int segment = 0; segment < numSegments; segment++) {
final int j = segment;
final double[] meanInSegmentSamples =
Doubles.toArray(meansSamples.stream().map(s -> s.get(j)).collect(Collectors.toList()));
final double meanPosteriorCenter = new Mean().evaluate(meanInSegmentSamples);
final double meanPosteriorStandardDeviation =
new StandardDeviation().evaluate(meanInSegmentSamples);
meanPosteriorStandardDeviations.add(meanPosteriorStandardDeviation);
final double absoluteDifferenceFromTruth = Math.abs(meanPosteriorCenter - meansTruth.get(segment));
if (absoluteDifferenceFromTruth > meanPosteriorStandardDeviation) {
numMeansOutsideOneSigma++;
}
if (absoluteDifferenceFromTruth > 2 * meanPosteriorStandardDeviation) {
numMeansOutsideTwoSigma++;
}
if (absoluteDifferenceFromTruth > 3 * meanPosteriorStandardDeviation) {
numMeansOutsideThreeSigma++;
}
}
final double meanPosteriorStandardDeviationsMean =
new Mean().evaluate(Doubles.toArray(meanPosteriorStandardDeviations));
Assert.assertEquals(numMeansOutsideOneSigma, 100 - 68, DELTA_NUMBER_OF_MEANS_ALLOWED_OUTSIDE_1_SIGMA);
Assert.assertEquals(numMeansOutsideTwoSigma, 100 - 95, DELTA_NUMBER_OF_MEANS_ALLOWED_OUTSIDE_2_SIGMA);
Assert.assertTrue(numMeansOutsideThreeSigma <= DELTA_NUMBER_OF_MEANS_ALLOWED_OUTSIDE_3_SIGMA);
Assert.assertEquals(
relativeError(meanPosteriorStandardDeviationsMean, MEAN_POSTERIOR_STANDARD_DEVIATION_MEAN_TRUTH),
0., RELATIVE_ERROR_THRESHOLD_FOR_STANDARD_DEVIATIONS);
}
@Test
public void testSkipTrash() throws IOException {
FileSystem fs = mock(FileSystem.class);
Trash trash = mock(Trash.class);
Path datasetRoot = new Path("/test/dataset");
DatasetVersion dataset1Version1 = new StringDatasetVersion("version1", new Path(datasetRoot, "version1"));
DatasetVersion dataset1Version2 = new StringDatasetVersion("version2", new Path(datasetRoot, "version2"));
when(fs.delete(any(Path.class), anyBoolean())).thenReturn(true);
when(trash.moveToTrash(any(Path.class))).thenReturn(true);
when(fs.exists(any(Path.class))).thenReturn(true);
DatasetImpl dataset = new DatasetImpl(fs, false, true, false, false, datasetRoot);
when(dataset.versionFinder.findDatasetVersions(dataset)).
thenReturn(Lists.newArrayList(dataset1Version1, dataset1Version2));
dataset.clean();
Assert.assertEquals(dataset.getTrash().getDeleteOperations().size(), 1);
Assert.assertTrue(dataset.getTrash().getDeleteOperations().get(0).getPath()
.equals(dataset1Version2.getPathsToDelete().iterator().next()));
Assert.assertTrue(dataset.getTrash().isSkipTrash());
}