Java Code Examples for junit.framework.Assert

The following examples show how to use junit.framework.Assert. These examples are extracted from open source projects. 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 Project: RDFS   Source File: TestVLong.java    License: Apache License 2.0 6 votes vote down vote up
public void testVLongByte() throws IOException {
  FSDataOutputStream out = fs.create(path);
  for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; ++i) {
    Utils.writeVLong(out, i);
  }
  out.close();
  Assert.assertEquals("Incorrect encoded size", (1 << Byte.SIZE) + 96, fs
      .getFileStatus(
      path).getLen());

  FSDataInputStream in = fs.open(path);
  for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; ++i) {
    long n = Utils.readVLong(in);
    Assert.assertEquals(n, i);
  }
  in.close();
  fs.delete(path, false);
}
 
Example 2
Source Project: mt-flume   Source File: TestTransactionEventRecordV3.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPutSerialization() throws IOException, CorruptEventException {
  Map<String, String> headers = new HashMap<String, String>();
  headers.put("key", "value");
  Put in = new Put(System.currentTimeMillis(),
      WriteOrderOracle.next(),
      new FlumeEvent(headers, new byte[0]));
  Put out = (Put)TransactionEventRecord.fromByteArray(toByteArray(in));
  Assert.assertEquals(in.getClass(), out.getClass());
  Assert.assertEquals(in.getRecordType(), out.getRecordType());
  Assert.assertEquals(in.getTransactionID(), out.getTransactionID());
  Assert.assertEquals(in.getLogWriteOrderID(), out.getLogWriteOrderID());
  Assert.assertEquals(in.getEvent().getHeaders(), out.getEvent().getHeaders());
  Assert.assertEquals(headers, in.getEvent().getHeaders());
  Assert.assertEquals(headers, out.getEvent().getHeaders());
  Assert.assertTrue(Arrays.equals(in.getEvent().getBody(), out.getEvent().getBody()));
}
 
Example 3
Source Project: dal   Source File: DatabasePoolConfigParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test2() {
    PoolPropertiesConfigure configure =
            DataSourceConfigureLocatorManager.getInstance().getUserPoolPropertiesConfigure("dao_test_select");
    Assert.assertEquals(true, configure.getTestWhileIdle().booleanValue());
    Assert.assertEquals(true, configure.getTestOnBorrow().booleanValue());
    Assert.assertEquals("SELECT 1", configure.getValidationQuery());
    Assert.assertEquals(30000, configure.getValidationInterval().intValue());
    Assert.assertEquals(30000,
            configure.getTimeBetweenEvictionRunsMillis().intValue());
    Assert.assertEquals(100, configure.getMaxActive().intValue());
    Assert.assertEquals(10, configure.getMinIdle().intValue());
    Assert.assertEquals(1000, configure.getMaxWait().intValue());
    Assert.assertEquals(10, configure.getInitialSize().intValue());
    Assert.assertEquals(60, configure.getRemoveAbandonedTimeout().intValue());
    Assert.assertEquals(true, configure.getRemoveAbandoned().booleanValue());
    Assert.assertEquals(true, configure.getLogAbandoned().booleanValue());
    Assert.assertEquals(30000,
            configure.getMinEvictableIdleTimeMillis().intValue());
    Assert.assertEquals("rewriteBatchedStatements=true;allowMultiQueries=true",
            configure.getConnectionProperties());
}
 
Example 4
Source Project: lucene-solr   Source File: ArrayEvaluatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void arrayLongSortDescTest() throws IOException{
  StreamEvaluator evaluator = factory.constructEvaluator("array(a,b,c, sort=desc)");
  StreamContext context = new StreamContext();
  evaluator.setStreamContext(context);
  Object result;
  
  values.put("a", 1L);
  values.put("b", 3L);
  values.put("c", 2L);
  
  result = evaluator.evaluate(new Tuple(values));
  
  Assert.assertTrue(result instanceof List<?>);
  
  Assert.assertEquals(3, ((List<?>)result).size());
  Assert.assertEquals(3D, ((List<?>)result).get(0));
  Assert.assertEquals(2D, ((List<?>)result).get(1));
  Assert.assertEquals(1D, ((List<?>)result).get(2));
}
 
Example 5
Source Project: zstack   Source File: TestSnapshotOnKvm42.java    License: Apache License 2.0 6 votes vote down vote up
private void fullSnapshot(VolumeSnapshotInventory inv, int distance) {
    Assert.assertEquals(VolumeSnapshotState.Enabled.toString(), inv.getState());
    Assert.assertEquals(VolumeSnapshotStatus.Ready.toString(), inv.getStatus());
    VolumeVO vol = dbf.findByUuid(inv.getVolumeUuid(), VolumeVO.class);
    VolumeSnapshotVO svo = dbf.findByUuid(inv.getUuid(), VolumeSnapshotVO.class);
    Assert.assertNotNull(svo);
    Assert.assertFalse(svo.isFullSnapshot());
    Assert.assertTrue(svo.isLatest());
    Assert.assertNull(svo.getParentUuid());
    Assert.assertEquals(distance, svo.getDistance());
    Assert.assertEquals(vol.getPrimaryStorageUuid(), svo.getPrimaryStorageUuid());
    Assert.assertNotNull(svo.getPrimaryStorageInstallPath());
    VolumeSnapshotTreeVO cvo = dbf.findByUuid(svo.getTreeUuid(), VolumeSnapshotTreeVO.class);
    Assert.assertNotNull(cvo);
    Assert.assertTrue(cvo.isCurrent());
}
 
Example 6
Source Project: ensemble-clustering   Source File: TestExactTokenMatchDistance.java    License: MIT License 6 votes vote down vote up
@Test
public void testIdentical3() {
	BagOfWordsFeature t1 = new BagOfWordsFeature();
	t1.setCount("dog", 10);
	t1.setCount("food", 5);
	t1.setCount("house", 1);
	t1.setCount("walk", 6);
	t1.setCount("yard", 8);
	
	BagOfWordsFeature t2 = new BagOfWordsFeature();
	t2.setCount("dog", 10);
	t2.setCount("food", 5);
	t2.setCount("house", 1);
	t2.setCount("walk", 6);
	t2.setCount("yard", 8);
	
	ExactTokenMatchDistance d = new ExactTokenMatchDistance();
	double distance = d.aveMinDistance(Collections.singletonList(t1), Collections.singletonList(t2));
	System.out.println(distance);
	Assert.assertTrue(isEqual(distance, 0));
}
 
Example 7
Source Project: sqlbrite-dao   Source File: DaoSqlBriteIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void runRawStatementQueryNoTablesSpecified() {
  BriteDatabase db = PowerMockito.mock(BriteDatabase.class);
  userDao.setSqlBriteDb(db);

  String arg1 = "arg1", arg2 = "arg2";
  String table = "Table";
  String sql = "SELECT * FROM " + table;
  List<String> argsList = Arrays.asList(arg1, arg2);
  Set<String> emptySet = Collections.emptySet();

  userDao.rawQuery(sql).args(arg1, arg2).run();

  ArgumentCaptor<String> varArgs = ArgumentCaptor.forClass(String.class);

  QueryObservable query = Mockito.verify(db, Mockito.times(1))
      .createQuery(Mockito.eq(emptySet), Mockito.eq(sql), varArgs.capture());

  Assert.assertEquals(argsList, varArgs.getAllValues());
}
 
Example 8
Source Project: product-ei   Source File: ApiStatisticsTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true)
protected void initialize() throws Exception {
    //Starting the thrift port to listen to statistics events
    thriftServer = new ThriftServer("Wso2EventTestCase", 7612, true);
    thriftServer.start(7612);
    log.info("Thrift Server is Started on port 8462");

    //Changing synapse configuration to enable statistics and tracing
    serverConfigurationManager =
            new ServerConfigurationManager(new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN));
    serverConfigurationManager.applyConfiguration(
            new File(getESBResourceLocation() + File.separator + "StatisticTestResources" + File.separator +
                    "synapse.properties"));
    super.init();

    thriftServer.resetMsgCount();
    thriftServer.resetPreservedEventList();
    //load esb configuration to the server
    loadESBConfigurationFromClasspath("/artifacts/ESB/synapseconfig/statistics/synapseconfigapi.xml");
    thriftServer.waitToReceiveEvents(20000, 3); //waiting for esb to send artifact config data to the thriftserver

    //Checking whether all the artifact configuration events are received
    Assert.assertEquals("Three configuration events are required", 3, thriftServer.getMsgCount());
}
 
Example 9
Source Project: dubbo3   Source File: MockClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerInvoke_forcemock_defaultreturn(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName());
	url = url.addParameter(Constants.MOCK_KEY, "force" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
    URL mockUrl = URL.valueOf("mock://localhost/"+IHelloService.class.getName()
			+"?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ")
			.addParameters(url.getParameters());
	
	Protocol protocol = new MockProtocol();
	Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
	invokers.add(mInvoker1);
    
    RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("sayHello");
    Result ret = cluster.invoke(invocation);
    Assert.assertEquals(null, ret.getValue());
}
 
Example 10
public void validate( final LogicalPageBox logicalPageBox, final SheetLayout sheetLayout,
    final TableContentProducer tableContentProducer ) {
  Assert.assertEquals( "RowCount", getRowCount(), sheetLayout.getRowCount() );
  Assert.assertEquals( "ColCount", getColumnCount(), sheetLayout.getColumnCount() );
  int row = 0;
  int col = 0;
  try {
    for ( row = 0; row < getRowCount(); row++ ) {
      for ( col = 0; col < getColumnCount(); col++ ) {
        final ResultCell resultCell = getResultCell( row, col );
        final CellMarker.SectionType sectionType = tableContentProducer.getSectionType( row, col );
        final CellBackground backgroundAt =
            cellBackgroundProducer.getBackgroundAt( logicalPageBox, sheetLayout, col, row, true, sectionType );
        if ( resultCell == null ) {
          assertEmptyBackground( backgroundAt );
        } else {
          resultCell.assertValidity( backgroundAt );
        }
      }
    }
  } catch ( AssertionFailedError afe ) {
    logger.error( "Assertation failure at row " + row + ", column " + col );
    throw afe;
  }
}
 
Example 11
Source Project: dubbox   Source File: ConnectChannelHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_Connect_Blocked() throws RemotingException{
    handler = new ConnectionOrderedChannelHandler(new BizChannelHander(false), url);
    ThreadPoolExecutor executor = (ThreadPoolExecutor)getField(handler, "connectionExecutor", 1);
    Assert.assertEquals(1, executor.getMaximumPoolSize());
    
    int runs = 20;
    int taskCount = runs * 2;
    for(int i=0; i<runs;i++){
        handler.connected(new MockedChannel());
        handler.disconnected(new MockedChannel());
        Assert.assertTrue(executor.getActiveCount() + " must <=1" ,executor.getActiveCount() <= 1);
    }
    //queue.size 
    Assert.assertEquals(taskCount -1 , executor.getQueue().size());
    
    for( int i=0;i<taskCount; i++){
        if (executor.getCompletedTaskCount() < taskCount){
            sleep(100);
        }
    }
    Assert.assertEquals(taskCount, executor.getCompletedTaskCount());        
}
 
Example 12
@Test
public void testErrorReportingOnEntityRefFieldMissing() throws IOException {
    // entity doesn't have property to get at sourceRefPath
    AbstractMessageReport errorReport = new DummyMessageReport();
    ReportStats reportStats = new SimpleReportStats();

    NeutralRecordEntity entity = createSourceEntityMissingRefField();
    DidRefConfig refConfig = createRefConfig("Simple_DID_ref_config.json");
    DidEntityConfig entityConfig = createEntityConfig("Simple_DID_entity_config.json");

    mockRefConfig(refConfig, ENTITY_TYPE);
    mockEntityConfig(entityConfig, ENTITY_TYPE);
    Mockito.when(schemaRepository.getSchema(ENTITY_TYPE)).thenReturn(null);
    didResolver.resolveInternalIds(entity, TENANT, errorReport, reportStats);

    Assert.assertNull("Id should not have been resolved", entity.getBody().get(REF_FIELD));
    Assert.assertTrue("Errors should be reported from reference resolution ", reportStats.hasErrors());
}
 
Example 13
public void testValidCombination2Sets() {
    registerHolidays("UK", createUKHolidayCalendar());
    registerHolidays("US", createUSHolidayCalendar());
    final DateCalculator<E> cal1 = newDateCalculator("US", HolidayHandlerType.FORWARD);
    final E localDate = newDate("2006-08-08");
    cal1.setStartDate(localDate);
    final DateCalculator<E> cal2 = newDateCalculator("UK", HolidayHandlerType.FORWARD);

    final DateCalculator<E> combo = cal1.combine(cal2);
    Assert.assertEquals("Combo name", "US/UK", combo.getName());
    Assert.assertEquals("Combo type", HolidayHandlerType.FORWARD, combo.getHolidayHandlerType());
    Assert.assertEquals("start", localDate, combo.getStartDate());
    Assert.assertEquals("currentDate", localDate, combo.getCurrentBusinessDate());
    Assert.assertEquals("Holidays", 6, combo.getHolidayCalendar().getHolidays().size());
    Assert.assertEquals("Early Boundary", newDate("2006-01-01"), combo.getHolidayCalendar().getEarlyBoundary());
    Assert.assertEquals("Late Boundary", newDate("2020-12-31"), combo.getHolidayCalendar().getLateBoundary());
}
 
Example 14
Source Project: zstack   Source File: TestLocalStorage54.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws ApiSenderException, InterruptedException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    api.stopVmInstance(vm.getUuid());

    config.deleteBitsCmds.clear();
    HostInventory host2 = deployer.hosts.get("host2");
    HostInventory host1 = deployer.hosts.get("host1");
    VolumeInventory root = vm.getRootVolume();
    // xml file defined vm was on host1
    migrateVolume(root, host2.getUuid());
    migrateVolume(root, host2.getUuid());
    latch.await(1, TimeUnit.MINUTES);

    Assert.assertEquals(1, config.deleteBitsCmds.size());
    DeleteBitsCmd cmd = config.deleteBitsCmds.get(0);
    Assert.assertEquals(host1.getUuid(), cmd.getHostUuid());
    Assert.assertEquals(1, config.copyBitsFromRemoteCmds.size());
    CopyBitsFromRemoteCmd ccmd = config.copyBitsFromRemoteCmds.get(0);
    Assert.assertEquals(host2.getManagementIp(), ccmd.dstIp);
}
 
Example 15
Source Project: gemfirexd-oss   Source File: LocatorJUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testServerOnly() throws Exception {
    Properties props = new Properties();
    props.setProperty("mcast-port", "0");
    locator = Locator.startLocatorAndDS(port, tmpFile, null, props, false, true, null);
    Assert.assertFalse(locator.isPeerLocator());
    Assert.assertTrue(locator.isServerLocator());
    Thread.sleep(1000);
    try {
      GossipData request = new GossipData(GossipData.REGISTER_REQ, "group", new IpAddress(InetAddress.getLocalHost(), 55), null, null);
      TcpClient.requestToServer(InetAddress.getLocalHost(), port, request, REQUEST_TIMEOUT);
      Assert.fail("Should have got an exception");
    } catch (Exception expected) {
//      expected.printStackTrace();
    }

    doServerLocation();
  }
 
Example 16
Source Project: Llunatic   Source File: TestAlgebra.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void testJoinProjectRS() {
        Scenario scenario = UtilityTest.loadScenarioFromResources(References.testRS);
        TableAlias tableAliasR = new TableAlias("R");
        TableAlias tableAliasS = new TableAlias("S");
        List<AttributeRef> leftAttributes = new ArrayList<AttributeRef>();
        leftAttributes.add(new AttributeRef(tableAliasR, "c"));
        List<AttributeRef> rightAttributes = new ArrayList<AttributeRef>();
        rightAttributes.add(new AttributeRef(tableAliasS, "a"));
        Join join = new Join(leftAttributes, rightAttributes);
        join.addChild(new Scan(tableAliasR));
        join.addChild(new Scan(tableAliasS));
        List<AttributeRef> attributes = new ArrayList<AttributeRef>();
        attributes.add(new AttributeRef(tableAliasR, "a"));
        attributes.add(new AttributeRef(tableAliasS, "a"));
        Project project = new Project(SpeedyUtility.createProjectionAttributes(attributes));
        project.addChild(join);
        if (logger.isTraceEnabled()) logger.debug(project.toString());
        Iterator<Tuple> result = project.execute(scenario.getSource(), scenario.getTarget());
        String stringResult = LunaticUtility.printTupleIterator(result);
        if (logger.isTraceEnabled()) logger.debug(stringResult);
//        Assert.assertTrue(stringResult.startsWith("Number of tuples: 2\n"));
        Assert.assertTrue(stringResult.startsWith("Number of tuples: 4\n"));
    }
 
Example 17
@Test
@Category(UnitTest.class)
public void testGetTileBadJsonColorScalePng() throws Exception
{
  String version = "1.0.0";
  String raster = astersmall_nopyramids_abs;
  int x = 2846;
  int y = 1411;
  int z = 12;
  String format = "png";
  String json = "{\"foo\":\"bar\"}";


  Response response = target("tms" + "/" + version + "/" +
      URLEncoder.encode(raster, "UTF-8") + "/global-geodetic/" + z + "/" + x + "/" + y + "." + format)
      .queryParam("color-scale", URLEncoder.encode(json, "UTF-8"))
      .request().get();

  Assert.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
  Assert.assertEquals("Unable to parse color scale JSON", response.readEntity(String.class));
}
 
Example 18
Source Project: zstack   Source File: TestVirtualRouterPortForwarding27.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws ApiSenderException {
    PortForwardingRuleInventory rule1 = new PortForwardingRuleInventory();
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    api.stopVmInstance(vm.getUuid());
    VmNicInventory nic = vm.getVmNics().get(0);
    L3NetworkInventory vipNw = deployer.l3Networks.get("PublicNetwork");
    VipInventory vip = api.acquireIp(vipNw.getUuid());

    rule1.setName("pfRule1");
    rule1.setVipUuid(vip.getUuid());
    rule1.setVmNicUuid(nic.getUuid());
    rule1.setVipPortStart(22);
    rule1.setVipPortEnd(100);
    rule1.setPrivatePortStart(22);
    rule1.setPrivatePortEnd(100);
    rule1.setProtocolType(PortForwardingProtocolType.TCP.toString());
    api.createPortForwardingRuleByFullConfig(rule1);

    String ref = Q.New(VipNetworkServicesRefVO.class).select(VipNetworkServicesRefVO_.serviceType).eq(VipNetworkServicesRefVO_.uuid,rule1.getUuid()).find();
    Assert.assertEquals(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE, ref);
}
 
Example 19
Source Project: stratosphere   Source File: CrossOperatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCrossProjection2() {

	final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
	DataSet<Tuple5<Integer, Long, String, Long, Integer>> ds1 = env.fromCollection(emptyTupleData, tupleTypeInfo);
	DataSet<Tuple5<Integer, Long, String, Long, Integer>> ds2 = env.fromCollection(emptyTupleData, tupleTypeInfo);

	// should work
	try {
		ds1.cross(ds2)
			.projectFirst(0,3)
			.types(Integer.class, Long.class);
	} catch(Exception e) {
		Assert.fail();
	}
}
 
Example 20
@Test
public void test7() throws Exception {
	DataSource ds = (DataSource) context.getBean("zebraDS");
	Connection conn = null;
	try {
		conn = ds.getConnection();
		PreparedStatement stmt = conn
				.prepareStatement("SELECT COUNT(FollowNoteID) FROM DP_GroupFollowNote WHERE (NoteClass = 1 OR (NoteClass = 4 AND UserID = ?)) AND NoteID = ? AND UserID = ?");
		stmt.setInt(1, 0);
		stmt.setInt(2, 7);
		stmt.setInt(3, 0);
		stmt.execute();
		ResultSet rs = stmt.getResultSet();
		while (rs.next()) {
			Assert.assertEquals(2, rs.getLong(1));
		}
	} catch (Exception e) {
		Assert.fail();
	} finally {
		if (conn != null) {
			conn.close();
		}
	}
}
 
Example 21
protected void singleEntity(int numToExpect) throws Exception {
  h.query("/dataimport", generateRequest());
  assertQ("There should be 1 document per person in the database: "
      + totalPeople(), req("*:*"), "//*[@numFound='" + totalPeople() + "']");
  Assert.assertTrue("Expecting " + numToExpect
      + " database calls, but DIH reported " + totalDatabaseRequests(),
      totalDatabaseRequests() == numToExpect);
}
 
Example 22
Source Project: graphhopper-navigation-android   Source File: TriggerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void equal_validatesToTrue() throws Exception {
  RouteProgress routeProgress = buildTriggerRouteProgress();
  Milestone milestone = new StepMilestone.Builder()
    .setTrigger(
      Trigger.eq(TriggerProperty.STEP_DISTANCE_TOTAL_METERS,
        routeProgress.currentLegProgress().currentStep().distance())
    )
    .build();

  boolean result = milestone.isOccurring(routeProgress, routeProgress);

  Assert.assertTrue(result);
}
 
Example 23
Source Project: spork   Source File: TestLogicalPlanBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery23Fail2() throws Exception {
    String query = "A = load 'a';" +
                   "B = load 'b';" +
                   "C = cogroup A by (*, $0), B by ($0, $1);";
    boolean exceptionThrown = false;
    try {
        buildPlan(query);
    } catch (AssertionFailedError e) {
        exceptionThrown = true;
    }
    Assert.assertTrue(exceptionThrown);
}
 
Example 24
Source Project: product-emm   Source File: MobileDeviceManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = "addEnrollment", description = "Test response for minus length")
public void testGetDeviceWithMinusLength() throws Exception{
    MDMResponse response = client.get(Constants.MobileDeviceManagement.GET_ALL_DEVICES_ENDPOINT+"?start=0&length=-2");
    Assert.assertEquals(HttpStatus.SC_OK,response.getStatus());
    JsonObject jsonObject = parser.parse(response.getBody()).getAsJsonObject();
    Assert.assertTrue("number of android devices in response not equal to the actual enrolled number.",
                                                                    String.valueOf(jsonObject.get("count")).equals("10"));
}
 
Example 25
Source Project: dubbox   Source File: ReferenceConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInjvm() throws Exception {
    ApplicationConfig application = new ApplicationConfig();
    application.setName("test-protocol-random-port");

    RegistryConfig registry = new RegistryConfig();
    registry.setAddress("multicast://224.5.6.7:1234");

    ProtocolConfig protocol = new ProtocolConfig();
    protocol.setName("dubbo");

    ServiceConfig<DemoService> demoService;
    demoService = new ServiceConfig<DemoService>();
    demoService.setInterface(DemoService.class);
    demoService.setRef(new DemoServiceImpl());
    demoService.setApplication(application);
    demoService.setRegistry(registry);
    demoService.setProtocol(protocol);

    ReferenceConfig<DemoService> rc = new ReferenceConfig<DemoService>();
    rc.setApplication(application);
    rc.setRegistry(registry);
    rc.setInterface(DemoService.class.getName());
    rc.setInjvm(false);

    try {
        demoService.export();
        rc.get();
        Assert.assertTrue(!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(
            rc.getInvoker().getUrl().getProtocol()));
    } finally {
        demoService.unexport();
    }
}
 
Example 26
Source Project: JavaLinuxNet   Source File: libnetlink3Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRtnlListen() throws Exception {

    libnetlink3.rtnl_handle handle;
    ByteBuffer buffer;
    int result=0;
    final Counter cnt=new Counter();

    logger.info("rtnl listen...");
    //open netlink3 socket
    handle=new libnetlink3.rtnl_handle();
    int groups = rtnetlink.RTMGRP_IPV4_IFADDR |
                 rtnetlink.RTMGRP_IPV4_ROUTE |
                 rtnetlink.RTMGRP_IPV4_MROUTE |
                 rtnetlink.RTMGRP_LINK;
    result=libnetlink3.rtnl_open_byproto(handle, groups,netlink.NETLINK_ROUTE);
    Assert.assertTrue(result == 0);
    //Request addres information
    logger.info("rtnl dump request");
    result=libnetlink3.rtnl_wilddump_request(handle, 0, rtnetlink.RTM_GETADDR);
    int retry=0;
    //this runs async so retry 10 times
    while(cnt.getCount()==0 & retry<10) {
        result=libnetlink3.rtnl_listen(handle, messageBuffer, new rtnl_accept() {
            @Override
            public int accept(ByteBuffer message) {
                logger.info("rtnl got message, stopping");
                cnt.inc();
                return libnetlink3.rtl_accept_STOP;
            }
        });
        Thread.sleep(100);
        retry++;
    }
    //we recieved a message ?
    Assert.assertTrue(cnt.getCount()==1);
    //close it
    libnetlink3.rtnl_close(handle);
}
 
Example 27
Source Project: datacollector   Source File: TestKuduTarget.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks that a LineageEvent is returned.
 * @throws Exception
 */
@Test
public void testLineageEvent() throws Exception{
  TargetRunner targetRunner = getTargetRunner(
      "${record:attribute('tableName')}",
      KuduOperationType.INSERT,
      UnsupportedOperationAction.DISCARD
  );

  Record record =  RecordCreator.create();
  LinkedHashMap<String, Field> field = new LinkedHashMap<>();
  field.put("key", Field.create(1));
  field.put("value", Field.create("value"));
  field.put("name", Field.create("name"));
  record.set(Field.createListMap(field));
  record.getHeader().setAttribute("tableName", "test_table");
  targetRunner.runInit();

  try {
    targetRunner.runWrite(ImmutableList.of(record));
  } catch (StageException e){
    Assert.fail();
  }
  List<LineageEvent> events = targetRunner.getLineageEvents();
  Assert.assertEquals(1, events.size());
  Assert.assertEquals(LineageEventType.ENTITY_WRITTEN, events.get(0).getEventType());
  Assert.assertEquals(
      "test_table",
      events.get(0).getSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME)
  );
  targetRunner.runDestroy();
}
 
Example 28
Source Project: zstack   Source File: TestSnapshotOnKvm43.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ApiSenderException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    VolumeInventory dataVol = CollectionUtils.find(vm.getAllVolumes(), new Function<VolumeInventory, VolumeInventory>() {
        @Override
        public VolumeInventory call(VolumeInventory arg) {
            if (arg.getType().equals(VolumeType.Data.toString())) {
                return arg;
            }
            return null;
        }
    });

    String volUuid = dataVol.getUuid();
    VolumeSnapshotInventory inv1 = api.createSnapshot(volUuid);
    fullSnapshot(inv1, 0);

    VolumeSnapshotInventory inv = api.createSnapshot(volUuid);
    deltaSnapshot(inv, 1);

    inv = api.createSnapshot(volUuid);
    deltaSnapshot(inv, 2);

    inv = api.createSnapshot(volUuid);
    deltaSnapshot(inv, 3);

    BackupStorageInventory sftp = deployer.backupStorages.get("sftp");
    api.backupSnapshot(inv.getUuid());

    api.deleteSnapshotFromBackupStorage(inv1.getUuid(), sftp.getUuid());

    BackupStorageVO sftpvo = dbf.findByUuid(sftp.getUuid(), BackupStorageVO.class);
    Assert.assertEquals(sftp.getAvailableCapacity(), sftpvo.getAvailableCapacity());
}
 
Example 29
Source Project: mini2Dx   Source File: UiContainerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredControllerTypeChangeNotification() {
	uiContainer.setLastGamePadType(GamePadType.PS4);

	Assert.assertEquals(true, listenerEvents.isEmpty());
	uiContainer.update(1f);
	Assert.assertEquals(true, listenerEvents.contains("gamePadTypeChanged"));
}
 
Example 30
Source Project: jagged   Source File: TreeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCanRealizeTreeEntry()
{
    final File repoPath = setupRepository("testrepo");
    Repository repository = new Repository(repoPath.getAbsolutePath());

    ObjectId oid = new ObjectId("e77ab1c63f3fbde9c5ef9972939aa0717012d7c0");
    Tree tree = repository.lookup(oid);

    TreeEntry entry = tree.getEntry("one.txt");
    Blob blob = entry.realize();

    Assert.assertEquals(new ObjectId("d1796967d47949153bb852c07304d9e5f2f0040c"), blob.getId());
}