Java Examples for java.lang.AssertionError
The following java examples will help you to understand the usage of java.lang.AssertionError. These source code samples are taken from different open source projects.
Example 1
| Project: neembuunow-master File: OAuthAuthorization.java View source code |
/* Error */
String generateSignature(String paramString, OAuthToken paramOAuthToken) {
// Byte code:
// 0: ldc 14
// 2: invokestatic 350 javax/crypto/Mac:getInstance (Ljava/lang/String;)Ljavax/crypto/Mac;
// 5: astore 5
// 7: aload_2
// 8: ifnonnull +66 -> 74
// 11: new 352 javax/crypto/spec/SecretKeySpec
// 14: dup
// 15: new 142 java/lang/StringBuilder
// 18: dup
// 19: invokespecial 143 java/lang/StringBuilder:<init> ()V
// 22: aload_0
// 23: getfield 267 twitter4j/auth/OAuthAuthorization:consumerSecret Ljava/lang/String;
// 26: invokestatic 195 twitter4j/internal/http/HttpParameter:encode (Ljava/lang/String;)Ljava/lang/String;
// 29: invokevirtual 147 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 32: ldc 161
// 34: invokevirtual 147 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 37: invokevirtual 153 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 40: invokevirtual 356 java/lang/String:getBytes ()[B
// 43: ldc 14
// 45: invokespecial 359 javax/crypto/spec/SecretKeySpec:<init> ([BLjava/lang/String;)V
// 48: astore 6
// 50: aload 5
// 52: aload 6
// 54: invokevirtual 363 javax/crypto/Mac:init (Ljava/security/Key;)V
// 57: aload 5
// 59: aload_1
// 60: invokevirtual 356 java/lang/String:getBytes ()[B
// 63: invokevirtual 367 javax/crypto/Mac:doFinal ([B)[B
// 66: astore 7
// 68: aload 7
// 70: invokestatic 372 twitter4j/internal/http/BASE64Encoder:encode ([B)Ljava/lang/String;
// 73: areturn
// 74: aload_2
// 75: invokevirtual 376 twitter4j/auth/OAuthToken:getSecretKeySpec ()Ljavax/crypto/spec/SecretKeySpec;
// 78: astore 6
// 80: aload 6
// 82: ifnonnull -32 -> 50
// 85: new 352 javax/crypto/spec/SecretKeySpec
// 88: dup
// 89: new 142 java/lang/StringBuilder
// 92: dup
// 93: invokespecial 143 java/lang/StringBuilder:<init> ()V
// 96: aload_0
// 97: getfield 267 twitter4j/auth/OAuthAuthorization:consumerSecret Ljava/lang/String;
// 100: invokestatic 195 twitter4j/internal/http/HttpParameter:encode (Ljava/lang/String;)Ljava/lang/String;
// 103: invokevirtual 147 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 106: ldc 161
// 108: invokevirtual 147 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 111: aload_2
// 112: invokevirtual 379 twitter4j/auth/OAuthToken:getTokenSecret ()Ljava/lang/String;
// 115: invokestatic 195 twitter4j/internal/http/HttpParameter:encode (Ljava/lang/String;)Ljava/lang/String;
// 118: invokevirtual 147 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 121: invokevirtual 153 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 124: invokevirtual 356 java/lang/String:getBytes ()[B
// 127: ldc 14
// 129: invokespecial 359 javax/crypto/spec/SecretKeySpec:<init> ([BLjava/lang/String;)V
// 132: astore 6
// 134: aload_2
// 135: aload 6
// 137: invokevirtual 383 twitter4j/auth/OAuthToken:setSecretKeySpec (Ljavax/crypto/spec/SecretKeySpec;)V
// 140: goto -90 -> 50
// 143: astore 4
// 145: getstatic 55 twitter4j/auth/OAuthAuthorization:logger Ltwitter4j/internal/logging/Logger;
// 148: ldc_w 385
// 151: aload 4
// 153: invokevirtual 389 twitter4j/internal/logging/Logger:error (Ljava/lang/String;Ljava/lang/Throwable;)V
// 156: new 391 java/lang/AssertionError
// 159: dup
// 160: aload 4
// 162: invokespecial 394 java/lang/AssertionError:<init> (Ljava/lang/Object;)V
// 165: athrow
// 166: astore_3
// 167: getstatic 55 twitter4j/auth/OAuthAuthorization:logger Ltwitter4j/internal/logging/Logger;
// 170: ldc_w 396
// 173: aload_3
// 174: invokevirtual 389 twitter4j/internal/logging/Logger:error (Ljava/lang/String;Ljava/lang/Throwable;)V
// 177: new 391 java/lang/AssertionError
// 180: dup
// 181: aload_3
// 182: invokespecial 394 java/lang/AssertionError:<init> (Ljava/lang/Object;)V
// 185: athrow
// Local variable table:
// start length slot name signature
// 0 186 0 this OAuthAuthorization
// 0 186 1 paramString String
// 0 186 2 paramOAuthToken OAuthToken
// 166 16 3 localNoSuchAlgorithmException java.security.NoSuchAlgorithmException
// 143 18 4 localInvalidKeyException java.security.InvalidKeyException
// 5 53 5 localMac javax.crypto.Mac
// 48 88 6 localSecretKeySpec javax.crypto.spec.SecretKeySpec
// 66 3 7 arrayOfByte byte[]
// Exception table:
// from to target type
// 0 68 143 java/security/InvalidKeyException
// 74 140 143 java/security/InvalidKeyException
// 0 68 166 java/security/NoSuchAlgorithmException
// 74 140 166 java/security/NoSuchAlgorithmException
}Example 2
| Project: assertj-core-master File: AbstractAssert.java View source code |
/**
* Utility method to ease writing custom assertions classes using {@link String#format(String, Object...)} specifiers
* in error message.
* <p>
* Moreover, this method honors any description set with {@link #as(String, Object...)} or overridden error message
* defined by the user with {@link #overridingErrorMessage(String, Object...)}.
* <p>
* Example :
* <pre><code class='java'> public TolkienCharacterAssert hasName(String name) {
* // check that actual TolkienCharacter we want to make assertions on is not null.
* isNotNull();
*
* // check condition
* if (!actual.getName().equals(name)) {
* failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName());
* }
*
* // return the current assertion for method chaining
* return this;
* }</code></pre>
*
* @param errorMessage the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
*/
protected void failWithMessage(String errorMessage, Object... arguments) {
AssertionError assertionError = Failures.instance().failureIfErrorMessageIsOverridden(info);
if (assertionError == null) {
// error message was not overridden, build it.
String description = MessageFormatter.instance().format(info.description(), info.representation(), "");
assertionError = new AssertionError(description + String.format(errorMessage, arguments));
}
Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(assertionError);
throw assertionError;
}Example 3
| Project: play21-frames-orientdb-plugin-master File: BlueprintsKeyIndexTest.java View source code |
@Test
public void test_with_createKeyIndex() throws Exception {
final OrientGraph graph = new OrientGraph("memory:temp");
try {
/* create key index */
graph.createKeyIndex(KEY_NAME, Vertex.class);
/* create the root vertex */
{
final Vertex v = graph.addVertex(null);
v.setProperty(KEY_NAME, ROOT_NODE_NAME);
/* as key index */
graph.commit();
final Object rootVertexId = v.getId();
assertNotNull(rootVertexId);
}
/* get rootNode */
final List<Vertex> rootNodes = toArrayList(graph.getVertices(KEY_NAME, ROOT_NODE_NAME));
// ########## java.lang.AssertionError: expected:<1> but was:<0>
assertEquals(1, rootNodes.size());
} finally {
graph.shutdown();
}
}Example 4
| Project: cs282-master File: DownloadServiceTestLogger.java View source code |
/** * Accomodating methods available in JUnit4 * <p> * Asserts that two byte arrays are equal. If they are not, an * java.lang.AssertionError is thrown. * <p> * * @param message * the identifying message for the java.lang.AssertionError * @param expecteds * byte array with expected values. * @param actuals * byte array with actual values */ public static void assertArrayEquals(String message, byte[] expected, byte[] actuals) throws AssertionError { if (expected == actuals) return; if (Arrays.equals(expected, actuals)) { return; } final StringBuilder sb = new StringBuilder(message); sb.append('\n').append(" expected={").append(Arrays.toString(expected)).append("}"); sb.append('\n').append(" actuals={").append(Arrays.toString(actuals)).append("}"); throw new AssertionError(sb.toString()); }
Example 5
| Project: detective-master File: SimpleStoryRunner.java View source code |
private void runAsNormal(final Scenario scenario, Parameters parameterForWholeScenario, Step step, Closure<?> expectClosure) {
Parameters dataToPassIntoExpectClosure = parameterForWholeScenario;
ExpectClosureDelegate delegate = new ExpectClosureDelegate(dataToPassIntoExpectClosure);
expectClosure.setDelegate(delegate);
//expectClosure.setResolveStrategy(Closure.DELEGATE_ONLY);
expectClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
try {
//GroovyCategorySupport.use(ExpectObjectWrapper.class, scenario.getOutcomes().getExpectClosure());
expectClosure.call();
} catch (WrongPropertyNameInDslException e) {
StringBuilder sb = new StringBuilder(e.getPropertyName());
sb.append(" not able to found in properties list, do you mean : ").append(StringUtils.getBestMatch(e.getPropertyName(), dataToPassIntoExpectClosure.keySet()).or("notAbleToFoundBestMatchProperties")).append("\nthe avaiable properties we got:").append(dataToPassIntoExpectClosure.keySet()).append("\nHere is the properties and the values for your reference:\n").append(dataToPassIntoExpectClosure.toString());
throw new DslException(sb.toString(), e);
} catch (java.lang.AssertionError e) {
SubsetAssertError subsetError = Utils.findCauseBy(e, SubsetAssertError.class);
if (subsetError != null) {
Detective.logUserMessage(parameterForWholeScenario, subsetError.getMessage());
Detective.logUserMessage(parameterForWholeScenario, subsetError.getFullTableStrVersion());
Detective.logUserMessage(parameterForWholeScenario, subsetError.getSubsetTableStrVersion());
}
throw new detective.core.AssertionError(scenario.getStory(), scenario, step, e);
} catch (groovy.lang.MissingPropertyException e) {
throw new DslException(e.getMessage() + ". Please note we have a know ambiguousness for parent child relationship, for example login.username is a valid identifier for us, but when you add login.username.lastname, we have no idea it is going to access a property from identifier login.username or it is a new identifier.", e);
}
//this.updateSharedData(scenario, dataToPassIntoExpectClosure);
}Example 6
| Project: jslint4java-master File: JUnitXmlFormatter.java View source code |
public String format(JSLintResult result) {
// TODO use a proper serializer
StringBuilder sb = new StringBuilder("<testsuite");
List<Issue> issues = result.getIssues();
String testFailures = issues.isEmpty() ? "0" : "1";
sb.append(attr("failures", testFailures));
sb.append(attr("time", formatTimeAsSeconds(result.getDuration())));
sb.append(attr("skipped", "0"));
sb.append(attr("errors", testFailures));
sb.append(attr("tests", "1"));
sb.append(attr("name", result.getName()));
sb.append(">");
sb.append("<testcase");
sb.append(attr("time", formatTimeAsSeconds(result.getDuration())));
sb.append(attr("classname", TEST_CLASSNAME));
sb.append(attr("name", result.getName()));
sb.append(">");
if (!issues.isEmpty()) {
sb.append("<failure");
String msg = String.format("Found %d problem%s", issues.size(), s(issues.size()));
sb.append(attr("message", msg));
sb.append(attr("type", AssertionError.class.getName()));
sb.append(">");
for (Issue issue : issues) {
sb.append(escape(issue.toString()));
sb.append(System.getProperty("line.separator"));
}
sb.append("</failure>");
}
sb.append("</testcase>");
sb.append("</testsuite>");
return sb.toString();
}Example 7
| Project: fitNevis-master File: JUnitXMLTestListener.java View source code |
public void recordTestResult(String testName, TestSummary result, long executionTime) throws IOException {
int errors = 0;
int failures = 0;
String failureXml = "";
if (result.exceptions + result.wrong > 0) {
failureXml = "<failure type=\"java.lang.AssertionError\" message=\"" + " exceptions: " + result.exceptions + " wrong: " + result.wrong + "\"></failure>";
if (result.exceptions > 0)
errors = 1;
else
failures = 1;
}
String resultXml = "<testsuite errors=\"" + errors + "\" skipped=\"0\" tests=\"1\" time=\"" + executionTime / 1000d + "\" failures=\"" + failures + "\" name=\"" + testName + "\">" + "<properties></properties>" + "<testcase classname=\"" + testName + "\" time=\"" + executionTime / 1000d + "\" name=\"" + testName + "\">" + failureXml + "</testcase>" + "</testsuite>";
String finalPath = new File(outputPath, "TEST-" + testName + ".xml").getAbsolutePath();
FileWriter fw = new FileWriter(finalPath);
fw.write(resultXml);
fw.close();
}Example 8
| Project: jayhorn-master File: AssertionReconstruction.java View source code |
/** @formatter:off * Look for parts of the body that have been created from Java assert * statements. These are always of the form: * * $z0 = <Assert: boolean $assertionsDisabled>; * if $z0 != 0 goto label1; * [[some statements]] * if [[some condition]] goto label1; * $r1 = new java.lang.AssertionError; * specialinvoke $r1.<java.lang.AssertionError: * void <init>()>(); * throw $r1; * * and replace those blocks by: * [[some statements]] * $assert_condition = [[some condition]]; * staticinvoke <JayHornAssertions: void * super_crazy_assertion(boolean[])>($assert_condition); * * @param body */ public void reconstructJavaAssertions(Body body) { Set<Unit> unitsToRemove = new HashSet<Unit>(); Map<Unit, Value> assertionsToInsert = new HashMap<Unit, Value>(); Map<Unit, Unit> postAssertionGotos = new HashMap<Unit, Unit>(); //This is a hack to ensure that the generated assertions //have a nice line number. The actual assertion in the byte code //is always off by one. Map<Unit, Unit> assertionToLineNumberUnit = new HashMap<Unit, Unit>(); // body.getUnits().insertAfter(toInsert, point); Iterator<Unit> iterator = body.getUnits().iterator(); while (iterator.hasNext()) { Unit u = iterator.next(); if (isSootAssertionFlag(u)) { // u := $z0 = <Assert: boolean $assertionsDisabled>; //This has also the line number tag that we want for the assert //statement! Anything after that is off by one. unitsToRemove.add(u); Unit unitWithInterestingLineNumber = u; // u := if $z0 != 0 goto label1; u = iterator.next(); if (!(u instanceof IfStmt)) { throw new RuntimeException(""); } //remember where to go if the assertion holds. // Unit postAssertionStatement = ((IfStmt)u).getTarget(); unitsToRemove.add(u); // Unit lastAssertion = null; while (iterator.hasNext()) { u = iterator.next(); if (isNewJavaAssertionError(u)) { //make an assert false // u := $r1 = new java.lang.AssertionError; unitsToRemove.add(u); assertionsToInsert.put(u, IntConstant.v(0)); assertionToLineNumberUnit.put(u, unitWithInterestingLineNumber); // } break; } // previousUnit = u; } //we have to skip. if (!iterator.hasNext()) { /* Only observed that for cases of trivial asserts. * See issue #84: * assert(cond || true); */ break; } u = iterator.next(); while (!(u instanceof InvokeStmt) || !((InvokeStmt) u).getInvokeExpr().getMethod().getSignature().contains("java.lang.AssertionError: void <init>")) { if (!iterator.hasNext()) { throw new RuntimeException("Assertion reconstruction failed"); } u = iterator.next(); } unitsToRemove.add(u); // u := throw $r1; u = iterator.next(); if (!(u instanceof ThrowStmt)) { throw new RuntimeException(u.toString()); } unitsToRemove.add(u); continue; } } Local assertionLocal = null; if (!assertionsToInsert.isEmpty()) { assertionLocal = Jimple.v().newLocal("$assert_" + (body.getLocals().size()), BooleanType.v()); body.getLocals().add(assertionLocal); } // generated from the assertions. for (Entry<Unit, Value> entry : assertionsToInsert.entrySet()) { List<Unit> unitsToInsert = new LinkedList<Unit>(); unitsToInsert.add(this.assignStmtFor(assertionLocal, entry.getValue(), assertionToLineNumberUnit.get(entry.getKey()))); unitsToInsert.add(SootTranslationHelpers.v().makeAssertion(assertionLocal, assertionToLineNumberUnit.get(entry.getKey()))); if (postAssertionGotos.containsKey(entry.getKey())) { //go to the proper successor if the assertion passes. unitsToInsert.add(this.gotoStmtFor(postAssertionGotos.get(entry.getKey()), entry.getKey())); } body.getUnits().insertBefore(unitsToInsert, entry.getKey()); unitsToRemove.add(entry.getKey()); } body.getUnits().removeAll(unitsToRemove); body.validate(); }
Example 9
| Project: protobuf-el-master File: ServiceWithNoOuter.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.foo(controller, (protobuf_unittest.MessageWithNoOuter) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 10
| Project: GDSC-SMLM-master File: PrecisionTest.java View source code |
@Test(expected = java.lang.AssertionError.class) public void circularFunctionsPrecisionIsNot3sfAtLargeXY() { int maxx = this.maxx; try { for (; ; ) { maxx *= 2; System.out.printf("maxx = %d\n", maxx); functionsComputeSameValue(maxx, new SingleCircularGaussian(maxx), new DoubleCircularGaussian(maxx), 1e-3); } } catch (AssertionError e) { System.out.println(e.getMessage()); throw e; } }
Example 11
| Project: sosies-generator-master File: JsonAdapterAnnotationOnFieldsTest.java View source code |
@Test(timeout = 1000)
public void testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter_add1168() {
fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testFieldAnnotationTakesPrecedenceOverRegisteredTypeAdapter_add1168");
Gson gson = new GsonBuilder().registerTypeAdapter(Part.class, new TypeAdapter<Part>() {
@Override
public void write(JsonWriter out, Part part) throws IOException {
throw new java.lang.AssertionError();
}
@Override
public Part read(JsonReader in) throws IOException {
throw new java.lang.AssertionError();
}
}).create();
String json = gson.toJson(new Gadget(new Part("screen")));
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1687, json);
Gadget gadget = gson.fromJson("{\'part\':\'screen\'}", Gadget.class);
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1688, gadget.part.name);
fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}Example 12
| Project: Jnario-master File: UsingTablesSpec.java View source code |
/**
* `ExampleTable#forEach` executes the passed in procedure for all table rows.
* It will generate an error message for all procedures that have failed with the reason why they failed.
*/
@Test
@Named("Error message")
@Order(7)
public void _errorMessage() throws Exception {
final Procedure1<Boolean> _function = new Procedure1<Boolean>() {
public void apply(final Boolean it) {
final Procedure1<UsingTablesSpecExample> _function = new Procedure1<UsingTablesSpecExample>() {
public void apply(final UsingTablesSpecExample it) {
int _value1 = it.getValue1();
int _value2 = it.getValue2();
int _plus = (_value1 + _value2);
int _sum = it.getSum();
Assert.assertTrue("\nExpected value1 + value2 => sum but" + "\n value1 + value2 is " + new org.hamcrest.StringDescription().appendValue(Integer.valueOf(_plus)).toString() + "\n value1 is " + new org.hamcrest.StringDescription().appendValue(_value1).toString() + "\n value2 is " + new org.hamcrest.StringDescription().appendValue(_value2).toString() + "\n sum is " + new org.hamcrest.StringDescription().appendValue(Integer.valueOf(_sum)).toString() + "\n", Should.<Integer>operator_doubleArrow(Integer.valueOf(_plus), Integer.valueOf(_sum)));
}
};
ExampleTableIterators.<UsingTablesSpecExample>forEach(UsingTablesSpec.this.example, _function);
}
};
String _errorMessage = Helpers.errorMessage(_function);
StringConcatenation _builder = new StringConcatenation();
_builder.append("example failed");
_builder.newLine();
_builder.newLine();
_builder.append(" ");
_builder.append("| value1 | value2 | sum |");
_builder.newLine();
_builder.append(" ");
_builder.append("| 1 | 2 | 3 | ✓");
_builder.newLine();
_builder.append(" ");
_builder.append("| 4 | 5 | 7 | ✘ (1)");
_builder.newLine();
_builder.append(" ");
_builder.append("| 7 | 8 | 14 | ✘ (2)");
_builder.newLine();
_builder.newLine();
_builder.append("(1) | 4 | 5 | 7 | ✘");
_builder.newLine();
_builder.append("java.lang.AssertionError: ");
_builder.newLine();
_builder.append("Expected value1 + value2 => sum but");
_builder.newLine();
_builder.append(" ");
_builder.append("value1 + value2 is <9>");
_builder.newLine();
_builder.append(" ");
_builder.append("value1 is <4>");
_builder.newLine();
_builder.append(" ");
_builder.append("value2 is <5>");
_builder.newLine();
_builder.append(" ");
_builder.append("sum is <7>");
_builder.newLine();
_builder.newLine();
_builder.append("(2) | 7 | 8 | 14 | ✘");
_builder.newLine();
_builder.append("java.lang.AssertionError: ");
_builder.newLine();
_builder.append("Expected value1 + value2 => sum but");
_builder.newLine();
_builder.append(" ");
_builder.append("value1 + value2 is <15>");
_builder.newLine();
_builder.append(" ");
_builder.append("value1 is <7>");
_builder.newLine();
_builder.append(" ");
_builder.append("value2 is <8>");
_builder.newLine();
_builder.append(" ");
_builder.append("sum is <14>");
Helpers.is(_errorMessage, _builder);
}Example 13
| Project: bridlensis-master File: HTMLConvert.java View source code |
private static void markdownToHtml(String markdownFile, BufferedWriter output) throws IOException, UnsupportedEncodingException, FileNotFoundException, AssertionError {
try (InputStreamReader input = openMarkdownSourceFile(markdownFile)) {
Markdown4jProcessor processor = new Markdown4jProcessor().registerPlugins(new BuiltinVariablesPlugin(), new ReservedWordsPlugin(), new FunctionsPlugin(), new VersionPlugin(), new UsagePlugin());
output.write(processor.process(input));
}
}Example 14
| Project: C4J-master File: TryExpTest.java View source code |
@Test
public void testAddMultipleCatch() {
TryExp exp = new TryExp(new IfExp(BooleanExp.TRUE));
exp.addCatch(AssertionError.class, new IfExp(BooleanExp.TRUE));
exp.addCatch(Throwable.class, new IfExp(BooleanExp.TRUE));
assertEquals("\ntry {\nif (true) {\n}\n} catch (java.lang.AssertionError e1) {\nif (true) {\n}\n} catch (java.lang.Throwable e2) {\nif (true) {\n}\n}", exp.getCode());
}Example 15
| Project: nexus-core-master File: Nexus4066TaskMutualExclusionIT.java View source code |
@Test(dataProvider = "data")
public void run(String repo1, String repo2, boolean shouldWait) throws Exception {
try {
ScheduledServiceListResource task1 = createTask(repo1);
assertThat(task1.getStatus(), equalTo(TaskState.RUNNING.name()));
ScheduledServiceListResource task2 = createTask(repo2);
if (shouldWait) {
assertThat(task2.getStatus(), equalTo(TaskState.SLEEPING.name()));
} else {
assertThat(task2.getStatus(), equalTo(TaskState.RUNNING.name()));
}
} catch (java.lang.AssertionError e) {
throw new RuntimeException("Repo1: " + repo1 + " repo2: " + repo2 + " shouldWait: " + shouldWait, e);
}
}Example 16
| Project: redsniff-master File: AlertsErrorPageTest.java View source code |
@Test
public void complainsAndShowsErrorPageStackTraceWhenErrorPageFoundWhileLookingForSomethingElse() {
thrown.expectMessage("While expecting: a div that has name \"some-expected-div\"\n" + "Got wicket error page:");
thrown.expectMessage("WicketMessage: Can't instantiate page using constructor public jhc.webapps.figaro.test.utils.TestPage()\n" + "Root cause:\n" + "java.lang.AssertionError: jhc.webapps.figaro.FigaroWebException");
t.assertPresenceOf(div().that(hasName("some-expected-div")));
}Example 17
| Project: geowave-master File: AggregationProtos.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.aggregate(controller, (mil.nga.giat.geowave.datastore.hbase.query.generated.AggregationProtos.AggregationRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 18
| Project: hbase-cache-master File: MasterMonitorProtos.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.getSchemaAlterStatus(controller, (org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetSchemaAlterStatusRequest) request);
case 1:
return impl.getTableDescriptors(controller, (org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest) request);
case 2:
return impl.getClusterStatus(controller, (org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetClusterStatusRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 19
| Project: jitwatch-master File: TestIntrinsicFinder.java View source code |
@Test
public void testRegressionIntrinsicFinderCallTagChangesContext() {
String[] logLines = new String[] { "<task_queued compile_id='1564' method='java/util/TimSort mergeLo (IIII)V' bytes='55' count='520' backedge_count='5000' iicount='520' stamp='0.083' comment='count' hot_count='520'/>", "<nmethod compile_id='1564' compiler='C2' entry='0x000000010744c060' size='1256' address='0x000000010744bf10' relocation_offset='296' insts_offset='336' stub_offset='688' scopes_data_offset='720' scopes_pcs_offset='832' dependencies_offset='1232' nul_chk_table_offset='1240' method='java/util/TimSort mergeLo (IIII)V' bytes='55' count='546' backedge_count='5389' iicount='546' stamp='0.105'/>", "<task compile_id='1564' method='java/util/TimSort mergeLo (IIII)V' bytes='655' count='84' backedge_count='5110' iicount='88' stamp='22.534'>", "<phase name='parse' nodes='3' live='3' stamp='22.534'>", "<type id='636' name='void'/>", "<type id='634' name='int'/>", "<klass id='729' name='java/util/TimSort' flags='0'/>", "<method id='730' holder='729' name='mergeLo' return='636' arguments='634 634 634 634' flags='2' bytes='655' iicount='88'/>", "<klass id='741' name='java/lang/AssertionError' flags='1'/>", "<uncommon_trap method='730' bci='634' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='730' bci='615' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<klass id='742' name='java/lang/IllegalArgumentException' flags='1'/>", "<uncommon_trap method='730' bci='594' reason='unloaded' action='reinterpret' index='84' klass='742'/>", "<uncommon_trap method='730' bci='553' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='730' bci='285' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='730' bci='165' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='730' bci='22' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<parse method='730' uses='88' stamp='22.534'>", "<bc code='154' bci='3'/>", "<branch target_bci='30' taken='47' not_taken='0' cnt='47' prob='always'/>", "<bc code='183' bci='38'/>", "<klass id='734' name='[Ljava/lang/Object;' flags='1041'/>", "<method id='735' holder='729' name='ensureCapacity' return='734' arguments='634' flags='2' bytes='85' iicount='229'/>", "<call method='735' count='47' prof_factor='1' inline='1'/>", "<inline_fail reason='too big'/>", "<direct_call bci='38'/>", "<bc code='184' bci='50'/>", "<klass id='645' name='java/lang/Object' flags='1'/>", "<klass id='651' name='java/lang/System' flags='17'/>", "<method id='736' holder='651' name='arraycopy' return='636' arguments='645 634 645 634 634' flags='265' bytes='0' compile_id='25' compile_kind='c2n' iicount='10000'/>", "<call method='736' count='47' prof_factor='1' inline='1'/>", "<uncommon_trap bci='50' reason='null_check' action='maybe_recompile'/>", "<uncommon_trap bci='50' reason='null_check' action='maybe_recompile'/>", "<intrinsic id='_arraycopy' nodes='169'/>", "<bc code='50' bci='76'/>", "<uncommon_trap bci='76' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='77'/>", "<uncommon_trap bci='77' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='77' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='154' bci='83'/>", "<branch target_bci='99' taken='47' not_taken='0' cnt='47' prob='always'/>", "<bc code='184' bci='95'/>", "<call method='736' count='0' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='149'/>", "<bc code='160' bci='101'/>", "<branch target_bci='131' taken='47' not_taken='0' cnt='47' prob='always'/>", "<bc code='184' bci='114'/>", "<call method='736' count='0' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='99'/>", "<bc code='50' bci='128'/>", "<uncommon_trap bci='128' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='129'/>", "<uncommon_trap bci='129' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='129' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<uncommon_trap bci='149' reason='predicate' action='maybe_recompile'/>", "<uncommon_trap bci='149' reason='loop_limit_check' action='maybe_recompile'/>", "<bc code='154' bci='152'/>", "<branch target_bci='173' taken='7120' not_taken='0' cnt='7120' prob='always'/>", "<bc code='50' bci='179'/>", "<uncommon_trap bci='179' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='50' bci='184'/>", "<uncommon_trap bci='184' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='185' bci='185'/>", "<klass id='733' name='org/eclipse/dltk/internal/core/index2/SourceModulesRequest$1' flags='0'/>", "<klass id='737' name='java/util/Comparator' flags='1537'/>", "<method id='738' holder='737' name='compare' return='634' arguments='645 645' flags='1025' bytes='0' iicount='1'/>", "<call method='738' count='7120' prof_factor='1' virtual='1' inline='1' receiver='733' receiver_count='7120'/>", "<method id='746' holder='733' name='compare' return='634' arguments='645 645' flags='4161' bytes='13' compile_id='1562' compiler='C2' iicount='17524'/>", "<call method='746' count='7120' prof_factor='1' inline='1'/>", "<inline_fail reason='already compiled into a big method'/>", "<predicted_call bci='185' klass='733'/>", "<uncommon_trap bci='185' reason='null_check' action='maybe_recompile'/>", "<uncommon_trap bci='185' reason='class_check' action='maybe_recompile' comment='monomorphic vcall checkcast'/>", "<direct_call bci='185'/>", "<bc code='156' bci='190'/>", "<branch target_bci='226' taken='3554' not_taken='3565' cnt='7119' prob='0.499227'/>", "<bc code='50' bci='207'/>", "<uncommon_trap bci='207' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='208'/>", "<uncommon_trap bci='208' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='208' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='154' bci='220'/>", "<branch target_bci='259' taken='3547' not_taken='18' cnt='3565' prob='0.994951'/>", "<bc code='50' bci='240'/>", "<uncommon_trap bci='240' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='241'/>", "<uncommon_trap bci='241' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='241' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='160' bci='253'/>", "<branch target_bci='259' taken='3525' not_taken='29' cnt='3554' prob='0.99184'/>", "<bc code='161' bci='266'/>", "<branch target_bci='149' taken='7072' not_taken='0' cnt='7072' prob='always'/>", "<uncommon_trap bci='269' reason='predicate' action='maybe_recompile'/>", "<uncommon_trap bci='269' reason='loop_limit_check' action='maybe_recompile'/>", "<bc code='154' bci='272'/>", "<branch target_bci='293' taken='0' not_taken='0'/>", "<bc code='50' bci='297'/>", "<uncommon_trap bci='297' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='184' bci='306'/>", "<method id='739' holder='729' name='gallopRight' return='634' arguments='645 734 634 634 634 737' flags='10' bytes='335' iicount='262'/>", "<call method='739' count='0' prof_factor='1' inline='1'/>", "<uncommon_trap method='739' bci='324' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='739' bci='248' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='739' bci='21' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<inline_fail reason='too big'/>", "<direct_call bci='306'/>", "<bc code='153' bci='313'/>", "<branch target_bci='356' taken='0' not_taken='0'/>", "<bc code='184' bci='326'/>", "<call method='736' count='0' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='147'/>", "<bc code='163' bci='350'/>", "<branch target_bci='356' taken='0' not_taken='0'/>", "<bc code='50' bci='370'/>", "<uncommon_trap bci='370' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='371'/>", "<uncommon_trap bci='371' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='371' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='154' bci='377'/>", "<branch target_bci='383' taken='0' not_taken='0'/>", "<bc code='50' bci='387'/>", "<uncommon_trap bci='387' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='184' bci='397'/>", "<method id='740' holder='729' name='gallopLeft' return='634' arguments='645 734 634 634 634 737' flags='10' bytes='335' iicount='255'/>", "<call method='740' count='0' prof_factor='1' inline='1'/>", "<uncommon_trap method='740' bci='324' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='740' bci='248' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='740' bci='21' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='740' bci='248' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<uncommon_trap method='740' bci='324' reason='unloaded' action='reinterpret' index='82' klass='741'/>", "<inline_fail reason='too big'/>", "<direct_call bci='397'/>", "<bc code='153' bci='404'/>", "<branch target_bci='449' taken='0' not_taken='0'/>", "<bc code='184' bci='417'/>", "<call method='736' count='0' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='97'/>", "<bc code='154' bci='443'/>", "<branch target_bci='449' taken='0' not_taken='0'/>", "<bc code='50' bci='463'/>", "<uncommon_trap bci='463' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='464'/>", "<uncommon_trap bci='464' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='464' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='160' bci='470'/>", "<branch target_bci='476' taken='0' not_taken='0'/>", "<bc code='162' bci='525'/>", "<branch target_bci='532' taken='47' not_taken='0' cnt='47' prob='always'/>", "<bc code='160' bci='539'/>", "<branch target_bci='590' taken='18' not_taken='29' cnt='47' prob='0.382979'/>", "<bc code='154' bci='545'/>", "<branch target_bci='561' taken='29' not_taken='0'/>", "<bc code='184' bci='571'/>", "<call method='736' count='29' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='83'/>", "<bc code='50' bci='585'/>", "<uncommon_trap bci='585' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<bc code='83' bci='586'/>", "<uncommon_trap bci='586' reason='range_check' action='make_not_entrant' comment='range_check'/>", "<uncommon_trap bci='586' reason='array_check' action='maybe_recompile' klass='734'/>", "<cast_up reason='monomorphic_array' from='734' to='(exact)'/>", "<bc code='154' bci='591'/>", "<branch target_bci='604' taken='18' not_taken='0'/>", "<bc code='187' bci='594'/>", "<uncommon_trap bci='594' reason='unloaded' action='reinterpret' index='84'/>", "<bc code='154' bci='607'/>", "<branch target_bci='623' taken='18' not_taken='0'/>", "<bc code='154' bci='626'/>", "<branch target_bci='642' taken='18' not_taken='0'/>", "<bc code='184' bci='651'/>", "<call method='736' count='18' prof_factor='1' inline='1'/>", "<intrinsic id='_arraycopy' nodes='147'/>", "<bc code='161' bci='483'/>", "<branch target_bci='490' taken='0' not_taken='0'/>", "<bc code='161' bci='495'/>", "<branch target_bci='502' taken='0' not_taken='0'/>", "<bc code='154' bci='504'/>", "<branch target_bci='269' taken='0' not_taken='0'/>", "<bc code='156' bci='509'/>", "<branch target_bci='515' taken='0' not_taken='0'/>", "<parse_done nodes='1981' live='1944' memory='416408' stamp='22.536'/>", "</parse>", "<phase_done name='parse' nodes='1983' live='1267' stamp='22.536'/>", "</phase>", "<phase name='optimizer' nodes='1983' live='1267' stamp='22.536'>", "<phase name='idealLoop' nodes='2072' live='1224' stamp='22.537'>", "<loop_tree>", "<loop idx='2085' >", "<loop idx='2098' inner_loop='1' >", "</loop>", "<loop idx='2099' inner_loop='1' >", "</loop>", "</loop>", "</loop_tree>", "<phase_done name='idealLoop' nodes='2148' live='1185' stamp='22.538'/>", "</phase>", "<phase name='idealLoop' nodes='2148' live='1185' stamp='22.538'>", "<loop_tree>", "<loop idx='2085' >", "<loop idx='2098' inner_loop='1' >", "</loop>", "<loop idx='2099' inner_loop='1' >", "</loop>", "</loop>", "</loop_tree>", "<phase_done name='idealLoop' nodes='2148' live='1185' stamp='22.538'/>", "</phase>", "<phase name='idealLoop' nodes='2148' live='1185' stamp='22.538'>", "<loop_tree>", "<loop idx='2085' >", "<loop idx='2098' inner_loop='1' >", "</loop>", "<loop idx='2099' inner_loop='1' >", "</loop>", "</loop>", "</loop_tree>", "<phase_done name='idealLoop' nodes='2148' live='1185' stamp='22.539'/>", "</phase>", "<phase name='ccp' nodes='2148' live='1185' stamp='22.539'>", "<phase_done name='ccp' nodes='2148' live='1185' stamp='22.539'/>", "</phase>", "<phase name='idealLoop' nodes='2155' live='1184' stamp='22.539'>", "<loop_tree>", "<loop idx='2085' >", "<loop idx='2098' inner_loop='1' >", "</loop>", "<loop idx='2099' inner_loop='1' >", "</loop>", "</loop>", "</loop_tree>", "<phase_done name='idealLoop' nodes='2167' live='1148' stamp='22.540'/>", "</phase>", "<phase name='idealLoop' nodes='2167' live='1148' stamp='22.540'>", "<loop_tree>", "<loop idx='2085' >", "<loop idx='2098' inner_loop='1' >", "</loop>", "<loop idx='2099' inner_loop='1' >", "</loop>", "</loop>", "</loop_tree>", "<phase_done name='idealLoop' nodes='2179' live='1148' stamp='22.541'/>", "</phase>", "<phase_done name='optimizer' nodes='2206' live='1155' stamp='22.541'/>", "</phase>", "<phase name='matcher' nodes='2206' live='1155' stamp='22.541'>", "<phase_done name='matcher' nodes='1096' live='1096' stamp='22.542'/>", "</phase>", "<phase name='regalloc' nodes='1481' live='1481' stamp='22.543'>", "<regalloc attempts='2' success='1'/>", "<phase_done name='regalloc' nodes='2635' live='2219' stamp='22.558'/>", "</phase>", "<phase name='output' nodes='2643' live='2227' stamp='22.558'>", "<phase_done name='output' nodes='2701' live='2260' stamp='22.559'/>", "</phase>", "<code_cache total_blobs='2037' nmethods='1386' adapters='603' free_code_cache='45737472' largest_free_block='45650432'/>", "<task_done success='1' nmsize='5136' count='5000' backedge_count='5045' stamp='22.559'/>", "</task>" };
IMetaMember member = UnitTestUtil.createTestMetaMember();
UnitTestUtil.processLogLines(member, logLines);
IntrinsicFinder finder = new IntrinsicFinder();
Map<String, String> intrinsics = finder.findIntrinsics(member);
assertEquals(1, intrinsics.size());
String expectedMethod = "java.lang.System.arraycopy";
assertEquals(true, intrinsics.keySet().contains(expectedMethod));
assertEquals("_arraycopy", intrinsics.get(expectedMethod));
}Example 20
| Project: onos-master File: ImmutableClassChecker.java View source code |
/**
* Assert that the given class adheres to the immutable class rules.
*
* @param clazz the class to check
*
* @throws java.lang.AssertionError if the class is not an
* immutable class
*/
public static void assertThatClassIsImmutable(Class<?> clazz) {
final ImmutableClassChecker checker = new ImmutableClassChecker();
if (!checker.isImmutableClass(clazz, false)) {
final Description toDescription = new StringDescription();
final Description mismatchDescription = new StringDescription();
checker.describeTo(toDescription);
checker.describeMismatch(mismatchDescription);
final String reason = "\n" + "Expected: is \"" + toDescription.toString() + "\"\n" + " but : was \"" + mismatchDescription.toString() + "\"";
throw new AssertionError(reason);
}
}Example 21
| Project: jetty.project-master File: MappedByteBufferPoolTest.java View source code |
/**
* In a scenario where MappedByteBufferPool is being used improperly, such as releasing a buffer that wasn't created/acquired by the MappedByteBufferPool,
* an assertion is tested for.
* @throws Exception test failure
*/
@Test
public void testReleaseAssertion() throws Exception {
int factor = 1024;
MappedByteBufferPool bufferPool = new MappedByteBufferPool(factor);
try {
// Release a few small non-pool buffers
bufferPool.release(ByteBuffer.wrap(StringUtil.getUtf8Bytes("Hello")));
/* NOTES:
*
* 1) This test will pass on command line maven build, as its surefire setup uses "-ea" already.
* 2) In Eclipse, goto the "Run Configuration" for this test case.
* Select the "Arguments" tab, and make sure "-ea" is present in the text box titled "VM arguments"
*/
fail("Expected java.lang.AssertionError, do you have '-ea' JVM command line option enabled?");
} catch (java.lang.AssertionError e) {
}
}Example 22
| Project: eclipse.jdt.ui-master File: TestRunListenerTest4.java View source code |
public void testFail() throws Exception {
String source = "package pack;\n" + "import org.junit.Test;\n" + "import static org.junit.Assert.*;\n" + "public class ATestCase {\n" + " @Test public void testFail() { fail(); }\n" + "}";
IType aTestCase = createType(source, "pack", "ATestCase.java");
String[] expectedSequence = new String[] { "sessionStarted-" + TestRunListeners.sessionAsString("ATestCase", ProgressState.RUNNING, Result.UNDEFINED, 0), "testCaseStarted-" + TestRunListeners.testCaseAsString("testFail", "pack.ATestCase", ProgressState.RUNNING, Result.UNDEFINED, null, 0), "testCaseFinished-" + TestRunListeners.testCaseAsString("testFail", "pack.ATestCase", ProgressState.COMPLETED, Result.FAILURE, new FailureTrace("java.lang.AssertionError", null, null), 0), "sessionFinished-" + TestRunListeners.sessionAsString("ATestCase", ProgressState.COMPLETED, Result.FAILURE, 0) };
String[] actual = runSequenceTest(aTestCase);
assertEqualLog(expectedSequence, actual);
}Example 23
| Project: junit5-master File: FlatPrintingListenerTests.java View source code |
@Test
void executionFinishedWithFailure() {
StringWriter stringWriter = new StringWriter();
listener(stringWriter).executionFinished(newTestIdentifier(), failed(new AssertionError("Boom!")));
String[] lines = lines(stringWriter);
assertAll("lines in the output", () -> assertEquals(//
"Finished: demo-test ([engine:demo-engine])", //
lines[0]), () -> assertEquals(INDENTATION + "=> Exception: java.lang.AssertionError: Boom!", lines[1]));
}Example 24
| Project: jumi-master File: JUnitCompatibilityTest.java View source code |
@Test
public void reports_test_failures() throws Exception {
app.runTestsMatching("glob:sample/JUnitFailingTest.class");
app.checkPassingAndFailingTests(1, 1);
app.checkTotalTestRuns(1);
app.checkContainsRun("JUnitFailingTest", "failing", "/", "/");
app.checkHasStackTrace("java.lang.AssertionError: dummy failure", "at sample.JUnitFailingTest.failing");
}Example 25
| Project: xbnjava-master File: UnitTestAppOutputContainsXmpl.java View source code |
public static final void main(String[] ignored) {
System.out.println("Successful test (no crash)...");
VerifyApplicationOutput.assertWithNoParameters(DisplayOutputToConsole.NO, null, com.github.xbn.examples.testdev.HelloWorld.class, "Hello world");
System.out.println("Failure test... (crashes with an AssertionError)");
VerifyApplicationOutput.assertWithNoParameters(DisplayOutputToConsole.NO, null, com.github.xbn.examples.testdev.HelloWorld.class, "Goodbye, cruel world");
}Example 26
| Project: mtc-master File: FoldingTest.java View source code |
@Test
public void testFoldingBreaksEdgeAccess() {
Hypergraph<String, Integer> hGraph = new SetHypergraph<String, Integer>();
hGraph.addVertex("A");
hGraph.addVertex("B");
hGraph.addVertex("C");
hGraph.addVertex("D");
hGraph.addEdge(1, Arrays.asList("A", "B"));
hGraph.addEdge(2, Arrays.asList("B", "A"));
hGraph.addEdge(3, Arrays.asList("A", "B", "C"));
hGraph.addEdge(4, Arrays.asList("B", "C"));
// This is kind of awkward... if the method accepted a Factory<UndirectedGraph> one could
// just use UndirectedSparseGraph.getFactory()
Graph<String, FoldedEdge<String, Integer>> graph = FoldingTransformerFixed.foldHypergraphEdges(hGraph, UndirectedSparseGraph.<String, FoldedEdge<String, Integer>>getFactory());
// The vertices are copied fine
assertEquals(new HashSet<String>(Arrays.asList("A", "B", "C", "D")), new HashSet<String>(graph.getVertices()));
// The following works file: getting the edges for each of the vertices
assertEquals(3, graph.getEdgeCount());
assertEquals(new HashSet<Integer>(Arrays.asList(1, 2, 3)), new HashSet<Integer>(graph.findEdge("A", "B").getFolded()));
assertEquals(new HashSet<Integer>(Arrays.asList(3)), new HashSet<Integer>(graph.findEdge("A", "C").getFolded()));
assertEquals(new HashSet<Integer>(Arrays.asList(3, 4)), new HashSet<Integer>(graph.findEdge("B", "C").getFolded()));
// But this does not work: java.lang.AssertionError: expected:<<A, B>> but was:<null>
assertEquals(new Pair<String>("A", "B"), graph.getEndpoints(graph.findEdge("A", "B")));
}Example 27
| Project: evosuite-master File: JUnitResultBuilder.java View source code |
/**
* Translates <i>part</i> of the org.junit.runner.Result object
* into an evosuite independent object.
*
* @param result
* @return
*/
public JUnitResult build(Result result) {
boolean wasSuccessful = result.wasSuccessful();
int failureCount = result.getFailureCount();
int runCount = result.getRunCount();
JUnitResult junitResult = new JUnitResult(wasSuccessful, failureCount, runCount);
List<Failure> failures = result.getFailures();
for (Failure failure : failures) {
String descriptionMethodName = failure.getDescription().getMethodName();
String exceptionClassName = failure.getException().getClass().toString();
String message = failure.getMessage();
String trace = failure.getTrace();
boolean isAssertionError = (failure.getException() instanceof java.lang.AssertionError);
JUnitFailure junitFailure = new JUnitFailure(message, exceptionClassName, descriptionMethodName, isAssertionError, trace);
for (StackTraceElement elem : failure.getException().getStackTrace()) {
String elemToString = elem.toString();
junitFailure.addToExceptionStackTrace(elemToString);
}
junitResult.addFailure(junitFailure);
}
return junitResult;
}Example 28
| Project: intellij-community-master File: InstrumentationAdapter.java View source code |
// TODO: add actual value to assertion message
private void addPatternAssertion(String message, boolean isMethod) {
if (myInstrumenter.myInstrumentationType == Configuration.InstrumentationType.ASSERT) {
addThrow("java/lang/AssertionError", "(Ljava/lang/Object;)V", message);
} else if (myInstrumenter.myInstrumentationType == Configuration.InstrumentationType.EXCEPTION) {
if (isMethod) {
addThrow("java/lang/IllegalStateException", "(Ljava/lang/String;)V", message);
} else {
addThrow("java/lang/IllegalArgumentException", "(Ljava/lang/String;)V", message);
}
}
myInstrumenter.myInstrumented = true;
}Example 29
| Project: openpojo-master File: AbstractAffirmationTest.java View source code |
/**
* Test method for
* {@link com.openpojo.validation.affirm.Affirm#affirmEquals(java.lang.String, java.lang.Object, java.lang.Object)}.
*/
@Test
@SuppressWarnings("UnnecessaryBoxing")
public void testAffirmEquals() {
Integer five = new Integer(5);
Integer anotherFive = new Integer(5);
Integer six = new Integer(6);
Affirm.affirmEquals("Affirm.affirmEquals on equal objects failed", five, anotherFive);
try {
Affirm.affirmEquals("Affirm.affirmEquals on non-equal objects should have failed.", five, six);
} catch (AssertionError e) {
return;
}
Assert.fail("Affirm.affirmEquals call on non-equal objects passed!");
}Example 30
| Project: FindBug-for-Domino-Designer-master File: QuestionableBooleanAssignment.java View source code |
@Override
public void sawOpcode(int seen) {
if (seen == GOTO && getBranchOffset() == 4) {
state = SEEN_GOTO;
} else
switch(state) {
case SEEN_NOTHING:
if ((seen == ICONST_1) || (seen == ICONST_0))
state = SEEN_ICONST_0_OR_1;
break;
case SEEN_ICONST_0_OR_1:
if (seen == DUP)
state = SEEN_DUP;
else
state = SEEN_NOTHING;
break;
case SEEN_DUP:
if (((seen >= ISTORE_0) && (seen <= ISTORE_3)) || (seen == ISTORE))
state = SEEN_ISTORE;
else
state = SEEN_NOTHING;
break;
case SEEN_ISTORE:
if (seen == IFEQ || seen == IFNE) {
bug = new BugInstance(this, "QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT", HIGH_PRIORITY).addClassAndMethod(this).addSourceLine(this);
state = SEEN_IF;
} else
state = SEEN_NOTHING;
break;
case SEEN_IF:
state = SEEN_NOTHING;
if (seen == NEW) {
String cName = getClassConstantOperand();
if (cName.equals("java/lang/AssertionError"))
break;
}
bugReporter.reportBug(bug);
break;
case SEEN_GOTO:
state = SEEN_NOTHING;
break;
}
}Example 31
| Project: pitest-master File: SteppedTestUnit.java View source code |
private Throwable updateResultForExpectations(final ClassLoader loader, final Throwable tResult) {
if (this.expected.hasSome()) {
if (tResult == null) {
return new java.lang.AssertionError("Expected exception " + this.expected);
} else if (IsolationUtils.convertForClassLoader(loader, this.expected.value()).isAssignableFrom(tResult.getClass())) {
return null;
}
}
return tResult;
}Example 32
| Project: rabbit-escape-master File: TestCommandLineOption.java View source code |
@Test(expected = java.lang.AssertionError.class) public void Assertion_for_duplicate_short_form() { CommandLineOption test = new CommandLineOption("--test", false); CommandLineOption template = new CommandLineOption("--template", true); String[] args = "-t --template foo.rel".split(" "); // AssertionError here as both --test and --template can be -t. CommandLineOptionSet.parse(args, test, template); }
Example 33
| Project: VCL-Android-master File: VLCApplication.java View source code |
@Override
public void onCreate() {
super.onCreate();
// Are we using advanced debugging - locale?
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
String p = pref.getString("set_locale", "");
if (!p.equals("")) {
Locale locale;
// workaround due to region code
if (p.equals("zh-TW")) {
locale = Locale.TRADITIONAL_CHINESE;
} else if (p.startsWith("zh")) {
locale = Locale.CHINA;
} else if (p.equals("pt-BR")) {
locale = new Locale("pt", "BR");
} else if (p.equals("bn-IN") || p.startsWith("bn")) {
locale = new Locale("bn", "IN");
} else {
/**
* Avoid a crash of
* java.lang.AssertionError: couldn't initialize LocaleData for locale
* if the user enters nonsensical region codes.
*/
if (p.contains("-"))
p = p.substring(0, p.indexOf('-'));
locale = new Locale(p);
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
instance = this;
// Initialize the database soon enough to avoid any race condition and crash
MediaDatabase.getInstance();
// Prepare cache folder constants
AudioUtil.prepareCacheFolder(this);
}Example 34
| Project: doctester-master File: DocTesterTest.java View source code |
@Test
public void testThatAssertionFailureGetsWrittenToDoctesterHtmlFile() throws Exception {
boolean gotTestFailure = false;
try {
sayAndAssertThat("This will go wrong", false, is(true));
} catch (AssertionError assertionError) {
gotTestFailure = true;
}
assertThat(gotTestFailure, is(true));
finishDocTest();
File expectedDoctestfile = new File("target/site/doctester/" + DocTesterTest.EXPECTED_FILENAME);
// this makes sure that the correct alert type is used together
// with proper escaping and replacement of \n values...
assertThatFileContainsText(expectedDoctestfile, "<div class=\"alert alert-danger\">\n" + "java.lang.AssertionError: <br/>Expected: is <true><br/> but: was <false>");
}Example 35
| Project: HotswapAgent-master File: SessionFactoryProxyTest.java View source code |
// @Test
public void testConfig() {
try {
Configuration c = new Configuration();
c.configure("hibernate.cfg.xml");
c.buildSessionFactory();
ReInitializable r = ReInitializable.class.cast(c);
r.hotSwap();
SessionFactory s = c.buildSessionFactory();
Session ss = s.openSession();
Transaction tt = ss.beginTransaction();
Stock stock = new Stock("A", "B");
ss.persist(stock);
stock = new Stock("C", "D");
ss.persist(stock);
stock = new Stock("E", "F");
ss.persist(stock);
tt.commit();
ss.close();
System.err.println("StockId:" + stock.getStockId());
r.getOverrideConfig().configuredBy = ConfiguredBy.STRING;
r.getOverrideConfig().config = "/hibernate2.cfg.xml";
r.hotSwap();
try {
s = c.buildSessionFactory();
ss = s.openSession();
tt = ss.beginTransaction();
stock = new Stock("An", "Bn");
ss.persist(stock);
tt.commit();
ss.close();
fail("Should not reach!");
} catch (AssertionError x) {
throw x;
} catch (MappingException e) {
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 36
| Project: awaitility-master File: AssertionCondition.java View source code |
public ConditionEvaluationResult eval(Duration pollInterval) throws Exception {
try {
supplier.run();
conditionEvaluationHandler.handleConditionResultMatch(getMatchMessage(supplier, settings.getAlias()), null, pollInterval);
return new ConditionEvaluationResult(true);
} catch (AssertionError e) {
lastExceptionMessage = e.getMessage();
conditionEvaluationHandler.handleConditionResultMismatch(getMismatchMessage(supplier, lastExceptionMessage, settings.getAlias()), null, pollInterval);
return new ConditionEvaluationResult(false, null, e);
} catch (Throwable throwable) {
return CheckedExceptionRethrower.safeRethrow(throwable);
}
}Example 37
| Project: prevayler-master File: E105Test.java View source code |
@Test(expected = java.lang.AssertionError.class)
public void testFailing() throws Exception {
// This will update Entity#text outside of a transaction,
// hence the change will NOT be written to the journal and is lost when closing Prevayler.
new AbstractTest() {
@Override
protected void updateEntity(Prevayler<Root> prevayler, Entity entity, String value) throws Exception {
entity.setText(value);
}
}.runTest();
}Example 38
| Project: ISTIC_M2GL-master File: YetiTest.java View source code |
/** Test case automatically generated by YETI **/
@Test
public void test_0() throws Exception {
// class is not serializable, toString() returns: example.A@1988886
byte[] v15_bytes = {};
example.A v15 = (example.A) (new ObjectInputStream(new ByteArrayInputStream(v15_bytes)).readObject());
example.YetiExample.illustrateAssertion((example.A) v15);
/**BUG FOUND: RUNTIME EXCEPTION**/
/** java.lang.AssertionError
at example.YetiExample.illustrateAssertion(YetiExample.java:62)
**/
}Example 39
| Project: phosphor-master File: DroidBenchObjTagITCase.java View source code |
@Test(expected = java.lang.AssertionError.class)
public void testImplicitFlow2() {
String userInputPassword = taintedString("superSecure");
if (userInputPassword.equals("superSecure"))
passwordCorrect = true;
Taint taint = MultiTainter.getTaint(passwordCorrect);
assertTrue(MultiTainter.getTaint(passwordCorrect) != null && (MultiTainter.getTaint(passwordCorrect).lbl != null || !MultiTainter.getTaint(passwordCorrect).hasNoDependencies()));
}Example 40
| Project: h2o-3-master File: MRThrow.java View source code |
@Test
public void testContinuationThrow() throws InterruptedException, ExecutionException {
int sz = H2O.CLOUD.size();
Vec vec = Vec.makeZero((sz + 1) * FileVec.DFLT_CHUNK_SIZE + 1);
try {
for (int i = 0; i < H2O.CLOUD._memary.length; ++i) {
final ByteHistoThrow bh = new ByteHistoThrow(H2O.CLOUD._memary[i]);
final boolean[] ok = new boolean[] { false };
try {
CountedCompleter cc = new CountedCompleter() {
@Override
public void compute() {
tryComplete();
}
@Override
public boolean onExceptionalCompletion(Throwable ex, CountedCompleter cc) {
ok[0] = ex.getMessage().contains("test");
return super.onExceptionalCompletion(ex, cc);
}
};
bh.setCompleter(cc);
bh.dfork(vec);
// If the chosen file is too small for the cluster, some nodes will have *no* work
// and so no exception is thrown.
cc.join();
} catch (RuntimeException re) {
assertTrue(re.getMessage().contains("test") || re.getCause().getMessage().contains("test"));
} catch (java.lang.AssertionError ae) {
throw ae;
} catch (Throwable ex) {
ex.printStackTrace();
fail("Unexpected exception" + ex.toString());
}
}
} finally {
// remove from DKV
if (vec != null)
vec.remove();
}
}Example 41
| Project: jbehave-core-master File: StackTraceFormatterBehaviour.java View source code |
@Test
public void stackTracesShouldBeCompressible() throws IOException {
String start = "java.lang.AssertionError: cart should have contained 68467780\n" + "Expected: is <true>\n" + " got: <false>\n" + "\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)\n" + "\tat EtsyDotComSteps.anItemInTheEtsyCart(EtsyDotComSteps.groovy:51)\n" + // renamed in Groovy 1.8 ?
"\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:44)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)\n" + "\tat EtsyDotComSteps.anItemInTheEtsyCart(EtsyDotComSteps.groovy:51)\n" + "\tat sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n" + "\tat sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)\n" + "\tat sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)\n" + "\tat java.lang.reflect.Constructor.newInstance(Constructor.java:513)\n" + "\tat org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:21)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n" + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n" + "\tat java.lang.reflect.Method.invoke(Method.java:597)\n" + "\tat org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:88)\n" + "\tat groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)\n" + "\tat groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1302)\n" + "\tat org.codehaus.groovy.runtime.InvokerHelper.invokeStaticMethod(InvokerHelper.java:819)\n" + "\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeStaticMethodN(ScriptBytecodeAdapter.java:205)\n" + "\tat com.github.tanob.groobe.AssertionSupport.assertWithFailureMessage(AssertionSupport.groovy:32)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n" + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n" + "\tat java.lang.reflect.Method.invoke(Method.java:597)\n" + "\tat org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:88)\n" + "\tat groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)\n" + "\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:362)\n" + "\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnCurrentN(ScriptBytecodeAdapter.java:77)\n" + "\tat com.github.tanob.groobe.AssertionSupport$_assertTransformedDelegateAndOneParam_closure3.doCall(AssertionSupport.groovy:20)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n" + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n" + "\tat java.lang.reflect.Method.invoke(Method.java:597)\n" + "\tat org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:88)\n" + "\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke(ClosureMetaMethod.java:80)\n" + "\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:270)\n" + "\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:52)\n" + "\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)\n" + "\tat EtsyDotComSteps.cartHasThatItem(EtsyDotComSteps.groovy:112)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n" + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n" + "\tat java.lang.reflect.Method.invoke(Method.java:597)\n" + "\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)\n" + "\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)\n" + "\tat org.jbehave.core.steps.StepCreator$ParameterisedStep.perform(StepCreator.java:430)\n" + "\tat org.jbehave.core.embedder.StoryRunner$FineSoFar.run(StoryRunner.java:261)\n" + "\tat org.jbehave.core.embedder.StoryRunner.runStepsWhileKeepingState(StoryRunner.java:457)\n";
StackTraceFormatter formatter = new StackTraceFormatter(true);
assertEquals("java.lang.AssertionError: cart should have contained 68467780\n" + "Expected: is <true>\n" + " got: <false>\n" + "\t(groovy-call)\n" + "\tat EtsyDotComSteps.anItemInTheEtsyCart(EtsyDotComSteps.groovy:51)\n" + "\t(groovy-call)\n" + "\tat EtsyDotComSteps.anItemInTheEtsyCart(EtsyDotComSteps.groovy:51)\n" + "\t(reflection-construct)\n" + "\tat org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:21)\n" + "\t(groovy-static-method-invoke)\n" + "\tat com.github.tanob.groobe.AssertionSupport.assertWithFailureMessage(AssertionSupport.groovy:32)\n" + "\t(groovy-instance-method-invoke)\n" + "\tat com.github.tanob.groobe.AssertionSupport$_assertTransformedDelegateAndOneParam_closure3.doCall(AssertionSupport.groovy:20)\n" + "\t(groovy-closure-invoke)\n" + "\tat EtsyDotComSteps.cartHasThatItem(EtsyDotComSteps.groovy:112)\n" + "\t(groovy-call)\n" + "\tat org.jbehave.core.steps.StepCreator$ParameterisedStep.perform(StepCreator.java:430)\n" + "\tat org.jbehave.core.embedder.StoryRunner$FineSoFar.run(StoryRunner.java:261)\n" + "...", formatter.stackTrace(start));
}Example 42
| Project: spring-open-master File: UtilityClassChecker.java View source code |
/**
* Assert that the given class adheres to the utility class rules.
*
* @param clazz the class to check
*
* @throws java.lang.AssertionError if the class is not a valid
* utility class
*/
public static void assertThatClassIsUtility(Class<?> clazz) {
final UtilityClassChecker checker = new UtilityClassChecker();
if (!checker.isProperlyDefinedUtilityClass(clazz)) {
final Description toDescription = new StringDescription();
final Description mismatchDescription = new StringDescription();
checker.describeTo(toDescription);
checker.describeMismatch(mismatchDescription);
final String reason = "\n" + "Expected: is \"" + toDescription.toString() + "\"\n" + " but : was \"" + mismatchDescription.toString() + "\"";
throw new AssertionError(reason);
}
}Example 43
| Project: lucene-solr-master File: GeoPolygonTest.java View source code |
@Test
public void testLargePolygonFailureCase2() {
/*
[junit4] > Throwable #1: java.lang.AssertionError: FAIL: id=2 should have matched but did not
[junit4] > shape=GeoComplexPolygon: {planetmodel=PlanetModel.WGS84, number of shapes=1, address=6eccd33b,
testPoint=[lat=0.03170690566178683, lon=1.0862414976732029([X=0.46609969117964495, Y=0.8854242006628827, Z=0.0317369552646047])],
testPointInSet=false,
shapes={ {
[lat=1.0774842300167298, lon=-0.11534121538553185([X=0.46969930266058374, Y=-0.054417217622152375, Z=0.8794587218580684])],
[lat=0.05101544777239065, lon=1.031558236908661([X=0.5133835679471972, Y=0.8579350866926241, Z=0.051049928818862174])],
[lat=-0.011222928649880962, lon=1.5851249038356199([X=-0.01434320835886277, Y=1.0009526216234983, Z=-0.011235244842183226])],
[lat=-0.02571365137215876, lon=0.5627875521419741([X=0.8464356149277266, Y=0.5339650936800929, Z=-0.025739527171261035])],
[lat=0.03833766792865358, lon=1.0082901344798614([X=0.5335096521470836, Y=0.8462411929752105, Z=0.03837097111317845])],
[lat=0.1719054969347345, lon=0.9024290407832926([X=0.6111941952395734, Y=0.7740553755547761, Z=0.17123457719021212])],
[lat=0.08180947807010808, lon=1.0107147265848113([X=0.5300590148023426, Y=0.8453039531721928, Z=0.08180784289673602])]}}
[junit4] > bounds=XYZBounds: [xmin=-1.0011188544924792 xmax=1.0011188544924792
ymin=-1.0011188544924792 ymax=1.0011188544924792
zmin=-0.025739527671261034 zmax=0.9977622925221051]
[junit4] > world bounds=( minX=-1.0011188539924791 maxX=1.0011188539924791 minY=-1.0011188539924791 maxY=1.0011188539924791 minZ=-0.9977622920221051 maxZ=0.9977622920221051
[junit4] > quantized point=[X=-0.477874179571219, Y=0.5908091335156603, Z=-0.6495967142221521] within shape? true within bounds? false
[junit4] > unquantized point=[lat=-0.7073124559987376, lon=2.2509085326629887([X=-0.47787417938801546, Y=0.5908091336704123, Z=-0.6495967140640758])] within shape? true within bounds? false
[junit4] > docID=2 deleted?=false
[junit4] > query=PointInGeo3DShapeQuery: field=point: Shape: GeoComplexPolygon: {planetmodel=PlanetModel.WGS84, number of shapes=1, address=6eccd33b, testPoint=[lat=0.03170690566178683, lon=1.0862414976732029([X=0.46609969117964495, Y=0.8854242006628827, Z=0.0317369552646047])], testPointInSet=false, shapes={ {[lat=1.0774842300167298, lon=-0.11534121538553185([X=0.46969930266058374, Y=-0.054417217622152375, Z=0.8794587218580684])], [lat=0.05101544777239065, lon=1.031558236908661([X=0.5133835679471972, Y=0.8579350866926241, Z=0.051049928818862174])], [lat=-0.011222928649880962, lon=1.5851249038356199([X=-0.01434320835886277, Y=1.0009526216234983, Z=-0.011235244842183226])], [lat=-0.02571365137215876, lon=0.5627875521419741([X=0.8464356149277266, Y=0.5339650936800929, Z=-0.025739527171261035])], [lat=0.03833766792865358, lon=1.0082901344798614([X=0.5335096521470836, Y=0.8462411929752105, Z=0.03837097111317845])], [lat=0.1719054969347345, lon=0.9024290407832926([X=0.6111941952395734, Y=0.7740553755547761, Z=0.17123457719021212])], [lat=0.08180947807010808, lon=1.0107147265848113([X=0.5300590148023426, Y=0.8453039531721928, Z=0.08180784289673602])]}}
[junit4] > explanation:
[junit4] > target is in leaf _0(7.0.0):C11 of full reader StandardDirectoryReader(segments:3:nrt _0(7.0.0):C11)
[junit4] > full BKD path to target doc:
[junit4] > Cell(x=-0.8906255176936849 TO 1.0005089994430834 y=-0.6808995306272861 TO 0.9675171153117977 z=-0.997762292058209 TO 0.9939318087373729); Shape relationship = OVERLAPS; Quantized point within cell = true; Unquantized point within cell = true
[junit4] > on cell Cell(x=-0.8906255176936849 TO 1.0005089994430834 y=-0.6808995306272861 TO 0.9675171153117977 z=-0.997762292058209 TO 0.9939318087373729); Shape relationship = OVERLAPS; Quantized point within cell = true; Unquantized point within cell = true, wrapped visitor returned CELL_CROSSES_QUERY
[junit4] > leaf visit docID=2 x=-0.477874179571219 y=0.5908091335156603 z=-0.6495967142221521
*/
final GeoPoint testPoint = new GeoPoint(PlanetModel.WGS84, 0.03170690566178683, 1.0862414976732029);
final boolean testPointInSet = false;
final List<GeoPoint> pointList = new ArrayList<>();
// If the 1.07748... line is at the top, the bounds are correct and the test succeeds.
// If this line is at the bottom, though, the bounds are wrong and the test fails.
//pointList.add(new GeoPoint(PlanetModel.WGS84, 1.0774842300167298, -0.11534121538553185));
pointList.add(new GeoPoint(PlanetModel.WGS84, 0.05101544777239065, 1.031558236908661));
pointList.add(new GeoPoint(PlanetModel.WGS84, -0.011222928649880962, 1.5851249038356199));
pointList.add(new GeoPoint(PlanetModel.WGS84, -0.02571365137215876, 0.5627875521419741));
pointList.add(new GeoPoint(PlanetModel.WGS84, 0.03833766792865358, 1.0082901344798614));
pointList.add(new GeoPoint(PlanetModel.WGS84, 0.1719054969347345, 0.9024290407832926));
pointList.add(new GeoPoint(PlanetModel.WGS84, 0.08180947807010808, 1.0107147265848113));
pointList.add(new GeoPoint(PlanetModel.WGS84, 1.0774842300167298, -0.11534121538553185));
final GeoPolygon pSanity = GeoPolygonFactory.makeGeoPolygon(PlanetModel.WGS84, pointList);
assertTrue(pSanity.isWithin(testPoint) == testPointInSet);
final List<List<GeoPoint>> shapeList = new ArrayList<>();
shapeList.add(pointList);
final GeoPolygon p = new GeoComplexPolygon(PlanetModel.WGS84, shapeList, testPoint, testPointInSet);
//System.err.println(p);
/*
[junit4] 2> GeoComplexPolygon: {planetmodel=PlanetModel.WGS84, number of shapes=1, address=dcf3e99,
testPoint=[lat=0.03170690566178683, lon=1.0862414976732029([X=0.46609969117964506, Y=0.8854242006628825, Z=0.0317369552646047])],
testPointInSet=false,
shapes={ {
[lat=1.0774842300167298, lon=-0.11534121538553185([X=0.46969930266058374, Y=-0.054417217622152375, Z=0.8794587218580684])],
[lat=0.05101544777239065, lon=1.031558236908661([X=0.5133835679471972, Y=0.8579350866926241, Z=0.051049928818862174])],
[lat=-0.011222928649880962, lon=1.5851249038356199([X=-0.01434320835886277, Y=1.0009526216234983, Z=-0.011235244842183226])],
[lat=-0.02571365137215876, lon=0.5627875521419741([X=0.8464356149277266, Y=0.5339650936800929, Z=-0.025739527171261035])],
[lat=0.03833766792865358, lon=1.0082901344798614([X=0.5335096521470836, Y=0.8462411929752105, Z=0.03837097111317845])],
[lat=0.1719054969347345, lon=0.9024290407832926([X=0.6111941952395734, Y=0.7740553755547761, Z=0.17123457719021212])]}}
[lat=0.08180947807010808, lon=1.0107147265848113([X=0.5300590148023426, Y=0.8453039531721928, Z=0.08180784289673602])],
*/
final XYZBounds referenceBounds = new XYZBounds();
pSanity.getBounds(referenceBounds);
final XYZBounds actualBounds = new XYZBounds();
p.getBounds(actualBounds);
assertEquals(referenceBounds.getMinimumX(), actualBounds.getMinimumX(), 0.0000001);
assertEquals(referenceBounds.getMaximumX(), actualBounds.getMaximumX(), 0.0000001);
assertEquals(referenceBounds.getMinimumY(), actualBounds.getMinimumY(), 0.0000001);
assertEquals(referenceBounds.getMaximumY(), actualBounds.getMaximumY(), 0.0000001);
assertEquals(referenceBounds.getMinimumZ(), actualBounds.getMinimumZ(), 0.0000001);
assertEquals(referenceBounds.getMaximumZ(), actualBounds.getMaximumZ(), 0.0000001);
final XYZSolid solid = XYZSolidFactory.makeXYZSolid(PlanetModel.WGS84, actualBounds.getMinimumX(), actualBounds.getMaximumX(), actualBounds.getMinimumY(), actualBounds.getMaximumY(), actualBounds.getMinimumZ(), actualBounds.getMaximumZ());
final GeoPoint checkPoint = new GeoPoint(PlanetModel.WGS84, -0.7073124559987376, 2.2509085326629887);
// Given the choice of test point, does this all make sense?
assertTrue(pSanity.isWithin(checkPoint) == p.isWithin(checkPoint));
assertTrue(p.isWithin(checkPoint));
assertTrue(solid.isWithin(checkPoint));
}Example 44
| Project: objectlabkit-master File: CukeUtils.java View source code |
public static <T> void compareResults(final Class<T> classType, final List<T> actual, final DataTable expected) {
final List<String> fieldsToCompare = expected.topCells();
final T[] expectedEntities = convertDataTableToExpected(classType, expected, fieldsToCompare);
final List<T> actualEntities = actual.stream().map( sea -> copyFieldValues(fieldsToCompare, sea, classType)).collect(Collectors.toList());
try {
assertThat(actualEntities).usingElementComparator(comparator(buildExclusionFields(classType, fieldsToCompare))).containsOnly(expectedEntities);
} catch (final java.lang.AssertionError e) {
final String actualDataAsStr = convertToString(actual, fieldsToCompare);
throw new ComparisonFailure("Table comparison for " + classType.getSimpleName() + " does not match\n", expected.toString(), actualDataAsStr);
}
}Example 45
| Project: wisdom-master File: BuiltProject.java View source code |
public void assertErrorFreeLog() throws AssertionError { List<String> lines = getLogLines(); assertThat(lines).isNotNull(); for (String line : lines) { // A hack to keep stupid velocity resource loader errors from triggering failure if (line.contains("[ERROR]") && !isVelocityError(line)) { throw new AssertionError("Error in execution: " + line); } } }
Example 46
| Project: thredds-master File: TestN4problems.java View source code |
@Test
public void testTiling2() throws IOException, InvalidRangeException {
// java.lang.AssertionError: shape[2] (385) >= pt[2] (390)
String filename = TestN4reading.testDir + "UpperDeschutes_t4p10_swemelt.nc";
try (NetcdfFile ncfile = NetcdfFile.open(filename)) {
Variable v = ncfile.findVariable(null, "UpperDeschutes_t4p10_swemelt");
Array data = v.read("8087, 150:155, 150:155");
assert data != null;
}
}Example 47
| Project: VarexJ-master File: ThreadInfo.java View source code |
/**
* Executes a method call. Be aware that it executes the whole method as one atomic
* step. Arguments have to be already on the provided stack
* <p/>
* This only works for non-native methods, and does not allow any choice points,
* so you have to know very well what you are doing.
* <p/>
* Instructions executed by this method are still fully observable and stored in
* the path
*/
public void executeMethodAtomic(StackFrame frame) {
pushFrame(frame);
int depth = countStackFrames();
// Instruction pc = frame.getPC().getValue();
SystemState ss = vm.getSystemState();
// to shut off avoidable context switches (MONITOR_ENTER and wait() can still block)
ss.incAtomic();
while (depth <= countStackFrames()) {
executeInstruction();
if (ss.getNextChoiceGenerator() != null) {
// createAndThrowException("java.lang.AssertionError", "choice point in sync executed method: " + frame);
throw new JPFException("choice point in atomic method execution: " + frame);
} else {
// pc = nextPC;
}
}
vm.getSystemState().decAtomic();
nextPc = null;
// the frame was already removed by the RETURN insn of the frame's method
}Example 48
| Project: uncc2014watsonsim-master File: QClassDetectionTest.java View source code |
@Test
public void test() {
Question[] questions = { Question.known("In book 1, \"The ___ Hat\"", "sorting", "HARRY POTTER & TME CHAPTER TITLES"), Question.known("In book 4, \"The ___ World Cup\"", "quidditch", "HARRY POTTER & TME CHAPTER TITLES"), Question.known("In book 6, her \"helping hand\"", "Hermione", "HARRY POTTER & TME CHAPTER TITLES"), Question.known("Plant a Smooch on Yours Truly, Katharine", "Kiss Me, Kate", "MUSICALS BY ANY OTHER NAME"), Question.known("The 2 digits that give James Bond license to kill", "0", "BY THE NUMBERS"), Question.known("Of 1.8, 2.5, or 3.7 hours per home, the average time PBS is viewed each week in U.S.", "1.8", "PBS"), Question.known("Gary glitter: \"Rock and Roll _____ _____\"", "Part 2", "LET'S ROCK!"), Question.known("Simple Abundance by Sarah Ban Breathnach has this many messages for women, one for each day in 1996", "366", "IN THE BOOKSTORE"), // functionality is used by another method (JSONQuestionSource(Reader)).
Question.known("Kimono, caftan, bath-", "FASHIONABLE COMMON BONDS"), Question.known("Ontario,Havasu,Baikal", "COMMON BONDS"), Question.known("Trash, a boyfriend you're sick of, goods or securities sold below costs", "COMMON BONDS"), Question.known("green crested, collared, anole", "Beastly Common Bonds"), Question.known("Later jailed for fraud, Australian Alan Bond became a national hero for financing the 1983 capture of this sailing trophy", "UNCOMMON BONDS"), Question.known("Rolled, steelcut, Scotch", "EDIBLE COMMON BONDS"), Question.known("Nursery rhyme waterspout crawler who's a Marvel crime fighter", "BEFORE & AFTER"), Question.known("Nursery rhyme waterspout crawler who's a Marvel crime fighter", "Before & After"), Question.known("This man succeeded John Carver as governor of Plymouth Colony in 1621 & served for 31 of the next 35 years", "AMERICA BEFORE THE REVOLUTION"), Question.known("John Milton epic about Gertrude Stein's Parisian expatriate Yanks who were born starting in 1965", "BEFORE, DURING, & AFTER"), Question.known("Gray", "INDIANAGRAMS"), Question.known("The king is dead, long \"lives\" the king", " MUSICAL ANAGRAMS"), Question.known("Anthem ender: BEHAVE HOME FORT", "ANAGRAMS"), Question.known("Lose", "SCRAMBLED FISH"), Question.known("", ""), Question.known("He not only wrote & directed \"Little Johnny Jones\", he also played the title role", "QUOTATION") };
QType[] labels = { QType.FITB, QType.FITB, QType.FACTOID, QType.FACTOID, QType.FACTOID, QType.FACTOID, QType.FITB, QType.FACTOID, QType.COMMON_BONDS, QType.COMMON_BONDS, QType.COMMON_BONDS, QType.COMMON_BONDS, QType.COMMON_BONDS, QType.COMMON_BONDS, QType.BEFORE_AND_AFTER, QType.BEFORE_AND_AFTER, QType.BEFORE_AND_AFTER, QType.BEFORE_AND_AFTER, QType.ANAGRAM, QType.ANAGRAM, QType.ANAGRAM, QType.ANAGRAM, QType.FACTOID, QType.QUOTATION };
int missed = 0;
for (int i = 0; i < questions.length; i++) {
try {
assertEquals(labels[i], questions[i].getType());
} catch (java.lang.AssertionError ae) {
System.out.println("Failed to correctly categorize " + questions[i].text + " as " + labels[i] + "; incorrect type: " + questions[i].getType());
missed++;
}
}
assertTrue(missed * 4 < questions.length);
}Example 49
| Project: martus-android-master File: Flexidate.java View source code |
public Calendar getCalendarLow() {
if (calendarLow == null) {
int context = getRangeContext();
switch(context) {
case NO_CONTEXT:
// Need to define better lowest unknown
calendarLow = new GregorianCalendar(0, Calendar.JANUARY, 1, 1, 0, 0);
break;
case YEAR_CONTEXT:
calendarLow = new GregorianCalendar(getYear(), Calendar.JANUARY, 1, 1, 0, 0);
break;
case MONTH_CONTEXT:
calendarLow = new GregorianCalendar(getYear(), getMonth() - 1, 1, 1, 0, 0);
break;
case DAY_CONTEXT:
calendarLow = new GregorianCalendar(getYear(), getMonth() - 1, getDay(), 1, 0, 0);
break;
default:
throw new java.lang.AssertionError("Flexidate produced invalid context");
}
}
return calendarLow;
}Example 50
| Project: h-store-master File: Counter.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.add(controller, (ca.evanjones.protorpc.Counter.Value) request);
case 1:
return impl.get(controller, (ca.evanjones.protorpc.Counter.GetRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 51
| Project: fepss-rpc-master File: TestProto.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.testMethod(controller, (com.fepss.rpc.test.TestProto.User) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 52
| Project: pbase-master File: MultiRowMutationProtos.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.mutateRows(controller, (org.apache.hadoop.hbase.protobuf.generated.MultiRowMutationProtos.MutateRowsRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 53
| Project: hbase-book-master File: ObserverStatisticsProtos.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.getStatistics(controller, (coprocessor.generated.ObserverStatisticsProtos.StatisticsRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 54
| Project: rich-test-results-master File: AntXmlParserTest.java View source code |
private TestSuite getExpectedFailTestSuite() {
return TestSuite.newBuilder().setName("com.google.SimpleTest").setTotalCount(2).setFailureCount(1).setErrorCount(0).setSkippedCount(0).setElapsedTimeMillis(6L).addTestCase(TestCase.newBuilder().setElapsedTimeMillis(6L).setStatus(TestStatus.FAILED).setClassName("com.google.SimpleTest").setName("testThatFails").addFailure(StackTrace.newBuilder().setExceptionMessage("expected:<1> but was:<2>").setExceptionType("java.lang.AssertionError").setContent("java.lang.AssertionError: expected:<1> but was:<2>\n" + "\tat org.junit.Assert.fail(Assert.java:88)\n" + "\tat org.junit.Assert.failNotEquals(Assert.java:743)\n" + "\tat org.junit.Assert.assertEquals(Assert.java:118)\n" + "\tat org.junit.Assert.assertEquals(Assert.java:555)\n" + "\tat org.junit.Assert.assertEquals(Assert.java:542)\n" + "\tat com.google.SimpleTest.testThatFails(SimpleTest.java:11)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n").addStackContent(text("java.lang.AssertionError: expected:<1> but was:<2>\n" + "\tat org.junit.Assert.fail(")).addStackContent(codeRef("Assert.java:88", "org/junit/Assert.java", 88)).addStackContent(text(")\n" + "\tat org.junit.Assert.failNotEquals(")).addStackContent(codeRef("Assert.java:743", "org/junit/Assert.java", 743)).addStackContent(text(")\n" + "\tat org.junit.Assert.assertEquals(")).addStackContent(codeRef("Assert.java:118", "org/junit/Assert.java", 118)).addStackContent(text(")\n" + "\tat org.junit.Assert.assertEquals(")).addStackContent(codeRef("Assert.java:555", "org/junit/Assert.java", 555)).addStackContent(text(")\n" + "\tat org.junit.Assert.assertEquals(")).addStackContent(codeRef("Assert.java:542", "org/junit/Assert.java", 542)).addStackContent(text(")\n" + "\tat com.google.SimpleTest.testThatFails(")).addStackContent(codeRef("SimpleTest.java:11", "com/google/SimpleTest.java", 11)).addStackContent(text(")\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n")))).addTestCase(TestCase.newBuilder().setElapsedTimeMillis(0L).setStatus(TestStatus.PASSED).setClassName("com.google.SimpleTest").setName("testThatPasses")).build();
}Example 55
| Project: incubator-slider-master File: SliderClusterAPI.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.stopCluster(controller, (org.apache.slider.api.proto.Messages.StopClusterRequestProto) request);
case 1:
return impl.flexCluster(controller, (org.apache.slider.api.proto.Messages.FlexClusterRequestProto) request);
case 2:
return impl.getJSONClusterStatus(controller, (org.apache.slider.api.proto.Messages.GetJSONClusterStatusRequestProto) request);
case 3:
return impl.getInstanceDefinition(controller, (org.apache.slider.api.proto.Messages.GetInstanceDefinitionRequestProto) request);
case 4:
return impl.listNodeUUIDsByRole(controller, (org.apache.slider.api.proto.Messages.ListNodeUUIDsByRoleRequestProto) request);
case 5:
return impl.getNode(controller, (org.apache.slider.api.proto.Messages.GetNodeRequestProto) request);
case 6:
return impl.getClusterNodes(controller, (org.apache.slider.api.proto.Messages.GetClusterNodesRequestProto) request);
case 7:
return impl.echo(controller, (org.apache.slider.api.proto.Messages.EchoRequestProto) request);
case 8:
return impl.killContainer(controller, (org.apache.slider.api.proto.Messages.KillContainerRequestProto) request);
case 9:
return impl.amSuicide(controller, (org.apache.slider.api.proto.Messages.AMSuicideRequestProto) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 56
| Project: protobuf-rpc-pro-master File: PingPong.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.ping(controller, (com.googlecode.protobuf.pro.duplex.test.PingPong.Ping) request);
case 1:
return impl.fail(controller, (com.googlecode.protobuf.pro.duplex.test.PingPong.Ping) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 57
| Project: RoboBuggy-master File: AssertionTest.java View source code |
@Test
public void arraysDifferAtElement1withMessage() {
try {
assertArrayEquals("message", (new Object[] { true, true }), (new Object[] { true, false }));
fail();
} catch (AssertionError exception) {
assertEquals("message: arrays first differed at element [1]; expected:<true> but was:<false>", exception.getMessage());
}
}Example 58
| Project: SQLBulkQueryTool-master File: TestXMLQueryVisitationStrategy.java View source code |
@Test(expected = java.lang.AssertionError.class)
public void testIsExceptionExpected_Failure() throws Exception {
// the following 3 properties are what's normally found in the scenario.properties file
System.setProperty("queryset.dirname", "test_query_set");
System.setProperty("test.queries.dirname", "test_queries");
System.setProperty("expected.results.dirname", "expected_results");
System.setProperty("result.mode", "compare");
//
System.setProperty("project.data.path", UnitTestUtil.getTestDataPath());
System.setProperty("output.dir", UnitTestUtil.getTestOutputPath() + File.separator + "sqltest");
System.setProperty(ConfigPropertyNames.CONFIG_FILE, UnitTestUtil.getTestDataPath() + File.separator + "localconfig.properties");
ConfigPropertyLoader _instance = ConfigPropertyLoader.getInstance();
Properties p = _instance.getProperties();
if (p == null || p.isEmpty()) {
throw new RuntimeException("Failed to load config properties file");
}
QueryScenario set = QueryScenario.createInstance("testscenario", p);
XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
final ExpectedResultsHolder expectedResult;
QueryTest test = new QueryTest(set.getQueryScenarioIdentifier(), "samplefiles", "expectedresult_error", null);
String filename = UnitTestUtil.getTestDataPath() + File.separator + "samplefiles" + File.separator + "expectedresult_error.xml";
File resultsFile = new File(filename);
expectedResult = jstrat.parseXMLResultsFile(test, set.getQueryScenarioIdentifier(), resultsFile);
assertFalse(expectedResult.isExceptionExpected());
}Example 59
| Project: tripping-dangerzone-master File: SuccessListener.java View source code |
protected static void logError(PrintStream ps, boolean fullTrace, Throwable ex, int causeDepth) {
if ((ps != null) && (ex != null)) {
if (ex instanceof AGException) {
// Custom failure shows friendly name (perhaps more stuff later)
ps.format("%s%n", ex);
} else if (ex instanceof java.lang.AssertionError) {
// A regular style JUnit error, show friendly message
ps.format("ASSERT-FAILED: %s%n", ex.getMessage());
} else {
// Log exception basics, plus message in case toString() doesn't have it
ps.format("EXCEPTION: %s [%s]%n", ex, ex.getMessage());
}
try {
// Dump the visible pieces of the stack trace
for (StackTraceElement ste : ex.getStackTrace()) {
if (fullTrace) {
ps.format("\t%s%n", ste);
} else if (isVisibleClass(ste.getClassName())) {
ps.format(" %s.%s(%s:%d)%n", ste.getClassName(), ste.getMethodName(), ste.getFileName(), ste.getLineNumber());
}
ps.flush();
}
} catch (Exception exIgnore) {
}
try {
// Trace back the cause chain
Throwable ecause = ex.getCause();
if (ecause != null) {
if (causeDepth < MAX_CAUSE_DEPTH) {
ps.format(" CAUSE-%d: ", causeDepth + 1);
logError(ps, fullTrace, ecause, causeDepth + 1);
} else {
ps.println(" CAUSE CHAIN ABORTED.");
}
}
} catch (Exception exIgnore) {
}
}
streamFlush(ps);
}Example 60
| Project: cdh3u3-with-mesos-master File: TestStorageDirectoryFailure.java View source code |
@Test
public /** Remove storage dirs and checkpoint to trigger detection */
void testCheckpointAfterFailingFirstNamedir() throws IOException {
assertEquals(0, numRemovedDirs());
checkFileCreation("file0");
// Remove the 1st storage dir
FileUtil.fullyDelete(new File(nameDirs.get(0)));
secondaryNN.doCheckpoint();
assertEquals(1, numRemovedDirs());
assertEquals(nameDirs.get(0), getRemovedDirs().get(0).getRoot().getPath());
checkFileCreation("file1");
// Remove the 2nd
FileUtil.fullyDelete(new File(nameDirs.get(1)));
secondaryNN.doCheckpoint();
assertEquals(2, numRemovedDirs());
assertEquals(nameDirs.get(1), getRemovedDirs().get(1).getRoot().getPath());
checkFileCreation("file2");
// Remove the last one. Prevent the NN from exiting the process when
// it notices this via the checkpoint.
FSEditLog spyLog = spy(cluster.getNameNode().getFSImage().getEditLog());
doNothing().when(spyLog).fatalExit(anyString());
cluster.getNameNode().getFSImage().setEditLog(spyLog);
// After the checkpoint, we should be dead. Verify fatalExit was
// called and that eg a checkpoint fails.
FileUtil.fullyDelete(new File(nameDirs.get(2)));
try {
secondaryNN.doCheckpoint();
fail("There's no storage to retrieve an image from");
} catch (FileNotFoundException fnf) {
}
verify(spyLog, atLeastOnce()).fatalExit(anyString());
// Check that we can't mutate state without any edit streams
try {
checkFileCreation("file3");
fail("Created a file w/o edit streams");
} catch (IOException ioe) {
assertTrue(ioe.getMessage().contains("java.lang.AssertionError: No edit streams to log to"));
}
}Example 61
| Project: flare-spork-master File: CmdLineParser.java View source code |
/** * Register a command line option. * @param c Single character designator for this option. It cannot be '-'. * @param s Full word designator for this option. This can be null, in which case * no long designator will exist for this option. * @param ve If REQUIRED, a value will be expected with this option. If * OPTIONAL a value will be accepted if it is seen. * @throws AssertionError if there is no short option, or if this option has already been * used. */ public void registerOpt(char c, String s, ValueExpected ve) { if (c == '-') { throw new AssertionError("CmdLineParser: '-' is not a legal single character designator."); } Character cc = Character.valueOf(c); if (mShort.put(cc, ve) != null) { throw new AssertionError("CmdLineParser: You have already registered option " + cc.toString()); } if (mLong != null) { if (mLong.put(s, cc) != null) { throw new AssertionError("CmdLineParser: You have already registered option " + s); } } }
Example 62
| Project: substeps-runner-master File: BaseJunitFeatureRunnerTest.java View source code |
/**
* {@inheritDoc}
*/
public void doCallback(final String methodName, final String[] params) {
System.out.println("got callback from method: " + methodName);
try {
assertNotificationState();
} catch (final java.lang.AssertionError ae) {
assertions.add(ae);
}
// final Description current = testNotifier.getCurrentlyRunning();
// if (current != null)
// {
// final String displayName = current.getDisplayName();
//
// final String key = displayName.split(" ")[0];
//
// }
descriptionSnapshotsIdx++;
// from this method name we want to get back to the description
// check that when this method is invoked, fireTestStarted has been
// invoked for this test, but not finished, and finished or failed for
// prior tests and nothing for subsequent
}Example 63
| Project: elassandra-master File: AbstractChildTestCase.java View source code |
static void assertBitSet(BitDocIdSet actual, BitDocIdSet expected, IndexSearcher searcher) throws IOException {
if (!equals(expected, actual)) {
Description description = new StringDescription();
description.appendText(reason(actual, expected, searcher));
description.appendText("\nExpected: ");
description.appendValue(expected);
description.appendText("\n got: ");
description.appendValue(actual);
description.appendText("\n");
throw new java.lang.AssertionError(description.toString());
}
}Example 64
| Project: j2objc-master File: Thread.java View source code |
/**
* Parks the current thread for a particular number of nanoseconds, or
* indefinitely. If not indefinitely, this method unparks the thread
* after the given number of nanoseconds if no other thread unparks it
* first. If the thread has been "preemptively unparked," this method
* cancels that unparking and returns immediately. This method may
* also return spuriously (that is, without the thread being told to
* unpark and without the indicated amount of time elapsing).
*
* <p>See {@link java.util.concurrent.locks.LockSupport} for more
* in-depth information of the behavior of this method.</p>
*
* <p>This method must only be called when <code>this</code> is the current
* thread.
*
* @param nanos number of nanoseconds to park for or <code>0</code>
* to park indefinitely
* @throws IllegalArgumentException thrown if <code>nanos < 0</code>
*
* @hide for Unsafe
*/
public final void parkFor$(long nanos) {
Object vmt = nativeThread;
synchronized (vmt) {
switch(parkState) {
case ParkState.PREEMPTIVELY_UNPARKED:
{
parkState = ParkState.UNPARKED;
break;
}
case ParkState.UNPARKED:
{
long millis = nanos / NANOS_PER_MILLI;
nanos %= NANOS_PER_MILLI;
parkState = ParkState.PARKED;
try {
vmt.wait(millis, (int) nanos);
} catch (InterruptedException ex) {
interrupt();
} finally {
/*
* Note: If parkState manages to become
* PREEMPTIVELY_UNPARKED before hitting this
* code, it should left in that state.
*/
if (parkState == ParkState.PARKED) {
parkState = ParkState.UNPARKED;
}
}
break;
}
default:
/*parked*/
{
throw new AssertionError("shouldn't happen: attempt to repark");
}
}
}
}Example 65
| Project: nifi-master File: TestReplaceTextWithMapping.java View source code |
@Test(expected = java.lang.AssertionError.class)
public void testMatchingGroupForLookupKeyTooLarge() throws IOException {
final TestRunner runner = TestRunners.newTestRunner(new ReplaceTextWithMapping());
runner.setProperty(ReplaceTextWithMapping.REGEX, "-(.*?)-");
runner.setProperty(ReplaceTextWithMapping.MATCHING_GROUP_FOR_LOOKUP_KEY, "2");
runner.setProperty(ReplaceTextWithMapping.MAPPING_FILE, Paths.get("src/test/resources/TestReplaceTextWithMapping/color-mapping.txt").toFile().getAbsolutePath());
final Path path = Paths.get("src/test/resources/TestReplaceTextWithMapping/colors.txt");
runner.enqueue(path);
runner.run();
}Example 66
| Project: bugvm-master File: Scene.java View source code |
private void addSootBasicClasses() {
basicclasses[SootClass.HIERARCHY] = new HashSet<String>();
basicclasses[SootClass.SIGNATURES] = new HashSet<String>();
basicclasses[SootClass.BODIES] = new HashSet<String>();
addBasicClass("java.lang.Object");
addBasicClass("java.lang.Class", SootClass.SIGNATURES);
addBasicClass("java.lang.Void", SootClass.SIGNATURES);
addBasicClass("java.lang.Boolean", SootClass.SIGNATURES);
addBasicClass("java.lang.Byte", SootClass.SIGNATURES);
addBasicClass("java.lang.Character", SootClass.SIGNATURES);
addBasicClass("java.lang.Short", SootClass.SIGNATURES);
addBasicClass("java.lang.Integer", SootClass.SIGNATURES);
addBasicClass("java.lang.Long", SootClass.SIGNATURES);
addBasicClass("java.lang.Float", SootClass.SIGNATURES);
addBasicClass("java.lang.Double", SootClass.SIGNATURES);
addBasicClass("java.lang.String");
addBasicClass("java.lang.StringBuffer", SootClass.SIGNATURES);
addBasicClass("java.lang.Error");
addBasicClass("java.lang.AssertionError", SootClass.SIGNATURES);
addBasicClass("java.lang.Throwable", SootClass.SIGNATURES);
addBasicClass("java.lang.NoClassDefFoundError", SootClass.SIGNATURES);
addBasicClass("java.lang.ExceptionInInitializerError");
addBasicClass("java.lang.RuntimeException");
addBasicClass("java.lang.ClassNotFoundException");
addBasicClass("java.lang.ArithmeticException");
addBasicClass("java.lang.ArrayStoreException");
addBasicClass("java.lang.ClassCastException");
addBasicClass("java.lang.IllegalMonitorStateException");
addBasicClass("java.lang.IndexOutOfBoundsException");
addBasicClass("java.lang.ArrayIndexOutOfBoundsException");
addBasicClass("java.lang.NegativeArraySizeException");
addBasicClass("java.lang.NullPointerException");
addBasicClass("java.lang.InstantiationError");
addBasicClass("java.lang.InternalError");
addBasicClass("java.lang.OutOfMemoryError");
addBasicClass("java.lang.StackOverflowError");
addBasicClass("java.lang.UnknownError");
addBasicClass("java.lang.ThreadDeath");
addBasicClass("java.lang.ClassCircularityError");
addBasicClass("java.lang.ClassFormatError");
addBasicClass("java.lang.IllegalAccessError");
addBasicClass("java.lang.IncompatibleClassChangeError");
addBasicClass("java.lang.LinkageError");
addBasicClass("java.lang.VerifyError");
addBasicClass("java.lang.NoSuchFieldError");
addBasicClass("java.lang.AbstractMethodError");
addBasicClass("java.lang.NoSuchMethodError");
addBasicClass("java.lang.UnsatisfiedLinkError");
addBasicClass("java.lang.Thread");
addBasicClass("java.lang.Runnable");
addBasicClass("java.lang.Cloneable");
addBasicClass("java.io.Serializable");
// RoboVM note: Not available in RoboVM
// addBasicClass("java.lang.ref.Finalizer");
//
// addBasicClass("java.dyn.InvokeDynamic");
}Example 67
| Project: koa-master File: TestUtilsTest.java View source code |
@Test(expected = AssertionError.class, timeout = 1000)
public void testEqualsConcurrency_concurrentAccessFails() throws Exception {
TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() {
public void assertOn(String msg, Object o0, Object o1) {
assertEquals(msg, o0, o1);
}
}, IllegalMonitorStateException.class, new Runnable() {
public void run() {
waste(10);
}
}, new Runnable() {
public void run() {
waste(11);
}
}, new Runnable() {
public void run() {
waste(3);
}
});
assertSystemErrContains("Thread-1\" java.lang.IllegalMonitorStateException");
assertSystemErrContains("Thread-2\" java.lang.IllegalMonitorStateException");
assertSystemErrContains("Thread-3\" java.lang.IllegalMonitorStateException");
assertSystemErrContains("Thread-4");
}Example 68
| Project: junit.contrib-master File: ProxyTest.java View source code |
@Test
public void testForgotToCallMethodDetectedOnFinalize() {
ByteArrayOutputStream buff = new ByteArrayOutputStream();
PrintStream p = new PrintStream(buff);
PrintStream oldErr = System.err;
try {
System.setErr(p);
testFinalMethod();
// force gc - this is not guaranteed to work
LinkedList<byte[]> memoryEater = new LinkedList<byte[]>();
for (int i = 0; i < 100 && buff.size() == 0; i++) {
memoryEater.add(new byte[1000]);
System.gc();
System.err.flush();
}
String error = new String(buff.toByteArray());
if (error.length() > 0) {
// only verify the message if it _did_ work
assertTrue(error, error.startsWith("java.lang.AssertionError: A proxy for the class\n" + "org.junit.contrib.assertthrows.ProxyTest$ClassWithFinalMethod\n" + "was created, but then no overridable method was called on it.\n" + "See the stack trace for where the proxy was created."));
}
} finally {
System.setErr(oldErr);
}
}Example 69
| Project: sx10-master File: Types.java View source code |
/*
* returns runtime type for known types.
* mainly for primitives, string and exceptions.
*/
public static RuntimeType getRTTForKnownType(/*<?>*/
Class<?> javaClass) {
if (java.lang.Object.class.equals(javaClass)) {
return ANY;
} else if (java.lang.String.class.equals(javaClass)) {
return STRING;
} else if (java.lang.Comparable.class.equals(javaClass)) {
return COMPARABLE;
} else if (javaClass.isPrimitive()) {
if (byte.class.equals(javaClass)) {
return BYTE;
} else if (short.class.equals(javaClass)) {
return SHORT;
} else if (int.class.equals(javaClass)) {
return INT;
} else if (long.class.equals(javaClass)) {
return LONG;
} else if (float.class.equals(javaClass)) {
return FLOAT;
} else if (double.class.equals(javaClass)) {
return DOUBLE;
} else if (char.class.equals(javaClass)) {
return CHAR;
} else if (boolean.class.equals(javaClass)) {
return BOOLEAN;
}
} else if (java.lang.Throwable.class.isAssignableFrom(javaClass)) {
if (java.lang.RuntimeException.class.isAssignableFrom(javaClass)) {
if (java.lang.NullPointerException.class.equals(javaClass)) {
return NULL_POINTER_EXCEPTION;
} else if (java.lang.ClassCastException.class.equals(javaClass)) {
return CLASS_CAST_EXCEPTION;
} else if (java.lang.ArithmeticException.class.equals(javaClass)) {
return ARITHMETIC_EXCEPTION;
} else if (java.lang.UnsupportedOperationException.class.equals(javaClass)) {
return UNSUPPORTED_OPERATION_EXCEPTION;
} else if (java.util.NoSuchElementException.class.equals(javaClass)) {
return NO_SUCH_ELEMENT_EXCEPTION;
} else if (java.lang.ArrayIndexOutOfBoundsException.class.equals(javaClass)) {
return ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION;
} else if (java.lang.StringIndexOutOfBoundsException.class.equals(javaClass)) {
return STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION;
} else if (java.lang.IndexOutOfBoundsException.class.equals(javaClass)) {
return INDEX_OUT_OF_BOUNDS_EXCEPTION;
} else if (java.lang.NumberFormatException.class.equals(javaClass)) {
return NUMBER_FORMAT_EXCEPTION;
} else if (java.lang.IllegalArgumentException.class.equals(javaClass)) {
return ILLEGAL_ARGUMENT_EXCEPTION;
} else if (java.lang.IllegalStateException.class.equals(javaClass)) {
return ILLEGAL_STATE_EXCEPTION;
} else if (java.lang.RuntimeException.class.equals(javaClass)) {
return EXCEPTION;
}
} else if (java.lang.Exception.class.isAssignableFrom(javaClass)) {
if (java.lang.Exception.class.equals(javaClass)) {
return CHECKED_EXCEPTION;
}
} else if (java.lang.Error.class.isAssignableFrom(javaClass)) {
if (java.lang.InternalError.class.equals(javaClass)) {
return INTERNAL_ERROR;
} else if (java.lang.OutOfMemoryError.class.equals(javaClass)) {
return OUT_OF_MEMORY_ERROR;
} else if (java.lang.StackOverflowError.class.equals(javaClass)) {
return STACK_OVERFLOW_ERROR;
} else if (java.lang.AssertionError.class.equals(javaClass)) {
return ASSERTION_ERROR;
} else if (java.lang.Error.class.equals(javaClass)) {
return ERROR;
}
} else {
if (java.lang.Throwable.class.equals(javaClass)) {
return CHECKED_THROWABLE;
}
}
}
return null;
}Example 70
| Project: tinker-master File: AndroidNClassLoader.java View source code |
private static AndroidNClassLoader createAndroidNClassLoader(PathClassLoader original, Application application) throws Exception {
//let all element ""
AndroidNClassLoader androidNClassLoader = new AndroidNClassLoader("", original, application);
Field originPathList = ShareReflectUtil.findField(original, "pathList");
Object originPathListObject = originPathList.get(original);
//should reflect definingContext also
Field originClassloader = ShareReflectUtil.findField(originPathListObject, "definingContext");
originClassloader.set(originPathListObject, androidNClassLoader);
//copy pathList
Field pathListField = ShareReflectUtil.findField(androidNClassLoader, "pathList");
//just use PathClassloader's pathList
pathListField.set(androidNClassLoader, originPathListObject);
//we must recreate dexFile due to dexCache
List<File> additionalClassPathEntries = new ArrayList<>();
Field dexElement = ShareReflectUtil.findField(originPathListObject, "dexElements");
Object[] originDexElements = (Object[]) dexElement.get(originPathListObject);
for (Object element : originDexElements) {
DexFile dexFile = (DexFile) ShareReflectUtil.findField(element, "dexFile").get(element);
if (dexFile == null) {
continue;
}
additionalClassPathEntries.add(new File(dexFile.getName()));
//protect for java.lang.AssertionError: Failed to close dex file in finalizer.
oldDexFiles.add(dexFile);
}
Method makePathElements = ShareReflectUtil.findMethod(originPathListObject, "makePathElements", List.class, File.class, List.class);
ArrayList<IOException> suppressedExceptions = new ArrayList<>();
Object[] newDexElements = (Object[]) makePathElements.invoke(originPathListObject, additionalClassPathEntries, null, suppressedExceptions);
dexElement.set(originPathListObject, newDexElements);
try {
Class.forName(CHECK_CLASSLOADER_CLASS, true, androidNClassLoader);
} catch (Throwable thr) {
Log.e(TAG, "load TinkerTestAndroidNClassLoader fail, try to fixDexElementsForProtectedApp");
fixDexElementsForProtectedApp(application, newDexElements);
}
return androidNClassLoader;
}Example 71
| Project: hbase-master File: SecureBulkLoadProtos.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.prepareBulkLoad(controller, (org.apache.hadoop.hbase.protobuf.generated.ClientProtos.PrepareBulkLoadRequest) request);
case 1:
return impl.secureBulkLoadHFiles(controller, (org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesRequest) request);
case 2:
return impl.cleanupBulkLoad(controller, (org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CleanupBulkLoadRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 72
| Project: glowroot-master File: WeavingClassVisitor.java View source code |
@RequiresNonNull({ "type", "metaHolderInternalName", "loader" })
private void generateMetaHolder() throws Exception {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, metaHolderInternalName, null, "java/lang/Object", null);
Type metaHolderType = Type.getObjectType(metaHolderInternalName);
MethodVisitor mv = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
Label l1 = new Label();
Label l2 = new Label();
mv.visitTryCatchBlock(l0, l1, l2, "java/lang/ClassNotFoundException");
mv.visitLabel(l0);
for (Type classMetaType : classMetaTypes) {
String classMetaInternalName = classMetaType.getInternalName();
String classMetaFieldName = "glowroot$class$meta$" + classMetaInternalName.replace('/', '$');
FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, classMetaFieldName, "L" + classMetaInternalName + ";", null, null);
fv.visitEnd();
mv.visitTypeInsn(NEW, classMetaInternalName);
mv.visitInsn(DUP);
loadType(mv, type, metaHolderType);
mv.visitMethodInsn(INVOKESPECIAL, classMetaInternalName, "<init>", "(Ljava/lang/Class;)V", false);
mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, classMetaFieldName, "L" + classMetaInternalName + ";");
}
for (MethodMetaGroup methodMetaGroup : methodMetaGroups) {
for (Type methodMetaType : methodMetaGroup.methodMetaTypes()) {
String methodMetaInternalName = methodMetaType.getInternalName();
String methodMetaFieldName = "glowroot$method$meta$" + methodMetaGroup.uniqueNum() + '$' + methodMetaInternalName.replace('/', '$');
FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, methodMetaFieldName, "L" + methodMetaInternalName + ";", null, null);
fv.visitEnd();
mv.visitTypeInsn(NEW, methodMetaInternalName);
mv.visitInsn(DUP);
loadType(mv, type, metaHolderType);
mv.visitLdcInsn(methodMetaGroup.methodName());
mv.visitLdcInsn(methodMetaGroup.methodParameterTypes().size());
mv.visitTypeInsn(ANEWARRAY, "java/lang/Class");
for (int i = 0; i < methodMetaGroup.methodParameterTypes().size(); i++) {
mv.visitInsn(DUP);
mv.visitLdcInsn(i);
loadType(mv, methodMetaGroup.methodParameterTypes().get(i), metaHolderType);
mv.visitInsn(AASTORE);
}
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", false);
mv.visitMethodInsn(INVOKESPECIAL, methodMetaInternalName, "<init>", "(Ljava/lang/reflect/Method;)V", false);
mv.visitFieldInsn(PUTSTATIC, metaHolderInternalName, methodMetaFieldName, "L" + methodMetaInternalName + ";");
}
}
// this is just try/catch ClassNotFoundException/re-throw AssertionError
mv.visitLabel(l1);
Label l3 = new Label();
mv.visitJumpInsn(GOTO, l3);
mv.visitLabel(l2);
mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/lang/ClassNotFoundException" });
mv.visitVarInsn(ASTORE, 0);
mv.visitTypeInsn(NEW, "java/lang/AssertionError");
mv.visitInsn(DUP);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", "(Ljava/lang/Object;)V", false);
mv.visitInsn(ATHROW);
mv.visitLabel(l3);
mv.visitFrame(F_SAME, 0, null, 0, null);
mv.visitInsn(RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
cw.visitEnd();
byte[] bytes = cw.toByteArray();
ClassLoaders.defineClass(ClassNames.fromInternalName(metaHolderInternalName), bytes, loader);
}Example 73
| Project: JFramework-master File: JAssertion.java View source code |
//endregion
//region JAssertion - Public Methods Section
/**
* Executes the assert lifecycle.
*
* <ul>
* <li>fires the event {@linkplain #onBeforeAssert(JAssert)}</li>
* <li>executes the assert by calling {@linkplain #executeAssert(JAssert)} under try/catch clause</li>
* <li>if the assert evaluated successfully, no <b>AssertionError</b> is thrown.
* calling to {@linkplain #onAssertSuccess(JAssert)}
* </li>
* <li><b>AssertionError</b> is caught. calling to {@linkplain #onAssertFailure(JAssert, AssertionError)}</li>
* <li>using the clause finally, fires the event {@linkplain #onAfterAssert(JAssert)}</li>
* </ul>
*
* @param assertCommand assertCommand the assertion command, with the checkpoint details.
*
* @see java.lang.AssertionError
* @see com.framework.asserts.JAssert
*/
protected void doAssert(JAssert assertCommand) {
this.assertCommand = assertCommand;
onBeforeAssert(assertCommand);
try {
executeAssert(assertCommand);
onAssertSuccess(assertCommand);
} catch (AssertionError ex) {
onAssertFailure(assertCommand, ex);
throw ex;
} finally {
onAfterAssert(assertCommand);
}
}Example 74
| Project: gauge-java-master File: StepExecutionStageTest.java View source code |
public void testStepMethodExecutionWithCOFOnAssertionFailure() throws Exception {
Messages.ExecuteStepRequest executeStepRequest = Messages.ExecuteStepRequest.newBuilder().setParsedStepText("hello").setActualStepText("hello").build();
StepExecutionStage executionStage = new StepExecutionStage(executeStepRequest, new ClassInstanceManager());
MethodExecutor methodExecutor = new MethodExecutor(new ClassInstanceManager());
Method fooMethod = this.getClass().getMethod("bar");
Spec.ProtoExecutionResult result = executionStage.executeStepMethod(methodExecutor, fooMethod);
assertEquals(true, result.getFailed());
assertEquals(true, result.getRecoverableError());
assertEquals("java.lang.AssertionError: assertion failed", result.getErrorMessage());
}Example 75
| Project: wildfly-master File: ObjectStoreTypeTestCase.java View source code |
/*
* Checks that using two different storage mechanisms, within a
* batch, make the batch fails.
*
* See https://issues.jboss.org/browse/WFLY-8335 for more information
*/
@Test(expected = java.lang.AssertionError.class)
public void testBatchCliFailsIfNoDSisDefined() throws IOException {
createDataSource();
cli.sendLine("batch");
cli.sendLine("/subsystem=transactions:write-attribute(name=use-journal-store,value=true)");
cli.sendLine("/subsystem=transactions:write-attribute(name=jdbc-store-datasource, value=java:jboss/datasources/" + JDBC_STORE_DS_NAME + ")");
cli.sendLine("/subsystem=transactions:write-attribute(name=use-jdbc-store,value=true)");
cli.sendLine("run-batch");
}Example 76
| Project: durian-master File: ErrorsExample.java View source code |
public void whereDoLogAndDialogComeFrom() {
// Errors.log() promises to "log", and Errors.dialog() promises to alert the user.
// Doing those things is very different depending on whether your code is running as a web
// application, console application, or desktop gui
// One way around this ambiguity is to avoid using Errors.log() and Errors.dialog()
// entirely, and only use your own custom Errors. But if you are shipping a framework,
// and your users might end up using Errors.log() and .dialog(), then you might want to
// specify what those do.
// By default, Errors.log() is just Throwable.printStackTrace, and Errors.dialog()
// opens a JOptionPane. You can modify this behavior with the following:
DurianPlugins.register(Errors.Plugins.Log.class, error -> {
});
DurianPlugins.register(Errors.Plugins.Dialog.class, error -> {
});
// The trick is, you have to call these methods BEFORE Errors.log() or Errors.dialog()
// are used anywhere in your whole application. Once log() or dialog() have been used, they are
// fixed for the duration of the runtime. If you're writing a library, then you probably shouldn't
// try to change them. If you're writing an application or framework, then you probably should.
// If you're running in a JUnit environment, then you probably want any call to log() or dialog()
// to kill the test. Setting the following system properties (again, before log() or dialog() are
// called) will cause any errors to get wrapped and thrown as a java.lang.AssertionError.
System.setProperty("durian.plugins.com.diffplug.common.base.Errors.Plugins.Log", "com.diffplug.common.base.Errors$Plugins$OnErrorThrowAssertion");
System.setProperty("durian.plugins.com.diffplug.common.base.Errors.Plugins.Dialog", "com.diffplug.common.base.Errors$Plugins$OnErrorThrowAssertion");
}Example 77
| Project: openjdk-master File: StringConcatFactory.java View source code |
private static MethodHandle generate(Lookup lookup, String className, MethodType args, Recipe recipe, Mode mode) throws Exception {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_PUBLIC + ACC_FINAL + ACC_SYNTHETIC, // Unsafe.defineAnonymousClass would append an unique ID
className, null, "java/lang/Object", null);
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC + ACC_FINAL, METHOD_NAME, args.toMethodDescriptorString(), null, null);
mv.visitAnnotation("Ljdk/internal/vm/annotation/ForceInline;", true);
mv.visitCode();
Class<?>[] arr = args.parameterArray();
boolean[] guaranteedNonNull = new boolean[arr.length];
if (mode.isExact()) {
/*
In exact mode, we need to convert all arguments to their String representations,
as this allows to compute their String sizes exactly. We cannot use private
methods for primitives in here, therefore we need to convert those as well.
We also record what arguments are guaranteed to be non-null as the result
of the conversion. String.valueOf does the null checks for us. The only
corner case to take care of is String.valueOf(Object) returning null itself.
Also, if any conversion happened, then the slot indices in the incoming
arguments are not equal to the final local maps. The only case this may break
is when converting 2-slot long/double argument to 1-slot String. Therefore,
we get away with tracking modified offset, since no conversion can overwrite
the upcoming the argument.
*/
int off = 0;
int modOff = 0;
for (int c = 0; c < arr.length; c++) {
Class<?> cl = arr[c];
if (cl == String.class) {
if (off != modOff) {
mv.visitIntInsn(getLoadOpcode(cl), off);
mv.visitIntInsn(ASTORE, modOff);
}
} else {
mv.visitIntInsn(getLoadOpcode(cl), off);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf", getStringValueOfDesc(cl), false);
mv.visitIntInsn(ASTORE, modOff);
arr[c] = String.class;
guaranteedNonNull[c] = cl.isPrimitive();
}
off += getParameterSize(cl);
modOff += getParameterSize(String.class);
}
}
if (mode.isSized()) {
/*
When operating in sized mode (this includes exact mode), it makes sense to make
StringBuilder append chains look familiar to OptimizeStringConcat. For that, we
need to do null-checks early, not make the append chain shape simpler.
*/
int off = 0;
for (RecipeElement el : recipe.getElements()) {
switch(el.getTag()) {
case TAG_CONST:
// Guaranteed non-null, no null check required.
break;
case TAG_ARG:
// Null-checks are needed only for String arguments, and when a previous stage
// did not do implicit null-checks. If a String is null, we eagerly replace it
// with "null" constant. Note, we omit Objects here, because we don't call
// .length() on them down below.
int ac = el.getArgPos();
Class<?> cl = arr[ac];
if (cl == String.class && !guaranteedNonNull[ac]) {
Label l0 = new Label();
mv.visitIntInsn(ALOAD, off);
mv.visitJumpInsn(IFNONNULL, l0);
mv.visitLdcInsn("null");
mv.visitIntInsn(ASTORE, off);
mv.visitLabel(l0);
}
off += getParameterSize(cl);
break;
default:
throw new StringConcatException("Unhandled tag: " + el.getTag());
}
}
}
// Prepare StringBuilder instance
mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
mv.visitInsn(DUP);
if (mode.isSized()) {
/*
Sized mode requires us to walk through the arguments, and estimate the final length.
In exact mode, this will operate on Strings only. This code would accumulate the
final length on stack.
*/
int len = 0;
int off = 0;
mv.visitInsn(ICONST_0);
for (RecipeElement el : recipe.getElements()) {
switch(el.getTag()) {
case TAG_CONST:
Object cnst = el.getValue();
len += cnst.toString().length();
break;
case TAG_ARG:
/*
If an argument is String, then we can call .length() on it. Sized/Exact modes have
converted arguments for us. If an argument is primitive, we can provide a guess
for its String representation size.
*/
Class<?> cl = arr[el.getArgPos()];
if (cl == String.class) {
mv.visitIntInsn(ALOAD, off);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "length", "()I", false);
mv.visitInsn(IADD);
} else if (cl.isPrimitive()) {
len += estimateSize(cl);
}
off += getParameterSize(cl);
break;
default:
throw new StringConcatException("Unhandled tag: " + el.getTag());
}
}
// Constants have non-zero length, mix in
if (len > 0) {
iconst(mv, len);
mv.visitInsn(IADD);
}
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(I)V", false);
} else {
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
}
// At this point, we have a blank StringBuilder on stack, fill it in with .append calls.
{
int off = 0;
for (RecipeElement el : recipe.getElements()) {
String desc;
switch(el.getTag()) {
case TAG_CONST:
Object cnst = el.getValue();
mv.visitLdcInsn(cnst);
desc = getSBAppendDesc(cnst.getClass());
break;
case TAG_ARG:
Class<?> cl = arr[el.getArgPos()];
mv.visitVarInsn(getLoadOpcode(cl), off);
off += getParameterSize(cl);
desc = getSBAppendDesc(cl);
break;
default:
throw new StringConcatException("Unhandled tag: " + el.getTag());
}
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", desc, false);
}
}
if (DEBUG && mode.isExact()) {
/*
Exactness checks compare the final StringBuilder.capacity() with a resulting
String.length(). If these values disagree, that means StringBuilder had to perform
storage trimming, which defeats the purpose of exact strategies.
*/
/*
The logic for this check is as follows:
Stack before: Op:
(SB) dup, dup
(SB, SB, SB) capacity()
(int, SB, SB) swap
(SB, int, SB) toString()
(S, int, SB) length()
(int, int, SB) if_icmpeq
(SB) <end>
Note that it leaves the same StringBuilder on exit, like the one on enter.
*/
mv.visitInsn(DUP);
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "capacity", "()I", false);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "length", "()I", false);
Label l0 = new Label();
mv.visitJumpInsn(IF_ICMPEQ, l0);
mv.visitTypeInsn(NEW, "java/lang/AssertionError");
mv.visitInsn(DUP);
mv.visitLdcInsn("Failed exactness check");
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", "(Ljava/lang/Object;)V", false);
mv.visitInsn(ATHROW);
mv.visitLabel(l0);
}
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
mv.visitInsn(ARETURN);
mv.visitMaxs(-1, -1);
mv.visitEnd();
cw.visitEnd();
byte[] classBytes = cw.toByteArray();
try {
Class<?> hostClass = lookup.lookupClass();
Class<?> innerClass = UNSAFE.defineAnonymousClass(hostClass, classBytes, null);
UNSAFE.ensureClassInitialized(innerClass);
dumpIfEnabled(innerClass.getName(), classBytes);
return Lookup.IMPL_LOOKUP.findStatic(innerClass, METHOD_NAME, args);
} catch (Exception e) {
dumpIfEnabled(className + "$$FAILED", classBytes);
throw new StringConcatException("Exception while spinning the class", e);
}
}Example 78
| Project: jsystem-master File: JUnitTestRunner.java View source code |
public void addError(Test test, Throwable t) {
if (junit4 && t instanceof AssertionFailedError) {
// JUnit 4 does not distinguish between errors and failures
// even in the JUnit 3 adapter.
// So we need to help it a bit to retain compatibility for JUnit 3 tests.
testListener.addFailure(test, (AssertionFailedError) t);
} else if (junit4 && t.getClass().getName().equals("java.lang.AssertionError")) {
// We would prefer to show "failure" for things that logically are.
try {
String msg = t.getMessage();
AssertionFailedError failure = msg != null ? new AssertionFailedError(msg) : new AssertionFailedError();
// To compile on pre-JDK 4 (even though this should always succeed):
Method initCause = Throwable.class.getMethod("initCause", new Class[] { Throwable.class });
initCause.invoke(failure, new Object[] { t });
testListener.addFailure(test, failure);
} catch (Exception e) {
e.printStackTrace();
testListener.addError(test, t);
}
} else {
testListener.addError(test, t);
}
}Example 79
| Project: example-projects-master File: ServerMarshallingFactoryImpl.java View source code |
public AssertionError demarshall(EJValue a0, MarshallingSession a1) { try { if (a0.isNull()) { return null; } EJObject obj = a0.isObject(); String objId = obj.get("^ObjectID").isString().stringValue(); if (a1.hasObjectHash(objId)) { return a1.getObject(AssertionError.class, objId); } AssertionError entity = new AssertionError(java_lang_String.demarshall(obj.get("message"), a1)); a1.recordObjectHash(objId, entity); if ((obj.containsKey("cause")) && (!obj.get("cause").isNull())) { entity.initCause(java_lang_Throwable.demarshall(obj.get("cause"), a1)); } if ((obj.containsKey("stackTrace")) && (!obj.get("stackTrace").isNull())) { entity.setStackTrace((StackTraceElement[]) arrayOf_java_lang_StackTraceElement_D1.demarshall(obj.get("stackTrace"), a1)); } return entity; } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("error demarshalling entity: java.lang.AssertionError", t); } }
Example 80
| Project: WaveInCloud-master File: Diff.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.fetch(controller, (org.waveprotocol.wave.diff.Diff.FetchDiffRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 81
| Project: fedone-master File: WaveClientRpc.java View source code |
public final com.google.protobuf.Message callBlockingMethod(com.google.protobuf.Descriptors.MethodDescriptor method, com.google.protobuf.RpcController controller, com.google.protobuf.Message request) throws com.google.protobuf.ServiceException {
if (method.getService() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("Service.callBlockingMethod() given method descriptor for " + "wrong service type.");
}
switch(method.getIndex()) {
case 0:
return impl.open(controller, (org.waveprotocol.wave.examples.fedone.waveserver.WaveClientRpc.ProtocolOpenRequest) request);
case 1:
return impl.submit(controller, (org.waveprotocol.wave.examples.fedone.waveserver.WaveClientRpc.ProtocolSubmitRequest) request);
default:
throw new java.lang.AssertionError("Can't get here.");
}
}Example 82
| Project: uml-auto-assessment-master File: ExecServer.java View source code |
/**
* Execute a JUnit test method and return the result.<p>
*
* The array returned in case of failure or error contains:<br>
* [0] = the runtime in milliseconds expressed as a decimal integer
* [1] = the exception message (or "no exception message")<br>
* [2] = the stack trace as a string (or "no stack trace")<br>
* [3] = the name of the class in which the exception/failure occurred<br>
* [4] = the source filename for where the exception/failure occurred<br>
* [5] = the name of the method in which the exception/failure occurred<br>
* [6] = the line number where the exception/failure occurred (a string)<br>
* [7] = "failure" or "error" (string)<br>
*
* The array returned in case of success contains:<br>
* [0] = the runtime in milliseconds expressed as a decimal integer
*
* @return an array of length 8 on test failure/error, or of length 1 if the test passed
*/
private static Object[] runTestMethod(String className, String methodName) {
Class<?> cl = loadAndInitClass(className);
Result res = (new JUnitCore()).run(Request.method(cl, methodName));
if (res.wasSuccessful()) {
Object result[] = new Object[1];
result[0] = String.valueOf(res.getRunTime());
return result;
} else {
Object result[] = new Object[8];
List<Failure> failures = res.getFailures();
for (Iterator<Failure> iterator = failures.iterator(); iterator.hasNext(); ) {
Failure failure = iterator.next();
if (failure.getException().getClass() == java.lang.AssertionError.class || failure.getException().getClass() == junit.framework.AssertionFailedError.class) {
result[7] = "failure";
} else {
result[7] = "error";
}
result[0] = String.valueOf(res.getRunTime());
result[1] = failure.getMessage() != null ? failure.getMessage() : "no exception message";
result[2] = failure.getTrace() != null ? failure.getTrace() : "no trace";
// search the stack trace backward until finding a class not
// part of the org.junit framework
StackTraceElement[] ste = failure.getException().getStackTrace();
int i = 0;
while (i < ste.length && ste[i].getClassName().startsWith("org.junit.")) {
i++;
}
result[3] = ste[i].getClassName();
result[4] = ste[i].getFileName();
result[5] = ste[i].getMethodName();
result[6] = String.valueOf(ste[i].getLineNumber());
}
return result;
}
}Example 83
| Project: testng-plugin-plugin-master File: MethodResultTest.java View source code |
/**
* Testing method result view with data provider tests that pass/fail
* @throws Exception
*/
@Test
public void testMethodResults_dataProviderTests() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
Publisher publisher = new Publisher();
publisher.setReportFilenamePattern("testng.xml");
p.getPublishersList().add(publisher);
//to setup project action
p.onCreatedFromScratch();
p.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
String contents = CommonUtil.getContents(Constants.TESTNG_XML_DATAPROVIDER);
build.getWorkspace().child("testng.xml").write(contents, "UTF-8");
return true;
}
});
//run build
FreeStyleBuild build = p.scheduleBuild2(0).get();
//Compare output for a dp method that failed
String urlPrefix = build.getUrl() + PluginImpl.URL;
JenkinsRule.WebClient wc = r.createWebClient();
HtmlPage page = wc.goTo(urlPrefix + "/org.jenkins/TestDataProvider/test/");
//method status information
HtmlElement element = page.getElementById("status", true);
assertEquals("result-failed", element.getAttribute("class"));
assertEquals("FAIL", element.getTextContent());
//this method has single parameter
element = page.getElementById("params", true);
String contents = element.getTextContent();
r.assertStringContains(contents, "Parameter #1");
r.assertStringContains(contents, "Value");
assertFalse(contents.contains("Parameter #2"));
//this method has no groups or reporter output
assertNull(page.getElementById("groups"));
assertNull(page.getElementById("reporter-output"));
//this method has exception with no message
element = (HtmlElement) page.getElementsByTagName("h3").get(0);
assertEquals("Exception java.lang.AssertionError", element.getTextContent());
element = page.getElementById("exp-msg", true);
r.assertStringContains(element.getTextContent(), "(none)");
element = page.getElementById("exp-st", true);
r.assertStringContains(element.getTextContent(), "org.jenkins.TestDataProvider.test(TestDataProvider.java:15)");
//compare output for a dp method that passed
page = wc.goTo(urlPrefix + "/org.jenkins/TestDataProvider/test_2/");
//method status information
element = page.getElementById("status", true);
assertEquals("result-passed", element.getAttribute("class"));
assertEquals("PASS", element.getTextContent());
//this method has single parameter
element = page.getElementById("params", true);
contents = element.getTextContent();
r.assertStringContains(contents, "Parameter #1");
r.assertStringContains(contents, "2");
assertFalse(contents.contains("Parameter #2"));
assertNull(page.getElementById("inst-name"));
assertNull(page.getElementById("groups"));
assertNull(page.getElementById("reporter-output"));
assertNull(page.getElementById("exp-msg"));
assertNull(page.getElementById("exp-st"));
}Example 84
| Project: helios-master File: TemporaryJob.java View source code |
void verifyHealthy() throws AssertionError {
log.debug("Checking health of {}", job.getImage());
final JobStatus status = Futures.getUnchecked(client.jobStatus(job.getId()));
if (status == null) {
return;
}
for (final Map.Entry<String, TaskStatus> entry : status.getTaskStatuses().entrySet()) {
verifyHealthy(entry.getKey(), entry.getValue());
}
}Example 85
| Project: error-prone-master File: TryFailThrowable.java View source code |
@Override
public boolean matches(ExpressionTree item, VisitorState state) {
if (item.getKind() != METHOD_INVOCATION) {
return false;
}
Symbol sym = getSymbol(item);
if (!(sym instanceof MethodSymbol)) {
throw new IllegalArgumentException("not a method call");
}
if (!sym.isStatic()) {
return false;
}
String methodName = sym.getQualifiedName().toString();
String className = sym.owner.getQualifiedName().toString();
// TODO(cpovirk): Look for literal "throw new AssertionError()," etc.
return (methodName.startsWith("assert") || methodName.startsWith("fail")) && (className.equals("org.junit.Assert") || className.equals("junit.framework.Assert") || className.equals("junit.framework.TestCase") || className.endsWith("MoreAsserts"));
}Example 86
| Project: kotlin-master File: GenerateMockJdk.java View source code |
private static void generateFilteredJar(File source, File target, Set<String> entryNamesToInclude, boolean assertAllFound) throws IOException {
if (!source.exists()) {
throw new AssertionError(source + " doesn't exist");
}
JarFile sourceJar = new JarFile(source);
JarOutputStream targetJar = new JarOutputStream(new FileOutputStream(target));
List<String> foundEntries = Lists.newArrayList();
List<JarEntry> sourceList = Collections.list(sourceJar.entries());
for (JarEntry entry : sourceList) {
// For Map$Entry.class we want to check Map.class presense
String topLevelClassFile = entry.getName().replaceAll("\\$.+\\.class$", ".class");
if (entryNamesToInclude.contains(topLevelClassFile)) {
targetJar.putNextEntry(new ZipEntry(entry.getName()));
FileUtil.copy(sourceJar.getInputStream(entry), targetJar);
foundEntries.add(topLevelClassFile);
}
}
targetJar.close();
sourceJar.close();
if (assertAllFound) {
HashSet<String> notFound = Sets.newHashSet(entryNamesToInclude);
notFound.removeAll(foundEntries);
if (!notFound.isEmpty()) {
System.err.println("Not found:");
for (String entry : notFound) {
System.err.println(entry);
}
throw new AssertionError("See errors above");
}
}
}Example 87
| Project: groovypp-master File: StaticCompiler.java View source code |
@Override
public void visitAssertStatement(AssertStatement statement) {
visitStatement(statement);
Label noError = new Label();
BytecodeExpr condition = transformLogical(statement.getBooleanExpression().getExpression(), noError, true);
Expression msg = statement.getMessageExpression();
if (msg instanceof ConstantExpression && ((ConstantExpression) msg).getValue() == null)
msg = new ConstantExpression("\n" + su.getSample(statement.getLineNumber(), 0, null));
BytecodeExpr msgExpr = (BytecodeExpr) transform(msg);
condition.visit(mv);
mv.visitTypeInsn(NEW, "java/lang/AssertionError");
mv.visitInsn(DUP);
if (msgExpr != null)
msgExpr.visit(mv);
else
mv.visitLdcInsn("<no message>");
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/AssertionError", "<init>", "(Ljava/lang/Object;)V");
mv.visitInsn(ATHROW);
mv.visitLabel(noError);
}Example 88
| Project: calcite-master File: RuleQueue.java View source code |
/**
* Removes the rule match with the highest importance, and returns it.
*
* <p>Returns {@code null} if there are no more matches.</p>
*
* <p>Note that the VolcanoPlanner may still decide to reject rule matches
* which have become invalid, say if one of their operands belongs to an
* obsolete set or has importance=0.
*
* @throws java.lang.AssertionError if this method is called with a phase
* previously marked as completed via
* {@link #phaseCompleted(VolcanoPlannerPhase)}.
*/
VolcanoRuleMatch popMatch(VolcanoPlannerPhase phase) {
dump();
PhaseMatchList phaseMatchList = matchListMap.get(phase);
if (phaseMatchList == null) {
throw new AssertionError("Used match list for phase " + phase + " after phase complete");
}
final List<VolcanoRuleMatch> matchList = phaseMatchList.list;
VolcanoRuleMatch match;
for (; ; ) {
if (matchList.isEmpty()) {
return null;
}
if (LOGGER.isTraceEnabled()) {
Collections.sort(matchList, MATCH_COMPARATOR);
match = matchList.remove(0);
StringBuilder b = new StringBuilder();
b.append("Sorted rule queue:");
for (VolcanoRuleMatch match2 : matchList) {
final double importance = match2.computeImportance();
b.append("\n");
b.append(match2);
b.append(" importance ");
b.append(importance);
}
LOGGER.trace(b.toString());
} else {
// If we're not tracing, it's not worth the effort of sorting the
// list to find the minimum.
match = null;
int bestPos = -1;
int i = -1;
for (VolcanoRuleMatch match2 : matchList) {
++i;
if (match == null || MATCH_COMPARATOR.compare(match2, match) < 0) {
bestPos = i;
match = match2;
}
}
match = matchList.remove(bestPos);
}
if (skipMatch(match)) {
LOGGER.debug("Skip match: {}", match);
} else {
break;
}
}
// A rule match's digest is composed of the operand RelNodes' digests,
// which may have changed if sets have merged since the rule match was
// enqueued.
match.recomputeDigest();
phaseMatchList.matchMap.remove(planner.getSubset(match.rels[0]), match);
LOGGER.debug("Pop match: {}", match);
return match;
}Example 89
| Project: bazel-master File: JUnit4RunnerTest.java View source code |
@Test
public void testFailingTest() throws Exception {
config = createConfig();
mockRunListener = mock(RunListener.class);
JUnit4Runner runner = createRunner(SampleFailingTest.class);
Description testDescription = Description.createTestDescription(SampleFailingTest.class, "testThatAlwaysFails");
Description suiteDescription = Description.createSuiteDescription(SampleFailingTest.class);
suiteDescription.addChild(testDescription);
Result result = runner.run();
assertEquals(1, result.getRunCount());
assertEquals(1, result.getFailureCount());
assertEquals(0, result.getIgnoreCount());
assertTrue(extractOutput(stdoutByteStream).contains("1) testThatAlwaysFails(" + SampleFailingTest.class.getName() + ")\n" + "java.lang.AssertionError: expected"));
InOrder inOrder = inOrder(mockRunListener);
inOrder.verify(mockRunListener).testRunStarted(any(Description.class));
inOrder.verify(mockRunListener).testStarted(any(Description.class));
inOrder.verify(mockRunListener).testFailure(any(Failure.class));
inOrder.verify(mockRunListener).testFinished(any(Description.class));
inOrder.verify(mockRunListener).testRunFinished(any(Result.class));
}Example 90
| Project: HDPDeviceAdapter-master File: HDPHealthManagerService.java View source code |
private synchronized int insert_context(BluetoothDevice dev) {
String addr = dev.getAddress();
if (addr_ctx.containsKey(addr)) {
throw new AssertionError("Trying to reinsert context for " + addr);
}
int context = new_context();
ctx_dev.put(context, dev);
addr_ctx.put(addr, context);
path_ctx.put(PATH_PREFIX + context, context);
return context;
}Example 91
| Project: atlas-master File: NClassLoader.java View source code |
public static void replacePathClassLoader(Context base, ClassLoader original) throws Exception {
NClassLoader loader = new NClassLoader(".", original.getParent());
Field pathListField = findField(original, "pathList");
pathListField.setAccessible(true);
Object originPathListObject = pathListField.get(original);
Field definingContextField = findField(originPathListObject, "definingContext");
definingContextField.set(originPathListObject, loader);
Field loadPathList = findField(loader, "pathList");
//just use PathClassloader's pathList
loadPathList.set(loader, originPathListObject);
//we must recreate dexFile due to dexCache
List<File> additionalClassPathEntries = new ArrayList<File>();
Field dexElement = findField(originPathListObject, "dexElements");
Object[] originDexElements = (Object[]) dexElement.get(originPathListObject);
for (Object element : originDexElements) {
DexFile dexFile = (DexFile) findField(element, "dexFile").get(element);
additionalClassPathEntries.add(new File(dexFile.getName()));
//protect for java.lang.AssertionError: Failed to close dex file in finalizer.
// oldDexFiles.add(dexFile);
}
Method makePathElements = findMethod(originPathListObject, "makePathElements", List.class, File.class, List.class);
ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
Object[] newDexElements = (Object[]) makePathElements.invoke(originPathListObject, additionalClassPathEntries, null, suppressedExceptions);
dexElement.set(originPathListObject, newDexElements);
Field mPackageInfoField = base.getClass().getDeclaredField("mPackageInfo");
mPackageInfoField.setAccessible(true);
Object loadedApk = mPackageInfoField.get(base);
Field classloaderField = loadedApk.getClass().getDeclaredField("mClassLoader");
classloaderField.setAccessible(true);
classloaderField.set(loadedApk, loader);
Thread.currentThread().setContextClassLoader(loader);
}Example 92
| Project: thucydides-master File: WhenRunningStepsThroughAScenarioProxy.java View source code |
@Test
public void the_proxy_should_notify_listeners_with_a_description_and_a_cause_when_a_step_fails() {
SimpleTestScenarioSteps steps = factory.getStepLibraryFor(SimpleTestScenarioSteps.class);
steps.failing_step();
ArgumentCaptor<StepFailure> argument = ArgumentCaptor.forClass(StepFailure.class);
verify(listener).stepFailed(argument.capture());
assertThat(argument.getValue().getDescription().getStepClass().getName(), is(SimpleTestScenarioSteps.class.getName()));
assertThat(argument.getValue().getDescription().getName(), is("failing_step"));
assertThat(argument.getValue().getException().getClass().getName(), is(AssertionError.class.getName()));
verify(listener, times(1)).stepFailed(any(StepFailure.class));
}Example 93
| Project: eclipse.jdt.core-master File: CodeStream.java View source code |
public void invokeJavaLangAssertionErrorConstructor(int typeBindingID) {
//$NON-NLS-1$
if (DEBUG)
System.out.println(position + "\t\tinvokespecial: java.lang.AssertionError.<init>(typeBindingID)V");
countLabels = 0;
if (classFileOffset + 2 >= bCodeStream.length) {
resizeByteArray();
}
position++;
bCodeStream[classFileOffset++] = OPC_invokespecial;
writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionErrorConstructor(typeBindingID));
stackDepth -= 2;
}Example 94
| Project: gluu-opendj-master File: DbHandlerTest.java View source code |
/**
* Test the logic that manages counter records in the DbHandler in order to
* optimize the counting of record in the replication changelog db.
* @throws Exception
*/
@Test(enabled = true, groups = { "opendj-256" })
void testDbCounts() throws Exception {
// FIXME: for some reason this test is always failing in Jenkins when run as
// part of the unit tests. Here is the output (the failure is 100%
// reproducible and always has the same value of 3004):
//
// Failed Test:
// org.opends.server.replication.server.DbHandlerTest#testDbCounts
// [testng] Failure Cause: java.lang.AssertionError: AFTER PURGE
// expected:<8000> but was:<3004>
// [testng] org.testng.Assert.fail(Assert.java:84)
// [testng] org.testng.Assert.failNotEquals(Assert.java:438)
// [testng] org.testng.Assert.assertEquals(Assert.java:108)
// [testng] org.testng.Assert.assertEquals(Assert.java:323)
// [testng]
// org.opends.server.replication.server.DbHandlerTest.testDBCount(DbHandlerTest.java:594)
// [testng]
// org.opends.server.replication.server.DbHandlerTest.testDbCounts(DbHandlerTest.java:389)
// It's worth testing with 2 different setting for counterRecord
// - a counter record is put every 10 Update msg in the db - just a unit
// setting.
// - a counter record is put every 1000 Update msg in the db - something
// closer to real setting.
// In both cases, we want to test the counting algorithm,
// - when start and stop are before the first counter record,
// - when start and stop are before and after the first counter record,
// - when start and stop are after the first counter record,
// - when start and stop are before and after more than one counter record,
// After a purge.
// After shutdowning/closing and reopening the db.
testDBCount(40, 10);
testDBCount(4000, 1000);
}Example 95
| Project: h2database-master File: TestMVTableEngine.java View source code |
private void testDataTypes() throws Exception {
deleteDb(getTestName());
String dbName = getTestName() + ";MV_STORE=TRUE";
Connection conn = getConnection(dbName);
Statement stat = conn.createStatement();
stat.execute("create table test(id int primary key, " + "vc varchar," + "ch char(10)," + "bo boolean," + "by tinyint," + "sm smallint," + "bi bigint," + "de decimal," + "re real," + "do double," + "ti time," + "da date," + "ts timestamp," + "bin binary," + "uu uuid," + "bl blob," + "cl clob)");
stat.execute("insert into test values(1000, '', '', null, 0, 0, 0, " + "9, 2, 3, '10:00:00', '2001-01-01', " + "'2010-10-10 10:10:10', x'00', 0, x'b1', 'clob')");
stat.execute("insert into test values(1, 'vc', 'ch', true, 8, 16, 64, " + "123.00, 64.0, 32.0, '10:00:00', '2001-01-01', " + "'2010-10-10 10:10:10', x'00', 0, x'b1', 'clob')");
stat.execute("insert into test values(-1, " + "'quite a long string ሴ ÿ', 'ch', false, -8, -16, -64, " + "0, 0, 0, '10:00:00', '2001-01-01', " + "'2010-10-10 10:10:10', SECURE_RAND(100), 0, x'b1', 'clob')");
stat.execute("insert into test values(-1000, space(1000), 'ch', " + "false, -8, -16, -64, " + "1, 1, 1, '10:00:00', '2001-01-01', " + "'2010-10-10 10:10:10', SECURE_RAND(100), 0, x'b1', 'clob')");
if (!config.memory) {
conn.close();
conn = getConnection(dbName);
stat = conn.createStatement();
}
ResultSet rs;
rs = stat.executeQuery("select * from test order by id desc");
rs.next();
assertEquals(1000, rs.getInt(1));
assertEquals("", rs.getString(2));
assertEquals("", rs.getString(3));
assertFalse(rs.getBoolean(4));
assertEquals(0, rs.getByte(5));
assertEquals(0, rs.getShort(6));
assertEquals(0, rs.getLong(7));
assertEquals("9", rs.getBigDecimal(8).toString());
assertEquals(2d, rs.getDouble(9));
assertEquals(3d, rs.getFloat(10));
assertEquals("10:00:00", rs.getString(11));
assertEquals("2001-01-01", rs.getString(12));
assertEquals("2010-10-10 10:10:10.0", rs.getString(13));
assertEquals(1, rs.getBytes(14).length);
assertEquals("00000000-0000-0000-0000-000000000000", rs.getString(15));
assertEquals(1, rs.getBytes(16).length);
assertEquals("clob", rs.getString(17));
rs.next();
assertEquals(1, rs.getInt(1));
assertEquals("vc", rs.getString(2));
assertEquals("ch", rs.getString(3));
assertTrue(rs.getBoolean(4));
assertEquals(8, rs.getByte(5));
assertEquals(16, rs.getShort(6));
assertEquals(64, rs.getLong(7));
assertEquals("123.00", rs.getBigDecimal(8).toString());
assertEquals(64d, rs.getDouble(9));
assertEquals(32d, rs.getFloat(10));
assertEquals("10:00:00", rs.getString(11));
assertEquals("2001-01-01", rs.getString(12));
assertEquals("2010-10-10 10:10:10.0", rs.getString(13));
assertEquals(1, rs.getBytes(14).length);
assertEquals("00000000-0000-0000-0000-000000000000", rs.getString(15));
assertEquals(1, rs.getBytes(16).length);
assertEquals("clob", rs.getString(17));
rs.next();
assertEquals(-1, rs.getInt(1));
assertEquals("quite a long string ሴ ÿ", rs.getString(2));
assertEquals("ch", rs.getString(3));
assertFalse(rs.getBoolean(4));
assertEquals(-8, rs.getByte(5));
assertEquals(-16, rs.getShort(6));
assertEquals(-64, rs.getLong(7));
assertEquals("0", rs.getBigDecimal(8).toString());
assertEquals(0.0d, rs.getDouble(9));
assertEquals(0.0d, rs.getFloat(10));
assertEquals("10:00:00", rs.getString(11));
assertEquals("2001-01-01", rs.getString(12));
assertEquals("2010-10-10 10:10:10.0", rs.getString(13));
assertEquals(100, rs.getBytes(14).length);
assertEquals("00000000-0000-0000-0000-000000000000", rs.getString(15));
assertEquals(1, rs.getBytes(16).length);
assertEquals("clob", rs.getString(17));
rs.next();
assertEquals(-1000, rs.getInt(1));
assertEquals(1000, rs.getString(2).length());
assertEquals("ch", rs.getString(3));
assertFalse(rs.getBoolean(4));
assertEquals(-8, rs.getByte(5));
assertEquals(-16, rs.getShort(6));
assertEquals(-64, rs.getLong(7));
assertEquals("1", rs.getBigDecimal(8).toString());
assertEquals(1.0d, rs.getDouble(9));
assertEquals(1.0d, rs.getFloat(10));
assertEquals("10:00:00", rs.getString(11));
assertEquals("2001-01-01", rs.getString(12));
assertEquals("2010-10-10 10:10:10.0", rs.getString(13));
assertEquals(100, rs.getBytes(14).length);
assertEquals("00000000-0000-0000-0000-000000000000", rs.getString(15));
assertEquals(1, rs.getBytes(16).length);
assertEquals("clob", rs.getString(17));
stat.execute("drop table test");
stat.execute("create table test(id int, obj object, " + "rs result_set, arr array, ig varchar_ignorecase)");
PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?, ?, ?, ?)");
prep.setInt(1, 1);
prep.setObject(2, new java.lang.AssertionError());
prep.setObject(3, stat.executeQuery("select 1 from dual"));
prep.setObject(4, new Object[] { 1, 2 });
prep.setObject(5, "test");
prep.execute();
prep.setInt(1, 1);
prep.setObject(2, new java.lang.AssertionError());
prep.setObject(3, stat.executeQuery("select 1 from dual"));
prep.setObject(4, new Object[] { new BigDecimal(new String(new char[1000]).replace((char) 0, '1')) });
prep.setObject(5, "test");
prep.execute();
if (!config.memory) {
conn.close();
conn = getConnection(dbName);
stat = conn.createStatement();
}
stat.execute("select * from test");
rs = stat.executeQuery("script");
int count = 0;
while (rs.next()) {
count++;
}
assertTrue(count < 10);
stat.execute("drop table test");
conn.close();
}Example 96
| Project: apkinspector-master File: JimpleBodyBuilder.java View source code |
/*class LabelKey{
public LabelKey(String label, soot.jimple.Stmt noop){
this.label = label;
this.noop = noop;
}
private String label;
public String label(){
return label;
}
private soot.jimple.Stmt noop;
public soot.jimple.Stmt noop(){
return noop;
}
}*/
/**
* Assert Stmt Creation
*/
private void createAssert(polyglot.ast.Assert assertStmt) {
// check if assertions are disabled
soot.Local testLocal = lg.generateLocal(soot.BooleanType.v());
soot.SootFieldRef assertField = soot.Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true);
soot.jimple.FieldRef assertFieldRef = soot.jimple.Jimple.v().newStaticFieldRef(assertField);
soot.jimple.AssignStmt fieldAssign = soot.jimple.Jimple.v().newAssignStmt(testLocal, assertFieldRef);
body.getUnits().add(fieldAssign);
soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.ConditionExpr cond1 = soot.jimple.Jimple.v().newNeExpr(testLocal, soot.jimple.IntConstant.v(0));
soot.jimple.IfStmt testIf = soot.jimple.Jimple.v().newIfStmt(cond1, nop1);
body.getUnits().add(testIf);
// actual cond test
if ((assertStmt.cond() instanceof polyglot.ast.BooleanLit) && (!((polyglot.ast.BooleanLit) assertStmt.cond()).value())) {
// don't makeif
} else {
soot.Value sootCond = base().createAggressiveExpr(assertStmt.cond(), false, false);
boolean needIf = needSootIf(sootCond);
if (!(sootCond instanceof soot.jimple.ConditionExpr)) {
sootCond = soot.jimple.Jimple.v().newEqExpr(sootCond, soot.jimple.IntConstant.v(1));
} else {
sootCond = handleDFLCond((soot.jimple.ConditionExpr) sootCond);
}
if (needIf) {
// add if
soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(sootCond, nop1);
body.getUnits().add(ifStmt);
Util.addLnPosTags(ifStmt.getConditionBox(), assertStmt.cond().position());
Util.addLnPosTags(ifStmt, assertStmt.position());
}
}
// assertion failure code
soot.Local failureLocal = lg.generateLocal(soot.RefType.v("java.lang.AssertionError"));
soot.jimple.NewExpr newExpr = soot.jimple.Jimple.v().newNewExpr(soot.RefType.v("java.lang.AssertionError"));
soot.jimple.AssignStmt newAssign = soot.jimple.Jimple.v().newAssignStmt(failureLocal, newExpr);
body.getUnits().add(newAssign);
soot.SootMethodRef methToInvoke;
ArrayList paramTypes = new ArrayList();
ArrayList params = new ArrayList();
if (assertStmt.errorMessage() != null) {
soot.Value errorExpr = base().createAggressiveExpr(assertStmt.errorMessage(), false, false);
if (errorExpr instanceof soot.jimple.ConditionExpr) {
errorExpr = handleCondBinExpr((soot.jimple.ConditionExpr) errorExpr);
}
soot.Type errorType = errorExpr.getType();
if (assertStmt.errorMessage().type().isChar()) {
errorType = soot.CharType.v();
}
if (errorType instanceof soot.IntType) {
paramTypes.add(soot.IntType.v());
} else if (errorType instanceof soot.LongType) {
paramTypes.add(soot.LongType.v());
} else if (errorType instanceof soot.FloatType) {
paramTypes.add(soot.FloatType.v());
} else if (errorType instanceof soot.DoubleType) {
paramTypes.add(soot.DoubleType.v());
} else if (errorType instanceof soot.CharType) {
paramTypes.add(soot.CharType.v());
} else if (errorType instanceof soot.BooleanType) {
paramTypes.add(soot.BooleanType.v());
} else if (errorType instanceof soot.ShortType) {
paramTypes.add(soot.IntType.v());
} else if (errorType instanceof soot.ByteType) {
paramTypes.add(soot.IntType.v());
} else {
paramTypes.add(soot.Scene.v().getSootClass("java.lang.Object").getType());
}
params.add(errorExpr);
}
methToInvoke = soot.Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.AssertionError"), "<init>", paramTypes, soot.VoidType.v(), false);
soot.jimple.SpecialInvokeExpr invokeExpr = soot.jimple.Jimple.v().newSpecialInvokeExpr(failureLocal, methToInvoke, params);
soot.jimple.InvokeStmt invokeStmt = soot.jimple.Jimple.v().newInvokeStmt(invokeExpr);
body.getUnits().add(invokeStmt);
if (assertStmt.errorMessage() != null) {
Util.addLnPosTags(invokeExpr.getArgBox(0), assertStmt.errorMessage().position());
}
soot.jimple.ThrowStmt throwStmt = soot.jimple.Jimple.v().newThrowStmt(failureLocal);
body.getUnits().add(throwStmt);
// end
body.getUnits().add(nop1);
}Example 97
| Project: blazegraph-master File: History.java View source code |
/**
* Adds a sample to the history. The sample is placed into a slot in this
* history that reflects its <i>timestamp</i>.
* <p>
* If the history wraps around into the next period and there is another
* history that aggregates this one, then the average for the last period
* will be added to the aggregating history.
* <p>
* Multiple samples in the same period are recorded as (a) the total of
* those samples in the period; and (b) the #of samples in the period.
*
* @param timestamp
* The timestamp associated with the sample.
* @param value
* The sampled value.
*
* @throws IllegalArgumentException
* if the timestamp is non-postitive.
* @throws TimestampOrderException
* if the timestamp is way out of the current range for the
* history buffer.
*/
public synchronized void add(final long timestamp, final T value) {
if (log.isInfoEnabled())
log.info("timestamp=" + timestamp + ", value=" + value);
if (timestamp <= 0) {
throw new IllegalArgumentException("timestamp=" + timestamp + ", value=" + value);
}
/*
* The [logicalSlot] is the index corresponding to the #of elapsed
* periods since the epoch (when timestamp was 0).
*
* The [physicalSlot] is the index at which the sample will be placed in
* the buffer.
*
* Note: The buffer has a fixed capacity, but samples can arrive out of
* timestamp sequence. Of necessity, we can no longer record samples for
* an earlier period once that physical in the buffer has been recycled
* to represent a later period. In practice this is only a problem if a
* sample arrives so far out of sequence that its timestamp is [capacity *
* period] out of date. Such samples MUST be ignored.
*/
final long logicalSlot = timestamp / period;
if (lastLogicalSlot != -1) {
if ((lastLogicalSlot - logicalSlot) >= capacity) {
if (log.isInfoEnabled())
log.info("Timestamp out of order?", new TimestampOrderException("timestamp=" + timestamp + ", value=" + value));
// throw new TimestampOrderException("timestamp=" + timestamp
// + ", value=" + value);
}
}
final int physicalSlot = (int) (logicalSlot % capacity);
if (lastLogicalSlot == -1) {
assert lastLogicalSlot == -1;
assert size == 0;
timestamps[physicalSlot] = timestamp;
counts[physicalSlot] = 1;
data[physicalSlot] = value;
size = 1;
} else {
final int lastPhysicalSlot = (int) (lastLogicalSlot % capacity);
final long lastModified = timestamps[lastPhysicalSlot];
assert lastModified > 0 : "lastModified=" + lastModified;
/*
* Clear old samples in the buffer starting at one beyond the most
* recent sample previously record and continuing up to the current
* sample.
*/
for (long ls = lastLogicalSlot + 1; ls <= logicalSlot; ls++) {
final int ps = (int) (ls % capacity);
if (ps == 0 && sink != null) {
/*
* Overflow.
*
* Note: The overflow point is designed to be on an even
* period boundary for the next level of aggregation.
*/
final long t = ls * period;
final T avg = getAverage();
if (log.isInfoEnabled())
log.info("overflow: t=" + t + ", avg=" + avg);
sink.add(t, avg);
}
if (data[ps] != null) {
if (!overwrite) {
/*
* Note: Overwrite is not always desirable - there is a
* ctor option to disable it.
*/
throw new RuntimeException("Would overwrite data: ps=" + ps + ", capacity=" + capacity + ", size=" + size);
}
// clear old slot.
size--;
assert size >= 0 : "size=" + size;
data[ps] = null;
counts[ps] = 0;
timestamps[ps] = 0L;
}
}
if (data[physicalSlot] == null) {
// another slot has its first sample.
size++;
}
// aggregate iff numeric.
data[physicalSlot] = (data[physicalSlot] == null || !isNumeric() ? value : valueOf(((Number) data[physicalSlot]).doubleValue() + ((Number) value).doubleValue()));
// #of samples in that slot.
counts[physicalSlot]++;
// most recent timestamp for that sample.
timestamps[physicalSlot] = timestamp;
if (size > capacity) {
/*
* FIXME I am seeing this exception after a few days of run
* time. The [size] appears to grow by one every minute.
* 2/22/09. The stack trace is emerging out of the LBS update
* task, but the problem is clearly in the History class itself:
*
* java.lang.AssertionError: size=1000, capacity=24
at com.bigdata.counters.History.add(History.java:938)
at com.bigdata.counters.History.add(History.java:894)
at com.bigdata.counters.HistoryInstrument.add(HistoryInstrument.java:130)
at com.bigdata.service.LoadBalancerService$UpdateTask.setupCounters(LoadBalancerService.java:1668)
at com.bigdata.service.LoadBalancerService$UpdateTask.run(LoadBalancerService.java:843)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
*/
// log assertion but do not throw the execption.
log.warn("size=" + size + ", capacity=" + capacity);
}
}
// strictly increasing since samples may arrive out of timestamp order.
lastLogicalSlot = Math.max(lastLogicalSlot, logicalSlot);
}Example 98
| Project: plugin-java-master File: ImportRewriteTest.java View source code |
@Test
public void testAddImports_bug24804_5() throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.lang.AssertionError; //test\n");
buf.append("\n");
buf.append("/** comment2 */\n");
buf.append("\n");
buf.append("/** comment */\n");
buf.append("import java.lang.System;\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append("}\n");
String[] order = new String[] { "java" };
Document d = new WorkerDocument(buf.toString());
CompilationUnit cu = createCompilationUnit(d, "C");
ImportRewrite imports = newImportsRewrite(d, cu, order, 1, 1, false);
imports.addImport("java.io.Exception");
apply(imports);
buf = new StringBuffer();
buf.append("package pack1;\n");
buf.append("\n");
buf.append("import java.io.*;\n");
buf.append("//test\n");
buf.append("/** comment2 */\n");
buf.append("/** comment */\n");
buf.append("\n");
buf.append("public class C {\n");
buf.append("}\n");
assertEqualString(d.get(), buf.toString());
}Example 99
| Project: gs-collections-master File: Verify.java View source code |
/**
* Mangles the stack trace of {@link AssertionError} so that it looks like
* its been thrown from the line that called to a custom assertion.
* <p>
* This is useful for when you are in a debugging session and you want to go to the source
* of the problem in the test case quickly. The regular use case for this would be something
* along the lines of:
* <pre>
* public class TestFoo extends junit.framework.TestCase
* {
* public void testFoo() throws Exception
* {
* Foo foo = new Foo();
* ...
* assertFoo(foo);
* }
*
* // Custom assert
* private static void assertFoo(Foo foo)
* {
* try
* {
* assertEquals(...);
* ...
* assertSame(...);
* }
* catch (AssertionFailedException e)
* {
* AssertUtils.throwMangledException(e, 2);
* }
* }
* }
* </pre>
* <p>
* Without the {@code try ... catch} block around lines 11-13 the stack trace following a test failure
* would look a little like:
* <p>
* <pre>
* java.lang.AssertionError: ...
* at TestFoo.assertFoo(TestFoo.java:11)
* at TestFoo.testFoo(TestFoo.java:5)
* at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
* at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
* at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
* at java.lang.reflect.Method.invoke(Method.java:324)
* ...
* </pre>
* <p>
* Note that the source of the error isn't readily apparent as the first line in the stack trace
* is the code within the custom assert. If we were debugging the failure we would be more interested
* in the second line of the stack trace which shows us where in our tests the assert failed.
* <p>
* With the {@code try ... catch} block around lines 11-13 the stack trace would look like the
* following:
* <p>
* <pre>
* java.lang.AssertionError: ...
* at TestFoo.testFoo(TestFoo.java:5)
* at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
* at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
* at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
* at java.lang.reflect.Method.invoke(Method.java:324)
* ...
* </pre>
* <p>
* Here the source of the error is more visible as we can instantly see that the testFoo test is
* failing at line 5.
*
* @param e The exception to mangle.
* @param framesToPop The number of frames to remove from the stack trace.
* @throws AssertionError that was given as an argument with its stack trace mangled.
*/
public static void throwMangledException(AssertionError e, int framesToPop) {
e.fillInStackTrace();
StackTraceElement[] stackTrace = e.getStackTrace();
StackTraceElement[] newStackTrace = new StackTraceElement[stackTrace.length - framesToPop];
System.arraycopy(stackTrace, framesToPop, newStackTrace, 0, newStackTrace.length);
e.setStackTrace(newStackTrace);
throw e;
}Example 100
| Project: ceylon-compiler-master File: ModelLoaderTests.java View source code |
protected void verifyCompilerClassLoading(String ceylon, final RunnableTest test, List<String> options) {
// now compile the ceylon usage file
JavacTaskImpl task2 = getCompilerTask(options, ceylon);
// get the context to grab the declarations
final Context context2 = task2.getContext();
// declarations from the jar anymore because we've overridden the jar and the javac jar index is corrupted
class Listener implements TaskListener {
@Override
public void started(TaskEvent e) {
}
@Override
public void finished(TaskEvent e) {
if (e.getKind() == Kind.ENTER) {
CeylonModelLoader modelLoader = (CeylonModelLoader) CeylonModelLoader.instance(context2);
test.test(modelLoader);
}
}
}
Listener listener = new Listener();
task2.setTaskListener(listener);
try {
Boolean success = task2.call();
Assert.assertTrue("Compilation failed", success);
} catch (AssertionError x) {
throw x;
} catch (Throwable x) {
while (x.getCause() != null) x = x.getCause();
if (x instanceof Error)
throw (Error) x;
if (x instanceof RuntimeException)
throw (RuntimeException) x;
throw new RuntimeException(x);
}
}Example 101
| Project: hadoop-release-2.6.0-master File: TaskImpl.java View source code |
/**
* Recover a completed task from a previous application attempt
* @param taskInfo recovered info about the task
* @param recoverTaskOutput whether to recover task outputs
* @return state of the task after recovery
*/
private TaskStateInternal recover(TaskInfo taskInfo, OutputCommitter committer, boolean recoverTaskOutput) {
LOG.info("Recovering task " + taskId + " from prior app attempt, status was " + taskInfo.getTaskStatus());
scheduledTime = taskInfo.getStartTime();
sendTaskStartedEvent();
Collection<TaskAttemptInfo> attemptInfos = taskInfo.getAllTaskAttempts().values();
if (attemptInfos.size() > 0) {
metrics.launchedTask(this);
}
// recover the attempts for this task in the order they finished
// so task attempt completion events are ordered properly
int savedNextAttemptNumber = nextAttemptNumber;
ArrayList<TaskAttemptInfo> taInfos = new ArrayList<TaskAttemptInfo>(taskInfo.getAllTaskAttempts().values());
Collections.sort(taInfos, TA_INFO_COMPARATOR);
for (TaskAttemptInfo taInfo : taInfos) {
nextAttemptNumber = taInfo.getAttemptId().getId();
TaskAttemptImpl attempt = addAttempt(Avataar.VIRGIN);
// handle the recovery inline so attempts complete before task does
attempt.handle(new TaskAttemptRecoverEvent(attempt.getID(), taInfo, committer, recoverTaskOutput));
finishedAttempts.add(attempt.getID());
TaskAttemptCompletionEventStatus taces = null;
TaskAttemptState attemptState = attempt.getState();
switch(attemptState) {
case FAILED:
taces = TaskAttemptCompletionEventStatus.FAILED;
break;
case KILLED:
taces = TaskAttemptCompletionEventStatus.KILLED;
break;
case SUCCEEDED:
taces = TaskAttemptCompletionEventStatus.SUCCEEDED;
break;
default:
throw new IllegalStateException("Unexpected attempt state during recovery: " + attemptState);
}
if (attemptState == TaskAttemptState.FAILED) {
failedAttempts.add(attempt.getID());
if (failedAttempts.size() >= maxAttempts) {
taces = TaskAttemptCompletionEventStatus.TIPFAILED;
}
}
// TODO: this shouldn't be necessary after MAPREDUCE-4330
if (successfulAttempt == null) {
handleTaskAttemptCompletion(attempt.getID(), taces);
if (attemptState == TaskAttemptState.SUCCEEDED) {
successfulAttempt = attempt.getID();
}
}
}
nextAttemptNumber = savedNextAttemptNumber;
TaskStateInternal taskState = TaskStateInternal.valueOf(taskInfo.getTaskStatus());
switch(taskState) {
case SUCCEEDED:
if (successfulAttempt != null) {
sendTaskSucceededEvents();
} else {
LOG.info("Missing successful attempt for task " + taskId + ", recovering as RUNNING");
// there must have been a fetch failure and the retry wasn't complete
taskState = TaskStateInternal.RUNNING;
metrics.runningTask(this);
addAndScheduleAttempt(Avataar.VIRGIN);
}
break;
case FAILED:
case KILLED:
{
if (taskState == TaskStateInternal.KILLED && attemptInfos.size() == 0) {
metrics.endWaitingTask(this);
}
TaskFailedEvent tfe = new TaskFailedEvent(taskInfo.getTaskId(), taskInfo.getFinishTime(), taskInfo.getTaskType(), taskInfo.getError(), taskInfo.getTaskStatus(), taskInfo.getFailedDueToAttemptId(), taskInfo.getCounters());
eventHandler.handle(new JobHistoryEvent(taskId.getJobId(), tfe));
eventHandler.handle(new JobTaskEvent(taskId, getExternalState(taskState)));
break;
}
default:
throw new java.lang.AssertionError("Unexpected recovered task state: " + taskState);
}
return taskState;
}