focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public int handshake(final ChannelHandlerContext context) { int result = ConnectionIdGenerator.getInstance().nextId(); connectionPhase = MySQLConnectionPhase.AUTH_PHASE_FAST_PATH; boolean sslEnabled = ProxySSLContext.getInstance().isSSLEnabled(); if (sslEnabled) { ...
@Test void assertHandshakeWithSSLEnabled() { when(ProxySSLContext.getInstance().isSSLEnabled()).thenReturn(true); ChannelHandlerContext context = mockChannelHandlerContext(); when(context.pipeline()).thenReturn(mock(ChannelPipeline.class)); assertTrue(authenticationEngine.handshake(c...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public AppInfo get() { return getAppInfo(); }
@Test public void testInvalidUri2() throws JSONException, Exception { WebResource r = resource(); String responseStr = ""; try { responseStr = r.path("ws").path("v1").path("invalid") .accept(MediaType.APPLICATION_JSON).get(String.class); fail("should have thrown exception on invalid ...
public static void parseParams(Map<String, String> params) { if (params != null && params.size() > 0) { for (Map.Entry<String, String> entry : UTM_LINK_MAP.entrySet()) { String utmKey = entry.getValue(); String value = params.get(utmKey); if (!TextUtil...
@Test public void parseParams() { Map<String, String> params = new HashMap<>(); params.put("utm_source", "source_value"); params.put("utm_medium", "medium_value"); ChannelUtils.parseParams(params); JSONObject jsonObject = ChannelUtils.getUtmProperties(); Assert.assert...
@Override public int removeRangeByRank(int startIndex, int endIndex) { return get(removeRangeByRankAsync(startIndex, endIndex)); }
@Test public void testRemoveRangeByRank() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); set.add(0.1, "a"); set.add(0.2, "b"); set.add(0.3, "c"); set.add(0.4, "d"); set.add(0.5, "e"); set.add(0.6, "f"); set.add(0.7, "g"); ...
public static int checkLessThanOrEqual(int n, long expected, String name) { if (n > expected) { throw new IllegalArgumentException(name + ": " + n + " (expected: <= " + expected + ')'); } return n; }
@Test public void checkLessThanOrEqualMustPassIfArgumentIsLessThanExpected() { final int n = 0; final int actual = RangeUtil.checkLessThanOrEqual(n, 1, "var"); assertThat(actual, is(equalTo(n))); }
@Override public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttpEntityCallable<StorageObject>(file) { @Override ...
@Test public void testWriteCustomMetadata() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final Tra...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testGetName() { assertEquals("Composer.lock analyzer", analyzer.getName()); }
@Override public SeekableByteChannel getChannel() { return new RedissonByteChannel(); }
@Test public void testChannelOverwrite() throws IOException { RBinaryStream stream = redisson.getBinaryStream("test"); SeekableByteChannel c = stream.getChannel(); assertThat(c.write(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7}))).isEqualTo(7); c.position(3); assertThat(c....
@Override public String put(String key, String value) { if (value == null) throw new IllegalArgumentException("Null value not allowed as an environment variable: " + key); return super.put(key, value); }
@Test public void overrideOrderCalculatorSelfReference() { EnvVars env = new EnvVars(); EnvVars overrides = new EnvVars(); overrides.put("PATH", "some;${PATH}"); OverrideOrderCalculator calc = new OverrideOrderCalculator(env, overrides); List<String> order = calc.getOrderedV...
public static Object parseType(String name, Object value, Type type) { try { if (value == null) return null; String trimmed = null; if (value instanceof String) trimmed = ((String) value).trim(); switch (type) { case BOOLEAN: ...
@Test public void testClassWithAlias() { final String alias = "PluginAlias"; ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { // Could try to use the Plugins class from Connect here, but this should simulate enough // of the alia...
@Override public CompletableFuture<ShareGroupHeartbeatResponseData> shareGroupHeartbeat( RequestContext context, ShareGroupHeartbeatRequestData request ) { if (!isActive.get()) { return CompletableFuture.completedFuture(new ShareGroupHeartbeatResponseData() .s...
@Test public void testShareGroupHeartbeat() throws ExecutionException, InterruptedException, TimeoutException { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), ...
public static void addSecurityProvider(Properties properties) { properties.keySet().stream() .filter(key -> key.toString().matches("security\\.provider(\\.\\d+)?")) .sorted(Comparator.comparing(String::valueOf)).forEach(key -> addSecurityProvider(properties.get(key).toString()));...
@Test void addSecurityProvidersViaProperties() { removeAllDummyProviders(); int providersCountBefore = Security.getProviders().length; Properties properties = new Properties(); properties.put("security.provider.1", DummyProviderWithConfig.class.getName() + ":2:CONFIG"); prop...
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRe...
@Test void testFieldMappingLegacyCompositeTypeWithRenaming() { int[] indices = TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("a", DataTypes.BIGINT()) .field("b", DataTypes.STRING()...
static List<String> serversMapToList(Map<String, String> servers) { List<String> serversList = new ArrayList<>(servers.size()); for (var entry : servers.entrySet()) { serversList.add(String.format("%s=%s", entry.getKey(), entry.getValue())); } return serversList; }
@Test public void testMapToList() { Map<String, String> servers = new HashMap<>(3); servers.put("server.1", "my-cluster-zookeeper-0.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181"); servers.put("server.2", "my-cluster-zookeeper-1.my-cluster-zookeeper-nodes.myp...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_orientation_land() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("land", config); assertThat(config.orientation).isEqualTo(ORIENTATION_LAND); }
@Override public Interpreter getInterpreter(String replName, ExecutionContext executionContext) throws InterpreterNotFoundException { if (StringUtils.isBlank(replName)) { // Get the default interpreter of the defaultInterpreterSetting InterpreterSetting defau...
@Test void testUnknownRepl2() { try { interpreterFactory.getInterpreter("unknown_repl", new ExecutionContext("user1", "note1", "test")); fail("should fail due to no such interpreter"); } catch (InterpreterNotFoundException e) { assertEquals("No such interpreter: unknown_repl", e.getMessage()...
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException { final String httpSessionId = authenticationRequest.getRequest().getSession().getId(); if (authenticationRequest.getFederationName() !...
@Test public void checkIfAssertionConsumerServiceUrlIsSet() throws SamlSessionException, SharedServiceClientException { samlSessionService.initializeSession(authenticationRequest, bindingContext); assertEquals("https://sso.afnemer.nl", authenticationRequest.getSamlSession().getAssertionConsumerServ...
@Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { return new InjvmExporter<>(invoker, invoker.getUrl().getServiceKey(), exporterMap); }
@Test void testApplication() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .addParameter("application", "consumer") .addParameter(APPLICAT...
@Override public boolean filterPath(Path filePath) { if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) { return false; } // compensate for the fact that Flink paths are slashed final String path = filePath.hasWindowsDrive() ? filePath....
@Test void testMatchAllFilesByDefault() { GlobFilePathFilter matcher = new GlobFilePathFilter(Collections.emptyList(), Collections.emptyList()); assertThat(matcher.filterPath(new Path("dir/file.txt"))).isFalse(); }
@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 shouldThrowIfCanNotCoerceToDouble() { // Given: final KsqlJsonDeserializer<Double> deserializer = givenDeserializerForSchema(Schema.OPTIONAL_FLOAT64_SCHEMA, Double.class); final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Exception e = asser...
public long size() { return mInStreamCache.size() + mOutStreamCache.size(); }
@Test public void size() throws Exception { StreamCache streamCache = new StreamCache(Constants.HOUR_MS); FileInStream is = mock(FileInStream.class); FileOutStream os = mock(FileOutStream.class); Assert.assertEquals(0, streamCache.size()); int isId = streamCache.put(is); Assert.assertEquals(1,...
public static Compressor getCompressor(String alias) { // 工厂模式 托管给ExtensionLoader return EXTENSION_LOADER.getExtension(alias); }
@Test public void getCompressor1() throws Exception { Compressor compressor = CompressorFactory.getCompressor("test"); Assert.assertNotNull(compressor); Assert.assertEquals(compressor.getClass(), TestCompressor.class); }
public static void loadRules(List<AuthorityRule> rules) { currentProperty.updateValue(rules); }
@Test public void testLoadRules() { String resourceName = "testLoadRules"; AuthorityRule rule = new AuthorityRule(); rule.setResource(resourceName); rule.setLimitApp("a,b"); rule.setStrategy(RuleConstant.AUTHORITY_WHITE); AuthorityRuleManager.loadRules(Collections.si...
@Override public StorageVolume getDefaultStorageVolume() { try (LockCloseable lock = new LockCloseable(rwLock.readLock())) { if (defaultStorageVolumeId.isEmpty()) { return getStorageVolumeByName(BUILTIN_STORAGE_VOLUME); } return getStorageVolume(getDefault...
@Test public void testGetDefaultStorageVolume() throws IllegalAccessException, AlreadyExistsException, DdlException, NoSuchFieldException { new Expectations() { { editLog.logSetDefaultStorageVolume((SetDefaultStorageVolumeLog) any); } }; S...
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { expectCaseSensitiveDefaultCollation(connection); if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) { repairColumns(connection); } }
@Test public void upgrade_fails_if_default_collation_is_not_CS_AS() throws SQLException { answerDefaultCollation("Latin1_General_CI_AI"); assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE)) .isInstanceOf(MessageException.class) .hasMessage("Database collat...
public static Transcript parse(String jsonStr) { try { Transcript transcript = new Transcript(); long startTime = -1L; long endTime = -1L; long segmentStartTime = -1L; long segmentEndTime = -1L; long duration = 0L; String speake...
@Test public void testParse() { String type = "application/json"; Transcript result = TranscriptParser.parse(jsonStr, type); // There isn't a segment at 900L, so go backwards and get the segment at 800L assertEquals(result.getSegmentAtTime(900L).getSpeaker(), "John Doe"); ass...
@Nullable public JavaEmojiUtils.SkinTone getDefaultSkinTone() { if (mRandom) { switch (new Random().nextInt(JavaEmojiUtils.SkinTone.values().length)) { case 0: return JavaEmojiUtils.SkinTone.Fitzpatrick_2; case 1: return JavaEmojiUtils.SkinTone.Fitzpatrick_3; case 2...
@Test public void getDefaultSkinTone() { DefaultSkinTonePrefTracker tracker = new DefaultSkinTonePrefTracker(AnyApplication.prefs(getApplicationContext())); // default value is null Assert.assertNull(tracker.getDefaultSkinTone()); final String[] skinToneValues = getApplicationContext...
public static MetricRegistry getOrCreate(String name) { final MetricRegistry existing = REGISTRIES.get(name); if (existing == null) { final MetricRegistry created = new MetricRegistry(); final MetricRegistry raced = add(name, created); if (raced == null) { ...
@Test public void memorizesRegistriesByName() throws Exception { final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); assertThat(one) .isSameAs(two); }
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { return wasmLoader.getWasmExtern(DO_EXECUTE_ME...
@Test public void executeSelectorManyMatch() { List<ConditionData> conditionDataList = Collections.singletonList(conditionData); this.ruleData.setConditionDataList(conditionDataList); this.ruleData.setMatchMode(0); this.selectorData.setSort(1); this.selectorData.setMatchMode(...
@Override public TimeValue getRetryInterval(HttpResponse response, int execCount, HttpContext context) { // a server may send a 429 / 503 with a Retry-After header // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After Header header = response.getFirstHeader(HttpHeaders.RETRY_AFTER); ...
@Test public void invalidRetryAfterHeader() { HttpResponse response = new BasicHttpResponse(503, "Oopsie"); response.setHeader(HttpHeaders.RETRY_AFTER, "Stuff"); assertThat(retryStrategy.getRetryInterval(response, 3, null).toMilliseconds()) .isBetween(4000L, 5000L); }
@GetMapping("/trace") @PreAuthorize(value = "@apolloAuditLogQueryApiPreAuthorizer.hasQueryPermission()") public List<ApolloAuditLogDetailsDTO> findTraceDetails(@RequestParam String traceId) { List<ApolloAuditLogDetailsDTO> detailsDTOList = api.queryTraceDetails(traceId); return detailsDTOList; }
@Test public void testFindTraceDetails() throws Exception { final String traceId = "query-trace-id"; final int traceDetailsListLength = 3; { List<ApolloAuditLogDetailsDTO> mockDetailsDTOList = MockBeanFactory.mockTraceDetailsDTOListByLength( traceDetailsListLength); mockDetailsDTOLis...
public synchronized Map<String, Object> getSubtaskProgress(String taskName, @Nullable String subtaskNames, Executor executor, HttpClientConnectionManager connMgr, Map<String, String> workerEndpoints, Map<String, String> requestHeaders, int timeoutMs) throws Exception { return getSubtaskProgress(ta...
@Test public void testGetSubtaskProgressPending() throws Exception { TaskDriver taskDriver = mock(TaskDriver.class); JobConfig jobConfig = mock(JobConfig.class); when(taskDriver.getJobConfig(anyString())).thenReturn(jobConfig); JobContext jobContext = mock(JobContext.class); when(taskDriver....
public static String getType(String fileStreamHexHead) { if(StrUtil.isBlank(fileStreamHexHead)){ return null; } if (MapUtil.isNotEmpty(FILE_TYPE_MAP)) { for (final Entry<String, String> fileTypeEntry : FILE_TYPE_MAP.entrySet()) { if (StrUtil.startWithIgnoreCase(fileStreamHexHead, fileTypeEntry.getKey())...
@Test @Disabled public void emptyTest() { final File file = FileUtil.file("d:/empty.txt"); final String type = FileTypeUtil.getType(file); Console.log(type); }
@Override public boolean hasReservedCapacity(@Nonnull UUID txnId) { if (txnId.equals(NULL_UUID)) { return false; } return reservedCapacityCountByTxId.containsKey(txnId); }
@Test public void null_uuid_has_no_reserved_capacity() { assertFalse(counter.hasReservedCapacity(TxnReservedCapacityCounter.NULL_UUID)); }
public boolean checkStateUpdater(final long now, final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) { addTasksToStateUpdater(); if (stateUpdater.hasExceptionsAndFailedTasks()) { handleExceptionsFromStateUpdater(); } if ...
@Test public void shouldRetryInitializationWhenLockExceptionInStateUpdater() { final StreamTask task00 = statefulTask(taskId00, taskId00ChangelogPartitions) .withInputPartitions(taskId00Partitions) .inState(State.RESTORING).build(); final StandbyTask task01 = standbyTask(task...
@Override // FsDatasetSpi public FsVolumeReferences getFsVolumeReferences() { return new FsVolumeReferences(volumes.getVolumes()); }
@Test(timeout = 30000) public void testReportBadBlocks() throws Exception { boolean threwException = false; final Configuration config = new HdfsConfiguration(); try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(config) .numDataNodes(1).build()) { cluster.waitActive(); Assert.a...
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException { if (StringUtils.isBlank(filter)) { return true; } Script script; try { script = ENGINE.createScript(filter); } catch (JexlException e) { throw new FeedEntryFilterException("Exception while parsing exp...
@Test void emptyFilterMatchesFilter() throws FeedEntryFilterException { Assertions.assertTrue(service.filterMatchesEntry(null, entry)); }
private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); }
@Test public void javaSerdeInvalidVersion() throws Exception { int invalidVersion = -1; byte[] data = new byte[]{0x1, 0x2, 0x3, 0x4}; WorkerIdentity identity = new WorkerIdentity(data, invalidVersion); final byte[] buffer; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOut...
public Timestamp convertDateToTimestamp( Date date ) throws KettleValueException { if ( date == null ) { return null; } Timestamp result = null; if ( date instanceof Timestamp ) { result = (Timestamp) date; } else { result = new Timestamp( date.getTime() ); } return result;...
@Test public void testConvertDateToTimestamp() throws Exception { ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp(); // Converting date to timestamp Date date = new Date(); assertEquals( valueMetaTimestamp.convertDateToTimestamp( date ).getTime(), date.getTime() ); // Converting ti...
@Override public long currentTime() { return timerService.currentProcessingTime(); }
@Test void testCurrentProcessingTime() throws Exception { TestInternalTimerService<Integer, VoidNamespace> timerService = getTimerService(); DefaultProcessingTimeManager manager = new DefaultProcessingTimeManager(timerService); long newTime = 100L; timerService.advanceProcessingTime(...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeTags() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'withtags': {'type': 'STRING','tags': ['tag1', 'tag3'], 'value': 'hello'}}"); Map<String, ParamDefinition> paramsToMerge = parseParamDefMap( "...
@Override public boolean isSameRM(final XAResource xaResource) { SingleXAResource singleXAResource = (SingleXAResource) xaResource; return resourceName.equals(singleXAResource.resourceName); }
@Test void assertIsSameRM() { assertTrue(singleXAResource.isSameRM(new SingleXAResource("ds1", xaResource))); }
@Override public Exchange add(CamelContext camelContext, String key, Exchange oldExchange, Exchange newExchange) throws OptimisticLockingException { if (!optimistic) { throw new UnsupportedOperationException(); } LOG.trace("Adding an Exchange with ID {} for key {} in...
@Test public void checkThreadSafeAddOfNewExchange() throws Exception { JCacheAggregationRepository repoOne = createRepository(false); JCacheAggregationRepository repoTwo = createRepository(false); repoOne.start(); repoTwo.start(); try { final String testBody = "...
@Override public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) { final ModelId modelId = entityDescriptor.id(); try { final Input input = inputService.find(modelId.id()); final InputWithExtractors inputWithExtractor...
@Test @MongoDBFixtures("InputFacadeTest.json") public void collectEntity() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf25294b900a0fdb4e5365", ModelTypes.INPUT_V1); final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor); final Optional<En...
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComDebugPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_DEBUG, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
public static Map<String, Object> convert(FormData data) { Map<String, Object> map = new HashMap<>(); for (String key : data) { if (data.get(key).size() == 1) { // If the form data is file, read it as FileItem, else read as String. if (data.getFirst(key).getF...
@Test public void shouldToGetConvertedFormDataInAMap() { String aKey = "aKey"; String aValue = "aValue"; String anotherKey = "anotherKey"; String anotherValue = "anotherValue"; FormData formData = new FormData(99); formData.add(aKey, aValue); formData.add(ano...
@CanIgnoreReturnValue public final Ordered containsExactly() { return containsExactlyEntriesIn(ImmutableMap.of()); }
@Test public void containsExactlyExtraKey() { ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3); expectFailureWhenTestingThat(actual).containsExactly("feb", 2, "jan", 1); assertFailureKeys( "unexpected keys", "for key", "unexpected value", "---", "expected", "b...
public synchronized void userAddFunction(Function f, boolean allowExists) throws UserException { addFunction(f, false, allowExists); GlobalStateMgr.getCurrentState().getEditLog().logAddFunction(f); }
@Test public void testUserAddFunction() throws UserException { // User adds addIntInt UDF FunctionName name = new FunctionName(null, "addIntInt"); name.setAsGlobalFunction(); final Type[] argTypes = {Type.INT, Type.INT}; Function f = new Function(name, argTypes, Type.INT, fal...
@Override public void export(RegisterTypeEnum registerType) { if (this.exported) { return; } if (getScopeModel().isLifeCycleManagedExternally()) { // prepare model for reference getScopeModel().getDeployer().prepare(); } else { // ensu...
@Test void testMethodConfigWithConfiguredArgumentTypeAndIndex() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { ...
public static boolean isLocalhostReachable(int port) { return reachable(null, port); }
@Test public void shouldReturnFalseIfPortIsNotReachableOnLocalhost() throws Exception { assertThat(SystemUtil.isLocalhostReachable(9876), is(false)); }
public static String escape(String original) { if (original != null) { return original.replace("\\", "\\\\").replace("\r", "\\r").replace("\n", "\\n"); } else { return null; } }
@Test public void testEscape() { assertEquals("Hello\\\\nWorld!", StringUtil.escape("Hello\\nWorld!")); assertEquals("Hello\\nWorld!", StringUtil.escape("Hello\nWorld!")); assertEquals("\\r\tHello\\nWorld!", StringUtil.escape("\r\tHello\nWorld!")); assertEquals("Hello\\\\\\nWorld!", StringUtil.escape("Hello\\\...
ProducerListeners listeners() { return new ProducerListeners(eventListeners.toArray(new HollowProducerEventListener[0])); }
@Test public void fireIntegrityCheckStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener)....
public Repository getRepo(String serverUrl, String token, String project, String repoSlug) { HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s", project, repoSlug)); return doGet(token, url, body -> buildGson().fromJson(body, Repository.class)); }
@Test public void malformed_json() { server.enqueue(new MockResponse() .setHeader("Content-Type", "application/json;charset=UTF-8") .setBody("I'm malformed JSON")); String serverUrl = server.url("/").toString(); assertThatThrownBy(() -> underTest.getRepo(serverUrl, "token", "", "")) .is...
public long lappedCount() { return lappedCount.get(); }
@Test void shouldNotBeLappedBeforeReception() { assertThat(broadcastReceiver.lappedCount(), is(0L)); }
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { PDFParserConfig localConfig = defaultConfig; PDFParserConfig userConfig = context.get(PDFParserConfig.class); if (userCo...
@Test public void testSingleCloseDoc() throws Exception { //TIKA-1341 Metadata m = new Metadata(); ParseContext c = new ParseContext(); ContentHandler h = new EventCountingHandler(); try (InputStream is = getResourceAsStream("/test-documents/testPDFTripleLangTitle.pdf")) { ...
@GetMapping @Secured(action = ActionTypes.READ, signType = SignType.CONFIG) public Result<ConfigHistoryInfo> getConfigHistoryInfo(@RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam(value = "namespaceId", required = false, defaultValue = StringUtils....
@Test void testGetConfigHistoryInfo() throws Exception { ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); configHistoryInfo.setDataId(TEST_DATA_ID); configHistoryInfo.setGroup(TEST_GROUP); configHistoryInfo.setContent(TEST_CONTENT); configHistoryInfo.se...
public B protocolIds(String protocolIds) { this.protocolIds = protocolIds; return getThis(); }
@Test void protocolIds() { ServiceBuilder builder = new ServiceBuilder(); builder.protocolIds("protocolIds"); Assertions.assertEquals("protocolIds", builder.build().getProtocolIds()); }
@Override public <T> T persist(T detachedObject) { Map<Object, Object> alreadyPersisted = new HashMap<Object, Object>(); return persist(detachedObject, alreadyPersisted, RCascadeType.PERSIST); }
@Test public void testInheritedREntity() { Dog d = new Dog("Fido"); d.setBreed("lab"); d = redisson.getLiveObjectService().persist(d); assertThat(d.getName()).isEqualTo("Fido"); assertThat(d.getBreed()).isEqualTo("lab"); }
@ApiOperation(value = "Create Or update Tenant (saveTenant)", notes = "Create or update the Tenant. When creating tenant, platform generates Tenant Id as " + UUID_WIKI_LINK + "Default Rule Chain and Device profile are also generated for the new tenants automatically. " + ...
@Test public void testSaveTenant() throws Exception { loginSysAdmin(); Tenant tenant = new Tenant(); tenant.setTitle("My tenant"); Mockito.reset(tbClusterService); Tenant savedTenant = saveTenant(tenant); Assert.assertNotNull(savedTenant); Assert.assertNotNu...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Bundled"); for (PluginInfo plugin : repository.getPluginsInfoByType(PluginType.BUNDLED)) { String label = ""; Version version = p...
@Test public void toProtobuf_given3BundledPlugins_returnThree() { when(repo.getPluginsInfoByType(PluginType.BUNDLED)).thenReturn(Arrays.asList( new PluginInfo("java") .setName("Java") .setVersion(Version.create("20.0")), new PluginInfo("c++") .setName("C++") .setVersion...
public @CheckForNull R search(final int n, final Direction d) { switch (d) { case EXACT: return getByNumber(n); case ASC: for (int m : numberOnDisk) { if (m < n) { // TODO could be made more efficient with numberOnDisk.find ...
@Issue("JENKINS-22681") @Test public void exactSearchShouldNotReload() throws Exception { FakeMap m = localBuilder.add(1).add(2).make(); assertNull(m.search(0, Direction.EXACT)); Build a = m.search(1, Direction.EXACT); a.asserts(1); Build b = m.search(2, Direction.EXACT); ...
public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path...
@Test public void testLookup_absolute_notExists() throws IOException { try { lookup("/a/b"); fail(); } catch (NoSuchFileException expected) { } try { lookup("/work/one/foo/bar"); fail(); } catch (NoSuchFileException expected) { } try { lookup("$c/d"); ...
public static byte[] encodeObjectIdentifier(String oid) { try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(oid.length() / 3 + 1)) { encodeObjectIdentifier(oid, bos); return bos.toByteArray(); } catch (IOException e) { throw new Asn1Exception("Unexpecte...
@Test public void encodeObjectIdentifierWithDoubleFirst() { assertArrayEquals(new byte[] { (byte) 0x81, 5 }, Asn1Utils.encodeObjectIdentifier("2.53")); }
@Override public abstract String toString();
@Test public void testFrom_toString() { assertThat(STRING_PREFIX_EQUALITY.toString()).isEqualTo("starts with"); }
@Override public Mono<GetVersionedProfileResponse> getVersionedProfile(final GetVersionedProfileRequest request) { final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); final ServiceIdentifier targetIdentifier = ServiceIdentifierUtil.fromGrpcServiceIdentifier...
@Test void getVersionedProfileRatelimited() { final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(7), false); final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder() .setAccountIdentifier(ServiceId...
@Override public String name() { return name; }
@Test public void testSetNamespaceOwnershipNoop() throws TException, IOException { setNamespaceOwnershipAndVerify( "set_ownership_noop_1", ImmutableMap.of(HiveCatalog.HMS_DB_OWNER, "some_individual_owner"), ImmutableMap.of( HiveCatalog.HMS_DB_OWNER, "some_individual...
public static <T> T[] checkNonEmpty(T[] array, String name) { //No String concatenation for check if (checkNotNull(array, name).length == 0) { throw new IllegalArgumentException("Param '" + name + "' must not be empty"); } return array; }
@Test public void testCheckNonEmptyCharArrayString() { Exception actualEx = null; try { ObjectUtil.checkNonEmpty((char[]) NULL_OBJECT, NULL_NAME); } catch (Exception e) { actualEx = e; } assertNotNull(actualEx, TEST_RESULT_NULLEX_OK); assertTr...
public void acknowledgePages(long sequenceId) { checkArgument(sequenceId >= 0, "Invalid sequence id"); // Fast path early-return without synchronizing if (destroyed.get() || sequenceId < currentSequenceId.get()) { return; } ImmutableList.Builder<SerializedPageRef...
@Test public void testBufferResults() { ClientBuffer buffer = new ClientBuffer(TASK_INSTANCE_ID, BUFFER_ID, NOOP_RELEASE_LISTENER); long totalSizeOfPagesInBytes = 0; for (int i = 0; i < 3; i++) { Page page = createPage(i); SerializedPageReference pageReference = ...
@Override public synchronized void putConnectorConfig(String connName, final Map<String, String> config, boolean allowReplace, final Callback<Created<ConnectorInfo>> callba...
@Test public void testCreateConnectorWithStoppedInitialState() throws Exception { initialize(true); Map<String, String> config = connectorConfig(SourceSink.SINK); expectConfigValidation(SourceSink.SINK, config); // Only the connector should be created; we expect no tasks to be spawn...
@Override public void setConfigAttributes(Object attributes) { if (attributes == null) { return; } super.setConfigAttributes(attributes); Map map = (Map) attributes; if (map.containsKey(URL)) { this.url = new HgUrlArgument((String) map.get(URL)); ...
@Test void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged() throws Exception { HgMaterialConfig hgMaterialConfig = hg(); Map<String, String> map = new HashMap<>(); map.put(HgMaterialConfig.PASSWORD, "secret"); map.put(HgMaterialConfig.PASSWORD_CHANGED, "1")...
Plugin create(Options.Plugin plugin) { try { return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument()); } catch (IOException | URISyntaxException e) { throw new CucumberException(e); } }
@Test void instantiates_usage_plugin_without_file_arg() { PluginOption option = parse("usage"); plugin = fc.create(option); assertThat(plugin.getClass(), is(equalTo(UsageFormatter.class))); }
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingUpdateStructRowNewValuesToDataChangeRecord() { final DataChangeRecord dataChangeRecord = new DataChangeRecord( "partitionToken", Timestamp.ofTimeSecondsAndNanos(10L, 20), "serverTransactionId", true, "1", ...
@Override public Long put(final K key, final Long value) { return valOrNull(put(key, value.longValue())); }
@Test public void putShouldReturnOldValue() { map.put("1", 1L); assertEquals(1L, map.put("1", 2L)); }
public static String maskString(String input, String key) { if(input == null) return null; String output = input; Map<String, Object> stringConfig = (Map<String, Object>) config.get(MASK_TYPE_STRING); if (stringConfig != null) { Map<String, Object> keyConfig = (Ma...
@Test public void testMaskString() { String url1 = "/v1/customer?sin=123456789&password=secret&number=1234567890123456"; String output = Mask.maskString(url1, "uri"); System.out.println("ouput = " + output); Assert.assertEquals("/v1/customer?sin=masked&password=******&number=--------...
@Override public String getOriginalHost() { try { if (originalHost == null) { originalHost = getOriginalHost(getHeaders(), getServerName()); } return originalHost; } catch (URISyntaxException e) { throw new IllegalArgumentException(e); ...
@Test void testGetOriginalHost_immutable() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", ...
public FifoOrderingPolicy() { List<Comparator<SchedulableEntity>> comparators = new ArrayList<Comparator<SchedulableEntity>>(); comparators.add(new PriorityComparator()); comparators.add(new FifoComparator()); this.comparator = new CompoundComparator(comparators); this.schedulableEntities = ...
@Test public void testFifoOrderingPolicy() { FifoOrderingPolicy<MockSchedulableEntity> policy = new FifoOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity r1 = new MockSchedulableEntity(); MockSchedulableEntity r2 = new MockSchedulableEntity(); assertEquals("The comparator should r...
@Override public Object getValue() { return serializationService.toObject(value); }
@Test public void getValue_caching() { QueryableEntry entry = createEntry("key", "value"); assertThat(entry.getValue()).isNotSameAs(entry.getValue()); }
static int determineCoordinatorReservoirSize(int numPartitions) { int reservoirSize = numPartitions * COORDINATOR_TARGET_PARTITIONS_MULTIPLIER; if (reservoirSize < COORDINATOR_MIN_RESERVOIR_SIZE) { // adjust it up and still make reservoirSize divisible by numPartitions int remainder = COORDINATOR_M...
@Test public void testCoordinatorReservoirSize() { // adjusted to over min threshold of 10_000 and is divisible by number of partitions (3) assertThat(SketchUtil.determineCoordinatorReservoirSize(3)).isEqualTo(10_002); // adjust to multiplier of 100 assertThat(SketchUtil.determineCoordinatorReservoirS...
public void createApplication(ApplicationId id) { database().createApplication(id); }
@Test public void require_that_application_ids_can_be_written() throws Exception { TenantApplications repo = createZKAppRepo(); ApplicationId myapp = createApplicationId("myapp"); repo.createApplication(myapp); writeActiveTransaction(repo, myapp, 3); String path = TenantRepos...
public QueryConfiguration applyOverrides(QueryConfigurationOverrides overrides) { Map<String, String> sessionProperties; if (overrides.getSessionPropertiesOverrideStrategy() == OVERRIDE) { sessionProperties = new HashMap<>(overrides.getSessionPropertiesOverride()); } else...
@Test public void testEmptyOverrides() { assertEquals(CONFIGURATION_1.applyOverrides(new QueryConfigurationOverridesConfig()), CONFIGURATION_1); assertEquals(CONFIGURATION_2.applyOverrides(new QueryConfigurationOverridesConfig()), CONFIGURATION_2); }
Subscription addSubscription(final String channel, final int streamId) { return addSubscription(channel, streamId, defaultAvailableImageHandler, defaultUnavailableImageHandler); }
@Test void shouldFailToAddSubscriptionOnMediaDriverError() { whenReceiveBroadcastOnMessage( ControlProtocolEvents.ON_ERROR, errorMessageBuffer, (buffer) -> { errorResponse.errorCode(INVALID_CHANNEL); errorResponse.errorMessa...
public void isInStrictOrder() { isInStrictOrder(Ordering.natural()); }
@Test public void iterableIsInStrictOrderWithComparatorFailure() { expectFailureWhenTestingThat(asList("1", "2", "2", "10")).isInStrictOrder(COMPARE_AS_DECIMAL); assertFailureKeys( "expected to be in strict order", "but contained", "followed by", "full contents"); assertFailureValue("but contained...
int run() { final Map<String, String> configProps = options.getConfigFile() .map(Ksql::loadProperties) .orElseGet(Collections::emptyMap); final Map<String, String> sessionVariables = options.getVariables(); try (KsqlRestClient restClient = buildClient(configProps)) { try (Cli cli = c...
@Test public void shouldRunScriptFileWhenFileOptionIsUsed() throws IOException { // Given: final String sqlFile = TMP.newFile().getAbsolutePath(); when(options.getScriptFile()).thenReturn(Optional.of(sqlFile)); // When: ksql.run(); // Then: verify(cli).runScript(sqlFile); }
@Override protected boolean isNewMigration(NoSqlMigration noSqlMigration) { // why: as Jedis does not have a schema, each migration checks if it needs to do something return true; }
@Test void testMigrationsHappyPath() { assertThat(lettuceRedisDBCreator.isNewMigration(new NoSqlMigrationByClass(M001_JedisRemoveJobStatsAndUseMetadata.class))).isTrue(); assertThatCode(lettuceRedisDBCreator::runMigrations).doesNotThrowAnyException(); assertThatCode(lettuceRedisDBCreator::r...
public Record convert(final AbstractWALEvent event) { if (filter(event)) { return createPlaceholderRecord(event); } if (!(event instanceof AbstractRowEvent)) { return createPlaceholderRecord(event); } PipelineTableMetaData tableMetaData = getPipelineTableM...
@Test void assertConvertWriteRowEvent() { Record record = walEventConverter.convert(mockWriteRowEvent()); assertThat(record, instanceOf(DataRecord.class)); assertThat(((DataRecord) record).getType(), is(PipelineSQLOperationType.INSERT)); }
List<Endpoint> endpoints() { try { String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace); return enrichWithPublicAddresses(parsePodsList(callGet(urlString))); } catch (RestClientException e) { return handleKnownException(e); ...
@Test(expected = KubernetesClientException.class) public void endpointsFailFastWhenLbServiceHasNoHazelcastPort() throws JsonProcessingException { // given kubernetesClient = newKubernetesClient(ExposeExternallyMode.ENABLED, false, null, null); stub(String.format("/api/v1/namespaces/%s/pods"...
@Override public int hashCode() { int result = (includeValue ? 1 : 0); result = 31 * result + (key != null ? key.hashCode() : 0); return result; }
@Test public void testHashCode() { assertEquals(multiMapEventFilter.hashCode(), multiMapEventFilter.hashCode()); assertEquals(multiMapEventFilter.hashCode(), multiMapEventFilterSameAttributes.hashCode()); assumeDifferentHashCodes(); assertNotEquals(multiMapEventFilter.hashCode(), mu...
public Session getSession(String name) { return new Session(UUID.randomUUID().toString(), name); }
@Test void checkGetSession() { Server server = new Server("localhost", 8080); Session session = server.getSession("Session"); assertEquals("Session", session.getClientName()); }
@Override public LocalAddress localAddress() { return (LocalAddress) super.localAddress(); }
@Test @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS) public void testConnectFutureBeforeChannelActive() throws Exception { Bootstrap cb = new Bootstrap(); ServerBootstrap sb = new ServerBootstrap(); cb.group(group1) .channel(LocalChannel.class) .han...
public static Serializer getDefault() { return SERIALIZER_MAP.get(defaultSerializer); }
@Test void testSetSerialize() { Serializer serializer = SerializeFactory.getDefault(); Set<Integer> logsMap = new CopyOnWriteArraySet<>(); for (int i = 0; i < 4; i++) { logsMap.add(i); } byte[] data = serializer.serialize(logsMap); assertNotEquals...
@Override public void checkCanTruncateTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName) { if (!checkTablePermission(identity, tableName, DELETE)) { denyTruncateTable(tableName.toString()); } }
@Test public void testTableRulesForCheckCanTruncateTable() throws IOException { ConnectorAccessControl accessControl = createAccessControl("table.json"); accessControl.checkCanTruncateTable(TRANSACTION_HANDLE, user("bob"), CONTEXT, new SchemaTableName("bobschema", "bobtable")); ...
@Override @Transactional(value="defaultTransactionManager") public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException { if (authentication != null && authentication.getOAuth2Request() != null) { // look up our client OAuth2Requ...
@Test(expected = InvalidClientException.class) public void createAccessToken_nullClient() { when(clientDetailsService.loadClientByClientId(anyString())).thenReturn(null); service.createAccessToken(authentication); }
public Object select(String id, ParamOption[] options, Object defaultValue) { if (defaultValue == null && options != null && options.length > 0) { defaultValue = options[0].getValue(); } forms.put(id, new Select(id, defaultValue, options)); Object value = params.get(id); if (value == null) { ...
@Test void testSelect() { GUI gui = new GUI(); Object selected = gui.select("list_1", options, null); // use the first one as the default value assertEquals("1", selected); gui = new GUI(); selected = gui.select("list_1", options, "2"); assertEquals("2", selected); // "2" is selected...
@VisibleForTesting void validateMenu(Long parentId, String name, Long id) { MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name); if (menu == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的菜单 if (id == null) { throw exception(MENU_NAME_DUPLI...
@Test public void testValidateMenu_sonMenuNameDuplicate() { // mock 父子菜单 MenuDO sonMenu = createParentAndSonMenu(); // 准备参数 Long parentId = sonMenu.getParentId(); Long otherSonMenuId = randomLongId(); String otherSonMenuName = sonMenu.getName(); //相同名称 // 调用,...
@Override public void writeDouble(final double v) throws IOException { ensureAvailable(DOUBLE_SIZE_IN_BYTES); MEM.putDouble(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += DOUBLE_SIZE_IN_BYTES; }
@Test public void testWriteDoubleForPositionV() throws Exception { double expected = 1.1d; out.writeDouble(1, expected); long theLong = Bits.readLong(out.buffer, 1, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); double actual = Double.longBitsToDouble(theLong); assertEqua...
public boolean shouldFlush(Duration flushInterval) { final long lastFlush = lastFlushTime.get(); // If we don't know the last flush time, we want to flush. Happens with a new buffer instance. return lastFlush == 0 || (System.nanoTime() - lastFlush) > flushInterval.toNanos(); }
@Test void shouldFlush() { // No interactions yet, we want to flush because we don't know the last execution time. assertThat(buffer.shouldFlush(Duration.ofSeconds(1))).isTrue(); // Trigger a flush buffer.flush(flusher); // The last flush just happened, flush interval not r...
@Override public int run(String[] args) throws Exception { if (args.length != 2) { return usage(args); } String action = args[0]; String name = args[1]; int result; if (A_LOAD.equals(action)) { result = loadClass(name); } else if (A_CREATE.equals(action)) { //first load t...
@Test public void testCreatesClass() throws Throwable { run(FindClass.SUCCESS, FindClass.A_CREATE, "org.apache.hadoop.util.TestFindClass"); }
@Override public void lockEdge(Inode lastInode, String childName, LockMode mode) { mode = nextLockMode(mode); long edgeParentId = lastInode.getId(); Edge edge = new Edge(lastInode.getId(), childName); if (!mLocks.isEmpty()) { Preconditions.checkState(endsInInode(), "Cannot lock edge %s...
@Test public void lockEdgeAfterEdge() { mLockList.lockEdge(mDirA, mDirB.getName(), LockMode.READ); mThrown.expect(IllegalStateException.class); mLockList.lockEdge(mDirB, mFileC.getName(), LockMode.READ); }
@Override public LeastLoadedNode leastLoadedNode(long now) { List<Node> nodes = this.metadataUpdater.fetchNodes(); if (nodes.isEmpty()) throw new IllegalStateException("There are no nodes in the Kafka cluster"); int inflight = Integer.MAX_VALUE; Node foundConnecting = nu...
@Test public void testLeastLoadedNode() { client.ready(node, time.milliseconds()); assertFalse(client.isReady(node, time.milliseconds())); LeastLoadedNode leastLoadedNode = client.leastLoadedNode(time.milliseconds()); assertEquals(node, leastLoadedNode.node()); assertTrue(lea...
@Override public String toString() { return StringUtils.toString(this); }
@Test public void testToString() { Assertions.assertEquals("Metadata(leaders={}, clusterTerm={}, clusterNodes={\"cluster\"->{}}, storeMode=StoreMode.RAFT)", metadata.toString()); }