focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Range<T> rangeContaining(long key, long value) { return rangeSet.rangeContaining(key, value); }
@Test public void testRangeContaining() { set = new RangeSetWrapper<>(consumer, reverseConvert, managedCursor); set.add(Range.closed(new LongPair(0, 98), new LongPair(0, 99))); set.add(Range.closed(new LongPair(0, 100), new LongPair(1, 5))); com.google.common.collect.RangeSet<LongPai...
public static int fromVersionString(String verStr) { if (verStr == null || verStr.length() < 1) { return 0; } int[] versions = new int[] {0, 0, 0, 0}; int index = 0; String segment; int cur = 0; int pos; do { if (index >= versions.l...
@Test public void testFromVersionString() { assertEquals(0x01020300, VersionUtil.fromVersionString("1.2.3")); assertEquals(0x01020304, VersionUtil.fromVersionString("1.2.3.4")); assertEquals(0x0102ff04, VersionUtil.fromVersionString("1.2.255.4")); assertEquals(0xffffffff, VersionUtil...
@Override public synchronized RegisterApplicationMasterResponse registerApplicationMaster( RegisterApplicationMasterRequest request) throws YarnException, IOException { if (request == null) { throw new YarnException("RegisterApplicationMasterRequest can't be null!"); } // Reset the heartbeat...
@Test public void testTwoIdenticalRegisterRequest() throws Exception { // Register the application twice RegisterApplicationMasterRequest registerReq = Records.newRecord(RegisterApplicationMasterRequest.class); registerReq.setHost(Integer.toString(testAppId)); registerReq.setRpcPort(0); re...
@Override public double calcNormalizedEdgeDistance3D(double ry, double rx, double rz, double ay, double ax, double az, double by, double bx, double bz) { double dx = bx - ax; double dy = by - ay; do...
@Test public void testCalcNormalizedEdgeDistance3dStartEndSame() { DistanceCalcEuclidean distanceCalc = new DistanceCalcEuclidean(); double distance = distanceCalc.calcNormalizedEdgeDistance3D(0, 3, 4, 0, 0, 0, 0, 0, 0); assertEquals(25, distance, 0); }
void taskLookup(ChatMessage chatMessage, String message) { if (!config.taskCommand()) { return; } ChatMessageType type = chatMessage.getType(); final String player; if (type.equals(ChatMessageType.PRIVATECHATOUT)) { player = client.getLocalPlayer().getName(); } else { player = Text.remov...
@Test public void testTaskLookup() throws IOException { net.runelite.http.api.chat.Task task = new net.runelite.http.api.chat.Task(); task.setTask("Abyssal demons"); task.setLocation("The Abyss"); task.setAmount(42); task.setInitialAmount(42); when(slayerConfig.taskCommand()).thenReturn(true); when(cha...
@Override public void lock() { try { lock(-1, null, false); } catch (InterruptedException e) { throw new IllegalStateException(); } }
@Test public void testSubscriptionsPerConnection() throws InterruptedException { Config config = createConfig(); config.useSingleServer() .setSubscriptionConnectionPoolSize(1) .setSubscriptionConnectionMinimumIdleSize(1) .setSubscriptionsPerConnection(...
@Override public ServerGroup servers() { return cache.get(); }
@Test public void all_down_endpoint_is_down() { NginxHealthClient service = createClient("nginx-health-output-all-down.json"); assertFalse(service.servers().isHealthy("gateway.prod.music.vespa.us-east-2.prod")); }
public static Map<String, String> parseQueryString(String qs) { if (isEmpty(qs)) { return new HashMap<>(); } return parseKeyValuePair(qs, "\\&"); }
@Test void testParseQueryString() throws Exception { assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key1"), equalTo("value1")); assertThat(StringUtils.getQueryStringValue("key1=value1&key2=value2", "key2"), equalTo("value2")); assertThat(StringUtils.getQueryStringValu...
public boolean removeKey(ECKey key) { lock.lock(); try { boolean a = hashToKeys.remove(ByteString.copyFrom(key.getPubKeyHash())) != null; boolean b = pubkeyToKeys.remove(ByteString.copyFrom(key.getPubKey())) != null; checkState(a == b); // Should be in both maps or ...
@Test public void removeKey() { ECKey key = new ECKey(); chain.importKeys(key); assertEquals(1, chain.numKeys()); assertTrue(chain.removeKey(key)); assertEquals(0, chain.numKeys()); assertFalse(chain.removeKey(key)); }
@Override public void verify(byte[] data, byte[] signature, MessageDigest digest) { final byte[] decrypted = engine.processBlock(signature, 0, signature.length); final int delta = checkSignature(decrypted, digest); final int offset = decrypted.length - digest.getDigestLength() - delta; ...
@Test public void shouldValidateSignatureSHA384() { final byte[] challenge = CryptoUtils.random(40); final byte[] signature = sign(0x54, challenge, ISOTrailers.TRAILER_SHA384, "SHA-384"); new DssRsaSignatureVerifier(PUBLIC).verify(challenge, signature, "SHA-384"); }
public static byte[] decodeBase64Zipped( String string ) throws IOException { if ( string == null || string.isEmpty() ) { return new byte[0]; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); // base 64 decode byte[] bytes64 = org.apache.commons.codec.binary.Base64.decodeBase64( str...
@Test public void testDecodeBase64Zipped() throws Exception { TestClass testClass = new TestClass(); testClass.setTestProp1( "testPropValue1" ); testClass.setTestProp2( "testPropValue2" ); String base64ZippedString = this.encode( testClass ); TestClass reconstructedTestClass = (TestClass) this.d...
public MonitorBuilder isDefault(Boolean isDefault) { this.isDefault = isDefault; return getThis(); }
@Test void isDefault() { MonitorBuilder builder = MonitorBuilder.newBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); }
public static DockerContainerDeletionTask convertProtoToDockerContainerDeletionTask( DeletionServiceDeleteTaskProto proto, DeletionService deletionService, int taskId) { String user = proto.hasUser() ? proto.getUser() : null; String containerId = proto.hasDockerContainerId() ? proto.ge...
@Test public void testConvertProtoToDockerContainerDeletionTask() throws Exception { DeletionService deletionService = mock(DeletionService.class); int id = 0; String user = "user"; String dockerContainerId = "container_e123_12321231_00001"; DeletionServiceDeleteTaskProto.Builder protoBuilder = ...
public void delHop() { final TransMeta transMeta = (TransMeta) selectionObjectParent; final TransHopMeta transHopMeta = (TransHopMeta) selectionObject; delHop( transMeta, transHopMeta ); }
@Test public void testDelHop() throws Exception { StepMetaInterface fromStepMetaInterface = Mockito.mock( StepMetaInterface.class ); StepMeta fromStep = new StepMeta(); fromStep.setStepMetaInterface( fromStepMetaInterface ); StepMetaInterface toStepMetaInterface = Mockito.mock( StepMetaInterface.cla...
@Override public ByteBuf writeFloat(float value) { writeInt(Float.floatToRawIntBits(value)); return this; }
@Test public void testWriteFloatAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().writeFloat(1); } }); }
@Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.koraAppElement = this.elements.getTypeElement(CommonClassNames.koraApp.canonicalName()); if (this.koraAppElement == null) { return; } this.moduleElement ...
@Test void appWithComonentDescriptorCollision() throws Throwable { var graphDraw = testClass(AppWithComponentCollision.class); Assertions.assertThat(graphDraw.getNodes()).hasSize(3); var materializedGraph = graphDraw.init(); Assertions.assertThat(materializedGraph).isNotNull(); }
boolean eosEnabled() { return StreamsConfigUtils.eosEnabled(processingMode); }
@Test public void shouldNotHaveEosEnabledIfEosAlphaEnable() { assertThat(eosAlphaStreamsProducer.eosEnabled(), is(true)); }
public static int compare(final byte[] a, final byte[] b) { return getDefaultByteArrayComparator().compare(a, b); }
@Test public void testCompare() { byte[] array = new byte[] { 1, 2 }; Assert.assertEquals(0, BytesUtil.compare(array, array)); Assert.assertEquals(-2, BytesUtil.compare(new byte[] { 1, 2 }, new byte[] { 3, 4 })); Assert.assertEquals(0, BytesUtil.compare(new byte[] { 3, 4 }, new byte...
@Override public FailureResult howToHandleFailure( Throwable failure, CompletableFuture<Map<String, String>> failureLabels) { FailureResult failureResult = howToHandleFailure(failure); if (reportEventsAsSpans) { // TODO: replace with reporting as event once events are support...
@Test void testHowToHandleFailureUnrecoverableFailure() throws Exception { final Configuration configuration = new Configuration(); configuration.set(TraceOptions.REPORT_EVENTS_AS_SPANS, Boolean.TRUE); final List<Span> spanCollector = new ArrayList<>(1); final UnregisteredMetricGroup...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testCpuPercentageMemoryAbsoluteMemoryNegative() throws Exception { expectMissingResource("memory"); parseResourceConfigValue("50% cpu, -1024 mb"); }
@Override public ProcNodeInterface lookup(String beIdStr) throws AnalysisException { if (Strings.isNullOrEmpty(beIdStr)) { throw new AnalysisException("Backend id is null"); } long backendId = -1L; try { backendId = Long.parseLong(beIdStr); } catch (N...
@Test public void testLookupNormal() { ExceptionChecker.expectThrowsNoException(() -> { BackendsProcDir dir = new BackendsProcDir(systemInfoService); ProcNodeInterface node = dir.lookup("1000"); Assert.assertNotNull(node); Assert.assertTrue(node instanceof Bac...
public static Applier fromSource(CharSequence source, EndPosTable endPositions) { return new Applier(source, endPositions); }
@Test public void shouldReturnNullOnImportOnlyFix() { AppliedFix fix = AppliedFix.fromSource("public class Foo {}", endPositions) .apply(SuggestedFix.builder().addImport("foo.bar.Baz").build()); assertThat(fix).isNull(); }
static boolean passSingleValueCheck(ResourceWrapper resourceWrapper, ParamFlowRule rule, int acquireCount, Object value) { if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS) { if (rule.getControlBehavior() == RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER) { ...
@Test public void testSingleValueCheckThreadCountWithExceptionItems() { final String resourceName = "testSingleValueCheckThreadCountWithExceptionItems"; final ResourceWrapper resourceWrapper = new StringResourceWrapper(resourceName, EntryType.IN); int paramIdx = 0; long globalThresh...
static void parseServerIpAndPort(MysqlConnection connection, Span span) { try { URI url = URI.create(connection.getURL().substring(5)); // strip "jdbc:" String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName"); if (remoteServiceName == null || "".equals(remoteServiceN...
@Test void parseServerIpAndPort_ipFromHost_portFromUrl() throws SQLException { setupAndReturnPropertiesForHost("1.2.3.4"); TracingQueryInterceptor.parseServerIpAndPort(connection, span); verify(span).remoteServiceName("mysql"); verify(span).remoteIpAndPort("1.2.3.4", 5555); }
public static LogExceptionBehaviourInterface getExceptionStrategy( LogTableCoreInterface table ) { return getExceptionStrategy( table, null ); }
@Test public void testExceptionStrategyWithMysqlDataTruncationException80driver() { DatabaseMeta databaseMeta = mock( DatabaseMeta.class ); DatabaseInterface databaseInterface = new MySQLDatabaseMeta(); com.mysql.cj.jdbc.exceptions.MysqlDataTruncation e = new com.mysql.cj.jdbc.exceptions.MysqlDataTruncation...
@VisibleForTesting CompletableFuture<Acknowledge> getBootstrapCompletionFuture() { return bootstrapCompletionFuture; }
@Test void testErrorHandlerIsCalledWhenSubmissionThrowsAnException() throws Exception { final AtomicBoolean shutdownCalled = new AtomicBoolean(false); final TestingDispatcherGateway.Builder dispatcherBuilder = runningJobGatewayBuilder() .setSubmitFunction( ...
public static ExecutableStage forGrpcPortRead( QueryablePipeline pipeline, PipelineNode.PCollectionNode inputPCollection, Set<PipelineNode.PTransformNode> initialNodes) { checkArgument( !initialNodes.isEmpty(), "%s must contain at least one %s.", GreedyStageFuser.class.getS...
@Test public void noEnvironmentThrows() { // (impulse.out) -> runnerTransform -> gbk.out // runnerTransform can't be executed in an environment, so trying to construct it should fail PTransform gbkTransform = PTransform.newBuilder() .putInputs("input", "impulse.out") .setSp...
public static String subString(String src, String start, String to) { return subString(src, start, to, false); }
@Test public void testSubString() { Assert.assertNull(StringUtils.subString(",", "foo", ",")); Assert.assertNull( StringUtils.subString("foo", "foo", "a\'b\'c", false)); Assert.assertNull( StringUtils.subString("foo", "foo", "a\'b\'c", true)); Assert....
@Override public void execute(Runnable command) { if (command == null) { throw new NullPointerException(); } try { super.execute(command); } catch (RejectedExecutionException rx) { // retry to offer the task into queue. final TaskQueue...
@Test void testEagerThreadPool_rejectExecution1() { String name = "eager-tf"; int cores = 1; int threads = 3; int queues = 2; long alive = 1000; // init queue and executor TaskQueue<Runnable> taskQueue = new TaskQueue<>(queues); final EagerThreadPoolE...
public void incGroupGetSize(final String group, final String topic, final int incValue) { final String statsKey = buildStatsKey(topic, group); this.statsTable.get(Stats.GROUP_GET_SIZE).addValue(statsKey, incValue, 1); }
@Test public void testIncGroupGetSize() { brokerStatsManager.incGroupGetSize(GROUP_NAME, TOPIC, 1); String statsKey = brokerStatsManager.buildStatsKey(TOPIC, GROUP_NAME); assertThat(brokerStatsManager.getStatsItem(GROUP_GET_SIZE, statsKey).getValue().doubleValue()).isEqualTo(1L); }
@Override public DataTableType dataTableType() { return dataTableType; }
@Test void can_define_table_row_transformer() throws NoSuchMethodException { Method method = JavaDataTableTypeDefinitionTest.class.getMethod("convert_table_row_to_string", List.class); JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, lookup, new String[0]); as...
public static <K, V> V putToConcurrentMap(ConcurrentMap<K, V> map, K key, V value) { V old = map.putIfAbsent(key, value); return old != null ? old : value; }
@Test public void testPutToConcurrentMap() throws Exception { final ConcurrentMap<String, AtomicInteger> hashMap = new ConcurrentHashMap<String, AtomicInteger>(); final CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { Thread thread = new Thread(new Runn...
public void setMessageRequestMode(final String brokerAddr, final String topic, final String consumerGroup, final MessageRequestMode mode, final int popShareQueueNum, final long timeoutMillis) throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectExce...
@Test public void testSetMessageRequestMode_Success() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); RemotingCommand response = RemotingCommand.createResponseCommand(null); response.setCode(ResponseCode.SUCC...
@Override public double p(double x) { if (x < 0) { return 0.0; } else { return lambda * Math.exp(-lambda * x); } }
@Test public void testP() { System.out.println("p"); ExponentialDistribution instance = new ExponentialDistribution(2.0); instance.rand(); assertEquals(0, instance.p(-0.1), 1E-7); assertEquals(2.0, instance.p(0.0), 1E-7); assertEquals(0.2706706, instance.p(1.0), 1E-7)...
public static Object applyLogicalType(Schema.Field field, Object value) { if (field == null || field.schema() == null) { return value; } Schema fieldSchema = resolveUnionSchema(field.schema()); return applySchemaTypeLogic(fieldSchema, value); }
@Test public void testApplyLogicalTypeReturnsSameValueWhenNotUsingLogicalType() { String value = "abc"; String schemaString = new StringBuilder().append("{").append(" \"type\": \"record\",").append(" \"name\": \"test\",") .append(" \"fields\": [{").append(" \"name\": \"column1\",").a...
static long sizeOf(Mutation m) { if (m.getOperation() == Mutation.Op.DELETE) { return sizeOf(m.getKeySet()); } long result = 0; for (Value v : m.getValues()) { switch (v.getType().getCode()) { case ARRAY: result += estimateArrayValue(v); break; case STRUCT...
@Test public void bytes() throws Exception { Mutation empty = Mutation.newInsertOrUpdateBuilder("test").set("one").to(ByteArray.fromBase64("")).build(); Mutation nullValue = Mutation.newInsertOrUpdateBuilder("test").set("one").to((ByteArray) null).build(); Mutation sample = Mutatio...
public static Builder builder() { return new Builder(); }
@Test public void testBackOffWithMaxTime() { final BackOff backOff = BackOff.builder().maxElapsedTime(9, TimeUnit.SECONDS).build(); final BackOffTimerTask context = new BackOffTimerTask(backOff, null, t -> true); long delay; for (int i = 1; i <= 5; i++) { delay = contex...
public static Identifier parse(String stringValue) { return parse(stringValue, -1); }
@Test public void testParseIntegerMaxInclusive() { Identifier.parse("65535"); }
IdBatchAndWaitTime newIdBaseLocal(int batchSize) { return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize); }
@Test public void test_timeMiddle() { long id = gen.newIdBaseLocal(1516028439000L, 1234, 10).idBatch.base(); assertEquals(5300086112257234L, id); }
public EncryptedKeyVersion generateEncryptedKey(String encryptionKeyName) throws IOException, GeneralSecurityException { return getExtension().generateEncryptedKey(encryptionKeyName); }
@Test public void testGenerateEncryptedKey() throws Exception { // Generate a new EEK and check it KeyProviderCryptoExtension.EncryptedKeyVersion ek1 = kpExt.generateEncryptedKey(encryptionKey.getName()); assertEquals("Version name of EEK should be EEK", KeyProviderCryptoExtension.EEK, ...
@Override public String execute(CommandContext commandContext, String[] args) { String config = frameworkModel.getApplicationModels().stream() .map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()) .map(o -> o.orElse(...
@Test void testExecute() { Live live = new Live(frameworkModel); CommandContext commandContext = new CommandContext("live"); String result = live.execute(commandContext, new String[0]); Assertions.assertEquals(result, "false"); Assertions.assertEquals(commandContext.getHttpCo...
@Udf public <T extends Comparable<? super T>> List<T> arraySortWithDirection(@UdfParameter( description = "The array to sort") final List<T> input, @UdfParameter( description = "Marks the end of the series (inclusive)") final String direction) { if (input == null || direction == null) { ...
@Test public void shouldSortNullsToEndDescending() { final List<String> input = Arrays.asList(null, "foo", null, "bar", null); final List<String> output = udf.arraySortWithDirection(input, "desc"); assertThat(output, contains("foo", "bar", null, null, null)); }
@Override protected String getScheme() { return config.getScheme(); }
@Test public void testGetScheme() { S3FileSystem s3FileSystem = new S3FileSystem(s3Config("s3")); assertEquals("s3", s3FileSystem.getScheme()); s3FileSystem = new S3FileSystem(s3Config("other")); assertEquals("other", s3FileSystem.getScheme()); }
public static CompletionStage<Void> lockAsync( InterProcessLock lock, long timeout, TimeUnit unit, Executor executor) { CompletableFuture<Void> future = new CompletableFuture<>(); if (executor == null) { CompletableFuture.runAsync(() -> lock(future, lock, timeout, unit)); ...
@Test public void testContention() throws Exception { try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); InterProcessMutex lock1 = new InterProcessMutex(client, "/one/two"); ...
public Encoding getEncoding() { return encoding; }
@Test public void testEncodeCharactersOutsideOfLowerSpecial() { // Contains characters outside LOWER_SPECIAL String testString = "abcdefABCDEF1234!@#"; MetaStringEncoder encoder = new MetaStringEncoder('_', '$'); MetaString encodedMetaString = encoder.encode(testString); assertSame(encodedMetaStri...
public MemoryCache() { this.mainCache = new ConcurrentHashMap<>(); }
@Test public void testMemoryCache() { final MemoryCache memoryCache = new MemoryCache(); final String key = "data"; memoryCache.isExist(key).subscribe(v -> assertEquals(Boolean.FALSE, v)); memoryCache.cacheData(key, "data".getBytes(StandardCharsets.UTF_8), 10) .subscr...
public static int[] convertToByteCode(String instructions) { if (instructions == null || instructions.trim().length() == 0) { return new int[0]; } var splitedInstructions = instructions.trim().split(" "); var bytecode = new int[splitedInstructions.length]; for (var i = 0; i < splitedInstructi...
@Test void testInstructions() { var instructions = "LITERAL 35 SET_HEALTH SET_WISDOM SET_AGILITY PLAY_SOUND" + " SPAWN_PARTICLES GET_HEALTH ADD DIVIDE"; var bytecode = InstructionConverterUtil.convertToByteCode(instructions); Assertions.assertEquals(10, bytecode.length); Assertions.assertEqu...
public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path...
@Test public void testLookup_absolute_withDotDotsInPath_afterSymlink() throws IOException { assertExists(lookup("/work/four/five/.."), "/", "/"); assertExists(lookup("/work/four/six/.."), "/", "work"); }
@Override public PollResult poll(long currentTimeMs) { if (memberId == null) { return PollResult.EMPTY; } // Send any pending acknowledgements before fetching more records. PollResult pollResult = processAcknowledgements(currentTimeMs); if (pollResult != null) { ...
@Test public void testFetchDisconnected() { buildRequestManager(); assignFromSubscribed(singleton(tp0)); assertEquals(1, sendFetches()); client.prepareResponse(fullFetchResponse(tip0, records, acquiredRecords, Errors.NONE), true); networkClientDelegate.poll(time.timer(0)); ...
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group, final long timestamp, final boolean isForce, final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException { return invokeBrokerToResetOffset(addr, to...
@Test public void assertInvokeBrokerToResetOffset() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); ResetOffsetBody responseBody = new ResetOffsetBody(); responseBody.getOffsetTable().put(new MessageQueue(), 1L); setResponseBody(responseBody); ...
public List<StepOption> retriveOptions() { return Arrays.asList( new StepOption( DISABLE_MESSAGE_ID, getString( PKG, "JmsDialog.Options.DISABLE_MESSAGE_ID" ), disableMessageId ), new StepOption( DISABLE_MESSAGE_TIMESTAMP, getString( PKG, "JmsDialog.Options.DISABLE_MESSAGE_TIMESTAMP" ), disableMe...
@Test public void testRetriveOptions() { List<StepOption> compareStepOptions = Arrays.asList( new StepOption( DISABLE_MESSAGE_ID, getString( JmsProducerMeta.class, "JmsDialog.Options.DISABLE_MESSAGE_ID" ), "false" ), new StepOption( DISABLE_MESSAGE_TIMESTAMP, getString( JmsProducerMeta...
@Override public final void invoke() throws Exception { // Allow invoking method 'invoke' without having to call 'restore' before it. if (!isRunning) { LOG.debug("Restoring during invoke will be called."); restoreInternal(); } // final check to exit early bef...
@Test void testProcessWithAvailableOutput() throws Exception { try (final MockEnvironment environment = setupEnvironment(true, true)) { final int numberOfProcessCalls = 10; final AvailabilityTestInputProcessor inputProcessor = new AvailabilityTestInputProcessor(nu...
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) { // Start of evaluate boolean retval = false; // If we have 0 items in the list, evaluate the current condition // Otherwise, evaluate all sub-conditions // try { if ( isAtomic() ) { if ( function == FUNC_TRUE ) { ...
@Test public void testNullSmallerOrEqualsThanZero() { String left = "left"; String right = "right"; Long leftValue = null; Long rightValue = 0L; RowMetaInterface rowMeta = new RowMeta(); rowMeta.addValueMeta( new ValueMetaInteger( left ) ); rowMeta.addValueMeta( new ValueMetaInteger( rig...
public static boolean testURLPassesExclude(String url, String exclude) { // If the url doesn't decode to UTF-8 then return false, it could be trying to get around our rules with nonstandard encoding // If the exclude rule includes a "?" character, the url must exactly match the exclude rule. // ...
@Test public void wildcardInExcludePassesWhenWildcardsAllowed() throws Exception { AuthCheckFilter.ALLOW_WILDCARDS_IN_EXCLUDES.setValue(true); assertTrue(AuthCheckFilter.testURLPassesExclude("setup/setup-new.jsp","setup/setup-*")); }
public MacAddress encapEthDst() { return encapEthDst; }
@Test public void testConstruction() { final NiciraEncapEthDst encapEthDst1 = new NiciraEncapEthDst(mac1); assertThat(encapEthDst1, is(notNullValue())); assertThat(encapEthDst1.encapEthDst(), is(mac1)); }
public EndpointResponse registerHeartbeat(final HeartbeatMessage request) { handleHeartbeat(request); return EndpointResponse.ok(new HeartbeatResponse(true)); }
@Test public void shouldSendHeartbeat() { // When: final HeartbeatMessage request = new HeartbeatMessage(new KsqlHostInfoEntity("localhost", 8080), 1); final EndpointResponse response = heartbeatResource.registerHeartbeat(request); // Then: assertThat(response.getStatus(), is(200)); a...
static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException { // copy all the bytes that return immediately, stopping at the first // read that doesn't return a full buffer. int nextReadLength = Math.min(buf.remaining(), temp.length); int totalBytesRead = 0; int bytesR...
@Test public void testDirectSmallReads() throws Exception { ByteBuffer readBuffer = ByteBuffer.allocateDirect(10); MockInputStream stream = new MockInputStream(2, 3, 3); int len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, TEMP.get()); Assert.assertEquals(2, len); Assert....
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) { IdentityProvider provider = resolveProviderOrHandleResponse(request, response, INIT_CONTEXT); if (provider != null) { handleProvider(request, response, provider); } }
@Test public void redirect_contains_cookie_with_error_message_when_failing_because_of_UnauthorizedExceptionException() throws Exception { IdentityProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider("failing"); when(request.getRequestURI()).thenReturn("/sessions/init/" + identityProvider.ge...
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = ...
@Test public void testPojoGeneric2() throws NoSuchMethodException { String personName = "testName"; { Ageneric<Ageneric<PersonInfo>> generic2PersonInfo = createAGenericLoop(personName); Object o = JSON.toJSON(generic2PersonInfo); { Ageneric person...
public static void close(@Nullable Context context, boolean swallowIOException) throws NamingException { if (context == null) { return; } try { context.close(); } catch (NamingException e) { if (swallowIOException) { LOG.warn("NamingException thrown while closing context.", e);...
@Test public void shouldNotSwallow() throws Exception { Context context = mock(Context.class); doThrow(new NamingException()).when(context).close(); assertThatThrownBy(() -> ContextHelper.close(context, false)) .isInstanceOf(NamingException.class); }
public static void init(String applicationId, String transactionServiceGroup) { init(applicationId, transactionServiceGroup, null, null); }
@Test public void testInit() { TMClient.init(APPLICATION_ID, SERVICE_GROUP); TmNettyRemotingClient tmNettyRemotingClient = TmNettyRemotingClient.getInstance(); Assertions.assertEquals(tmNettyRemotingClient.getTransactionServiceGroup(), SERVICE_GROUP); }
@Udf public String concatWS( @UdfParameter(description = "Separator string and values to join") final String... inputs) { if (inputs == null || inputs.length < 2) { throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments."); } final String separator = inputs[0...
@Test public void shouldReturnEmptyIfAllInputsNull() { assertThat(udf.concatWS("SEP", null, null), is("")); assertThat(udf.concatWS(ByteBuffer.wrap(new byte[] {2}), null, null), is(EMPTY_BYTES)); }
@Override public Optional<ShardingTableNameReviser> getTableNameReviser() { return Optional.of(new ShardingTableNameReviser()); }
@Test void assertGetTableNameReviser() { Optional<ShardingTableNameReviser> tableNameReviser = reviseEntry.getTableNameReviser(); assertTrue(tableNameReviser.isPresent()); assertThat(tableNameReviser.get().getClass(), is(ShardingTableNameReviser.class)); }
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldNotAllowConfigWithEnvironmentsWithSameNames() { String content = configWithEnvironments( """ <environments> <environment name='uat' /> <environment name='uat' /> </environment...
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testDateType() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); Date gmtDate = Date.valueOf(LocalDate.of(2015, 11, 12)); SearchArgument arg = builder.startAnd().equals("date", PredicateLeaf.Type.DATE, gmtDate).end().build(); UnboundPredicate expected = ...
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) { AnalyzerContext context = new AnalyzerContext(); int treeSize = aggregatePredicateStatistics(predicate, false, context); int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h...
@Test void require_that_minfeature_is_1_for_simple_term() { Predicate p = feature("foo").inSet("bar"); PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p); assertEquals(1, r.minFeature); assertEquals(1, r.treeSize); assertTrue(r.sizeMap.isEmpty()); ...
@Description("Given a Bing tile, returns the polygon representation of the tile") @ScalarFunction("bing_tile_polygon") @SqlType(GEOMETRY_TYPE_NAME) public static Slice bingTilePolygon(@SqlType(BingTileType.NAME) long input) { BingTile tile = BingTile.decode(input); return serialize(tile...
@Test public void testBingTilePolygon() { assertFunction("ST_AsText(bing_tile_polygon(bing_tile('123030123010121')))", VARCHAR, "POLYGON ((59.996337890625 30.11662158281937, 59.996337890625 30.12612436422458, 60.00732421875 30.12612436422458, 60.00732421875 30.11662158281937, 59.996337890625 30.11662158...
@VisibleForTesting static <T extends Comparable<? super T>> boolean le(T a, T b) { return a.compareTo(b) <= 0; }
@Test public void testComparators_LE() { Assert.assertTrue(VersionChecker.le(0, 1)); Assert.assertTrue(VersionChecker.le(1, 1)); Assert.assertFalse(VersionChecker.le(2, 1)); }
public Optional<Session> getActiveSession(ApplicationId applicationId) { return getActiveSession(getTenant(applicationId), applicationId); }
@Test public void testThatPreviousSessionIsDeactivated() { deployApp(testAppJdiscOnly); Session firstSession = applicationRepository.getActiveSession(applicationId()).get(); deployApp(testAppJdiscOnly); assertEquals(DEACTIVATE, firstSession.getStatus()); }
@Override protected void doStart() throws Exception { super.doStart(); asyncDispatchesAwareServletRequestListener = new AsyncDispatchesAwareServletRequestListener(getAsyncDispatches()); }
@Test public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); handler.setHandler(new TestHandler()); handler.setName("handler"); handler.doStart(); assertThat...
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) ); } ...
@Test( expected = KettleDatabaseException.class ) public void testGetLegacyColumnNameDriverLessOrEqualToThreeException() throws Exception { DatabaseMetaData databaseMetaData = mock( DatabaseMetaData.class ); doReturn( 3 ).when( databaseMetaData ).getDriverMajorVersion(); new MySQLDatabaseMeta().getLegacy...
PartitionRegistration getPartition(Uuid topicId, int partitionId) { TopicControlInfo topic = topics.get(topicId); if (topic == null) { return null; } return topic.parts.get(partitionId); }
@Test public void testEligibleLeaderReplicas_ShrinkAndExpandIsr() { ReplicationControlTestContext ctx = new ReplicationControlTestContext.Builder().setIsElrEnabled(true).build(); ReplicationControlManager replicationControl = ctx.replicationControl; ctx.registerBrokers(0, 1, 2); ctx....
@Override public void setConfig(RedisClusterNode node, String param, String value) { RedisClient entry = getEntry(node); RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value); syncFuture(f); }
@Test public void testSetConfig() { testInCluster(connection -> { RedisClusterNode master = getFirstMaster(connection); connection.setConfig(master, "timeout", "10"); }); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Struct struct = (Struct) o; return Objects.equals(schema, struct.schema) && Arrays.deepEquals(values, struct.values); }
@Test public void testEquals() { Struct struct1 = new Struct(FLAT_STRUCT_SCHEMA) .put("int8", (byte) 12) .put("int16", (short) 12) .put("int32", 12) .put("int64", (long) 12) .put("float32", 12.f) .put("float64", ...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void nullTest() throws Exception { DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resolve(testMethod, new Object[]{}, null); assertThat(result).isNull(); ...
public void setDescription(String description) { this.description = description; }
@Test public void testSetDescription() { String description = "description"; String expected = "description"; Model instance = new Model(); instance.setDescription(description); assertEquals(expected, instance.getDescription()); }
@Override public void doSubscribe(final URL url, final NotifyListener listener) { try { checkDestroyed(); if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); boolean check = url.getParameter(CHECK_KEY, false); ...
@Test void testDoSubscribeWithException() { Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.doSubscribe(anyUrl, listener)); }
public void updateClusterState(final ClusterState state) { repository.persist(ComputeNode.getClusterStateNodePath(), state.name()); }
@Test void assertUpdateClusterStateClusterStateWithoutPath() { StatePersistService statePersistService = new StatePersistService(repository); statePersistService.updateClusterState(ClusterState.OK); verify(repository).persist(ComputeNode.getClusterStateNodePath(), ClusterState.OK.name()); ...
String getApplicationId() { return configuration.get(APPLICATION_ID).orElseThrow(() -> new IllegalArgumentException("Application ID is missing")); }
@Test public void return_default_value_of_application_id() { assertThat(underTest.getApplicationId()).isEqualTo("sonarqube"); }
public BigDecimal calculateTDEE(ActiveLevel activeLevel) { if(activeLevel == null) return BigDecimal.valueOf(0); BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer()); return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN); }
@Test void calculateTDEE_LIGHTLY_ACTIVE() { BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(ActiveLevel.LIGHTLY); assertEquals(new BigDecimal("2808.44"), TDEE); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseLaterVariadicWhenTwoVariadicsMatchReversedInsertionOrder() { // Given: givenFunctions( function(EXPECTED, 2, LONG, INT, STRING_VARARGS, DOUBLE), function(OTHER, 1, LONG, INT_VARARGS, STRING, DOUBLE) ); // When: final KsqlScalarFunction fun = u...
@Override public ApplicationId applicationId() { return OrchestratorUtil.toApplicationId(applicationInstance.reference()); }
@Test public void testApplicationId() { try (var api = modelUtils.createScopedApplicationApi(modelUtils.createApplicationInstance(new ArrayList<>()))) { assertEquals("tenant:application-name:default", api.applicationApi().applicationId().serializedForm()); } }
protected SuppressionRules rules() { return rules; }
@Test public void addDeviceTypeRule() { Device.Type deviceType1 = Device.Type.ROADM; Device.Type deviceType2 = Device.Type.SWITCH; Set<Device.Type> deviceTypes = new HashSet<>(); deviceTypes.add(deviceType1); cfg.deviceTypes(deviceTypes); configEvent(NetworkConfigE...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final ReadOnlySessionStore<GenericKey, GenericRow> store = sta...
@Test public void shouldIgnoreSessionsThatStartAtLowerBoundIfLowerBoundOpen() { // Given: final Range<Instant> startBounds = Range.openClosed( LOWER_INSTANT, UPPER_INSTANT ); givenSingleSession(LOWER_INSTANT, LOWER_INSTANT.plusMillis(1)); // When: final Iterator<WindowedRow> ...
CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File connectorConfigurationFile = Paths.get(filePath).toFile(); try { Map<String, String> connectorConfigs = objectMapper.readValue( ...
@Test public void testParseJsonFileWithCreateConnectorRequestWithoutInitialState() throws Exception { Map<String, Object> requestToWrite = new HashMap<>(); requestToWrite.put("name", CONNECTOR_NAME); requestToWrite.put("config", CONNECTOR_CONFIG); try (FileWriter writer = new FileWr...
public void refresh() { try { if (contextManager.getMetaDataContexts().getMetaData().getTemporaryProps().getValue(TemporaryConfigurationPropertyKey.PROXY_META_DATA_COLLECTOR_ENABLED)) { collectAndRefresh(); } // CHECKSTYLE:OFF } catch (final Exception ...
@Test void assertRefresh() { ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS); ShardingSphereStatistics statistics = mockStatistics(); when(contextManager.getMetaDataContexts().getStatistics()).thenReturn(statistics); ShardingSphereMetaData metaData = mo...
@Override public KsqlObject getKsqlObject(final int columnIndex) { return values.getKsqlObject(columnIndex - 1); }
@Test public void shouldGetKsqlObject() { assertThat(row.getKsqlObject("f_map"), is(new KsqlObject(ImmutableMap.of("k1", "v1", "k2", "v2")))); assertThat(row.getKsqlObject("f_struct"), is(new KsqlObject(ImmutableMap.of("f1", "baz", "f2", 12)))); }
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException { // set URL if set in authnRequest final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL(); if (authnAcsURL != null) { ...
@Test void resolveAcsUrlWithoutIndexInMultiAcsMetadata() throws SamlValidationException { AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class); AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.setAuthnRequest(authnRequ...
public static Version of(int major, int minor) { if (major == UNKNOWN_VERSION && minor == UNKNOWN_VERSION) { return UNKNOWN; } else { return new Version(major, minor); } }
@Test(expected = AssertionError.class) @RequireAssertEnabled public void construct_withNegativeMinor() { Version.of(1, -1); }
@Override public OperatorContext getOperatorContext() { return operatorContext; }
@Test(dataProvider = "hashEnabledAndMemoryLimitForMergeValues") public void testHashAggregationMemoryReservation(boolean hashEnabled, boolean spillEnabled, boolean revokeMemoryWhenAddingPages, long memoryLimitForMerge, long memoryLimitForMergeWithMemory) { JavaAggregationFunctionImplementation arrayAggC...
@Override public List<Class<?>> getIgnoredViewTypeList() { return new ArrayList<>(); }
@Test public void getIgnoredViewTypeList() { mSensorsAPI.ignoreViewType(Button.class); Assert.assertEquals(0, mSensorsAPI.getIgnoredViewTypeList().size()); }
@Override public TenantPackageDO getTenantPackage(Long id) { return tenantPackageMapper.selectById(id); }
@Test public void testGetTenantPackage() { // mock 数据 TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class); tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 // 调用 TenantPackageDO result = tenantPackageService.getTenantPackage(dbTenantPackage.ge...
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException { final List<MavenArtifact> result = new ArrayList<>(); try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); JsonParser ...
@Test public void shouldThrowExceptionWhenPatternCannotBeParsed() throws IOException { // Given Dependency dependency = new Dependency(); dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0f"); dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f5798170248d3...
public static String toString(Object o) { if (null == o) { return null; } return o.toString(); }
@Test public void testToString() { Assertions.assertNull(Utils.toString(null)); Assertions.assertEquals("", Utils.toString("")); Assertions.assertEquals("foo", Utils.toString("foo")); Assertions.assertEquals("123", Utils.toString(123)); }
public static String getRootCauseOrMessage(Throwable t) { final Throwable rootCause = getRootCause(t, true); return formatMessageCause(rootCause != null ? rootCause : t); }
@Test public void getRootCauseOrMessage() { assertThat(ExceptionUtils.getRootCauseOrMessage(new Exception("cause1", new Exception("root")))).satisfies(m -> { assertThat(m).isNotBlank(); assertThat(m).isEqualTo("root."); }); assertThat(ExceptionUtils.getRootCauseOrMess...
public static void main(String[] args) { Blacksmith blacksmith = new OrcBlacksmith(); Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); LOGGER.info(MANUFACTURED, blacksmith, weapon); weapon = blacksmith.manufactureWeapon(WeaponType.AXE); LOGGER.info(MANUFACTURED, blacksmith, weapon); ...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public void giveWine(Royalty r) { r.getDrink(); }
@Test void testGiveWine() { final var royalty = mock(Royalty.class); final var servant = new Servant("test"); servant.giveWine(royalty); verify(royalty).getDrink(); verifyNoMoreInteractions(royalty); }
public void emptyStruct(String message) { messages.add(message); hasEmptyStruct = true; }
@Test public void testEmptyStruct() { CompatibilityReport report = getCompatibilityReport(NestedEmptyStruct.class, NestedEmptyStruct.class); assertEquals( "encountered an empty struct: required_empty\nencountered an empty struct: optional_empty", report.prettyMessages()); assertTrue(report...
@Override public CiConfiguration loadConfiguration() { String revision = system.envVariable("DRONE_COMMIT_SHA"); return new CiConfigurationImpl(revision, getName()); }
@Test public void loadConfiguration() { setEnvVariable("CI", "true"); setEnvVariable("DRONE", "true"); setEnvVariable("DRONE_COMMIT_SHA", "abd12fc"); assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc"); }
public Node deserializeObject(JsonReader reader) { Log.info("Deserializing JSON to Node."); JsonObject jsonObject = reader.readObject(); return deserializeObject(jsonObject); }
@Test void testAttachingSymbolResolver() { SymbolResolver stubResolver = new SymbolResolver() { @Override public <T> T resolveDeclaration(Node node, Class<T> resultClass) { return null; } @Override public <T> T toResolvedType(Type ...