org.junit.Assert Java Examples

The following examples show how to use org.junit.Assert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExpressionBuilderTest.java    From rheem with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #2
Source File: RMHATestBase.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: RungeKuttaFieldIntegratorAbstractTest.java    From hipparchus with Apache License 2.0 6 votes vote down vote up
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());

}
 
Example #4
Source File: Neo4JEdgeWhileGettingPropertiesTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: TestCoercePredicates.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #6
Source File: LedgerAddressTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
    }
}
 
Example #7
Source File: AssetCatalogClientTest.java    From egeria with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source File: LongObjectHashtableTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
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");
                }
            }
        }
    }
 
Example #9
Source File: KafkaMultiDCSourceSynchronizerTestCases.java    From siddhi-io-kafka with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #10
Source File: ExtractStateTest.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: OperatorDeclarationTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #12
Source File: GeoFireTestingRule.java    From geofire-android with Apache License 2.0 6 votes vote down vote up
/** 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));
}
 
Example #13
Source File: StateBackendMigrationTestBase.java    From flink with Apache License 2.0 6 votes vote down vote up
@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());
	}
}
 
Example #14
Source File: TaskStateSnapshotTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #15
Source File: ReOpenableHashTableTestBase.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@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;
	}
}
 
Example #16
Source File: CassandraTypeConverterTest.java    From debezium-incubator with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #17
Source File: GPatternUTF8LexerTest.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #18
Source File: TestReplicationManager.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #19
Source File: ConfigurationManagerTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source File: DuplicateTestId.java    From neodymium-library with MIT License 6 votes vote down vote up
@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++;
}
 
Example #21
Source File: TestNameMapping.java    From iceberg with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #22
Source File: TestITCHVisitorNegative.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
	}
}
 
Example #23
Source File: DatabaseSequenceElementIdProviderWhileGeneratingIdTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #24
Source File: FeedItemTargetServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example #25
Source File: ViewModelProviderTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void localViewModel() throws Throwable {
    class VM extends ViewModel1 {
    }
    try {
        mViewModelProvider.get(VM.class);
        Assert.fail();
    } catch (IllegalArgumentException ignored) {
    }
}
 
Example #26
Source File: TestPerfInfo.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testToString() {
  PerfInfo perf = new PerfInfo();
  perf.setTps(10);
  perf.setMsTotalTime(10);
  perf.setMsMaxLatency(100);

  Assert.assertEquals("PerfInfo [tps=10.0, msTotalTime=10.0, msLatency=1.0, msMaxLatency=100.0]", perf.toString());
}
 
Example #27
Source File: TestRackResolverScriptBasedMapping.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testScriptName() {
  Configuration conf = new Configuration();
  conf
      .setClass(
          CommonConfigurationKeysPublic.
              NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY,
          ScriptBasedMapping.class, DNSToSwitchMapping.class);
  conf.set(CommonConfigurationKeysPublic.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY,
      "testScript");
  RackResolver.init(conf);
  Assert.assertEquals(RackResolver.getDnsToSwitchMapping().toString(),
      "script-based mapping with script testScript");
}
 
Example #28
Source File: JpaResourceInformationProviderTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testVersionAccess() {
    ResourceInformation info = builder.build(VersionedEntity.class);
    ResourceField field = info.findAttributeFieldByName("version");
    // must not be immutable to support optimistic locking
    Assert.assertTrue(field.getAccess().isPostable());
    Assert.assertTrue(field.getAccess().isPatchable());
}
 
Example #29
Source File: RunImplTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-44981")
@Test
public void queuedSingleNode() throws Exception {
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(),"queuedSingleNode.jenkinsfile");

    // Ensure null before first run
    Map pipeline = request().get(String.format("/organizations/jenkins/pipelines/%s/", p.getName())).build(Map.class);
    Assert.assertNull(pipeline.get("latestRun"));

    // Run until completed
    WorkflowRun r = p.scheduleBuild2(0).waitForStart();
    j.waitForMessage("Still waiting to schedule task", r);

    // Get latest run for this pipeline
    pipeline = request().get(String.format("/organizations/jenkins/pipelines/%s/", p.getName())).build(Map.class);
    Map latestRun = (Map) pipeline.get("latestRun");

    Assert.assertEquals("QUEUED", latestRun.get("state"));
    Assert.assertEquals("1", latestRun.get("id"));

    // Jenkins 2.125 introduced quotes around these labels - see commit 91ddc6. This came
    // just after the current Jenkins LTS, which is version 2.121.1. So this assert now
    // tests for the new quoted version, and the old non-quoted version.
    Assert.assertThat((String)latestRun.get("causeOfBlockage"), anyOf(
        equalTo("\u2018Jenkins\u2019 doesn’t have label \u2018test\u2019"),
        equalTo("Jenkins doesn’t have label test")
    ));

    j.createOnlineSlave(Label.get("test"));

    j.assertBuildStatusSuccess(j.waitForCompletion(r));
}
 
Example #30
Source File: TableSummarizerTest.java    From Alink with Apache License 2.0 5 votes vote down vote up
@Test
public void testMerge() {
    TableSummarizer summarizer = testWithMerge(false);

    Assert.assertEquals(4, summarizer.count);
    Assert.assertArrayEquals(new double[]{3.0, 3.0, 1.0}, summarizer.sum.getData(), 10e-4);
    Assert.assertArrayEquals(new double[]{5.0, 5.0, 17.0}, summarizer.squareSum.getData(), 10e-4);
    Assert.assertArrayEquals(new double[]{0.0, 0.0, -3.0}, summarizer.min.getData(), 10e-4);
    Assert.assertArrayEquals(new double[]{2.0, 2.0, 2.0}, summarizer.max.getData(), 10e-4);

}