use of org.junit.Assert.assertEquals in project pravega by pravega.
the class ZkStreamTest method testTransaction.
@Test(timeout = 10000)
public void testTransaction() throws Exception {
final ScalingPolicy policy = ScalingPolicy.fixed(5);
final StreamMetadataStore store = new ZKStreamMetadataStore(cli, executor);
final String streamName = "testTx";
store.createScope(SCOPE).get();
final Predicate<Throwable> operationNotAllowedPredicate = ex -> Exceptions.unwrap(ex) instanceof StoreException.IllegalStateException;
StreamConfiguration streamConfig = StreamConfiguration.builder().scope(SCOPE).streamName(streamName).scalingPolicy(policy).build();
store.createStream(SCOPE, streamName, streamConfig, System.currentTimeMillis(), null, executor).get();
store.setState(SCOPE, streamName, State.ACTIVE, null, executor).get();
OperationContext context = store.createContext(ZkStreamTest.SCOPE, streamName);
UUID txnId1 = UUID.randomUUID();
VersionedTransactionData tx = store.createTransaction(SCOPE, streamName, txnId1, 10000, 600000, 30000, context, executor).get();
Assert.assertEquals(txnId1, tx.getId());
UUID txnId2 = UUID.randomUUID();
VersionedTransactionData tx2 = store.createTransaction(SCOPE, streamName, txnId2, 10000, 600000, 30000, context, executor).get();
Assert.assertEquals(txnId2, tx2.getId());
store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.<Integer>empty(), context, executor).get();
assert store.transactionStatus(SCOPE, streamName, tx.getId(), context, executor).get().equals(TxnStatus.COMMITTING);
// Test to ensure that sealTransaction is idempotent.
Assert.assertEquals(TxnStatus.COMMITTING, store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.empty(), context, executor).join().getKey());
// Test to ensure that COMMITTING transaction cannot be aborted.
testAbortFailure(store, SCOPE, streamName, tx.getEpoch(), tx.getId(), context, operationNotAllowedPredicate);
CompletableFuture<TxnStatus> f1 = store.commitTransaction(SCOPE, streamName, tx.getEpoch(), tx.getId(), context, executor);
store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.<Integer>empty(), context, executor).get();
assert store.transactionStatus(SCOPE, streamName, tx2.getId(), context, executor).get().equals(TxnStatus.ABORTING);
// Test to ensure that sealTransaction is idempotent.
Assert.assertEquals(TxnStatus.ABORTING, store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.empty(), context, executor).join().getKey());
// Test to ensure that ABORTING transaction cannot be committed.
testCommitFailure(store, SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, operationNotAllowedPredicate);
CompletableFuture<TxnStatus> f2 = store.abortTransaction(SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, executor);
CompletableFuture.allOf(f1, f2).get();
assert store.transactionStatus(SCOPE, streamName, tx.getId(), context, executor).get().equals(TxnStatus.COMMITTED);
assert store.transactionStatus(SCOPE, streamName, tx2.getId(), context, executor).get().equals(TxnStatus.ABORTED);
// Test to ensure that sealTransaction, to commit it, on committed transaction does not throw an error.
Assert.assertEquals(TxnStatus.COMMITTED, store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.empty(), context, executor).join().getKey());
// Test to ensure that commitTransaction is idempotent.
Assert.assertEquals(TxnStatus.COMMITTED, store.commitTransaction(SCOPE, streamName, tx.getEpoch(), tx.getId(), context, executor).join());
// Test to ensure that sealTransaction, to abort it, and abortTransaction on committed transaction throws error.
testAbortFailure(store, SCOPE, streamName, tx.getEpoch(), tx.getId(), context, operationNotAllowedPredicate);
// Test to ensure that sealTransaction, to abort it, on aborted transaction does not throw an error.
Assert.assertEquals(TxnStatus.ABORTED, store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.empty(), context, executor).join().getKey());
// Test to ensure that abortTransaction is idempotent.
Assert.assertEquals(TxnStatus.ABORTED, store.abortTransaction(SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, executor).join());
// Test to ensure that sealTransaction, to abort it, and abortTransaction on committed transaction throws error.
testCommitFailure(store, SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, operationNotAllowedPredicate);
assert store.commitTransaction(ZkStreamTest.SCOPE, streamName, 0, UUID.randomUUID(), null, executor).handle((ok, ex) -> {
if (ex.getCause() instanceof StoreException.DataNotFoundException) {
return true;
} else {
throw new RuntimeException("assert failed");
}
}).get();
assert store.abortTransaction(ZkStreamTest.SCOPE, streamName, 0, UUID.randomUUID(), null, executor).handle((ok, ex) -> {
if (ex.getCause() instanceof StoreException.DataNotFoundException) {
return true;
} else {
throw new RuntimeException("assert failed");
}
}).get();
assert store.transactionStatus(ZkStreamTest.SCOPE, streamName, UUID.randomUUID(), context, executor).get().equals(TxnStatus.UNKNOWN);
}
use of org.junit.Assert.assertEquals in project graal by oracle.
the class SLExceptionTest method assertException.
private void assertException(boolean failImmediately, String source, String... expectedFrames) {
boolean initialExecute = true;
try {
Value value = ctx.eval("sl", source);
initialExecute = false;
if (failImmediately) {
Assert.fail("Should not reach here.");
}
ProxyExecutable proxy = (args) -> args[0].execute();
value.execute(proxy);
Assert.fail("Should not reach here.");
} catch (PolyglotException e) {
Assert.assertEquals(failImmediately, initialExecute);
assertFrames(failImmediately, e, expectedFrames);
}
}
use of org.junit.Assert.assertEquals in project graal by oracle.
the class MultiThreadedLanguageTest method testAccessTruffleContextFromExclusivePolyglotThread.
@Test
public void testAccessTruffleContextFromExclusivePolyglotThread() throws Throwable {
// don't allow multi-threading in this test as every context
// is used exclusively by one thread.
MultiThreadedLanguage.isThreadAccessAllowed = (req) -> {
return req.singleThreaded;
};
final int iterations = 10;
final int innerIterations = 10;
AtomicReference<Throwable> lastError = new AtomicReference<>();
UncaughtExceptionHandler uncaughtHandler = (run, e) -> lastError.set(e);
Context polyglotContext = Context.newBuilder().allowCreateThread(true).build();
ConcurrentHashMap<LanguageContext, String> seenContexts = new ConcurrentHashMap<>();
eval(polyglotContext, new Function<Env, Object>() {
@SuppressWarnings("hiding")
public Object apply(Env env) {
List<Thread> threads = new ArrayList<>();
List<TruffleContext> contexts = new ArrayList<>();
for (int i = 0; i < iterations; i++) {
TruffleContext context = env.newContextBuilder().build();
Thread thread = env.createThread(() -> {
assertUniqueContext();
List<Thread> innerThreads = new ArrayList<>();
List<TruffleContext> innerContexts = new ArrayList<>();
for (int j = 0; j < innerIterations; j++) {
TruffleContext innerContext = env.newContextBuilder().build();
Thread innerThread = env.createThread(() -> {
assertUniqueContext();
}, innerContext);
innerThread.setUncaughtExceptionHandler(uncaughtHandler);
innerThread.start();
innerThreads.add(innerThread);
innerContexts.add(innerContext);
}
for (Thread innerThread : innerThreads) {
try {
innerThread.join();
} catch (InterruptedException e) {
}
}
for (TruffleContext innerContext : innerContexts) {
innerContext.close();
}
}, context);
thread.setUncaughtExceptionHandler(uncaughtHandler);
thread.start();
threads.add(thread);
contexts.add(context);
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
for (TruffleContext context : contexts) {
context.close();
}
return null;
}
private LanguageContext assertUniqueContext() {
LanguageContext languageContext = MultiThreadedLanguage.getContext();
Assert.assertNotNull(languageContext);
Assert.assertFalse(seenContexts.containsKey(languageContext));
seenContexts.put(languageContext, "");
return languageContext;
}
});
Assert.assertEquals(221, initializeCount.get());
Assert.assertEquals(initializeCount.get() - 1, disposeCount.get());
Assert.assertEquals(0, initializeMultiThreadingCount.get());
// Test that the same context is available in threads when created with Env.getContext()
MultiThreadedLanguage.isThreadAccessAllowed = (req) -> {
return true;
};
eval(polyglotContext, new Function<Env, Object>() {
@SuppressWarnings("hiding")
public Object apply(Env env) {
List<Thread> threads = new ArrayList<>();
LanguageContext languageContext = MultiThreadedLanguage.getContext();
for (int i = 0; i < iterations; i++) {
Thread thread = env.createThread(() -> {
LanguageContext threadContext = MultiThreadedLanguage.getContext();
assertSame(languageContext, threadContext);
List<Thread> innerThreads = new ArrayList<>();
List<TruffleContext> innerContexts = new ArrayList<>();
for (int j = 0; j < innerIterations; j++) {
Thread innerThread = env.createThread(() -> {
LanguageContext innerThreadContext = MultiThreadedLanguage.getContext();
assertSame(languageContext, innerThreadContext);
}, env.getContext());
innerThread.setUncaughtExceptionHandler(uncaughtHandler);
innerThread.start();
innerThreads.add(innerThread);
}
for (Thread innerThread : innerThreads) {
try {
innerThread.join();
} catch (InterruptedException e) {
}
}
for (TruffleContext innerContext : innerContexts) {
innerContext.close();
}
}, env.getContext());
thread.setUncaughtExceptionHandler(uncaughtHandler);
thread.start();
threads.add(thread);
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
return null;
}
});
if (lastError.get() != null) {
throw lastError.get();
}
polyglotContext.close();
Assert.assertEquals(331, initializeCount.get());
Assert.assertEquals(initializeCount.get(), disposeCount.get());
Assert.assertEquals(1, initializeMultiThreadingCount.get());
}
use of org.junit.Assert.assertEquals in project rdf2neo by Rothamsted.
the class CypherHandlersIT method testRelations.
/**
* Tests {@link CyRelationLoadingHandler} to see if relations are mapped from RDF and loaded into Neo4J.
*/
@Test
public void testRelations() throws Exception {
try (Driver neoDriver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "test"));
CyRelationLoadingHandler handler = new CyRelationLoadingHandler();
RdfDataManager rdfMgr = new RdfDataManager(RdfDataManagerTest.TDB_PATH);
Neo4jDataManager neoMgr = new Neo4jDataManager(neoDriver)) {
handler.setRdfDataManager(rdfMgr);
handler.setNeo4jDataManager(neoMgr);
handler.setRelationTypesSparql(RdfDataManagerTest.SPARQL_REL_TYPES);
handler.setRelationPropsSparql(RdfDataManagerTest.SPARQL_REL_PROPS);
Set<QuerySolution> relSparqlRows = new HashSet<>();
Dataset dataSet = rdfMgr.getDataSet();
Txn.executeRead(dataSet, () -> SparqlUtils.select(RdfDataManagerTest.SPARQL_REL_TYPES, rdfMgr.getDataSet().getDefaultModel()).forEachRemaining(row -> relSparqlRows.add(row)));
handler.accept(relSparqlRows);
Session session = neoDriver.session(AccessMode.READ);
StatementResult cursor = session.run("MATCH ()-[r]->() RETURN COUNT ( r ) AS ct");
Assert.assertEquals("Wrong count for relations", 3, cursor.next().get("ct").asLong());
cursor = session.run("MATCH p = (:TestNode{ iri:$iri1 })-[:relatedTo]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) AS ct", parameters("iri1", iri("ex:1"), "iri2", iri("ex:2")));
Assert.assertEquals("Wrong count for {1 relatedTo 2}!", 1, cursor.next().get("ct").asLong());
cursor = session.run("MATCH p = (:SuperTestNode{ iri:$iri1 })-[:derivedFrom]->(:TestNode{ iri:$iri2 }) RETURN COUNT ( p ) AS ct", parameters("iri1", iri("ex:3"), "iri2", iri("ex:1")));
Assert.assertEquals("Wrong count for {3 derivedFrom 1}!", 1, cursor.next().get("ct").asLong());
cursor = session.run("MATCH (:TestNode{ iri:$iri1 })-[r:relatedTo]->(:AdditionalLabel{ iri:$iri2 }) RETURN r.note AS note", parameters("iri1", iri("ex:2"), "iri2", iri("ex:3")));
assertTrue("{2 relatedTo 3} not found!", cursor.hasNext());
Set<String> values = cursor.next().get("note").asList().stream().map(v -> (String) v).collect(Collectors.toSet());
Set<String> refValues = new HashSet<>(Arrays.asList(new String[] { "Reified Relation", "Another Note" }));
assertTrue("reified relation, wrong property value for 'note'!", Sets.difference(values, refValues).isEmpty());
}
}
use of org.junit.Assert.assertEquals in project atlasdb by palantir.
the class SnapshotTransactionTest method testTransactionAtomicity.
@Test
public void testTransactionAtomicity() throws Exception {
// This test runs multiple transactions in parallel, with KeyValueService.put calls throwing
// a RuntimeException from time to time and hanging other times. which effectively kills the
// thread. We ensure that every transaction either adds 5 rows to the table or adds 0 rows
// by checking at the end that the number of rows is a multiple of 5.
final TableReference tableRef = TABLE;
Random random = new Random(1);
final UnstableKeyValueService unstableKvs = new UnstableKeyValueService(keyValueService, random);
final TestTransactionManager unstableTransactionManager = new TestTransactionManagerImpl(unstableKvs, timestampService, lockClient, lockService, transactionService, conflictDetectionManager, sweepStrategyManager, sweepQueue);
ScheduledExecutorService service = PTExecutors.newScheduledThreadPool(20);
for (int i = 0; i < 30; i++) {
final int threadNumber = i;
service.schedule((Callable<Void>) () -> {
if (threadNumber == 10) {
unstableKvs.setRandomlyThrow(true);
}
if (threadNumber == 20) {
unstableKvs.setRandomlyHang(true);
}
Transaction transaction = unstableTransactionManager.createNewTransaction();
BatchingVisitable<RowResult<byte[]>> results = transaction.getRange(tableRef, RangeRequest.builder().build());
final MutableInt nextIndex = new MutableInt(0);
results.batchAccept(1, AbortingVisitors.batching((AbortingVisitor<RowResult<byte[]>, Exception>) row -> {
byte[] dataBytes = row.getColumns().get(PtBytes.toBytes("data"));
BigInteger dataValue = new BigInteger(dataBytes);
nextIndex.setValue(Math.max(nextIndex.toInteger(), dataValue.intValue() + 1));
return true;
}));
// rows to the table.
for (int j = 0; j < 5; j++) {
int rowNumber = nextIndex.toInteger() + j;
Cell cell = Cell.create(PtBytes.toBytes("row" + rowNumber), PtBytes.toBytes("data"));
transaction.put(tableRef, ImmutableMap.of(cell, BigInteger.valueOf(rowNumber).toByteArray()));
Thread.yield();
}
transaction.commit();
return null;
}, i * 20, TimeUnit.MILLISECONDS);
}
service.shutdown();
service.awaitTermination(1, TimeUnit.SECONDS);
// Verify each table has a number of rows that's a multiple of 5
Transaction verifyTransaction = txManager.createNewTransaction();
BatchingVisitable<RowResult<byte[]>> results = verifyTransaction.getRange(tableRef, RangeRequest.builder().build());
final MutableInt numRows = new MutableInt(0);
results.batchAccept(1, AbortingVisitors.batching((AbortingVisitor<RowResult<byte[]>, Exception>) row -> {
numRows.increment();
return true;
}));
Assert.assertEquals(0, numRows.toInteger() % 5);
}
Aggregations