src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
BatchMetaCollection implements MutableMetaCollection { public final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts() { return docPartsByRef.values().stream(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> st... | @Test public void testConstructor() { assertTrue("The constructor do not copy doc parts contained by the delegate", collection.streamContainedMetaDocParts() .findAny() .isPresent() ); assertTrue("There is at least one doc part that is marked as created on the current branch", collection.streamContainedMetaDocParts() .n... |
BatchMetaCollection implements MutableMetaCollection { @Override public BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier) throws IllegalArgumentException { MutableMetaDocPart delegateDocPart = delegate.addMetaDocPart(tableRef, identifier); BatchMetaDocPart myDocPart = new BatchMetaDocPart( delegateD... | @Test public void testAddMetaDocPart() { TableRef tableRef = tableRefFactory.createChild(tableRefFactory.createRoot(), "aPath"); String tableId = "aTableId"; BatchMetaDocPart newDocPart = collection.addMetaDocPart(tableRef, tableId); assertNotNull(newDocPart); assertEquals(newDocPart, collection.getMetaDocPartByTableRe... |
BatchMetaCollection implements MutableMetaCollection { @Override public String getName() { return delegate.getName(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchM... | @Test public void testGetName() { assertEquals(collection.getName(), delegate.getName()); } |
BatchMetaCollection implements MutableMetaCollection { @Override public String getIdentifier() { return delegate.getIdentifier(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Ite... | @Test public void testGetIdentifier() { assertEquals(collection.getIdentifier(), delegate.getIdentifier()); } |
CompletionExceptions { public static Throwable getFirstNonCompletionException(Throwable ex) { Throwable throwableResult = ex; while (isCompletionException(throwableResult)) { Throwable cause = throwableResult.getCause(); if (cause == null || cause == throwableResult) { return throwableResult; } throwableResult = cause;... | @Test public void firstNonCompletionExceptionIsReturned() throws Exception { Throwable nullPointerException = new NullPointerException(); Throwable completionException = new CompletionException("message", nullPointerException); Throwable result = CompletionExceptions.getFirstNonCompletionException(completionException);... |
HexUtils { public static String bytes2Hex(@Nonnull byte[] bytes) { checkNotNull(bytes, "bytes"); final int length = bytes.length; final char[] chars = new char[length << 1]; int index; int charPos = 0; for (int i = 0; i < length; i++) { index = (bytes[i] & 0xFF) << 1; chars[charPos++] = BYTE_HEX_VALUES[index++]; chars[... | @Test public void bytes2HexArray() { String expected = DatatypeConverter.printHexBinary(bytes); String result = HexUtils.bytes2Hex(bytes); assertEquals(expected, result); }
@Test public void bytes2HexCollection() { String expected = DatatypeConverter.printHexBinary(bytes); List<Byte> collectionBytes = new ArrayList<>(b... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public ToroMetricRegistry createSubRegistry(String key, String value) { return new DirectoryToroMetricRegistry( directory.createDirectory(key, value), safeMetricRegistry ); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricReg... | @Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalKey() { registry.createSubRegistry("a-illegal-key", "avalue"); }
@Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalValue() { registry.createSubRegistry("aValue", "a-illegal-value"); }
@T... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Counter counter(String finalName) { return safeMetricRegistry.counter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String ... | @Test public void testCounter() { String sName = "legalName"; Name name = directory.createName(sName); Counter metric = registry.counter(sName); verify(safeRegistry).counter(name); assertThat(metric, is(safeRegistry.counter(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalCounter() { S... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Meter meter(String finalName) { return safeMetricRegistry.meter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, S... | @Test public void testMeter() { String sName = "legalName"; Name name = directory.createName(sName); Meter metric = registry.meter(sName); verify(safeRegistry).meter(name); assertThat(metric, is(safeRegistry.meter(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalMeter() { String sName ... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Histogram histogram(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.histogram(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Overr... | @Test public void testHistogram() { String sName = "legalName"; Name name = directory.createName(sName); Histogram metric = registry.histogram(sName); verify(safeRegistry).histogram(name, false); assertThat(metric, is(safeRegistry.histogram(name))); }
@Test(expected = IllegalArgumentException.class) public void testIll... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Timer timer(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.timer(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetr... | @Test public void testTimer() { String sName = "legalName"; Name name = directory.createName(sName); Timer metric = registry.timer(sName); verify(safeRegistry).timer(name, false); assertThat(metric, is(safeRegistry.timer(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalTimer() { String... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T> SettableGauge<T> gauge(String finalName) { return safeMetricRegistry.gauge(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistr... | @Test public void testGauge() { String sName = "legalName"; Name name = directory.createName(sName); SettableGauge<?> metric = registry.gauge(sName); verify(safeRegistry).gauge(name); assertThat(metric, is(safeRegistry.gauge(name))); }
@Test(expected = IllegalArgumentException.class) public void testIllegalGauge() { St... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T extends Metric> T register(String finalName, T metric) { return safeMetricRegistry.register(directory.createName(finalName), metric); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricR... | @Test public void testRegister() { String sName = "legalName"; Name name = directory.createName(sName); Counter actualCounter = new Counter(); Counter metric = registry.register(sName, actualCounter); verify(safeRegistry).register(name, actualCounter); assertThat(metric, is(safeRegistry.register(name, actualCounter)));... |
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public boolean remove(String finalName) { return safeMetricRegistry.remove(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String ke... | @Test public void testRemove() { String sName = "legalName"; Name name = directory.createName(sName); registry.remove(sName); verify(safeRegistry).remove(name); }
@Test(expected = IllegalArgumentException.class) public void testIllegalRemove() { String sName = "illegal-Name"; registry.remove(sName); } |
ConcurrentOplogBatchExecutor extends SimpleAnalyzedOplogBatchExecutor { @Override public void execute(CudAnalyzedOplogBatch cudBatch, ApplierContext context) throws UserException { assert isRunning() : "The service is on state " + state() + " instead of RUNNING"; List<NamespaceJob> namespaceJobList = cudBatch.streamNam... | @Test public void testExecute() throws Exception { int batchSize = 100; int opsPerJob = 20; int subBatchSize = 11; int subBatchesPerJob = opsPerJob / subBatchSize + (opsPerJob % subBatchSize != 0 ? 1 : 0); int expectedSize = batchSize * subBatchesPerJob; CudAnalyzedOplogBatch batch = mock(CudAnalyzedOplogBatch.class); ... |
EssentialInjectorFactory { public static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory) { return createEssentialInjector(lifecycleLoggerFactory, () -> true, Clock.systemUTC()); } private EssentialInjectorFactory(); static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory); s... | @Test public void testCreateEssentialInjector() { EssentialInjectorFactory.createEssentialInjector(DefaultLoggerFactory.getInstance()); } |
SimpleAnalyzedOplogBatchExecutor extends AbstractService implements AnalyzedOplogBatchExecutor { @Override public void execute(OplogOperation op, ApplierContext context) throws OplogApplyingException, RollbackException, UserException { oplogOperationApplier.apply(op, server, context); } @Inject SimpleAnalyzedOplogBatc... | @Test public void testExecute_OplogOperation() throws Exception { OplogOperation op = mock(OplogOperation.class); ApplierContext applierContext = new ApplierContext.Builder() .setReapplying(true) .setUpdatesAsUpserts(true) .build(); executor.execute(op, applierContext); then(applier).should().apply(op, server, applierC... |
AbstractAnalyzedOp extends AnalyzedOp { @Override public Status<?> getMismatchErrorMessage() throws UnsupportedOperationException { if (!requiresMatch()) { throw new UnsupportedOperationException(); } return Status.from(ErrorCode.OPERATION_FAILED); } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type,
... | @Test public void getMismatchErrorMessageTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); if (op.getType().requiresMatch()) { Status<?> status = op.getMismatchErrorMessage(); assertNotNull( "The mismatch error of an analyzed operation that requires match must not be null", status); assertFalse("The mismatch e... |
AbstractAnalyzedOp extends AnalyzedOp { @Override public KvValue<?> getMongoDocId() { return mongoDocId; } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type,
@Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override Kv... | @Test public void getMongoDocIdTest() { assertEquals("Unexpected mongo doc id.", defaultMongoDocId, getAnalyzedOp(defaultMongoDocId) .getMongoDocId()); } |
FastMath { public static Vector2 rotateVector90(Vector2 v, Vector2 newVector) { float x = -v.y; float y = v.x; newVector.set(x, y); return newVector; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); sta... | @Test public void testRotateVector90() { Vector2 v1 = new Vector2(1, 0); Vector2 expected = new Vector2(0, 1); Vector2 rotatedVector = FastMath.rotateVector90(v1); assertEquals( "wrong rotated vector calculation, expected: " + expected + ", calculated vector: " + rotatedVector, true, (expected.x == rotatedVector.x && e... |
FastMath { public static boolean checkVectorsParallel(Vector2 v1, Vector2 v2) { Vector2 rotatedVector1 = rotateVector90(v1, Vector2Pool.create()); float dotProduct = rotatedVector1.dot(v2); Vector2Pool.free(rotatedVector1); return dotProduct == 0; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static V... | @Test public void testCheckVectorsParallel() { Vector2 v1 = new Vector2(1, 1); Vector2 v2 = new Vector2(1, 1); assertEquals(true, FastMath.checkVectorsParallel(v1, v2)); assertEquals(true, FastMath.checkVectorsParallel(v2, v1)); Vector2 v3 = new Vector2(1, 2); assertEquals(false, FastMath.checkVectorsParallel(v1, v3));... |
FastMath { public static boolean checkIfLinesAreEquals(Line a, Line b) { if (!checkVectorsParallel(a.getDirection(), b.getDirection())) { return false; } Vector2 d = Vector2Pool.create(); d.set(a.getBase().x, a.getBase().y); d.sub(b.getBase()); Vector2Pool.free(d); return checkVectorsParallel(d, a.getDirection()); } s... | @Test public void testCheckIfLinesAreEquals() { Line line1 = new Line(0, 0, 1, 1); Line line2 = new Line(0, 0, 1, 1); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line2)); assertEquals(true, FastMath.checkIfLinesAreEquals(line2, line1)); Line line3 = new Line(1, 1, 1, 1); assertEquals(true, FastMath.checkIf... |
CCircle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CCircle) { CCircle circle = (CCircle) obj; float dx = getCenterX() - circle.getCenterX(); float dy = getCenterY() - circle.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = radius + circle.radius; return distan... | @Test public void testOverlapsCircle() { CCircle circle1 = new CCircle(0, 0, 50); CCircle circle2 = new CCircle(200, 200, 50); assertEquals(false, circle1.overlaps(circle2)); CCircle circle3 = new CCircle(100, 100, 50); assertEquals(false, circle1.overlaps(circle3)); CCircle circle4 = new CCircle(100, 0, 50); assertEqu... |
CRectangle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CRectangle) { CRectangle rect = (CRectangle) obj; return x <= rect.getX() + rect.width && getX() + width >= rect.getX() && getY() <= rect.getY() + rect.height && getY() + height >= rect.getY(); } else { throw new IllegalArgum... | @Test public void testOverlapsRectangle() { CRectangle rect1 = new CRectangle(0, 0, 100, 100); CRectangle rect2 = new CRectangle(0, 0, 100, 100); assertEquals(true, rect1.overlaps(rect2)); CRectangle rect3 = new CRectangle(-10, -10, 5, 5); assertEquals(false, rect1.overlaps(rect3)); CRectangle rect4 = new CRectangle(10... |
ColliderUtils { public static boolean overlaping(float minA, float maxA, float minB, float maxB) { if (maxA < minA) { float a = maxA; maxA = minA; minA = a; } if (maxB < minB) { float b = minB; maxB = minB; minB = b; } return minB <= maxA && minA <= maxB; } static boolean testRectangleRectangleCollision(Rectangle rect... | @Test public void testOverlaping() { assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(0, 1, 2, 3)); assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(2, 3, 3.1f, 4)); assertEquals("values are overlaping, but method returns ... |
ColliderUtils { public static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2) { return rect1.overlaps(rect2); } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCircle... | @Test public void testRectangleRectangleCollisionTest() { Rectangle rect1 = new Rectangle(0, 0, 100, 100); Rectangle rect2 = new Rectangle(99, 99, 100, 100); assertEquals("rectangle is overlaping, but collision test returns false.", true, ColliderUtils.testRectangleRectangleCollision(rect1, rect2)); } |
ColliderUtils { public static boolean testCirclePointCollision(CCircle circle, CPoint point) { float dx = circle.getCenterX() - point.getCenterX(); float dy = circle.getCenterY() - point.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = circle.getRadius(); return distance <= radiusSum * radiusSum; } ... | @Test public void testOverlapingCirclePoint() { CCircle circle = new CCircle(0, 0, 5); CPoint point1 = new CPoint(0, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point1)); CPoint point2 = new CPoint(5, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point2)); CPoint point3... |
ColliderUtils { public static boolean testLineCollision(Line a, Line b) { if (FastMath.checkVectorsParallel(a.getDirection(), b.getDirection())) { return FastMath.checkIfLinesAreEquals(a, b); } else { } return true; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean test... | @Test public void testLineCollision() { Line line1 = new Line(0, 0, 1, 1); Line line2 = new Line(0, 0, 1, 1); assertEquals(true, ColliderUtils.testLineCollision(line1, line2)); Line line3 = new Line(0, 0, -1, -1); assertEquals(true, ColliderUtils.testLineCollision(line1, line3)); assertEquals(true, ColliderUtils.testLi... |
ColliderUtils { public static boolean testSegmentCollision(Segment a, Segment b) { Vector2 d = Vector2Pool.create(a.getPoint2()).sub(a.getPoint1()); Line axisA = LinePool.create(); axisA.setBase(a.getPoint1()); axisA.setDirection(d); Line axisB = LinePool.create(); if (onOneSide(axisA, b)) { LinePool.free(axisA, axisB)... | @Test public void testSegmentCollision() { Segment segment1 = new Segment(new Vector2(0, 0), new Vector2(1, 1)); Segment segment2 = new Segment(new Vector2(0, 0), new Vector2(1, 1)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment2)); assertEquals(true, ColliderUtils.testSegmentCollision(segment... |
DemoController { @RequestMapping("/now") public String now(){ return "hello"; } @RequestMapping("/now") String now(); } | @Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now"); } }).andExpect(status().isOk()).andExpect(content().... |
Mockito { public static <T> When<T> when(T t){ return new When<T>(); } static T mock(Class<T> t); static When<T> when(T t); } | @Test public void testStub(){ when(mockList.get(0)).thenReturn(1); System.out.println(mockList.get(0)); }
@Test public void testArgsMatch(){ when(mockList.get(anyInt())).thenReturn("Hello Chubin"); when(mockList.contains(argThat(new Contains("Chubin")))).thenReturn(true); assertEquals(mockList.get(1), "Hello Chubin"); ... |
Mockito { public static <T> T mock(Class<T> t){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t); enhancer.setCallback(new MockMethodInterceptor()); return (T) enhancer.create(); } static T mock(Class<T> t); static When<T> when(T t); } | @Test public void testOrder(){ List simpleList1 = mock(List.class); List simpleList2 = mock(List.class); simpleList1.add("first call"); simpleList2.add("second call"); InOrder inOrder = inOrder(simpleList1, simpleList2); inOrder.verify(simpleList1).add("first call"); inOrder.verify(simpleList2).add("second call"); } |
LogController { @RequestMapping("/now/{id}") @ResponseBody public LocalDateTime now(@PathVariable String id, HttpServletRequest request) { mdcThreadPool.execute(new Runnable() { @Override public void run() { MDC.put("traceId", request.getRequestURI()); logger.info("线程池任务执行-------1"); } }); logger.info("mdc context:{}",... | @Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now/1"); } }).andExpect(status().isOk()); String contentAsS... |
MessagingAccessPointAdapter { public static MessagingAccessPoint getMessagingAccessPoint(String url, KeyValue attributes) { AccessPointURI accessPointURI = new AccessPointURI(url); String driverImpl = parseDriverImpl(accessPointURI.getDriverType(), attributes); attributes.put(OMSBuiltinKeys.ACCESS_POINTS, accessPointUR... | @Test public void getMessagingAccessPoint() { String testURI = "oms:test-vendor: KeyValue keyValue = OMS.newKeyValue(); keyValue.put(OMSBuiltinKeys.DRIVER_IMPL, "io.openmessaging.internal.TestVendor"); MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint(testURI, keyValue); assertThat(messagingAccess... |
DefaultKeyValue implements KeyValue { @Override public Set<String> keySet() { return properties.keySet(); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short getShort(String key)... | @Test public void testKeySet() throws Exception { keyValue.put("IndexKey", 123); assertThat(keyValue.keySet()).contains("IndexKey"); } |
DefaultKeyValue implements KeyValue { @Override public boolean containsKey(String key) { return properties.containsKey(key); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short g... | @Test public void testContainsKey() throws Exception { keyValue.put("ContainsKey", 123); assertThat(keyValue.containsKey("ContainsKey")).isTrue(); } |
AccessPointURI { public String getAccessPointString() { return accessPointString; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); } | @Test public void testGetAccessPointString() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccessPointString()).isEqualTo(fullSchemaURI); } |
AccessPointURI { public String getDriverType() { return driverType; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); } | @Test public void testGetDriverType() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getDriverType()).isEqualTo("rocketmq"); } |
AccessPointURI { public String getAccountId() { return accountId; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); } | @Test public void testGetAccountId() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccountId()).isEqualTo("alice"); } |
AccessPointURI { public String getHosts() { return hosts; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); } | @Test public void testGetHosts() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org"); String multipleHostsURI = "oms:rocketmq: accessPointURI = new AccessPointURI(multipleHostsURI); assertThat(accessPointURI.getHosts()).isEqualTo("r... |
AccessPointURI { public String getRegion() { return region; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); } | @Test public void testGetRegion() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getRegion()).isEqualTo("us-east"); } |
TwitterMessageProducer extends MessageProducerSupport { StatusListener getStatusListener() { return statusListener; } TwitterMessageProducer(TwitterStream twitterStream, MessageChannel outputChannel); @Override void doStart(); @Override void doStop(); void setFollows(List<Long> follows); void setTerms(List<String> term... | @Test public void shouldReceiveStatus() { StatusListener statusListener = twitterMessageProducer.getStatusListener(); Status status = mock(Status.class); statusListener.onStatus(status); Message<?> statusMessage = outputChannel.receive(); assertSame(status, statusMessage.getPayload()); } |
PhoenixPigSchemaUtil { public static ResourceSchema getResourceSchema(final Configuration configuration, Dependencies dependencies) throws IOException { final ResourceSchema schema = new ResourceSchema(); try { List<ColumnInfo> columns = null; final SchemaType schemaType = PhoenixConfigurationUtil.getSchemaType(configu... | @Test public void testSchema() throws SQLException, IOException { final Configuration configuration = mock(Configuration.class); when(configuration.get(PhoenixConfigurationUtil.SCHEMA_TYPE)).thenReturn(SchemaType.TABLE.name()); final ResourceSchema actual = PhoenixPigSchemaUtil.getResourceSchema( configuration, new Dep... |
IndexWriter implements Stoppable { public static IndexCommitter getCommitter(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexCommitter committer = conf.getClass(INDEX_COMMITTER_CONF_KEY, ParallelWriterIndexCommitter.class, IndexCommitter.class).newInstance(... | @Test public void getDefaultWriter() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getCommitter(env)); } |
IndexWriter implements Stoppable { public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, KillServerOnFailurePolicy.class, IndexFailurePolicy.c... | @Test public void getDefaultFailurePolicy() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getFailurePolicy(env)); } |
MutationState implements SQLCloseable { public static int[] joinSortedIntArrays(int[] a, int[] b) { int[] result = new int[a.length + b.length]; int i = 0, j = 0, k = 0, current; while (i < a.length && j < b.length) { current = a[i] < b[j] ? a[i++] : b[j++]; for ( ; i < a.length && a[i] == current; i++); for ( ; j < b.... | @Test public void testJoinIntArrays() { int[] a = new int[] {1}; int[] b = new int[] {2}; int[] result = joinSortedIntArrays(a, b); assertEquals(2, result.length); assertArrayEquals(new int[] {1,2}, result); a = new int[0]; b = new int[0]; result = joinSortedIntArrays(a, b); assertEquals(0, result.length); assertArrayE... |
OrderedResultIterator implements PeekingResultIterator { @Override public void close() throws SQLException { if (null != resultIterator) { resultIterator.close(); } resultIterator = PeekingResultIterator.EMPTY_ITERATOR; } OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions,
... | @Test public void testNullIteratorOnClose() throws SQLException { ResultIterator delegate = ResultIterator.EMPTY_ITERATOR; List<OrderByExpression> orderByExpressions = Collections.singletonList(null); int thresholdBytes = Integer.MAX_VALUE; OrderedResultIterator iterator = new OrderedResultIterator(delegate, orderByExp... |
TypeUtil { public static Tuple transformToTuple(final PhoenixRecordWritable record, final ResourceFieldSchema[] projectedColumns) throws IOException { Map<String, Object> columnValues = record.getResultMap(); if (columnValues == null || columnValues.size() == 0 || projectedColumns == null || projectedColumns.length != ... | @Test public void testTransformToTuple() throws Exception { PhoenixRecordWritable record = mock(PhoenixRecordWritable.class); Double[] doubleArr = new Double[2]; doubleArr[0] = 64.87; doubleArr[1] = 89.96; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PDouble.INSTANCE, doubleArr); Map<String,Object> values ... |
CsvBulkImportUtil { @VisibleForTesting static Character getCharacter(Configuration conf, String confKey) { String strValue = conf.get(confKey); if (strValue == null) { return null; } return new String(Base64.decode(strValue)).charAt(0); } static void initCsvImportJob(Configuration conf, char fieldDelimiter, char quote... | @Test public void testGetChar_NotPresent() { Configuration conf = new Configuration(); assertNull(CsvBulkImportUtil.getCharacter(conf, "conf.key")); } |
ScanRanges { public boolean intersectRegion(byte[] regionStartKey, byte[] regionEndKey, boolean isLocalIndex) { if (isEverything()) { return true; } if (isDegenerate()) { return false; } if (isLocalIndex) { return true; } boolean crossesSaltBoundary = isSalted && ScanUtil.crossesPrefixBoundary(regionEndKey, ScanUtil.ge... | @Test public void test() { byte[] lowerInclusiveKey = keyRange.getLowerRange(); if (!keyRange.isLowerInclusive() && !Bytes.equals(lowerInclusiveKey, KeyRange.UNBOUND)) { lowerInclusiveKey = ByteUtil.nextKey(lowerInclusiveKey); } byte[] upperExclusiveKey = keyRange.getUpperRange(); if (keyRange.isUpperInclusive()) { upp... |
ResourceList { Collection<String> getResourcesFromJarFile( final File file, final Pattern pattern) { final List<String> retVal = new ArrayList<>(); ZipFile zf; try { zf = new ZipFile(file); } catch (FileNotFoundException e) { return Collections.emptyList(); } catch (final ZipException e) { throw new Error(e); } catch (... | @Test public void testMissingJarFileReturnsGracefully() { ResourceList rl = new ResourceList("foo"); File missingFile = new File("abracadabraphoenix.txt"); assertFalse("Did not expect a fake test file to actually exist", missingFile.exists()); assertEquals(Collections.emptyList(), rl.getResourcesFromJarFile(missingFile... |
PhoenixEmbeddedDriver implements Driver, SQLCloseable { @Override public boolean acceptsURL(String url) throws SQLException { if (url.startsWith(PhoenixRuntime.JDBC_PROTOCOL)) { if (url.length() == PhoenixRuntime.JDBC_PROTOCOL.length()) { return true; } if (PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR == url.charAt(PhoenixR... | @Test public void testNotAccept() throws Exception { Driver driver = new PhoenixDriver(); assertFalse(driver.acceptsURL("jdbc:phoenix: assertFalse(driver.acceptsURL("jdbc:phoenix:localhost;test=true;bar=foo")); assertFalse(driver.acceptsURL("jdbc:phoenix:localhost;test=true")); assertTrue(driver.acceptsURL("jdbc:phoeni... |
Pherf { public static void main(String[] args) { try { new Pherf(args).run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } Pherf(String[] args); static void main(String[] args); void run(); } | @Test public void testListArgument() { String[] args = {"-listFiles"}; Pherf.main(args); }
@Test public void testUnknownOption() { String[] args = {"-drop", "all", "-q", "-m","-bsOption"}; exit.expectSystemExitWithStatus(1); Pherf.main(args); } |
StatisticsScanner implements InternalScanner { @Override public void close() throws IOException { boolean async = getConfig().getBoolean(COMMIT_STATS_ASYNC, DEFAULT_COMMIT_STATS_ASYNC); StatisticsCollectionRunTracker collectionTracker = getStatsCollectionRunTracker(config); StatisticsScannerCallable callable = createCa... | @Test public void testCheckRegionServerStoppingOnClose() throws Exception { when(rsServices.isStopping()).thenReturn(true); when(rsServices.isStopped()).thenReturn(false); mockScanner.close(); verify(rsServices).isStopping(); verify(callable, never()).call(); verify(runTracker, never()).runTask(callable); }
@Test publi... |
PhoenixQueryBuilder { public String buildQuery(JobConf jobConf, String tableName, List<String> readColumnList, String whereClause, Map<String, TypeInfo> columnTypeMap) throws IOException { String hints = getHint(jobConf, tableName); if (LOG.isDebugEnabled()) { LOG.debug("Building query with columns : " + readColumnList... | @Test public void testBuildQueryWithCharColumns() throws IOException { final String COLUMN_CHAR = "Column_Char"; final String COLUMN_VARCHAR = "Column_VChar"; final String expectedQueryPrefix = "select \"" + COLUMN_CHAR + "\",\"" + COLUMN_VARCHAR + "\" from TEST_TABLE where "; JobConf jobConf = new JobConf(); List<Stri... |
PhoenixRuntime { private static List<PColumn> getColumns(PTable table, List<Pair<String, String>> columns) throws SQLException { List<PColumn> pColumns = new ArrayList<PColumn>(columns.size()); for (Pair<String, String> column : columns) { pColumns.add(getColumn(table, column.getFirst(), column.getSecond())); } return ... | @Test public void testParseArguments_MinimalCase() { PhoenixRuntime.ExecutionCommand execCmd = PhoenixRuntime.ExecutionCommand.parseArgs( new String[] { "localhost", "test.csv" }); assertEquals( "localhost", execCmd.getConnectionString()); assertEquals( ImmutableList.of("test.csv"), execCmd.getInputFiles()); assertEqua... |
PhoenixRuntime { public static Expression getTenantIdExpression(Connection conn, String fullTableName) throws SQLException { PTable table = getTable(conn, fullTableName); if (!SchemaUtil.isMetaTable(table) && !SchemaUtil.isSequenceTable(table) && !table.isMultiTenant()) { return null; } return getFirstPKColumnExpressio... | @Test public void testGetTenantIdExpression() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); Expression e1 = PhoenixRuntime.getTenantIdExpression(conn, PhoenixDatabaseMetaData.SYSTEM_STATS_NAME); assertNull(e1); Expression e2 = PhoenixRuntime.getTenantIdExpression(conn, PhoenixDatabaseMetaD... |
PhoenixRuntime { public static long getWallClockTimeFromCellTimeStamp(long tsOfCell) { return TxUtils.isPreExistingVersion(tsOfCell) ? tsOfCell : TransactionUtil.convertToMilliseconds(tsOfCell); } private PhoenixRuntime(); static void main(String [] args); static int executeStatements(Connection conn, Reader reader, L... | @Test public void testGetWallClockTimeFromCellTimeStamp() { long ts = System.currentTimeMillis(); assertEquals(ts, PhoenixRuntime.getWallClockTimeFromCellTimeStamp(ts)); long nanoTs = TransactionUtil.convertToNanoseconds(ts); assertEquals(ts, PhoenixRuntime.getWallClockTimeFromCellTimeStamp(nanoTs)); long skewedTs = ts... |
PropertiesUtil { public static Properties extractProperties(Properties props, final Configuration conf) { Iterator<Map.Entry<String, String>> iterator = conf.iterator(); if(iterator != null) { while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); props.setProperty(entry.getKey(), entry.getValu... | @Test public void testCopyFromConfiguration() throws Exception{ final Configuration conf = HBaseConfiguration.create(); final Properties props = new Properties(); conf.set(HConstants.ZOOKEEPER_QUORUM, HConstants.LOCALHOST); conf.set(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY, PropertiesUtilTest.SOME_OTHER_PROPERTY_VALU... |
JDBCUtil { public static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info) { Preconditions.checkNotNull(url); Preconditions.checkNotNull(info); Map<String, String> combinedProperties = getCombinedConnectionProperties(url, info); Map<String, String> result = newHashMapWithExpectedSize(com... | @Test public void testGetCustomTracingAnnotationsWithNone() { String url = "localhost;TenantId=abc;"; Map<String, String> customAnnotations = JDBCUtil.getAnnotations(url, new Properties()); assertTrue(customAnnotations.isEmpty()); }
@Test public void testGetCustomTracingAnnotationInBothPropertiesAndURL() { String annot... |
JDBCUtil { public static String removeProperty(String url, String propName) { String urlPropName = PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR + propName.toUpperCase() + "="; String upperCaseURL = url.toUpperCase(); int begIndex = upperCaseURL.indexOf(urlPropName); if (begIndex >= 0) { int endIndex = upperCaseURL.indexOf(P... | @Test public void testRemoveProperty() { assertEquals("localhost;", JDBCUtil.removeProperty("localhost;TenantId=abc;", TENANT_ID_ATTRIB)); assertEquals("localhost;foo=bar", JDBCUtil.removeProperty("localhost;TenantId=abc;foo=bar", TENANT_ID_ATTRIB)); assertEquals("localhost;TenantId=abc", JDBCUtil.removeProperty("local... |
JDBCUtil { public static boolean getAutoCommit(String url, Properties info, boolean defaultValue) { String autoCommit = findProperty(url, info, PhoenixRuntime.AUTO_COMMIT_ATTRIB); if (autoCommit == null) { return defaultValue; } return Boolean.valueOf(autoCommit); } private JDBCUtil(); static String findProperty(Strin... | @Test public void testGetAutoCommit_NotSpecified_DefaultTrue() { assertTrue(JDBCUtil.getAutoCommit("localhost", new Properties(), true)); }
@Test public void testGetAutoCommit_NotSpecified_DefaultFalse() { assertFalse(JDBCUtil.getAutoCommit("localhost", new Properties(), false)); }
@Test public void testGetAutoCommit_T... |
JDBCUtil { public static Consistency getConsistencyLevel(String url, Properties info, String defaultValue) { String consistency = findProperty(url, info, PhoenixRuntime.CONSISTENCY_ATTRIB); if(consistency != null && consistency.equalsIgnoreCase(Consistency.TIMELINE.toString())){ return Consistency.TIMELINE; } return Co... | @Test public void testGetConsistency_TIMELINE_InUrl() { assertTrue(JDBCUtil.getConsistencyLevel("localhost;Consistency=TIMELINE", new Properties(), Consistency.STRONG.toString()) == Consistency.TIMELINE); }
@Test public void testGetConsistency_TIMELINE_InProperties() { Properties props = new Properties(); props.setProp... |
JDBCUtil { public static String getSchema(String url, Properties info, String defaultValue) { String schema = findProperty(url, info, PhoenixRuntime.SCHEMA_ATTRIB); return (schema == null || schema.equals("")) ? defaultValue : schema; } private JDBCUtil(); static String findProperty(String url, Properties info, String... | @Test public void testSchema() { assertTrue(JDBCUtil.getSchema("localhost;schema=TEST", new Properties(), null).equals("TEST")); assertNull(JDBCUtil.getSchema("localhost;schema=", new Properties(), null)); assertNull(JDBCUtil.getSchema("localhost;", new Properties(), null)); } |
JDBCUtil { public static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props) throws SQLException { String batchSizeStr = findProperty(url, info, PhoenixRuntime.UPSERT_BATCH_SIZE_BYTES_ATTRIB); return (batchSizeStr == null ? props.getLong(QueryServices.MUTATE_BATCH_SIZE_BYTES_ATTRIB, QueryServ... | @Test public void testGetMaxMutateBytes() throws Exception { assertEquals(1000L, JDBCUtil.getMutateBatchSizeBytes("localhost;" + PhoenixRuntime.UPSERT_BATCH_SIZE_BYTES_ATTRIB + "=1000", new Properties(), ReadOnlyProps.EMPTY_PROPS)); Properties props = new Properties(); props.setProperty(PhoenixRuntime.UPSERT_BATCH_SIZE... |
QueryUtil { public static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos) { if (columnInfos.isEmpty()) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } final List<String> columnNames = Lists.transform(columnInfos, new Function<ColumnInfo,String>... | @Test public void testConstructUpsertStatement_ColumnInfos() { assertEquals( "UPSERT INTO MYTAB (\"ID\", \"NAME\") VALUES (?, ?)", QueryUtil.constructUpsertStatement("MYTAB", ImmutableList.of(ID_COLUMN, NAME_COLUMN))); }
@Test(expected=IllegalArgumentException.class) public void testConstructUpsertStatement_ColumnInfos... |
QueryUtil { public static String constructGenericUpsertStatement(String tableName, int numColumns) { if (numColumns == 0) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } List<String> parameterList = Lists.newArrayListWithCapacity(numColumns); for (int i = 0; i < numColumns; i... | @Test public void testConstructGenericUpsertStatement() { assertEquals( "UPSERT INTO MYTAB VALUES (?, ?)", QueryUtil.constructGenericUpsertStatement("MYTAB", 2)); }
@Test(expected=IllegalArgumentException.class) public void testConstructGenericUpsertStatement_NoColumns() { QueryUtil.constructGenericUpsertStatement("MYT... |
SqlQueryToColumnInfoFunction implements Function<String,List<ColumnInfo>> { @Override public List<ColumnInfo> apply(String sqlQuery) { Preconditions.checkNotNull(sqlQuery); Connection connection = null; List<ColumnInfo> columnInfos = null; try { connection = ConnectionUtil.getInputConnection(this.configuration); final ... | @Test public void testValidSelectQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id integer not null, name varchar, age integer,location varchar " + " CONSTRAINT pk PRIMARY KEY (id))\n"; createTestTable(getUrl(), ddl); final String selectQuery = "SELECT name as a ,age AS b,UPPER(location) AS c ... |
QueryUtil { public static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions) { Preconditions.checkNotNull(fullTableName,"Table name cannot be null"); if(columnInfos == null || columnInfos.isEmpty()) { throw new IllegalArgumentException("At least one column must b... | @Test public void testConstructSelectStatement() { assertEquals( "SELECT \"ID\",\"NAME\" FROM MYTAB", QueryUtil.constructSelectStatement("MYTAB", ImmutableList.of(ID_COLUMN,NAME_COLUMN),null)); }
@Test public void testConstructSelectStatementWithSchema() { assertEquals( "SELECT \"ID\",\"NAME\" FROM A.MYTAB", QueryUtil.... |
QueryUtil { public static String getConnectionUrl(Properties props, Configuration conf) throws ClassNotFoundException, SQLException { return getConnectionUrl(props, conf, null); } private QueryUtil(); static String toSQL(CompareOp op); static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInf... | @Test public void testCreateConnectionFromConfiguration() throws Exception { Properties props = new Properties(); Configuration conf = new Configuration(false); conf.set(HConstants.ZOOKEEPER_QUORUM, "localhost"); conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, "2181"); String conn = QueryUtil.getConnectionUrl(props, conf); ... |
ByteUtil { public static byte[] toBytes(byte[][] byteArrays) { int size = 0; for (byte[] b : byteArrays) { if (b == null) { size++; } else { size += b.length; size += WritableUtils.getVIntSize(b.length); } } TrustedByteArrayOutputStream bytesOut = new TrustedByteArrayOutputStream(size); DataOutputStream out = new DataO... | @Test public void testSplitBytes() { byte[] startRow = Bytes.toBytes("EA"); byte[] stopRow = Bytes.toBytes("EZ"); byte[][] splitPoints = Bytes.split(startRow, stopRow, 10); for (byte[] splitPoint : splitPoints) { assertTrue(Bytes.toStringBinary(splitPoint), Bytes.compareTo(startRow, splitPoint) <= 0); assertTrue(Bytes.... |
ByteUtil { public static int vintToBytes(byte[] result, int offset, final long vint) { long i = vint; if (i >= -112 && i <= 127) { result[offset] = (byte) i; return 1; } int len = -112; if (i < 0) { i ^= -1L; len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len--; } result[offset++] = (byte) len; len = (l... | @Test public void testVIntToBytes() { for (int i = -10000; i <= 10000; i++) { byte[] vint = Bytes.vintToBytes(i); int vintSize = vint.length; byte[] vint2 = new byte[vint.length]; assertEquals(vintSize, ByteUtil.vintToBytes(vint2, 0, i)); assertTrue(Bytes.BYTES_COMPARATOR.compare(vint,vint2) == 0); } } |
ByteUtil { public static byte[] nextKey(byte[] key) { byte[] nextStartRow = new byte[key.length]; System.arraycopy(key, 0, nextStartRow, 0, key.length); if (!nextKey(nextStartRow, nextStartRow.length)) { return null; } return nextStartRow; } static byte[] toBytes(byte[][] byteArrays); static byte[][] toByteArrays(byte... | @Test public void testNextKey() { byte[] key = new byte[] {1}; assertEquals((byte)2, ByteUtil.nextKey(key)[0]); key = new byte[] {1, (byte)255}; byte[] nextKey = ByteUtil.nextKey(key); byte[] expectedKey = new byte[] {2,(byte)0}; assertArrayEquals(expectedKey, nextKey); key = ByteUtil.concat(Bytes.toBytes("00D300000000... |
QuerySchemaParserFunction implements Function<String,Pair<String,String>> { @Override public Pair<String, String> apply(final String selectStatement) { Preconditions.checkNotNull(selectStatement); Preconditions.checkArgument(!selectStatement.isEmpty(), "Select Query is empty!!"); Connection connection = null; try { con... | @Test(expected=RuntimeException.class) public void testSelectQuery() { final String selectQuery = "SELECT col1 FROM test"; function.apply(selectQuery); fail("Should fail as the table [test] doesn't exist"); }
@Test public void testValidSelectQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id in... |
DateUtil { public static Timestamp getTimestamp(long millis, int nanos) { if (nanos > MAX_ALLOWED_NANOS || nanos < 0) { throw new IllegalArgumentException("nanos > " + MAX_ALLOWED_NANOS + " or < 0"); } Timestamp ts = new Timestamp(millis); if (ts.getNanos() + nanos > MAX_ALLOWED_NANOS) { int millisToNanosConvertor = Bi... | @Test public void testDemonstrateSetNanosOnTimestampLosingMillis() { Timestamp ts1 = new Timestamp(120055); ts1.setNanos(60); Timestamp ts2 = new Timestamp(120100); ts2.setNanos(60); assertTrue(ts1.equals(ts2)); ts1 = DateUtil.getTimestamp(120055, 60); ts2 = DateUtil.getTimestamp(120100, 60); assertFalse(ts1.equals(ts2... |
DateUtil { public static Date parseDate(String dateValue) { return new Date(parseDateTime(dateValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZo... | @Test public void testParseDate() { assertEquals(10000L, DateUtil.parseDate("1970-01-01 00:00:10").getTime()); }
@Test public void testParseDate_PureDate() { assertEquals(0L, DateUtil.parseDate("1970-01-01").getTime()); }
@Test(expected = IllegalDataException.class) public void testParseDate_InvalidDate() { DateUtil.pa... |
DateUtil { public static Time parseTime(String timeValue) { return new Time(parseDateTime(timeValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZo... | @Test public void testParseTime() { assertEquals(10000L, DateUtil.parseTime("1970-01-01 00:00:10").getTime()); } |
DateUtil { public static Timestamp parseTimestamp(String timestampValue) { Timestamp timestamp = new Timestamp(parseDateTime(timestampValue)); int period = timestampValue.indexOf('.'); if (period > 0) { String nanosStr = timestampValue.substring(period + 1); if (nanosStr.length() > 9) throw new IllegalDataException("na... | @Test public void testParseTimestamp() { assertEquals(10000L, DateUtil.parseTimestamp("1970-01-01 00:00:10").getTime()); }
@Test public void testParseTimestamp_WithMillis() { assertEquals(10123L, DateUtil.parseTimestamp("1970-01-01 00:00:10.123").getTime()); }
@Test public void testParseTimestamp_WithNanos() { assertEq... |
MetaDataUtil { public static long encodeVersion(String hbaseVersionStr, Configuration config) { long hbaseVersion = VersionUtil.encodeVersion(hbaseVersionStr); long isTableNamespaceMappingEnabled = SchemaUtil.isNamespaceMappingEnabled(PTableType.TABLE, new ReadOnlyProps(config.iterator())) ? 1 : 0; long phoenixVersion ... | @Test public void testEncode() { assertEquals(VersionUtil.encodeVersion("0.94.5"),VersionUtil.encodeVersion("0.94.5-mapR")); assertTrue(VersionUtil.encodeVersion("0.94.6")>VersionUtil.encodeVersion("0.94.5-mapR")); assertTrue(VersionUtil.encodeVersion("0.94.6")>VersionUtil.encodeVersion("0.94.5")); assertTrue(VersionUt... |
MetaDataUtil { public static boolean getMutationValue(Mutation headerRow, byte[] key, KeyValueBuilder builder, ImmutableBytesWritable ptr) { List<Cell> kvs = headerRow.getFamilyCellMap().get(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES); if (kvs != null) { for (Cell cell : kvs) { KeyValue kv = org.apache.hadoop.hbase.Key... | @Test public void testGetMutationKeyValue() throws Exception { String version = VersionInfo.getVersion(); KeyValueBuilder builder = KeyValueBuilder.get(version); byte[] row = Bytes.toBytes("row"); byte[] family = PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES; byte[] qualifier = Bytes.toBytes("qual"); byte[] value = Bytes.... |
IndexManagementUtil { public static void ensureMutableIndexingCorrectlyConfigured(Configuration conf) throws IllegalStateException { if (isWALEditCodecSet(conf)) { return; } String codecClass = INDEX_WAL_EDIT_CODEC_CLASS_NAME; String indexLogReaderName = INDEX_HLOG_READER_CLASS_NAME; try { Class.forName(indexLogReaderN... | @Test public void testUncompressedWal() throws Exception { Configuration conf = new Configuration(false); conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, IndexedWALEditCodec.class.getName()); IndexManagementUtil.ensureMutableIndexingCorrectlyConfigured(conf); conf = new Configuration(false); conf.set(IndexManagementUti... |
CoveredColumnIndexCodec extends BaseIndexCodec { public static boolean checkRowKeyForAllNulls(byte[] bytes) { int keyCount = CoveredColumnIndexCodec.getPreviousInteger(bytes, bytes.length); int pos = bytes.length - Bytes.SIZEOF_INT; for (int i = 0; i < keyCount; i++) { int next = CoveredColumnIndexCodec.getPreviousInte... | @Test public void testCheckRowKeyForAllNulls() { byte[] pk = new byte[] { 'a', 'b', 'z' }; byte[] result = EMPTY_INDEX_KEY; assertTrue("Didn't correctly read single element as being null in row key", CoveredColumnIndexCodec.checkRowKeyForAllNulls(result)); result = CoveredColumnIndexCodec.composeRowKey(pk, 0, Lists.new... |
EmailValidator { public static boolean isValidEmail(CharSequence email) { return email != null && EMAIL_PATTERN.matcher(email).matches(); } static boolean isValidEmail(CharSequence email); static final Pattern EMAIL_PATTERN; } | @Test public void isValidEmail() throws Exception { assertThat(EmailValidator.isValidEmail("jaredsburrows@gmail.com")).isTrue(); } |
SampleService { public static boolean start() { return true; } static boolean start(); } | @Test public void onStartCommand() throws Exception { assertThat(SampleService.start()).isTrue(); } |
Calculator { public static double add(int firstOperand, double secondOperand) { return firstOperand + secondOperand; } static double add(int firstOperand, double secondOperand); } | @Test public void add() throws Exception { assertThat(Calculator.add(1, 2)).isEqualTo(3); } |
BridgeServiceImpl implements BridgeService { @Override public BridgeDTO create(BridgeCreateDTO bridge) throws InvalidIpException, BridgeAlreadyExistsException, UserDoesNotExistException { if (!isIPv4Address(bridge.getIp())) { throw new InvalidIpException(bridge.getIp()); } else if (bridgeRepository.findByIp(bridge.getI... | @Test(expected = InvalidIpException.class) public void testCreateWithInvalidIp() { bridgeService.create(new BridgeCreateDTO("invalid", -1)); fail(); }
@Test(expected = UserDoesNotExistException.class) public void testCreateWithoutValidUserId() { bridgeService.create(new BridgeCreateDTO("127.0.0.1", -1)); fail(); } |
LampServiceImpl implements LampService { @Override public LampDTO create(LampCreateDTO lamp) throws EmptyInputException, TeamDoesNotExistException, LampAlreadyExistsException { if (lamp.getName() == null || lamp.getName().trim().isEmpty() || lamp.getHueUniqueId() == null || lamp.getHueUniqueId().trim().isEmpty()) { thr... | @Test(expected = LampAlreadyExistsException.class) public void testCreateWithDuplicateHueUniqueId() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())); lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())... |
LampServiceImpl implements LampService { @Override public LampDTO update(LampUpdateDTO lamp) throws InvalidWorkingPeriodException, LampDoesNotExistsException { if (lamp.getWorkingStart() == null) { lamp.setWorkingStart(defaultWorkingStart()); } if (lamp.getWorkingEnd() == null) { lamp.setWorkingEnd(defaultWorkingEnd())... | @Test public void testUpdate() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); LampDTO lamp = lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())); assertNotNull(lamp.getWorkingStart()); assertNotNull(lamp.getWorkingEnd()); assertNull(lamp.getLastShownScenario()); assertNull... |
LampServiceImpl implements LampService { @Override public LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp) throws LampDoesNotExistsException { Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setLastShownScenario(lamp.getLastShownScenario()); l = lampRepository.save(l); return mappe... | @Test(expected = LampDoesNotExistsException.class) public void testUpdateLastShownScenarioWithoutValidLampId() { lampService.updateLastShownScenario(new LampUpdateLastShownScenarioDTO(-1, Scenario.BUILDING)); fail(); } |
LampServiceImpl implements LampService { @Override public LampDTO rename(LampRenameDTO lamp) throws EmptyInputException, LampDoesNotExistsException { if (lamp.getName() == null || lamp.getName().trim().isEmpty()) { throw new EmptyInputException(); } Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setN... | @Test(expected = EmptyInputException.class) public void testRenameWithEmptyInput() { try { lampService.rename(new LampRenameDTO(-1, null)); } catch (EmptyInputException eie) { lampService.rename(new LampRenameDTO(-1, "")); } fail(); }
@Test(expected = LampDoesNotExistsException.class) public void testRenameWithInvalidL... |
LampServiceImpl implements LampService { @Override public List<LampDTO> findAll() { List<Lamp> lamps = lampRepository.findAll(); List<LampDTO> dtos = new ArrayList<>(lamps.size()); for (Lamp lamp : lamps) { LampDTO dto = mapper.map(lamp, LampDTO.class); dtos.add(dto); } return dtos; } @Autowired LampServiceImpl(LampRe... | @Test public void testFindAll() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); assertEquals(0, lampService.count(team.getId())); LampCreateDTO lampCreateDTO1 = new LampCreateDTO("hueId 1", "Name 1", team.getId()); LampDTO lampDTO1 = lampService.create(lampCreateDTO1); assertEquals(1, lampService... |
LampServiceImpl implements LampService { @Override public TeamLampsDTO findAllOfATeam(long teamId) throws TeamDoesNotExistException { Team team = teamRepository.findOne(teamId); if (team != null) { TeamLampsDTO dto = mapper.map(team, TeamLampsDTO.class); for (int i = 0; i < nullSafe(team.getLamps()).size(); i++) { Team... | @Test(expected = TeamDoesNotExistException.class) public void testFindAllOfATeamWithoutValidTeamId() { lampService.findAllOfATeam(-1); fail(); } |
UserServiceImpl implements UserService { @Override public UserDTO create(UserCreateDTO user) throws EmptyInputException, TeamDoesNotExistException, UserAlreadyExistsException, InvalidLoginException { if (user.getLogin() == null || user.getLogin().trim().isEmpty()) { throw new EmptyInputException(); } user.setLogin(user... | @Test public void testCreate() { assertEquals(0, userService.count()); TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); userService.create(new UserCreateDTO("wennier", team.getId())); assertEquals(1, userService.count()); UserDTO user = userService.findByLogin("wennier"); assertNotNull(user); }
@Tes... |
UserServiceImpl implements UserService { @Override public UserDTO update(UserUpdateDTO user) throws UserDoesNotExistException { User userInDB = userRepository.findOne(user.getId()); if (userInDB == null) { throw new UserDoesNotExistException(user.getId()); } userInDB.setRoles(user.getRoles()); userInDB = userRepository... | @Test(expected = UserDoesNotExistException.class) public void testUpdateUserWithoutValidId() { userService.update(new UserUpdateDTO(-1, null)); fail(); } |
JobServiceImpl implements JobService { @Override public long countNameDistinctly(long teamId) { return jobRepository.countNameDistinctly(teamId); } @Autowired JobServiceImpl(JobRepository jobRepository); @Override long countNameDistinctly(long teamId); @Override long countNameDistinctly(); } | @Test public void testCountNameDistinctly() { assertEquals(0, jobService.countNameDistinctly()); jobRepository.save(new Job(0, "A")); jobRepository.save(new Job(0, "A")); jobRepository.save(new Job(0, "B")); jobRepository.save(new Job(0, "B")); jobRepository.save(new Job(0, "C")); assertEquals(3, jobService.countNameDi... |
TeamServiceImpl implements TeamService { @Override public TeamLampsDTO create(TeamCreateDTO team) throws EmptyInputException, TeamAlreadyExistsException { if (team.getName() == null || team.getName().trim().isEmpty()) { throw new EmptyInputException(); } team.setName(team.getName().trim()); if(teamRepository.findByName... | @Test public void testCreate() { assertEquals(0, teamService.count()); TeamCreateDTO teamCreateDTO1 = new TeamCreateDTO("Team 1"); TeamLampsDTO teamDTO1 = teamService.create(teamCreateDTO1); assertEquals(1, teamService.count()); assertEquals("Team 1", teamRepository.findOne(teamDTO1.getId()).getName()); TeamCreateDTO t... |
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO update(TeamUpdateDTO team) throws TeamDoesNotExistException { Team teamInDB = teamRepository.findOne(team.getId()); if(teamInDB == null) { throw new TeamDoesNotExistException(team.getId()); } else { if(team.getScenarioPriority() != null && team.getS... | @Test(expected = TeamDoesNotExistException.class) public void testUpdateTeamWithoutValidId() { teamService.update(new TeamUpdateDTO(-1, null)); fail(); } |
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO rename(TeamRenameDTO team) throws TeamDoesNotExistException, TeamAlreadyExistsException, EmptyInputException { Team t = teamRepository.findOne(team.getId()); if(t != null) { if(team.getName() == null || team.getName().trim().isEmpty()) { throw new E... | @Test(expected = TeamDoesNotExistException.class) public void testRenameTeamWithoutValidId() { teamService.rename(new TeamRenameDTO(-1, "Team 2")); fail(); } |
HueServiceImpl implements HueService { @Override public boolean ipAreEqual(String ip1, String ip2) { return removePortAndToLowerCase(ip1).equals(removePortAndToLowerCase(ip2)); } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @... | @Test public void testIpAreEqual() { String ip1 = "10.10.10.10"; String ip2 = "10.10.10.10:80"; String ip3 = "10.10.10.20:80"; String ip4 = "10.10.10.20:45"; assertTrue(hueService.ipAreEqual(ip1, ip2)); assertFalse(hueService.ipAreEqual(ip2, ip3)); assertTrue(hueService.ipAreEqual(ip3, ip4)); } |
BridgeServiceImpl implements BridgeService { boolean isIPv4Address(String ip) { if (ip == null) { return false; } else { String regex255 = "(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))"; String regexIPv4 = regex255 + "\\." + regex255 + "\\." + regex255 + "\\." + regex255; return ip.matches(regexIPv4); }... | @Test public void testIsIPv4Address() { assertTrue(bridgeService.isIPv4Address("0.0.0.0")); assertTrue(bridgeService.isIPv4Address("48.51.37.15")); assertTrue(bridgeService.isIPv4Address("199.125.25.15")); assertTrue(bridgeService.isIPv4Address("245.255.2.245")); assertTrue(bridgeService.isIPv4Address("255.255.255.255"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.