类org.junit.Assert源码实例Demo

下面列出了怎么用org.junit.Assert的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: ghidra   文件: LongObjectHashtableTest.java
public static void testContains(LongObjectHashtable<String> ht, long[] keys, String test) {

        for(int i=0;i<keys.length;i++) {
            if (!ht.contains(keys[i])) {
                Assert.fail("hastable should contain key "+keys[i]+", but it doesn't");
            }
        }

        for(int i= 0;i<=50000;i++) {
            if (ht.contains(i)) {
                if (!contains(keys,i)) {
                    Assert.fail("hashtable contains key "+i+", but it shouldn't");
                }
            }
        }
    }
 
@Test
public void testMultiMessageGapFiledByOtherSource1() throws InterruptedException {
    SourceSynchronizer synchronizer = new SourceSynchronizer(eventListener, servers, 1000, 10 * 1000);

    sendEvent(synchronizer, SOURCE_1, 0);
    sendEvent(synchronizer, SOURCE_1, 4);

    sendEvent(synchronizer, SOURCE_2, 0);
    sendEvent(synchronizer, SOURCE_2, 1);

    sendEvent(synchronizer, SOURCE_1, 5);

    sendEvent(synchronizer, SOURCE_2, 2);
    sendEvent(synchronizer, SOURCE_2, 3);

    List<Object> expectedEvents = new ArrayList<>();
    expectedEvents.add(buildDummyEvent(SOURCE_1, 0));
    expectedEvents.add(buildDummyEvent(SOURCE_2, 1));
    expectedEvents.add(buildDummyEvent(SOURCE_2, 2));
    expectedEvents.add(buildDummyEvent(SOURCE_2, 3));
    expectedEvents.add(buildDummyEvent(SOURCE_1, 4));
    expectedEvents.add(buildDummyEvent(SOURCE_1, 5));

    Assert.assertTrue(compareEventSequnce(expectedEvents));
}
 
源代码3 项目: egeria   文件: AssetCatalogClientTest.java
@Test
public void testGetClassificationsForAsset() throws Exception {
    ClassificationListResponse response = mockClassificationsResponse();

    when(connector.callGetRESTCall(eq("getClassificationsForAsset"),
            eq(ClassificationListResponse.class),
            anyString(),
            eq(SERVER_NAME),
            eq(USER_ID),
            eq(ASSET_ID),
            eq(ASSET_TYPE),
            eq(CLASSIFICATION_NAME))).thenReturn(response);

    ClassificationListResponse classificationListResponse = assetCatalog.getClassificationsForAsset(
            USER_ID,
            ASSET_ID,
            ASSET_TYPE,
            CLASSIFICATION_NAME);

    Assert.assertEquals(CLASSIFICATION_NAME, classificationListResponse.getClassifications().get(0).getName());
}
 
源代码4 项目: pravega   文件: LedgerAddressTests.java
/**
 * Tests the Compare method.
 */
@Test(timeout = 5000)
public void testCompare() {
    val addresses = new ArrayList<LedgerAddress>();
    for (int ledgerSeq = 0; ledgerSeq < LEDGER_COUNT; ledgerSeq++) {
        long ledgerId = (ledgerSeq + 1) * 31;
        for (long entryId = 0; entryId < ENTRY_COUNT; entryId++) {
            addresses.add(new LedgerAddress(ledgerSeq, ledgerId, entryId));
        }
    }

    for (int i = 0; i < addresses.size() / 2; i++) {
        val a1 = addresses.get(i);
        val a2 = addresses.get(addresses.size() - i - 1);
        val result1 = a1.compareTo(a2);
        val result2 = a2.compareTo(a1);
        AssertExtensions.assertLessThan("Unexpected when comparing smaller to larger.", 0, result1);
        AssertExtensions.assertGreaterThan("Unexpected when comparing larger to smaller.", 0, result2);
        Assert.assertEquals("Unexpected when comparing to itself.", 0, a1.compareTo(a1));
    }
}
 
protected <T extends RealFieldElement<T>> void doTestSmallStep(Field<T> field,
                                                               final double epsilonLast,
                                                               final double epsilonMaxValue,
                                                               final double epsilonMaxTime,
                                                               final String name)
     throws MathIllegalArgumentException, MathIllegalStateException {

    TestFieldProblem1<T> pb = new TestFieldProblem1<T>(field);
    T step = pb.getFinalTime().subtract(pb.getInitialState().getTime()).multiply(0.001);

    RungeKuttaFieldIntegrator<T> integ = createIntegrator(field, step);
    TestFieldProblemHandler<T> handler = new TestFieldProblemHandler<T>(pb, integ);
    integ.addStepHandler(handler);
    integ.integrate(new FieldExpandableODE<T>(pb), pb.getInitialState(), pb.getFinalTime());

    Assert.assertEquals(0, handler.getLastError().getReal(),         epsilonLast);
    Assert.assertEquals(0, handler.getMaximalValueError().getReal(), epsilonMaxValue);
    Assert.assertEquals(0, handler.getMaximalTimeError().getReal(),  epsilonMaxTime);
    Assert.assertEquals(name, integ.getName());

}
 
源代码6 项目: hadoop   文件: RMHATestBase.java
protected void startRMs(MockRM rm1, Configuration confForRM1, MockRM rm2,
    Configuration confForRM2) throws IOException {
  rm1.init(confForRM1);
  rm1.start();
  Assert.assertTrue(rm1.getRMContext().getHAServiceState()
      == HAServiceState.STANDBY);

  rm2.init(confForRM2);
  rm2.start();
  Assert.assertTrue(rm2.getRMContext().getHAServiceState()
      == HAServiceState.STANDBY);

  rm1.adminService.transitionToActive(requestInfo);
  Assert.assertTrue(rm1.getRMContext().getHAServiceState()
      == HAServiceState.ACTIVE);
}
 
源代码7 项目: xtext-xtend   文件: OperatorDeclarationTest.java
@Test
public void testOperatorDeclaration_genericReturnTypeWithFunctionType_03() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("class A {");
    _builder.newLine();
    {
      Set<QualifiedName> _operators = this.operatorMapping.getOperators();
      for(final QualifiedName op : _operators) {
        _builder.append("\t");
        _builder.append("def Iterable<()=>void> ");
        _builder.append(op, "\t");
        _builder.append("() { return null }");
        _builder.newLineIfNotEmpty();
      }
    }
    _builder.append("}");
    _builder.newLine();
    final XtendFile file = this._parseHelper.parse(_builder);
    Assert.assertTrue(IterableExtensions.join(file.eResource().getErrors(), "\n"), file.eResource().getErrors().isEmpty());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
源代码8 项目: geofire-android   文件: GeoFireTestingRule.java
/** This lets you blockingly wait until the onGeoFireReady was fired on the provided Geofire instance. */
public void waitForGeoFireReady(GeoFire geoFire) throws InterruptedException {
    final Semaphore semaphore = new Semaphore(0);
    geoFire.getDatabaseReference().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            semaphore.release();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Assert.fail("Firebase error: " + databaseError);
        }
    });

    Assert.assertTrue("Timeout occured!", semaphore.tryAcquire(timeout, TimeUnit.SECONDS));
}
 
源代码9 项目: Flink-CEPplus   文件: TaskStateSnapshotTest.java
@Test
public void putGetSubtaskStateByOperatorID() {
	TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot();

	OperatorID operatorID_1 = new OperatorID();
	OperatorID operatorID_2 = new OperatorID();
	OperatorSubtaskState operatorSubtaskState_1 = new OperatorSubtaskState();
	OperatorSubtaskState operatorSubtaskState_2 = new OperatorSubtaskState();
	OperatorSubtaskState operatorSubtaskState_1_replace = new OperatorSubtaskState();

	Assert.assertNull(taskStateSnapshot.getSubtaskStateByOperatorID(operatorID_1));
	Assert.assertNull(taskStateSnapshot.getSubtaskStateByOperatorID(operatorID_2));
	taskStateSnapshot.putSubtaskStateByOperatorID(operatorID_1, operatorSubtaskState_1);
	taskStateSnapshot.putSubtaskStateByOperatorID(operatorID_2, operatorSubtaskState_2);
	Assert.assertEquals(operatorSubtaskState_1, taskStateSnapshot.getSubtaskStateByOperatorID(operatorID_1));
	Assert.assertEquals(operatorSubtaskState_2, taskStateSnapshot.getSubtaskStateByOperatorID(operatorID_2));
	Assert.assertEquals(operatorSubtaskState_1, taskStateSnapshot.putSubtaskStateByOperatorID(operatorID_1, operatorSubtaskState_1_replace));
	Assert.assertEquals(operatorSubtaskState_1_replace, taskStateSnapshot.getSubtaskStateByOperatorID(operatorID_1));
}
 
源代码10 项目: flink   文件: StateBackendMigrationTestBase.java
@Test
public void testBroadcastStateRegistrationFailsIfNewValueSerializerIsIncompatible() {
	final String stateName = "broadcast-state";

	try {
		testBroadcastStateValueUpgrade(
			new MapStateDescriptor<>(
				stateName,
				IntSerializer.INSTANCE,
				new TestType.V1TestTypeSerializer()),
			new MapStateDescriptor<>(
				stateName,
				IntSerializer.INSTANCE,
				// new value serializer is incompatible
				new TestType.IncompatibleTestTypeSerializer()));

		fail("should have failed.");
	} catch (Exception e) {
		Assert.assertTrue(ExceptionUtils.findThrowable(e, StateMigrationException.class).isPresent());
	}
}
 
@Test
@SuppressWarnings("unchecked")
public void givenTwoIdentifierRequestsShouldRequestPoolOfIdentifiers() {
    // arrange
    Mockito.when(record.get(Mockito.eq(0))).thenAnswer(invocation -> Values.value(1));
    Mockito.when(result.hasNext()).thenAnswer(invocation -> true);
    Mockito.when(result.next()).thenAnswer(invocation -> record);
    Mockito.when(transaction.run(Mockito.any(String.class), Mockito.anyMap())).thenAnswer(invocation -> result);
    Mockito.when(session.beginTransaction()).thenAnswer(invocation -> transaction);
    Mockito.when(driver.session()).thenAnswer(invocation -> session);
    DatabaseSequenceElementIdProvider provider = new DatabaseSequenceElementIdProvider(driver, 1, "field1", "label");
    // act
    Long id = provider.generate();
    // assert
    Assert.assertNotNull("Invalid identifier value", id);
    Assert.assertEquals("Provider returned an invalid identifier value", 1L, (long)id);
    // arrange
    Mockito.when(record.get(Mockito.eq(0))).thenAnswer(invocation -> Values.value(2));
    // act
    id = provider.generate();
    // assert
    Assert.assertNotNull("Invalid identifier value", id);
    Assert.assertEquals("Provider returned an invalid identifier value", 2L, (long)id);
}
 
源代码12 项目: sailfish-core   文件: TestITCHVisitorNegative.java
/**
 * Try to encode and decode message with Long type and invalid Type=Byte
 */
@Test
public void testInvalidTypeLong(){
	try{
		IMessage message = getMessageHelper().getMessageFactory().createMessage("testLong", "ITCH");
		message.addField("Byte", (long)1);
		message=getMessageHelper().prepareMessageToEncode(message, null);
        testNegativeEncode(message, codec);
        message=getMessageCreator().getTestLong();
        testNegativeDecode(message, codec, codecValid, "Byte");
	}catch(Exception e){
		e.printStackTrace(System.err);
		logger.error(e.getMessage(),e);
		Assert.fail(e.getMessage());
	}
}
 
源代码13 项目: iceberg   文件: TestNameMapping.java
@Test
public void testComplexValueMapSchemaToMapping() {
  Schema schema = new Schema(
      required(1, "id", Types.LongType.get()),
      required(2, "data", Types.StringType.get()),
      required(3, "map", Types.MapType.ofRequired(4, 5,
          Types.DoubleType.get(),
          Types.StructType.of(
              required(6, "x", Types.DoubleType.get()),
              required(7, "y", Types.DoubleType.get()))
      )));

  MappedFields expected = MappedFields.of(
      MappedField.of(1, "id"),
      MappedField.of(2, "data"),
      MappedField.of(3, "map", MappedFields.of(
          MappedField.of(4, "key"),
          MappedField.of(5, "value", MappedFields.of(
              MappedField.of(6, "x"),
              MappedField.of(7, "y")
          ))
      )));

  NameMapping mapping = MappingUtil.create(schema);
  Assert.assertEquals(expected, mapping.asMappedFields());
}
 
源代码14 项目: neodymium-library   文件: DuplicateTestId.java
@Test
public void testDuplicateTestId() throws Exception
{
    if (dataSet == 1)
    {
        Assert.assertEquals("id1", Neodymium.dataValue("testId"));
        Assert.assertEquals("value1", Neodymium.dataValue("testParam1"));
    }
    else if (dataSet == 2)
    {
        Assert.assertEquals("id2", Neodymium.dataValue("testId"));
        Assert.assertEquals("value2", Neodymium.dataValue("testParam1"));
    }
    else if (dataSet == 3)
    {
        Assert.assertEquals("id1", Neodymium.dataValue("testId"));
        Assert.assertEquals("value3", Neodymium.dataValue("testParam1"));
    }
    dataSet++;
}
 
源代码15 项目: cosmic   文件: ConfigurationManagerTest.java
@Test
public void validateTFStaticNatServiceCapablitiesTest() {
    final Map<Capability, String> staticNatServiceCapabilityMap = new HashMap<>();
    staticNatServiceCapabilityMap.put(Capability.AssociatePublicIP, "true and Talse");
    staticNatServiceCapabilityMap.put(Capability.ElasticIp, "false");

    boolean caught = false;
    try {
        configurationMgr.validateStaticNatServiceCapablities(staticNatServiceCapabilityMap);
    } catch (final InvalidParameterValueException e) {
        Assert.assertTrue(
                e.getMessage(),
                e.getMessage().contains(
                        "Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + Capability.ElasticIp.getName() + " is true"));
        caught = true;
    }
    Assert.assertTrue("should not be accepted", caught);
}
 
@Test
public void testList() {
    // list of ints
    // test non-frozen
    DataType listType = DataType.list(DataType.cint(), false);
    AbstractType<?> convertedType = CassandraTypeConverter.convert(listType);

    ListType<?> expectedType = ListType.getInstance(Int32Type.instance, true);
    Assert.assertEquals(expectedType, convertedType);

    // test frozen
    listType = DataType.list(DataType.cint(), true);
    convertedType = CassandraTypeConverter.convert(listType);
    expectedType = ListType.getInstance(Int32Type.instance, false);
    Assert.assertEquals(expectedType, convertedType);
    Assert.assertTrue("Expected convertedType to be frozen", convertedType.isFrozenCollection());
}
 
@After
public void afterTest() {
	if (this.ioManager != null) {
		this.ioManager.shutdown();
		if (!this.ioManager.isProperlyShutDown()) {
			Assert.fail("I/O manager failed to properly shut down.");
		}
		this.ioManager = null;
	}

	if (this.memoryManager != null) {
		Assert.assertTrue("Memory Leak: Not all memory has been returned to the memory manager.",
			this.memoryManager.verifyEmpty());
		this.memoryManager.shutdown();
		this.memoryManager = null;
	}
}
 
源代码18 项目: rheem   文件: ExpressionBuilderTest.java
@Test
public void shouldFailOnInvalidInput() {
    Collection<String> expressions = Arrays.asList(
            "2x",
            "f(x,)",
            "~3",
            "",
            "*2",
            "f(3, x"
    );
    for (String expression : expressions) {
        boolean isFailed = false;
        try {
            ExpressionBuilder.parse(expression);
        } catch (ParseException e) {
            isFailed = true;
        } finally {
            Assert.assertTrue(isFailed);
        }
    }
}
 
源代码19 项目: Mycat2   文件: GPatternUTF8LexerTest.java
@Test
public void init2() {
    GPatternIdRecorder recorder = new GPatternIdRecorderImpl(false);
    Set<String> map = new HashSet<>();
    map.add("1234");
    map.add("abc");
    map.add("1a2b3c");
    map.add("`qac`");
    recorder.load(map);
    GPatternUTF8Lexer utf8Lexer = new GPatternUTF8Lexer(recorder);
    String text = "1234 abc 1a2b3c 'a哈哈哈哈1' `qac`";
    utf8Lexer.init(text);

    Assert.assertTrue(utf8Lexer.nextToken());
    Assert.assertEquals("1234", utf8Lexer.getCurTokenString());
    Assert.assertTrue(utf8Lexer.nextToken());
    Assert.assertEquals("abc", utf8Lexer.getCurTokenString());
    Assert.assertTrue(utf8Lexer.nextToken());
    Assert.assertEquals("1a2b3c", utf8Lexer.getCurTokenString());
    Assert.assertTrue(utf8Lexer.nextToken());
    Assert.assertEquals("'a哈哈哈哈1'", utf8Lexer.getCurTokenString());
    Assert.assertTrue(utf8Lexer.nextToken());
    Assert.assertEquals("`qac`", utf8Lexer.getCurTokenString());
}
 
源代码20 项目: hadoop-ozone   文件: TestReplicationManager.java
/**
 * ReplicationManager should replicate an QUASI_CLOSED replica if it is
 * under replicated.
 */
@Test
public void testUnderReplicatedQuasiClosedContainer() throws
    SCMException, ContainerNotFoundException, InterruptedException {
  final ContainerInfo container = getContainer(LifeCycleState.QUASI_CLOSED);
  final ContainerID id = container.containerID();
  final UUID originNodeId = UUID.randomUUID();
  final ContainerReplica replicaOne = getReplicas(
      id, State.QUASI_CLOSED, 1000L, originNodeId, randomDatanodeDetails());
  final ContainerReplica replicaTwo = getReplicas(
      id, State.QUASI_CLOSED, 1000L, originNodeId, randomDatanodeDetails());

  containerStateManager.loadContainer(container);
  containerStateManager.updateContainerReplica(id, replicaOne);
  containerStateManager.updateContainerReplica(id, replicaTwo);

  final int currentReplicateCommandCount = datanodeCommandHandler
      .getInvocationCount(SCMCommandProto.Type.replicateContainerCommand);

  replicationManager.processContainersNow();
  // Wait for EventQueue to call the event handler
  Thread.sleep(100L);
  Assert.assertEquals(currentReplicateCommandCount + 1,
      datanodeCommandHandler.getInvocationCount(
          SCMCommandProto.Type.replicateContainerCommand));
}
 
@Test
@SuppressWarnings("all")
public void getFeedItemTargetTest() {
  String resourceName2 = "resourceName2625949903";
  FeedItemTarget expectedResponse =
      FeedItemTarget.newBuilder().setResourceName(resourceName2).build();
  mockFeedItemTargetService.addResponse(expectedResponse);

  String formattedResourceName =
      FeedItemTargetServiceClient.formatFeedItemTargetName("[CUSTOMER]", "[FEED_ITEM_TARGET]");

  FeedItemTarget actualResponse = client.getFeedItemTarget(formattedResourceName);
  Assert.assertEquals(expectedResponse, actualResponse);

  List<AbstractMessage> actualRequests = mockFeedItemTargetService.getRequests();
  Assert.assertEquals(1, actualRequests.size());
  GetFeedItemTargetRequest actualRequest = (GetFeedItemTargetRequest) actualRequests.get(0);

  Assert.assertEquals(formattedResourceName, actualRequest.getResourceName());
  Assert.assertTrue(
      channelProvider.isHeaderSent(
          ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
          GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
 
@Test
public void givenNoKeysShouldShouldGetAllProperties() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(relationship.get(Mockito.eq("id"))).thenAnswer(invocation -> Values.value(1L));
    Mockito.when(relationship.type()).thenAnswer(invocation -> "label");
    Mockito.when(relationship.keys()).thenAnswer(invocation -> new ArrayList<>());
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class);
    Mockito.when(provider.processIdentifier(argument.capture())).thenAnswer(invocation -> argument.getValue());
    Neo4JEdge edge = new Neo4JEdge(graph, session, provider, outVertex, relationship, inVertex);
    edge.property("p1", 1L);
    edge.property("p2", 1L);
    // act
    Iterator<Property<Long>> result = edge.properties();
    // assert
    Assert.assertNotNull("Failed to get properties", result);
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertTrue("Property is not present", result.hasNext());
    result.next();
    Assert.assertFalse("Too many properties in edge", result.hasNext());
}
 
源代码23 项目: policyscanner   文件: ExtractStateTest.java
@Test
public void testProjectWithIamErrorsCreatesSideOutput() throws IOException {
  String projectSuffix = "project-with-error";
  GCPProject project = getSampleProject(projectSuffix);
  List<GCPProject> projects = new ArrayList<>(1);
  projects.add(project);

  when(this.getIamPolicy.execute()).thenThrow(GoogleJsonResponseException.class);

  sideOutputTester.processBatch(projects);
  List<GCPResourceErrorInfo> sideOutputs = sideOutputTester.takeSideOutputElements(errorTag);

  List<GCPResourceErrorInfo> expected = new ArrayList<>();
  expected.add(new GCPResourceErrorInfo(project, "Policy error null"));
  Assert.assertEquals(expected, sideOutputs);
}
 
源代码24 项目: arcusplatform   文件: TestCoercePredicates.java
@Test
public void testAddressPredicate() {
   Predicate<Object> isAddressSame = typeCoercer.createPredicate(Address.class, new Predicate<Address>() {
      @Override
      public boolean apply(Address input) {
         return TEST_ADDRESS.equals(input);
      }        
   });
   
   Assert.assertTrue(isAddressSame.apply(TEST_ADDRESS));
   Assert.assertFalse(isAddressSame.apply(TEST_ADDRESS_SERVICE));
   Assert.assertTrue(isAddressSame.apply(TEST_STRING_ADDRESS));
   Assert.assertFalse(isAddressSame.apply(TEST_STRING_ADDRESS_SERVICE));
   
   try {
      isAddressSame.apply(5);
   }
   catch(IllegalArgumentException iae) {
      // Expected
      return;
   }
   Assert.fail("Should have thrown IllegalArguementException");
}
 
源代码25 项目: TestingApp   文件: EndpointNamingTest.java
@Test
public void canMoveApiBack(){
    // api might be nested in another app so we need the ability to nest the api
    ApiEndPoint.setUrlPrefix("/listicator/");
    Assert.assertEquals("/listicator/heartbeat", ApiEndPoint.HEARTBEAT.getPath());
    Assert.assertEquals("/listicator/lists", ApiEndPoint.LISTS.getPath());
    ApiEndPoint.clearUrlPrefix();

    Assert.assertEquals("/heartbeat", ApiEndPoint.HEARTBEAT.getPath());
    Assert.assertEquals("/lists", ApiEndPoint.LISTS.getPath());

}
 
源代码26 项目: jstarcraft-core   文件: BerkeleyAccessorTestCase.java
private void testCommitTransactor(Pack pack, BerkeleyIsolation isolation) {
	accessor.openTransactor(isolation);
	Assert.assertNotNull(accessor.getTransactor());
	accessor.createInstance(Pack.class, pack);
	pack = accessor.getInstance(Pack.class, 1L);
	Assert.assertThat(pack.getSize(), CoreMatchers.equalTo(10));

	accessor.closeTransactor(false);
	Assert.assertNull(accessor.getTransactor());

	pack = accessor.getInstance(Pack.class, 1L);
	Assert.assertNotNull(pack);
	accessor.deleteInstance(Pack.class, 1L);
}
 
源代码27 项目: hipparchus   文件: UnitTestUtils.java
/** verifies that two arrays are close (sup norm) */
public static void assertEquals(String msg, double[] expected, double[] observed, double tolerance) {
    StringBuilder out = new StringBuilder(msg);
    if (expected.length != observed.length) {
        out.append("\n Arrays not same length. \n");
        out.append("expected has length ");
        out.append(expected.length);
        out.append(" observed length = ");
        out.append(observed.length);
        Assert.fail(out.toString());
    }
    boolean failure = false;
    for (int i=0; i < expected.length; i++) {
        if (!Precision.equalsIncludingNaN(expected[i], observed[i], tolerance)) {
            failure = true;
            out.append("\n Elements at index ");
            out.append(i);
            out.append(" differ. ");
            out.append(" expected = ");
            out.append(expected[i]);
            out.append(" observed = ");
            out.append(observed[i]);
        }
    }
    if (failure) {
        Assert.fail(out.toString());
    }
}
 
源代码28 项目: FontVerter   文件: TestControlFlowInstructions.java
@Test
public void givenJumpOnFalseInstruction_withTrueCondition_whenExecuted_thenDoesNotSkip() throws Exception {
    vm.getStack().push(25);
    vm.getStack().push(3);
    vm.getStack().push(1);

    List<TtfInstruction> instructions = new ArrayList<TtfInstruction>();
    instructions.add(new JumpOnFalseInstruction());
    instructions.add(new ClearInstruction());
    instructions.add(new ClearInstruction());
    instructions.add(new DuplicateInstruction());
    vm.execute(instructions);

    Assert.assertEquals(0, vm.getStack().size());
}
 
源代码29 项目: hadoop   文件: TestApplicationMasterService.java
@Test(timeout = 3000000)
public void testRMIdentifierOnContainerAllocation() throws Exception {
  MockRM rm = new MockRM(conf);
  rm.start();

  // Register node1
  MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB);

  // Submit an application
  RMApp app1 = rm.submitApp(2048);

  // kick the scheduling
  nm1.nodeHeartbeat(true);
  RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
  MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
  am1.registerAppAttempt();

  am1.addRequests(new String[] { "127.0.0.1" }, GB, 1, 1);
  AllocateResponse alloc1Response = am1.schedule(); // send the request

  // kick the scheduler
  nm1.nodeHeartbeat(true);
  while (alloc1Response.getAllocatedContainers().size() < 1) {
    LOG.info("Waiting for containers to be created for app 1...");
    sleep(1000);
    alloc1Response = am1.schedule();
  }

  // assert RMIdentifer is set properly in allocated containers
  Container allocatedContainer =
      alloc1Response.getAllocatedContainers().get(0);
  ContainerTokenIdentifier tokenId =
      BuilderUtils.newContainerTokenIdentifier(allocatedContainer
        .getContainerToken());
  Assert.assertEquals(MockRM.getClusterTimeStamp(), tokenId.getRMIdentifier());
  rm.stop();
}
 
源代码30 项目: commons-geometry   文件: SegmentTest.java
@Test
public void testGetInterval() {
    // arrange
    Segment seg = Lines.segmentFromPoints(Vector2D.of(2, -1), Vector2D.of(2, 2), TEST_PRECISION);

    // act
    Interval interval = seg.getInterval();

    // assert
    Assert.assertEquals(-1, interval.getMin(), TEST_EPS);
    Assert.assertEquals(2, interval.getMax(), TEST_EPS);

    Assert.assertSame(seg.getLine().getPrecision(), interval.getMinBoundary().getPrecision());
}
 
 类所在包
 同包方法