focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Result runExtractor(String value) { final Matcher matcher = pattern.matcher(value); final boolean found = matcher.find(); if (!found) { return null; } final int start = matcher.groupCount() > 0 ? matcher.start(1) : -1; final int end = matcher.groupCou...
@Test public void testReplacementWithCustomReplacement() throws Exception { final Message message = messageFactory.createMessage("Foobar 123", "source", Tools.nowUTC()); final RegexReplaceExtractor extractor = new RegexReplaceExtractor( metricRegistry, "id", ...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_containsExactly_primitiveFloatArray_inOrder_failure() { expectFailureWhenTestingThat(array(1.1f, 2.2f, 3.3f)) .usingExactEquality() .containsExactly(array(2.2f, 1.1f, 3.3f)) .inOrder(); assertFailureKeys( "value of", "contents match,...
public static TypeBuilder<Schema> builder() { return new TypeBuilder<>(new SchemaCompletion(), new NameContext()); }
@Test void namesFailAbsent() { assertThrows(SchemaParseException.class, () -> { SchemaBuilder.builder().type("notdefined"); }); }
@Override public NodeInfo getNode(String nodeId) { final Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); if (subClustersActive.isEmpty()) { throw new NotFoundException(FederationPolicyUtils.NO_ACTIVE_SUBCLUSTER_AVAILABLE); } final Map<SubClusterInfo, No...
@Test public void testGetNode() { NodeInfo responseGet = interceptor.getNode("testGetNode"); Assert.assertNotNull(responseGet); Assert.assertEquals(NUM_SUBCLUSTER - 1, responseGet.getLastHealthUpdate()); }
public boolean isVersionedExpirationTimerSupported() { return allDevicesHaveCapability(DeviceCapabilities::versionedExpirationTimer); }
@Test void isVersionedExpirationTimerSupported() { assertTrue(AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), List.of(versionedExpirationTimerCapableDevice), "1234".getBytes(StandardCharsets.UTF_8)).isVersionedExpirationTimerSupported()); assertFalse(Ac...
@Override public boolean doOffer(final Runnable runnable) { return super.offer(runnable); }
@Test public void testOffer() { MemoryLimitedTaskQueue memoryLimitedTaskQueue = new MemoryLimitedTaskQueue<>(instrumentation); assertTrue(memoryLimitedTaskQueue.doOffer(() -> { })); }
@Override public V put(K key, V value, Duration ttl) { return get(putAsync(key, value, ttl)); }
@Test public void testKeySet() throws InterruptedException { RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simple03"); map.put(new SimpleKey("33"), new SimpleValue("44"), Duration.ofSeconds(1)); map.put(new SimpleKey("1"), new SimpleValue("2")); Assertion...
public static String[][] normalizeArrays( int normalizeToLength, String[]... arraysToNormalize ) { if ( arraysToNormalize == null ) { return null; } int arraysToProcess = arraysToNormalize.length; String[][] rtn = new String[ arraysToProcess ][]; for ( int i = 0; i < arraysToNormalize.length; ...
@Test public void testNormalizeArraysMethods() { String[] s1 = new String[] { "one" }; String[] s2 = new String[] { "one", "two" }; String[] s3 = new String[] { "one", "two", "three" }; long[] l1 = new long[] { 1 }; long[] l2 = new long[] { 1, 2 }; long[] l3 = new long[] { 1, 2, 3 }; short...
public long getBlock_len() { return block_len; }
@Test public void testGetBlock_len() { assertEquals(TestParameters.VP_BLOCK_LENGTH, chmItspHeader.getBlock_len()); }
private static String parseArchitecture(P4Info p4info) { if (p4info.hasPkgInfo()) { return p4info.getPkgInfo().getArch(); } return null; }
@Test public void testParseArchitecture() throws Exception { // Generate two PiPipelineModels from the same p4Info file PiPipelineModel model = P4InfoParser.parse(p4InfoUrl); PiPipelineModel sameAsModel = P4InfoParser.parse(p4InfoUrl); PiPipelineModel model3 = P4InfoParser.parse(p4I...
@Override public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("clusterState", clusterState.name()); root.add("nodeState", nodeState.name()); root.add("clusterVersion", clusterVersion.toString()); root.add("memberVersion", memberVersion.toString()); ...
@Test public void toJson() throws Exception { ClusterState clusterState = ClusterState.ACTIVE; com.hazelcast.instance.impl.NodeState nodeState = com.hazelcast.instance.impl.NodeState.PASSIVE; Version clusterVersion = Version.of("3.8"); MemberVersion memberVersion = MemberVersion.of("...
@Override public void onSelectorChanged(final List<SelectorData> selectorDataList, final DataEventTypeEnum eventType) { WebsocketData<SelectorData> websocketData = new WebsocketData<>(ConfigGroupEnum.SELECTOR.name(), eventType.name(), selectorDataList); WebsocketCollector.send(GsonUt...
@Test public void testOnSelectorChanged() { String message = "{\"groupType\":\"SELECTOR\",\"eventType\":\"UPDATE\",\"data\":" + "[{\"id\":\"1336329408516136960\",\"pluginId\":\"5\",\"pluginName\":\"divide\",\"name\":" + "\"/http\",\"matchMode\":0,\"type\":1,\"sort\":1,\"enabl...
@Override @InterfaceAudience.Private public void readFields(DataInput in) throws IOException { this.length = in.readLong(); this.fileCount = in.readLong(); this.directoryCount = in.readLong(); setQuota(in.readLong()); setSpaceConsumed(in.readLong()); setSpaceQuota(in.readLong()); }
@Test public void testReadFields() throws IOException { long length = 11111; long fileCount = 22222; long directoryCount = 33333; long quota = 44444; long spaceConsumed = 55555; long spaceQuota = 66666; ContentSummary contentSummary = new ContentSummary.Builder().build(); DataInput i...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnInvalidActionReturnTypeRef() { @RestLiCollection(name = "invalidReturnTypeRef") class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> { @Action(name = "invalidReturnTypeRef", returnTyperef = StringRef.class) ...
@VisibleForTesting public static void validateAndResolveService(Service service, SliderFileSystem fs, org.apache.hadoop.conf.Configuration conf) throws IOException { boolean dnsEnabled = conf.getBoolean(RegistryConstants.KEY_DNS_ENABLED, RegistryConstants.DEFAULT_DNS_ENABLED); if (dnsEnabl...
@Test public void testArtifacts() throws IOException { SliderFileSystem sfs = ServiceTestUtils.initMockFs(); Service app = new Service(); app.setName("service1"); app.setVersion("v1"); Resource res = new Resource(); app.setResource(res); res.setMemory("512M"); // no artifact id fails...
public static boolean checkpw(String plaintext, String hashed) { byte hashed_bytes[]; byte try_bytes[]; try { String try_pw = hashpw(plaintext, hashed); hashed_bytes = hashed.getBytes("UTF-8"); try_bytes = try_pw.getBytes("UTF-8"); } catch (Unsupported...
@Test public void testCheckpw_success() { System.out.print("BCrypt.checkpw w/ good passwords: "); for (int i = 0; i < test_vectors.length; i++) { String plain = test_vectors[i][0]; String expected = test_vectors[i][2]; Assert.assertTrue(BCrypt.checkpw(plain, ex...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("loaded", (Gauge<Long>) mxBean::getTotalLoadedClassCount); gauges.put("unloaded", (Gauge<Long>) mxBean::getUnloadedClassCount); return gauges; }
@Test public void loadedGauge() { final Gauge gauge = (Gauge) gauges.getMetrics().get("loaded"); assertThat(gauge.getValue()).isEqualTo(2L); }
@Override public Thread newThread(Runnable r) { String name = prefix + "_" + counter.incrementAndGet(); if (totalSize > 1) { name += "_" + totalSize; } Thread thread = new FastThreadLocalThread(group, r, name); thread.setDaemon(makeDaemons); if (thread.ge...
@Test public void testNamedThreadFactoryWithSecurityManager() { NamedThreadFactory factory = new NamedThreadFactory("testThreadGroup", true); Thread thread = factory.newThread(() -> {}); assertThat(thread.getThreadGroup()).isNotNull(); }
public Component buildProject(ScannerReport.Component project, String scmBasePath) { this.rootComponent = project; this.scmBasePath = trimToNull(scmBasePath); Node root = createProjectHierarchy(project); return buildComponent(root, "", ""); }
@Test void project_name_is_loaded_from_db_if_not_on_main_branch() { String reportName = randomAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setName(reportName) .build(); Component root = newUnderTest(SOME_PROJECT_ATTRIBUTES, false) .buildPr...
@Override public String execute(CommandContext commandContext, String[] args) { if (ArrayUtils.isEmpty(args)) { return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \...
@Test void testOverriddenMethodWithSpecifyParamType() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) ...
public static UParens create(UExpression expression) { return new AutoValue_UParens(expression); }
@Test public void serialization() { SerializableTester.reserializeAndAssert(UParens.create(ULiteral.longLit(5L))); }
@VisibleForTesting static int calculateTextWidth(FontMetrics metrics, String line) { char[] chars = line.toCharArray(); int textWidth = 0; int begin = 0; boolean inTag = false; for (int j = 0; j < chars.length; j++) { if (chars[j] == '<') { textWidth += metrics.stringWidth(line.substring(begin,...
@Test public void testCalculateTextWidth() { FontMetrics fontMetics = mock(FontMetrics.class); when(fontMetics.stringWidth(anyString())).thenAnswer((invocation) -> ((String) invocation.getArguments()[0]).length()); assertEquals(11, calculateTextWidth(fontMetics, "line1<col=ff0000>>line2")); }
public static String escapeHtml(String input) { // Avoid building a new string in the majority of cases (nothing to escape) StringBuilder sb = null; loop: for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); String replacement; switch ...
@Test public void testEscapeHtml() { assertEquals("nothing to escape", Escaping.escapeHtml("nothing to escape")); assertEquals("&amp;", Escaping.escapeHtml("&")); assertEquals("&lt;", Escaping.escapeHtml("<")); assertEquals("&gt;", Escaping.escapeHtml(">")); assertEquals("&qu...
@Override @PublicAPI(usage = ACCESS) public String getName() { return WILDCARD_TYPE_NAME + boundsToString(); }
@Test public void wildcard_name_upper_bounded_by_array() { @SuppressWarnings("unused") class UpperBounded<T extends List<? extends String[][]>> { } JavaWildcardType wildcardType = importWildcardTypeOf(UpperBounded.class); assertThat(wildcardType.getName()).isEqualTo("? exte...
public static Configuration configurePythonDependencies(ReadableConfig config) { final PythonDependencyManager pythonDependencyManager = new PythonDependencyManager(config); final Configuration pythonDependencyConfig = new Configuration(); pythonDependencyManager.applyToConfiguration(pythonDepen...
@Test void testPythonArchives() { Configuration config = new Configuration(); config.set( PythonOptions.PYTHON_ARCHIVES, "hdfs:///tmp_dir/file1.zip," + "hdfs:///tmp_dir/file1.zip," + "tmp_dir/py37.zip," ...
static PodSecurityProvider findProviderOrThrow(String providerClass) { ServiceLoader<PodSecurityProvider> loader = ServiceLoader.load(PodSecurityProvider.class); for (PodSecurityProvider provider : loader) { if (providerClass.equals(provider.getClass().getCanonicalName())) { ...
@Test public void testExistingClass() { assertThat(PodSecurityProviderFactory.findProviderOrThrow("io.strimzi.plugin.security.profiles.impl.RestrictedPodSecurityProvider"), is(instanceOf(RestrictedPodSecurityProvider.class))); }
@ExceptionHandler(NullPointerException.class) protected ShenyuAdminResult handleNullPointException(final NullPointerException exception) { LOG.error("null pointer exception ", exception); return ShenyuAdminResult.error(CommonErrorCode.NOT_FOUND_EXCEPTION, ShenyuResultMessage.NOT_FOUND_EXCEPTION); ...
@Test public void testNullPointExceptionHandler() { NullPointerException nullPointerException = new NullPointerException("TEST NULL POINT EXCEPTION"); ShenyuAdminResult result = exceptionHandlersUnderTest.handleNullPointException(nullPointerException); Assertions.assertEquals(result.getCode(...
@Override public int getNumOfPartitions() { return topicMetadata.numPartitions(); }
@Test public void testGetNumOfPartitions() throws Exception { String topicName = "test-get-num-of-partitions"; ClientConfigurationData conf = new ClientConfigurationData(); conf.setServiceUrl("pulsar://localhost:6650"); conf.setStatsIntervalSeconds(100); ThreadFactory thread...
public long getSize() { return size; }
@Test public void testGetSize() { assertEquals(TestParameters.VP_CONTROL_DATA_SIZE, chmLzxcControlData.getSize()); }
@VisibleForTesting static String extractTableName(MultivaluedMap<String, String> pathParameters, MultivaluedMap<String, String> queryParameters) { String tableName = extractTableName(pathParameters); if (tableName != null) { return tableName; } return extractTableName(queryParameters); }
@Test public void testExtractTableNameWithTableNameWithTypeInQueryParams() { MultivaluedMap<String, String> pathParams = new MultivaluedHashMap<>(); MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>(); queryParams.putSingle("tableNameWithType", "E"); queryParams.putSingle("schemaNa...
@Override public void preflight(final Path source, final Path target) throws BackgroundException { if(!CteraTouchFeature.validate(target.getName())) { throw new InvalidFilenameException(MessageFormat.format(LocaleFactory.localizedString("Cannot rename {0}", "Error"), source.getName())).withFile(...
@Test public void testPreflightFileAccessDeniedTargetExistsNotWritableCustomProps() throws Exception { final Path source = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); source.setAttributes(source.attributes().with...
public static String buildPopRetryTopicV1(String topic, String cid) { return MixAll.RETRY_GROUP_TOPIC_PREFIX + cid + POP_RETRY_SEPARATOR_V1 + topic; }
@Test public void testBuildPopRetryTopicV1() { assertThat(KeyBuilder.buildPopRetryTopicV1(topic, group)).isEqualTo(MixAll.RETRY_GROUP_TOPIC_PREFIX + group + "_" + topic); }
@Override public ExecuteContext before(ExecuteContext context) { String name = context.getMethod().getName(); if (context.getArguments() == null || context.getArguments().length == 0) { return context; } Object argument = context.getArguments()[0]; if ("setName".e...
@Test public void testPutParametersWithNull() throws NoSuchMethodException { Object[] args = new Object[1]; args[0] = null; ExecuteContext context = ExecuteContext.forMemberMethod(new Object(), ApplicationConfig.class.getMethod("setParameters", Map.class), args, null, null); ...
@Override public AuthenticationDataSource getAuthDataSource() { return authenticationDataSource; }
@Test public void verifyGetAuthRoleBeforeAuthenticateFails() { CountingAuthenticationProvider provider = new CountingAuthenticationProvider(); AuthData authData = AuthData.of("role".getBytes()); OneStageAuthenticationState authState = new OneStageAuthenticationState(authData, null, null, pro...
@VisibleForTesting Class<?> cookClass( UserDefinedJavaClassDef def, ClassLoader clsloader ) throws CompileException, IOException, RuntimeException, KettleStepException { String checksum = def.getChecksum(); Class<?> rtn = UserDefinedJavaClassMeta.classCache.getIfPresent( checksum ); if ( rtn != null ) { ...
@Test public void cookClassesCachingTest() throws Exception { String codeBlock1 = "public boolean processRow() {\n" + " return true;\n" + "}\n\n"; String codeBlock2 = "public boolean processRow() {\n" + " // Random comment\n" + " return true;\n" + "}\n\n"; ...
public static UStaticIdent create(UClassIdent classIdent, CharSequence member, UType memberType) { return new AutoValue_UStaticIdent(classIdent, StringName.of(member), memberType); }
@Test public void serialization() { SerializableTester.reserializeAndAssert( UStaticIdent.create( "java.lang.Integer", "valueOf", UMethodType.create( UClassType.create("java.lang.Integer"), UClassType.create("java.lang.String")))); }
@Udf public <T> String toJsonString(@UdfParameter final T input) { return toJson(input); }
@Test public void shouldSerializeBoolean() { // When: final String result = udf.toJsonString(true); // Then: assertEquals("true", result); }
@Override public synchronized void start() { LOG.info("Starting {}", this.getClass().getSimpleName()); startRejectingServer(); }
@Test public void doubleStartRejectingServer() { RpcServerService service = RpcServerService.Factory.create(mRpcAddress, mMasterProcess, mRegistry); service.start(); Assert.assertThrows("rejecting server must not be running", IllegalStateException.class, service::start); }
public static void main(String[] args) { var customer = Customer.newCustomer(BORROWER, INVESTOR); LOGGER.info("New customer created : {}", customer); var hasBorrowerRole = customer.hasRole(BORROWER); LOGGER.info("Customer has a borrower role - {}", hasBorrowerRole); var hasInvestorRole = customer....
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> ApplicationRoleObject.main(new String[]{})); }
@Operation(summary = "create", description = "CREATE_TASK_GROUP_NOTE") @Parameters({ @Parameter(name = "name", description = "NAME", schema = @Schema(implementation = String.class)), @Parameter(name = "projectCode", description = "PROJECT_CODE", schema = @Schema(implementation = long.class))...
@Test public void testCreateTaskGroup() throws Exception { // success MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("name", "TGQ1"); paramsMap.add("description", "this is a task group queue!"); paramsMap.add("groupSize", "10"); ...
public List<RoutingProto.Route> getServiceRouterRule(String namespace, String sourceService, String dstService) { LOG.debug("Get service router rules with namespace:{} and sourceService:{} and dstService:{}.", namespace, sourceService, dstService); List<RoutingProto.Route> rules = new ArrayList<>(); //get sourc...
@Test public void testGetServiceRouterRule() { final String testNamespace = "testNamespace"; final String testSourceService = "testSourceService"; final String testDstService = "testDstService"; RoutingProto.Routing routing = RoutingProto.Routing.newBuilder() .addOutbounds(RoutingProto.Route.newBuilder()....
@Override public E putIfAbsent(String key, E value) { return computeIfAbsent(key, k -> value); }
@Test public void putIfAbsent_cacheMiss_updatesCache() { Function<String, Integer> mappingFunction = k -> 17; doReturn(null).when(mutableEntryMock).getValue(); entryProcessorMock = new CacheRegistryStore.AtomicComputeProcessor<>(); entryProcessorArgMock = mappingFunction; In...
public List<String> getDeletedIds() { return deletedIds; }
@Test void getDeletedIds() { List<String> expectDeleteIds = ListUtil.map(selectorDOList, BaseDO::getId); List<String> actualDeleteIds = batchSelectorDeletedEvent.getDeletedIds(); assertArrayEquals(expectDeleteIds.toArray(new String[0]), actualDeleteIds.toArray(new String[0])); }
public FindBrokerResult findBrokerAddressInSubscribe( final String brokerName, final long brokerId, final boolean onlyThisBroker ) { if (brokerName == null) { return null; } String brokerAddr = null; boolean slave = false; boolean found = f...
@Test public void testFindBrokerAddressInSubscribeWithOneBroker() throws IllegalAccessException { brokerAddrTable.put(defaultBroker, createBrokerAddrMap()); consumerTable.put(group, createMQConsumerInner()); ConcurrentMap<String, HashMap<String, Integer>> brokerVersionTable = new ConcurrentH...
@SneakyThrows(ReflectiveOperationException.class) public static <T extends YamlConfiguration> T unmarshal(final File yamlFile, final Class<T> classType) throws IOException { try (BufferedReader inputStreamReader = Files.newBufferedReader(Paths.get(yamlFile.toURI()))) { T result = new Yaml(new Sh...
@Test void assertUnmarshalWithEmptyYamlBytes() throws IOException { URL url = getClass().getClassLoader().getResource("yaml/empty-config.yaml"); assertNotNull(url); String yamlContent = readContent(url); YamlShortcutsConfigurationFixture actual = YamlEngine.unmarshal(yamlContent.getB...
static Optional<SearchPath> fromString(String path) { if (path == null || path.isEmpty()) { return Optional.empty(); } if (path.indexOf(';') >= 0) { return Optional.empty(); // multi-level not supported at this time } try { SearchPath sp = pars...
@Test void invalidPartMustThrowException() { try { SearchPath.fromString("p/0"); fail("Expected exception"); } catch (InvalidSearchPathException e) { // success } }
public void addLast(PDOutlineItem newChild) { requireSingleNode(newChild); append(newChild); updateParentOpenCountForAddedChild(newChild); }
@Test void cannotAddLastAList() { PDOutlineItem child = new PDOutlineItem(); child.insertSiblingAfter(new PDOutlineItem()); child.insertSiblingAfter(new PDOutlineItem()); assertThrows(IllegalArgumentException.class, () -> root.addLast(child)); }
public JspEmail(String sFileID, String sLocale, Object oCaller) { if (sLocale != null) { sFileID = sLocale + "-" + sFileID; } sHtmlName_ = "/" + sFileID + "-html.jsp"; sPlainName_ = "/" + sFileID + "-plain.jsp"; request_ = new StringHttpServletRequest();...
@Test public void jspEmail() { new ConfigManager("testapp", ApplicationType.COMMAND_LINE); JspEmail jsp = new JspEmail("jsp_email", null, this); jsp.getSession().setAttribute("name", "JSPEmail Unit Test"); jsp.executeJSP(); String plain = jsp.getPlain(); String html =...
public WeightedItem<T> addOrVote(T item) { for (int i = 0; i < list.size(); i++) { WeightedItem<T> weightedItem = list.get(i); if (weightedItem.item.equals(item)) { voteFor(weightedItem); return weightedItem; } } return organize...
@Test public void testListReorganizesAfterMaxSize() { WeightedEvictableList<String> list = new WeightedEvictableList<>(3, 100); list.addOrVote("c"); list.addOrVote("b"); list.addOrVote("b"); list.addOrVote("a"); list.addOrVote("a"); list.addOrVote("a"); ...
@Config("failure-resolver.enabled") public FailureResolverConfig setEnabled(boolean enabled) { this.enabled = enabled; return this; }
@Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("failure-resolver.enabled", "false") .build(); FailureResolverConfig expected = new FailureResolverConfig() .setEnab...
protected RequestInterceptor createRequestInterceptorChain() { Configuration conf = getConfig(); List<String> interceptorClassNames = getInterceptorClassNames(conf); RequestInterceptor pipeline = null; RequestInterceptor current = null; for (String interceptorClassName : interceptorClassNames) { ...
@Test public void testRequestInterceptorChainCreation() throws Exception { RequestInterceptor root = super.getAMRMProxyService().createRequestInterceptorChain(); int index = 0; while (root != null) { switch (index) { case 0: case 1: case 2: Assert.assertEquals(PassT...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void highPrecisionNumericDecimalToConnect() { // this number is too big to be kept in a float64! BigDecimal reference = new BigDecimal("1.23456789123456789"); Schema schema = Decimal.schema(17); String msg = "{ \"schema\": { \"type\": \"bytes\", \"name\": \"org.apache.ka...
public Type getGELFType() { if (payload.length < Type.HEADER_SIZE) { throw new IllegalStateException("GELF message is too short. Not even the type header would fit."); } return Type.determineType(payload[0], payload[1]); }
@Test public void testGetGELFTypeDetectsGZIPCompressedMessage() throws Exception { byte[] fakeData = new byte[20]; fakeData[0] = (byte) 0x1f; fakeData[1] = (byte) 0x8b; GELFMessage msg = new GELFMessage(fakeData); assertEquals(GELFMessage.Type.GZIP, msg.getGELFType()); }
@Override public <R> HoodieData<HoodieRecord<R>> tagLocation( HoodieData<HoodieRecord<R>> records, HoodieEngineContext context, HoodieTable hoodieTable) { return HoodieJavaRDD.of(HoodieJavaRDD.getJavaRDD(records) .mapPartitionsWithIndex(locationTagFunction(hoodieTable.getMetaClient()), true));...
@Test public void testEnsureTagLocationUsesCommitTimeline() throws Exception { // Load to memory HoodieWriteConfig config = getConfigBuilder(100, false, false) .withRollbackUsingMarkers(false).build(); SparkHoodieHBaseIndex index = new SparkHoodieHBaseIndex(config); try (SparkRDDWriteClient wr...
public static int computeNetworkBuffersForAnnouncing( final int numBuffersPerChannel, final int numFloatingBuffersPerGate, final Optional<Integer> maxRequiredBuffersPerGate, final int sortShuffleMinParallelism, final int sortShuffleMinBuffers, fina...
@Test void testComputeRequiredNetworkBuffers() throws Exception { int numBuffersPerChannel = 5; int numBuffersPerGate = 8; Optional<Integer> maxRequiredBuffersPerGate = Optional.of(Integer.MAX_VALUE); int sortShuffleMinParallelism = 8; int numSortShuffleMinBuffers = 12; ...
@Override public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewKey(), "New name must not be null!...
@Test public void testRenameNX() { testInClusterReactive(connection -> { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer origi...
@JsonProperty("type") public FSTType getFstType() { return _fstType; }
@Test public void withDisabledFalse() throws JsonProcessingException { String confStr = "{\"disabled\": false}"; FstIndexConfig config = JsonUtils.stringToObject(confStr, FstIndexConfig.class); assertFalse(config.isDisabled(), "Unexpected disabled"); assertNull(config.getFstType(), "Unexpected ...
public static List<UpdateRequirement> forReplaceView( ViewMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid view metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Build...
@Test public void setLocationForView() { List<UpdateRequirement> requirements = UpdateRequirements.forReplaceView( viewMetadata, ImmutableList.of(new MetadataUpdate.SetLocation("location"))); requirements.forEach(req -> req.validate(viewMetadata)); assertThat(requirements) .ha...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test(expectedExceptions = EmptyStackException.class) public void testNotMissingOperandAnd() { PredicateExpressionParser.parse("! & com.linkedin.data.it.AlwaysFalsePredicate"); }
public void rehash() { resize(keys.length); }
@Test public void testRehash() { removeOdd(); map.trimToSize(); testGet(map); }
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public @Nullable <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) { return createEvaluator((AppliedPTransform) application); }
@Test public void unboundedSourceWithDuplicatesMultipleCalls() throws Exception { Long[] outputs = new Long[20]; for (long i = 0L; i < 20L; i++) { outputs[(int) i] = i % 5L; } TestUnboundedSource<Long> source = new TestUnboundedSource<>(BigEndianLongCoder.of(), outputs); source.dedupes = tru...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsAnyOf_primitiveFloatArray_success() { assertThat(array(1.0f, TOLERABLE_2POINT2, 3.0f)) .usingTolerance(DEFAULT_TOLERANCE) .containsAnyOf(array(99.99f, 2.2f)); }
void wakeup() { wokenUp.set(true); lock.lock(); try { notEmptyCondition.signalAll(); } finally { lock.unlock(); } }
@Test public void testWakeup() throws Exception { try (ShareFetchBuffer fetchBuffer = new ShareFetchBuffer(logContext)) { final Thread waitingThread = new Thread(() -> { final Timer timer = time.timer(Duration.ofMinutes(1)); fetchBuffer.awaitNotEmpty(timer); ...
public Optional<Integer> leaderOpt() { return leader == LeaderAndIsr.NO_LEADER ? Optional.empty() : Optional.of(leader); }
@Test public void testLeaderOpt() { LeaderAndIsr leaderAndIsr = new LeaderAndIsr(2, Arrays.asList(1, 2, 3)); assertEquals(2, leaderAndIsr.leaderOpt().orElse(0)); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { if(status.isExists()) { delete.delete(Collections.singletonMap(renamed, sta...
@Test public void testMoveNotFound() throws Exception { final Home workdir = new FTPWorkdirService(session); final Path test = new Path(workdir.find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)); assertThrows(NotfoundException.class, () -> new FTPMoveFeature(session).move(test...
public static MemberSelector and(MemberSelector... selectors) { return new AndMemberSelector(selectors); }
@Test public void testAndMemberSelector3() { when(member.localMember()).thenReturn(true); when(member.isLiteMember()).thenReturn(true); MemberSelector selector = MemberSelectors.and(LOCAL_MEMBER_SELECTOR, LITE_MEMBER_SELECTOR); assertTrue(selector.select(member)); verify(memb...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { if (tradingRecord != null && !tradingRecord.isClosed()) { Num entryPrice = tradingRecord.getCurrentPosition().getEntry().getNetPrice(); Num currentPrice = this.referencePrice.getValue(index); N...
@Test public void testStopLossTriggeredOnLongPosition() { TradingRecord tradingRecord = new BaseTradingRecord(); tradingRecord.enter(0, series.getBar(0).getClosePrice(), series.numOf(1)); AverageTrueRangeTrailingStopLossRule rule = new AverageTrueRangeTrailingStopLossRule(series, 3, 1.0); ...
@Override public void onChannelClose(String remoteAddr, Channel channel) { this.namesrvController.getRouteInfoManager().onChannelDestroy(channel); }
@Test public void testOnChannelClose() { brokerHousekeepingService.onChannelClose("127.0.0.1:9876", null); }
@Override public V replace(K key, V newValue) { return map.replace(key, newValue); }
@Test public void testReplace() { map.put(42, "oldValue"); String oldValue = adapter.replace(42, "newValue"); assertEquals("oldValue", oldValue); assertEquals("newValue", map.get(42)); }
public static Builder from(K8sNode node) { return new Builder() .hostname(node.hostname()) .clusterName(node.clusterName()) .type(node.type()) .segmentId(node.segmentId()) .intgBridge(node.intgBridge()) .extBridge(no...
@Test public void testFrom() { K8sNode updatedNode = DefaultK8sNode.from(refNode).build(); assertEquals(updatedNode, refNode); }
@Override public boolean overlap(final Window other) { if (getClass() != other.getClass()) { throw new IllegalArgumentException("Cannot compare windows of different type. Other window has type " + other.getClass() + "."); } return true; }
@Test public void cannotCompareUnlimitedWindowWithDifferentWindowType() { assertThrows(IllegalArgumentException.class, () -> window.overlap(sessionWindow)); }
public byte[] getNextTag() { byte[] tagBytes = null; if (tagPool != null) { tagBytes = tagPool.pollFirst(); } if (tagBytes == null) { long tag = nextTagId++; int size = encodingSize(tag); tagBytes = new byte[size]; for (int ...
@Test public void testTagGenerationWorksWithIdRollover() throws Exception { AmqpTransferTagGenerator tagGen = new AmqpTransferTagGenerator(false); Field urisField = tagGen.getClass().getDeclaredField("nextTagId"); urisField.setAccessible(true); urisField.set(tagGen, Long.MAX_VALUE +...
@Override public long removeConsumer(String groupName, String consumerName) { return get(removeConsumerAsync(groupName, consumerName)); }
@Test public void testRemoveConsumer() { RStream<String, String> stream = redisson.getStream("test"); stream.add(StreamAddArgs.entry("0", "0")); stream.createGroup(StreamCreateGroupArgs.name("testGroup").makeStream()); StreamMessageId id1 = stream.add(StreamAddArgs.entry("1", "1")...
@Override public void publishLong(MetricDescriptor descriptor, long value) { publishNumber(descriptor, value, LONG); }
@Test public void when_singleMetric() throws Exception { MetricDescriptor descriptor = newDescriptor() .withMetric("c") .withTag("tag1", "a") .withTag("tag2", "b"); jmxPublisher.publishLong(descriptor, 1L); helper.assertMBeans(singletonList( ...
@Override public void onNewResourcesAvailable() { checkDesiredOrSufficientResourcesAvailable(); }
@Test void testNotifyNewResourcesAvailable() { ctx.setHasDesiredResources(() -> false); // initially, not enough resources WaitingForResources wfr = new WaitingForResources(ctx, LOG, Duration.ZERO, STABILIZATION_TIMEOUT); ctx.setHasDesiredResources(() -> true); // make resour...
boolean shouldRetry(GetQueryExecutionResponse getQueryExecutionResponse) { String stateChangeReason = getQueryExecutionResponse.queryExecution().status().stateChangeReason(); if (this.retry.contains("never")) { LOG.trace("AWS Athena start query execution detected error ({}), marked as not r...
@Test public void shouldRetryReturnsTrueForExhaustedResourcedError() { Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable"); assertTrue(helper.shouldRetry( newGetQueryExecutionResponse(QueryExecutionState.FAILED, "exhausted resources at this scale factor"))); }
@Override public List<RemoteFileInfo> getRemoteFiles(Table table, GetRemoteFilesParams params) { TableVersionRange version = params.getTableVersionRange(); long snapshotId = version.end().isPresent() ? version.end().get() : -1; return getRemoteFiles((IcebergTable) table, snapshotId, params.g...
@Test public void testGetRemoteFile() throws IOException { IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG); List<Column> columns = Lists.newArrayList(new Column("k1", INT), new Column("k2", INT)); IcebergMetadata metadata = ne...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { byte[] header = new byte[4]; IOUtils.read(stream, header, 0, 4); // Extract magic byte if (header[0] == (byte) 'i' && hea...
@Test public void testICNS_basic() throws Exception { Metadata metadata = new Metadata(); metadata.set(Metadata.CONTENT_TYPE, "image/icns"); metadata.set("Icons count", "1"); metadata.set("Icons details", "512x512 (JPEG 2000 or PNG format)"); try (InputStream stream = getCl...
public List<KuduPredicate> convert(ScalarOperator operator) { if (operator == null) { return null; } return operator.accept(this, null); }
@Test public void testNull() { List<KuduPredicate> result = CONVERTER.convert(null); Assert.assertNull(result); }
public Quantity<U> zoomBy(double zoom) { return new Quantity<U>(value * zoom, unit); }
@Test public void zoomQuantity() throws Exception { Quantity<Metrics> q = new Quantity<Metrics>(100, Metrics.cm); assertThat(q.zoomBy(0.5)).isEqualTo(new Quantity<Metrics>(50, Metrics.cm)); }
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testPopupForRegularKey() { KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); Assert.assertNull(getLatestCreatedPopupWindow()); underTest.showPreviewForKey(mTestKeys[0], "y", mKeyboardView, mTheme); Assert.assertNotNull(...
@Override public JdbcRecordIterator getRecordIterator(Configuration conf, String partitionColumn, String lowerBound, String upperBound, int limit, int offset) throws HiveJdbcDatabaseAccessException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; tr...
@Test(expected = HiveJdbcDatabaseAccessException.class) public void testGetRecordIterator_invalidQuery() throws HiveJdbcDatabaseAccessException { Configuration conf = buildConfiguration(); conf.set(JdbcStorageConfig.QUERY.getPropertyName(), "select * from strategyx"); DatabaseAccessor accessor = DatabaseA...
public List<SpoonPluginInterface> getPlugins() { return Collections.unmodifiableList( Arrays.asList( plugins.values().toArray( new SpoonPluginInterface[] {} ) ) ); }
@Test public void testGetPlugins() throws Exception { spoonPluginManager.pluginAdded( plugin1 ); spoonPluginManager.pluginAdded( plugin2 ); List<SpoonPluginInterface> pluginInterfaces = spoonPluginManager.getPlugins(); assertEquals( 2, pluginInterfaces.size() ); assertTrue( pluginInterfaces ...
public ProviderBuilder threadPool(String threadPool) { this.threadpool = threadPool; return getThis(); }
@Test void threadPool() { ProviderBuilder builder = ProviderBuilder.newBuilder(); builder.threadPool("mockthreadpool"); Assertions.assertEquals("mockthreadpool", builder.build().getThreadpool()); }
public Object execute(ProceedingJoinPoint proceedingJoinPoint, Method method, String fallbackMethodValue, CheckedSupplier<Object> primaryFunction) throws Throwable { String fallbackMethodName = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), fallbackMethodValue); FallbackMethod fallbackMeth...
@Test public void testPrimaryMethodExecutionWithFallbackNotFound() throws Throwable { Method method = this.getClass().getMethod("getName", String.class); final CheckedSupplier<Object> primaryFunction = () -> getName("Name"); final String fallbackMethodValue = "incorrectFallbackMethodName"; ...
public static RuntimeException peel(final Throwable t) { return (RuntimeException) peel(t, null, null, HAZELCAST_EXCEPTION_WRAPPER); }
@Test public void testPeel_whenThrowableIsExecutionExceptionWithNullCause_thenReturnHazelcastException() { ExecutionException exception = new ExecutionException(null); RuntimeException result = ExceptionUtil.peel(exception); assertTrue(result instanceof HazelcastException); assertEq...
@Override public Iterator<IndexEntry> readyIndexesIterator() { readLock.lock(); try { var readyIndexes = new ArrayList<IndexEntry>(); for (IndexEntry entry : indexEntries) { if (entry.getIndexDescriptor().isReady()) { readyIndexes.add(entry...
@Test void readyIndexesIterator() { var indexContainer = new IndexEntryContainer(); var descriptor = new IndexDescriptor(getNameIndexSpec()); descriptor.setReady(true); var nameIndexEntry = new IndexEntryImpl(descriptor); indexContainer.add(nameIndexEntry); var index...
public static IssueChangeContextBuilder issueChangeContextByScanBuilder(Date date) { return newBuilder().withScan().setUserUuid(null).setDate(date); }
@Test public void test_issueChangeContextByScanBuilder() { context = issueChangeContextByScanBuilder(NOW).build(); verifyContext(true, false, null, null, null); }
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { Map<String, List<GeneralContextHandle>> generalContextHandleMap = GeneralContextPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST....
@Test public void testDoExecute() { SelectorData selectorData = mock(SelectorData.class); when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(generalContextPlugin.doExecute(this.exchange, this.chain, selectorData, this.ruleData)).expectSubscription().verifyComplete...
@Override public void draw(int x, int y) { pixels[getIndex(x, y)] = Pixel.BLACK; }
@Test void testDraw() { var frameBuffer = new FrameBuffer(); frameBuffer.draw(0, 0); assertEquals(Pixel.BLACK, frameBuffer.getPixels()[0]); }
@Override public SelArray assignOps(SelOp op, SelType rhs) { if (op == SelOp.ASSIGN) { SelTypeUtil.checkTypeMatch(this.type(), rhs.type()); this.val = ((SelArray) rhs).val; // direct assignment return this; } throw new UnsupportedOperationException( this.type() + " DO NOT support...
@Test public void testAssignOps() { one.assignOps(SelOp.ASSIGN, new SelArray(1, SelTypes.STRING_ARRAY)); assertEquals("STRING_ARRAY: [null]", one.type() + ": " + one); }
public static boolean isInstantiationStrategy(Object extension, String strategy) { InstantiationStrategy annotation = AnnotationUtils.getAnnotation(extension, InstantiationStrategy.class); if (annotation != null) { return strategy.equals(annotation.value()); } return InstantiationStrategy.PER_PROJ...
@Test public void shouldBeProjectInstantiationStrategy() { assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstantiationStrategy.PER_PROJECT)).isTrue(); assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstantiationStrategy.PER_PROJECT)).isTrue(); assertThat(...
public void extractTablesFromSelect(final SelectStatement selectStatement) { if (selectStatement.getCombine().isPresent()) { CombineSegment combineSegment = selectStatement.getCombine().get(); extractTablesFromSelect(combineSegment.getLeft().getSelect()); extractTablesFromSel...
@Test void assertExtractTablesFromSelectProjects() { AggregationProjectionSegment aggregationProjection = new AggregationProjectionSegment(10, 20, AggregationType.SUM, "SUM(t_order.id)"); ColumnSegment columnSegment = new ColumnSegment(133, 136, new IdentifierValue("id")); columnSegment.setO...
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null)...
@Test public void testAlterOffsetsMissingPartitionKey() { MirrorCheckpointConnector connector = new MirrorCheckpointConnector(); Function<Map<String, ?>, Boolean> alterOffsets = partition -> connector.alterOffsets(null, Collections.singletonMap( partition, SOURCE_OFF...
public static Frequency ofMHz(long value) { return new Frequency(value * MHZ); }
@Test public void testofMHz() { Frequency frequency = Frequency.ofMHz(1.0); assertThat(frequency.asKHz(), is(1000.0)); }
@Activate protected void activate() { this.loadConfigs(); log.info("Started"); }
@Test public void badConfig() throws IOException { stageTestResource("badConfig.json"); loader.activate(); assertNull("incorrect configuration", service.component); }
@SuppressWarnings("unchecked") public static <R> R getField(final Object object, final String fieldName) { try { return traverseClassHierarchy( object.getClass(), NoSuchFieldException.class, traversalClass -> { Field field = traversalClass.getDeclaredField(fieldName...
@Test public void getFieldReflectively_getsInheritedFields() { ExampleDescendant example = new ExampleDescendant(); example.setNotOverridden(6); assertThat((int) ReflectionHelpers.getField(example, "notOverridden")).isEqualTo(6); }
public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); ...
@Test @PactVerification("userCreatedMessagePact") public void verifyCreatePersonPact() throws IOException { messageConsumer.consumeStringMessage(new String(this.currentMessage)); }
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { ...
@Test public void compareWithFillValue_oneEmptyListAndSmallFillValue_returnsNegative() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(), Lists.newArrayList(1, 2, 3), 0)) .isLessThan(0); }
@Override public List<PMMLModel> getPMMLModels(PMMLRuntimeContext context) { logger.debug("getPMMLModels {}", context); return PMMLRuntimeHelper.getPMMLModels(context); }
@Test void getPMMLModels() { List<PMMLModel> retrieved = pmmlRuntimeInternal.getPMMLModels(pmmlRuntimeContext); assertThat(retrieved).isNotNull().hasSize(1); PMMLModel pmmlModel = retrieved.get(0); assertThat(pmmlModel.getFileName()).isEqualTo(fileName); assertThat(pmmlModel....