focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String formatMailTemplateContent(String content, Map<String, Object> params) { return StrUtil.format(content, params); }
@Test public void testFormatMailTemplateContent() { // 准备参数 Map<String, Object> params = new HashMap<>(); params.put("name", "小红"); params.put("what", "饭"); // 调用,并断言 assertEquals("小红,你好,饭吃了吗?", mailTemplateService.formatMailTemplateContent("{name},你好...
public Binder(Pattern pattern, GroupExpression groupExpression) { this.pattern = pattern; this.groupExpression = groupExpression; this.groupExpressionIndex = Lists.newArrayList(0); // MULTI_JOIN is a special pattern which can contain children groups if the input group expression ...
@Test public void testBinder() { OlapTable table1 = new OlapTable(); table1.setDefaultDistributionInfo(new HashDistributionInfo()); OlapTable table2 = new OlapTable(); table2.setDefaultDistributionInfo(new HashDistributionInfo()); OptExpression expr = OptExpression.create(new...
public void updateColdDataFlowCtrGroupConfig(final String addr, final Properties properties, final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException, UnsupportedEncodingException { RemotingCommand request ...
@Test public void testUpdateColdDataFlowCtrGroupConfig() throws RemotingException, InterruptedException, MQBrokerException, UnsupportedEncodingException { mockInvokeSync(); Properties props = new Properties(); mqClientAPI.updateColdDataFlowCtrGroupConfig(defaultBrokerAddr, props, defaultTime...
@Override public synchronized void blameResult(InputFile file, List<BlameLine> lines) { checkNotNull(file); checkNotNull(lines); checkArgument(allFilesToBlame.contains(file), "It was not expected to blame file %s", file); if (lines.size() != file.lines()) { LOG.debug("Ignoring blame result sinc...
@Test public void shouldFailIfNullRevision() { InputFile file = new TestInputFileBuilder("foo", "src/main/java/Foo.java").setLines(1).build(); var blameOUtput = new DefaultBlameOutput(null, analysisWarnings, singletonList(file), mock(DocumentationLinkGenerator.class)); var lines = singletonList(new BlameL...
@Override public void publish(ScannerReportWriter writer) { AbstractProjectOrModule rootProject = moduleHierarchy.root(); ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder() .setAnalysisDate(projectInfo.getAnalysisDate().getTime()) // Here we want key without branch ...
@Test @UseDataProvider("buildStrings") public void write_buildString(@Nullable String buildString, String expected) { when(projectInfo.getBuildString()).thenReturn(Optional.ofNullable(buildString)); underTest.publish(writer); ScannerReport.Metadata metadata = reader.readMetadata(); assertThat(meta...
@Override public int addFirst(V... elements) { return get(addFirstAsync(elements)); }
@Test public void testRemoveFirst() { RDeque<Integer> queue1 = redisson.getDeque("deque1"); queue1.addFirst(1); queue1.addFirst(2); queue1.addFirst(3); Assertions.assertEquals(3, (int)queue1.removeFirst()); Assertions.assertEquals(2, (int)queue1.removeFirst()); ...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseLaterVariadicWhenTwoVariadicsMatchDiffBranches() { // Given: givenFunctions( function(OTHER, 1, GenericType.of("A"), INT_VARARGS, STRING, DOUBLE), function(EXPECTED, 2, GenericType.of("B"), INT, STRING_VARARGS, DOUBLE) ); // When: final KsqlSc...
public final void containsEntry(@Nullable Object key, @Nullable Object value) { // TODO(kak): Can we share any of this logic w/ MapSubject.containsEntry()? checkNotNull(actual); if (!actual.containsEntry(key, value)) { Map.Entry<@Nullable Object, @Nullable Object> entry = immutableEntry(key, value); ...
@Test public void containsEntryWithNullValueNullExpected() { ListMultimap<String, String> actual = ArrayListMultimap.create(); actual.put("a", null); assertThat(actual).containsEntry("a", null); }
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs1Des3EncryptedRsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") ...
public static L3ModificationInstruction copyTtlIn() { return new ModTtlInstruction(L3SubType.TTL_IN); }
@Test public void testCopyTtlInMethod() { final Instruction instruction = Instructions.copyTtlIn(); final L3ModificationInstruction.ModTtlInstruction modTtlInstruction = checkAndConvert(instruction, Instruction.Type.L3MODIFICATION, ...
public static <K, V> Reshuffle<K, V> of() { return new Reshuffle<>(); }
@Test @Category({ValidatesRunner.class}) public void testAssignShardFn() { List<KV<String, Integer>> inputKvs = Lists.newArrayList(); for (int i = 0; i < 10; i++) { inputKvs.addAll(ARBITRARY_KVS); } PCollection<KV<String, Integer>> input = pipeline.apply( Create.of(inputKv...
public static String name(String name, String... names) { final StringBuilder builder = new StringBuilder(); append(builder, name); if (names != null) { for (String s : names) { append(builder, s); } } return builder.toString(); }
@Test public void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { assertThat(name("one", null, "three")) .isEqualTo("one.three"); }
void updateInactivityStateIfExpired(long ts, DeviceId deviceId, DeviceStateData stateData) { log.trace("Processing state {} for device {}", stateData, deviceId); if (stateData != null) { DeviceState state = stateData.getState(); if (!isActive(ts, state) && (st...
@Test public void givenStateDataIsNull_whenUpdateInactivityTimeoutIfExpired_thenShouldCleanupDevice() { // GIVEN service.deviceStates.put(deviceId, deviceStateDataMock); // WHEN service.updateInactivityStateIfExpired(System.currentTimeMillis(), deviceId, null); // THEN ...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsExactly_primitiveFloatArray_inOrder_success() { assertThat(array(1.1f, TOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .containsExactly(array(1.1f, 2.2f, 3.3f)) .inOrder(); }
@Override public Integer doCall() throws Exception { JsonObject pluginConfig = loadConfig(); JsonObject plugins = pluginConfig.getMap("plugins"); Optional<PluginType> camelPlugin = PluginType.findByName(name); if (camelPlugin.isPresent()) { if (command == null) { ...
@Test public void shouldAddDefaultPlugin() throws Exception { PluginAdd command = new PluginAdd(new CamelJBangMain().withPrinter(printer)); command.name = "camel-k"; command.doCall(); Assertions.assertEquals("", printer.getOutput()); Assertions.assertEquals( ...
@Override public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) throws InterpreterException { return innerIntp.completion(buf, cursor, interpreterContext); ...
@Test void testCompletion() throws InterpreterException { InterpreterContext context = getInterpreterContext(); InterpreterResult result = interpreter.interpret("val a=\"hello world\"", context); assertEquals(InterpreterResult.Code.SUCCESS, result.code()); List<InterpreterCompletion> completions = in...
public static <K, V> MapCoder<K, V> of(Coder<K> keyCoder, Coder<V> valueCoder) { return new MapCoder<>(keyCoder, valueCoder); }
@Test public void testStructuralValueDecodeEncodeEqual() throws Exception { MapCoder<byte[], Integer> coder = MapCoder.of(ByteArrayCoder.of(), VarIntCoder.of()); Map<byte[], Integer> value = Collections.singletonMap(new byte[] {1, 2, 3, 4}, 1); CoderProperties.structuralValueDecodeEncodeEqual(coder, value...
static void verifyAddMissingValues(final List<KiePMMLMiningField> notTargetMiningFields, final PMMLRequestData requestData) { logger.debug("verifyMissingValues {} {}", notTargetMiningFields, requestData); Collection<ParameterInfo> requestParams = requestData.getReq...
@Test void verifyAddMissingValuesNotMissingNotReturnInvalidNotReplacement() { List<KiePMMLMiningField> miningFields = IntStream.range(0, 3).mapToObj(i -> { DATA_TYPE dataType = DATA_TYPE.values()[i]; return KiePMMLMiningField.builder("FIELD-" + i, null) .withDataT...
@Override public Long getValue() { return Arrays.stream(watermarkGauges).mapToLong(WatermarkGauge::getValue).min().orElse(0); }
@Test void testSetCurrentLowWatermark() { WatermarkGauge metric1 = new WatermarkGauge(); WatermarkGauge metric2 = new WatermarkGauge(); MinWatermarkGauge metric = new MinWatermarkGauge(metric1, metric2); assertThat(metric.getValue()).isEqualTo(Long.MIN_VALUE); metric1.setCu...
@Override public void commit() throws SQLException { for (TransactionHook each : transactionHooks) { each.beforeCommit(connection.getCachedConnections().values(), getTransactionContext(), ProxyContext.getInstance().getContextManager().getComputeNodeInstanceContext().getLockContext()); } ...
@Test void assertCommitWithoutTransaction() throws SQLException { ContextManager contextManager = mockContextManager(TransactionType.LOCAL); when(ProxyContext.getInstance().getContextManager()).thenReturn(contextManager); newBackendTransactionManager(TransactionType.LOCAL, false); ba...
@Override public WindowStoreIterator<V> backwardFetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { Objects.requireNonNull(key, "key can't be null"); final L...
@Test public void emptyBackwardIteratorPeekNextKeyShouldThrowNoSuchElementException() { final StateStoreProvider storeProvider = mock(StateStoreProvider.class); when(storeProvider.stores(anyString(), any())).thenReturn(emptyList()); final CompositeReadOnlyWindowStore<Object, Object> store =...
public void forceDrain() { appendLock.lock(); try { drainStatus = DrainStatus.STARTED; maybeCompleteDrain(); } finally { appendLock.unlock(); } }
@Test public void testForceDrain() { int leaderEpoch = 17; long baseOffset = 157; int lingerMs = 50; int maxBatchSize = 512; Mockito.when(memoryPool.tryAllocate(maxBatchSize)) .thenReturn(ByteBuffer.allocate(maxBatchSize)); BatchAccumulator<String> acc =...
@Override public void acquirePermissionToRemove(OrchestratorContext context, ApplicationApi applicationApi) throws HostStateChangeDeniedException { ApplicationInstanceStatus applicationStatus = applicationApi.getApplicationStatus(); if (applicationStatus == ApplicationInstanceStatus.ALLO...
@Test public void testAcquirePermissionToRemoveConfigServer() throws OrchestrationException { final HostedVespaClusterPolicy clusterPolicy = mock(HostedVespaClusterPolicy.class); final HostedVespaPolicy policy = new HostedVespaPolicy(clusterPolicy, clientFactory, applicationApiFactory, flagSource); ...
@Override public int intValue() { return (int) lvVal(); }
@Test public void testIntValue() { PaddedAtomicLong counter = new PaddedAtomicLong(10); assertEquals(10, counter.intValue()); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> objects = new AttributedList<>(); Marker marker = new Marker(null, null); final String containerId = fileid....
@Test public void testListRevisions() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(new Path( String.format("test-%s", new AsciiRandomStringService().random()), EnumSet.of(Path...
public static void cleanUpTokenReferral(Configuration conf) { conf.unset(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY); }
@Test public void testCleanUpTokenReferral() throws Exception { Configuration conf = new Configuration(); conf.set(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY, "foo"); TokenCache.cleanUpTokenReferral(conf); assertNull(conf.get(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY)); }
@Override public String getMethod() { return PATH; }
@Test public void testAnswerWebAppQueryWithInvalidResult() { AnswerWebAppQuery answerWebAppQuery = AnswerWebAppQuery .builder() .webAppQueryId("123456789") .queryResult(InlineQueryResultArticle .builder() .id("")...
@Override public Class<? extends StorageBuilder> builder() { return SumPerMinLabeledStorageBuilder.class; }
@Test public void testBuilder() throws IllegalAccessException, InstantiationException { function.accept(MeterEntity.newService("sum_sync_time", Layer.GENERAL), table1); function.calculate(); StorageBuilder<SumPerMinLabeledFunction> storageBuilder = function.builder().newInstance(); ...
@Override public Optional<OffsetExpirationCondition> offsetExpirationCondition() { return Optional.of(new OffsetExpirationConditionImpl(offsetAndMetadata -> offsetAndMetadata.commitTimestampMs)); }
@Test public void testOffsetExpirationCondition() { long currentTimestamp = 30000L; long commitTimestamp = 20000L; long offsetsRetentionMs = 10000L; OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(15000L, OptionalInt.empty(), "", commitTimestamp, OptionalLong.empty()); ...
public Coin parse(String str) throws NumberFormatException { return Coin.valueOf(parseValue(str, Coin.SMALLEST_UNIT_EXPONENT)); }
@Test(expected = NumberFormatException.class) public void parseInvalidHugeNegativeNumber() { NO_CODE.parse("-99999999999999999999"); }
@Override public BeamSqlTable buildBeamSqlTable(Table table) { Schema schema = table.getSchema(); ObjectNode properties = table.getProperties(); Optional<ParsedLocation> parsedLocation = Optional.empty(); if (!Strings.isNullOrEmpty(table.getLocation())) { parsedLocation = Optional.of(parseLocat...
@Test public void testBuildBeamSqlProtoTable() { Table table = mockProtoTable("hello", PayloadMessages.SimpleMessage.class); BeamSqlTable sqlTable = provider.buildBeamSqlTable(table); assertNotNull(sqlTable); assertTrue(sqlTable instanceof BeamKafkaTable); BeamKafkaTable kafkaTable = (BeamKafkaT...
@Override public JobStatus getState() { return jobStatus; }
@Test void initialState() { final JobStatusStore store = new JobStatusStore(0); assertThat(store.getState(), is(JobStatus.INITIALIZING)); }
public static Map<PCollection<?>, ReplacementOutput> singleton( Map<TupleTag<?>, PCollection<?>> original, POutput replacement) { Entry<TupleTag<?>, PCollection<?>> originalElement = Iterables.getOnlyElement(original.entrySet()); Entry<TupleTag<?>, PCollection<?>> replacementElement = Iter...
@Test public void singletonSucceeds() { Map<PCollection<?>, ReplacementOutput> replacements = ReplacementOutputs.singleton(PValues.expandValue(ints), replacementInts); assertThat(replacements, Matchers.hasKey(replacementInts)); ReplacementOutput replacement = replacements.get(replacementInts); ...
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@Test public void shouldNotAllowNullValueJoinerWithKeyOnLeftJoinWithGlobalTable() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin(testGlobalTable, MockMapper.selectValueMapper(), (ValueJoinerWithKey<? super String, ? super ...
public static String getJobOffsetPath(final String jobId) { return String.join("/", getJobRootPath(jobId), "offset"); }
@Test void assertGetJobOffsetPath() { assertThat(PipelineMetaDataNode.getJobOffsetPath(jobId), is(jobRootPath + "/offset")); }
public UiTopoLayout scale(double scale) { checkArgument(scaleWithinBounds(scale), E_SCALE_OOB); this.scale = scale; return this; }
@Test public void setScale() { mkRootLayout(); layout.scale(3.0); assertEquals("wrong scale", 3.0, layout.scale(), DELTA); layout.scale(0.05); assertEquals("wrong scale", 0.05, layout.scale(), DELTA); }
@Override public OUT nextRecord(OUT record) throws IOException { OUT returnRecord = null; do { returnRecord = super.nextRecord(record); } while (returnRecord == null && !reachedEnd()); return returnRecord; }
@Disabled("Test disabled because we do not support double-quote escaped quotes right now.") @Test void testParserCorrectness() throws Exception { // RFC 4180 Compliance Test content // Taken from http://en.wikipedia.org/wiki/Comma-separated_values#Example final String fileContent = ...
@Override public Result reconcile(Request request) { client.fetch(Theme.class, request.name()) .ifPresent(theme -> { if (isDeleted(theme)) { cleanUpResourcesAndRemoveFinalizer(request.name()); return; } addFi...
@Test void reconcileDelete() throws IOException { Path testWorkDir = tempDirectory.resolve("reconcile-delete"); Files.createDirectory(testWorkDir); when(themeRoot.get()).thenReturn(testWorkDir); Theme theme = new Theme(); Metadata metadata = new Metadata(); metadata....
@Override public LocalAddress localAddress() { return (LocalAddress) super.localAddress(); }
@Test public void testLocalAddressReuse() throws Exception { for (int i = 0; i < 2; i ++) { Bootstrap cb = new Bootstrap(); ServerBootstrap sb = new ServerBootstrap(); cb.group(group1) .channel(LocalChannel.class) .handler(new TestHandler()); ...
@Override public void enableAutoTrackFragments(List<Class<?>> fragmentsList) { }
@Test public void enableAutoTrackFragments() { ArrayList<Class<?>> fragments = new ArrayList<>(); fragments.add(Fragment.class); fragments.add(DialogFragment.class); mSensorsAPI.enableAutoTrackFragments(fragments); Assert.assertFalse(mSensorsAPI.isFragmentAutoTrackAppViewScre...
public MapStoreConfig setWriteCoalescing(boolean writeCoalescing) { this.writeCoalescing = writeCoalescing; return this; }
@Test public void setWriteCoalescing() { MapStoreConfig cfg = new MapStoreConfig(); cfg.setWriteCoalescing(false); assertFalse(cfg.isWriteCoalescing()); MapStoreConfig otherCfg = new MapStoreConfig(); otherCfg.setWriteCoalescing(false); assertEquals(otherCfg, cfg); ...
@ApiOperation("删除功能按钮资源") @DeleteMapping("/{actionId}") public ApiResult del(@PathVariable Long actionId){ baseActionService.delAction(actionId); return ApiResult.success(); }
@Test void del() { }
@VisibleForTesting public HashMap<String, File> getPluginsToLoad(String pluginsDirectories, String pluginsInclude) throws IllegalArgumentException { String[] directories = pluginsDirectories.split(";"); LOGGER.info("Plugin directories env: {}, parsed directories to load: '{}'", pluginsDirectories, direc...
@Test public void testGetPluginsToLoad() throws IOException { /* We have two plugin directories (../plugins/d1/ and ../plugins/d2/) * plugins to include = [ p1, p2, p3 ] * d1 has plugins: p1 * d2 has plugins: p1, p2, p3, p4 * We expect d1/p1, d2/p2, d2/p3 to be picked up * - ensur...
public static Schema create(Type type) { switch (type) { case STRING: return new StringSchema(); case BYTES: return new BytesSchema(); case INT: return new IntSchema(); case LONG: return new LongSchema(); case FLOAT: return new FloatSchema(); case DOUBLE: ...
@Test void longAsFloatDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.FLOAT), "doc", 1L); assertTrue(field.hasDefaultValue()); assertEquals(1.0f, field.defaultVal()); assertEquals(1.0f, GenericData.get().getDefaultValue(field)); }
@Description("Inverse of Laplace cdf given mean, scale parameters and probability") @ScalarFunction @SqlType(StandardTypes.DOUBLE) public static double inverseLaplaceCdf( @SqlType(StandardTypes.DOUBLE) double mean, @SqlType(StandardTypes.DOUBLE) double scale, @SqlType(Sta...
@Test public void testInverseLaplaceCdf() { assertFunction("inverse_laplace_cdf(5, 1, 0.5)", DOUBLE, 5.0); assertFunction("inverse_laplace_cdf(5, 2, 0.5)", DOUBLE, 5.0); assertFunction("round(inverse_laplace_cdf(5, 2, 0.6), 4)", DOUBLE, 5.0 + 0.4463); assertFunction("round(invers...
@Override public URI getUri() { return myUri; }
@Test public void testURI() { URI uri = fSys.getUri(); Assert.assertEquals(chrootedTo.toUri(), uri); }
public static KiePMMLRegressionModel getKiePMMLRegressionModelClasses(final RegressionCompilationDTO compilationDTO) throws IOException, IllegalAccessException, InstantiationException { logger.trace("getKiePMMLRegressionModelClasses {} {}", compilationDTO.getFields(), compilationDTO.getModel()); Map<Str...
@Test void getKiePMMLRegressionModelClasses() throws IOException, IllegalAccessException, InstantiationException { final CompilationDTO<RegressionModel> compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME, ...
public List<String> getWordList() { return wordList; }
@Test public void testGetWordList() { List<String> wordList = mc.getWordList(); assertEquals(2048, wordList.size()); assertEquals("abandon", wordList.get(0)); assertEquals("zoo", wordList.get(2047)); }
public static boolean isPositiveInteger( String strNum ) { boolean result = true; if ( strNum == null ) { result = false; } else { try { int value = Integer.parseInt( strNum.trim() ); if ( value <= 0 ) { result = false; } } catch ( NumberFormatException nf...
@Test public void test_isPositiveNumber_ForPositiveIntegers() { for ( String value : posInt) { assertTrue( JobEntryPing.isPositiveInteger( value ) ); } }
public static String getSystemProperty(final String key, final String defaultValue) { return System.getProperty(key, defaultValue); }
@Test void assertGetDefaultValue() { assertThat(SystemPropertyUtils.getSystemProperty("key0", "value0"), is("value0")); }
public void isInstanceOf(Class<?> clazz) { if (clazz == null) { throw new NullPointerException("clazz"); } if (actual == null) { failWithActual("expected instance of", clazz.getName()); return; } if (!isInstanceOfType(actual, clazz)) { if (Platform.classMetadataUnsupported())...
@Test public void isInstanceOfClassForNull() { expectFailure.whenTesting().that((Object) null).isInstanceOf(Long.class); assertFailureKeys("expected instance of", "but was"); assertFailureValue("expected instance of", "java.lang.Long"); }
@Override public Iterable<Device> getDevices() { return Collections.unmodifiableCollection(devices.values()); }
@Test public final void testGetDevices() { assertEquals("initialy empty", 0, Iterables.size(deviceStore.getDevices())); putDevice(DID1, SW1); putDevice(DID2, SW2); putDevice(DID1, SW1); assertEquals("expect 2 uniq devices", 2, Iterables.size(deviceStore.getD...
@Override public boolean skip(final ServerWebExchange exchange) { return skipExcept(exchange, RpcTypeEnum.WEB_SOCKET); }
@Test public void skip() { initMockInfo(); assertTrue(webSocketPlugin.skip(exchange)); }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComProcessKillPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_PROCESS_KILL, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
static DiscoveryResponse parseJsonResponse(JsonValue jsonValue, boolean tpcEnabled) throws IOException { List<JsonValue> response = jsonValue.asArray().values(); Map<Address, Address> privateToPublic = new HashMap<>(); List<Address> memberAddresses = new ArrayList<>(response.size()); f...
@Test public void testJsonResponseParse_withTpc_whenTpcIsDisabled() throws IOException { JsonValue jsonResponse = Json.parse(""" [ { "private-address": "10.96.5.1:30000", "public-address": "100.113.44.139:31115", "...
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { ...
@Test public void testNotEqual2() { String query = "b <> 30"; List<String> list = parser.toPrefix(query); assertEquals(Arrays.asList("b", "30", "<>"), list); }
@Override public boolean isResourceEvictable(String key, FileStatus file) { synchronized (initialAppsLock) { if (initialApps.size() > 0) { return false; } } long staleTime = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(this.stalenessMinutes); long acc...
@Test void testEvictableWithInitialApps() throws Exception { startStoreWithApps(); assertFalse(store.isResourceEvictable("key", mock(FileStatus.class))); }
@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 testSetupPopupLayoutForKeyLabel() { KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); underTest.showPreviewForKey(mTestKeys[0], mTestKeys[0].label, mKeyboardView, mTheme); final PopupWindow window = getLatestCreatedPopupWindo...
public synchronized NumaResourceAllocation allocateNumaNodes( Container container) throws ResourceHandlerException { NumaResourceAllocation allocation = allocate(container.getContainerId(), container.getResource()); if (allocation != null) { try { // Update state store. conte...
@Test public void testAllocateNumaNodeWithMultipleNodesForMemory() throws Exception { NumaResourceAllocation nodeInfo = numaResourceAllocator .allocateNumaNodes(getContainer( ContainerId.fromString("container_1481156246874_0001_01_000001"), Resource.newInstance(102400, 2))); ...
@Override public String toString() { return getClass().getSimpleName(); }
@Test public void testRoadClassInfo() { GraphHopper gh = new GraphHopper() { @Override protected File _getOSMFile() { return new File(getClass().getResource(file2).getFile()); } }.setOSMFile("dummy"). setEncodedValuesString("car_acc...
@Override public boolean registerApplication(ApplicationId appId) { Application app = applicationAdminService.getApplication(appId); if (app == null) { log.warn("Unknown application."); return false; } localAppBundleDirectory.put(appId, getBundleLocations(app)...
@Test public void testRegisterApplication() { states.remove(appId); assertNull(states.get(appId)); for (String location : localAppBundleDirectory.get(appId)) { if (!localBundleAppDirectory.containsKey(location)) { localBundleAppDirectory.put(location, new HashSet...
@Override public void resumeAutoTrackActivity(Class<?> activity) { }
@Test public void resumeAutoTrackActivity() { mSensorsAPI.ignoreAutoTrackActivity(EmptyActivity.class); mSensorsAPI.resumeAutoTrackActivity(EmptyActivity.class); Assert.assertTrue(mSensorsAPI.isActivityAutoTrackAppClickIgnored(EmptyActivity.class)); }
@Override public Collection<? extends Backend> get() { ClassLoader classLoader = classLoaderSupplier.get(); return get(ServiceLoader.load(BackendProviderService.class, classLoader)); }
@Test void should_throw_an_exception_when_no_backend_could_be_found() { BackendServiceLoader backendSupplier = new BackendServiceLoader(classLoaderSupplier, objectFactory); Executable testMethod = () -> backendSupplier.get(emptyList()).iterator().next(); CucumberException actualThrown = ass...
public void setProfile(final Set<String> indexSetsIds, final String profileId, final boolean rotateImmediately) { checkProfile(profileId); checkAllIndicesSupportProfileChange(indexSetsIds); for (String indexSetId : indexSetsIds) { ...
@Test void testOverridesPreviousProfile() { existingIndexSet = existingIndexSet.toBuilder() .fieldTypeProfile("000000000000000000000042") .build(); doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set"); final String profileId ...
@Override public void showUpWebView(WebView webView, boolean isSupportJellyBean) { }
@Test public void showUpWebView() { WebView webView = new WebView(mApplication); mSensorsAPI.showUpWebView(webView, false); }
long[] index() { return index; }
@Test void defaultIndexCapacityIsTenEntries() { final long[] emptyIndex = new long[20]; assertArrayEquals(emptyIndex, catalogIndex.index()); }
@Override public boolean removeAll(Collection<?> c) { // will throw UnsupportedOperationException; delegate anyway for testability return underlying().removeAll(c); }
@Test public void testDelegationOfUnsupportedFunctionRemoveAll() { new PCollectionsHashSetWrapperDelegationChecker<>() .defineMockConfigurationForUnsupportedFunction(mock -> mock.removeAll(eq(Collections.emptyList()))) .defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.re...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabl...
@Test public void testListPlaceholderPlusCharacter() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); bucket.attributes().setRegion("us-east-1"); final S3AccessControlListFeature acl = new S3AccessCo...
public static DataSource createDataSource(final ModeConfiguration modeConfig) throws SQLException { return createDataSource(DefaultDatabase.LOGIC_NAME, modeConfig); }
@Test void assertCreateDataSourceWithDatabaseNameAndModeConfiguration() throws SQLException { assertDataSource(ShardingSphereDataSourceFactory.createDataSource("test_db", new ModeConfiguration("Standalone", null), Collections.emptyMap(), null, null), "test_db"); }
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) public static TableReference parseTableSpec(String tableSpec) { Matcher match = BigQueryIO.TABLE_SPEC.matcher(tableSpec); if (!match.matches()) { throw new IllegalArgumentException( String.format( ...
@Test public void testTableParsing_validPatterns() { BigQueryHelpers.parseTableSpec("a123-456:foo_bar.d"); BigQueryHelpers.parseTableSpec("a12345:b.c"); BigQueryHelpers.parseTableSpec("a1:b.c"); BigQueryHelpers.parseTableSpec("b12345.c"); }
@Override public Expression getExpression(String tableName, Alias tableAlias) { // 只有有登陆用户的情况下,才进行数据权限的处理 LoginUser loginUser = SecurityFrameworkUtils.getLoginUser(); if (loginUser == null) { return null; } // 只有管理员类型的用户,才进行数据权限的处理 if (ObjectUtil.notEqual(...
@Test // 拼接 Dept 和 User 的条件(字段都不符合) public void testGetExpression_noDeptColumn_noSelfColumn() { try (MockedStatic<SecurityFrameworkUtils> securityFrameworkUtilsMock = mockStatic(SecurityFrameworkUtils.class)) { // 准备参数 String tableName = "t_user"; Ali...
public static Set<org.onosproject.security.Permission> convertToOnosPermissions(List<Permission> permissions) { Set<org.onosproject.security.Permission> result = Sets.newHashSet(); for (Permission perm : permissions) { org.onosproject.security.Permission onosPerm = getOnosPermission(perm); ...
@Test public void testConvertToOnosPermissions() { Permission testJavaPerm = new AppPermission("testName"); List<org.onosproject.security.Permission> result = Lists.newArrayList(); org.onosproject.security.Permission onosPerm = new org.onosproject.security.Permission(AppPerm...
public synchronized void removeListen(String groupKey, String connectionId) { //1. remove groupKeyContext Set<String> connectionIds = groupKeyContext.get(groupKey); if (connectionIds != null) { connectionIds.remove(connectionId); if (connectionIds.isEmpty()) { ...
@Test void testRemoveListen() { configChangeListenContext.addListen("groupKey", "md5", "connectionId"); configChangeListenContext.removeListen("groupKey", "connectionId"); Set<String> groupKey = configChangeListenContext.getListeners("groupKey"); assertNull(groupKey); }
private static int parseInteger(final String text) { // This methods expects |text| is not null. final String textTrimmed = text.trim(); final int length = textTrimmed.length(); if ("null".equals(textTrimmed)) { throw new NullPointerException("\"" + text + "\" is considered ...
@Test public void testParseInteger() { assertInteger("11", 11, 1234); assertInteger(" 13", 13, 1234); assertInteger(" 17 ", 17, 1234); assertInteger("111111111", 111111111, 1234); assertInteger("-11", -11, 1234); }
@Override public boolean next() throws SQLException { currentRow.clear(); if (getOrderByValuesQueue().isEmpty()) { return false; } if (isFirstNext()) { super.next(); } if (aggregateCurrentGroupByRowAndNext()) { currentGroupByValues ...
@Test void assertNextForResultSetsAllEmpty() throws SQLException { ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL")); MergedResult actual = resultMerger.merge(Arrays.asList(mockQueryResult(), mockQueryResult(), mockQueryResult(...
protected String parsePolicyWeights(Map<SubClusterIdInfo, Float> policyWeights) { if (MapUtils.isEmpty(policyWeights)) { return null; } List<String> policyWeightList = new ArrayList<>(); for (Map.Entry<SubClusterIdInfo, Float> entry : policyWeights.entrySet()) { SubClusterIdInfo key = entry....
@Test public void testParsePolicyWeights() { Map<SubClusterIdInfo, Float> policyWeights = new LinkedHashMap<>(); SubClusterIdInfo sc1 = new SubClusterIdInfo("SC-1"); policyWeights.put(sc1, 0.7f); SubClusterIdInfo sc2 = new SubClusterIdInfo("SC-2"); policyWeights.put(sc2, 0.3f); String policyWe...
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void testConvertNamenodeRegistration() { StorageInfo info = getStorageInfo(NodeType.NAME_NODE); NamenodeRegistration reg = new NamenodeRegistration("address:999", "http:1000", info, NamenodeRole.NAMENODE); NamenodeRegistrationProto regProto = PBHelper.convert(reg); NamenodeRegistr...
@Override public int partition(int total, T data) { return (int) Thread.currentThread().getId() % total; }
@Test public void testPartition() { int partitionNum = (int) Thread.currentThread().getId() % 10; ProducerThreadPartitioner<SampleData> partitioner = new ProducerThreadPartitioner<SampleData>(); assertEquals(partitioner.partition(10, new SampleData()), partitionNum); assertEquals(par...
public CompletableFuture<Void> setAsync(UUID uuid, VersionedProfile versionedProfile) { return profiles.setAsync(uuid, versionedProfile) .thenCompose(ignored -> redisSetAsync(uuid, versionedProfile)); }
@Test public void testSetAsync() { final UUID uuid = UUID.randomUUID(); final byte[] name = TestRandomUtil.nextBytes(81); final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null, null, null, "somecommitment".getBytes()); when(asyncCommands.hset(eq("...
@Override public String getUserName() { return null; }
@Test void assertGetUserName() { assertNull(metaData.getUserName()); }
public static JWKSet load(Path path) { try (var fin = Files.newInputStream(path)) { return JWKSet.load(fin); } catch (IOException | ParseException e) { var fullPath = path.toAbsolutePath(); throw new RuntimeException( "failed to load JWKS from '%s' ('%s')".formatted(path, fullPath),...
@Test void load() { var jwks = JwksUtils.load(Path.of("./src/test/resources/fixtures/jwks_utils_sample.json")); assertEquals(1, jwks.size()); assertNotNull(jwks.getKeyByKeyId("test")); }
@Override public Pod pod(String uid) { checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_POD_UID); return kubevirtPodStore.pod(uid); }
@Test public void testGetPodByUid() { createBasicPods(); assertNotNull("Pod did not match", target.pod(POD_UID)); assertNull("Pod did not match", target.pod(UNKNOWN_UID)); }
@Override public void write(DataOutput out) throws IOException { String json = GsonUtils.GSON.toJson(this, OnlineOptimizeJobV2.class); Text.writeString(out, json); }
@Test public void testSerializeOfOptimizeJob() throws IOException { // prepare file File file = new File(TEST_FILE_NAME); file.createNewFile(); file.deleteOnExit(); DataOutputStream out = new DataOutputStream(new FileOutputStream(file)); OnlineOptimizeJobV2 optimizeJ...
public int sleepAndExecute() { long timeout = timeout(); while (timeout > 0) { ZMQ.msleep(timeout); timeout = timeout(); } return execute(); }
@Test public void testInvokedAfterReset() { testNotInvokedAfterResetHalfTime(); // Wait until the end int rc = timers.sleepAndExecute(); assertThat(rc, is(1)); assertThat(invoked.get(), is(true)); }
public Path(URI uri) { this.path = HttpURL.Path.parse(uri.getRawPath()); }
@Test void testPath() { assertFalse(new Path(URI.create("")).matches("/a/{foo}/bar/{b}")); assertFalse(new Path(URI.create("///")).matches("/a/{foo}/bar/{b}")); assertFalse(new Path(URI.create("///foo")).matches("/a/{foo}/bar/{b}")); assertFalse(new Path(URI.create("///bar/")).matche...
@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(expected = InteroperabilityException.class) public void testToUrlInvalidEmail() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet....
public MethodBuilder onreturnMethod(String onreturnMethod) { this.onreturnMethod = onreturnMethod; return getThis(); }
@Test void onreturnMethod() { MethodBuilder builder = MethodBuilder.newBuilder(); builder.onreturnMethod("on-return-method"); Assertions.assertEquals("on-return-method", builder.build().getOnreturnMethod()); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMultimapRemoveThenPut() { final String tag = "multimap"; StateTag<MultimapState<byte[], Integer>> addr = StateTags.multimap(tag, ByteArrayCoder.of(), VarIntCoder.of()); MultimapState<byte[], Integer> multimapState = underTest.state(NAMESPACE, addr); final byte[] key = "k...
@Override public String resolve(Method method, Object[] arguments, String spelExpression) { if (StringUtils.isEmpty(spelExpression)) { return spelExpression; } if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) { return stringValueReso...
@Test public void testRootMethodName() throws Exception { String testExpression = "#root.methodName"; DefaultSpelResolverTest target = new DefaultSpelResolverTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); String result = sut.resolve(testMethod,...
@Override public void configure(String encodedAuthParamString) { if (StringUtils.isBlank(encodedAuthParamString)) { throw new IllegalArgumentException("No authentication parameters were provided"); } Map<String, String> params; try { params = AuthenticationUti...
@Test public void testConfigure() throws Exception { Map<String, String> params = new HashMap<>(); params.put("type", "client_credentials"); params.put("privateKey", "data:base64,e30="); params.put("issuerUrl", "http://localhost"); params.put("audience", "http://localhost"); ...
public static Object applyLogicalType(Schema.Field field, Object value) { if (field == null || field.schema() == null) { return value; } Schema fieldSchema = resolveUnionSchema(field.schema()); return applySchemaTypeLogic(fieldSchema, value); }
@Test public void testApplyLogicalTypeReturnsConvertedValueWhenConversionForLogicalTypeIsKnown() { String value = "d7738003-1472-4f63-b0f1-b5e69c8b93e9"; String schemaString = new StringBuilder().append("{").append(" \"type\": \"record\",").append(" \"name\": \"test\",") .append(" \"fie...
public static State toState(@Nullable String stateName) { if (stateName == null) { return State.UNRECOGNIZED; } switch (stateName) { case "JOB_STATE_UNKNOWN": return State.UNKNOWN; case "JOB_STATE_STOPPED": return State.STOPPED; case "JOB_STATE_FAILED": retur...
@Test public void testToStateWithOtherValueReturnsUnknown() { assertEquals(State.UNRECOGNIZED, MonitoringUtil.toState("FOO_BAR_BAZ")); }
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldThrowIfCanNotCoerceMapValue() { // Given: final KsqlJsonDeserializer<Map> deserializer = givenDeserializerForSchema( SchemaBuilder .map(Schema.OPTIONAL_STRING_SCHEMA, Schema.INT32_SCHEMA) .build(), Map.class ); final byte[] bytes = seria...
public static Mode parse(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException(ExceptionMessage.INVALID_MODE.getMessage(value)); } try { return parseNumeric(value); } catch (NumberFormatException e) { // Treat as symbolic return parseSymbolic(value...
@Test public void symbolicsCombined() { Mode parsed = ModeParser.parse("a=rwx"); assertEquals(Mode.Bits.ALL, parsed.getOwnerBits()); assertEquals(Mode.Bits.ALL, parsed.getGroupBits()); assertEquals(Mode.Bits.ALL, parsed.getOtherBits()); parsed = ModeParser.parse("ugo=rwx"); assertEquals(Mode....
public static <T extends Throwable> void checkNotEmpty(final String value, final Supplier<T> exceptionSupplierIfUnexpected) throws T { if (Strings.isNullOrEmpty(value)) { throw exceptionSupplierIfUnexpected.get(); } }
@Test void assertCheckNotEmptyWithCollectionToNotThrowException() { assertDoesNotThrow(() -> ShardingSpherePreconditions.checkNotEmpty(Collections.singleton("foo"), SQLException::new)); }
@Override public Optional<Track<T>> clean(Track<T> track) { TreeSet<Point<T>> points = new TreeSet<>(track.points()); Optional<Point<T>> firstNonNull = firstPointWithAltitude(points); if (!firstNonNull.isPresent()) { return Optional.empty(); } SortedSet<Point<T...
@Test public void removeTracksWithNoAltitudes() { Track<NoRawData> testTrack = trackWithNoAltitudes(); Optional<Track<NoRawData>> cleanedTrack = (new FillMissingAltitudes<NoRawData>()).clean(testTrack); assertTrue(!cleanedTrack.isPresent(), "A track with no altitude data should be removed")...
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testCopyFile() throws Exception { final DeepboxIdProvider fileid = new DeepboxIdProvider(session); final Path documents = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Documents/", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(documents, ...
public String getPath() { return urlAddress == null ? null : urlAddress.getPath(); }
@Test void test_Path() throws Exception { URL url = new ServiceConfigURL("dubbo", "localhost", 20880, "////path"); assertURLStrDecoder(url); assertEquals("path", url.getPath()); }
Flux<DataEntityList> export(KafkaCluster cluster) { String clusterOddrn = Oddrn.clusterOddrn(cluster); Statistics stats = statisticsCache.get(cluster); return Flux.fromIterable(stats.getTopicDescriptions().keySet()) .filter(topicFilter) .flatMap(topic -> createTopicDataEntity(cluster, topic,...
@Test void doesExportTopicData() { when(schemaRegistryClientMock.getSubjectVersion("testTopic-value", "latest", false)) .thenReturn(Mono.just( new SchemaSubject() .schema("\"string\"") .schemaType(SchemaType.AVRO) )); when(schemaRegistryClientMock.g...
void parse() throws IOException, DefParserException { root = new InnerCNode(name); normalizedDefinition = new NormalizedDefinition(); String s; List<String> originalInput = new ArrayList<>(); while ((s = reader.readLine()) != null) { originalInput.add(s); } ...
@Test void duplicate_parameter_is_illegal() { Class<?> exceptionClass = DefParser.DefParserException.class; StringBuilder sb = createDefTemplate(); String duplicateLine = "b int\n"; sb.append(duplicateLine); sb.append(duplicateLine); try { createParser(sb....