focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static String getNativeDataTypeSimpleName( ValueMetaInterface v ) { try { return v.getType() != ValueMetaInterface.TYPE_BINARY ? v.getNativeDataTypeClass().getSimpleName() : "Binary"; } catch ( KettleValueException e ) { LogChannelInterface log = new LogChannel( v ); log.logDebug( BaseM...
@Test public void getNativeDataTypeSimpleName_InetAddress() { ValueMetaInternetAddress v = new ValueMetaInternetAddress(); assertEquals( "InetAddress", FieldHelper.getNativeDataTypeSimpleName( v ) ); }
@Override public boolean fastPut(K key, V value, long ttl, TimeUnit ttlUnit) { return get(fastPutAsync(key, value, ttl, ttlUnit)); }
@Test public void testRemoveEmptyEvictionTask() throws InterruptedException { Config config = createConfig(); config.setMaxCleanUpDelay(2); config.setMinCleanUpDelay(1); RedissonClient redisson = Redisson.create(config); assertThat(redisson.getKeys().count()).isZero(); ...
@Override public PageResult<RewardActivityDO> getRewardActivityPage(RewardActivityPageReqVO pageReqVO) { return rewardActivityMapper.selectPage(pageReqVO); }
@Test public void testGetRewardActivityPage() { // mock 数据 RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> { // 等会查询到 o.setName("芋艿"); o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()); }); rewardActivityMapper.insert(dbRewardAct...
@SuppressWarnings("unchecked") public QueryMetadataHolder handleStatement( final ServiceContext serviceContext, final Map<String, Object> configOverrides, final Map<String, Object> requestProperties, final PreparedStatement<?> statement, final Optional<Boolean> isInternalRequest, f...
@Test public void shouldRateLimitStreamPullQueries() { when(ksqlEngine.createStreamPullQuery(any(), any(), any(), anyBoolean())) .thenReturn(streamPullQueryMetadata); // When: queryExecutor.handleStatement(serviceContext, ImmutableMap.of(), ImmutableMap.of(), pullQuery, Optional.empty(), ...
public static Set<String> getNotCreatedRootNodesInRestartRuntimeDag( @NotNull Map<String, StepTransition> runtimeDag, @NotNull RestartConfig restartConfig) { Set<String> rootStepIds = runtimeDag.entrySet().stream() .filter(entry -> entry.getValue().getPredecessors().isEmpty()) ...
@Test public void testGetNotCreatedRootNodesInRestartRuntimeDag() { RestartConfig config = RestartConfig.builder().addRestartNode("sample-dag-test-1", 1, "job_3").build(); Set<String> actual = DagHelper.getNotCreatedRootNodesInRestartRuntimeDag(runtimeDag1, config); Assert.assertEquals(Collections...
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnDuplicateKeyR2() { HandlerMaps.forClass(BaseType.class) .withArgTypes(String.class, Integer.class) .withReturnType(Number.class) .put(LeafTypeA.class, handlerR2_1) .put(LeafTypeA.class, handlerR2_2); }
@Override public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, CreateDownloadShareRequest options, final PasswordCallback callback) throws BackgroundException { try { if(log.isDebugEnabled()) { log.debug(String.format("Create download share for %s", file)); ...
@Test public void testShareTopLevelRoom() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), ...
public static UAnnotation create(UTree<?> annotationType, List<UExpression> arguments) { return new AutoValue_UAnnotation(annotationType, ImmutableList.copyOf(arguments)); }
@Test public void serialization() { SerializableTester.reserializeAndAssert( UAnnotation.create( UClassIdent.create("java.lang.SuppressWarnings"), ULiteral.stringLit("cast"))); }
public void reset(final int timeoutMs) { this.lock.lock(); this.timeoutMs = timeoutMs; try { if (this.stopped) { return; } if (this.running) { schedule(); } } finally { this.lock.unlock(); ...
@Test public void testReset() throws Exception { this.timer.start(); assertEquals(50, this.timer.getTimeoutMs()); for (int i = 0; i < 10; i++) { Thread.sleep(80); this.timer.reset(); } assertEquals(10, this.timer.counter.get(), 3); this.timer.r...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testAgilityLap() { final String NEW_PB = "Lap duration: <col=ff0000>1:01</col> (new personal best)."; final String NEW_PB_PRECISE = "Lap duration: <col=ff0000>1:01.20</col> (new personal best)."; // This sets lastBoss ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your Pr...
public static String toString(Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName()); if (e.getMessage() != null) { p.print(": " + e.getMessage()); } p.println(); try { ...
@Test void testExceptionToStringWithMessage() throws Exception { String s = StringUtils.toString("greeting", new RuntimeException("abc")); assertThat(s, containsString("greeting")); assertThat(s, containsString("java.lang.RuntimeException: abc")); }
void setRequestPath(ServletRequest req, final String destinationPath) { if (req instanceof AwsProxyHttpServletRequest) { ((AwsProxyHttpServletRequest) req).getAwsProxyRequest().setPath(dispatchTo); return; } if (req instanceof AwsHttpApiV2ProxyHttpServletRequest) { ...
@Test void setPath_forwardByPath_proxyRequestObjectInPropertyReferencesSameProxyRequest() throws InvalidRequestEventException { AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build(); HttpServletRequest servletRequest = requestReader.readRequest(proxyRequest, null, new Mo...
public static void generateHostCert(File keystore, String password, String host, int validity) throws IOException { // generate the keypair for the host generateSignedCert(keystore, password, validity, host, // alias host); // subject }
@Test public void testIPBasedCert() throws Exception { KeyToolUtils.generateHostCert(keystore, password, "10.1.2.3", validity); }
public LoginResponse login(LoginRequest request) { User user = userRepository.findByIdentificationNumber(request.getIdentificationNumber()).orElseThrow(() ->GenericException.builder() .httpStatus(HttpStatus.NOT_FOUND) .logMessage(this.getClass().getName() + ".login user not found...
@Test void login_successfulLogin() { // Arrange LoginRequest request = new LoginRequest("1234567890", "password"); User user = new User("1234567890", "John", "Doe", "encodedPassword"); String token = "validToken"; when(userRepository.findByIdentificationNumber(request.getIden...
public static void writeAndFlushWithVoidPromise(ChannelOutboundInvoker ctx, ByteBuf msg) { ctx.writeAndFlush(msg, ctx.voidPromise()); }
@Test public void testWriteAndFlushWithVoidPromise() { final ChannelOutboundInvoker ctx = mock(ChannelOutboundInvoker.class); final VoidChannelPromise voidChannelPromise = mock(VoidChannelPromise.class); when(ctx.voidPromise()).thenReturn(voidChannelPromise); final byte[] data = "tes...
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) { // stop in reverse order of start Exception firstException = null; List<Service> services = getServices(); for (int i = numOfServicesStarted - 1; i >= 0; i--) { Service service = services.get(i); if (LOG.isDebugEn...
@Test public void testServiceLifecycleNoChildren() { ServiceManager serviceManager = new ServiceManager("ServiceManager"); serviceManager.init(new Configuration()); serviceManager.start(); serviceManager.stop(); }
void storeEdits(byte[] inputData, long newStartTxn, long newEndTxn, int newLayoutVersion) { if (newStartTxn < 0 || newEndTxn < newStartTxn) { Journal.LOG.error(String.format("Attempted to cache data of length %d " + "with newStartTxn %d and newEndTxn %d", inputData.length, newStartTx...
@Test public void testCacheSingleSegment() throws Exception { storeEdits(1, 20); // Leading part of the segment assertTxnCountAndContents(1, 5, 5); // All of the segment assertTxnCountAndContents(1, 20, 20); // Past the segment assertTxnCountAndContents(1, 40, 20); // Trailing part of ...
@Override public SortedSet<IndexRange> find(DateTime begin, DateTime end) { final DBQuery.Query query = DBQuery.or( DBQuery.and( DBQuery.notExists("start"), // "start" has been used by the old index ranges in MongoDB DBQuery.lessThanEquals(Ind...
@Test @MongoDBFixtures("MongoIndexRangeServiceTest.json") public void testHandleIndexReopeningWhenNotManaged() throws Exception { final DateTime begin = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC); final DateTime end = new DateTime(2016, 1, 15, 0, 0, DateTimeZone.UTC); when(indexSet...
public URL getInterNodeListener( final Function<URL, Integer> portResolver ) { return getInterNodeListener(portResolver, LOGGER); }
@Test public void shouldUseExplicitInterNodeListenerIfSetToIpv6Loopback() { // Given: final URL expected = url("https://[::1]:12345"); final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder() .putAll(MIN_VALID_CONFIGS) .put(ADVERTISED_LISTENER_CONFIG, expect...
@Override public ApplicationAttemptReport getApplicationAttemptReport( ApplicationAttemptId applicationAttemptId) throws YarnException, IOException { TimelineEntity entity = readerClient.getApplicationAttemptEntity( applicationAttemptId, "ALL", null); return TimelineEntityV2Converter.conve...
@Test public void testGetAppAttemptReport() throws IOException, YarnException { final ApplicationId appId = ApplicationId.newInstance(0, 1); final ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); when(spyTimelineReaderClient.getApplicationAttemptEntity(appAttemptId, ...
@Override public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException { ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenTypeCircleAndConfigWithoutPerimeterKeyName_whenOnMsg_thenTrue() throws TbNodeException { // GIVEN var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration(); config.setPerimeterKeyName(null); node.init(ctx, new TbNodeConfiguration(JacksonUtil.val...
@Udf public Long round(@UdfParameter final long val) { return val; }
@Test public void shouldRoundDoubleWithDecimalPlacesNegative() { assertThat(udf.round(-1.0d, 0), is(-1.0d)); assertThat(udf.round(-1.1d, 0), is(-1.0d)); assertThat(udf.round(-1.5d, 0), is(-1.0d)); assertThat(udf.round(-1.75d, 0), is(-2.0d)); assertThat(udf.round(-100.1d, 0), is(-100.0d)); asse...
public ShardingSphereDatabase getDatabase(final String name) { ShardingSpherePreconditions.checkNotEmpty(name, NoDatabaseSelectedException::new); ShardingSphereMetaData metaData = getMetaDataContexts().getMetaData(); ShardingSpherePreconditions.checkState(metaData.containsDatabase(name), () -> n...
@Test void assertGetDatabaseWithNull() { assertThrows(NoDatabaseSelectedException.class, () -> contextManager.getDatabase(null)); }
@Override @InterfaceAudience.Private public Serializer<T> getSerializer(Class<T> c) { return new AvroSerializer(c); }
@Test public void testAcceptHandlingPrimitivesAndArrays() throws Exception { SerializationFactory factory = new SerializationFactory(conf); assertNull(factory.getSerializer(byte[].class)); assertNull(factory.getSerializer(byte.class)); }
public static boolean shouldEnablePushdownForTable(ConnectorSession session, Table table, String path, Optional<Partition> optionalPartition) { if (!isS3SelectPushdownEnabled(session)) { return false; } if (path == null) { return false; } // Hive tab...
@Test public void testShouldNotEnableSelectPushdownWhenDisabledOnSession() { ConnectorSession testSession = initTestingConnectorSession(false); assertFalse(shouldEnablePushdownForTable(testSession, table, "", Optional.empty())); }
public void createView(View view, boolean replace, boolean ifNotExists) { if (ifNotExists) { relationsStorage.putIfAbsent(view.name(), view); } else if (replace) { relationsStorage.put(view.name(), view); } else if (!relationsStorage.putIfAbsent(view.name(), view)) { ...
@Test public void when_createsDuplicateViewsIfReplace_then_succeeds() { // given View view = view(); // when catalog.createView(view, true, false); // then verify(relationsStorage).put(eq(view.name()), isA(View.class)); }
public StepBreakpoint addStepBreakpoint( String workflowId, long version, long instanceId, long runId, String stepId, long stepAttemptId, User user) { final String revisedWorkflowId = getRevisedWorkflowId(workflowId, stepId, true); return withMetricLogError( () ...
@Test public void testAddStepBreakpointForAllWorkflowVersionsInvalid() { when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd); AssertHelper.assertThrows( "invalid step", MaestroBadRequestException.class, "Breakpoint can't be set as stepId [non-exist] is not...
public static boolean equivalent( Expression left, Expression right, Types.StructType struct, boolean caseSensitive) { return Binder.bind(struct, Expressions.rewriteNot(left), caseSensitive) .isEquivalentTo(Binder.bind(struct, Expressions.rewriteNot(right), caseSensitive)); }
@Test public void testInEquivalence() { assertThat( ExpressionUtil.equivalent( Expressions.in("id", 1, 2, 1), Expressions.in("id", 2, 1, 2), STRUCT, true)) .as("Should ignore duplicate longs (in)") .isTrue(); assertThat( ExpressionUtil.equivalent( ...
public void ensureCapacity(@NonNegative long maximumSize) { requireArgument(maximumSize >= 0); int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1); if ((table != null) && (table.length >= maximum)) { return; } table = new long[Math.max(Caffeine.ceilingPowerOfTwo(maximum), 8)]; ...
@Test(dataProvider = "sketch") public void ensureCapacity_negative(FrequencySketch<Integer> sketch) { assertThrows(IllegalArgumentException.class, () -> sketch.ensureCapacity(-1)); }
@Override public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() { Iterable<RedisClusterNode> res = clusterGetNodes(); Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>(); for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator....
@Test public void testClusterGetMasterSlaveMap() { Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap(); assertThat(map).hasSize(3); for (Collection<RedisClusterNode> slaves : map.values()) { assertThat(slaves).hasSize(1); } ...
@GetMapping("/getUserPermissionByToken") public ShenyuAdminResult getUserPermissionByToken(@RequestParam(name = "token") final String token) { PermissionMenuVO permissionMenuVO = permissionService.getPermissionMenu(token); return Optional.ofNullable(permissionMenuVO) .map(item -> She...
@Test public void testGetUserPermissionByToken() { final PermissionMenuVO permissionMenuVO = new PermissionMenuVO( Collections.singletonList(new MenuInfo("id", "name", "url", "component", new Meta("icon", "title"), Collections.emptyList(), 0)), Collect...
static boolean isRemoteSegmentWithinLeaderEpochs(RemoteLogSegmentMetadata segmentMetadata, long logEndOffset, NavigableMap<Integer, Long> leaderEpochs) { long segmentEndOffset = segmentMetadata.endOffset();...
@Test public void testRemoteSegmentWithinLeaderEpochsForOverlappingSegments() { NavigableMap<Integer, Long> leaderEpochCache = new TreeMap<>(); leaderEpochCache.put(7, 51L); leaderEpochCache.put(9, 100L); TreeMap<Integer, Long> segment1Epochs = new TreeMap<>(); segment1Epoch...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PiCounterCellData)) { return false; } PiCounterCellData that = (PiCounterCellData) o; return packets == that.packets && bytes == that...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(PI_COUNTER_DATA_1, SAME_AS_PI_COUNTER_DATA_1) .addEqualityGroup(PI_COUNTER_DATA_2) .testEquals(); }
public Distance avgAltitude() { double avgInFeet = (point1.altitude().inFeet() + point2.altitude().inFeet()) / 2.0; return Distance.ofFeet(avgInFeet); }
@Test public void testAvgAltitude() { Point p1 = Point.builder().altitude(Distance.ofFeet(1000.0)).time(EPOCH).latLong(0.0, 0.0).build(); Point p2 = Point.builder().altitude(Distance.ofFeet(1500.0)).time(EPOCH).latLong(0.0, 0.0).build(); PointPair pair = PointPair.of(p1, p2); asse...
@Override public void acceptPolicy(ApplicationId appId, Set<Permission> permissionSet) { Application app = applicationAdminService.getApplication(appId); if (app == null) { log.warn("Unknown Application"); return; } states.computeIf(appId, Ob...
@Test public void testAcceptPolicy() { assertEquals(SECURED, states.get(appId).getState()); states.compute(appId, (id, securityInfo) -> { switch (securityInfo.getState()) { case POLICY_VIOLATED: return new Securi...
public void notify(PluginJarChangeListener listener, Collection<BundleOrPluginFileDetails> knowPluginFiles, Collection<BundleOrPluginFileDetails> currentPluginFiles) { List<BundleOrPluginFileDetails> oldPlugins = new ArrayList<>(knowPluginFiles); subtract(oldPlugins, currentPluginFiles).forEach(listene...
@Test void shouldNotifyWhenNewPluginIsAdded() { final PluginJarChangeListener listener = mock(PluginJarChangeListener.class); List<BundleOrPluginFileDetails> knownPlugins = Collections.emptyList(); BundleOrPluginFileDetails pluginOne = mock(BundleOrPluginFileDetails.class); BundleOrP...
static KiePMMLNormDiscrete getKiePMMLNormDiscrete(final NormDiscrete normDiscrete) { List<KiePMMLExtension> extensions = getKiePMMLExtensions(normDiscrete.getExtensions()); return new KiePMMLNormDiscrete(normDiscrete.getField(), extensions, ...
@Test void getKiePMMLNormDiscrete() { NormDiscrete toConvert = getRandomNormDiscrete(); KiePMMLNormDiscrete retrieved = KiePMMLNormDiscreteInstanceFactory.getKiePMMLNormDiscrete(toConvert); commonVerifyKiePMMLNormDiscrete(retrieved, toConvert); }
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final ReadOnlyKeyValueStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedKeyValueSt...
@Test public void shouldCloseIterator_fullTableScan() { // Given: when(tableStore.all()).thenReturn(keyValueIterator); when(keyValueIterator.hasNext()).thenReturn(true, true, false); when(keyValueIterator.next()) .thenReturn(KEY_VALUE1) .thenReturn(KEY_VALUE2); // When: Stream...
public FileTime now() { return fileTimeSource.now(); }
@Test public void testNow() { assertThat(state.now()).isEqualTo(fileTimeSource.now()); fileTimeSource.advance(Duration.ofSeconds(1)); assertThat(state.now()).isEqualTo(fileTimeSource.now()); }
@Operation(summary = "saveWorkerGroup", description = "CREATE_WORKER_GROUP_NOTES") @Parameters({ @Parameter(name = "id", description = "WORKER_GROUP_ID", schema = @Schema(implementation = int.class, example = "10", defaultValue = "0")), @Parameter(name = "name", description = "WORKER_GROUP_N...
@Test public void testSaveWorkerGroup() throws Exception { Map<String, String> serverMaps = new HashMap<>(); serverMaps.put("192.168.0.1", "192.168.0.1"); serverMaps.put("192.168.0.2", "192.168.0.2"); Mockito.when(registryClient.getServerMaps(RegistryNodeType.WORKER)).thenReturn(serv...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { return new DeepBoxesListService().list(directory, listener); } if(containerService.isDeepbox(directory)) { // in DeepBox ...
@Test public void testListDeepBoxes() throws Exception { final DeepboxIdProvider nodeid = new DeepboxIdProvider(session); final Path directory = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final AttributedList<Path> list = new DeepboxListService(session, nodeid).list(di...
@Override public void addNewBlockedNodes(Collection<BlockedNode> newNodes) { assertRunningInMainThread(); if (newNodes.isEmpty()) { return; } BlockedNodeAdditionResult result = blocklistTracker.addNewBlockedNodes(newNodes); Collection<BlockedNode> newlyAddedNode...
@Test void testAddNewBlockedNodes() throws Exception { BlockedNode node1 = new BlockedNode("node1", "cause", 1L); BlockedNode node2 = new BlockedNode("node2", "cause", 1L); BlockedNode node2Update = new BlockedNode("node2", "cause", 2L); List<List<BlockedNode>> contextReceivedNodes ...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testChronicleTeleportEmpty() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_TELEPORT_EMPTY, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_CHRONICLE,...
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldHandleErrorMessageOnGetRequests() { // Given: server.setResponseObject(new KsqlErrorMessage(40000, "ouch")); server.setErrorCode(400); // When: KsqlTarget target = ksqlClient.target(serverUri); RestResponse<ServerInfo> response = target.getServerInfo(); // Then: ...
public Set<MethodDescriptor> getAllMethods() { Set<MethodDescriptor> methodModels = new HashSet<>(); methods.forEach((k, v) -> methodModels.addAll(v)); return methodModels; }
@Test void getAllMethods() { Assertions.assertFalse(service.getAllMethods().isEmpty()); }
@Override public void onApplicationEvent(ApplicationStartedEvent event) { schemeManager.schemes().forEach(scheme -> { var factory = new ExtensionRouterFunctionFactory(scheme, client); this.schemeRouterFuncMapper.put(scheme, factory.create()); }); }
@Test void shouldBuildRouterFunctionsOnApplicationStarted() { var applicationStartedEvent = mock(ApplicationStartedEvent.class); extensionRouterFunc.onApplicationEvent(applicationStartedEvent); verify(schemeManager).schemes(); }
public DescribeGroupsResponseData.DescribedGroupMember describe(String protocolName) { return describeNoMetadata().setMemberMetadata(metadata(protocolName)); }
@Test public void testDescribe() { JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestProtocolCollection(Collections.singletonList( new JoinGroupRequestProtocol() .setName("range") .setMetadata(new byte[]{0}) ).iterator()); Classic...
public static int formatFloatFast(float value, int maxFractionDigits, byte[] asciiBuffer) { if (Float.isNaN(value) || Float.isInfinite(value) || value > Long.MAX_VALUE || value <= Long.MIN_VALUE || maxFractionDigits > MAX_FRACTION_DIGITS) ...
@Test void testFormatOfRealValues() { assertEquals(3, NumberFormatUtil.formatFloatFast(0.7f, 5, buffer)); assertArrayEquals(new byte[]{'0', '.', '7'}, Arrays.copyOfRange(buffer, 0, 3)); assertEquals(4, NumberFormatUtil.formatFloatFast(-0.7f, 5, buffer)); assertArrayEquals(new by...
public static NotControllerException newWrongControllerException(OptionalInt controllerId) { if (controllerId.isPresent()) { return new NotControllerException("The active controller appears to be node " + controllerId.getAsInt() + "."); } else { return new Not...
@Test public void testNewWrongControllerExceptionWithActiveController() { assertExceptionsMatch(new NotControllerException("The active controller appears to be node 1."), newWrongControllerException(OptionalInt.of(1))); }
@Override public Set<SystemScope> getUnrestricted() { return Sets.filter(getAll(), Predicates.not(isRestricted)); }
@Test public void getUnrestricted() { Set<SystemScope> unrestricted = Sets.newHashSet(defaultDynScope1, defaultDynScope2, dynScope1); assertThat(service.getUnrestricted(), equalTo(unrestricted)); }
@ConstantFunction(name = "bitShiftLeft", argTypes = {SMALLINT, BIGINT}, returnType = SMALLINT) public static ConstantOperator bitShiftLeftSmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) (first.getSmallint() << second.getBigint())); }
@Test public void bitShiftLeftSmallInt() { assertEquals(80, ScalarOperatorFunctions.bitShiftLeftSmallInt(O_SI_10, O_BI_3).getSmallint()); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Responses schema resolved from return type") public void testResponseReturnType() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(ResponseReturnTypeResource.class); String yaml = "openapi: 3.0.1\n" + "paths:\n" + ...
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<ObjectKeyAndVersion>> map = new HashMap<>(); final List<Path> containers = new ArrayList<>(); for(Path file : files.keySet()) { ...
@Test public void testDeleteVersionedPlaceholder() throws Exception { final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final String name = new AlphanumericRandomStringService().random(); final S3AccessControlListFea...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 0 && "currentTimeMillis".equals(methodName)) { return SelLong.of(DateTimeUtils.currentTimeMillis()); } // no-op to support Arrays.asList if (args.length == 1 && "asList".equals(methodName)) { return args[...
@Test(expected = UnsupportedOperationException.class) public void testCallOtherMethods() { SelMiscFunc.INSTANCE.call("nonExisting", new SelType[0]); }
static String headerLine(CSVFormat csvFormat) { return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader()); }
@Test public void givenNotIgnoreSurroundingSpaces_keepsSpaces() { CSVFormat csvFormat = csvFormat().withIgnoreSurroundingSpaces(false); PCollection<String> input = pipeline.apply( Create.of( headerLine(csvFormat), " a ,1,1.1", "b, 2 ...
@Override public void open() throws Exception { executableStage = ExecutableStage.fromPayload(payload); hasSdfProcessFn = hasSDF(executableStage); initializeUserState(executableStage, getKeyedStateBackend(), pipelineOptions); // TODO: Wire this into the distributed cache and make it pluggable. // ...
@Test @SuppressWarnings("unchecked") public void testEnsureStateCleanupWithKeyedInput() throws Exception { TupleTag<Integer> mainOutput = new TupleTag<>("main-output"); DoFnOperator.MultiOutputOutputManagerFactory<Integer> outputManagerFactory = new DoFnOperator.MultiOutputOutputManagerFactory( ...
@SuppressWarnings("OptionalGetWithoutIsPresent") // Enforced by type @Override public StreamsMaterializedWindowedTable windowed() { if (!windowInfo.isPresent()) { throw new UnsupportedOperationException("Table has non-windowed key"); } final WindowInfo wndInfo = windowInfo.get(); final Window...
@Test public void shouldReturnWindowedForHopping() { // Given: givenWindowType(Optional.of(WindowType.HOPPING)); // When: final StreamsMaterializedWindowedTable table = materialization.windowed(); // Then: assertThat(table, is(instanceOf(KsMaterializedWindowTable.class))); }
protected String readEncodingAndString(int max) throws IOException { byte encoding = readByte(); return readEncodedString(encoding, max - 1); }
@Test public void testReadString() throws IOException { byte[] data = { ID3Reader.ENCODING_ISO, 'T', 'e', 's', 't', 0 // Null-terminated }; CountingInputStream inputStream = new CountingInputStream(new ByteArrayInputStream(data)); String string = n...
@Override public String lock(final Path file) throws BackgroundException { if(!containerService.getContainer(file).getType().contains(Path.Type.shared)) { log.warn(String.format("Skip attempting to lock file %s not in shared folder", file)); throw new UnsupportedException(); ...
@Test(expected = InteroperabilityException.class) public void testLock() throws Exception { final DropboxTouchFeature touch = new DropboxTouchFeature(session); final Path file = touch.touch(new Path(new Path(new DefaultHomeFinderService(session).find(), "Projects", EnumSet.of(Path.Type.directory, Pa...
@Override public void accept(Point newPoint) { updateTimeAndConfirmOrdering(newPoint.time()); List<SearchResult<Point, Object>> pointsWithinRange = mTree.getAllWithinRange( newPoint, DISTANCE_THRESHOLD ); //add after search so the "newPoint" isn't in the po...
@Test public void testUnorderedPoints() { DistanceMetric<Point> metric = new PointDistanceMetric(1.0, 1.0); double DISTANCE_THRESHOLD = 1250.0; TestSink sink = new TestSink(); PointPairFinder pairer = new PointPairFinder(Duration.ofSeconds(13), metric, DISTANCE_THRESHOLD, sink); ...
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testTableWithInvalidVariableName() { fail = true; run( "table table1 =", "| col |", "| foo |" ); }
@Override public boolean encode( @NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options) { GifDrawable drawable = resource.get(); Transformation<Bitmap> transformation = drawable.getFrameTransformation(); boolean isTransformed = !(transformation instanceof UnitTransfor...
@Test public void testEncode_withEncodeTransformationFalse_writesSourceDataToStream() throws IOException { options.set(ReEncodingGifResourceEncoder.ENCODE_TRANSFORMATION, false); String expected = "testString"; byte[] data = expected.getBytes("UTF-8"); when(gifDrawable.getBuffer()).thenReturn(By...
public ScalarOperator rewrite(ScalarOperator origin) { if (origin == null) { return null; } return origin.clone().accept(rewriter, null); }
@Test public void testRecursiveWithChildren() { Map<ColumnRefOperator, ScalarOperator> operatorMap = Maps.newHashMap(); ColumnRefOperator columnRef1 = createColumnRef(1); ColumnRefOperator columnRef2 = createColumnRef(2); ColumnRefOperator columnRef3 = createColumnRef(3); Bi...
@Override @SuppressWarnings("nullness") public List<Map<String, Object>> readTable(String tableName) { LOG.info("Reading all rows from {}.{}", databaseName, tableName); List<Map<String, Object>> result = runSQLQuery(String.format("SELECT * FROM %s", tableName)); LOG.info("Successfully loaded rows from {...
@Test public void testReadTableShouldThrowErrorWhenJDBCFailsToExecuteSQL() throws SQLException { when(container.getHost()).thenReturn(HOST); when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT); Statement statement = driver.getConnection(any(), any(), any()).createStatement(); doThrow(SQLE...
@Override public void trace(String msg) { logger.trace(msg); }
@Test void testMarkerTraceWithException() { Exception exception = new Exception(); jobRunrDashboardLogger.trace(marker, "trace", exception); verify(slfLogger).trace(marker, "trace", exception); }
static void executeRunnable(Observation observation, Runnable runnable) { decorateRunnable(observation, runnable).run(); }
@Test public void shouldExecuteRunnable() throws Throwable { Observations.executeRunnable(observation, helloWorldService::sayHelloWorld); assertThatObservationWasStartedAndFinishedWithoutErrors(); then(helloWorldService).should(times(1)).sayHelloWorld(); }
@Override public Collection<SQLToken> generateSQLTokens(final InsertStatementContext insertStatementContext) { Collection<SQLToken> result = new LinkedList<>(); EncryptTable encryptTable = encryptRule.getEncryptTable(insertStatementContext.getSqlStatement().getTable().getTableName().getIdentifier()....
@Test void assertGenerateSQLTokensNotContainColumns() { EncryptInsertDerivedColumnsTokenGenerator tokenGenerator = new EncryptInsertDerivedColumnsTokenGenerator(mockEncryptRule()); InsertStatementContext insertStatementContext = mock(InsertStatementContext.class, RETURNS_DEEP_STUBS); when(in...
@Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException { final Path copy = proxy.copy(source, target, status.withLength(source.attributes().getSize()), callback, new DisabledStr...
@Test public void testMove() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final String name = new AlphanumericRandomStringService().random(); ...
@Override public Collection<Integer> getOutboundPorts(EndpointQualifier endpointQualifier) { final AdvancedNetworkConfig advancedNetworkConfig = node.getConfig().getAdvancedNetworkConfig(); if (advancedNetworkConfig.isEnabled()) { EndpointConfig endpointConfig = advancedNetworkConfig.get...
@Test public void testGetOutboundPorts_acceptsZero() { networkConfig.addOutboundPortDefinition("0"); Collection<Integer> outboundPorts = serverContext.getOutboundPorts(MEMBER); assertEquals(0, outboundPorts.size()); }
public static RedissonClient create() { Config config = new Config(); config.useSingleServer() .setAddress("redis://127.0.0.1:6379"); return create(config); }
@Test public void testMasterSlaveConnectionFail() { Assertions.assertThrows(RedisConnectionException.class, () -> { Config config = new Config(); config.useMasterSlaveServers() .setMasterAddress("redis://127.99.0.1:1111") .addSlaveAddress("redi...
public static <T> T fillBean(String className, Map<List<String>, Object> params, ClassLoader classLoader) { return fillBean(errorEmptyMessage(), className, params, classLoader); }
@Test(expected = ScenarioException.class) public void fillBeanFailTest() { Map<List<String>, Object> paramsToSet = new HashMap<>(); paramsToSet.put(List.of("fakeField"), null); ScenarioBeanUtil.fillBean(errorEmptyMessage(), Dispute.class.getCanonicalName(), paramsToSet, classLoader); }
@Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { // 1.1 参数校验 if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } ...
@Test public void testImportUserList_04() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setStatus(randomEle(CommonStatusEnum.values()).getStatus...
@Override public void process(Object elem) throws Exception { try (Closeable scope = context.enterProcess()) { checkStarted(); Receiver receiver = receivers[0]; if (receiver != null) { receiver.process(elem); } } }
@Test public void testRunFlattenOperation() throws Exception { TestOutputReceiver receiver = new TestOutputReceiver( counterSet, NameContext.create("test", "receiver", "receiver", "receiver")); OperationContext context = TestOperationContext.create(counterSet, nameContext); FlattenOpe...
public void setCreateTimeMills(Long createTimeMills) { this.createTimeMills = createTimeMills; }
@Test public void testSetCreateTimeMills() { long newCreateTimeMills = System.currentTimeMillis() + 2000; accAndTimeStamp.setCreateTimeMills(newCreateTimeMills); assertEquals("Create time should be set to new value", newCreateTimeMills, accAndTimeStamp.getCreateTimeMills().longValue()); ...
@Override public KStream<K, V> merge(final KStream<K, V> stream) { return merge(stream, NamedInternal.empty()); }
@Test public void shouldNotAllowNullNamedOnMerge() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.merge(testStream, null)); assertThat(exception.getMessage(), equalTo("named can't be null")); }
@Override public List<List<Object>> getInsertRows(Collection<Integer> primaryKeyIndex) { if (ast.getTop() != null) { //deal with top sql dealTop(ast); } List<SQLInsertStatement.ValuesClause> valuesClauses = ast.getValuesList(); List<List<Object>> rows = new Ar...
@Test public void testGetInsertRows() { //test for null value String sql = "insert into t(id, no, name, age, time) values (default, null, 'a', ?, now())"; SQLStatement ast = getSQLStatement(sql); SqlServerInsertRecognizer recognizer = new SqlServerInsertRecognizer(sql, ast); ...
public NodeMgr getNodeMgr() { return nodeMgr; }
@Test public void testReplayUpdateFrontend() throws Exception { GlobalStateMgr globalStateMgr = mockGlobalStateMgr(); List<Frontend> frontends = globalStateMgr.getNodeMgr().getFrontends(null); Frontend fe = frontends.get(0); fe.updateHostAndEditLogPort("testHost", 1000); glob...
public static Pair<Optional<Method>, Optional<TypedExpression>> resolveMethodWithEmptyCollectionArguments( final MethodCallExpr methodExpression, final MvelCompilerContext mvelCompilerContext, final Optional<TypedExpression> scope, List<TypedExpression> arguments, ...
@Test public void resolveMethodWithEmptyCollectionArgumentsCoerceListAndMap() { final MethodCallExpr methodExpression = new MethodCallExpr("setAddressesAndItems", new MapCreationLiteralExpression(null, NodeList.nodeList())); final List<TypedExpression> arguments = new ArrayList<>(); argument...
@Override public DescribeReplicaLogDirsResult describeReplicaLogDirs(Collection<TopicPartitionReplica> replicas, DescribeReplicaLogDirsOptions options) { final Map<TopicPartitionReplica, KafkaFutureImpl<DescribeReplicaLogDirsResult.ReplicaLogDirInfo>> futures = new HashMap<>(replicas.size()); for (...
@Test public void testDescribeReplicaLogDirsWithNonExistReplica() throws Exception { int brokerId = 0; TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic1", 12, brokerId); TopicPartitionReplica tpr2 = new TopicPartitionReplica("topic2", 12, brokerId); try (AdminClientUnitT...
@Override public GroupCoordinatorMetricsShard newMetricsShard(SnapshotRegistry snapshotRegistry, TopicPartition tp) { return new GroupCoordinatorMetricsShard(snapshotRegistry, globalSensors, tp); }
@Test public void testGlobalSensors() { MetricsRegistry registry = new MetricsRegistry(); Time time = new MockTime(); Metrics metrics = new Metrics(time); GroupCoordinatorMetrics coordinatorMetrics = new GroupCoordinatorMetrics(registry, metrics); GroupCoordinatorMetricsShard...
public void processAf01(Af01 af01, Afnemersbericht afnemersbericht){ afnemersberichtRepository.delete(afnemersbericht); logger.info("Finished processing Af01 message"); }
@Test public void testProcessAf01(){ String testBsn = "SSSSSSSSS"; Af01 testAf01 = TestDglMessagesUtil.createTestAf01(testBsn); classUnderTest.processAf01(testAf01, afnemersbericht); verify(afnemersberichtRepository, times(1)).delete(afnemersbericht); }
public static String validateIndexName(@Nullable String indexName) { checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE); return indexName; }
@Test public void validateIndexName_throws_IAE_when_index_name_contains_invalid_characters() { assertThatThrownBy(() -> validateIndexName("(not/valid)")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Index name must be lower case and contain only alphanumeric chars or '_', got '(not/valid...
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test public void shouldFailDropStreamWhenAnInsertQueryIsWritingTheStream() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream bar as select * from test1;" + "insert into bar select * from test1;...
@Override public String getName() { return "AwsCodeBuild"; }
@Test public void getName() { assertThat(underTest.getName()).isEqualTo("AwsCodeBuild"); }
protected static String getReverseZoneNetworkAddress(String baseIp, int range, int index) throws UnknownHostException { if (index < 0) { throw new IllegalArgumentException( String.format("Invalid index provided, must be positive: %d", index)); } if (range < 0) { throw new Illegal...
@Test public void testVariousRangeAndIndexValues() throws Exception { // Given the base address of 172.17.4.0, step 256 IP addresses, 5 times. assertEquals("172.17.9.0", ReverseZoneUtils.getReverseZoneNetworkAddress(NET, 256, 5)); assertEquals("172.17.4.128", ReverseZoneUtils.getReverseZon...
public Optional<Details> updateRuntimeOverview( WorkflowSummary summary, WorkflowRuntimeOverview overview, Timeline timeline) { return updateWorkflowInstance(summary, overview, timeline, null, 0); }
@Test public void testUpdateRuntimeOverview() { WorkflowSummary summary = new WorkflowSummary(); summary.setWorkflowId(wfi.getWorkflowId()); summary.setWorkflowInstanceId(wfi.getWorkflowInstanceId()); summary.setWorkflowRunId(wfi.getWorkflowRunId()); instanceDao.executeWorkflowInstance(summary, "t...
public String nextNonCliCommand() { String line; do { line = terminal.readLine(); } while (maybeHandleCliSpecificCommands(line)); return line; }
@Test public void shouldSupportCmdBeingTerminatedWithSemiColon() { // Given: when(lineSupplier.get()) .thenReturn(CLI_CMD_NAME + WHITE_SPACE + "Arg0;") .thenReturn("not a CLI command;"); // When: console.nextNonCliCommand(); // Then: verify(cliCommand).execute(eq(ImmutableLis...
public ProvisionResponse aggregate(ProvisionResponse other) { if (_status == ProvisionStatus.UNDER_PROVISIONED) { if (other.status() == ProvisionStatus.UNDER_PROVISIONED) { aggregateRecommendations(other); } } else { switch (other.status()) { case UNDER_PROVISIONED: _...
@Test public void testAggregate() { // Verify validity of input while creating a ProvisionResponse using an invalid recommender and recommendation. assertThrows(IllegalArgumentException.class, () -> new ProvisionResponse(ProvisionStatus.RIGHT_SIZED, OVER_PROV_REC, RECOMMENDER_UP)); assertThrows(IllegalArg...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void getChatMenuButton() { MenuButton menu = new MenuButtonCommands(); BaseResponse set = bot.execute(new SetChatMenuButton().chatId(chatId) .menuButton(menu)); assertTrue(set.isOk()); GetChatMenuButtonResponse response = bot.execute(new GetChatMenuButto...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateTypeForCreateMapExpression() { // Given: Expression expression = new CreateMapExpression( ImmutableMap.of( COL3, new UnqualifiedColumnReferenceExp(COL0) ) ); // When: final SqlType type = expressionTypeManager.getExpressionSqlType(expres...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { if (1 == queryResults.size() && !isNeedAggregateRewri...
@Test void assertBuildGroupByStreamMergedResultWithMySQLLimit() throws SQLException { final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_ST...
public ReplicatedMapIterationService getIterationService() { return iterationService; }
@Test public void testCleanups_StaleIterators() { String name = randomMapName(); for (int i = 0; i < 10000; i++) { hazelcastInstance.getReplicatedMap(name).put(i, i); } ReplicatedMapService service = getNodeEngineImpl(hazelcastInstance).getService(ReplicatedMapService.SER...
@Override public Optional<String> getUrlPathToJs() { return Optional.ofNullable(analytics) .map(WebAnalytics::getUrlPathToJs) .filter(path -> !path.startsWith("/") && !path.contains("..") && !path.contains("://")) .map(path -> "/" + path); }
@Test public void return_empty_if_path_is_an_url() { WebAnalytics analytics = newWebAnalytics("http://foo"); WebAnalyticsLoaderImpl underTest = new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics}); assertThat(underTest.getUrlPathToJs()).isEmpty(); }
public static Dish createDish(Recipe recipe) { Map<Product, BigDecimal> calculatedRecipeToGram = new HashMap<>(); recipe.getIngredientsProportion().forEach(((product, proportion) -> { calculatedRecipeToGram.put(product, recipe.getBasePortionInGrams() .multiply(proportion....
@Test void calculateNutrients_positiveValue() { Dish dish = Dish.createDish(recipe, BigDecimal.valueOf(1300)); assertAll("Should double the values", () -> assertEquals(new BigDecimal("1300"), dish.getNutrients().getCalories().getTotalCalories()), () -> assertEquals(n...
@Override public X process(T input, Context context) throws Exception { if (!this.initialized) { initialize(context); } // record must be PulsarFunctionRecord. Record<T> record = (Record<T>) context.getCurrentRecord(); // windows function processing semantics re...
@Test public void testPrepareLateTupleStreamWithoutTs() throws Exception { context = mock(Context.class); doReturn("test-function").when(context).getFunctionName(); doReturn("test-namespace").when(context).getNamespace(); doReturn("test-tenant").when(context).getTenant(); doR...
@Override public Partition getPartition(String dbName, String tblName, List<String> partitionValues) { StorageDescriptor sd; Map<String, String> params; if (partitionValues.size() > 0) { org.apache.hadoop.hive.metastore.api.Partition partition = client.getPart...
@Test public void testGetPartition() { HiveMetaClient client = new MockedHiveMetaClient(); HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS); com.starrocks.connector.hive.Partition partition = metastore.getPartition("db1", "tbl1", Lists.newArrayList("par1...
@Override public GetApplicationAttemptsResponse getApplicationAttempts( GetApplicationAttemptsRequest request) throws YarnException, IOException { GetApplicationAttemptsResponse response = GetApplicationAttemptsResponse .newInstance(new ArrayList<ApplicationAttemptReport>(history ...
@Test void testApplicationAttempts() throws IOException, YarnException { ApplicationId appId = ApplicationId.newInstance(0, 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ApplicationAttemptId appAttemptId1 = ApplicationAttemptId.newInstance(appId, 2); ...
@Subscribe public void onPostMenuSort(PostMenuSort postMenuSort) { // The menu is not rebuilt when it is open, so don't swap or else it will // repeatedly swap entries if (client.isMenuOpen()) { return; } MenuEntry[] menuEntries = client.getMenuEntries(); // Build option map for quick lookup in fin...
@Test public void testContains() { when(config.swapPay()).thenReturn(true); entries = new MenuEntry[]{ menu("Cancel", "", MenuAction.CANCEL), menu("Examine", "Kragen", MenuAction.EXAMINE_NPC), menu("Walk here", "", MenuAction.WALK), menu("Pay (south)", "Kragen", MenuAction.NPC_FOURTH_OPTION), men...
public static ThreadPoolExecutor newFixedThreadPool(int corePoolSize) { return new ThreadPoolExecutor(corePoolSize, corePoolSize, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>()); }
@Test public void newFixedThreadPool2() throws Exception { BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>(); ThreadFactory factory = new NamedThreadFactory("xxx"); ThreadPoolExecutor executor = ThreadPoolUtils.newFixedThreadPool(10, queue, factory); Assert.assertEqual...
private RemotingCommand getUser(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); GetUserRequestHeader requestHeader = request.decodeCommandCustomHeader(GetUserRequestHeader.class);...
@Test public void testGetUser() throws RemotingCommandException { when(authenticationMetadataManager.getUser(eq("abc"))).thenReturn(CompletableFuture.completedFuture(User.of("abc", "123", UserType.NORMAL))); GetUserRequestHeader getUserRequestHeader = new GetUserRequestHeader(); getUserRequ...