focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void containerAllocated(S schedulableEntity, RMContainer r) { entityRequiresReordering(schedulableEntity); }
@Test public void testIterators() { OrderingPolicy<MockSchedulableEntity> schedOrder = new FairOrderingPolicy<MockSchedulableEntity>(); MockSchedulableEntity msp1 = new MockSchedulableEntity(); MockSchedulableEntity msp2 = new MockSchedulableEntity(); MockSchedulableEntity msp3 = new MockSchedul...
@Override public void logout() { }
@Test public void logout() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); mS...
static Schema getSchema(Class<? extends Message> clazz) { return getSchema(ProtobufUtil.getDescriptorForClass(clazz)); }
@Test public void testOptionalPrimitiveSchema() { assertEquals( TestProtoSchemas.OPTIONAL_PRIMITIVE_SCHEMA, ProtoSchemaTranslator.getSchema(Proto2SchemaMessages.OptionalPrimitive.class)); }
public GoPluginBundleDescriptor build(BundleOrPluginFileDetails bundleOrPluginJarFile) { if (!bundleOrPluginJarFile.exists()) { throw new RuntimeException(format("Plugin or bundle jar does not exist: %s", bundleOrPluginJarFile.file())); } String defaultId = bundleOrPluginJarFile.fil...
@Test void shouldCreateInvalidPluginDescriptorEvenIfPluginXMLIsNotFound() throws Exception { String pluginJarName = "descriptor-aware-test-plugin-with-no-plugin-xml.jar"; copyPluginToThePluginDirectory(pluginDirectory, pluginJarName); File pluginJarFile = new File(pluginDirectory, pluginJarN...
public void receiveMessage(ProxyContext ctx, ReceiveMessageRequest request, StreamObserver<ReceiveMessageResponse> responseObserver) { ReceiveMessageResponseStreamWriter writer = createWriter(ctx, responseObserver); try { Settings settings = this.grpcClientSettingsManager.getClientS...
@Test public void testReceiveMessageWithIllegalPollingTime() { StreamObserver<ReceiveMessageResponse> receiveStreamObserver = mock(ServerCallStreamObserver.class); ArgumentCaptor<ReceiveMessageResponse> responseArgumentCaptor0 = ArgumentCaptor.forClass(ReceiveMessageResponse.class); doNothin...
@Override @Nullable public String readUTF(@Nonnull String fieldName) throws IOException { return readString(fieldName); }
@Test public void testReadUTF() throws Exception { String aString = reader.readString("string"); assertEquals("test", aString); assertNull(reader.readString("NO SUCH FIELD")); }
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldThrowIfRetentionConfigPresentInCreateTableAs() { // Given: givenStatement("CREATE TABLE foo_bar WITH (kafka_topic='doesntexist', partitions=2, format='avro', retention_ms=30000) AS SELECT * FROM SOURCE;"); // When: final Exception e = assertThrows( KsqlException.class,...
public void onChange(Multimap<QProfileName, ActiveRuleChange> changedProfiles, long startDate, long endDate) { if (config.getBoolean(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES).orElse(false)) { return; } BuiltInQPChangeNotificationBuilder builder = new BuiltInQPChangeNotificationBuilder(); change...
@Test public void add_profile_to_notification_for_updated_rules() { enableNotificationInGlobalSettings(); Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create(); Languages languages = new Languages(); Tuple expectedTuple = addProfile(profiles, languages, UPDATED); BuiltInQ...
public @CheckForNull V start() throws Exception { V result = null; int currentAttempt = 0; boolean success = false; while (currentAttempt < attempts && !success) { currentAttempt++; try { if (LOGGER.isLoggable(Level.INFO)) { LO...
@Test public void performedAtThirdAttemptTest() throws Exception { final int SUCCESSFUL_ATTEMPT = 3; final String ACTION = "print"; RingBufferLogHandler handler = new RingBufferLogHandler(20); Logger.getLogger(Retrier.class.getName()).addHandler(handler); // Set the require...
@Override public Header getHeaders() { if (this.responseHeader == null) { this.responseHeader = Header.newInstance(); org.apache.http.Header[] allHeaders = response.getAllHeaders(); for (org.apache.http.Header header : allHeaders) { this.responseHeader.add...
@Test void testGetHeaders() { assertEquals(3, clientHttpResponse.getHeaders().getHeader().size()); assertEquals("testValue", clientHttpResponse.getHeaders().getValue("testName")); }
@Override public Cursor<Tuple> zScan(byte[] key, ScanOptions options) { return new KeyBoundCursor<Tuple>(key, 0, options) { private RedisClient client; @Override protected ScanIteration<Tuple> doScan(byte[] key, long cursorId, ScanOptions options) { if (...
@Test public void testZScan() { connection.zAdd("key".getBytes(), 1, "value1".getBytes()); connection.zAdd("key".getBytes(), 2, "value2".getBytes()); Cursor<Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build()); assertThat(t.hasNext()).isTrue(); as...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testNumberWithNegativeScale() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("number(38,-1)") .dataType("number") .precision(38L) ...
public static <T extends SpecificRecordBase> T dataMapToSpecificRecord(DataMap map, RecordDataSchema dataSchema, Schema avroSchema) throws DataTranslationException { DataMapToSpecificRecordTranslator translator = new DataMapToSpecificRecordTranslator(); try { T avroRecord = translator.translate(map,...
@Test public void testDataMapToSpecificRecordTranslatorInnerRecord() throws IOException { RecordDataSchema recordDataSchema = (RecordDataSchema) TestUtil.dataSchemaFromString(TestEventRecordOfRecord.TEST_SCHEMA.toString()); RecordDataSchema innerRecordDataSchema = (RecordDataSchema) TestUtil.d...
static int linuxMinorVersion0(String version, boolean isLinux) { if (!isLinux) { return -1; } String[] versionTokens = version.split("\\."); try { return Integer.parseInt(versionTokens[1]); } catch (NumberFormatException e) { return -1; ...
@Test public void test_linuxMinorVersion0_whenNotIsLinux() { assertEquals(-1, OS.linuxMinorVersion0("5.16.12-200.fc35.x86_64", false)); }
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) throws SQLException { int length = payload.readInt1(); switch (length) { case 0: throw new SQLFeatureNotSupportedException("Can not support date format if year, month, day is absent.");...
@Test void assertReadWithSevenBytes() throws SQLException { when(payload.readInt1()).thenReturn(7, 12, 31, 10, 59, 0); when(payload.readInt2()).thenReturn(2018); LocalDateTime actual = LocalDateTime.ofInstant(Instant.ofEpochMilli(((Timestamp) new MySQLDateBinaryProtocolValue().read(payload, ...
@Override public void setConfiguration(final Path file, final LoggingConfiguration configuration) throws BackgroundException { // Logging target bucket final Path bucket = containerService.getContainer(file); try { final S3BucketLoggingStatus status = new S3BucketLoggingStatus( ...
@Test(expected = NotfoundException.class) public void testWriteNotFound() throws Exception { new S3LoggingFeature(session).setConfiguration( new Path(UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory)), new LoggingConfiguration(false) ); }
public static String formatToSimpleDate(Date date) { SimpleDateFormat simpleDate = new SimpleDateFormat("dd MMM yyyy"); return simpleDate.format(date); }
@Test public void shouldFormatDateToDisplayOnUI() { Calendar instance = Calendar.getInstance(); instance.set(2009, Calendar.NOVEMBER, 5); Date date = instance.getTime(); String formattedDate = DateUtils.formatToSimpleDate(date); assertThat(formattedDate, is("05 Nov 2009")); ...
@Override public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) { Predicate<Map.Entry<TextBlock, Integer>> containsLine = new TextBlockContainsLine(lineBuilder.getLine()); // list is sorted to cope with the non-guaranteed order of Map entries which would trigger false detection of changes ...
@Test public void read_nothing() { DuplicationLineReader reader = new DuplicationLineReader(Collections.emptySet()); assertThat(reader.read(line1)).isEmpty(); assertThat(line1.getDuplicationList()).isEmpty(); }
public ConvertedTime getConvertedTime(long duration) { Set<Seconds> keys = RULES.keySet(); for (Seconds seconds : keys) { if (duration <= seconds.getSeconds()) { return RULES.get(seconds).getConvertedTime(duration); } } return new TimeConverter.Ove...
@Test public void testShouldReportAbout1MonthFor29Days23Hours59Minutes30Seconds() throws Exception { assertEquals(TimeConverter.ABOUT_1_MONTH_AGO, timeConverter.getConvertedTime(29 * TimeConverter.DAY_IN_SECONDS + 23 * 60 * 60 + 59 * 60 + 30)); }
public static boolean containsSkinTone( @NonNull CharSequence text, @NonNull JavaEmojiUtils.SkinTone skinTone) { return JavaEmojiUtils.containsSkinTone(text, skinTone); }
@Test public void testContainsSkinTone() { Assert.assertFalse( EmojiUtils.containsSkinTone("\uD83D\uDC4D", JavaEmojiUtils.SkinTone.Fitzpatrick_2)); Assert.assertTrue( EmojiUtils.containsSkinTone( "\uD83D\uDC4D\uD83C\uDFFB", JavaEmojiUtils.SkinTone.Fitzpatrick_2)); Assert.assert...
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public @Nullable <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) throws IOException { return createEvaluator((AppliedPTransform) application); }
@Test public void boundedSourceInMemoryTransformEvaluatorShardsOfSource() throws Exception { PipelineOptions options = PipelineOptionsFactory.create(); List<? extends BoundedSource<Long>> splits = source.split(source.getEstimatedSizeBytes(options) / 2, options); UncommittedBundle<BoundedSourceSha...
public void incQueuePutNums(final String topic, final Integer queueId) { if (enableQueueStat) { this.statsTable.get(Stats.QUEUE_PUT_NUMS).addValue(buildStatsKey(topic, queueId), 1, 1); } }
@Test public void testIncQueuePutNums() { brokerStatsManager.incQueuePutNums(TOPIC, QUEUE_ID); String statsKey = brokerStatsManager.buildStatsKey(TOPIC, String.valueOf(QUEUE_ID)); assertThat(brokerStatsManager.getStatsItem(QUEUE_PUT_NUMS, statsKey).getTimes().doubleValue()).isEqualTo(1L); ...
@Override public int getOrder() { return PluginEnum.SENTINEL.getCode(); }
@Test public void testGetOrder() { final int result = sentinelPlugin.getOrder(); assertEquals(PluginEnum.SENTINEL.getCode(), result); }
@SuppressWarnings("WeakerAccess") public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); // Get main consumer override configs final Map<String, Object> mainC...
@Test public void shouldNotSetInternalThrowOnFetchStableOffsetUnsupportedConfigToFalseInConsumerForEosDisabled() { final Map<String, Object> consumerConfigs = streamsConfig.getMainConsumerConfigs(groupId, clientId, threadIdx); assertThat(consumerConfigs.get("internal.throw.on.fetch.stable.offset.uns...
@Override public ObjectNode encode(MappingInstruction instruction, CodecContext context) { checkNotNull(instruction, "Mapping instruction cannot be null"); return new EncodeMappingInstructionCodecHelper(instruction, context).encode(); }
@Test public void multicastWeightInstructionTest() { final MulticastMappingInstruction.WeightMappingInstruction instruction = (MulticastMappingInstruction.WeightMappingInstruction) MappingInstructions.multicastWeight(MULTICAST_WEIGHT); final ObjectNode instruc...
public static FailoverStrategy.Factory loadFailoverStrategyFactory(final Configuration config) { checkNotNull(config); final String strategyParam = config.get(JobManagerOptions.EXECUTION_FAILOVER_STRATEGY); switch (strategyParam.toLowerCase()) { case FULL_RESTART_STRATEGY_NAME: ...
@Test void testLoadRestartPipelinedRegionStrategyFactory() { final Configuration config = new Configuration(); config.set( JobManagerOptions.EXECUTION_FAILOVER_STRATEGY, FailoverStrategyFactoryLoader.PIPELINED_REGION_RESTART_STRATEGY_NAME); assertThat(Failover...
public String getBaseUrl() { String url = config.get(SERVER_BASE_URL).orElse(""); if (isEmpty(url)) { url = computeBaseUrl(); } // Remove trailing slashes return StringUtils.removeEnd(url, "/"); }
@Test public void base_url_is_http_specified_host_9000_when_host_is_set() { settings.setProperty(HOST_PROPERTY, "my_host"); assertThat(underTest().getBaseUrl()).isEqualTo("http://my_host:9000"); }
public static Sessions withGapDuration(Duration gapDuration) { return new Sessions(gapDuration); }
@Test public void testDisplayData() { Duration gapDuration = Duration.standardMinutes(234); Sessions session = Sessions.withGapDuration(gapDuration); assertThat(DisplayData.from(session), hasDisplayItem("gapDuration", gapDuration)); }
@Override public boolean isReusable() { return true; }
@Test public void testIsReusable() { assertThat(parser.isReusable(), CoreMatchers.is(true)); }
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(String topic, long offset, int queueId, String brokerName, boolean deCompressBody) { MessageStore messageStore = brokerController.getMessageStoreByBrokerName(brokerName); if (messageStore != null) { return messageS...
@Test public void getMessageAsyncTest_localStore_decodeNothing_DefaultMessageStore() throws Exception { when(brokerController.getMessageStoreByBrokerName(any())).thenReturn(defaultMessageStore); for (GetMessageStatus status : GetMessageStatus.values()) { GetMessageResult getMessageResult...
@Override public Status check() { Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); boolean ok = (maxMemory - (totalMemory - freeMemory) > 2 * 1024 * 1024); // Alarm ...
@Test void test() { MemoryStatusChecker statusChecker = new MemoryStatusChecker(); Status status = statusChecker.check(); assertThat(status.getLevel(), anyOf(is(OK), is(WARN))); logger.info("memory status level: " + status.getLevel()); logger.info("memory status message: " + ...
@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 shouldThrowIfCanNotCoerceToTimestamp() { // Given: final KsqlJsonDeserializer<java.sql.Timestamp> deserializer = givenDeserializerForSchema(Timestamp.SCHEMA, java.sql.Timestamp.class); final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Excepti...
@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 testDecommissionWithExcludeHosts() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode...
@Override public HashSlotCursor16byteKey cursor() { return new CursorLongKey2(); }
@Test(expected = AssertionError.class) public void testCursor_key1_whenDisposed() { HashSlotCursor16byteKey cursor = hsa.cursor(); hsa.dispose(); cursor.key1(); }
public Optional<Search> getForUser(String id, SearchUser searchUser) { final Optional<Search> search = dbService.get(id); search.ifPresent(s -> checkPermission(searchUser, s)); return search; }
@Test public void throwsPermissionExceptionIfNeitherOwnedNorPermittedFromViews() { final Search search = mockSearchWithOwner("someone else"); final SearchUser searchUser = mock(SearchUser.class); when(viewService.forSearch(anyString())).thenReturn(ImmutableList.of()); assertThatExc...
public AcceptState getAcceptState() { return acceptState; }
@Test public void testConstructor() { Verifier verifier = new VerifierNone(); RpcAcceptedReply reply = new RpcAcceptedReply(0, ReplyState.MSG_ACCEPTED, verifier, AcceptState.SUCCESS); assertEquals(0, reply.getXid()); assertEquals(RpcMessage.Type.RPC_REPLY, reply.getMessageType()); assertEq...
public void replayCreateCatalog(Catalog catalog) throws DdlException { String type = catalog.getType(); String catalogName = catalog.getName(); Map<String, String> config = catalog.getConfig(); CatalogConnector catalogConnector = null; try { if (Strings.isNullOrEmpty...
@Test public void testCreate() throws DdlException { CatalogMgr catalogMgr = GlobalStateMgr.getCurrentState().getCatalogMgr(); Map<String, String> config = new HashMap<>(); config.put("type", "paimon"); final ExternalCatalog catalog = new ExternalCatalog(10000, "catalog_0", "", conf...
public static double validateLatitude(double latitude) { if (Double.isNaN(latitude) || latitude < LATITUDE_MIN || latitude > LATITUDE_MAX) { throw new IllegalArgumentException("invalid latitude: " + latitude); } return latitude; }
@Test public void validateLatitudeTest() { LatLongUtils.validateLatitude(LatLongUtils.LATITUDE_MAX); LatLongUtils.validateLatitude(LatLongUtils.LATITUDE_MIN); verifyInvalidLatitude(Double.NaN); verifyInvalidLatitude(Math.nextAfter(LatLongUtils.LATITUDE_MAX, Double.POSITIVE_INFINITY)...
@Override public String deserialize(Asn1ObjectInputStream in) { final String oid = Asn1Utils.decodeObjectIdentifier(in.buffer(), in.position(), in.length); in.advanceToEnd(); return oid; }
@Test public void shouldDeserialize() { assertEquals("1.2.3", deserialize( new ObjectIdentifierConverter(), String.class, new byte[] { 0x2a, 0x03 } )); }
@Override public AnalysisPhase getAnalysisPhase() { return ANALYSIS_PHASE; }
@Test public void testGetAnalysisPhase() { FalsePositiveAnalyzer instance = new FalsePositiveAnalyzer(); AnalysisPhase expResult = AnalysisPhase.POST_IDENTIFIER_ANALYSIS; AnalysisPhase result = instance.getAnalysisPhase(); assertEquals(expResult, result); }
public String getLabel(String labelKey) { Map<String, String> routerLabels = labels.get(RouterConstant.ROUTER_LABELS); if (CollectionUtils.isEmpty(routerLabels)) { return StringUtils.EMPTY; } return routerLabels.get(labelKey); }
@Test public void testGetLabel() { Map<String, String> labels = new HashMap<>(); labels.put("k1", "v1"); labels.put("k2", "v2"); labels.put("k3", "v3"); PolarisRouterContext routerContext = new PolarisRouterContext(); routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels); String resolvedLabel =...
@Override public void refreshPluginDataAll() { BaseDataCache.getInstance().cleanPluginData(); }
@Test public void testRefreshPluginDataAll() { baseDataCache.cleanPluginData(); PluginData firstCachedPluginData = PluginData.builder().name(mockName1).build(); PluginData secondCachedPluginData = PluginData.builder().name(mockName2).build(); baseDataCache.cachePluginData(firstCached...
@Override public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo, List<String> partNames, boolean areAllPartsFound) throws MetaException { checkStatisticsList(colStatsWithSourceInfo); ColumnStatisticsObj statsObj = null; String colType; String colName; B...
@Test public void testAggregateMultiStatsWhenAllAvailable() throws MetaException { List<String> partitions = Arrays.asList("part1", "part2", "part3"); ColumnStatisticsData data1 = new ColStatsBuilder<>(byte[].class).numNulls(1).avgColLen(20.0 / 3).maxColLen(13).build(); ColumnStatisticsData data2 = new C...
public static void checkArgument(boolean expression, String errorMessage) { checkArgument(expression, () -> errorMessage); }
@Test(expected = IllegalArgumentException.class) public void testCheckingIncorrectArgument() { Utils.checkArgument(false, "Error"); }
@Override public Data getValueData() { return serializationService.toData(value); }
@Test public void getValueData_caching() { QueryableEntry entry = createEntry("key", "value"); assertThat(entry.getValueData()).isSameAs(entry.getValueData()); }
public <E extends Enum<E>> void logStateChange( final ClusterEventCode eventCode, final int memberId, final E oldState, final E newState) { final int length = stateChangeLength(oldState, newState); final int captureLength = captureLength(length); final int encodedLength = encodedLeng...
@Test void logStateChange() { final int offset = ALIGNMENT * 11; logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, offset); final TimeUnit from = MINUTES; final TimeUnit to = SECONDS; final int memberId = 42; final String payload = from.name() + STATE_SEPARATOR +...
@Subscribe public void publishClusterEvent(Object event) { if (event instanceof DeadEvent) { LOG.debug("Skipping DeadEvent on cluster event bus"); return; } final String className = AutoValueUtils.getCanonicalName(event.getClass()); final ClusterEvent cluster...
@Test public void testPublishClusterEvent() throws Exception { @SuppressWarnings("deprecation") DBCollection collection = mongoConnection.getDatabase().getCollection(ClusterEventPeriodical.COLLECTION_NAME); SimpleEvent event = new SimpleEvent("test"); assertThat(collection.count())....
@Override public double mean() { return mean; }
@Test public void testMean() { System.out.println("mean"); KernelDensity instance = new KernelDensity(x); double expResult = 3.55417; double result = instance.mean(); assertEquals(expResult, result, 1E-5); }
@Override public ChannelBuffer copy() { return copy(readerIndex, readableBytes()); }
@Test void copyBoundaryCheck3() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(buffer.capacity() + 1, 0)); }
@Override public Collection<String> getXADriverClassNames() { return Collections.singletonList("oracle.jdbc.xa.client.OracleXADataSource"); }
@Test void assertGetXADriverClassName() { assertThat(new OracleXADataSourceDefinition().getXADriverClassNames(), is(Collections.singletonList("oracle.jdbc.xa.client.OracleXADataSource"))); }
public static boolean isValidOrigin(String sourceHost, ZeppelinConfiguration zConf) throws UnknownHostException, URISyntaxException { String sourceUriHost = ""; if (sourceHost != null && !sourceHost.isEmpty()) { sourceUriHost = new URI(sourceHost).getHost(); sourceUriHost = (sourceUriHost ==...
@Test void isValidFromConfig() throws URISyntaxException, UnknownHostException { assertTrue(CorsUtils.isValidOrigin("http://otherhost.com", ZeppelinConfiguration.load("zeppelin-site.xml"))); }
@Override public Map<String, Long> queuesDetail() { Map<String, Long> detail = new HashMap<>(); queues.forEach((k, v) -> detail.put(k, (long) v.size())); return detail; }
@Test public void testQueuesDetail() { String queueName = "test-queue"; String id = "abcd-1234-defg-5678"; queueDao.pushIfNotExists(queueName, id, 123); assertEquals(Collections.singletonMap(queueName, 1L), queueDao.queuesDetail()); }
@Override public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) { List<FetchTask> fetchTasks = pipelineConfig.getFetchTasks(); for (FetchTask fetchTask : fetchTasks) { if (pipelineName.equals(fetchTask.getDirectParentInAncestorPath())) return true; }...
@Test void shouldDetectDependencyMaterialUsedInFetchArtifact() { DependencyMaterial material = new DependencyMaterial(new CaseInsensitiveString("pipeline-foo"), new CaseInsensitiveString("stage-bar")); PipelineConfig pipelineConfig = mock(PipelineConfig.class); ArrayList<FetchTask> fetchTask...
public int validate( final ServiceContext serviceContext, final List<ParsedStatement> statements, final SessionProperties sessionProperties, final String sql ) { requireSandbox(serviceContext); final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext)); ...
@Test public void shouldThrowIfTooManyPersistentQueries() { // Given: when(ksqlConfig.getInt(KsqlConfig.KSQL_ACTIVE_PERSISTENT_QUERY_LIMIT_CONFIG)).thenReturn(1); givenPersistentQueryCount(2); final List<ParsedStatement> statements = givenParsed( "CREATE STREAM sink AS SELECT * FR...
@Override @CacheEvict(cacheNames = RedisKeyConstants.MAIL_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理 public void updateMailTemplate(@Valid MailTemplateSaveReqVO updateReqVO) { // 校验是否存在 validateMailTemplateExists(updateReqVO.getId()); // 校验 code 是否...
@Test public void testUpdateMailTemplate_success() { // mock 数据 MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); mailTemplateMapper.insert(dbMailTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 MailTemplateSaveReqVO reqVO = randomPojo(MailTemplateSaveReqVO.class, o -> ...
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { char subCommand = safeReadLine(reader).charAt(0); String returnCommand = null; if (subCommand == CREATE_VIEW_SUB_COMMAND_NAME) { returnCommand = createJVMView(reader); } el...
@Test public void testSubCommands() { String inputCommand1 = JVMViewCommand.CREATE_VIEW_SUB_COMMAND_NAME + "\n" + "custom" + "\ne\n"; String inputCommand2 = JVMViewCommand.IMPORT_SUB_COMMAND_NAME + "\nro0\n" + "java.util.*" + "\ne\n"; String inputCommand3 = JVMViewCommand.IMPORT_SUB_COMMAND_NAME + "\nro0\n" + "j...
@Input @Optional public String getContainerizingMode() { String property = System.getProperty(PropertyNames.CONTAINERIZING_MODE); return property != null ? property : containerizingMode.get(); }
@Test public void testContainerizingMode() { assertThat(testJibExtension.getContainerizingMode()).isEqualTo("exploded"); }
public String destinationURL(File rootPath, File file) { return destinationURL(rootPath, file, getSrc(), getDest()); }
@Test public void shouldProvideAppendFilePathToDestWhenPathMatchingAtTheRoot() { ArtifactPlan artifactPlan = new ArtifactPlan(ArtifactPlanType.file, "*.jar", "logs"); assertThat(artifactPlan.destinationURL(new File("pipelines/pipelineA"), new File("pipelines/pipelineA/a.jar"))).isEqualTo...
public static <T> T toObj(byte[] json, Class<T> cls) { try { return mapper.readValue(json, cls); } catch (Exception e) { throw new NacosDeserializationException(cls, e); } }
@Test void testToObjFromBytes() { String json = "{\"code\":0,\"data\":{\"string\":\"你好,中国!\",\"integer\":999}}"; RestResult<Map<String, Object>> restResult = JacksonUtils.toObj(json, RestResult.class); assertEquals(0, restResult.getCode()); assertEquals("你好,中国!", restResult....
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsExactly_primitiveDoubleArray_inOrder_failure() { expectFailureWhenTestingThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsExactly(array(2.2, 1.1, 3.3)) .inOrder(); assertFailureKeys( "value of", ...
public Set<GsonUser> getAllGroupMembers(String gitlabUrl, String token, String groupId) { return getMembers(gitlabUrl, token, format(GITLAB_GROUPS_MEMBERS_ENDPOINT + "/all", groupId)); }
@Test public void getAllGroupMembers_whenCallIsSuccessful_deserializesAndReturnsCorrectlyGroupMembers() throws IOException { ArgumentCaptor<Function<String, List<GsonUser>>> deserializerCaptor = ArgumentCaptor.forClass(Function.class); String token = "token-toto"; GitlabToken gitlabToken = new GitlabToke...
public Page<Organization> searchAllOrganizations(Organization org, int pageIndex, int pageSize) { OrganizationRole orgRole = org.getOrganizationRoles().isEmpty() ? new OrganizationRole() : org.getOrganizationRoles().get(0); return organizationRepository.searchAll(org, orgRole, PageRequest.of(pageIndex, ...
@Test public void searchAllOrganizations() { when(repositoryMock.searchAll(any(Organization.class), any(OrganizationRole.class), any(Pageable.class))).thenReturn(getPageOrganizations()); Page<Organization> result = organizationServiceMock.searchAllOrganizations(newOrganization(), 1, 10); v...
public static void preserve(FileSystem targetFS, Path path, CopyListingFileStatus srcFileStatus, EnumSet<FileAttribute> attributes, boolean preserveRawXattrs) throws IOException { // strip out those attributes we don't need a...
@Test public void testPreserveTimestampOnDirectory() throws IOException { FileSystem fs = FileSystem.get(config); EnumSet<FileAttribute> attributes = EnumSet.of(FileAttribute.TIMES); Path dst = new Path("/tmp/abc"); Path src = new Path("/tmp/src"); createDirectory(fs, src); createDirectory(f...
@Override public Set<StoreBuilder<?>> stores() { return transformerSupplier.stores(); }
@Test public void shouldCallStoresOfAdaptedTransformerSupplier() { when(transformerSupplier.stores()).thenReturn(stores); final TransformerSupplierAdapter<String, String, Integer, Integer> adapter = new TransformerSupplierAdapter<>(transformerSupplier); adapter.stores(); }
@Override public BasicTypeDefine<MysqlType> reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.<MysqlType>builder() .name(column.getName()) .nullable(column.isNullable()) .comment...
@Test public void testReconvertString() { Column column = PhysicalColumn.builder() .name("test") .dataType(BasicType.STRING_TYPE) .columnLength(null) .build(); BasicTypeDefine<MysqlType> ...
@PutMapping @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE, signType = SignType.CONSOLE) public Result<Boolean> editNamespace(NamespaceForm namespaceForm) throws NacosException { namespaceForm.validate(); // contains illegal ...
@Test void testEditNamespace() throws NacosException { when(namespaceOperationService.editNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC)).thenReturn(true); Result<Boolean> result = namespaceControllerV2.editNamespace( new NamespaceForm(TEST_NAMESPACE_ID, TEST_...
@Override public List<IndexSegment> getSegments() { List<IndexSegment> segments = new ArrayList<>(_segmentDataManagers.size()); for (SegmentDataManager segmentDataManager : _segmentDataManagers) { if (segmentDataManager.getReferenceCount() > 0) { segments.add(segmentDataManager.getSegment()); ...
@Test public void testGetSegments() { SegmentDataManager sdm1 = mockSegmentDataManager("seg01", false, 1); SegmentDataManager sdm2 = mockSegmentDataManager("seg01", true, 1); DuoSegmentDataManager dsdm = new DuoSegmentDataManager(sdm1, sdm2); assertTrue(dsdm.hasMultiSegments()); assertSame(dsdm.g...
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) { return ConfigInstanceUtil.getNewInstance(clazz, configId, this); }
@Test public void test_map_of_struct() { Slime slime = new Slime(); Cursor map = slime.setObject().setObject("innermap"); map.setObject("one").setLong("foo", 1); map.setObject("two").setLong("foo", 2); MaptypesConfig config = new ConfigPayload(slime).toInstance(MaptypesConfi...
@VisibleForTesting List<String> getEntityTypes() throws IOException { LeveldbIterator iterator = null; try { iterator = getDbIterator(false); List<String> entityTypes = new ArrayList<String>(); iterator.seek(ENTITY_ENTRY_PREFIX); while (iterator.hasNext()) { byte[] key = iterat...
@Test void testGetEntityTypes() throws IOException { List<String> entityTypes = ((LeveldbTimelineStore) store).getEntityTypes(); assertEquals(7, entityTypes.size()); assertEquals("ACL_ENTITY_TYPE_1", entityTypes.get(0)); assertEquals("OLD_ENTITY_TYPE_1", entityTypes.get(1)); assertEquals(entityTyp...
public static StructType convert(Schema schema) { return (StructType) TypeUtil.visit(schema, new TypeToSparkType()); }
@Test public void testSchemaConversionWithMetaDataColumnSchema() { StructType structType = SparkSchemaUtil.convert(TEST_SCHEMA_WITH_METADATA_COLS); List<AttributeReference> attrRefs = scala.collection.JavaConverters.seqAsJavaList(structType.toAttributes()); for (AttributeReference attrRef : attrRe...
@Override public List<String> getServices() { if (!isRegistered.get()) { LOGGER.warning("Query instance must be at the stage that finish registry!"); return Collections.emptyList(); } return RegisterManager.INSTANCE.getServices(); }
@Test public void getServices() { Assert.assertTrue(registerCenterService.getServices().isEmpty()); }
@Override public Long zLexCount(byte[] key, org.springframework.data.domain.Range range) { String min = value(range.getLowerBound(), "-"); String max = value(range.getUpperBound(), "+"); return read(key, StringCodec.INSTANCE, ZLEXCOUNT, key, min, max); }
@Test public void testZLexCount() { StringRedisTemplate redisTemplate = new StringRedisTemplate(); redisTemplate.setConnectionFactory(new RedissonConnectionFactory(redisson)); redisTemplate.afterPropertiesSet(); redisTemplate.boundZSetOps("test").add("1", 10); redisTemplate....
@Override public List<E> subList(int fromIndex, int toIndex) { return Collections.unmodifiableList(underlying).subList(fromIndex, toIndex); }
@Test public void testSubList() { BoundedList<Integer> list = BoundedList.newArrayBacked(3); list.add(1); list.add(2); list.add(3); assertEquals(Arrays.asList(2), list.subList(1, 2)); assertThrows(UnsupportedOperationException.class, () -> list.subList(1, ...
@Override public String pluginNamed() { return PluginEnum.DUBBO.getName(); }
@Test public void pluginNamed() { assertThat(handler.pluginNamed(), is(PluginEnum.DUBBO.getName())); }
public T runWithDelay() throws Exception { try { return execute(); } catch(Exception e) { if (e.getClass().equals(retryExceptionType)){ tries++; if (MAX_RETRIES == tries) { throw e; } else { Thread.sleep((long) DELAY * tries); return runWithDelay...
@Test public void testRetryFailureWithDelay() { Retry<Void> retriable = new Retry<Void>(NullPointerException.class) { @Override public Void execute() { throw new RuntimeException(); } }; try { retriable.runWithDelay(); Assert.fail(); } catch (Exception e) { ...
@Override public void start() { boolean hasExternalPlugins = pluginRepository.getPlugins().stream().anyMatch(plugin -> plugin.getType().equals(PluginType.EXTERNAL)); try (DbSession session = dbClient.openSession(false)) { PropertyDto property = Optional.ofNullable(dbClient.propertiesDao().selectGlobalPr...
@Test public void consent_does_not_change_when_value_is_required() { setupExternalPluginConsent(REQUIRED); setupExternalPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(REQUIRED.name...
@Override public boolean skip(final ServerWebExchange exchange) { return skipExcept(exchange, RpcTypeEnum.MOTAN); }
@Test public void testSkip() { final boolean result = motanPlugin.skip(exchange); Assertions.assertTrue(result); }
public final Strictness getStrictness() { return strictness; }
@Test public void testDefaultStrictness() { JsonReader reader = new JsonReader(reader("{}")); assertThat(reader.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); }
public static ComputeStepSyntaxElement<SplitDataset> splitDataset( final Collection<Dataset> parents, final EventCondition condition) { final ClassFields fields = new ClassFields(); final ValueSyntaxElement ifData = fields.add(new ArrayList<>()); final ValueSyntaxElement else...
@Test public void compilesSplitDataset() { final FieldReference key = FieldReference.from("foo"); final SplitDataset left = DatasetCompiler.splitDataset( Collections.emptyList(), event -> event.getEvent().includes(key) ).instantiate(); final Event trueEvent = new Event();...
@Override public String getString(int rowIndex, int columnIndex) { if (columnIndex != 0) { throw new IllegalArgumentException("Column index must always be 0 for aggregation result sets"); } if (rowIndex != 0) { throw new IllegalArgumentException("Row index must always be 0 for aggregation res...
@Test(expectedExceptions = IllegalArgumentException.class) public void testGetStringForNonZeroRow() { // Run the test _aggregationResultSetUnderTest.getString(1, 0); }
@Override protected String toHtmlDisplay(Element element, String query) { String label = element.getLabel(); int index = label.toLowerCase().indexOf(query.toLowerCase()); String before = label.substring(0, index); String match = label.substring(index, index + query.length()); ...
@Test public void testHtmlMiddle() { Mockito.when(node.getLabel()).thenReturn("foobar"); Assert.assertTrue( new FuzzyElementLabelSearchProvider().toHtmlDisplay(node, "oo").contains("f<b>oo</b>bar")); }
public static <T> Write<T> write() { return new AutoValue_SnsIO_Write.Builder<T>() .setClientConfiguration(ClientConfiguration.builder().build()) .build(); }
@Test public void testWriteWithoutTopicArn() { List<String> input = ImmutableList.of("message1", "message2"); when(sns.publish(any(PublishRequest.class))) .thenReturn(PublishResponse.builder().messageId("id").build()); Write<String> snsWrite = SnsIO.<String>write().withPublishRequestBuil...
public static void copyBody(Message source, Message target) { // Preserve the DataType if both messages are DataTypeAware if (source.hasTrait(MessageTrait.DATA_AWARE)) { target.setBody(source.getBody()); target.setPayloadForTrait(MessageTrait.DATA_AWARE, sourc...
@Test void shouldCopyBodyIfBothNotDataTypeAware() { Object body = new Object(); Message m1 = new MyMessageType(body); Message m2 = new MyMessageType(new Object()); copyBody(m1, m2); assertSame(body, m2.getBody()); }
public static String computeQueryHash(String query) { requireNonNull(query, "query is null"); if (query.isEmpty()) { return ""; } byte[] queryBytes = query.getBytes(UTF_8); long queryHash = new XxHash64().update(queryBytes).hash(); return toHexString(que...
@Test public void testComputeQueryHash() { String query = "SELECT * FROM CUSTOMER LIMIT 5"; assertEquals(computeQueryHash(query), "7f3325a942b43504"); }
@Override public void upgrade() { if (hasBeenRunSuccessfully()) { LOG.debug("Migration already completed."); return; } final Map<String, String> savedSearchToViewsMap = new HashMap<>(); final Map<View, Search> newViews = this.savedSearchService.streamAll() ...
@Test @MongoDBFixtures("sample_saved_search_keyword_with_interval_field.json") public void migrateSavedSearchKeywordWithIntervalField() throws Exception { this.migration.upgrade(); final MigrationCompleted migrationCompleted = captureMigrationCompleted(); assertThat(migrationCompleted.s...
static boolean apply(@Nullable HttpStatus httpStatus) { if (Objects.isNull(httpStatus)) { return false; } RpcEnhancementReporterProperties reportProperties; try { reportProperties = ApplicationContextAwareUtils.getApplicationContext() .getBean(RpcEnhancementReporterProperties.class); } catch (Bea...
@Test public void testApplyWithIgnoreInternalServerError() { RpcEnhancementReporterProperties properties = new RpcEnhancementReporterProperties(); // Mock Condition properties.getStatuses().clear(); properties.setIgnoreInternalServerError(true); ApplicationContext applicationContext = mock(ApplicationContex...
static void setStaticGetter(final RegressionCompilationDTO compilationDTO, final LinkedHashMap<String, KiePMMLTableSourceCategory> regressionTablesMap, final MethodDeclaration staticGetterMethod, ...
@Test void setStaticGetter() throws IOException { String variableName = "variableName"; RegressionTable regressionTableProf = getRegressionTable(3.5, "professional"); RegressionTable regressionTableCler = getRegressionTable(27.4, "clerical"); OutputField outputFieldCat = getOutputFie...
@Override public int channel(CommittableMessage<MultiTableCommittable> committableMessage) { if (committableMessage instanceof CommittableWithLineage) { MultiTableCommittable multiTableCommittable = ((CommittableWithLineage<MultiTableCommittable>) committableMessage) ...
@Test public void testChannel() { MultiTableCommittableChannelComputer computer = new MultiTableCommittableChannelComputer(); computer.setup(4); List<MultiTableCommittable> commits = Arrays.asList( new MultiTableCommittable("database", "table1", 1L, nu...
public static SslProvider getSslProvider(String provider) { if (SslProvider.OPENSSL.name().equalsIgnoreCase(provider)) { return SslProvider.OPENSSL; } if (SslProvider.JDK.name().equalsIgnoreCase(provider)) { return SslProvider.JDK; } if (SslProvider.OPENSS...
@Test void test() { SslProvider openssl = TlsTypeResolve.getSslProvider("openssl"); assertEquals(SslProvider.OPENSSL, openssl); SslProvider openSsL = TlsTypeResolve.getSslProvider("openSSL"); assertEquals(SslProvider.OPENSSL, openSsL); SslProvider j...
@Udf(description = "Converts an INT value in degrees to a value in radians") public Double radians( @UdfParameter( value = "value", description = "The value in degrees to convert to radians." ) final Integer value ) { return radians(value == null ? null : ...
@Test public void shouldHandleNull() { assertThat(udf.radians((Integer) null), is(nullValue())); assertThat(udf.radians((Long) null), is(nullValue())); assertThat(udf.radians((Double) null), is(nullValue())); }
@Override public int getInt(final int columnIndex) throws SQLException { return (int) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, int.class), int.class); }
@Test void assertGetIntWithColumnLabel() throws SQLException { when(mergeResultSet.getValue(1, int.class)).thenReturn((short) 1); assertThat(shardingSphereResultSet.getInt("label"), is(1)); }
public static Builder route() { return new RouterFunctionBuilder(); }
@Test void andOther() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().body("42"); RouterFunction<?> routerFunction1 = request -> Optional.empty(); RouterFunction<ServerResponse> routerFunction2 = request -> Optional.of(handlerFunction); RouterFunction<?> result = routerFunct...
@Override public String description() { return "ChronoLocalDateTime.timeLineOrder()"; }
@Test void should_have_description() { assertThat(comparator.description()).isEqualTo("ChronoLocalDateTime.timeLineOrder()"); }
public static <T extends DataflowWorkerHarnessOptions> T initializeGlobalStateAndPipelineOptions( Class<?> workerHarnessClass, Class<T> harnessOptionsClass) throws Exception { /* Extract pipeline options. */ T pipelineOptions = WorkerPipelineOptionsFactory.createFromSystemProperties(harnessOptions...
@Test public void testStreamingStreamingConfiguration() throws Exception { DataflowWorkerHarnessOptions pipelineOptions = PipelineOptionsFactory.as(DataflowWorkerHarnessOptions.class); pipelineOptions.setJobId(JOB_ID); pipelineOptions.setWorkerId(WORKER_ID); int activeWorkRefreshPeriodMillis =...
public void to(Action<? super TargetImageParameters> action) { action.execute(to); }
@Test public void testTo() { assertThat(testJibExtension.getTo().getImage()).isNull(); assertThat(testJibExtension.getTo().getCredHelper().getHelper()).isNull(); testJibExtension.to( to -> { to.setImage("some image"); to.setCredHelper("some cred helper"); to.auth(aut...
@SuppressWarnings("unchecked") public <IN, OUT> AvroDatumConverter<IN, OUT> create(Class<IN> inputClass) { boolean isMapOnly = ((JobConf) getConf()).getNumReduceTasks() == 0; if (AvroKey.class.isAssignableFrom(inputClass)) { Schema schema; if (isMapOnly) { schema = AvroJob.getMapOutputKeyS...
@Test void convertLongWritable() { AvroDatumConverter<LongWritable, Long> converter = mFactory.create(LongWritable.class); assertEquals(123L, converter.convert(new LongWritable(123L)).longValue()); }
@Override public Collection<String> doSharding(final Collection<String> availableTargetNames, final HintShardingValue<Comparable<?>> shardingValue) { return shardingValue.getValues().isEmpty() ? availableTargetNames : shardingValue.getValues().stream().map(this::doSharding).collect(Collectors.toList()); ...
@Test void assertDoShardingWithSingleValue() { List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3"); HintShardingValue<Comparable<?>> shardingValue = new HintShardingValue<>("t_order", "order_id", Collections.singleton(4)); Collection<String> ...
public void undelete() { // make a copy because the selected trash items changes as soon as trashService.undelete is called List<UIDeletedObject> selectedTrashFileItemsSnapshot = new ArrayList<UIDeletedObject>( selectedTrashFileItems ); if ( selectedTrashFileItemsSnapshot != null && selectedTrashFileItemsSn...
@Test public void testUnDeleteJob() throws Exception { testUnDelete( RepositoryObjectType.JOB.name(), true ); verify( trashServiceMock, times( 1 ) ).undelete( anyList() ); verify( transMetaMock, never() ).clearChanged(); verify( repositoryMock, never() ).loadTransformation( objectIdMock, null ); ...
public EBPFProfilingAnalyzation analyze(List<String> scheduleIdList, List<EBPFProfilingAnalyzeTimeRange> ranges, EBPFProfilingAnalyzeAggregateType aggregateType) throws IOException { EBPFProfilingAnalyzation analyzation = ne...
@Test public void testAnalyze() throws IOException { EBPFProfilingAnalyzerHolder holder = loadYaml("ebpf-profiling-data.yml", EBPFProfilingAnalyzerHolder.class); for (int c = 0; c < holder.getList().size(); c++) { try { holder.getList().get(c).analyzeAssert(); ...
@Override public String ping(RedisClusterNode node) { return execute(node, RedisCommands.PING); }
@Test public void testClusterPing() { RedisClusterNode master = getFirstMaster(); String res = connection.ping(master); assertThat(res).isEqualTo("PONG"); }