junit.framework.Assert Java Examples

The following examples show how to use junit.framework.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: SingleDBPreparedStatementGroupFollowNoteIntegrationTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: DatabasePoolConfigParserTest.java    From dal with 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 #3
Source File: TestTransactionEventRecordV3.java    From mt-flume with 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 #4
Source File: ArrayEvaluatorTest.java    From lucene-solr with 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 File: TestSnapshotOnKvm42.java    From zstack with 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 File: TestExactTokenMatchDistance.java    From ensemble-clustering with 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 File: DaoSqlBriteIntegrationTest.java    From sqlbrite-dao with 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 File: ApiStatisticsTest.java    From product-ei with 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 File: MockClusterInvokerTest.java    From dubbo3 with 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
Source File: ResultTable.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 File: DeterministicIdResolverTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: AbstractDateCalculatorCombinationTest.java    From objectlabkit with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: TestLocalStorage54.java    From zstack with 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 #14
Source File: LocatorJUnitTest.java    From gemfirexd-oss with 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 #15
Source File: TestAlgebra.java    From Llunatic with 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 #16
Source File: TileMapServiceResourceIntegrationTest.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: TestVirtualRouterPortForwarding27.java    From zstack with 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 #18
Source File: CrossOperatorTest.java    From stratosphere with 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 #19
Source File: TestVLong.java    From RDFS with 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 #20
Source File: ConnectChannelHandlerTest.java    From dubbox with 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 #21
Source File: TestKafkaPrivilegeValidator.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private void testHostResourceIsChecked(KafkaPrivilegeValidator kafkaPrivilegeValidator, String privilege) {
  try {
    kafkaPrivilegeValidator.validate(new PrivilegeValidatorContext(privilege));
    Assert.fail("Expected ConfigurationException");
  } catch (ConfigurationException ex) {
    Assert.assertEquals("Kafka privilege must begin with host authorizable.\n" + KafkaPrivilegeValidator.KafkaPrivilegeHelpMsg, ex.getMessage());
  }
}
 
Example #22
Source File: TestSQLFlipFlop.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
public void testScenarioFlipFlop() throws Exception {
        Scenario scenario = UtilityTest.loadScenarioFromResources(References.flipflop_dmbs);
        setConfigurationForTest(scenario);
        if (logger.isDebugEnabled()) logger.debug("Scenario " + scenario);
        ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario);
        DeltaChaseStep result = chaser.doChase(scenario);
//        if (logger.isDebugEnabled()) logger.debug(result.toShortString());
        if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort());
        Assert.assertEquals(2, resultSizer.getPotentialSolutions(result));
        Assert.assertEquals(0, resultSizer.getDuplicates(result));
        checkSolutions(result);
//        exportResults("/Users/enzoveltri/Temp/lunatic_tmp/expectedFlipFlop", result);
        checkExpectedSolutions("expectedFlipFlop", result);
    }
 
Example #23
Source File: ChannelViewsTest.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteAndReadLongRecords() throws Exception
{
	final TestData.Generator generator = new TestData.Generator(SEED, KEY_MAX, VALUE_LONG_LENGTH, KeyMode.RANDOM, ValueMode.RANDOM_LENGTH);
	final Channel.ID channel = this.ioManager.createChannel();
	
	// create the writer output view
	List<MemorySegment> memory = this.memoryManager.allocatePages(this.parentTask, NUM_MEMORY_SEGMENTS);
	final BlockChannelWriter writer = this.ioManager.createBlockChannelWriter(channel);
	final ChannelWriterOutputView outView = new ChannelWriterOutputView(writer, memory, MEMORY_PAGE_SIZE);
	
	// write a number of pairs
	final Record rec = new Record();
	for (int i = 0; i < NUM_PAIRS_LONG; i++) {
		generator.next(rec);
		rec.write(outView);
	}
	this.memoryManager.release(outView.close());
	
	// create the reader input view
	memory = this.memoryManager.allocatePages(this.parentTask, NUM_MEMORY_SEGMENTS);
	final BlockChannelReader reader = this.ioManager.createBlockChannelReader(channel);
	final ChannelReaderInputView inView = new ChannelReaderInputView(reader, memory, outView.getBlockCount(), true);
	generator.reset();
	
	// read and re-generate all records and compare them
	final Record readRec = new Record();
	for (int i = 0; i < NUM_PAIRS_LONG; i++) {
		generator.next(rec);
		readRec.read(inView);
		final Key k1 = rec.getField(0, Key.class);
		final Value v1 = rec.getField(1, Value.class);
		final Key k2 = readRec.getField(0, Key.class);
		final Value v2 = readRec.getField(1, Value.class);
		Assert.assertTrue("The re-generated and the read record do not match.", k1.equals(k2) && v1.equals(v2));
	}
	
	this.memoryManager.release(inView.close());
	reader.deleteChannel();
}
 
Example #24
Source File: LatLngTest.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@Test
@Category(UnitTest.class)
public void testCalcDestNorthWestLimited() throws Exception
{
  LatLng p1 = new LatLng(89.99, -179.99);
  LatLng p2 = LatLng.calculateCartesianDestinationPoint(p1, LatLng.METERS_PER_DEGREE, 315.0);
  Assert.assertEquals(-180.0, p2.getLng(), EPSILON);
  Assert.assertEquals(90.0, p2.getLat(), EPSILON);
}
 
Example #25
Source File: RuntimeDelegateImplTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
public void testCreateResponseBuilder() {
	try {
		new RuntimeDelegateImpl().createResponseBuilder();
		Assert.fail();
	} catch (UnsupportedOperationException e) {
		// Ok
	}
}
 
Example #26
Source File: ReferenceConfigTest.java    From dubbox with 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 #27
Source File: MobileDeviceManagement.java    From product-emm with 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 #28
Source File: XmlIndexerConfWriterTest.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteNonRegexTable() throws Exception {
    Map<String, String> params = Maps.newHashMap();
    params.put("thename", "thevalue");
    IndexerConf conf = new IndexerConfBuilder()
            .table("myTable")
            .mappingType(IndexerConf.MappingType.COLUMN)
            .rowReadMode(IndexerConf.RowReadMode.DYNAMIC)
            .uniqueyKeyField("keyfield")
            .rowField("rf")
            .columnFamilyField("cf-field")
            .tableNameField("tn-field")
            .globalParams(params)
            .mapperClass(DefaultResultToSolrMapper.class)
            .uniqueKeyFormatterClass(StringUniqueKeyFormatter.class)
            .addFieldDefinition("fieldname", "fieldvalue", FieldDefinition.ValueSource.VALUE, "fieldtype", params)
            .addDocumentExtractDefinition("theprefix", "valueexpr", FieldDefinition.ValueSource.VALUE, "deftype", params)
            .build();

    IndexerConf conf2 = serializeDeserializeConf(conf);

    Assert.assertEquals("myTable",conf2.getTable());
    Assert.assertEquals(false, conf2.tableNameIsRegex());
    Assert.assertEquals(conf.getMappingType(),conf2.getMappingType());
    Assert.assertEquals(conf.getRowReadMode(),conf2.getRowReadMode());
    Assert.assertEquals(conf.getUniqueKeyField(),conf2.getUniqueKeyField());
    Assert.assertEquals(conf.getRowField(),conf2.getRowField());
    Assert.assertEquals(conf.getColumnFamilyField(),conf2.getColumnFamilyField());
    Assert.assertEquals(conf.getTableNameField(),conf2.getTableNameField());
    Assert.assertEquals(conf.getGlobalParams(), conf2.getGlobalParams());
    Assert.assertEquals(conf.getMapperClass(),conf2.getMapperClass());
    Assert.assertEquals(conf.getUniqueKeyFormatterClass(),conf2.getUniqueKeyFormatterClass());
    Assert.assertEquals(conf.getFieldDefinitions().size(),conf2.getFieldDefinitions().size());
    Assert.assertEquals(conf.getDocumentExtractDefinitions().size(),conf2.getDocumentExtractDefinitions().size());
}
 
Example #29
Source File: TestUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** verifies that two arrays are close (sup norm) */
public static void assertEquals(String msg, double[] expected, double[] observed,
    double tolerance) {
    StringBuffer out = new StringBuffer(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++) {
        try {
            assertEquals(expected[i], observed[i], tolerance);
        } catch (AssertionFailedError ex) {
            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());
    }
}
 
Example #30
Source File: BarcodeWithCountTest.java    From Drop-seq with MIT License 5 votes vote down vote up
@SuppressWarnings("unlikely-arg-type")
@Test
public void testBarcodeWithCountTest() {

	BarcodeWithCount b1 = new BarcodeWithCount("AAAA", 5);
	BarcodeWithCount b2 = new BarcodeWithCount("AAAA", 2);
	BarcodeWithCount b3 = new BarcodeWithCount("GGGG", 3);
	BarcodeWithCount b4 = new BarcodeWithCount("GGGG", 7);

	Assert.assertEquals("AAAA", b1.getBarcode());
	Assert.assertSame(5, b1.getCount());

	// equals uses barcode name and count.
	Assert.assertTrue(b1.equals(b1));
	Assert.assertFalse(b1.equals(b2));
	Assert.assertFalse(b1.equals(b3));

	// other dumb tests for coverage
	Assert.assertFalse(b1.equals(null));
	Assert.assertFalse(b1.equals(new String ("Foo")));
	Assert.assertNotNull(b1.hashCode());

	// compares by count alone.
	BarcodeWithCount.CountComparator c = new BarcodeWithCount.CountComparator();
	int r = c.compare(b1, b2);
	Assert.assertTrue(r>0);




}