focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public AsyncHttpResponse handle(HttpRequest request) { Instant from = Optional.ofNullable(request.getProperty("from")) .map(Long::valueOf).map(Instant::ofEpochMilli).orElse(Instant.MIN); Instant to = Optional.ofNullable(request.getProperty("to")) ...
@Test void handleCorrectlyParsesQueryParameters() throws IOException { MockLogReader mockLogReader = new MockLogReader(); LogHandler logHandler = new LogHandler(mock(Executor.class), mockLogReader); { String uri = "http://myhost.com:1111/logs?from=1000&to=2000"; Asyn...
public boolean isValid() { return !Double.isNaN(lat) && !Double.isNaN(lon); }
@Test public void testIsValid() { GHPoint instance = new GHPoint(); assertFalse(instance.isValid()); instance.lat = 1; assertFalse(instance.isValid()); instance.lon = 1; assertTrue(instance.isValid()); }
@Override public boolean isShutdown() { return shutdown.get(); }
@Test public void isShutdown() { ManagedExecutorService executorService = newManagedExecutorService(); executorService.shutdown(); assertTrue(executorService.isShutdown()); }
Duration lap() { Instant now = clock.instant(); Duration duration = Duration.between(lapStartTime, now); lapStartTime = now; return duration; }
@Test public void testLap() { Mockito.when(mockClock.instant()).thenReturn(Instant.EPOCH); Timer parentTimer = new Timer(mockClock, null); Mockito.when(mockClock.instant()).thenReturn(Instant.EPOCH.plusMillis(5)); Duration parentDuration1 = parentTimer.lap(); Mockito.when(mockClock.instant()).then...
public MethodDescriptor getMethod(String methodName, String params) { Map<String, MethodDescriptor> methods = descToMethods.get(methodName); if (CollectionUtils.isNotEmptyMap(methods)) { return methods.get(params); } return null; }
@Test void getMethod() { String desc = ReflectUtils.getDesc(String.class); Assertions.assertNotNull(service.getMethod("sayHello", desc)); }
String getProfileViewResponseFromBody(String responseBody) { String template = (String) DEFAULT_GSON.fromJson(responseBody, Map.class).get("template"); if (StringUtils.isBlank(template)) { throw new RuntimeException("Template was blank!"); } return template; }
@Test public void shouldUnJSONizeGetProfileViewResponseFromBody() { String template = new ElasticAgentExtensionConverterV4().getProfileViewResponseFromBody("{\"template\":\"foo\"}"); assertThat(template, is("foo")); }
public static PrivilegedOperation squashCGroupOperations (List<PrivilegedOperation> ops) throws PrivilegedOperationException { if (ops.size() == 0) { return null; } StringBuilder finalOpArg = new StringBuilder(PrivilegedOperation .CGROUP_ARG_PREFIX); boolean noTasks = true; for (Pr...
@Test public void testSquashCGroupOperationsWithInvalidOperations() { List<PrivilegedOperation> ops = new ArrayList<>(); //Ensure that disallowed ops are rejected ops.add(opTasksNone); ops.add(opDisallowed); try { PrivilegedOperationExecutor.squashCGroupOperations(ops); Assert.fail("...
public void isEqualTo(@Nullable Object expected) { standardIsEqualTo(expected); }
@SuppressWarnings("TruthSelfEquals") @Test public void isEqualToSameInstanceBadEqualsImplementation() { Object o = new ThrowsOnEquals(); assertThat(o).isEqualTo(o); }
@Override public Counter counter(String name) { return NoopCounter.INSTANCE; }
@Test public void accessingACustomCounterRegistersAndReusesTheCounter() { final MetricRegistry.MetricSupplier<Counter> supplier = () -> counter; final Counter counter1 = registry.counter("thing", supplier); final Counter counter2 = registry.counter("thing", supplier); assertThat(cou...
public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum, final long begin, final long end) { if (this.mappedFile.hold()) { int keyHash = indexKeyHashMethod(key); int slotPos = keyHash % this.hashSlotNum; int ...
@Test public void testSelectPhyOffset() throws Exception { IndexFile indexFile = new IndexFile("200", HASH_SLOT_NUM, INDEX_NUM, 0, 0); for (long i = 0; i < (INDEX_NUM - 1); i++) { boolean putResult = indexFile.putKey(Long.toString(i), i, System.currentTimeMillis()); assertTh...
@Override public Collection<Member> getMemberList() { return client.getClientClusterService().getMemberList(); }
@Test public void testGetMemberList() { Collection<Member> memberList = context.getMemberList(); assertNotNull(memberList); assertEquals(1, memberList.size()); }
@Override public long timestamp() { throw new UnsupportedOperationException("StateStores can't access timestamp."); }
@Test public void shouldThrowOnTimestamp() { assertThrows(UnsupportedOperationException.class, () -> context.timestamp()); }
public static SqlPrimitiveType of(final String typeName) { switch (typeName.toUpperCase()) { case INT: return SqlPrimitiveType.of(SqlBaseType.INTEGER); case VARCHAR: return SqlPrimitiveType.of(SqlBaseType.STRING); default: try { final SqlBaseType sqlType = SqlBase...
@Test public void shouldSupportAlternativeSqlPrimitiveTypeNames() { // Given: final java.util.Map<String, SqlBaseType> primitives = ImmutableMap.of( "InT", SqlBaseType.INTEGER, "VarchaR", SqlBaseType.STRING ); primitives.forEach((string, expected) -> // Then: assertTha...
public static String getPID() { String pid = System.getProperty("pid"); if (pid == null) { // first, reliable with sun jdk (http://golesny.de/wiki/code:javahowtogetpid) final RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean(); final String processName = rtb.getName(); /* tested on: */ /* - wind...
@Test public void testGetPID() { assertNotNull("getPID", PID.getPID()); }
public static void main(String[] args) throws Exception { Arguments arguments = new Arguments(); CommandLine commander = new CommandLine(arguments); try { commander.parseArgs(args); if (arguments.help) { commander.usage(commander.getOut()); ...
@Test public void testMainGenerateDocs() throws Exception { PrintStream oldStream = System.out; try { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); Class argumentsClass = Class.forNam...
public void fillMaxSpeed(Graph graph, EncodingManager em) { // In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info, // but now we have and can fill the country-dependent max_speed value where missing. EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(...
@Test public void testLivingStreetWithWalk() { ReaderWay way = new ReaderWay(0L); way.setTag("country", Country.AUT); way.setTag("highway", "living_street"); EdgeIteratorState edge = createEdge(way).set(urbanDensity, CITY); calc.fillMaxSpeed(graph, em); assertEquals(6...
public List<MemorySegment> requestBuffers() throws Exception { List<MemorySegment> allocated = new ArrayList<>(numBuffersPerRequest); synchronized (buffers) { checkState(!destroyed, "Buffer pool is already destroyed."); if (!initialized) { initialize(); ...
@Test void testRequestBuffers() throws Exception { BatchShuffleReadBufferPool bufferPool = createBufferPool(); List<MemorySegment> buffers = new ArrayList<>(); try { buffers.addAll(bufferPool.requestBuffers()); assertThat(buffers).hasSize(bufferPool.getNumBuffersPerR...
@SuppressWarnings("unchecked") public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { return register(MetricName.build(name), metric); }
@Test public void registeringATimerTriggersANotification() throws Exception { assertThat(registry.register(THING, timer)) .isEqualTo(timer); verify(listener).onTimerAdded(THING, timer); }
@Override public void validate(CruiseConfig cruiseConfig) { ServerConfig serverConfig = cruiseConfig.server(); String artifactDir = serverConfig.artifactsDir(); if (isEmpty(artifactDir)) { throw new RuntimeException("Please provide a not empty value for artifactsdir"); }...
@Test public void shouldNotThrowExceptionWhenUserProvidesValidPath() throws Exception { File file = new File(""); CruiseConfig cruiseConfig = new BasicCruiseConfig(); cruiseConfig.setServerConfig(new ServerConfig(file.getAbsolutePath() + "/logs", null)); ArtifactDirValidator dirVali...
@Override public String toString() { return pathService.toString(this); }
@Test public void testPathParsing_windowsStylePaths() throws IOException { PathService windowsPathService = PathServiceTest.fakeWindowsPathService(); assertEquals("C:\\", pathService.parsePath("C:\\").toString()); assertEquals("C:\\foo", windowsPathService.parsePath("C:\\foo").toString()); assertEqual...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { return payload.readStringFixByBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); }
@Test void assertReadWithMeta2() { columnDef.setColumnMeta(2); when(payload.getByteBuf()).thenReturn(byteBuf); when(byteBuf.readUnsignedShortLE()).thenReturn(0xffff); when(payload.readStringFixByBytes(0xffff)).thenReturn(new byte[65535]); assertThat(new MySQLBlobBinlogProtoco...
List<String> getStatements(int oldVersion, int newVersion) { List<String> result = new ArrayList<>(); for (int i = oldVersion + 1; i <= newVersion; ++i) { List<String> list = statementsMap.get(i); if (list != null) { result.addAll(list); } } return result; }
@Test public void testGetStatements() { MSQLiteBuilder builder = new MSQLiteBuilder() .version(1) .statement("11") .statement("12") .version(3) .statement("31") .statement("32"); List<String> list = new ArrayList<>(); list.add("31"); list.add("32"); ...
public static String wrap(String input, Formatter formatter) throws FormatterException { return StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, input, formatter); }
@Test public void textBlockTrailingWhitespace() throws Exception { assumeTrue(Runtime.version().feature() >= 15); String input = lines( "public class T {", " String s =", " \"\"\"", " lorem ", " ipsum", " \"...
@Config public static PrintStream fallbackLogger() { final String fallbackLoggerName = getProperty(FALLBACK_LOGGER_PROP_NAME, "stderr"); switch (fallbackLoggerName) { case "stdout": return System.out; case "no_op": return NO_OP_LOG...
@Test void fallbackLoggerReturnsNoOpLoggerIfConfigured() { System.setProperty(FALLBACK_LOGGER_PROP_NAME, "no_op"); try { final PrintStream logger = CommonContext.fallbackLogger(); assertNotNull(logger); assertNotSame(System.err, logger); as...
public static boolean isCoastedRadarHit(CenterRadarHit centerRh) { String cmsFieldValue = centerRh.cmsField153A(); return nonNull(cmsFieldValue) ? CENTER_COASTED_FLAGS.contains(cmsFieldValue) : false; }
@Test public void testIsCoastedRadarHit() { CenterRadarHit notCoasted = (CenterRadarHit) parse(NON_COASTED_RH); CenterRadarHit coasted = (CenterRadarHit) parse(COASTED_RH); assertFalse(CenterSmoothing.isCoastedRadarHit(notCoasted)); assertTrue(CenterSmoothing.isCoastedRadarHit(coas...
@Override public Map<String, String> convertToEntityAttribute(String dbData) { return GSON.fromJson(dbData, TYPE); }
@Test void convertToEntityAttribute_null_twoElement() throws IOException { Map<String, String> map = new HashMap<>(8); map.put("a", "1"); map.put("disableCheck", "true"); String content = readAllContentOf("json/converter/element.2.json"); assertEquals(map, this.converter.convertToEntityAttribute(...
public OkHttpClientBuilder setResponseTimeoutMs(long l) { if (l < 0) { throw new IllegalArgumentException("Response timeout must be positive. Got " + l); } this.responseTimeoutMs = l; return this; }
@Test public void build_throws_IAE_if_response_timeout_is_negative() { assertThatThrownBy(() -> underTest.setResponseTimeoutMs(-10)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Response timeout must be positive. Got -10"); }
public void fillMaxSpeed(Graph graph, EncodingManager em) { // In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info, // but now we have and can fill the country-dependent max_speed value where missing. EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(...
@Test public void testLivingStreetWithMaxSpeed() { ReaderWay way = new ReaderWay(0L); way.setTag("country", Country.DEU); way.setTag("highway", "living_street"); way.setTag("maxspeed", "30"); EdgeIteratorState edge = createEdge(way).set(urbanDensity, CITY); calc.fillM...
@Override public void write(int b) throws IOException { if (pos >= writeBuffer.length) { flush(); } writeBuffer[pos++] = (byte) b; }
@Test void testWriteLargerThanBufferSize() throws IOException { final Path workingDir = new Path(TempDirUtils.newFolder(temporaryFolder).getAbsolutePath()); final Path file = new Path(workingDir, "test-file"); TestingFsBatchFlushOutputStream outputStream = new TestingFsBatch...
@Override void decode(ByteBufAllocator alloc, ByteBuf headerBlock, SpdyHeadersFrame frame) throws Exception { ObjectUtil.checkNotNull(headerBlock, "headerBlock"); ObjectUtil.checkNotNull(frame, "frame"); if (cumulation == null) { decodeHeaderBlock(headerBlock, frame); ...
@Test public void testIllegalValueStartsWithNull() throws Exception { ByteBuf headerBlock = Unpooled.buffer(22); headerBlock.writeInt(1); headerBlock.writeInt(4); headerBlock.writeBytes(nameBytes); headerBlock.writeInt(6); headerBlock.writeByte(0); headerBlock...
@Override public SortedSet<IndexRange> findAll() { try (DBCursor<MongoIndexRange> cursor = collection.find(DBQuery.notExists("start"))) { return ImmutableSortedSet.copyOf(IndexRange.COMPARATOR, (Iterator<? extends IndexRange>) cursor); } }
@Test @MongoDBFixtures("MongoIndexRangeServiceTest-LegacyIndexRanges.json") public void findAllReturnsAllIgnoresLegacyIndexRanges() throws Exception { assertThat(indexRangeService.findAll()).hasSize(1); }
@Override protected String buildUndoSQL() { TableRecords beforeImage = sqlUndoLog.getBeforeImage(); List<Row> beforeImageRows = beforeImage.getRows(); if (CollectionUtils.isEmpty(beforeImageRows)) { throw new ShouldNeverHappenException("Invalid UNDO LOG"); // TODO } ...
@Test public void buildUndoSQLByUpperCase() { OracleUndoUpdateExecutor executor = upperCaseSQL(); String sql = executor.buildUndoSQL(); Assertions.assertNotNull(sql); Assertions.assertTrue(sql.contains("UPDATE")); Assertions.assertTrue(sql.contains("ID")); Assertions...
@Nonnull public ResourceProfile merge(final ResourceProfile other) { checkNotNull(other, "Cannot merge with null resources"); if (equals(ANY) || other.equals(ANY)) { return ANY; } if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) { return UNKNOWN; }...
@Test void testMerge() { final ResourceProfile rp1 = ResourceProfile.newBuilder() .setCpuCores(1.0) .setTaskHeapMemoryMB(100) .setTaskOffHeapMemoryMB(100) .setManagedMemoryMB(100) ...
public TolerantDoubleComparison isWithin(double tolerance) { return new TolerantDoubleComparison() { @Override public void of(double expected) { Double actual = DoubleSubject.this.actual; checkNotNull( actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance...
@Test public void isWithinOfZero() { assertThat(+0.0).isWithin(0.00001).of(+0.0); assertThat(+0.0).isWithin(0.00001).of(-0.0); assertThat(-0.0).isWithin(0.00001).of(+0.0); assertThat(-0.0).isWithin(0.00001).of(-0.0); assertThat(+0.0).isWithin(0.0).of(+0.0); assertThat(+0.0).isWithin(0.0).of(-...
public void add(Boolean bool) { elements.add(bool == null ? JsonNull.INSTANCE : new JsonPrimitive(bool)); }
@Test public void testStringPrimitiveAddition() { JsonArray jsonArray = new JsonArray(); jsonArray.add("Hello"); jsonArray.add("Goodbye"); jsonArray.add("Thank you"); jsonArray.add((String) null); jsonArray.add("Yes"); assertThat(jsonArray.toString()) .isEqualTo("[\"Hello\",\"Goo...
@Override public void open() throws Exception { this.timerService = getInternalTimerService("processing timer", VoidNamespaceSerializer.INSTANCE, this); this.keySet = new HashSet<>(); super.open(); }
@Test void testEndInput() throws Exception { AtomicInteger firstInputCounter = new AtomicInteger(); AtomicInteger secondInputCounter = new AtomicInteger(); KeyedTwoInputNonBroadcastProcessOperator<Long, Integer, Long, Long> processOperator = new KeyedTwoInputNonBroadcastProce...
public static long readUint32BE(ByteBuffer buf) throws BufferUnderflowException { return Integer.toUnsignedLong(buf.order(ByteOrder.BIG_ENDIAN).getInt()); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void testReadUint32BEThrowsException2() { ByteUtils.readUint32BE(new byte[]{1, 2, 3, 4, 5}, 2); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { if(containerService.isContainer(folder)) { return super.mkdir(folder, status); } else { status.setChecksum(writer.checksum(folder, status).compute(new NullInputStr...
@Test public void testCreatePlaceholder() throws Exception { final String bucketname = new AlphanumericRandomStringService().random(); final String name = new AlphanumericRandomStringService().random(); final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(sessi...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // Get the mime4j configuration, or use a default one MimeConfig config = new MimeConfig.Builder().setMaxLineLen(...
@Test public void testSimple() throws Exception { Metadata metadata = new Metadata(); InputStream stream = getStream("test-documents/testRFC822"); ContentHandler handler = mock(DefaultHandler.class); try { EXTRACT_ALL_ALTERNATIVES_PARSER.parse(stream, handler, metadata, ...
@VisibleForTesting static String getDataKeyName(UUID jobId, String key) { return String.format("%s-%s", jobId, key); }
@Test public void getDataKeyName() throws Exception { assertEquals( JOB_ID + "-tempTaskData", GoogleJobStore.getDataKeyName(JOB_ID, "tempTaskData")); assertEquals( JOB_ID + "-tempCalendarData", GoogleJobStore.getDataKeyName(JOB_ID, "tempCalendarData")); }
@Override public Object getDateValue(final ResultSet resultSet, final int columnIndex) throws SQLException { if (isYearDataType(resultSet.getMetaData().getColumnTypeName(columnIndex))) { return resultSet.wasNull() ? null : resultSet.getObject(columnIndex); } return resultSet.getD...
@Test void assertGetDateValueWithYearDataTypeAndNotNullValue() throws SQLException { when(resultSet.getMetaData().getColumnTypeName(1)).thenReturn("YEAR"); Object expectedObject = new Object(); when(resultSet.getObject(1)).thenReturn(expectedObject); assertThat(dialectResultSetMapper...
public static String toJson(UpdateRequirement updateRequirement) { return toJson(updateRequirement, false); }
@Test public void testAssertCurrentSchemaIdToJson() { String requirementType = UpdateRequirementParser.ASSERT_CURRENT_SCHEMA_ID; int schemaId = 4; String expected = String.format("{\"type\":\"%s\",\"current-schema-id\":%d}", requirementType, schemaId); UpdateRequirement actual = new UpdateRequ...
@Override public int launch(AgentLaunchDescriptor descriptor) { LogConfigurator logConfigurator = new LogConfigurator("agent-launcher-logback.xml"); return logConfigurator.runWithLogger(() -> doLaunch(descriptor)); }
@Test public void shouldNotThrowException_insteadReturnAppropriateErrorCode_whenSomethingGoesWrongInLaunch() { AgentLaunchDescriptor launchDesc = mock(AgentLaunchDescriptor.class); when(launchDesc.context().get(AgentBootstrapperArgs.SERVER_URL)).thenThrow(new RuntimeException("Ouch!")); asse...
public static String executeDockerCommand(DockerCommand dockerCommand, String containerId, Map<String, String> env, PrivilegedOperationExecutor privilegedOperationExecutor, boolean disableFailureLogging, Context nmContext) throws ContainerExecutionException { PrivilegedOperation dockerOp = d...
@Test public void testExecuteDockerStop() throws Exception { DockerStopCommand dockerCommand = new DockerStopCommand(MOCK_CONTAINER_ID); DockerCommandExecutor.executeDockerCommand(dockerCommand, MOCK_CONTAINER_ID, env, mockExecutor, false, nmContext); List<PrivilegedOperation> ops = MockPrivileged...
@Override public boolean equals(Object o) { if (!(o instanceof AtomicValueEvent)) { return false; } AtomicValueEvent that = (AtomicValueEvent) o; return Objects.equals(this.name, that.name) && Objects.equals(this.newValue, that.newValue) && ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(event1) .addEqualityGroup(event2, sameAsEvent2) .addEqualityGroup(event3) .testEquals(); }
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { Map<String, String> mdcContextMap = getMdcContextMap(); return super.schedule(ContextPropagator.decorateRunnable(contextPropagators, () -> { try { setMDCContext(mdcContextM...
@Test public void testThreadFactory() { final ScheduledFuture<String> schedule = schedulerService.schedule(() -> Thread.currentThread().getName(), 0, TimeUnit.MILLISECONDS); waitAtMost(1, TimeUnit.SECONDS).until(matches(() -> assertThat(schedule.get()).contains("ContextAwareScheduledThre...
public static void setCommitDirectory(Job job, Path commitDirectory) { job.getConfiguration().set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, commitDirectory.toString()); }
@Test public void testSetCommitDirectory() { try { Job job = Job.getInstance(new Configuration()); Assert.assertEquals(null, CopyOutputFormat.getCommitDirectory(job)); job.getConfiguration().set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, ""); Assert.assertEquals(null, CopyOutputFormat....
@Override public Set<DatabaseTableName> getCachedTableNames() { return cachingMetastore.getCachedTableNames(); }
@Test public void testGetCachedTable(@Mocked ConnectContext connectContext) { new Expectations() { { ConnectContext.get(); result = connectContext; minTimes = 0; connectContext.getCommand(); result = MysqlCommand.CO...
public Future<Void> maybeRollingUpdate(Reconciliation reconciliation, int replicas, Labels selectorLabels, Function<Pod, List<String>> podRestart, TlsPemIdentity coTlsPemIdentity) { String namespace = reconciliation.namespace(); // We prepare the list of expected Pods. This is needed as we need to acco...
@Test public void testOnlySomePodsAreRolled(VertxTestContext context) { PodOperator podOperator = mock(PodOperator.class); when(podOperator.listAsync(any(), any(Labels.class))).thenReturn(Future.succeededFuture(PODS)); when(podOperator.readiness(any(), any(), any(), anyLong(), anyLong())).t...
Optional<String> getQueriesFile(final Map<String, String> properties) { if (queriesFile != null) { return Optional.of(queriesFile); } return Optional.ofNullable(properties.get(QUERIES_FILE_CONFIG)); }
@Test public void shouldNotHaveQueriesFileIfNotInPropertiesOrCommandLine() { assertThat(serverOptions.getQueriesFile(emptyMap()), is(Optional.empty())); }
@Override public float getFloat(int index) { return Float.intBitsToFloat(getInt(index)); }
@Test public void testGetFloatAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().getFloat(0); } }); }
public RunResponse restartDirectly( RunResponse restartStepInfo, RunRequest runRequest, boolean blocking) { WorkflowInstance instance = restartStepInfo.getInstance(); String stepId = restartStepInfo.getStepId(); validateStepId(instance, stepId, Actions.StepInstanceAction.RESTART); StepInstance ste...
@Test public void testRestartDirectlyWithTerminatedStep() { stepInstance.getRuntimeState().setStatus(StepInstance.Status.FATALLY_FAILED); // emulate restarted step finishes stepInstance.getRuntimeState().setCreateTime(System.currentTimeMillis() + 3600 * 1000); stepInstance.getStepRetry().setRetryable(...
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 shouldThrowOnInvalidInsertValues() { // When: final MigrationException e = assertThrows(MigrationException.class, () -> parse("insert into foo values (this_should_not_here) ('val');")); // Then: assertThat(e.getMessage(), containsString("Failed to parse the statement")); }
public int exceptionCount() { return this.exceptionCount; }
@Test public void testFileWithManyFlaws() { NopParser parser = new NopParser(new File(FILE_WITH_LOTS_OF_BAD_LINES)); assertDoesNotThrow(() -> parseAllMessages(parser)); assertEquals(10000, parser.exceptionCount()); }
public static CommandExecutor newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket, final ConnectionSession connectionSession, final PortalContext portalContext) throws SQLException { if (commandPacket instance...
@Test void assertAggregatedPacketIsBatchedStatements() throws SQLException { PostgreSQLComParsePacket parsePacket = mock(PostgreSQLComParsePacket.class); when(parsePacket.getIdentifier()).thenReturn(PostgreSQLCommandPacketType.PARSE_COMMAND); PostgreSQLComBindPacket bindPacket = mock(Postgre...
private MergeSortedPages() {}
@Test public void testDifferentTypes() throws Exception { List<Type> types = ImmutableList.of(DOUBLE, VARCHAR, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(2, 0, 1), ImmutableList.of(DESC_NULLS_LAST, D...
@Udf(description = "Returns a masked version of the input string. All characters except for the" + " first n will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final St...
@Test public void shouldNotMaskFirstNChars() { final String result = udf.mask("AbCd#$123xy Z", 5); assertThat(result, is("AbCd#-nnnxx-X")); }
@Override public CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath, Time timeout) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return CompletableFuture.supplyAsync( () -> { log.info("Disposing savepoint {}."...
@Test public void testSavepointDisposal() throws Exception { final URI externalPointer = createTestingSavepoint(); final Path savepointPath = Paths.get(externalPointer); dispatcher = createAndStartDispatcher( heartbeatServices, ...
public static Map<String, Set<String>> getVarListInString(String input) { Map<String, Set<String>> varMap = new HashMap<>(); Matcher matcher = VAR_PATTERN_IN_DEST.matcher(input); while (matcher.find()) { // $var or ${var} String varName = matcher.group(0); // var or {var} String stri...
@Test public void testGetVarListInString() throws IOException { String srcRegex = "/(\\w+)"; String target = "/$0/${1}/$1/${2}/${2}"; RegexMountPoint regexMountPoint = new RegexMountPoint(inodeTree, srcRegex, target, null); regexMountPoint.initialize(); Map<String, Set<String>> varMap = re...
@Nullable @Override public Message decode(@Nonnull final RawMessage rawMessage) { final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress()); final String json = gelfMessage.getJSON(decompressSizeLimit, charset); final JsonNode node; ...
@Test public void decodeFailsWithEmptyHost() throws Exception { final String json = "{" + "\"version\": \"1.1\"," + "\"host\": \"\"," + "\"short_message\": \"A short message that helps you identify what is going on\"" + "}"; final RawM...
public TaskManagerJobMetricGroup addJob(JobID jobId, String jobName) { Preconditions.checkNotNull(jobId); String resolvedJobName = jobName == null || jobName.isEmpty() ? jobId.toString() : jobName; TaskManagerJobMetricGroup jobGroup; synchronized (this) { // synchronization isn't strictl...
@Test void testCloseWithoutRemoval() { TaskManagerJobMetricGroup jobGroup = metricGroup.addJob(JOB_ID, JOB_NAME); metricGroup.close(); assertThat(jobGroup.isClosed()).isTrue(); }
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testEarlierOffsetResetArrivesLate() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.EARLIEST); offsetFetcher.resetPositionsIfNeeded(); client.prepareResponse(req -> { if (listOffsetMat...
@GET @Path("{id}") @ApiOperation("Get a single view") public ViewDTO get(@ApiParam(name = "id") @PathParam("id") @NotEmpty String id, @Context SearchUser searchUser) { if ("default".equals(id)) { // If the user is not permitted to access the default view, return a 404 return ...
@Test public void invalidObjectIdReturnsViewNotFoundException() { final ViewsResource viewsResource = createViewsResource( mock(ViewService.class), mock(StartPageService.class), mock(RecentActivityService.class), mock(ClusterEventBus.class), ...
@Override public void execute(Exchange exchange) throws SmppException { byte[] message = getShortMessage(exchange.getIn()); ReplaceSm replaceSm = createReplaceSmTempate(exchange); replaceSm.setShortMessage(message); if (log.isDebugEnabled()) { log.debug("Sending replace...
@Test public void executeWithValidityPeriodAsString() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "ReplaceSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); excha...
public Path find(final Path selected) { if(null == selected) { return workdir; } if(selected.getType().contains(Path.Type.volume)) { return selected; } return selected.getParent(); }
@Test public void testFindContainerSelected() { assertEquals(new Path("/container", EnumSet.of(Path.Type.directory, Path.Type.volume)), new UploadTargetFinder(new Path("/", EnumSet.of(Path.Type.directory))) .find(new Path("/container", EnumSet.of(Path.Type.directory, ...
public void writeMethodDescriptor(MethodReference methodReference) throws IOException { writeType(methodReference.getDefiningClass()); writer.write("->"); writeSimpleName(methodReference.getName()); writer.write('('); for (CharSequence paramType: methodReference.getParameterTypes...
@Test public void testWriteMethodDescriptor() throws IOException { DexFormattedWriter writer = new DexFormattedWriter(output); writer.writeMethodDescriptor(getMethodReference()); Assert.assertEquals("Ldefining/class;->methodName(Lparam1;Lparam2;)Lreturn/type;", output.toString()); }
public <T> Future<Iterable<Map.Entry<ByteString, Iterable<T>>>> multimapFetchAllFuture( boolean omitValues, ByteString encodedTag, String stateFamily, Coder<T> elemCoder) { StateTag<ByteString> stateTag = StateTag.<ByteString>of(Kind.MULTIMAP_ALL, encodedTag, stateFamily) .toBuilder() ...
@Test public void testReadMultimapAllEntries() throws Exception { Future<Iterable<Map.Entry<ByteString, Iterable<Integer>>>> future = underTest.multimapFetchAllFuture(false, STATE_KEY_1, STATE_FAMILY, INT_CODER); Mockito.verifyNoMoreInteractions(mockWindmill); Windmill.KeyedGetDataRequest.Builder...
@VisibleForTesting boolean parseArguments(String[] args) throws IOException { Options opts = new Options(); opts.addOption(Option.builder("h").build()); opts.addOption(Option.builder("help").build()); opts.addOption(Option.builder("input") .desc("Input class path. Defaults to the default class...
@Test void testWrongArgument() throws IOException { String[] args = new String[]{"-unexpected"}; FrameworkUploader uploader = new FrameworkUploader(); boolean success = uploader.parseArguments(args); assertFalse(success, "Expected to print help"); }
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE") public static LocalCommands open( final KsqlEngine ksqlEngine, final File directory ) { if (!directory.exists()) { if (!directory.mkdirs()) { throw new KsqlServerException("Couldn't create the local commands directory: " ...
@Test public void shouldThrowWhenCommandLocationIsNotDirectory() throws IOException { // Given File file = commandsDir.newFile(); // When final Exception e = assertThrows( KsqlServerException.class, () -> LocalCommands.open(ksqlEngine, file) ); // Then assertThat(e.getMes...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvAlreadyQuoted() { CharSequence value = "\"something\""; CharSequence expected = "\"something\""; escapeCsv(value, expected); }
@InterfaceAudience.Public @InterfaceStability.Evolving public static void setConfiguration(Configuration conf) { initialize(conf, true); }
@Test (timeout = 30000) public void testConstructorWithRules() throws Exception { // security off, but use rules if explicitly set conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL, "RULE:[1:$1@$0](.*@OTHER.REALM)s/(.*)@.*/other-$1/"); conf.set(HADOOP_SECURITY_AUTH_TO_LOCAL_MECHANISM, "hadoop"); UserGrou...
@Override public void transferBufferOwnership(Object oldOwner, Object newOwner, Buffer buffer) { checkState(buffer.isBuffer(), "Only buffer supports transfer ownership."); decNumRequestedBuffer(oldOwner); incNumRequestedBuffer(newOwner); buffer.setRecycler(memorySegment -> recycleBuf...
@Test void testCanNotTransferOwnershipForEvent() throws IOException { TieredStorageMemoryManagerImpl memoryManager = createStorageMemoryManager( 1, Collections.singletonList(new TieredStorageMemorySpec(this, 0))); BufferConsumer bufferConsumer = ...
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) { HttpHeaders inHeaders = in.headers(); final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size()); if (in instanceof HttpRequest) { HttpRequest request = (HttpRequest) in; ...
@Test public void stripConnectionHeadersAndNominees() { HttpHeaders inHeaders = new DefaultHttpHeaders(); inHeaders.add(CONNECTION, "foo"); inHeaders.add("foo", "bar"); Http2Headers out = new DefaultHttp2Headers(); HttpConversionUtil.toHttp2Headers(inHeaders, out); as...
public String cloneNote(String sourceNoteId, String newNotePath, AuthenticationInfo subject) throws IOException { return cloneNote(sourceNoteId, "", newNotePath, subject); }
@Test void testCloneNote() throws Exception { String noteId = notebook.createNote("note1", anonymous); notebook.processNote(noteId, note -> { final Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS); p.setText("hello world"); try { note.runAll(anonymous, t...
public Set<String> makeReady(final Map<String, InternalTopicConfig> topics) { // we will do the validation / topic-creation in a loop, until we have confirmed all topics // have existed with the expected number of partitions, or some create topic returns fatal errors. log.debug("Starting to vali...
@Test public void shouldExhaustRetriesOnMarkedForDeletionTopic() { mockAdminClient.addTopic( false, topic1, Collections.singletonList(new TopicPartitionInfo(0, broker1, cluster, Collections.emptyList())), null); mockAdminClient.markTopicForDeletion(top...
public static <T> Flattened<T> flattenedSchema() { return new AutoValue_Select_Flattened.Builder<T>() .setNameFn(CONCAT_FIELD_NAMES) .setNameOverrides(Collections.emptyMap()) .build(); }
@Test @Category(NeedsRunner.class) public void testClashingNameWithRenameFlatten() { List<Row> bottomRow = IntStream.rangeClosed(0, 2) .mapToObj(i -> Row.withSchema(SIMPLE_SCHEMA).addValues(i, Integer.toString(i)).build()) .collect(Collectors.toList()); List<Row> rows = ...
public synchronized ListenableFuture<?> waitForMinimumWorkers() { if (currentWorkerCount >= workerMinCount) { return immediateFuture(null); } SettableFuture<?> future = SettableFuture.create(); workerSizeFutures.add(future); // if future does not finish in wait ...
@Test(timeOut = 10_000) public void testTimeoutWaitingForWorkers() throws InterruptedException { waitForMinimumWorkers(); assertFalse(workersTimeout.get()); addWorker(nodeManager); assertFalse(workersTimeout.get()); assertEquals(minWorkersLatch.getCount(), 1)...
public static String generateFileName(String string) { string = StringUtils.stripAccents(string); StringBuilder buf = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Character.isSpaceChar(c) && (buf.lengt...
@Test public void testFeedTitleContainsDash() { String result = FileNameGenerator.generateFileName("Left - Right"); assertEquals("Left - Right", result); }
public EclipseProfile getUserProfile(String accessToken) { checkApiUrl(); var headers = new HttpHeaders(); headers.setBearerAuth(accessToken); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); var requestUrl = UrlUtil.createApiUrl(eclipseApiUrl, "openvsx", "profile");...
@Test public void testGetUserProfile() throws Exception { Mockito.when(restTemplate.exchange(any(RequestEntity.class), eq(String.class))) .thenReturn(mockProfileResponse()); var profile = eclipse.getUserProfile("12345"); assertThat(profile).isNotNull(); assertThat(profi...
@Override public Double getDoubleAndRemove(K name) { return null; }
@Test public void testGetDoubleAndRemoveDefault() { assertEquals(1, HEADERS.getDoubleAndRemove("name1", 1), 0); }
public void shutdown(ComponentGraph graph) { shutdownConfigRetriever(); if (graph != null) { // As we are shutting down, there is no need to uninstall bundles. deconstructComponentsAndBundles(graph.generation(), List.of(), graph.allConstructedComponentsAndProviders()); ...
@Test void providers_are_invoked_only_when_needed() { writeBootstrapConfigs("id1", FailOnGetProvider.class); Container container = newContainer(dirConfigSource); ComponentGraph oldGraph = getNewComponentGraph(container); container.shutdown(oldGraph); }
public JType generate(JCodeModel codeModel, String className, String packageName, URL schemaUrl) { JPackage jpackage = codeModel._package(packageName); ObjectNode schemaNode = readSchema(schemaUrl); return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(nul...
@Test public void generateCreatesSchemaFromSchemaAsStringInput() throws IOException { String schemaContent = IOUtils.toString(this.getClass().getResourceAsStream("/schema/address.json")); final SchemaRule mockSchemaRule = mock(SchemaRule.class); final RuleFactory mockRuleFactory = mock(Ru...
@VisibleForTesting List<ScheduledFuture<?>> getScheduledFutures() { return scheduledFutures; }
@Test void requestClientToClose() throws Exception { doHandshakeComplete(); Mockito.reset(eventLoopSpy); authenticateChannel(); verify(eventLoopSpy).schedule(scheduledCaptor.capture(), anyLong(), eq(TimeUnit.SECONDS)); Runnable requestClientToClose = scheduledCaptor.getValue(...
@Override public Map<String, String> evaluate(FunctionArgs args, EvaluationContext context) { final String value = valueParam.required(args, context); if (Strings.isNullOrEmpty(value)) { return Collections.emptyMap(); } final CharMatcher kvPairsMatcher = splitParam.option...
@Test void testConcatDemiliter() { final Map<String, Expression> arguments = Map.of("value", valueExpression, "handle_dup_keys", new StringExpression(new CommonToken(0), ",")); Map<String, String> result = classUnderTest.evaluate(new FunctionArgs(classUnderTest, arguments), evaluati...
@Override public TransformResultMetadata getResultMetadata() { return BOOLEAN_SV_NO_DICTIONARY_METADATA; }
@Test public void testLogicalOperatorTransformFunction() { ExpressionContext intEqualsExpr = RequestContextUtils.getExpression(String.format("EQUALS(%s, %d)", INT_SV_COLUMN, _intSVValues[0])); ExpressionContext longEqualsExpr = RequestContextUtils.getExpression(String.format("EQUALS(%s, %d)", ...
@Override public Result<V, E> search(Graph<V, E> graph, V src, V dst, EdgeWeigher<V, E> weigher, int maxPaths) { checkArguments(graph, src, dst); return internalSearch(graph, src, dst, weigher != null ? weigher : new DefaultEdgeWeigher<>(), ...
@Test(expected = NullPointerException.class) public void nullGraphArgument() { graphSearch().search(null, A, H, weigher, 1); }
@Nonnull @SuppressWarnings("checkstyle:MagicNumber") // number of hours per day isn't magic :) public static String formatJobDuration(long durationMs) { if (durationMs == Long.MIN_VALUE) { return "" + Long.MIN_VALUE; } String sign = ""; if (durationMs < 0) { ...
@Test public void test_formatJobDuration() { assertEquals("20:19:02.855", formatJobDuration(73_142_855)); assertEquals("00:00:00.120", formatJobDuration(120)); assertEquals("00:00:05.120", formatJobDuration(5120)); assertEquals("13d 13:52:22.855", formatJobDuration(1173_142_855)); ...
@VisibleForTesting ExportResult<MediaContainerResource> exportOneDrivePhotos(TokensAndUrlAuthData authData, Optional<IdOnlyContainerResource> albumData, Optional<PaginationData> paginationData, UUID jobId) throws IOException { Optional<String> albumId = Optional.empty(); if (albumData.isPresent())...
@Test public void exportMediaWithNextPage() throws IOException { // Setup when(driveItemsResponse.getNextPageLink()).thenReturn(null); when(driveItemsResponse.getDriveItems()).thenReturn(new MicrosoftDriveItem[] { setUpSinglePhoto(PHOTO_FILENAME, PHOTO_URI, PHOTO_ID), setUpSingleVideo(VIDEO_FI...
@ApolloAuditLog(type = OpType.CREATE, name = "AppNamespace.create", description = "createDefaultAppNamespace") @Transactional public void createDefaultAppNamespace(String appId) { if (!isAppNamespaceNameUnique(appId, ConfigConsts.NAMESPACE_APPLICATION)) { throw new BadRequestException("App already has app...
@Test @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testCreateDefaultAppNamespace() { appNamespaceService.createDefaultAppNamespace(APP); AppNamespace appNamespace = appNamespaceService.findByAppIdAndName(APP, ConfigConsts.NAMESPACE_APPLICATION); ...
Object getCellValue(Cell cell, Schema.FieldType type) { ByteString cellValue = cell.getValue(); int valueSize = cellValue.size(); switch (type.getTypeName()) { case BOOLEAN: checkArgument(valueSize == 1, message("Boolean", 1)); return cellValue.toByteArray()[0] != 0; case BYTE: ...
@Test public void shouldParseBytesType() { byte[] value = new byte[] {1, 2, 3, 4, 5}; assertEquals( ByteString.copyFrom(value), ByteString.copyFrom((byte[]) PARSER.getCellValue(cell(value), BYTES))); }
@Override public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { if(proxy.isSupported(source, target)) { return proxy.copy(source, target, status, callback, listener); ...
@Test public void testCopyFileToDifferentDataRoom() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room1 = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directo...
public static boolean hasAnnotation(Class clazz, String annotationClass) { for (Annotation annot : clazz.getDeclaredAnnotations()) if (annot.annotationType().getName().equals(annotationClass)) return true; return false; }
@Test public void testHasAnnotationJavassist() throws Exception { ClassPool ctPool = ClassPool.getDefault(); CtClass ctClass = ctPool.getCtClass(AnonymousClassPatchPlugin.class.getName()); assertTrue(AnnotationHelper.hasAnnotation(ctClass, "org.hotswap.agent.annotation.Plugin")); as...
@Override public String rendering() { final StringBuilder ladderSB = new StringBuilder(); int deep = 0; for (String item : items) { // no separator is required for the first item if (deep == 0) { ladderSB.append(item).append(System.lineSeparator()); ...
@Test void testRendering() throws Exception { TLadder ladder = new TLadder(); ladder.addItem("1"); ladder.addItem("2"); ladder.addItem("3"); ladder.addItem("4"); String result = ladder.rendering(); String expected = "1" + System.lineSeparator() + " `-2" ...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { final AttributedList<Path> list = new AttributedList<>(); list.add(MYFILES_NAME); list.add(SHARED_NAME); ...
@Test public void testListShared() throws Exception { final AttributedList<Path> list = new OneDriveListService(session, fileid).list(OneDriveListService.SHARED_NAME, new DisabledListProgressListener()); assertFalse(list.isEmpty()); for(Path f : list) { assertEquals(OneDriveListS...
@Override public String version() { return AppInfoParser.getVersion(); }
@Test public void testTimestampRouterVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), xform.version()); }
public static <V> Values<V> create() { return new Values<>(); }
@Test @Category(NeedsRunner.class) public void testValuesEmpty() { PCollection<KV<String, Integer>> input = p.apply( Create.of(Arrays.asList(EMPTY_TABLE)) .withCoder(KvCoder.of(StringUtf8Coder.of(), BigEndianIntegerCoder.of()))); PCollection<Integer> output = input.appl...
public static AliyunClientFactory from(Map<String, String> properties) { String factoryImpl = PropertyUtil.propertyAsString( properties, AliyunProperties.CLIENT_FACTORY, DefaultAliyunClientFactory.class.getName()); return loadClientFactory(factoryImpl, properties); ...
@Test public void testLoadCustom() { Map<String, String> properties = Maps.newHashMap(); properties.put(AliyunProperties.CLIENT_FACTORY, CustomFactory.class.getName()); assertThat(AliyunClientFactories.from(properties)) .as("Should load custom class") .isInstanceOf(CustomFactory.class); ...
@Override public void ignoreAutoTrackActivity(Class<?> activity) { }
@Test public void ignoreAutoTrackActivity() { mSensorsAPI.ignoreAutoTrackActivity(EmptyActivity.class); Assert.assertTrue(mSensorsAPI.isActivityAutoTrackAppClickIgnored(EmptyActivity.class)); }
public void matches(@Nullable String regex) { checkNotNull(regex); if (actual == null) { failWithActual("expected a string that matches", regex); } else if (!actual.matches(regex)) { if (regex.equals(actual)) { failWithoutActual( fact("expected to match", regex), ...
@Test public void stringMatchesStringWithFail() { expectFailureWhenTestingThat("abcaqadev").matches(".*aaa.*"); assertFailureValue("expected to match", ".*aaa.*"); }
@Override public PageResult<SmsTemplateDO> getSmsTemplatePage(SmsTemplatePageReqVO pageReqVO) { return smsTemplateMapper.selectPage(pageReqVO); }
@Test public void testGetSmsTemplatePage() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomPojo(SmsTemplateDO.class, o -> { // 等会查询到 o.setType(SmsTemplateTypeEnum.PROMOTION.getType()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCode("tudou"); ...