private static void assertFloat(Slice slice, int index) { // fill slice with FF slice.fill((byte) 0xFF); // set and get the value slice.setFloat(index, intBitsToFloat(0xAAAA_5555)); assertEquals(floatToIntBits(slice.getFloat(index)), 0xAAAA_5555); try { slice.getFloat(-1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getFloat((slice.length() - SIZE_OF_FLOAT) + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getFloat(slice.length()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getFloat(slice.length() + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } }
private void verifyViewCreation() { // replace works for new view doCreateView(temporaryCreateView, true); // replace works for existing view doCreateView(temporaryCreateView, true); // create fails for existing view try { doCreateView(temporaryCreateView, false); fail("create existing should fail"); } catch (ViewAlreadyExistsException e) { assertEquals(e.getViewName(), temporaryCreateView); } // drop works when view exists metadata.dropView(SESSION, temporaryCreateView); assertEquals(metadata.getViews(SESSION, temporaryCreateView.toSchemaTablePrefix()).size(), 0); assertFalse( metadata .listViews(SESSION, temporaryCreateView.getSchemaName()) .contains(temporaryCreateView)); // drop fails when view does not exist try { metadata.dropView(SESSION, temporaryCreateView); fail("drop non-existing should fail"); } catch (ViewNotFoundException e) { assertEquals(e.getViewName(), temporaryCreateView); } // create works for new view doCreateView(temporaryCreateView, false); }
private static void assertDouble(Slice slice, int index) { // fill slice with FF slice.fill((byte) 0xFF); // set and get the value slice.setDouble(index, longBitsToDouble(0xAAAA_AAAA_5555_5555L)); assertEquals(doubleToLongBits(slice.getDouble(index)), 0xAAAA_AAAA_5555_5555L); try { slice.getDouble(-1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getDouble((slice.length() - SIZE_OF_DOUBLE) + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getDouble(slice.length()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getDouble(slice.length() + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } }
private static void assertLexicographicallySortableLong(Slice slice, int index) { // fill slice with FF slice.fill((byte) 0xFF); // set and get the value slice.setLexicographicallySortableLong(index, 0xAAAA_AAAA_5555_5555L); assertEquals(slice.getLexicographicallySortableLong(index), 0xAAAA_AAAA_5555_5555L); try { slice.getLexicographicallySortableLong(-1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getLexicographicallySortableLong((slice.length() - SIZE_OF_LONG) + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getLexicographicallySortableLong(slice.length()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getLexicographicallySortableLong(slice.length() + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } }
// Accept a confirmation public void waitForConfirmation(String confirmationText, int... wait) { String message = getTextFromAlert(); int timeOut = wait.length > 0 ? wait[0] : DEFAULT_TIMEOUT; // log("confirmation: " + message); if (message.isEmpty()) { if (loopCount > timeOut / 500) { Assert.fail("Message is empty"); } Utils.pause(500); loopCount++; waitForConfirmation(confirmationText); return; } for (int second = 0; ; second++) { if (second >= timeOut) { Assert.fail("Timeout at waitForConfirmation: " + confirmationText); } if (message.contains(confirmationText)) { break; } Utils.pause(100); } Alert alert = driver.switchTo().alert(); alert.accept(); Utils.pause(3000); }
@Test public void testPauseAndUnpause() { skipOnAdminExtensionAbsent(); ServerAdminApi api = apiOption.get(); // Unlock and lock (double-checking error contitions too) try { api.unpause(testServerId); fail("Unpaused active server!"); } catch (HttpResponseException e) { } assertTrue(api.pause(testServerId)); blockUntilServerInState(testServerId, serverApi, Status.PAUSED); try { api.pause(testServerId); fail("paused a paused server!"); } catch (HttpResponseException e) { } assertTrue(api.unpause(testServerId)); blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); try { api.unpause(testServerId); fail("Unpaused a server we just unpaused!"); } catch (HttpResponseException e) { } }
@BeforeTest( description = "Before test method for adding prerequisite deletion tags for test.", groups = TestGroups.DELETION_TAG_REQUIRED_GROUP) protected void addRequiredDeletionTagData() { try { existingDeletionTagOneName = createDynamicTestTagNames(); existingDeletionTagOneStbIds = createRequestedTestStbs(TestConstants.DELETE_TAG_ONE_STB_COUNT); addTagUsingRestRequest(existingDeletionTagOneName, existingDeletionTagOneStbIds); bufferTheTagsToBeCleared(existingDeletionTagOneName, existingDeletionTagOneStbIds); // A new tag creation which hold the STB of previously added tag. if (null != existingDeletionTagOneStbIds && existingDeletionTagOneStbIds.length > 0) { existingDeletionTagTwoName = createDynamicTestTagNames(); existingDeletionTagTwoStbId = existingDeletionTagOneStbIds[0]; addTagUsingRestRequest(existingDeletionTagTwoName, existingDeletionTagTwoStbId); bufferTheTagsToBeCleared(existingDeletionTagTwoName, existingDeletionTagTwoStbId); } else { Assert.fail( String.format( "Failed to create a second tag for deletion as no settop where tagged to the first tag for deletion.")); } } catch (IOException e) { Assert.fail( String.format( "Failed to add tags for deleting (%s,%s) in the precondition of the test.", existingDeletionTagOneName, existingDeletionTagTwoStbId), e); } }
public void testClosedStream() throws IOException { try (Stream<Path> s = Files.list(testFolder)) { s.close(); Object[] actual = s.sorted().toArray(); fail("Operate on closed stream should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected } try (Stream<Path> s = Files.walk(testFolder)) { s.close(); Object[] actual = s.sorted().toArray(); fail("Operate on closed stream should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected } try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, (p, attr) -> true)) { s.close(); Object[] actual = s.sorted().toArray(); fail("Operate on closed stream should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected } }
/** * If the coordinator of the lock locks the lock and then send a message, the receiver will wait * for ever in tryLock. However, castMessage will return after a while because of the default * settings of RequestOptions.SYNC(). */ public void testCoordSendFirst() throws Exception { System.out.println("Running testCoordSendFirst"); // =========================================================================== if (lock_a.tryLock()) { try { System.out.println("A aquired the lock, about to send message to B"); String rsp = disp_a.sendMessage( new Message(b.getAddress(), "bla"), RequestOptions.SYNC().setTimeout(60000)); if (rsp == null) { System.err.println("ERROR: didn't return correctly"); Assert.fail("Didn't return correctly"); } else System.out.println("Returned: " + rsp); } finally { lock_a.unlock(); } } else { Assert.fail("The lock was already locked"); System.out.println("A failed to aquire the lock"); } // =========================================================================== System.out.println(); }
@Test public final void testTransform() { File xml = new File(getClass().getResource("CR6941869.xml").getFile()); File xsl = new File(getClass().getResource("CR6941869.xsl").getFile()); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); StreamSource source = new StreamSource(xsl); transformer = tFactory.newTransformer(source); // the xml result StringWriter xmlResultString = new StringWriter(); StreamResult xmlResultStream = new StreamResult(xmlResultString); transformer.transform(new StreamSource(xml), xmlResultStream); System.out.println(xmlResultString.toString()); String temp = xmlResultString.toString(); int pos = temp.lastIndexOf("count"); if (temp.substring(pos + 8, pos + 9).equals("1")) { Assert.fail("count=1"); } else if (temp.substring(pos + 8, pos + 9).equals("2")) { // expected success System.out.println("count=2"); } } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
// todo: honfika @Test public void testNotRemoveParams() throws Exception { String res = recompile( "function tst(p1,p2){" + "var a = 2;" + "var b = 3 * a;" + "if(b>1){" + "trace(\"OK1\");" + "}else{" + "trace(\"FAIL1\");" + "}" + "var c = p1*5;" + "if(c){" + "trace(\"OK2\");" + "}else{" + "trace(\"OK3\");" + "}" + "}"); if (!res.contains("\"OK1\"")) { fail("basic if true onTrue removed"); } if (res.contains("\"FAIL1\"")) { fail("basic if true onFalse not removed"); } if (!res.contains("\"OK2\"")) { fail("if parameter onTrue removed"); } if (!res.contains("\"OK3\"")) { fail("if parameter onFalse removed"); } }
// The two following tests a really unit tests, but since the whole uses // CCMBridge.PerClassSingleNodeCluster, they'll still spawn a cluster even // you execute only them, so we keep them in the "long" group. We could // move them in another class but not sure where honestly (one could argue // that it would make more sense to move all the *other* tests to some // DataTypeIntegrationTest class). @Test(groups = "long") public void serializeDeserializeTest() { for (DataType dt : DataType.allPrimitiveTypes()) { if (exclude(dt)) continue; Object value = TestUtils.getFixedValue(dt); assertEquals(dt.deserialize(dt.serialize(value)), value); } try { DataType.bigint().serialize(4); fail("This should not have worked"); } catch (InvalidTypeException e) { /* That's what we want */ } try { ByteBuffer badValue = ByteBuffer.allocate(4); DataType.bigint().deserialize(badValue); fail("This should not have worked"); } catch (InvalidTypeException e) { /* That's what we want */ } }
public static <T> void assertContents(Iterator<T> actual, Iterator<T> expected, String msg) { List<T> history = new ArrayList<>(); while (expected.hasNext()) { if (!actual.hasNext()) { List<T> expectedData = new ArrayList<>(history); while (expected.hasNext()) expectedData.add(expected.next()); fail( String.format( "%s Premature end of data; expected=%s, found=%s", (msg == null ? "" : msg), expectedData, history)); } T a = actual.next(); T e = expected.next(); history.add(a); if (!Objects.equals(a, e)) fail( String.format( "%s Data mismatch; preceding=%s, nextExpected=%s, nextFound=%s", (msg == null ? "" : msg), history, e, a)); } if (actual.hasNext()) { List<T> rest = new ArrayList<>(); while (actual.hasNext()) rest.add(actual.next()); fail( String.format("%s Unexpected data %s after %s", (msg == null ? "" : msg), rest, history)); } }
@Test(groups = PROXY) public void checkInvalidProxy() throws Exception { if (true) { printKnownErrorButDoNotFail(getClass(), "downloadArtifactOverWebProxy"); return; } Thread thread = new Thread(this); thread.setDaemon(true); // don't stuck VM thread.start(); for (int i = 0; i < 100; i++) { String status = this.status; if (status.startsWith("fail")) { Assert.fail("Verifier fail: " + status); } else if (status.equals("executed")) { // finished ok return; } Thread.yield(); Thread.sleep(200); } Assert.fail("Verifier didn't runn after 20 seconds: " + this.status); }
@Test public void shouldTestCRUDShortTermRecommendations() throws URISyntaxException, MalformedURLException { try { recommendationsStorage.deleteShortTermResourceRecommendations(new URI(USER_URI)); } catch (RecommendationsStorageException e) { fail("failed deleting short term recs"); } List<WebResourceEnhanced> expectedRecs = PersistenceDomainFixtures.getResources(); try { recommendationsStorage.storeShortTermResourceRecommendations(new URI(USER_URI), expectedRecs); } catch (RecommendationsStorageException e) { fail("failed storing short term recs"); } List<WebResourceEnhanced> actualRecs = new ArrayList<WebResourceEnhanced>(); try { actualRecs.addAll( recommendationsStorage.getShortTermResourceRecommendations(new URI(USER_URI))); } catch (RecommendationsStorageException e) { fail("failed getting short term recs"); } assertNotNull(actualRecs); assertEqualsNoOrder(actualRecs.toArray(), expectedRecs.toArray()); try { recommendationsStorage.deleteShortTermResourceRecommendations(new URI(USER_URI)); } catch (RecommendationsStorageException e) { fail("failed deleting short term recs"); } }
private void validateInjectionPoints(Set<InjectionPoint> injectionPoints) { assertEquals(2, injectionPoints.size()); for (InjectionPoint ip : injectionPoints) { AnnotatedParameter<Factory> parameter = this.<AnnotatedParameter<Factory>>cast(ip.getAnnotated()); if (parameter.getPosition() == 0) { // BeanManager assertEquals(BeanManager.class, parameter.getBaseType()); } else if (parameter.getPosition() == 1) { // SpaceSuit<Toy> Type baseType = parameter.getBaseType(); if (baseType instanceof ParameterizedType && ((ParameterizedType) baseType).getRawType() instanceof Class<?>) { assertEquals(((ParameterizedType) baseType).getRawType(), SpaceSuit.class); } else { fail(); } } else { fail("Unexpected injection point " + ip); } assertFalse(ip.isDelegate()); assertFalse(ip.isTransient()); assertNull(ip.getBean()); } }
private void validateFileSystemLoopException(Path start, Path... causes) { try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) { try { int count = s.mapToInt(p -> 1).reduce(0, Integer::sum); fail("Should got FileSystemLoopException, but got " + count + "elements."); } catch (UncheckedIOException uioe) { IOException ioe = uioe.getCause(); if (ioe instanceof FileSystemLoopException) { FileSystemLoopException fsle = (FileSystemLoopException) ioe; boolean match = false; for (Path cause : causes) { if (fsle.getFile().equals(cause.toString())) { match = true; break; } } assertTrue(match); } else { fail("Unexpected UncheckedIOException cause " + ioe.toString()); } } } catch (IOException ex) { fail("Unexpected IOException " + ex); } }
@Test(groups = "fast") public void testBaseCase() throws CatalogApiException { final DefaultProduct product1 = cat.getCurrentProduct(0); final DefaultProduct product2 = cat.getCurrentProduct(1); final DefaultPriceList priceList1 = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME); final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[0]; final PlanPhaseSpecifier from = new PlanPhaseSpecifier( product1.getName(), BillingPeriod.MONTHLY, priceList1.getName(), PhaseType.EVERGREEN); final PlanSpecifier to = new PlanSpecifier(product2.getName(), BillingPeriod.MONTHLY, null); PlanChangeResult result = null; try { result = cat.getPlanRules().planChange(from, to, cat); } catch (IllegalPlanChange e) { Assert.fail("We should not have triggered this error"); } catch (CatalogApiException e) { Assert.fail("", e); } Assert.assertEquals(result.getPolicy(), BillingActionPolicy.END_OF_TERM); Assert.assertEquals(result.getAlignment(), PlanAlignmentChange.START_OF_SUBSCRIPTION); Assert.assertEquals(result.getNewPriceList(), priceList2); }
@Test(enabled = false) public void weCanCancelTasks(NodeMetadata node) throws InterruptedException, ExecutionException { ListenableFuture<ExecResponse> future = client.submitScriptOnNode(node.getId(), "sleep 300", nameTask("sleeper").runAsRoot(false)); ExecResponse response = null; try { response = future.get(1, TimeUnit.MILLISECONDS); fail(node.getId() + ": " + response); } catch (TimeoutException e) { assert !future.isDone(); response = client.runScriptOnNode( node.getId(), "/tmp/init-sleeper status", wrapInInitScript(false).runAsRoot(false)); assert !response.getOutput().trim().equals("") : node.getId() + ": " + response; future.cancel(true); response = client.runScriptOnNode( node.getId(), "/tmp/init-sleeper status", wrapInInitScript(false).runAsRoot(false)); assert response.getOutput().trim().equals("") : node.getId() + ": " + response; try { future.get(); fail(future.toString()); } catch (CancellationException e1) { } } }
@Test(expectedExceptions = {ConfigurationSerializerException.class}) public void testBadContent() throws ConfigurationSerializerException { File tmpF = null; PrintWriter out = null; try { tmpF = File.createTempFile("out", "out"); out = new PrintWriter(new FileWriter(tmpF)); out.println("toto"); } catch (IOException e) { Assert.fail(e.getMessage(), e); } finally { if (out != null) { out.close(); } } String name = tmpF.getAbsolutePath(); try { PlainTextConfigurationSerializer.getInstance().read(name); } catch (IOException e) { Assert.fail(e.getMessage(), e); } finally { tmpF.delete(); } }
@Test public void testInvalidTransitions() throws Exception { Feed mockEntity = new Feed(); mockEntity.setName("test"); storeEntity(EntityType.FEED, "test"); StateService.get().handleStateChange(mockEntity, EntityState.EVENT.SUBMIT, listener); // Attempt suspending a submitted entity try { StateService.get().handleStateChange(mockEntity, EntityState.EVENT.SUSPEND, listener); Assert.fail("Exception expected"); } catch (InvalidStateTransitionException e) { // Do nothing } StateService.get().handleStateChange(mockEntity, EntityState.EVENT.SCHEDULE, listener); // Attempt resuming a scheduled entity try { StateService.get().handleStateChange(mockEntity, EntityState.EVENT.RESUME, listener); Assert.fail("Exception expected"); } catch (InvalidStateTransitionException e) { // Do nothing } // Attempt scheduling a cluster Cluster mockCluster = new Cluster(); mockCluster.setName("test"); StateService.get().handleStateChange(mockCluster, EntityState.EVENT.SUBMIT, listener); try { StateService.get().handleStateChange(mockCluster, EntityState.EVENT.SCHEDULE, listener); Assert.fail("Exception expected"); } catch (FalconException e) { // Do nothing } }
// necessary to not overload equals for genotypes private void assertGenotypesAreMostlyEqual(GenotypesContext actual, GenotypesContext expected) { if (actual == expected) { return; } if (actual == null || expected == null) { Assert.fail("Maps not equal: expected: " + expected + " and actual: " + actual); } if (actual.size() != expected.size()) { Assert.fail("Maps do not have the same size:" + actual.size() + " != " + expected.size()); } for (Genotype value : actual) { Genotype expectedValue = expected.get(value.getSampleName()); Assert.assertEquals( value.getAlleles(), expectedValue.getAlleles(), "Alleles in Genotype aren't equal"); Assert.assertEquals(value.getGQ(), expectedValue.getGQ(), "GQ values aren't equal"); Assert.assertEquals( value.hasLikelihoods(), expectedValue.hasLikelihoods(), "Either both have likelihoods or both not"); if (value.hasLikelihoods()) Assert.assertEquals( value.getLikelihoods().getAsVector(), expectedValue.getLikelihoods().getAsVector(), "Genotype likelihoods aren't equal"); } }
public void testSuspendAndResume() { skipOnAdminExtensionAbsent(); ServerAdminApi api = apiOption.get(); // Suspend-resume try { api.resume(testServerId); fail("Resumed an active server!"); } catch (HttpResponseException e) { } assertTrue(api.suspend(testServerId)); blockUntilServerInState(testServerId, serverApi, Status.SUSPENDED); try { api.suspend(testServerId); fail("Suspended an already suspended server!"); } catch (HttpResponseException e) { } assertTrue(api.resume(testServerId)); blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); try { api.resume(testServerId); fail("Resumed an already resumed server!"); } catch (HttpResponseException e) { } }
private static void assertPropertiesSupported( ConfigurationMetadata<?> metadata, Set<String> propertyNames, boolean allowDeprecatedProperties) { Set<String> supportedProperties = new TreeSet<>(); Set<String> nonDeprecatedProperties = new TreeSet<>(); for (AttributeMetadata attribute : metadata.getAttributes().values()) { if (attribute.getInjectionPoint().getProperty() != null) { nonDeprecatedProperties.add(attribute.getInjectionPoint().getProperty()); supportedProperties.add(attribute.getInjectionPoint().getProperty()); } for (ConfigurationMetadata.InjectionPointMetaData deprecated : attribute.getLegacyInjectionPoints()) { supportedProperties.add(deprecated.getProperty()); } } if (!supportedProperties.containsAll(propertyNames)) { TreeSet<String> unsupportedProperties = new TreeSet<>(propertyNames); unsupportedProperties.removeAll(supportedProperties); Assert.fail("Unsupported properties: " + unsupportedProperties); } // check for usage of deprecated properties if (!allowDeprecatedProperties && !nonDeprecatedProperties.containsAll(propertyNames)) { TreeSet<String> deprecatedProperties = new TreeSet<>(propertyNames); deprecatedProperties.removeAll(nonDeprecatedProperties); Assert.fail("Deprecated properties: " + deprecatedProperties); } }
private static void assertShort(Slice slice, short index) { // fill slice with FF slice.fill((byte) 0xFF); // set and get the value slice.setShort(index, 0xAA55); assertEquals(slice.getShort(index), (short) 0xAA55); try { slice.getShort(-1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getShort((slice.length() - SIZE_OF_SHORT) + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getShort(slice.length()); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { slice.getShort(slice.length() + 1); fail("expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } }
public void testIndexMapAddItem() { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); final ODocument docThree = new ODocument(); docThree.save(); Map<String, ORID> map = new HashMap<String, ORID>(); map.put("key1", docOne.getIdentity()); map.put("key2", docTwo.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", map); document.save(); database .command( new OCommandSQL( "UPDATE " + document.getIdentity() + " put linkMap = 'key3', " + docThree.getIdentity())) .execute(); final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 3); for (ODocument d : resultByKey) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals("key1") && !d.field("key").equals("key2") && !d.field("key").equals("key3")) { Assert.fail("Unknown key found: " + d.field("key")); } } final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 3); for (ODocument d : resultByValue) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals(docOne.getIdentity()) && !d.field("key").equals(docTwo.getIdentity()) && !d.field("key").equals(docThree.getIdentity())) { Assert.fail("Unknown key found: " + d.field("key")); } } }
public void testIndexMapRemoveItemInTx() throws Exception { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); final ODocument docThree = new ODocument(); docThree.save(); Map<String, ORID> map = new HashMap<String, ORID>(); map.put("key1", docOne.getIdentity()); map.put("key2", docTwo.getIdentity()); map.put("key3", docThree.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", map); document.save(); try { database.begin(); final ODocument loadedDocument = database.load(document.getIdentity()); loadedDocument.<Map<String, ORID>>field("linkMap").remove("key2"); loadedDocument.save(); database.commit(); } catch (Exception e) { database.rollback(); throw e; } final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 2); for (ODocument d : resultByKey) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals("key1") && !d.field("key").equals("key3")) { Assert.fail("Unknown key found: " + d.field("key")); } } final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 2); for (ODocument d : resultByValue) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals(docOne.getIdentity()) && !d.field("key").equals(docThree.getIdentity())) { Assert.fail("Unknown key found: " + d.field("key")); } } }
public void searchContent() { SearchResultsBean bean = null; try { boolean searchSuccess = false; // Retrying until test passes log.info("### Content search retry cycle started .. "); for (int i = 0; i < RERTY_CYCLES; i++) { log.info("#### Content search cycle # " + i); bean = contentSearchAdminServiceStub.getContentSearchResults( "ArrayOftCountrySelectedTopScorer"); if (bean.getResourceDataList() != null) { bean.setResourceDataList(new ResourceData[0]); searchSuccess = true; log.info("#### Content search PASSED .. in seconds : " + i * 15); break; } else { doSleep(); } } if (!searchSuccess) { fail("# MetaData search test failed .. "); log.info("# MetaData search test failed .. "); log.error("# MetaData search test failed .. "); } } catch (Exception e) { fail("Content search failed: " + e); log.error("Content search failed: " + e.getMessage()); String msg = "Failed to get search results from the search service. " + e.getMessage(); log.error(msg, e); } }
/* 1. A command that throws exception 2. Try to take screenshot, it also throws exception. Don't fall into infinite loop 3. New command that throws exception 4. Should take screenshot correctly */ @Test public void shouldTakeScreenshotForCommandAfterThrowingExceptionWhileTakingScreenshot() throws Exception { // when // Do some command that throws exception. Taking screenshot also throws exception, it should // not fall into infinite loop. Screenshot not taken. try { exceptionThrowingScreenshotter.setExceptionThrowing(true); processor.doCommand(EXCEPTION_THROWING_COMMAND, null); Assert.fail("Exception should be thrown"); } catch (RuntimeException e) { // It's ok. This exception was expected. } // then Assert.assertEquals(exceptionThrowingScreenshotter.screenshotsCount(), 0); // Now again issue "exceptional" command, but this time screenshot should be captured. try { exceptionThrowingScreenshotter.setExceptionThrowing(false); processor.doCommand(EXCEPTION_THROWING_COMMAND, null); Assert.fail("Exception should be thrown"); } catch (RuntimeException e) { // It's ok. This exception was expected. } // then Assert.assertEquals(exceptionThrowingScreenshotter.screenshotsCount(), 1); }
public void testSuspendAndResume() { if (clientOption.isPresent()) { AdminActionsClient client = clientOption.get(); // Suspend-resume try { client.resumeServer(testServerId); fail("Resumed an active server!"); } catch (HttpResponseException e) { } assertTrue(client.suspendServer(testServerId)); blockUntilServerInState(testServerId, serverClient, Server.Status.SUSPENDED); try { client.suspendServer(testServerId); fail("Suspended an already suspended server!"); } catch (HttpResponseException e) { } assertTrue(client.resumeServer(testServerId)); blockUntilServerInState(testServerId, serverClient, Server.Status.ACTIVE); try { client.resumeServer(testServerId); fail("Resumed an already resumed server!"); } catch (HttpResponseException e) { } } }