focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Deprecated @Restricted(DoNotUse.class) public static String resolve(ConfigurationContext context, String toInterpolate) { return context.getSecretSourceResolver().resolve(toInterpolate); }
@Test public void resolve_JsonWithNewlineBetweenTokens() { String input = "{ \n \"a\": 1, \n \"b\": 2 }"; environment.set("FOO", input); String output = resolve("${json:a:${FOO}}"); assertThat(output, equalTo("1")); }
@Override public TListTableStatusResult listTableStatus(TGetTablesParams params) throws TException { LOG.debug("get list table request: {}", params); TListTableStatusResult result = new TListTableStatusResult(); List<TTableStatus> tablesResult = Lists.newArrayList(); result.setTables...
@Test public void testListViewStatusWithBaseTableDropped() throws Exception { starRocksAssert.useDatabase("test") .withTable("CREATE TABLE site_access_empty_for_view (\n" + " event_day DATETIME NOT NULL,\n" + " site_id INT DEFAULT '10',\n...
public static String getInterfaceName(Invoker invoker) { return getInterfaceName(invoker, false); }
@Test public void testGetInterfaceName() { URL url = URL.valueOf("dubbo://127.0.0.1:2181") .addParameter(CommonConstants.VERSION_KEY, "1.0.0") .addParameter(CommonConstants.GROUP_KEY, "grp1") .addParameter(CommonConstants.INTERFACE_KEY, DemoService.class.getN...
@ExecuteOn(TaskExecutors.IO) @Get(uri = "logs/{executionId}/download", produces = MediaType.TEXT_PLAIN) @Operation(tags = {"Logs"}, summary = "Download logs for a specific execution, taskrun or task") public StreamedFile download( @Parameter(description = "The execution id") @PathVariable String exe...
@Test void download() { LogEntry log1 = logEntry(Level.INFO); LogEntry log2 = log1.toBuilder().message("another message").build(); LogEntry log3 = logEntry(Level.DEBUG); logRepository.save(log1); logRepository.save(log2); logRepository.save(log3); String logs...
public static String getSecondaryNameServiceId(Configuration conf) { return getNameServiceId(conf, DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY); }
@Test public void getSecondaryNameServiceId() { Configuration conf = setupAddress(DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY); assertEquals("nn1", DFSUtil.getSecondaryNameServiceId(conf)); }
public boolean evaluateIfActiveVersion(UpdateCenter updateCenter) { Version installedVersion = Version.create(sonarQubeVersion.get().toString()); if (compareWithoutPatchVersion(installedVersion, updateCenter.getSonar().getLtaVersion().getVersion()) == 0) { return true; } SortedSet<Release> allRel...
@Test void evaluateIfActiveVersion_whenInstalledVersionIsPastLtaAndReleaseDateIsMissing_shouldThrowIllegalStateException() { when(sonarQubeVersion.get()).thenReturn(parse("8.9.5")); SortedSet<Release> releases = getReleases(); when(sonar.getAllReleases()).thenReturn(releases); assertThatThrownBy(() ...
public static void v(String tag, String message, Object... args) { sLogger.v(tag, message, args); }
@Test public void verbose() { String tag = "TestTag"; String message = "Test message"; LogManager.v(tag, message); verify(logger).v(tag, message); }
@Override public LoggingObjectInterface getParent() { return null; }
@Test public void testGetParent() { assertNull( meta.getParent() ); }
@Override public boolean doOffer(final Runnable runnable) { return super.offer(runnable); }
@Test public void testOfferWhenMemoryNotSufficient() { MemoryLimitedTaskQueue memoryLimitedTaskQueue = new MemoryLimitedTaskQueue<>(1, instrumentation); assertFalse(memoryLimitedTaskQueue.doOffer(() -> { })); }
public NodeMgr getNodeMgr() { return nodeMgr; }
@Test(expected = DdlException.class) public void testUpdateFeNotFoundException() throws Exception { GlobalStateMgr globalStateMgr = mockGlobalStateMgr(); ModifyFrontendAddressClause clause = new ModifyFrontendAddressClause("test", "sandbox-fqdn"); // this case will occur [frontend does not e...
public void begin(InterpretationContext ec, String localName, Attributes attributes) { if ("substitutionProperty".equals(localName)) { addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead."); } String name = attributes.getValue(NAME_ATTRIBUTE);...
@Test public void noName() { atts.setValue("value", "v1"); propertyAction.begin(ec, null, atts); assertEquals(1, context.getStatusManager().getCount()); assertTrue(checkError()); }
public void appendDocument(PDDocument destination, PDDocument source) throws IOException { if (source.getDocument().isClosed()) { throw new IOException("Error: source PDF is closed."); } if (destination.getDocument().isClosed()) { throw new IOException...
@Test void testStructureTreeMerge2() throws IOException { PDFMergerUtility pdfMergerUtility = new PDFMergerUtility(); PDDocument doc = Loader .loadPDF(new File(TARGETPDFDIR, "PDFBOX-3999-GeneralForbearance.pdf")); doc.getDocumentCatalog().getAcroForm().flatten(); ...
static void validateCsvFormat(CSVFormat format) { String[] header = checkArgumentNotNull(format.getHeader(), "Illegal %s: header is required", CSVFormat.class); checkArgument(header.length > 0, "Illegal %s: header cannot be empty", CSVFormat.class); checkArgument( !format.getAllowMissingCo...
@Test public void givenCSVFormatThatAllowsMissingColumnNames_throwsException() { CSVFormat format = csvFormatWithHeader().withAllowMissingColumnNames(true); String gotMessage = assertThrows( IllegalArgumentException.class, () -> CsvIOParseHelpers.validateCsvFormat(format)) ...
private void readPriorityFrame(ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { long word1 = payload.readUnsignedInt(); boolean exclusive = (word1 & 0x80000000L) != 0; int streamDependency = (int) (word1 & 0x7FFFFFFFL); if (stre...
@Test public void readPriorityFrame() throws Http2Exception { ByteBuf input = Unpooled.buffer(); try { writePriorityFrame(input, 1, 0, 10); frameReader.readFrame(ctx, input, listener); } finally { input.release(); } }
@Override public boolean updateGlobalWhiteAddrsConfig(List<String> globalWhiteAddrsList) { return aclPlugEngine.updateGlobalWhiteAddrsConfig(globalWhiteAddrsList); }
@Test public void updateGlobalWhiteRemoteAddressesTest() throws InterruptedException { String backupFileName = System.getProperty("rocketmq.home.dir") + File.separator + "conf/plain_acl_bak.yml".replace("/", File.separator); String targetFileName = System.getProperty("rocketmq.home.d...
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { Collection<TableMetaData> tableMetaDataList = new LinkedList<>(); try (Connection connection = new MetaDataLoaderConnection(TypedSPILoader.getService(DatabaseType.class, "Oracle"), material....
@Test void assertLoadCondition6() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet resultSet = mockTableMetaDataResultSet(); when(dataSource.getConnection().prepareStatement(ALL_TAB_COLUMNS_SQL_CONDITION6).executeQuery()).thenReturn(resultSet); ResultSet inde...
public static <T> CloseableIterator<T> concat(CloseableIterator<T> a, CloseableIterator<T> b) { return concat(Lists.newArrayList(a, b)); }
@Test public void concatList() { ArrayList<Integer> list1 = Lists.newArrayList(1, 2); ArrayList<Integer> list2 = Lists.newArrayList(3, 4, 5); ArrayList<Integer> list3 = Lists.newArrayList(0); TestIterator iterator1 = new TestIterator(list1); TestIterator iterator2 = new TestIterator(list2); Te...
@Override public void writeCallSite(CallSiteReference callSiteReference) throws IOException { writeSimpleName(callSiteReference.getName()); writer.write('('); writeQuotedString(callSiteReference.getMethodName()); writer.write(", "); writeMethodProtoDescriptor(callSiteReference.ge...
@Test public void testWriteCallsite_withSpaces() throws IOException { BaksmaliWriter writer = new BaksmaliWriter(output); writer.writeCallSite(new ImmutableCallSiteReference( "callsiteName with spaces", getInvokeStaticMethodHandleReferenceForMethodWithSpaces(), ...
public static String jaasConfig(String moduleName, Map<String, String> options) { StringJoiner joiner = new StringJoiner(" "); for (Entry<String, String> entry : options.entrySet()) { String key = Objects.requireNonNull(entry.getKey()); String value = Objects.requireNonNull(entry...
@Test public void testModuleNameContainsSemicolon() { Map<String, String> options = new HashMap<>(); options.put("key1", "value1"); String moduleName = "Module;"; assertThrows(IllegalArgumentException.class, () -> AuthenticationUtils.jaasConfig(moduleName, options)); }
@Override public void notifyGroup(final Map<String, ConfigChangeEvent> groupItems) { groupItems.forEach((groupItemName, event) -> { if (EventType.DELETE.equals(event.getEventType())) { this.openapiDefs.remove(groupItemName); log.info("EndpointNameGroupingRule4Open...
@Test public void testWatcher() throws FileNotFoundException { EndpointNameGrouping endpointNameGrouping = new EndpointNameGrouping(); EndpointNameGroupingRule4OpenapiWatcher watcher = new EndpointNameGroupingRule4OpenapiWatcher( new ModuleProvider() { @Override ...
public static ConfigInfos generateResult(String connType, Map<String, ConfigKey> configKeys, List<ConfigValue> configValues, List<String> groups) { int errorCount = 0; List<ConfigInfo> configInfoList = new LinkedList<>(); Map<String, ConfigValue> configValueMap = new HashMap<>(); for (C...
@Test public void testGenerateResultWithConfigValuesMoreThanConfigKeysAndWithSomeErrors() { String name = "com.acme.connector.MyConnector"; Map<String, ConfigDef.ConfigKey> keys = new HashMap<>(); addConfigKey(keys, "config.a1", null); addConfigKey(keys, "config.b1", "group B"); ...
@Override public void init(byte[] data, int offset) { this.data = data; this.size = data != null ? data.length : 0; this.pos = offset; }
@Test public void testInit() { in.init(INIT_DATA, 2); assertArrayEquals(INIT_DATA, in.data); assertEquals(INIT_DATA.length, in.size); assertEquals(2, in.pos); }
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldCoerceToInts() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( new IntegerLiteral(10), new StringLiteral("\t -100 \t"), INT_EXPRESSION ); // When: final Result result = CoercionUtil.coerceUserList(expressions, typeManager...
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "lookupConstraints is ImmutableList") public List<LookupConstraint> getLookupConstraints() { return lookupConstraints; }
@SuppressWarnings("unchecked") @Test public void shouldExtractConstraintWithMultipleKeyExpressions_tableScan() { // Given: when(plannerOptions.getTableScansEnabled()).thenReturn(true); final Expression expression1 = new ComparisonExpression( Type.EQUAL, new UnqualifiedColumnReferenceExp(...
protected static String getPropertyNameFromBeanReadMethod(Method method) { if (isBeanPropertyReadMethod(method)) { if (method.getName().startsWith("get")) { return method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); } ...
@Test public void testGetPropertyNameFromBeanReadMethod() throws Exception { Method method = TestReflect.class.getMethod("getS"); Assert.assertEquals("s", getPropertyNameFromBeanReadMethod(method)); method = TestReflect.class.getMethod("getName"); Assert.assertEquals("name", getProp...
@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_non_serializable_object() { Object original = new NonSerializableObject("value"); Object cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSame(original, cloned); }
@Nonnull public static String remove(@Nonnull String text, int removeIndex, int removeLength) { if (removeIndex < 0 || removeIndex >= text.length()) return text; String pre = text.substring(0, removeIndex); String post = text.substring(Math.min(removeIndex + removeLength, text.length())); return pre + post; }
@Test void testRemove() { assertEquals("demo", StringUtil.remove("demo", -1, 4)); assertEquals("demo", StringUtil.remove("demo", 999, 4)); assertEquals("do", StringUtil.remove("demo", 1, 2)); assertEquals("", StringUtil.remove("demo", 0, 4)); assertEquals("", StringUtil.remove("demo", 0, 999)); }
@GET @Path("/{logger}") @Operation(summary = "Get the log level for the specified logger") public Response getLogger(final @PathParam("logger") String namedLogger) { Objects.requireNonNull(namedLogger, "require non-null name"); LoggerLevel loggerLevel = herder.loggerLevel(namedLogger); ...
@Test public void testGetLevelNotFound() { final String logger = "org.apache.rostropovich"; when(herder.loggerLevel(logger)).thenReturn(null); assertThrows( NotFoundException.class, () -> loggingResource.getLogger(logger) ); }
public IntHashSet difference(final IntHashSet other) { IntHashSet difference = null; final int[] values = this.values; for (final int value : values) { if (MISSING_VALUE != value && !other.contains(value)) { if (null == difference) ...
@Test void differenceReturnsNullIfBothSetsEqual() { addTwoElements(testSet); final IntHashSet other = new IntHashSet(100); addTwoElements(other); assertNull(testSet.difference(other)); }
@Override public synchronized void cleanupAll() { LOG.info("Attempting to clean up Neo4j manager."); boolean producedError = false; // First, delete the database if it was not given as a static argument try { if (!usingStaticDatabase) { dropDatabase(databaseName, waitOption); } ...
@Test public void testCleanupAllShouldThrowErrorWhenNeo4jDriverFailsToClose() { doThrow(RuntimeException.class).when(neo4jDriver).close(); assertThrows(Neo4jResourceManagerException.class, () -> testManager.cleanupAll()); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void forwardMessage() { SendResponse response = bot.execute(new ForwardMessage(chatId, chatId, forwardMessageId).disableNotification(true)); Message message = response.message(); MessageTest.checkMessage(message); assertNotNull(message.forwardDate()); assertNotNu...
public EndpointResponse get() { return EndpointResponse.ok(new ServerInfo( appVersion.get(), kafkaClusterId.get(), ksqlServiceId.get(), serverStatus.get().toString())); }
@Test public void shouldReturnServerInfo() { // When: final EndpointResponse response = serverInfoResource.get(); // Then: assertThat(response.getStatus(), equalTo(200)); assertThat(response.getEntity(), instanceOf(ServerInfo.class)); final ServerInfo serverInfo = (ServerInfo)response.getEnti...
@Override public GetApplicationsResponse getApplications(GetApplicationsRequest request) throws YarnException, IOException { long startedBegin = request.getStartRange() == null ? 0L : request.getStartRange() .getMinimum(); long startedEnd = request.getStartRange() == ...
@Test void testApplications() throws IOException, YarnException { ApplicationId appId = null; appId = ApplicationId.newInstance(0, 1); ApplicationId appId1 = ApplicationId.newInstance(0, 2); GetApplicationsRequest request = GetApplicationsRequest.newInstance(); GetApplicationsResponse response = ...
@Override public V get() throws InterruptedException, ExecutionException { try { return get(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new ExecutionException(e); } }
@Test public void completeDelegate_successfully_callbackBeforeGet_invokeGetOnOuter_callbacksRun() throws Exception { BiConsumer<String, Throwable> callback = getStringExecutionCallback(); delegateFuture.run(); outerFuture.whenCompleteAsync(callback, CALLER_RUNS); outerFuture.get(); ...
public static String trimQueueName(String name) { if (name == null) { return null; } int start = 0; while (start < name.length() && isWhitespace(name.charAt(start)) && start < name.length()) { start++; } int end = name.length() - 1; while (end >= 0 && isWh...
@Test public void testTrimQueueNamesEmpty() throws Exception { assertNull(trimQueueName(null)); final String spaces = "\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000" + "\u2029\u000B\u3000\u2008\u2003\u205F\u3000\u1680" + "\u0009\u0020\u2006\u2001\u202F\u00A0\u000C\u2009" + "\u3000\u2004...
@Override public void print(Iterator<RowData> it, PrintWriter printWriter) { if (!it.hasNext()) { printEmptyResult(it, printWriter); return; } long numRows = printTable(it, printWriter); printFooter(printWriter, numRows); }
@Test void testPrintWithMultipleRowsAndDeriveColumnWidthByContent() { PrintStyle.tableauWithDataInferredColumnWidths( getSchema(), getConverter(), PrintStyle.DEFAULT_MAX_COLUMN_WIDTH, true, ...
public String getEndpointsInfo() { return loggingListener.getEndpointsInfo(); }
@Test void logsNoInterfaces() { rc.packages(getClass().getName()); runJersey(); assertThat(rc.getEndpointsInfo()).doesNotContain("io.dropwizard.jersey.DropwizardResourceConfigTest.ResourceInterface"); }
@Override public Stream<MappingField> resolveAndValidateFields( boolean isKey, List<MappingField> userFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(userF...
@Test public void when_duplicateExternalName_then_throws() { assertThatThrownBy(() -> INSTANCE.resolveAndValidateFields( isKey, List.of( field("field1", QueryDataType.INT, prefix + ".field"), field("field2", QueryDataType.VARCHA...
@Override public TransformResultMetadata getResultMetadata() { return _resultMetadata; }
@Test public void testArrayIndexOfAllString() { ExpressionContext expression = RequestContextUtils.getExpression( String.format("array_indexes_of_string(%s, 'a')", STRING_ALPHANUM_MV_COLUMN_2)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertT...
@Override public ChatAdministratorRights deserializeResponse(String answer) throws TelegramApiRequestException { return deserializeResponse(answer, ChatAdministratorRights.class); }
@Test public void testGetMyDefaultAdministratorRightsDeserializeValidResponse() { String responseText = "{\n" + " \"ok\": true,\n" + " \"result\": {\n" + " \"is_anonymous\": true,\n" + " \"can_manage_chat\": true,\n" + ...
public void setActiveState(boolean active) { if (mLogicalState == LOCKED) return; mLogicalState = active ? ACTIVE : INACTIVE; if (mLogicalState == ACTIVE) { // setting the start time to zero, so LOCKED state will not // be activated without actual user's double-clicking mActiveStateStartT...
@Test public void testSetActiveState() throws Exception { long millis = 1000; setCurrentTimeMillis(++millis); ModifierKeyState state = new ModifierKeyState(true); Assert.assertFalse(state.isActive()); Assert.assertFalse(state.isLocked()); Assert.assertFalse(state.isPressed()); state.setA...
public static boolean match(String pattern, String string) { assertSingleByte(string); return match(pattern.getBytes(StandardCharsets.US_ASCII), string.getBytes(StandardCharsets.US_ASCII)); }
@Test public void testValidInputs() { assertFalse(GlobMatcher.match("a*b", "aaa")); assertFalse(GlobMatcher.match("a*a*b", "aaaa")); // Hangs when parsing as regex. assertFalse(GlobMatcher.match("a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b", "a".repeat(55))); assertTrue(GlobMatcher.matc...
public TimestampOffset lookup(long targetTimestamp) { return maybeLock(lock, () -> { ByteBuffer idx = mmap().duplicate(); int slot = largestLowerBoundSlotFor(idx, targetTimestamp, IndexSearchType.KEY); if (slot == -1) return new TimestampOffset(RecordBatch.NO_...
@Test public void testLookUp() { // Empty time index assertEquals(new TimestampOffset(-1L, baseOffset), idx.lookup(100L)); // Add several time index entries. appendEntries(maxEntries - 1); // look for timestamp smaller than the earliest entry assertEquals(new Timest...
@Override public boolean containsObject(K name, Object value) { return false; }
@Test public void testContainsObject() { assertFalse(HEADERS.containsObject("name1", "")); }
@Override public IExpressionObjectFactory getExpressionObjectFactory() { return LINK_EXPRESSION_OBJECTS_FACTORY; }
@Test void getExpressionObjectFactory() { assertThat(linkExpressionObjectDialect.getName()) .isEqualTo("themeLink"); assertThat(linkExpressionObjectDialect.getExpressionObjectFactory()) .isInstanceOf(DefaultLinkExpressionFactory.class); }
@Override public void loginWithKey(String loginIDKey, String loginId) { }
@Test public void testLoginWithKey() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); ...
private <T> RFuture<T> pollEntry(int from, int to, RedisCommand<?> command) { return commandExecutor.evalWriteAsync(getRawName(), codec, command, "local v = redis.call('zrange', KEYS[1], ARGV[1], ARGV[2], 'withscores'); " + "if #v > 0 then " + "redis.c...
@Test public void testPollEntry() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("test"); set.add(1.1, "v1"); set.add(1.2, "v2"); set.add(1.3, "v3"); ScoredEntry<String> e = set.pollFirstEntry(); assertThat(e).isEqualTo(new ScoredEntry<>(1.1, "v1")); ...
@SuppressWarnings("unchecked") public <T extends Expression> T rewrite(final T expression, final C context) { return (T) rewriter.process(expression, context); }
@Test public void shouldRewriteType() { // Given: final Type type = new Type(SqlPrimitiveType.of("INTEGER")); // When: final Expression rewritten = expressionRewriter.rewrite(type, context); // Then: assertThat(rewritten, is(type)); }
@Override protected String getFolderSuffix() { return FOLDER_SUFFIX; }
@Test public void testGetFolderSuffix() { Assert.assertEquals("/", mOSSUnderFileSystem.getFolderSuffix()); }
@Override public OrganizedImports organizeImports(List<Import> imports) { Map<PackageType, ImmutableSortedSet<Import>> partitioned = imports.stream() .collect( Collectors.groupingBy( IdeaImportOrganizer::getPackageType, TreeMap::new, ...
@Test public void staticLastOrdering() { IdeaImportOrganizer organizer = new IdeaImportOrganizer(); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import android.foo;\n" + "import com.a...
public List<HttpClientRequestInterceptor> getInterceptors() { return interceptors; }
@Test void testGetInterceptors() { assertTrue(restTemplate.getInterceptors().isEmpty()); restTemplate.setInterceptors(Collections.singletonList(interceptor)); assertEquals(1, restTemplate.getInterceptors().size()); }
public static Optional<String> getDatabaseName(final String configNodeFullPath) { Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(configNodeFullPath); return matcher.find() ? Optional.of(matcher.gro...
@Test void assertGetDatabaseNameDbNameNotFoundScenario() { assertThat(ShardingSphereDataNode.getDatabaseName("/statistics/databases"), is(Optional.empty())); }
public static Schema createEnum(String name, String doc, String namespace, List<String> values) { return new EnumSchema(new Name(name, namespace), doc, new LockableArrayList<>(values), null); }
@Test void enumSymbolAsNull() { assertThrows(SchemaParseException.class, () -> { Schema.createEnum("myField", "doc", "namespace", Collections.singletonList(null)); }); }
@Override public void close() throws IOException { channel.close(); }
@Test(expected = RuntimeException.class) public void testVersionMismatch() throws IOException { FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE); channel.write(ByteBuffer.wrap(new byte[] { '2' })); channel.close(); RecordIOReader reader = new RecordIOReader(file...
public static Builder withSchema(Schema schema) { return new Builder(schema); }
@Test public void testCreateWithNames() { Schema type = Stream.of( Schema.Field.of("f_str", FieldType.STRING), Schema.Field.of("f_byte", FieldType.BYTE), Schema.Field.of("f_short", FieldType.INT16), Schema.Field.of("f_int", FieldType.INT32), ...
public final String toBitString(long value) { return toBitString(value, 64); }
@Test public void testToBitString() { assertEquals("0010101010101010101010101010101010101010101010101010101010101010", bitUtil.toBitString(Long.MAX_VALUE / 3)); assertEquals("0111111111111111111111111111111111111111111111111111111111111111", bitUtil.toBitString(Long.MAX_VALUE)); assertEqual...
static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) throws FormatterException { Context context = new Context(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options...
@Test public void testFormatLengthOutOfRange() throws Exception { String input = "class Foo{}\n"; Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); Files.writeString(path, input); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(...
static void closeStateManager(final Logger log, final String logPrefix, final boolean closeClean, final boolean eosEnabled, final ProcessorStateManager stateMgr, ...
@Test public void testCloseStateManagerThrowsExceptionWhenClean() { when(stateManager.taskId()).thenReturn(taskId); when(stateDirectory.lock(taskId)).thenReturn(true); doThrow(new ProcessorStateException("state manager failed to close")).when(stateManager).close(); final ProcessorSt...
protected Map<String, String> parseJettyOptions( Node node ) { Map<String, String> jettyOptions = null; Node jettyOptionsNode = XMLHandler.getSubNode( node, XML_TAG_JETTY_OPTIONS ); if ( jettyOptionsNode != null ) { jettyOptions = new HashMap<String, String>(); if ( XMLHandler.getTagValue( j...
@Test public void testParseJettyOption_AcceptQueueSize() throws KettleXMLException { Node configNode = getConfigNode( getConfigWithAcceptQueueSizeOnlyOption() ); Map<String, String> parseJettyOptions = slServerConfig.parseJettyOptions( configNode ); assertNotNull( parseJettyOptions ); assertEquals( ...
public void mergeRuntimeUpdate( List<TimelineEvent> pendingTimeline, Map<String, Artifact> pendingArtifacts) { if (timeline.addAll(pendingTimeline)) { synced = false; } if (pendingArtifacts != null && !pendingArtifacts.isEmpty()) { for (Map.Entry<String, Artifact> entry : pendingArtifacts....
@Test public void testNoChangeMerge() throws Exception { StepRuntimeSummary summary = loadObject( "fixtures/execution/sample-step-runtime-summary-1.json", StepRuntimeSummary.class); assertTrue(summary.isSynced()); summary.mergeRuntimeUpdate(null, null); assertTrue(summary.isSynced(...
@Override public boolean enableSendingOldValues(final boolean forceMaterialization) { if (queryableName != null) { sendOldValues = true; return true; } if (parent.enableSendingOldValues(forceMaterialization)) { sendOldValues = true; } retu...
@Test public void shouldSendOldValuesWhenEnabledOnUpStreamMaterialization() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final KTableImpl<String, Integer, Integer> table1 = (KTableImpl<String, Integer, Integer>) builder.table(topic1, con...
public long getTotalSyncCount() { final AtomicLong result = new AtomicLong(); distroRecords.forEach((s, distroRecord) -> result.addAndGet(distroRecord.getTotalSyncCount())); return result.get(); }
@Test void testGetTotalSyncCount() { long expected = DistroRecordsHolder.getInstance().getTotalSyncCount() + 1; DistroRecordsHolder.getInstance().getRecord("testGetTotalSyncCount").syncSuccess(); assertEquals(expected, DistroRecordsHolder.getInstance().getTotalSyncCount()); }
public static List<UpdateRequirement> forUpdateTable( TableMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid table metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Bui...
@Test public void setSnapshotRefFailure() { long snapshotId = 14L; String refName = "random_branch"; SnapshotRef snapshotRef = mock(SnapshotRef.class); when(snapshotRef.isBranch()).thenReturn(true); when(snapshotRef.snapshotId()).thenReturn(snapshotId); ImmutableList<MetadataUpdate> metadataU...
@Override public void execute(Runnable task) { execute0(task); }
@Test @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS) public void testAutomaticStartStop() throws Exception { final TestRunnable task = new TestRunnable(500); e.execute(task); // Ensure the new thread has started. Thread thread = e.thread; assertThat(thread, is(not(...
public static <T> Result<T> error(Status status) { return new Result<>(status); }
@Test public void error() { Result ret = Result.error(Status.ACCESS_TOKEN_NOT_EXIST); Assertions.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST.getCode(), ret.getCode().intValue()); }
public List<List<String>> getInfos() { List<List<String>> infos = Lists.newArrayList(); readLock(); try { for (Map.Entry<String, GroupId> entry : groupName2Id.entrySet()) { List<String> info = Lists.newArrayList(); GroupId groupId = entry.getValue(); ...
@Test public void testDropTable() throws Exception { ConnectContext connectContext = UtFrameUtils.createDefaultCtx(); // create db1 String createDbStmtStr = "create database db1;"; CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseStmtWithNewParser(createDbStmtStr, connec...
public Tree() { this(null); }
@Test public void treeTest() { //配置 TreeNodeConfig treeNodeConfig = new TreeNodeConfig(); // 自定义属性名 都要默认值的 treeNodeConfig.setWeightKey("order"); treeNodeConfig.setIdKey("rid"); treeNodeConfig.setDeep(2); //转换器 List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0", treeNodeConfig, (treeNode, ...
public long getDataOffset() { return data_offset; }
@Test public void getDataOffset() { assertEquals(TestParameters.VP_DATA_OFFSET_LENGTH, chmItsfHeader.getDataOffset()); }
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseDropSourceStatement() { // When: List<CommandParser.ParsedCommand> commands = parse("drop stream foo;"); // Then: assertThat(commands.size(), is(1)); assertThat(commands.get(0).getStatement().isPresent(), is (false)); assertThat(commands.get(0).getCommand(), is("d...
@Override public String[] getSchemes() { return new String[]{Scheme.davs.name(), Scheme.https.name()}; }
@Test public void testSchemes() { assertTrue(Arrays.asList(new DAVSSLProtocol().getSchemes()).contains(Scheme.https.name())); }
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeDurationZero() { FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ZERO), "PT0S"); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { String s = new String(rawMessage.getPayload(), StandardCharsets.UTF_8); LOG.trace("Received raw message: {}", s); String timezoneID = configuration.getString(CK_TIMEZONE); // previously existing PA input...
@Test public void testMoreSyslogFormats() { // Test an extra list of messages. for (String threatString : MORE_SYSLOG_THREAT_MESSAGES) { PaloAltoCodec codec = new PaloAltoCodec(Configuration.EMPTY_CONFIGURATION, messageFactory); Message message = codec.decode(new RawMessage(...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel()); ...
@Test @UseDataProvider("trueOrFalse") public void toProtobuf_whenRunningOrNotRunningInContainer_shouldReturnCorrectFlag(boolean flag) { when(containerSupport.isRunningInContainer()).thenReturn(flag); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Containe...
public static ExpressionEvaluatorFactory create(ClassLoader classLoader, Type type) { return new ExpressionEvaluatorFactory(classLoader, type); }
@Test public void create() { assertThat(ExpressionEvaluatorFactory.create(classLoader, ScenarioSimulationModel.Type.RULE)).isNotNull(); }
static boolean isVespaParent(String groupId) { return groupId.matches("(com\\.yahoo\\.vespa|ai\\.vespa)(\\..+)?"); }
@Test public void testRegex() { assertTrue(ApplicationMojo.isVespaParent("ai.vespa")); assertTrue(ApplicationMojo.isVespaParent("ai.vespa.hosted")); assertTrue(ApplicationMojo.isVespaParent("com.yahoo.vespa")); assertTrue(ApplicationMojo.isVespaParent("com.yahoo.vespa.hosted")); ...
public ServiceBusConfiguration getConfiguration() { return configuration; }
@Test void testCreateEndpointWithFqnsAndCredential() throws Exception { final String uri = "azure-servicebus://testTopicOrQueue"; final String remaining = "testTopicOrQueue"; final String fullyQualifiedNamespace = "namespace.servicebus.windows.net"; final TokenCredential credential =...
protected Repository getDelegate() { if ( this.delegate != null ) { return this.delegate; } Repository repository = null; try { repository = (Repository) purPluginClassLoader.loadClass( "org.pentaho.di.repository.pur.PurRepository" ).newInstance(); } catch ( Exception e ) { logger....
@Test public void getDelegateTest() { Repository repository = null; try { Mockito.<Class<?>>when( mockClassLoader.loadClass( anyString() ) ).thenReturn( Class.forName( "org.pentaho" + ".di.repository.pur.PurRepository" ) ); } catch ( ClassNotFoundException e ) { e.printStackTrace();...
public boolean intersects(BoundingBox boundingBox) { if (this == boundingBox) { return true; } return this.maxLatitude >= boundingBox.minLatitude && this.maxLongitude >= boundingBox.minLongitude && this.minLatitude <= boundingBox.maxLatitude && this.minLongitude <= b...
@Test public void intersectsTest() { BoundingBox boundingBox1 = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE); BoundingBox boundingBox2 = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE); BoundingBox boundingBox3 = new BoundingBox(0, 0, MI...
@Override public double variance() { return 1 / (lambda * lambda); }
@Test public void testVariance() { System.out.println("variance"); ExponentialDistribution instance = new ExponentialDistribution(1.0); instance.rand(); assertEquals(1.0, instance.variance(), 1E-7); instance.rand(); instance = new ExponentialDistribution(2.0); ...
public void writeEncodedValue(EncodedValue encodedValue) throws IOException { switch (encodedValue.getValueType()) { case ValueType.BOOLEAN: writer.write(Boolean.toString(((BooleanEncodedValue) encodedValue).getValue())); break; case ValueType.BYTE: ...
@Test public void testWriteEncodedValue_char() throws IOException { DexFormattedWriter writer = new DexFormattedWriter(output); writer.writeEncodedValue(new ImmutableCharEncodedValue('a')); Assert.assertEquals("0x61", output.toString()); }
@Override public ProcResult fetchResult() throws AnalysisException { Preconditions.checkNotNull(globalStateMgr); BaseProcResult result = new BaseProcResult(); result.setNames(TITLE_NAMES); List<Long> dbIds = globalStateMgr.getLocalMetastore().getDbIds(); if (dbIds == null |...
@Test public void testFetchResult() throws AnalysisException { new StatisticProcDir(GlobalStateMgr.getCurrentState()).fetchResult(); }
@Override public boolean isInput() { return false; }
@Test public void testIsInput() throws Exception { assertFalse( analyzer.isInput() ); }
@Nullable protected V get(K key) { if (key == null) return null; Object[] state = state(); int i = indexOfExistingKey(state, key); return i != -1 ? (V) state[i + 1] : null; }
@Test void get_ignored_if_unconfigured() { assertThat(extra.get("three")).isNull(); }
@Override public void print(Iterator<RowData> it, PrintWriter printWriter) { if (!it.hasNext()) { printEmptyResult(it, printWriter); return; } long numRows = printTable(it, printWriter); printFooter(printWriter, numRows); }
@Test void testPrintWithEmptyResultAndDeriveColumnWidthByContent() { PrintStyle.tableauWithTypeInferredColumnWidths( getSchema(), getConverter(), PrintStyle.DEFAULT_MAX_COLUMN_WIDTH, true, ...
static <T extends Comparable<? super T>> int compareListWithFillValue( List<T> left, List<T> right, T fillValue) { int longest = Math.max(left.size(), right.size()); for (int i = 0; i < longest; i++) { T leftElement = fillValue; T rightElement = fillValue; if (i < left.size()) { ...
@Test public void compareWithFillValue_bothEmptyListWithPositiveFillValue_returnsZero() { assertThat( ComparisonUtility.compareListWithFillValue( Lists.newArrayList(), Lists.newArrayList(), 1)) .isEqualTo(0); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@Test public void testPartitionedYears() throws Exception { createPartitionedTable(spark, tableName, "years(ts)"); SparkScanBuilder builder = scanBuilder(); YearsFunction.TimestampToYearsFunction function = new YearsFunction.TimestampToYearsFunction(); UserDefinedScalarFunc udf = toUDF(function, exp...
public static FactoryBuilder newFactoryBuilder(Propagation.Factory delegate) { return new FactoryBuilder(delegate); }
@Test void newFactory_sharingRemoteName() { BaggagePropagation.FactoryBuilder builder = newFactoryBuilder(B3Propagation.FACTORY); SingleBaggageField userName = SingleBaggageField.newBuilder(BaggageField.create("userName")).addKeyName("baggage").build(); SingleBaggageField userId = SingleBaggageF...
public static <T extends Enum<T>> T getForNameIgnoreCase(final @Nullable String value, final @NotNull Class<T> enumType) { return getForNameIgnoreCase(value, enumType, Map.of()); }
@Test void shouldGetEnumForNameIgnoreCaseForExisting() { TestEnum result = Enums.getForNameIgnoreCase("enum1", TestEnum.class); Assertions.assertEquals(TestEnum.ENUM1, result); }
public Collection<JID> getAdmins() { return administrators; }
@Test public void testOverrideBareJidWithFullJid() throws Exception { // Setup test fixture. final String groupName = "unit-test-group-l"; final Group group = groupManager.createGroup(groupName); final JID fullJid = new JID("unit-test-user-l", "example.org", "unit-test-resource-l...
public static void removeDeepLinkInfo(JSONObject jsonObject) { try { if (jsonObject == null) { return; } String latestKey; Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { latestKey = keys.next(); ...
@Test public void removeDeepLinkInfo() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("$latest_abc", "abc"); jsonObject.put("normal", "abc_normal"); } catch (JSONException e) { e.printStackTrace(); } ChannelUtils.removeDee...
public IThrowableRenderer<ILoggingEvent> getThrowableRenderer() { return throwableRenderer; }
@Test public void testAppendThrowable() throws Exception { StringBuilder buf = new StringBuilder(); PubThrowableProxy tp = new PubThrowableProxy(); tp.setClassName("test1"); tp.setMessage("msg1"); StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); S...
public static boolean isCollection(String className) { return Collection.class.getCanonicalName().equals(className) || isList(className); }
@Test public void isCollection() { assertThat(listValues).allMatch(ScenarioSimulationSharedUtils::isCollection); assertThat(mapValues).noneMatch(ScenarioSimulationSharedUtils::isCollection); assertThat(ScenarioSimulationSharedUtils.isCollectionOrMap(Collection.class.getCanonicalName())).isTr...
@Override public double dot(SGDVector other) { if (other.size() != elements.length) { throw new IllegalArgumentException("Can't dot two vectors of different dimension, this = " + elements.length + ", other = " + other.size()); } double score = 0.0; if (other instanceof De...
@Test public void emptyDot() { DenseVector a = generateVectorA(); DenseVector b = generateVectorB(); DenseVector c = generateVectorC(); DenseVector empty = generateEmptyVector(); assertEquals(a.dot(empty),empty.dot(a),1e-10); assertEquals(0.0, a.dot(empty),1e-10); ...
@Override public String stem(String word) { // Convert input to lowercase and remove all chars that are not a letter. word = cleanup(word.toLowerCase()); //if str's length is greater than 2 then remove prefixes if ((word.length() > 3) && (stripPrefix)) { word = stripPref...
@Test public void testStem() { System.out.println("stem"); String[] words = {"consign", "consigned", "consigning", "consignment", "consist", "consisted", "consistency", "consistent", "consistently", "consisting", "consists", "consolation", "consolations", "consolatory", ...
@Deprecated public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) { return Task.callable(name, () -> callable.call()); }
@SuppressWarnings("deprecation") @Test public void testThrowableCallableWithError() throws InterruptedException { final Throwable throwable = new Throwable(); final ThrowableCallable<Integer> callable = new ThrowableCallable<Integer>() { @Override public Integer call() throws Throwable { ...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { if(file.isDirectory()) { return this.toAttributes(new FoldersApi(new BoxApiClient(session.getClient())).getFoldersId(fileid.getFileId(file), ...
@Test public void testFindDirectory() throws Exception { final BoxFileidProvider fileid = new BoxFileidProvider(session); final Path folder = new BoxDirectoryFeature(session, fileid).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new...
@Override protected void processOptions(LinkedList<String> args) throws IOException { CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE, OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN, OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE, OPTION_MTIME, OPTION_SIZE, OPTION_A...
@Test public void processPathDirOrderAtime() throws IOException { TestFile testfile01 = new TestFile("testDirectory", "testFile01"); TestFile testfile02 = new TestFile("testDirectory", "testFile02"); TestFile testfile03 = new TestFile("testDirectory", "testFile03"); TestFile testfile04 = new TestFile(...
@Override @SuppressWarnings("unchecked") public int run() throws IOException { Preconditions.checkArgument(targets != null && targets.size() >= 1, "A Parquet file is required."); Preconditions.checkArgument(targets.size() == 1, "Cannot process multiple Parquet files."); String source = targets.get(0); ...
@Test public void testShowDirectoryCommand() throws IOException { File file = parquetFile(); ShowDictionaryCommand command = new ShowDictionaryCommand(createLogger()); command.targets = Arrays.asList(file.getAbsolutePath()); command.column = BINARY_FIELD; command.setConf(new Configuration()); ...
@Override public String getDefaultScheme() { return PluginEnum.GRPC.getName(); }
@Test public void getDefaultScheme() { assertEquals(shenyuNameResolverProvider.getDefaultScheme(), PluginEnum.GRPC.getName()); }
@Override public Cancellable schedule(final long delay, final TimeUnit unit, final Runnable command) { final IndirectRunnable indirectRunnable = new IndirectRunnable(command); final Cancellable cancellable = _executor.schedule(delay, unit, indirectRunnable); return new IndirectCancellable(cancellable, ind...
@Test public void testCancel() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final Cancellable cancellable = _executor.schedule(100, TimeUnit.MILLISECONDS, new Runnable() { @Override public void run() { latch.countDown(); } }); assertTrue(...