focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public String getRomOAID() { return null; }
@Test public void getRomOAID() { DefaultImpl impl = new DefaultImpl(); // if (impl.isSupported()) { // Assert.assertNull(impl.getRomOAID()); // } }
@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 testListCommonPrefixSlashOnly() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck-unsupportedprefix", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); assertTrue...
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> result = getTargetInvokersByRules(invokers, targetSe...
@Test public void testGetTargetInvokerByTagRulesWithPolicySceneThree() { // initialize the routing rule RuleInitializationUtils.initAZTagMatchTriggerThresholdMinAllInstancesPolicyRule(); // Scenario 1: The downstream provider has instances that meet the requirements List<Object> invo...
public static ConnectToSqlTypeConverter connectToSqlConverter() { return CONNECT_TO_SQL_CONVERTER; }
@Test public void shouldThrowOnUnsupportedConnectSchemaType() { // Given: final Schema unsupported = SchemaBuilder.int8().build(); // When: final Exception e = assertThrows( KsqlException.class, () -> SchemaConverters.connectToSqlConverter().toSqlType(unsupported) ); // Then:...
public static Object[] getArguments(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation.getArguments() != null && invocation.getArguments().length > 2 && invocation.getArgument...
@Test void testGet_$invoke_Arguments() { Object[] args = new Object[] {"hello", "dubbo", 520}; Class<?> demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); Invoker invoker = createMockInvoker(); RpcInvocation inv = new RpcInvocation( ...
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) { return Optional.ofNullable(HANDLERS.get(step.getClass())) .map(h -> h.handle(this, schema, step)) .orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass())); }
@Test public void shouldResolveSchemaForStreamSelect() { // Given: final StreamSelect<?> step = new StreamSelect<>( PROPERTIES, streamSource, ImmutableList.of(), Optional.empty(), ImmutableList.of( add("JUICE", "ORANGE", "APPLE"), ref("PLANTAIN",...
public Certificate add(CvCertificate cert) { final Certificate db = Certificate.from(cert); if (repository.countByIssuerAndSubject(db.getIssuer(), db.getSubject()) > 0) { throw new ClientException(String.format( "Certificate of subject %s and issuer %s already exists", db.ge...
@Test public void shouldNotAddATIfHSMIsUnavailable() throws Exception { Mockito.doThrow(new nl.logius.digid.sharedlib.exception.ClientException( "Bad Gateway", 503 )).when(hsmClient).keyInfo(Mockito.eq("AT"), Mockito.eq("SSSSSSSSSSSSSSSS")); certificateRepo.save(loadCvCertificat...
@Operation(summary = "updateUser", description = "UPDATE_USER_NOTES") @Parameters({ @Parameter(name = "id", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @Parameter(name = "userName", description = "USER_NAME", required = true, sche...
@Test public void testUpdateUser() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("id", "32"); paramsMap.add("userName", "user_test"); paramsMap.add("userPassword", "123456qwe?"); paramsMap.add("tenantId", "9"); ...
@Override public void log(Level logLevel, String message) { if (!messageConsumers.containsKey(logLevel)) { return; } Consumer<String> messageConsumer = messageConsumers.get(logLevel); // remove the color from the message final String plainMessage = message.replaceAll("\u001B\\[[0-9;]{1,5}m"...
@Test public void testLog_ignoreIfNoMessageConsumer() { testPlainConsoleLogger = new PlainConsoleLogger( ImmutableMap.of(Level.WARN, createMessageConsumer(Level.WARN)), singleThreadedExecutor); testPlainConsoleLogger.log(Level.LIFECYCLE, "lifecycle"); testPlainConsoleLogger.log(Level....
@Override @SuppressWarnings("unchecked") public boolean delDir(String dirPath) { if (false == cd(dirPath)) { return false; } final ChannelSftp channel = getClient(); Vector<LsEntry> list; try { list = channel.ls(channel.pwd()); } catch (SftpException e) { throw new JschRuntimeException(e); } ...
@Test @Disabled public void delDirTest() { sshjSftp.delDir("/home/test/temp"); }
@SuppressWarnings("unchecked") protected Set<PathSpec> getFields() { Object fields = _queryParams.get(RestConstants.FIELDS_PARAM); if (fields == null) { return Collections.emptySet(); } if (fields instanceof Set) { return (Set<PathSpec>) fields; } else if (fields instanceof ...
@Test public void testMaskTreeFieldsParam() { DataMap fields = new DataMap(); fields.put("id", MaskMap.POSITIVE_MASK); GetRequest<TestRecord> getRequest = generateDummyRequestBuilder().setParam(RestConstants.FIELDS_PARAM, fields).build(); assertEquals(getRequest.getFields(), Collections.sing...
@Override public Endpoint<Http2RemoteFlowController> remote() { return remoteEndpoint; }
@Test public void clientCreatePushShouldFailOnRemoteEndpointWhenMaxAllowedStreamsExceeded() throws Http2Exception { client = new DefaultHttp2Connection(false, 0); client.remote().maxActiveStreams(1); final Http2Stream requestStream = client.remote().createStream(2, false); assertThro...
@Override public List<RoleDO> getRoleList() { return roleMapper.selectList(); }
@Test public void testGetRoleList_ids() { // mock 数据 RoleDO dbRole01 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); roleMapper.insert(dbRole01); RoleDO dbRole02 = randomPojo(RoleDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); ...
public static <T> List<List<T>> partition(Collection<T> values, int partitionSize) { if (values == null) { return null; } else if (values.isEmpty()) { return Collections.emptyList(); } List<T> valuesList; if (values instanceof List) { valuesLi...
@Test void partitionSet() { Collection<String> set = new LinkedHashSet<>(); set.add("1"); set.add("2"); set.add("3"); set.add("4"); set.add("5"); assertThat(CollectionUtil.partition(set, 3)) .containsExactly( Arrays.asLi...
public Span handleReceive(RpcServerRequest request) { Span span = nextSpan(extractor.extract(request), request); return handleStart(request, span); }
@Test void handleReceive_samplerSeesRpcServerRequest() { SamplerFunction<RpcRequest> serverSampler = mock(SamplerFunction.class); init(httpTracingBuilder(tracingBuilder()).serverSampler(serverSampler)); handler.handleReceive(request); verify(serverSampler).trySample(request); }
@Override public void close() { }
@Test public void shouldSucceed_gapDetectedRemote_noRetry() throws ExecutionException, InterruptedException { // Given: final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>( ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemote)); final PushRouting routing = new PushRouting(sqr -> node...
public OpenConfigChannelHandler addLogicalChannelAssignments( OpenConfigLogicalChannelAssignmentsHandler logicalChannelAssignments) { modelObject.logicalChannelAssignments(logicalChannelAssignments.getModelObject()); return this; }
@Test public void testAddLogicalChannelAssignments() { // test Handler OpenConfigChannelHandler channel = new OpenConfigChannelHandler(1, parent); // call addLogicalChannelAssignments OpenConfigLogicalChannelAssignmentsHandler logicalChannelAssignments = new OpenConfigLo...
public boolean verifySignature(String jwksUri, SignedJWT signedJwt) throws JOSEException, InvalidSignatureException, IOException, ParseException { var publicKeys = getPublicKeys(jwksUri); var kid = signedJwt.getHeader().getKeyID(); if (kid != null) { var key = ((RSAKey) publicKeys.g...
@Test void verifyValidSignatureTest() throws ParseException, InvalidSignatureException, IOException, JOSEException { provider.verifySignature("jwskUri", SignedJWT.parse(client.generateRequest())); }
@Override public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK); Mode mode =...
@Test public void initializeWithZookeeperSystemProperties() throws Exception { HashMap<String, String> sysProps = new HashMap<>(); sysProps.put(PropertyKey.ZOOKEEPER_ENABLED.getName(), "true"); sysProps.put(PropertyKey.ZOOKEEPER_ADDRESS.getName(), "zkHost:2181"); try (Closeable p = new SystemPropertyR...
@Override public boolean contains(Object object) { return get(containsAsync(object)); }
@Test public void testContains() { RScoredSortedSet<TestObject> set = redisson.getScoredSortedSet("simple"); set.add(0, new TestObject("1", "2")); set.add(1, new TestObject("1", "2")); set.add(2, new TestObject("2", "3")); set.add(3, new TestObject("3", "4")); set.ad...
@Override public String serializeToString() { return REPLACE_RESOLVED_DST_PATH.getConfigName() + RegexMountPoint.INTERCEPTOR_INTERNAL_SEP + srcRegexString + RegexMountPoint.INTERCEPTOR_INTERNAL_SEP + replaceString; }
@Test public void testSerialization() { String srcRegex = "word1"; String replaceString = "word2"; String serializedString = createSerializedString(srcRegex, replaceString); RegexMountPointResolvedDstPathReplaceInterceptor interceptor = new RegexMountPointResolvedDstPathReplaceInterceptor(srcR...
public boolean couldHoldIgnoringSharedMemory(NormalizedResources other, double thisTotalMemoryMb, double otherTotalMemoryMb) { if (this.cpu < other.getTotalCpu()) { return false; } return couldHoldIgnoringSharedMemoryAndCpu(other, thisTotalMemoryMb, otherTotalMemoryMb); }
@Test public void testCouldHoldWithTooFewResource() { NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 1))); NormalizedResources resourcesToCheck = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 2))); ...
public static String servicePath(String basePath) { return servicePath(basePath, SERVICE_PATH); }
@Test(dataProvider = "servicePaths") public void testZKFSUtilServicePath(String basePath, String servicePath, String resultServicePath) { Assert.assertEquals(ZKFSUtil.servicePath(basePath, servicePath), resultServicePath); }
public static RecordBuilder<Schema> record(String name) { return builder().record(name); }
@Test void fields() { Schema rec = SchemaBuilder.record("Rec").fields().name("documented").doc("documented").type().nullType().noDefault() .name("ascending").orderAscending().type().booleanType().noDefault().name("descending").orderDescending().type() .floatType().noDefault().name("ignored").order...
@ConstantFunction.List(list = { @ConstantFunction(name = "divide", argTypes = {DECIMALV2, DECIMALV2}, returnType = DECIMALV2), @ConstantFunction(name = "divide", argTypes = {DECIMAL32, DECIMAL32}, returnType = DECIMAL32), @ConstantFunction(name = "divide", argTypes = {DECIMAL64, DECI...
@Test public void divideDecimal() { assertEquals("1", ScalarOperatorFunctions.divideDecimal(O_DECIMAL_100, O_DECIMAL_100).getDecimal().toString()); assertEquals("1", ScalarOperatorFunctions.divideDecimal(O_DECIMAL32P7S2_100, O_DECIMAL32P7S2_100).getDecimal() ...
public FEELFnResult<Boolean> invoke(@ParameterName( "string" ) String string, @ParameterName( "match" ) String match) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } if ( match == null ) { re...
@Test void invokeNotEndsWith() { FunctionTestUtil.assertResult(endsWithFunction.invoke("test", "es"), false); FunctionTestUtil.assertResult(endsWithFunction.invoke("test", "ttttt"), false); FunctionTestUtil.assertResult(endsWithFunction.invoke("test", "estt"), false); FunctionTestUti...
public NodeStatsResponse nodesStats() { return execute(() -> { Request request = new Request("GET", "/_nodes/stats/fs,process,jvm,indices,breaker"); Response response = restHighLevelClient.getLowLevelClient().performRequest(request); return NodeStatsResponse.toNodeStatsResponse(gson.fromJson(Entit...
@Test public void should_call_node_stats_api() throws Exception { HttpEntity entity = mock(HttpEntity.class); when(entity.getContent()).thenReturn(new ByteArrayInputStream(EXAMPLE_NODE_STATS_JSON.getBytes())); Response response = mock(Response.class); when(response.getEntity()).thenReturn(entity); ...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertFloat() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.FLOAT_TYPE).build(); BasicTypeDefine typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName())...
@VisibleForTesting Optional<Xpp3Dom> getSpringBootRepackageConfiguration() { Plugin springBootPlugin = project.getPlugin("org.springframework.boot:spring-boot-maven-plugin"); if (springBootPlugin != null) { for (PluginExecution execution : springBootPlugin.getExecutions()) { if (executio...
@Test public void testGetSpringBootRepackageConfiguration_noExecutions() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Collections.emptyList()); assertThat(mavenProjectProperties.getSprin...
@Override public <T> T attach(T detachedObject) { addExpireListener(commandExecutor); validateDetached(detachedObject); Class<T> entityClass = (Class<T>) detachedObject.getClass(); String idFieldName = getRIdFieldName(detachedObject.getClass()); Object id = ClassUtils.getFiel...
@Test public void test() { RLiveObjectService service = redisson.getLiveObjectService(); MyObject object = new MyObject(20L); try { service.attach(object); } catch (Exception e) { assertEquals("Non-null value is required for the field with RId annotation.", e...
public void registerWithStream(final long workerId, final List<String> storageTierAliases, final Map<String, Long> totalBytesOnTiers, final Map<String, Long> usedBytesOnTiers, final Map<BlockStoreLocation, List<Long>> currentBlocksOnLocation, final Map<String, List<String>> lostStorage, final Li...
@Test public void registerWithStream() throws Exception { register(true); }
public <T extends AwsSyncClientBuilder> void applyHttpClientConfigurations(T builder) { if (Strings.isNullOrEmpty(httpClientType)) { httpClientType = CLIENT_TYPE_DEFAULT; } switch (httpClientType) { case CLIENT_TYPE_URLCONNECTION: UrlConnectionHttpClientConfigurations urlConnectionHttpC...
@Test public void testInvalidHttpClientType() { Map<String, String> properties = Maps.newHashMap(); properties.put(HttpClientProperties.CLIENT_TYPE, "test"); HttpClientProperties httpClientProperties = new HttpClientProperties(properties); S3ClientBuilder s3ClientBuilder = S3Client.builder(); ass...
@Override protected File getFile(HandlerRequest<EmptyRequestBody> handlerRequest) { if (logDir == null) { return null; } // wrapping around another File instantiation is a simple way to remove any path information // - we're // solely interested in the filename ...
@Test void testGetJobManagerCustomLogsValidFilenameWithInvalidPath() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("../%s", VALID_LOG_FILENAME))); assertThat(actualFile).isNotNull(); String actualContent...
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology) // must be verified. expectUtf8AsDefault(connection); if (state == DatabaseCharse...
@Test public void schema_is_taken_into_account_when_selecting_columns() throws Exception { answerDefaultCharset("utf8"); answerSchema("test-schema"); answerColumns(asList( new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"}, new String[] {TABLE_PROJECTS, COLUMN_NAME, "" /* unset -> uses db collati...
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("start position") BigDecimal start) { return invoke( list, start, null ); }
@Test void invokeStartNegative() { FunctionTestUtil.assertResult(sublistFunction.invoke(Arrays.asList(1, 2, 3), BigDecimal.valueOf(-2)), Arrays.asList(2, 3)); FunctionTestUtil.assertResult(sublistFunction.invoke(Arrays.asList(1, "test", 3), BigDecimal.valueOf(-2...
public static Builder builder() { return new Builder(); }
@Test public void testBuilder() { StreamDataProducer producer = Mockito.mock(StreamDataProducer.class); PinotSourceDataGenerator generator = Mockito.mock(PinotSourceDataGenerator.class); PinotRealtimeSource realtimeSource = PinotRealtimeSource.builder().setTopic("mytopic").setProducer(producer).se...
public MpUnReachNlri(List<BgpLSNlri> mpUnReachNlri, short afi, byte safi, int length) { this.mpUnReachNlri = mpUnReachNlri; this.isMpUnReachNlri = true; this.afi = afi; this.safi = safi; this.length = length; }
@Test public void mpUnReachNlriTest() throws BgpParseException { // BGP flow spec Message byte[] flowSpecMsg = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, ...
@Override public void init(InitContext context) { String state = context.generateCsrfState(); OAuth20Service scribe = newScribeBuilder(context).build(scribeApi); String url = scribe.getAuthorizationUrl(state); context.redirectTo(url); }
@Test public void fail_to_init_when_disabled() { enableBitbucketAuthentication(false); OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class); assertThatThrownBy(() -> underTest.init(context)) .isInstanceOf(IllegalStateException.class) .hasMessage("Bitbuck...
public static boolean isJsonValid(String schemaText, String jsonText) throws IOException { return isJsonValid(schemaText, jsonText, null); }
@Test void testValidateJsonSuccess() { boolean valid = false; String schemaText = null; String jsonText = "{\"name\": \"307\", \"model\": \"Peugeot 307\", \"year\": 2003}"; try { // Load schema from file. schemaText = FileUtils .readFileToString(new File("tar...
@Override protected boolean isNan(Long number) { // NaN never applies here because only types like Float and Double have NaN return false; }
@Test void testIsNan() { LongSummaryAggregator ag = new LongSummaryAggregator(); // always false for Long assertThat(ag.isNan(-1L)).isFalse(); assertThat(ag.isNan(0L)).isFalse(); assertThat(ag.isNan(23L)).isFalse(); assertThat(ag.isNan(Long.MAX_VALUE)).isFalse(); ...
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_serializable_complex_object_with_serializable_nested_object() { Map<String, List<SerializableObject>> map = new LinkedHashMap<>(); map.put("key1", Lists.newArrayList(new SerializableObject("name1"))); map.put("key2", Lists.newArrayList( new Serializ...
public Optional<Map<String, ParamDefinition>> getDefaultParamsForType(StepType stepType) { Map<String, ParamDefinition> defaults = defaultTypeParams.get(stepType.toString().toLowerCase(Locale.US)); if (defaults != null) { return Optional.of(preprocessParams(defaults)); } else { return Op...
@Test public void testStepTypeParamsMutate() { defaultParamManager .getDefaultParamsForType(StepType.FOREACH) .get() .put("TEST", ParamDefinition.buildParamDefinition("TEST", "123")); assertNull(defaultParamManager.getDefaultParamsForType(StepType.FOREACH).get().get("TEST")); }
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test public void testReconnectNode() throws Exception { rm = new MockRM() { @Override protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() { return new EventDispatcher<SchedulerEvent>(this.scheduler, this.scheduler.getClass().getName()) { @Override ...
public static byte[] readFileBytes(File file) { if (file.exists()) { String result = readFile(file); if (result != null) { return ByteUtils.toBytes(result); } } return null; }
@Test void testReadFileBytesWithPath() { assertNotNull(DiskUtils.readFileBytes(testFile.getParent(), testFile.getName())); }
public HtmlCreator() { html.append("<!DOCTYPE html>"); html.append("<head>"); html.append("<meta charset=\"utf-8\">"); html.append("<style type='text/css'>.version{padding:10px;text-decoration-line: none;}.message-header{" + "background-color: #900C3F;\n" + ...
@Test public void testHtmlCreator() { String html = htmlCreator.html(); Assert.assertEquals(true, html.contains("Blade")); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PurgeableAnalysisDto that = (PurgeableAnalysisDto) o; return analysisUuid.equals(that.analysisUuid); }
@Test void testEquals() { PurgeableAnalysisDto dto1 = new PurgeableAnalysisDto().setAnalysisUuid("u3"); PurgeableAnalysisDto dto2 = new PurgeableAnalysisDto().setAnalysisUuid("u4"); assertThat(dto1.equals(dto2)).isFalse(); assertThat(dto2.equals(dto1)).isFalse(); assertThat(dto1.equals(dto1)).isTr...
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext, final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon...
@Test void assertNewInstanceForOptimizeTableWithShardingTable() { MySQLOptimizeTableStatement optimizeTableStatement = mock(MySQLOptimizeTableStatement.class); when(sqlStatementContext.getSqlStatement()).thenReturn(optimizeTableStatement); tableNames.add("table_1"); when(shardingRule...
@Override public Result apply(ApplyNode applyNode, Captures captures, Context context) { if (applyNode.getMayParticipateInAntiJoin()) { return Result.empty(); } Assignments subqueryAssignments = applyNode.getSubqueryAssignments(); if (subqueryAssignments.size() != 1)...
@Test public void testDoesNotFiresForInPredicateThatMayParticipateInAntiJoin() { tester().assertThat(new TransformUncorrelatedInPredicateSubqueryToDistinctInnerJoin()) .on(p -> p.apply( assignment( p.variable("x"), ...
@Override public String named() { return PluginEnum.GRPC.getName(); }
@Test public void testNamed() { final String result = grpcPlugin.named(); assertEquals(PluginEnum.GRPC.getName(), result); }
static void createCompactedTopic(String topicName, short partitions, short replicationFactor, Admin admin) { NewTopic topicDescription = TopicAdmin.defineTopic(topicName). compacted(). partitions(partitions). replicationFactor(replicationFactor). b...
@Test public void testCreateCompactedTopicAssumeTopicAlreadyExistsWithTopicAuthorizationException() throws Exception { Map<String, KafkaFuture<Void>> values = Collections.singletonMap(TOPIC, future); when(future.get()).thenThrow(new ExecutionException(new TopicAuthorizationException("not authorised"...
@Override public CloseableIterator<String> readScannerLogs() { ensureInitialized(); File file = delegate.getFileStructure().analysisLog(); if (!file.exists()) { return CloseableIterator.emptyCloseableIterator(); } try { InputStreamReader reader = new InputStreamReader(FileUtils.openInp...
@Test public void readScannerLogs() throws IOException { File scannerLogFile = writer.getFileStructure().analysisLog(); FileUtils.write(scannerLogFile, "log1\nlog2"); CloseableIterator<String> logs = underTest.readScannerLogs(); assertThat(logs).toIterable().containsExactly("log1", "log2"); }
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void testParseToday() throws Exception { DateTime reference = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 09:45:23"); DateTime startOfToday = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss").withZoneUTC().parseDateTime("12.06.2021 00:00:00");...
@Override public boolean isAdded(Component component) { checkComponent(component); if (analysisMetadataHolder.isFirstAnalysis()) { return true; } return addedComponents.contains(component); }
@Test public void isAdded_returns_true_for_any_component_type_on_first_analysis() { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); Arrays.stream(Component.Type.values()).forEach(type -> { Component component = newComponent(type); assertThat(underTest.isAdded(component)).isTrue(...
@Override public final void remove() { try { doRemove(); } catch (RuntimeException e) { close(); throw e; } }
@Test public void remove_is_not_supported_by_default() { SimpleCloseableIterator it = new SimpleCloseableIterator(); try { it.remove(); fail(); } catch (UnsupportedOperationException expected) { assertThat(it.isClosed).isTrue(); } }
public static boolean isJavaVersionAtLeast(int version) { return JAVA_SPEC_VER >= version; }
@Test public void testIsJavaVersionAtLeast() { assertTrue(Shell.isJavaVersionAtLeast(8)); }
public void createGroupTombstoneRecords( String groupId, List<CoordinatorRecord> records ) { // At this point, we have already validated the group id, so we know that the group exists and that no exception will be thrown. createGroupTombstoneRecords(group(groupId), records); }
@Test public void testConsumerGroupDelete() { String groupId = "group-id"; GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroup(new ConsumerGroupBuilder(groupId, 10)) .build(); List<CoordinatorRecord> expectedReco...
@Override public void replayOnAborted(TransactionState txnState) { writeLock(); try { replayTxnAttachment(txnState); failMsg = new FailMsg(FailMsg.CancelType.LOAD_RUN_FAIL, txnState.getReason()); finishTimestamp = txnState.getFinishTime(); state = JobS...
@Test public void testReplayOnAbortedAfterFailure(@Injectable TransactionState txnState, @Injectable LoadJobFinalOperation attachment, @Injectable FailMsg failMsg) { BrokerLoadJob brokerLoadJob = new BrokerLoadJo...
@Override public void updatePort(K8sPort port) { checkNotNull(port, ERR_NULL_PORT); checkArgument(!Strings.isNullOrEmpty(port.portId()), ERR_NULL_PORT_ID); checkArgument(!Strings.isNullOrEmpty(port.networkId()), ERR_NULL_PORT_NET_ID); k8sNetworkStore.updatePort(port); log.in...
@Test(expected = NullPointerException.class) public void testUpdateNullPort() { target.updatePort(null); }
@Override public void deleteFile(String location) { Preconditions.checkState(!closed, "Cannot call deleteFile after calling close()"); if (null == IN_MEMORY_FILES.remove(location)) { throw new NotFoundException("No in-memory file found for location: %s", location); } }
@Test public void testDeleteFileNotFound() { InMemoryFileIO fileIO = new InMemoryFileIO(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> fileIO.deleteFile("s3://nonexistent/file")); }
@Override public AppAttemptInfo getAppAttempt(HttpServletRequest req, HttpServletResponse res, String appId, String appAttemptId) { // Check that the appId/appAttemptId format is accurate try { RouterServerUtil.validateApplicationAttemptId(appAttemptId); } catch (IllegalArgumentException e) {...
@Test public void testGetAppAttempt() throws IOException, InterruptedException { // Generate ApplicationId information ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toSt...
public static String calculateSha256Hex(@Nonnull byte[] data) throws NoSuchAlgorithmException { return calculateSha256Hex(data, data.length); }
@Test public void testLeadingZero() throws Exception { byte[] data = {-103, -109, 6, 90, -72, 68, 41, 7, -45, 42, 12, -38, -50, 123, -100, 102, 95, 65, 5, 30, 64, 85, 126, -26, 5, 54, 18, -98, -85, -101, 109, -91}; String result = Sha256Util.calculateSha256Hex(data); assertEq...
public static void flip(Buffer buffer) { buffer.flip(); }
@Test public void testFlip() { ByteBuffer byteBuffer = ByteBuffer.allocate(4); byteBuffer.putInt(1); Assertions.assertDoesNotThrow(() -> BufferUtils.flip(byteBuffer)); }
public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName =...
@Test @Tag("IntegrationTest") void publishPriceUpdateTest() { String topicName = "MyTestTopic.fifo"; String wholesaleQueueName = "wholesaleQueue.fifo"; String retailQueueName = "retailQueue.fifo"; String analyticsQueueName = "analyticsQueue"; List<PriceUpdateExample.Queu...
@Override public boolean add(final Long value) { return add(value.longValue()); }
@Test public void setsWithTheSameValuesAreEqual() { final LongHashSet other = new LongHashSet(100, -1); set.add(1); set.add(1001); other.add(1); other.add(1001); assertEquals(set, other); }
public static List<PKafkaOffsetProxyResult> getBatchOffsets(List<PKafkaOffsetProxyRequest> requests) throws UserException { return PROXY_API.getBatchOffsets(requests); }
@Test public void testGetInfoRpcException() throws UserException, RpcException { Backend backend = new Backend(1L, "127.0.0.1", 9050); backend.setBeRpcPort(8060); backend.setAlive(true); new Expectations() { { service.getBackendOrComputeNode(anyLong); ...
public static Select select(String fieldName) { return new Select(fieldName); }
@Test void matches() { String q = Q.select("*") .from("sd1") .where("f1").matches("v1") .and("f2").matches("v2") .or("f3").matches("v3") .andnot("f4").matches("v4") .build(); assertEquals(q, "yql=select ...
public byte[] encode(String val, String delimiters) { return codecs[0].encode(val); }
@Test public void testEncodeArabicPersonName() { assertArrayEquals(ARABIC_PERSON_NAME_BYTE, iso8859_6().encode(ARABIC_PERSON_NAME, PN_DELIMS)); }
public void setLocalTaskQueueCapacity(int localTaskQueueCapacity) { this.localTaskQueueCapacity = checkPositive(localTaskQueueCapacity, "localTaskQueueCapacity"); }
@Test public void test_setLocalTaskQueueCapacity_whenNegative() { ReactorBuilder builder = newBuilder(); assertThrows(IllegalArgumentException.class, () -> builder.setLocalTaskQueueCapacity(-1)); }
public String toString(Object datum) { StringBuilder buffer = new StringBuilder(); toString(datum, buffer, new IdentityHashMap<>(128)); return buffer.toString(); }
@Test void mapWithNonStringKeyToStringIsJson() throws Exception { Schema intMapSchema = new Schema.Parser() .parse("{\"type\": \"map\", \"values\": \"string\", \"java-key-class\" : \"java.lang.Integer\"}"); Field intMapField = new Field("intMap", Schema.createMap(intMapSchema), null, null); Schema...
@Nonnull @Override public Collection<String> resourceTypes() { return Collections.singleton(OBJECT_TYPE_IMAP_JOURNAL); }
@Test public void should_list_resource_types() { // given DataConnectionConfig dataConnectionConfig = nonSharedDataConnectionConfig(clusterName); hazelcastDataConnection = new HazelcastDataConnection(dataConnectionConfig); // when Collection<String> resourcedTypes = hazelcas...
public static String toJsonStr(JSON json, int indentFactor) { if (null == json) { return null; } return json.toJSONString(indentFactor); }
@Test public void issue3540Test() { Long userId = 10101010L; final String jsonStr = JSONUtil.toJsonStr(userId); assertEquals("{}", jsonStr); }
@Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { filter(ch, start, length, ignorableWhitespaceOutput); }
@Test public void testInvalidSurrogates() throws SAXException { safe.ignorableWhitespace("\udb00\ubfff".toCharArray(), 0, 2); assertEquals("\ufffd\ubfff", output.toString()); }
public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) { if (fqjt.isArray()) { // if array, then calculate the name of the base (non-array) type // then add the array indicators back in String fqn = fqjt.getFullyQualifiedName(); ...
@Test void testGenericTypeWithWildCardAllImported() { Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper")); interfaze.addImportedType(new FullyQualifiedJavaType("java.util.Map")); interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List")); ...
@Override void execute() { String[] loc = getCl().getUpddateLocationParams(); Path newPath = new Path(loc[0]); Path oldPath = new Path(loc[1]); URI oldURI = oldPath.toUri(); URI newURI = newPath.toUri(); /* * validate input - Both new and old URI should contain valid host names and val...
@Test public void testNoHost() throws Exception { exception.expect(IllegalStateException.class); exception.expectMessage("HiveMetaTool:A valid host is required in both old-loc and new-loc"); MetaToolTaskUpdateLocation t = new MetaToolTaskUpdateLocation(); t.setCommandLine(new HiveMetaToolCommandLine(...
public static GeyserResourcePack readPack(Path path) throws IllegalArgumentException { if (!path.getFileName().toString().endsWith(".mcpack") && !path.getFileName().toString().endsWith(".zip")) { throw new IllegalArgumentException("Resource pack " + path.getFileName() + " must be a .zip or .mcpack f...
@Test public void testPack() throws Exception { // this mcpack only contains a folder, which the manifest is in Path path = getResource("empty_pack.mcpack"); ResourcePack pack = ResourcePackLoader.readPack(path); assertEquals("", pack.contentKey()); // should probably add som...
public static String generateWsRemoteAddress(HttpServletRequest request) { if (request == null) { throw new IllegalArgumentException("HttpServletRequest must not be null."); } StringBuilder remoteAddress = new StringBuilder(); String scheme = request.getScheme(); rem...
@Test public void testGenerateWsRemoteAddress() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getScheme()).thenReturn("http"); when(request.getRemoteAddr()).thenReturn("localhost"); when(request.getRemotePort()).thenReturn(8080); assertEquals("w...
@VisibleForTesting void validateParentMenu(Long parentId, Long childId) { if (parentId == null || ID_ROOT.equals(parentId)) { return; } // 不能设置自己为父菜单 if (parentId.equals(childId)) { throw exception(MENU_PARENT_ERROR); } MenuDO menu = menuMapper...
@Test public void testValidateParentMenu_success() { // mock 数据 MenuDO menuDO = buildMenuDO(MenuTypeEnum.MENU, "parent", 0L); menuMapper.insert(menuDO); // 准备参数 Long parentId = menuDO.getId(); // 调用,无需断言 menuService.validateParentMenu(parentId, null); }
static boolean hasUnboundedOutput(Pipeline p) { PipelineTranslationModeOptimizer optimizer = new PipelineTranslationModeOptimizer(); optimizer.translate(p); return optimizer.hasUnboundedCollections; }
@Test public void testBoundedCollectionProducingTransform() { PipelineOptions options = PipelineOptionsFactory.create(); options.setRunner(FlinkRunner.class); Pipeline pipeline = Pipeline.create(options); pipeline.apply(GenerateSequence.from(0).to(10)); assertThat(PipelineTranslationModeOptimizer...
@Override public void writeShort(final int v) throws IOException { ensureAvailable(SHORT_SIZE_IN_BYTES); MEM.putShort(buffer, ARRAY_BYTE_BASE_OFFSET + pos, (short) v); pos += SHORT_SIZE_IN_BYTES; }
@Test public void testWriteShortV() throws Exception { short expected = 100; out.writeShort(expected); short actual = Bits.readShort(out.buffer, 0, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); assertEquals(expected, actual); }
@Override public boolean isReadOnly() { return false; }
@Test void assertIsReadOnly() { assertFalse(metaData.isReadOnly()); }
static void validate(KafkaConsumer<byte[], byte[]> consumer, byte[] message, ConsumerRecords<byte[], byte[]> records) { if (records.isEmpty()) { consumer.commitSync(); throw new RuntimeException("poll() timed out before finding a result (timeout:[" + POLL_TIMEOUT_MS + "])"); } ...
@Test @SuppressWarnings("unchecked") public void shouldFailWhenSentIsNotEqualToReceived() { Iterator<ConsumerRecord<byte[], byte[]>> iterator = mock(Iterator.class); ConsumerRecord<byte[], byte[]> record = mock(ConsumerRecord.class); when(records.isEmpty()).thenReturn(false); whe...
public static BigDecimal getBigDecimalOrNull(Object value) { if ( value instanceof BigDecimal ) { return (BigDecimal) value; } if ( value instanceof BigInteger ) { return new BigDecimal((BigInteger) value, MathContext.DECIMAL128); } if ( value instanceof...
@Test void getBigDecimalOrNull() { assertThat(NumberEvalHelper.getBigDecimalOrNull(10d)).isEqualTo(new BigDecimal("10")); assertThat(NumberEvalHelper.getBigDecimalOrNull(10.00000000D)).isEqualTo(new BigDecimal("10")); assertThat(NumberEvalHelper.getBigDecimalOrNull(10000000000.5D)).isEqualTo...
public ServiceConfiguration getConfiguration() { return this.config; }
@Test public void testAdvertisedAddress() throws Exception { cleanup(); useStaticPorts = true; setup(); assertEquals(pulsar.getAdvertisedAddress(), "localhost"); assertEquals(pulsar.getBrokerServiceUrlTls(), "pulsar+ssl://localhost:6651"); assertEquals(pulsar.getBroke...
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { th...
@Test void handlesArrayOverride() throws Exception { System.setProperty("dw.type", "coder,wizard,overridden"); final Example example = factory.build(configurationSourceProvider, validFile); assertThat(example.getType()) .hasSize(3) .element(2) .isEqualTo("...
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromSnapshotTimestamp() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_TIMESTAMP) .startSnapshotTimestamp(snapshot2.timestampMillis(...
@Override @SuppressWarnings("DuplicatedCode") public Integer cleanErrorLog(Integer exceedDay, Integer deleteLimit) { int count = 0; LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay); // 循环删除,直到没有满足条件的数据 for (int i = 0; i < Short.MAX_VALUE; i++) { int...
@Test public void testCleanJobLog() { // mock 数据 ApiErrorLogDO log01 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3)))); apiErrorLogMapper.insert(log01); ApiErrorLogDO log02 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofD...
public static Boolean andOfWrap(Boolean... array) { if (ArrayUtil.isEmpty(array)) { throw new IllegalArgumentException("The Array must not be empty !"); } for (final Boolean b : array) { if(!isTrue(b)){ return false; } } return true; }
@Test public void issue3587Test() { Boolean boolean1 = true; Boolean boolean2 = null; Boolean result = BooleanUtil.andOfWrap(boolean1, boolean2); assertFalse(result); }
@Override public int sizeIdx2size(int sizeIdx) { return sizeClass.sizeIdx2size(sizeIdx); }
@Test public void testSizeIdx2size() { SizeClasses sc = new SizeClasses(PAGE_SIZE, PAGE_SHIFTS, CHUNK_SIZE, 0); PoolArena<ByteBuffer> arena = new PoolArena.DirectArena(null, sc); for (int i = 0; i < arena.sizeClass.nSizes; i++) { assertEquals(arena.sizeClass.sizeIdx2sizeCompute(i...
@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 testFindTenants() throws Exception { loginSysAdmin(); List<Tenant> tenants = new ArrayList<>(); PageLink pageLink = new PageLink(17); PageData<Tenant> pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); Assert.assertFalse...
public static List<Path> getJarsInDirectory(String path) { return getJarsInDirectory(path, true); }
@Test public void testGetJarsInDirectory() throws Exception { List<Path> jars = FileUtil.getJarsInDirectory("/foo/bar/bogus/"); assertTrue("no jars should be returned for a bogus path", jars.isEmpty()); // create jar files to be returned File jar1 = new File(tmp, "wildcard1.jar"); File j...
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testOutDatedLoadData() throws IllegalAccessException { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = setupContext(); var brokerLoadDataStore = ctx.brokerLoadDataStore(); var res = trans...
@Override public CRMaterial deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN); }
@Test public void shouldDeserializeP4tMaterialType() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("type", "p4"); materialTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext); verify(jsonDeserializationContext).deserialize(jsonObject, CRP4Materi...
void scheduleAfterWrite() { int drainStatus = drainStatusOpaque(); for (;;) { switch (drainStatus) { case IDLE: casDrainStatus(IDLE, REQUIRED); scheduleDrainBuffers(); return; case REQUIRED: scheduleDrainBuffers(); return; case PROC...
@Test public void scheduleAfterWrite() { var cache = new BoundedLocalCache<Object, Object>( Caffeine.newBuilder(), /* loader */ null, /* async */ false) { @Override void scheduleDrainBuffers() {} }; var transitions = Map.of( IDLE, REQUIRED, REQUIRED, REQUIRED, PROCESS...
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_attachNonexistentFileWithPathAndId_then_throwsException() { // Given String id = "exist"; String path = Paths.get("/i/do/not/" + id).toString(); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an exist...
public List<AttendeeGroup> findAttendeeGroupCombinationsOverSize(int minSize) { if (minSize < 1 || minSize > attendees.size()) { throw new MomoException(AttendeeErrorCode.INVALID_ATTENDEE_SIZE); } List<AttendeeGroup> array = new ArrayList<>(); for (int i = attendees.size(); ...
@DisplayName("참석자 그룹의 모든 조합을 구한다.") @Test void findCombinationAttendeeGroups() { Meeting meeting = MeetingFixture.DINNER.create(); Attendee jazz = AttendeeFixture.HOST_JAZZ.create(meeting); Attendee pedro = AttendeeFixture.GUEST_PEDRO.create(meeting); Attendee baeky = AttendeeFix...
@VisibleForTesting public static String getNsFromDataNodeNetworkLocation(String location) { // network location should be in the format of /ns/rack Pattern pattern = Pattern.compile("^/([^/]*)/"); Matcher matcher = pattern.matcher(location); if (matcher.find()) { return matcher.group(1); } ...
@Test public void testGetNsFromDataNodeNetworkLocation() { assertEquals("ns0", RouterWebHdfsMethods .getNsFromDataNodeNetworkLocation("/ns0/rack-info1")); assertEquals("ns0", RouterWebHdfsMethods .getNsFromDataNodeNetworkLocation("/ns0/row1/rack-info1")); assertEquals("", RouterWebHdfsMeth...
public <V> V retryCallable( Callable<V> callable, Set<Class<? extends Exception>> exceptionsToIntercept) { return RetryHelper.runWithRetries( callable, getRetrySettings(), getExceptionHandlerForExceptions(exceptionsToIntercept), NanoClock.getDefaultClock()); }
@Test public void testRetryCallable_RetriesExpectedNumberOfTimes() { AtomicInteger executeCounter = new AtomicInteger(0); Callable<Integer> incrementingFunction = () -> { executeCounter.incrementAndGet(); if (executeCounter.get() < 2) { throw new MyException(); ...
@Override public JCConditional inline(Inliner inliner) throws CouldNotResolveImportException { return inliner .maker() .Conditional( getCondition().inline(inliner), getTrueExpression().inline(inliner), getFalseExpression().inline(inliner)); }
@Test public void inline() { assertInlines( "true ? -1 : 1", UConditional.create(ULiteral.booleanLit(true), ULiteral.intLit(-1), ULiteral.intLit(1))); }
@Override public Optional<Product> findProduct(int productId) { return this.productRepository.findById(productId); }
@Test void findProduct_ProductExists_ReturnsNotEmptyOptional() { // given var product = new Product(1, "Товар №1", "Описание товара №1"); doReturn(Optional.of(product)).when(this.productRepository).findById(1); // when var result = this.service.findProduct(1); // t...
@Override public ListConsumerGroupsResult listConsumerGroups(ListConsumerGroupsOptions options) { final KafkaFutureImpl<Collection<Object>> all = new KafkaFutureImpl<>(); final long nowMetadata = time.milliseconds(); final long deadline = calcDeadlineMs(nowMetadata, options.timeoutMs()); ...
@Test public void testListConsumerGroupsWithTypes() throws Exception { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); // Test with a specific state filter but no type filter in list c...