@Test public void testResetBadgeCount_shouldMakeRequest_viaRestClient() { RequestModel expected = createRequestModel("https://me-inbox.eservice.emarsys.net/api/reset-badge-count", RequestMethod.POST); RestClient mockRestClient = mock(RestClient.class); inbox.client = mockRestClient; inbox.setAppLoginParameters(appLoginParameters_withCredentials); inbox.resetBadgeCount(resetListenerMock); ArgumentCaptor<RequestModel> requestCaptor = ArgumentCaptor.forClass(RequestModel.class); verify(mockRestClient).execute(requestCaptor.capture(), any(CoreCompletionHandler.class)); RequestModel requestModel = requestCaptor.getValue(); Assert.assertNotNull(requestModel.getId()); Assert.assertNotNull(requestModel.getTimestamp()); Assert.assertEquals(expected.getUrl(), requestModel.getUrl()); Assert.assertEquals(expected.getHeaders(), requestModel.getHeaders()); Assert.assertEquals(expected.getMethod(), requestModel.getMethod()); }
@Test public void testSpecialCharDDL() throws Exception { SchemaConfig schema = schemaMap.get("TESTDB"); CacheService cacheService = new CacheService(false); RouteService routerService = new RouteService(cacheService); // alter table test String sql = " ALTER TABLE COMPANY\r\nADD COLUMN TEST VARCHAR(255) NULL AFTER CREATE_DATE,\r\n CHARACTER SET = UTF8"; sql = RouterUtil.getFixedSql(sql); List<String> dataNodes = new ArrayList<>(); String tablename = "COMPANY"; Map<String, TableConfig> tables = schema.getTables(); TableConfig tc; if (tables != null && (tc = tables.get(tablename)) != null) { dataNodes = tc.getDataNodes(); } int nodeSize = dataNodes.size(); int rs = ServerParse.parse(sql); int sqlType = rs & 0xff; RouteResultset rrs = routerService.route(schema, sqlType, sql, null); Assert.assertTrue("COMPANY".equals(tablename)); Assert.assertTrue(rrs.getNodes().length == nodeSize); }
@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()); }
@Test public void test_getAdaptiveExtension_inject() throws Exception { LogUtil.start(); Ext6 ext = ExtensionLoader.getExtensionLoader(Ext6.class).getAdaptiveExtension(); URL url = new URL("p1", "1.2.3.4", 1010, "path1"); url = url.addParameters("ext6", "impl1"); assertEquals("Ext6Impl1-echo-Ext1Impl1-echo", ext.echo(url, "ha")); Assert.assertTrue("can not find error.", LogUtil.checkNoError()); LogUtil.stop(); url = url.addParameters("simple.ext", "impl2"); assertEquals("Ext6Impl1-echo-Ext1Impl2-echo", ext.echo(url, "ha")); }
/** * 测试清除override规则,同时下发清除规则和其他override规则 * 测试是否能够恢复到推送时的providerUrl */ @Test public void testNofityOverrideUrls_Clean1(){ RegistryDirectory registryDirectory = getRegistryDirectory(); invocation = new RpcInvocation(); List<URL> durls = new ArrayList<URL>(); durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); registryDirectory.notify(durls); durls = new ArrayList<URL>(); durls.add(URL.valueOf("override://0.0.0.0?timeout=1000")); registryDirectory.notify(durls); durls = new ArrayList<URL>(); durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); durls.add(URL.valueOf("override://0.0.0.0")); registryDirectory.notify(durls); List<Invoker<?>> invokers = registryDirectory.list(invocation); Invoker<?> aInvoker = invokers.get(0); //需要恢复到最初的providerUrl Assert.assertEquals("1",aInvoker.getUrl().getParameter("timeout")); }
private static void generateData(File file, Charset charset, int numLines, int lineLen) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); StringBuilder junk = new StringBuilder(); for (int x = 0; x < lineLen - 13; x++) { junk.append('x'); } String payload = junk.toString(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < numLines; i++) { builder.append(String.format("%010d: %s\n", i, payload)); if (i % 1000 == 0 && i != 0) { out.write(builder.toString().getBytes(charset)); builder.setLength(0); } } out.write(builder.toString().getBytes(charset)); out.close(); Assert.assertEquals(lineLen * numLines, file.length()); }
private void assertSrcCounterState(ObjectName on, long eventReceivedCount, long eventAcceptedCount, long appendReceivedCount, long appendAcceptedCount, long appendBatchReceivedCount, long appendBatchAcceptedCount) throws Exception { Assert.assertEquals("SrcEventReceived", getSrcEventReceivedCount(on), eventReceivedCount); Assert.assertEquals("SrcEventAccepted", getSrcEventAcceptedCount(on), eventAcceptedCount); Assert.assertEquals("SrcAppendReceived", getSrcAppendReceivedCount(on), appendReceivedCount); Assert.assertEquals("SrcAppendAccepted", getSrcAppendAcceptedCount(on), appendAcceptedCount); Assert.assertEquals("SrcAppendBatchReceived", getSrcAppendBatchReceivedCount(on), appendBatchReceivedCount); Assert.assertEquals("SrcAppendBatchAccepted", getSrcAppendBatchAcceptedCount(on), appendBatchAcceptedCount); }
public void testSaveWithConstructors() { Computer computer = new Computer("asus", 699.00); assertTrue(computer.save()); Assert.assertTrue(isDataExists(getTableName(computer), computer.getId())); Computer c = getComputer(computer.getId()); assertEquals("asus", c.getBrand()); assertEquals(699.00, c.getPrice()); Computer cc = DataSupport.find(Computer.class, computer.getId()); assertEquals("asus", cc.getBrand()); assertEquals(699.00, cc.getPrice()); Product p = new Product(null); p.setBrand("apple"); p.setPrice(1222.33); p.save(); Product.find(Product.class, p.getId()); }
@Test public void testGenericFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation("$invoke", new Class<?>[] { String.class, String[].class, Object[].class }, new Object[] { "xxx", new String[] {}, new Object[] {} } ); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); monitorFilter.invoke(serviceInvoker, invocation); while (lastStatistics == null) { Thread.sleep(10); } Assert.assertEquals("abc", lastStatistics.getParameter(MonitorService.APPLICATION)); Assert.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(MonitorService.INTERFACE)); Assert.assertEquals("xxx", lastStatistics.getParameter(MonitorService.METHOD)); Assert.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER)); Assert.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); Assert.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER)); Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0)); Assert.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0)); Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0)); Assert.assertEquals(invocation, lastInvocation); }
@Override public boolean addListener(final String eventId, final IDownloadListener listener) { if (FileDownloadLog.NEED_LOG) { FileDownloadLog.v(this, "setListener %s", eventId); } Assert.assertNotNull("EventPoolImpl.add", listener); LinkedList<IDownloadListener> container = listenersMap.get(eventId); if (container == null) { synchronized (eventId.intern()) { container = listenersMap.get(eventId); if (container == null) { listenersMap.put(eventId, container = new LinkedList<>()); } } } synchronized (eventId.intern()) { return container.add(listener); } }
/** * Compares the two given texts after removing the given line from both texts. * * @param expectedText * @param actualText * @param lineNumber to remove from both texts before comparing them. The first line is 1. * @throws IOException */ public static void compareSkipLine(String expectedText, String actualText, int lineNumber) throws IOException { //remove line. actualText = removeLine(actualText, lineNumber); if (actualText.isEmpty()) { Assert.fail("Actual text is empty after removing line " + lineNumber + ". Nothing to compare."); } expectedText = removeLine(expectedText, lineNumber); if (expectedText.isEmpty()) { Assert.fail("Expected text is empty after removing line " + lineNumber + ". Nothing to compare."); } Assert.assertEquals("Actual text does not equal expected text after removing line " + lineNumber + " from both texts.", expectedText, actualText); }
public void run() { if (check()) { return; } long timeout = mTimeout; while (timeout > 0) { try { Thread.sleep(TIME_SLICE); } catch (InterruptedException e) { Assert.fail("unexpected InterruptedException"); } if (check()) { return; } timeout -= TIME_SLICE; } Assert.fail("unexpected timeout"); }
public static void cropAndRescaleBitmap(final Bitmap src, final Bitmap dst, int sensorOrientation) { Assert.assertEquals(dst.getWidth(), dst.getHeight()); final float minDim = Math.min(src.getWidth(), src.getHeight()); final Matrix matrix = new Matrix(); // We only want the center square out of the original rectangle. final float translateX = -Math.max(0, (src.getWidth() - minDim) / 2); final float translateY = -Math.max(0, (src.getHeight() - minDim) / 2); matrix.preTranslate(translateX, translateY); final float scaleFactor = dst.getHeight() / minDim; matrix.postScale(scaleFactor, scaleFactor); // Rotate around the center if necessary. if (sensorOrientation != 0) { matrix.postTranslate(-dst.getWidth() / 2.0f, -dst.getHeight() / 2.0f); matrix.postRotate(sensorOrientation); matrix.postTranslate(dst.getWidth() / 2.0f, dst.getHeight() / 2.0f); } final Canvas canvas = new Canvas(dst); canvas.drawBitmap(src, matrix, null); }
@Test public void testBatchEventsWithoutMatTotalEvents() throws InterruptedException, EventDeliveryException { StressSource source = new StressSource(); source.setChannelProcessor(mockProcessor); Context context = new Context(); context.put("batchSize", "10"); source.configure(context); source.start(); for (int i = 0; i < 10; i++) { Assert.assertFalse("StressSource with no maxTotalEvents should not return " + Status.BACKOFF, source.process() == Status.BACKOFF); } verify(mockProcessor, times(10)).processEventBatch(getLastProcessedEventList(source)); long successfulEvents = getCounterGroup(source).get("events.successful"); TestCase.assertTrue("Number of successful events should be 100 but was " + successfulEvents, successfulEvents == 100); long failedEvents = getCounterGroup(source).get("events.failed"); TestCase.assertTrue("Number of failure events should be 0 but was " + failedEvents, failedEvents == 0); }
private void changeMap(IUT2004Server server, String map) { if (awaitAgentUp((AbstractAgent)server)) { System.out.println("Changing map to '" + map + "'..."); Future<Boolean> future = server.setGameMap(map); try { System.out.println("Waiting for the GB2004 to change the map (60sec timeout)."); Boolean result = future.get(60000, TimeUnit.MILLISECONDS); if (result == null || !result) { Assert.fail("Failed to change map to '" + map + "'."); } } catch (Exception e) { Assert.fail("Failed to change map to '" + map + "'."); } } else { Assert.fail("Failed to connect to GB2004..."); } }
@Test public void test_Notified_acceptProtocol0() { URL errorPathUrl = URL.valueOf("notsupport:/xxx?refer=" + URL.encode("interface="+service)); RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); List<URL> serviceUrls = new ArrayList<URL>(); URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9099?lazy=true&methods=getXXX"); serviceUrls.add(dubbo1URL); serviceUrls.add(dubbo2URL); registryDirectory.notify(serviceUrls); invocation = new RpcInvocation(); List<Invoker<DemoService>> invokers = registryDirectory.list(invocation); Assert.assertEquals(2, invokers.size()); }
@Test public void testHeapFileScanWithManyPages() throws IOException, DbException, TransactionAbortedException { System.out.println("EvictionTest creating large table"); HeapFile f = SystemTestUtil.createRandomHeapFile(2, 1024*500, null, null); System.out.println("EvictionTest scanning large table"); Database.resetBufferPool(BUFFER_PAGES); long beginMem = SystemTestUtil.getMemoryFootprint(); TransactionId tid = new TransactionId(); SeqScan scan = new SeqScan(tid, f.getId(), ""); scan.open(); while (scan.hasNext()) { scan.next(); } System.out.println("EvictionTest scan complete, testing memory usage of scan"); long endMem = SystemTestUtil.getMemoryFootprint(); long memDiff = (endMem - beginMem) / (1<<20); if (memDiff > MEMORY_LIMIT_IN_MB) { Assert.fail("Did not evict enough pages. Scan took " + memDiff + " MB of RAM, when limit was " + MEMORY_LIMIT_IN_MB); } }
/** * When the first arg of a method is String or Enum, Registry server can do parameter-value-based routing. */ @Test public void testParmeterRoute() { RegistryDirectory registryDirectory = getRegistryDirectory(); List<URL> serviceUrls = new ArrayList<URL>(); serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1.napoli")); serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1.MORGAN,getXXX2")); serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1.morgan,getXXX2,getXXX3")); registryDirectory.notify(serviceUrls); invocation = new RpcInvocation( Constants.$INVOKE, new Class[] { String.class, String[].class, Object[].class }, new Object[] { "getXXX1", new String[] { "Enum" }, new Object[] { Param.MORGAN } }); List invokers = registryDirectory.list(invocation); Assert.assertEquals(1, invokers.size()); }
@Test public void testRequest() { ReqLoginMessage request = new ReqLoginMessage(); request.setAccountId(123456L); request.setPassword("kingston"); Codec<ReqLoginMessage> simpleTypeCodec = ProtobufProxy .create(ReqLoginMessage.class); try { // 序列化 byte[] bb = simpleTypeCodec.encode(request); // 反序列化 ReqLoginMessage request2 = simpleTypeCodec.decode(bb); Assert.assertTrue(request2.getAccountId() == request.getAccountId()); Assert.assertTrue(request2.getPassword().equals(request.getPassword())); } catch (IOException e) { e.printStackTrace(); } }
@Test public void testGetConfiguration_MarketplaceNotFound() throws Exception { // Mock logging Log4jLogger loggerMock = mock(Log4jLogger.class); when(beanSpy.getLogger()).thenReturn(loggerMock); final String marketplaceId = "notFound"; when(msMock.getMarketplaceById(Matchers.anyString())).thenThrow( new ObjectNotFoundException()); // Simulate accessing none existing marketplace MarketplaceConfiguration mpc = beanSpy.getConfiguration(marketplaceId); // Ensure error is logged... verify(loggerMock, times(1)).logError( Matchers.eq(Log4jLogger.SYSTEM_LOG), Matchers.any(ObjectNotFoundException.class), Matchers.eq(LogMessageIdentifier.ERROR_MARKETPLACE_NOT_FOUND), Matchers.eq(marketplaceId)); // and default configuration is returned Assert.assertNull(mpc); }
/** * ?zone={zone_id}&pub={publisher_id}&prot={protocol}&h={height}&w={width}&sd={startdelay}&mime={mime_type}&domain={domain}&page={page}&ad={adid} */ @Test public void testParamsComplete() { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); request.addParameter("site", "1"); RequestSessionAgent agent = null; try { agent = new RequestSessionAgent(request, response); } catch (final RequestException e) { Assert.fail(e.getMessage()); } Assert.assertEquals("1", agent.getParamValues().getSite().getId()); }
@Test public void testFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); Invocation invocation = new RpcInvocation("aaa", new Class<?>[0], new Object[0]); RpcContext.getContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); monitorFilter.invoke(serviceInvoker, invocation); while (lastStatistics == null) { Thread.sleep(10); } Assert.assertEquals("abc", lastStatistics.getParameter(MonitorService.APPLICATION)); Assert.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(MonitorService.INTERFACE)); Assert.assertEquals("aaa", lastStatistics.getParameter(MonitorService.METHOD)); Assert.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(MonitorService.PROVIDER)); Assert.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress()); Assert.assertEquals(null, lastStatistics.getParameter(MonitorService.CONSUMER)); Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.SUCCESS, 0)); Assert.assertEquals(0, lastStatistics.getParameter(MonitorService.FAILURE, 0)); Assert.assertEquals(1, lastStatistics.getParameter(MonitorService.CONCURRENT, 0)); Assert.assertEquals(invocation, lastInvocation); }
public static void waitScanFinished() { try { class Wait implements Runnable { boolean initialized; boolean ok; public void run() { if (initialized) { ok = true; return; } initialized = true; boolean canceled = ScanDialog.runWhenScanFinished(this, "tests"); Assert.assertFalse("Dialog really finished", canceled); Assert.assertTrue("Runnable run", ok); } } Wait wait = new Wait(); SwingUtilities.invokeAndWait(wait); } catch (Exception ex) { throw (AssertionFailedError)new AssertionFailedError().initCause(ex); } }
@Test public void testRunnerReturns() { QuickPeriodicJobRunner qpjr = new QuickPeriodicJobRunner(); JobParameters jp = mock(JobParameters.class); doReturn(5).when(jp).getJobId(); Assert.assertTrue(qpjr.onStartJob(jp)); Assert.assertTrue(qpjr.onStopJob(jp)); }
private void test_Notified3invokers(RegistryDirectory registryDirectory) { List<URL> serviceUrls = new ArrayList<URL>(); serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); registryDirectory.notify(serviceUrls); Assert.assertEquals(true, registryDirectory.isAvailable()); invocation = new RpcInvocation(); List invokers = registryDirectory.list(invocation); Assert.assertEquals(3, invokers.size()); invocation.setMethodName("getXXX"); invokers = registryDirectory.list(invocation); Assert.assertEquals(3, invokers.size()); invocation.setMethodName("getXXX1"); invokers = registryDirectory.list(invocation); Assert.assertEquals(3, invokers.size()); invocation.setMethodName("getXXX2"); invokers = registryDirectory.list(invocation); Assert.assertEquals(2, invokers.size()); invocation.setMethodName("getXXX3"); invokers = registryDirectory.list(invocation); Assert.assertEquals(1, invokers.size()); }
/** Sets the GTS to a given grammar in the JUnit samples. */ private void prepare(String grammarName) { try { Generator generator = new Generator("-v", "0", "junit/samples/" + grammarName); ExploreResult result = generator.start(); if (result != null) { this.gts = result.getGTS(); } } catch (Exception e) { Assert.fail(e.toString()); } }
/** * 测试mock策略是否正常-fail-mock */ @Test public void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock(){ URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName()) .addParameter("mock","true") .addParameter("invoke_return_error", "true" ); Invoker<IHelloService> cluster = getClusterInvoker(url); //方法配置了mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assert.assertEquals("somethingmock", ret.getValue()); }
@Test public void addCorrectlyUpdatesTrack() { CheckPoint c1 = buildCheckPoint(50, 50); CheckPoint c2 = buildCheckPoint(51, 51); Track testTrack = new Track(c1); testTrack.add(c2); Assert.assertEquals(2, testTrack.getTotalCheckPoints()); Assert.assertEquals(51, testTrack.getLastPoint().getLatitude(), 0); Assert.assertEquals(51, testTrack.getLastPoint().getLongitude(), 0); Assert.assertEquals(c2.distanceTo(c1), testTrack.getDistance()); }
@Test public void testReferGenericExport() throws Exception { ApplicationConfig ac = new ApplicationConfig("test-refer-generic-export"); RegistryConfig rc = new RegistryConfig(); rc.setAddress(RegistryConfig.NO_AVAILABLE); ServiceConfig<GenericService> sc = new ServiceConfig<GenericService>(); sc.setApplication(ac); sc.setRegistry(rc); sc.setInterface(DemoService.class.getName()); sc.setRef(new GenericService() { public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { return null; } }); ReferenceConfig<DemoService> ref = new ReferenceConfig<DemoService>(); ref.setApplication(ac); ref.setRegistry(rc); ref.setInterface(DemoService.class.getName()); try { sc.export(); ref.get(); Assert.fail(); } catch (Exception e) { e.printStackTrace(); } finally { sc.unexport(); ref.destroy(); } }
public static void assertContainsAllOf(Iterable<?> actual, Object... expected) { List<Object> expectedList = new ArrayList<Object>(); expectedList.addAll(Arrays.asList(expected)); for (Object o : actual) { expectedList.remove(o); } if (!expectedList.isEmpty()) { Assert.fail("Not true that " + actual + " contains all of " + Arrays.asList(expected)); } }
@Test public void getPresenterReturnsNull(){ Activity activity = Mockito.mock(Activity.class); Application application = Mockito.mock(Application.class); Mockito.when(activity.getApplication()).thenReturn(application); Assert.assertNull(PresenterManager.getPresenter(activity, "viewId123")); }
/** * Verify that the listener completes in a reasonable amount of time, and * Asserts that the future throws an {@code ExecutableException} and that the * cause of the {@code ExecutableException} is {@code expectedCause}. */ public void assertException(Throwable expectedCause) throws Exception { // Verify that the listener executed in a reasonable amount of time. Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS)); try { future.get(); Assert.fail("This call was supposed to throw an ExecutionException"); } catch (ExecutionException expected) { Assert.assertSame(expectedCause, expected.getCause()); } }
@Test public void testSingleWriterUseHeaders() throws Exception { String[] colNames = {COL1, COL2}; String PART1_NAME = "country"; String PART2_NAME = "hour"; String[] partNames = {PART1_NAME, PART2_NAME}; List<String> partitionVals = null; String PART1_VALUE = "%{" + PART1_NAME + "}"; String PART2_VALUE = "%y-%m-%d-%k"; partitionVals = new ArrayList<String>(2); partitionVals.add(PART1_VALUE); partitionVals.add(PART2_VALUE); String tblName = "hourlydata"; TestUtil.dropDB(conf, dbName2); String dbLocation = dbFolder.newFolder(dbName2).getCanonicalPath() + ".db"; dbLocation = dbLocation.replaceAll("\\\\","/"); // for windows paths TestUtil.createDbAndTable(driver, dbName2, tblName, partitionVals, colNames, colTypes, partNames, dbLocation); int totalRecords = 4; int batchSize = 2; int batchCount = totalRecords / batchSize; Context context = new Context(); context.put("hive.metastore",metaStoreURI); context.put("hive.database",dbName2); context.put("hive.table",tblName); context.put("hive.partition", PART1_VALUE + "," + PART2_VALUE); context.put("autoCreatePartitions","true"); context.put("useLocalTimeStamp", "false"); context.put("batchSize","" + batchSize); context.put("serializer", HiveDelimitedTextSerializer.ALIAS); context.put("serializer.fieldnames", COL1 + ",," + COL2 + ","); context.put("heartBeatInterval", "0"); Channel channel = startSink(sink, context); Calendar eventDate = Calendar.getInstance(); List<String> bodies = Lists.newArrayList(); // push events in two batches - two per batch. each batch is diff hour Transaction txn = channel.getTransaction(); txn.begin(); for (int j = 1; j <= totalRecords; j++) { Event event = new SimpleEvent(); String body = j + ",blah,This is a log message,other stuff"; event.setBody(body.getBytes()); eventDate.clear(); eventDate.set(2014, 03, 03, j % batchCount, 1); // yy mm dd hh mm event.getHeaders().put( "timestamp", String.valueOf(eventDate.getTimeInMillis()) ); event.getHeaders().put( PART1_NAME, "Asia" ); bodies.add(body); channel.put(event); } // execute sink to process the events txn.commit(); txn.close(); checkRecordCountInTable(0, dbName2, tblName); for (int i = 0; i < batchCount ; i++) { sink.process(); } checkRecordCountInTable(totalRecords, dbName2, tblName); sink.stop(); // verify counters SinkCounter counter = sink.getCounter(); Assert.assertEquals(2, counter.getConnectionCreatedCount()); Assert.assertEquals(2, counter.getConnectionClosedCount()); Assert.assertEquals(2, counter.getBatchCompleteCount()); Assert.assertEquals(0, counter.getBatchEmptyCount()); Assert.assertEquals(0, counter.getConnectionFailedCount() ); Assert.assertEquals(4, counter.getEventDrainAttemptCount()); Assert.assertEquals(4, counter.getEventDrainSuccessCount() ); }
@Test public void testget() { int id = 1; App app = null; while (true) { app = appMapper.get(id); id++; if (app != null) { break; } } Assert.assertNotNull(app.getId()); }
@Test() public void uiLessShouldFail() { try { SupportFragmentTestUtil.startVisibleFragment(new UiLessFragment()); Assert.fail("Exception expected"); } catch (IllegalStateException e) { Assert.assertEquals( "It seems that you are using "+UiLessFragment.class.getCanonicalName()+" as headless (UI less) fragment (because onViewCreated() has not been called or maybe delegation misses that part). Having a Presenter without a View (UI) doesn't make sense. Simply use an usual fragment instead of an MvpFragment if you want to use a UI less Fragment", e.getMessage()); } }
@Test public void testLbDefaultClientTwoHosts() throws Exception { Server s1 = null; Server s2 = null; RpcClient c = null; try { LoadBalancedAvroHandler h1 = new LoadBalancedAvroHandler(); LoadBalancedAvroHandler h2 = new LoadBalancedAvroHandler(); s1 = RpcTestUtils.startServer(h1); s2 = RpcTestUtils.startServer(h2); Properties p = new Properties(); p.put("hosts", "h1 h2"); p.put("client.type", "default_loadbalance"); p.put("hosts.h1", "127.0.0.1:" + s1.getPort()); p.put("hosts.h2", "127.0.0.1:" + s2.getPort()); c = RpcClientFactory.getInstance(p); Assert.assertTrue(c instanceof LoadBalancingRpcClient); for (int i = 0; i < 100; i++) { c.append(getEvent(i)); } Assert.assertEquals(50, h1.getAppendCount()); Assert.assertEquals(50, h2.getAppendCount()); } finally { if (s1 != null) s1.close(); if (s2 != null) s2.close(); if (c != null) c.close(); } }
@Test public void testDefaultPort() { MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7")); try { MulticastSocket multicastSocket = multicastRegistry.getMutilcastSocket(); Assert.assertEquals(1234, multicastSocket.getLocalPort()); } finally { multicastRegistry.destroy(); } }
@Test public void testBootstrapLookup() { Context context = new Context(); context.put(ZOOKEEPER_CONNECT_FLUME_KEY, kafkaServer.getZkConnectString()); context.put(TOPIC, "old.topic"); context.put(OLD_GROUP_ID, "old.groupId"); KafkaSource source = new KafkaSource(); source.doConfigure(context); String bootstrapServers = source.getBootstrapServers(); Assert.assertEquals(kafkaServer.getBootstrapServers(), bootstrapServers); }
@Test public void testVoce() { clause.setSubject(voce); clause.setVerb(cantar); String realisation = realiser.realise(clause).getRealisation(); // System.out.println(realisation); Assert.assertEquals("você canta", realisation); }