focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Duration parseDuration(String text) { checkNotNull(text); final String trimmed = text.trim(); checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string"); final int len = trimmed.length(); int pos = 0; char current; while ...
@Test void testParseDurationMinutes() { assertThat(TimeUtils.parseDuration("7657623m").toMinutes()).isEqualTo(7657623); assertThat(TimeUtils.parseDuration("7657623min").toMinutes()).isEqualTo(7657623); assertThat(TimeUtils.parseDuration("7657623minute").toMinutes()).isEqualTo(7657623); ...
String getFirstTimeTriggerTimeZone() { if (timeTriggers != null && !timeTriggers.isEmpty()) { return timeTriggers.get(0).getTimezone(); } return null; }
@Test public void testGetFirstTimeTriggerTimeZone() throws Exception { WorkflowInstance instance = loadObject( "fixtures/instances/sample-workflow-instance-created.json", WorkflowInstance.class); CronTimeTrigger cronTrigger1 = new CronTimeTrigger(); cronTrigger1.setTimezone("US/Pacific...
public static boolean subjectExists( final SchemaRegistryClient srClient, final String subject ) { return getLatestSchema(srClient, subject).isPresent(); }
@Test public void shouldThrowAuthorizationExceptionOnUnauthorizedSubjectAccess() throws Exception { // Given: when(schemaRegistryClient.getLatestSchemaMetadata("bar-value")).thenThrow( new RestClientException( "User is denied operation Write on Subject: bar-value; error code: 40301", 403, ...
public static String decodeBase64(final String what) { return new String(BaseEncoding.base64().decode(what), StandardCharsets.UTF_8); }
@Test public void testDecodeBase64() { assertEquals("lolwat.encoded", Tools.decodeBase64("bG9sd2F0LmVuY29kZWQ=")); }
public static int getSizeOfPrimitiveType(TypeRef<?> numericType) { return getSizeOfPrimitiveType(getRawType(numericType)); }
@Test public void testGetSizeOfPrimitiveType() { List<Integer> sizes = ImmutableList.of( void.class, boolean.class, byte.class, char.class, short.class, int.class, float.class, l...
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { if (userSession.hasSession() && userSession.isLoggedIn() && userSession.shouldResetPassword()) { redirectTo(response, request.getContextPath() + RESET_PASSWORD_PATH); } chain.doFilter(...
@Test public void do_not_redirect_if_not_logged_in() throws Exception { when(session.isLoggedIn()).thenReturn(false); underTest.doFilter(request, response, chain); verify(response, never()).sendRedirect(any()); }
@GET @Operation(summary = "Get details about this Connect worker and the ID of the Kafka cluster it is connected to") public ServerInfo serverInfo() { return new ServerInfo(herder.kafkaClusterId()); }
@Test public void testRootGet() { when(herder.kafkaClusterId()).thenReturn(MockAdminClient.DEFAULT_CLUSTER_ID); ServerInfo info = rootResource.serverInfo(); assertEquals(AppInfoParser.getVersion(), info.version()); assertEquals(AppInfoParser.getCommitId(), info.commit()); as...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertSmallint() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("SMALLINT") .dataType("SMALLINT") .build(); Column column...
@Override public LocalAddress localAddress() { return (LocalAddress) super.localAddress(); }
@Test public void localChannelRaceCondition() throws Exception { final CountDownLatch closeLatch = new CountDownLatch(1); final EventLoopGroup clientGroup = new DefaultEventLoopGroup(1) { @Override protected EventLoop newChild(Executor threadFactory, Object... args) ...
@SuppressWarnings("unchecked") public static Class<? extends UuidGenerator> parseUuidGenerator(String cucumberUuidGenerator) { Class<?> uuidGeneratorClass; try { uuidGeneratorClass = Class.forName(cucumberUuidGenerator); } catch (ClassNotFoundException e) { throw new ...
@Test void parseUuidGenerator_IncrementingUuidGenerator() { // When Class<? extends UuidGenerator> uuidGeneratorClass = UuidGeneratorParser .parseUuidGenerator(IncrementingUuidGenerator.class.getName()); // Then assertEquals(IncrementingUuidGenerator.class, uuidGener...
@Override @SuppressWarnings("ReferenceEquality") protected boolean evaluateDependencies(final Dependency dependency, final Dependency nextDependency, final Set<Dependency> dependenciesToRemove) { Dependency main; //CSOFF: InnerAssignment if ((main = getMainGemspecDependency(dependency, n...
@Test public void testEvaluateDependencies() { // Dependency dependency = null; // Dependency nextDependency = null; // Set<Dependency> dependenciesToRemove = null; // DependencyMergingAnalyzer instance = new DependencyMergingAnalyzer(); // boolean expResult = false; // boo...
@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 testPrintWithMultipleRows() { PrintStyle.tableauWithDataInferredColumnWidths(getSchema(), getConverter()) .print(getData().iterator(), new PrintWriter(outContent)); // note: the expected result may look irregular because every CJK(Chinese/Japanese/Korean) // chara...
static String generateDatabaseName(String baseString) { baseString = Character.isLetter(baseString.charAt(0)) ? baseString : "d_" + baseString; return generateResourceId( baseString, ILLEGAL_DATABASE_NAME_CHARS, REPLACE_DATABASE_NAME_CHAR, MAX_DATABASE_NAME_LENGTH, TIME_F...
@Test public void testGenerateDatabaseNameShouldReplaceIllegalCharacters() { String testBaseString = "!@#_()"; String actual = generateDatabaseName(testBaseString); assertThat(actual).matches("d___#___\\d{8}_\\d{6}_\\d{6}"); }
@Override public ParSeqBasedCompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) { return nextStageByComposingTask(_task.transform("whenComplete", prevTaskResult -> { if (prevTaskResult.isFailed()) { try { action.accept(null, prevTaskResult.getError()); ...
@Test public void testWhenComplete_useUnwrappedException() throws Exception { BiConsumer<String, Throwable> biConsumer = mock(BiConsumer.class); CompletionStage<String> completionStage = createTestFailedStage(EXCEPTION); finish(completionStage.whenComplete(biConsumer)); verify(biConsumer, times(1))....
public static SqlType fromValue(final BigDecimal value) { // SqlDecimal does not support negative scale: final BigDecimal decimal = value.scale() < 0 ? value.setScale(0, BigDecimal.ROUND_UNNECESSARY) : value; /* We can't use BigDecimal.precision() directly for all cases, since it defines ...
@Test public void shouldGetSchemaFromDecimal4_3() { // When: final SqlType schema = DecimalUtil.fromValue(new BigDecimal("0.005")); // Then: assertThat(schema, is(SqlTypes.decimal(4, 3))); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(containerService.isContainer(file)) { final PathAttributes attributes = ...
@Test public void testMissingPlaceholder() throws Exception { final Path container = new AzureDirectoryFeature(session, null).mkdir( new Path(new AlphanumericRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); ...
public static boolean isUri(String potentialUri) { if (StringUtils.isBlank(potentialUri)) { return false; } try { URI uri = new URI(potentialUri); return uri.getScheme() != null && uri.getHost() != null; } catch (URISyntaxException e) { re...
@Test public void returns_false_when_uri_doesnt_contain_host() { assertThat(UriValidator.isUri("http://"), is(false)); }
public boolean isMatch(String input) { for (StringMatch stringMatch : oneof) { if (stringMatch.isMatch(input)) { return true; } } return false; }
@Test void isMatch() { ListStringMatch listStringMatch = new ListStringMatch(); List<StringMatch> oneof = new ArrayList<>(); StringMatch stringMatch1 = new StringMatch(); stringMatch1.setExact("1"); StringMatch stringMatch2 = new StringMatch(); stringMatch2.setExac...
public Type type() { return type; }
@Test void testType() { final var prototype = new Character(); prototype.set(Stats.ARMOR, 1); prototype.set(Stats.INTELLECT, 2); assertNull(prototype.type()); final var stupid = new Character(Type.ROGUE, prototype); stupid.remove(Stats.INTELLECT); assertEquals(Type.ROGUE, stupid.type()); ...
public ExitStatus(Options options) { this.options = options; }
@Test void should_pass_if_no_features_are_found() { createRuntime(); assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x0))); }
@Description("count of code points of the given string") @ScalarFunction @LiteralParameters("x") @SqlType(StandardTypes.BIGINT) public static long length(@SqlType("varchar(x)") Slice slice) { return countCodePoints(slice); }
@Test public void testLength() { assertFunction("LENGTH('')", BIGINT, 0L); assertFunction("LENGTH('hello')", BIGINT, 5L); assertFunction("LENGTH('Quadratically')", BIGINT, 13L); // // Test length for non-ASCII assertFunction("LENGTH('hello na\u00EFve world')", BIG...
@Override public List<Instance> getAllInstances(String serviceName) throws NacosException { return getAllInstances(serviceName, new ArrayList<>()); }
@Test void testGetAllInstanceFromFailover() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); serviceInfo.setHosts(Collections.singletonList(new Instance())); when(serviceInfoHolder.getF...
static Map<Boolean, List<String>> partitionSupport( String[] supportedByJVM, String[] enabledByJVM, String[] excludedByConfig, String[] includedByConfig ) { final List<Pattern> enabled = Arrays.stream(enabledByJVM).map(Pattern::compile).collect(Collectors.toList()); f...
@Test void partitionSupportInclude() { final String[] supported = {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; final String[] enabled = {"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; final String[] exclude = {"SSL*"}; final String[] include = {"TLSv1.2|SSLv2Hello"}; fin...
public static boolean isUnclosedQuote(final String line) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity int quoteStart = -1; for (int i = 0; i < line.length(); ++i) { if (quoteStart < 0 && isQuoteChar(line, i)) { quoteStart = i; } else if (quoteStart >= 0 && isTwoQuoteStart(line, i) && !...
@Test public void shouldNotFindUnclosedQuote_endsQuote() { // Given: final String line = "some line 'this is in a quote'"; // Then: assertThat(UnclosedQuoteChecker.isUnclosedQuote(line), is(false)); }
public static Read read() { return new AutoValue_RabbitMqIO_Read.Builder() .setQueueDeclare(false) .setExchangeDeclare(false) .setMaxReadTime(null) .setMaxNumRecords(Long.MAX_VALUE) .setUseCorrelationId(false) .build(); }
@Test public void testUseCorrelationIdSucceedsWhenIdsPresent() throws Exception { int messageCount = 1; AMQP.BasicProperties publishProps = new AMQP.BasicProperties().builder().correlationId("123").build(); doExchangeTest( new ExchangeTestPlan( RabbitMqIO.read() ...
public static String decodeObjectIdentifier(byte[] data) { return decodeObjectIdentifier(data, 0, data.length); }
@Test public void decodeObjectIdentifierWithDoubleBytes() { assertEquals("1.2.131", Asn1Utils.decodeObjectIdentifier(new byte[] { 0x2a, (byte) 0x81, 0x03 })); }
@Activate public void activate() { driverAdminService.addListener(driverListener); eventDispatcher.addSink(PiPipeconfEvent.class, listenerRegistry); checkMissingMergedDrivers(); if (!missingMergedDrivers.isEmpty()) { // Missing drivers should be created upon detecting reg...
@Test public void activate() { assertEquals("Incorrect driver admin service", driverAdminService, mgr.driverAdminService); assertEquals("Incorrect driverAdminService service", driverAdminService, mgr.driverAdminService); assertEquals("Incorrect configuration service", cfgService, mgr.cfgServ...
public static Protocol adaptiveProtocol(byte[] magicHeadBytes) { for (Protocol protocol : TYPE_PROTOCOL_MAP.values()) { if (protocol.protocolInfo().isMatchMagic(magicHeadBytes)) { return protocol; } } return null; }
@Test public void adaptiveProtocol() throws Exception { }
public List<HintRule> getHintRules() { return hintRules; }
@Test public void testHandler() throws ParserConfigurationException, SAXException, IOException { File file = BaseTest.getResourceAsFile(this, "hints.xml"); File schema = BaseTest.getResourceAsFile(this, "schema/dependency-hint.1.1.xsd"); HintHandler handler = new HintHandler(); SAXP...
@Override public void visitField(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) { // Each new property should put as required and we should not allow additional properties. ArrayNode required = getRequiredArrayNode(); required.add(queryVisitorFieldEnvironment.getFieldDefinition().getNa...
@Test public void testVisitFieldWithEnumType() { QueryVisitorFieldEnvironment environment = mock(QueryVisitorFieldEnvironment.class); GraphQLEnumType enumType = mock(GraphQLEnumType.class); TypeName definitionType = TypeName.newTypeName().name("EnumType").build(); when(environment.getFieldDe...
@Override public void to(final String topic) { to(topic, Produced.with(keySerde, valueSerde, null)); }
@Test public void shouldNotAllowNullTopicOnToWithProduced() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.to((String) null, Produced.as("to"))); assertThat(exception.getMessage(), equalTo("topic can't be null")); }
@Override public <T> AsyncResult<T> startProcess(Callable<T> task) { return startProcess(task, null); }
@Test void testLongRunningTaskWithoutCallback() { assertTimeout(ofMillis(5000), () -> { // Instantiate a new executor and start a new 'null' task ... final var executor = new ThreadAsyncExecutor(); final var result = new Object(); when(task.call()).thenAnswer(i -> { Thread.sleep(1...
@Override public String getRequestURL() { val url = request.getRequestURL().toString(); var idx = url.indexOf('?'); if (idx != -1) { return url.substring(0, idx); } return url; }
@Test public void testGetRequestUrl() throws Exception { when(request.getRequestURL()).thenReturn(new StringBuffer("https://pac4j.org?name=value&name2=value2")); WebContext context = new JEEContext(request, response); assertEquals("https://pac4j.org", context.getRequestURL()); }
@PrivateApi public static <V> Collection<V> returnWithDeadline(Collection<Future<V>> futures, long timeout, TimeUnit timeUnit) { return returnWithDeadline(futures, timeout, timeUnit, IGNORE_ALL_EXCEPT_LOG_MEMBER_LEFT); }
@Test public void test_returnWithDeadline_failing_second() { AtomicBoolean waitLock = new AtomicBoolean(true); List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add(executorService.submit(new FailingCallable(waitLock))); } ...
@Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var originator = msg.getOriginator(); var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null; if (!EntityType.DEVICE.equals(origin...
@Test void givenGetDeviceCredentials_whenOnMsg_thenShouldTellFailure() throws Exception { // GIVEN doReturn(deviceCredentialsServiceMock).when(ctxMock).getDeviceCredentialsService(); willAnswer(invocation -> null).given(deviceCredentialsServiceMock).findDeviceCredentialsByDeviceId(any(), any...
public Sensor cacheLevelSensor(final String threadId, final String taskName, final String storeName, final String ratioName, final Sensor.RecordingLevel recordingLevel, ...
@Test public void shouldGetExistingCacheLevelSensor() { final Metrics metrics = mock(Metrics.class); final RecordingLevel recordingLevel = RecordingLevel.INFO; final String processorCacheName = "processorNodeName"; setupGetExistingSensorTest(metrics); final StreamsMetricsImpl...
@Override protected double maintain() { List<Node> provisionedSnapshot; try { NodeList nodes; // Host and child nodes are written in separate transactions, but both are written while holding the // unallocated lock. Hold the unallocated lock while reading nodes to...
@Test public void does_not_deprovision_when_preprovisioning_enabled() { tester = new DynamicProvisioningTester().addInitialNodes(); setPreprovisionCapacityFlag(tester, new ClusterCapacity(1, 1.0, 3.0, 2.0, 1.0, "fast", "remote", "x86_64", null)); Optional<Node> failedHost = node("host2"); ...
@Override public Path copy(final Path file, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { if(status.isExists()) { if(log.isWarnEnabled()) { log.warn(String.f...
@Test public void testCopyFile() throws Exception { final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final Path target = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomS...
@Override public E poll(final long timeout, final TimeUnit unit) throws InterruptedException { final E e = super.poll(timeout, unit); memoryLimiter.releaseInterruptibly(e, timeout, unit); return e; }
@Test public void testPoll() { MemoryLimitedLinkedBlockingQueue<Integer> queue = new MemoryLimitedLinkedBlockingQueue<>(instrumentation); Integer testObject = 0; queue.offer(testObject); assertEquals(testObject, queue.poll()); assertEquals(0, queue.getCurrentMemory()); }
public static Optional<Object> getAdjacentValue(Type type, Object value, boolean isPrevious) { if (!type.isOrderable()) { throw new IllegalStateException("Type is not orderable: " + type); } requireNonNull(value, "value is null"); if (type.equals(BIGINT) || type instance...
@Test public void testPreviousValueForTinyInt() { long minValue = Byte.MIN_VALUE; long maxValue = Byte.MAX_VALUE; assertThat(getAdjacentValue(TINYINT, minValue, true)) .isEqualTo(Optional.empty()); assertThat(getAdjacentValue(TINYINT, minValue + 1, true)) ...
public static CharSequence removeGender( @NonNull CharSequence text, @NonNull JavaEmojiUtils.Gender gender) { return JavaEmojiUtils.removeGender(text, gender); }
@Test public void testRemoveGender() { for (JavaEmojiUtils.Gender gender : JavaEmojiUtils.Gender.values()) { Assert.assertEquals( "\uD83D\uDC4D", EmojiUtils.removeGender("\uD83D\uDC4D", gender).toString()); } // woman-mini-qualified Assert.assertEquals( "\uD83E\uDDD4", ...
protected abstract void heartbeat() throws Exception;
@Test(timeout = 2000) public void testRMContainerAllocatorYarnRuntimeExceptionIsHandled() throws Exception { ClientService mockClientService = mock(ClientService.class); AppContext mockContext = mock(AppContext.class); MockRMCommunicator mockRMCommunicator = new MockRMCommunicator(mockClient...
@Override public CompressionProvider createCompressionProviderInstance( String name ) { CompressionProvider provider = null; List<PluginInterface> providers = getPlugins(); if ( providers != null ) { for ( PluginInterface plugin : providers ) { if ( name != null && name.equalsIgnoreCase( p...
@Test public void testCreateCoreProviders() { CompressionProvider provider = factory.createCompressionProviderInstance( "None" ); assertNotNull( provider ); assertTrue( provider.getClass().isAssignableFrom( NoneCompressionProvider.class ) ); assertEquals( "None", provider.getName() ); assertEquals...
public static AggregateOperation1<CharSequence, StringBuilder, String> concatenating() { return AggregateOperation .withCreate(StringBuilder::new) .<CharSequence>andAccumulate(StringBuilder::append) .andCombine(StringBuilder::append) .andExportFini...
@Test public void when_concatenating_withDelimiterPrefixSuffix() { validateOpWithoutDeduct( concatenating(",", "(", ")"), StringBuilder::toString, "A", "B", "(A", "(A,B", "(A,B)" ); }
public static <T> ReadAll<T> readAll() { return new AutoValue_CassandraIO_ReadAll.Builder<T>().build(); }
@Test public void testReadAllQuery() { String physQuery = String.format( "SELECT * From %s.%s WHERE person_department='phys' AND person_id=0;", CASSANDRA_KEYSPACE, CASSANDRA_TABLE); String mathQuery = String.format( "SELECT * From %s.%s WHERE person_departm...
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { Http2HeadersSink sink = new Http2HeadersSink( streamId, headers, maxHeaderListSize, validateHeaders); // Check for dynamic table size updates, which must occur at the beginning: ...
@Test public void testIllegalIndex() throws Http2Exception { // Index larger than the header table assertThrows(Http2Exception.class, new Executable() { @Override public void execute() throws Throwable { decode("FF00"); } }); }
public boolean canPassCheck(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node, int acquireCount) { return canPassCheck(rule, context, node, acquireCount, false); }
@Test public void testPassCheckSelectEmptyNodeSuccess() { FlowRule rule = new FlowRule("abc").setCount(1); rule.setLimitApp("abc"); DefaultNode node = mock(DefaultNode.class); Context context = mock(Context.class); when(context.getOrigin()).thenReturn("def"); FlowRu...
static InjectorSource instantiateUserSpecifiedInjectorSource(Class<?> injectorSourceClass) { try { return (InjectorSource) injectorSourceClass.getConstructor().newInstance(); } catch (Exception e) { String message = format("Instantiation of '%s' failed. Check the caused by except...
@Test void failsToInstantiateClassWithNoDefaultConstructor() { Executable testMethod = () -> instantiateUserSpecifiedInjectorSource(NoDefaultConstructor.class); InjectorSourceInstantiationFailed actualThrown = assertThrows(InjectorSourceInstantiationFailed.class, testMethod); ass...
@JsonIgnore public boolean canHaveCustomFieldMappings() { return !this.indexTemplateType().map(TEMPLATE_TYPES_FOR_INDEX_SETS_WITH_IMMUTABLE_FIELD_TYPES::contains).orElse(false); }
@Test public void testEventIndexWithChangedFieldMappingsIsIllegal() { assertFalse(testIndexSetConfig(EVENT_TEMPLATE_TYPE, new CustomFieldMappings(List.of(new CustomFieldMapping("john", "long"))), null).canHaveCustomFieldMappings()); }
@Override public DataTableType dataTableType() { return dataTableType; }
@Test void can_define_table_cell_transformer() throws NoSuchMethodException { Method method = JavaDataTableTypeDefinitionTest.class.getMethod("converts_table_cell_to_string", String.class); JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, lookup, new String[0]); ...
@Override public UpdateApplicationPriorityResponse updateApplicationPriority( UpdateApplicationPriorityRequest request) throws YarnException, IOException { ApplicationId applicationId = request.getApplicationId(); Priority newAppPriority = request.getApplicationPriority(); UserGroupInformati...
@Test(timeout = 120000) public void testUpdateApplicationPriorityRequest() throws Exception { int maxPriority = 10; int appPriority = 5; conf = new YarnConfiguration(); Assume.assumeFalse("FairScheduler does not support Application Priorities", conf.get(YarnConfiguration.RM_SCHEDULER) ...
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test @Category(NeedsRunner.class) public void testNoFilterByPredicateWithLambda() { PCollection<Integer> output = p.apply(Create.of(1, 2, 4, 5)).apply(Filter.by(i -> false)); PAssert.that(output).empty(); p.run(); }
public static CompositeMeterRegistry getMeterRegistry(String registry) { return METER_REGISTRIES.get(registry); }
@Test void testGetMeterRegistry() { assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CORE_STABLE_REGISTRY)); assertNotNull(NacosMeterRegistryCenter.getMeterRegistry(NacosMeterRegistryCenter.CONFIG_STABLE_REGISTRY)); assertNotNull(NacosMeterRegistryCenter.getMe...
@SuppressWarnings("MethodLength") static void dissectControlRequest( final ArchiveEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); ...
@Test void controlRequestStopReplication() { internalEncodeLogHeader(buffer, 0, 1000, 1000, () -> 500_000_000L); final StopReplicationRequestEncoder requestEncoder = new StopReplicationRequestEncoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) ...
@Override public Set<DeviceId> getDevices(PiPipeconfId pipeconfId) { return ImmutableSet.copyOf(pipeconfToDevices.get(pipeconfId)); }
@Test public void getDevices() { clear(); createOrUpdatePipeconfToDeviceBinding(); assertEquals("Wrong set of DeviceIds", store.getDevices(PIPECONF_ID), ImmutableSet.of(DEVICE_ID)); }
@Override public CompletableFuture<ExecutionGraphInfo> getExecutionGraphInfo( JobID jobId, RestfulGateway restfulGateway) { return getExecutionGraphInternal(jobId, restfulGateway).thenApply(Function.identity()); }
@Test void testExecutionGraphCaching() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.hours(1L); final CountingRestfulGateway restfulGateway = createCountingRestfulGateway( expectedJobId, ...
@Override public String pluginNamed() { return PluginEnum.SOFA.getName(); }
@Test public void testPluginNamed() { assertEquals(sofaPluginDataHandler.pluginNamed(), PluginEnum.SOFA.getName()); }
public void contains(@Nullable CharSequence string) { checkNotNull(string); if (actual == null) { failWithActual("expected a string that contains", string); } else if (!actual.contains(string)) { failWithActual("expected to contain", string); } }
@Test public void stringInequalityIgnoringCaseFail() { expectFailureWhenTestingThat("café").ignoringCase().isNotEqualTo("CAFÉ"); assertFailureValue("expected not to be", "CAFÉ"); assertThat(expectFailure.getFailure()).factKeys().contains("(case is ignored)"); }
@Override public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> assignment = new HashMap<>(); List<MemberInfo> memberInfoList = new Arra...
@Test public void testTwoConsumersOneTopicOnePartition() { String consumer1 = "consumer1"; String consumer2 = "consumer2"; Map<String, Integer> partitionsPerTopic = new HashMap<>(); partitionsPerTopic.put(topic, 1); Map<String, Subscription> consumers = new HashMap<>(); ...
public Option<Dataset<Row>> loadAsDataset(SparkSession spark, List<CloudObjectMetadata> cloudObjectMetadata, String fileFormat, Option<SchemaProvider> schemaProviderOption, int numPartitions) { if (LOG.isDebugEnabled()) { LOG.debug("Extracted distinct files " + clou...
@Test public void loadDatasetWithSchemaAndRepartition() { TypedProperties props = new TypedProperties(); TestCloudObjectsSelectorCommon.class.getClassLoader().getResource("schema/sample_data_schema.avsc"); String schemaFilePath = TestCloudObjectsSelectorCommon.class.getClassLoader().getResource("schema/sa...
@Override public GcsPath getName(int count) { checkArgument(count >= 0); Iterator<Path> iterator = iterator(); for (int i = 0; i < count; ++i) { checkArgument(iterator.hasNext()); iterator.next(); } checkArgument(iterator.hasNext()); return (GcsPath) iterator.next(); }
@Test public void testGetName() { GcsPath a = GcsPath.fromComponents("bucket", "a/b/c/d"); assertEquals(5, a.getNameCount()); assertThat(a.getName(0).toString(), Matchers.equalTo("gs://bucket/")); assertThat(a.getName(1).toString(), Matchers.equalTo("a")); assertThat(a.getName(2).toString(), Match...
static <T> T getWildcardMappedObject(final Map<String, T> mapping, final String query) { T value = mapping.get(query); if (value == null) { for (String key : mapping.keySet()) { // Turn the search key into a regex, using all characters but the * as a literal. ...
@Test public void testWildcard() throws Exception { // Setup test fixture. final Map<String, Object> haystack = Map.of("myplugin/*", new Object()); // Execute system under test. final Object result = PluginServlet.getWildcardMappedObject(haystack, "myplugin/foo.jsp"); /...
@Override public void flush() throws IOException { currentTmpFile.write(buffer, 0, positionInBuffer); currentTmpFile.flush(); positionInBuffer = 0; }
@Test void testFlush() throws IOException { RefCountedBufferingFileStream stream = getStreamToTest(); final byte[] contentToWrite = bytesOf("hello"); stream.write(contentToWrite); assertThat(stream.getPositionInBuffer()).isEqualTo(contentToWrite.length); assertThat(stream.g...
@Override public void run() { // top-level command, do nothing }
@Test public void test_cancelJob_invalidNameOrId() { // When // Then exception.expectMessage("No job with name or id 'invalid' was found"); run("cancel", "invalid"); }
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testFailApi() { fail = true; run("fail-api.feature"); match(fr.result.getVariables(), "{ configSource: 'normal', functionFromKarateBase: '#notnull', before: true }"); }
@Override public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new BigQueryConnectorFactory()); }
@Test public void testStartup() { BigQueryPlugin plugin = new BigQueryPlugin(); ConnectorFactory factory = getOnlyElement(plugin.getConnectorFactories()); assertInstanceOf(factory, BigQueryConnectorFactory.class); }
@Override public V put(final K key, final V value) { checkAndScheduleRefresh(this); final V previous = cache.getIfPresent(key); cache.put(key, value); return previous; }
@Test public void testPut() { MemorySafeWindowTinyLFUMap<String, String> lru = new MemorySafeWindowTinyLFUMap<>(1 << 10, 16); lru.put("1", "1"); Assert.assertEquals(1, lru.size()); lru.put("2", "2"); lru.put("3", "3"); Assert.assertEquals(3, lru.size()); }
public static byte[] decodeOnionUrl(String onionUrl) { if (!onionUrl.toLowerCase(Locale.ROOT).endsWith(".onion")) throw new IllegalArgumentException("not an onion URL: " + onionUrl); byte[] onionAddress = BASE32.decode(onionUrl.substring(0, onionUrl.length() - 6)); if (onionAddress.l...
@Test(expected = IllegalArgumentException.class) public void decodeOnionUrl_badLength() { TorUtils.decodeOnionUrl("aaa.onion"); }
public Optional<Account> getByPhoneNumberIdentifier(final UUID pni) { return checkRedisThenAccounts( getByNumberTimer, () -> redisGetBySecondaryKey(getAccountMapKey(pni.toString()), redisPniGetTimer), () -> accounts.getByPhoneNumberIdentifier(pni) ); }
@Test void testGetAccountByPniBrokenCache() { UUID uuid = UUID.randomUUID(); UUID pni = UUID.randomUUID(); Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); when(commands.get(eq("Accoun...
@CanIgnoreReturnValue public boolean remove(JsonElement element) { return elements.remove(element); }
@Test public void testRemove() { JsonArray array = new JsonArray(); assertThrows(IndexOutOfBoundsException.class, () -> array.remove(0)); JsonPrimitive a = new JsonPrimitive("a"); array.add(a); assertThat(array.remove(a)).isTrue(); assertThat(array).doesNotContain(a); array.add(a); ar...
@SuppressWarnings({"unchecked", "UnstableApiUsage"}) @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement) { if (!(statement.getStatement() instanceof DropStatement)) { return statement; } final DropStatement dropStatement = (DropState...
@Test public void shouldNotThrowIfStatementHasIfExistsAndSourceDoesNotExist() { // Given: final ConfiguredStatement<DropStream> dropStatement = givenStatement( "DROP SOMETHING", new DropStream(SourceName.of("SOMETHING_ELSE"), true, true)); // When: deleteInjector.inject(dropStatement); }
@Override public LogicalSchema getSchema() { return outputSchema; }
@Test public void shouldBuildPullQueryOutputSchemaSelectKeyNonWindowed() { // Given: selects = ImmutableList.of(new SingleColumn(K_REF, Optional.of(K))); when(keyFormat.isWindowed()).thenReturn(false); when(analysis.getSelectColumnNames()).thenReturn(ImmutableSet.of(K)); // When: final QueryP...
ClassicGroup getOrMaybeCreateClassicGroup( String groupId, boolean createIfNotExists ) throws GroupIdNotFoundException { Group group = groups.get(groupId); if (group == null && !createIfNotExists) { throw new GroupIdNotFoundException(String.format("Classic group %s not f...
@Test public void testStaticMemberRejoinWithLeaderIdAndUnexpectedEmptyGroup() throws Exception { GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .build(); GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinA...
@Udf(description = "Returns the cube root of an INT value") public Double cbrt( @UdfParameter( value = "value", description = "The value to get the cube root of." ) final Integer value ) { return cbrt(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNull() { assertThat(udf.cbrt((Integer)null), is(nullValue())); assertThat(udf.cbrt((Long)null), is(nullValue())); assertThat(udf.cbrt((Double)null), is(nullValue())); }
public int boundedPoll(final FragmentHandler handler, final long limitPosition, final int fragmentLimit) { if (isClosed) { return 0; } final long initialPosition = subscriberPosition.get(); if (initialPosition >= limitPosition) { return 0; ...
@Test void shouldPollFragmentsToBoundedFragmentHandlerWithMaxPositionBeforeNextMessage() { final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID); final long maxPosition = initialPosition + ALIGNED_FRAME_LENGTH; position.setOrdered(initi...
@Override public <T> TableConfig set(ConfigOption<T> option, T value) { configuration.set(option, value); return this; }
@Test void testGetInvalidLocalTimeZoneUT() { CONFIG_BY_CONFIGURATION.set("table.local-time-zone", "UT+8"); assertThatThrownBy(CONFIG_BY_CONFIGURATION::getLocalTimeZone) .isInstanceOf(ValidationException.class) .hasMessageContaining("Invalid time zone."); }
@Override public InputFile newInputFile(String path) { return GCSInputFile.fromLocation(path, client(), gcpProperties, metrics); }
@Test public void newInputFile() throws IOException { String location = format("gs://%s/path/to/file.txt", TEST_BUCKET); byte[] expected = new byte[1024 * 1024]; random.nextBytes(expected); InputFile in = io.newInputFile(location); assertThat(in.exists()).isFalse(); OutputFile out = io.newOu...
public void addMergeTask(String dataId, String groupId, String tenant, String clientIp) { if (!canExecute()) { return; } MergeDataTask task = new MergeDataTask(dataId, groupId, tenant, clientIp); mergeTasks.addTask(task.getId(), task); }
@Test void testAddMergeTaskEmbeddedAndClusterModelNotLeader() { DatasourceConfiguration.setEmbeddedStorage(true); envUtilMockedStatic.when(() -> EnvUtil.getStandaloneMode()).thenReturn(false); TaskManager mockTasker = Mockito.mock(TaskManager.class); ReflectionTestUtils.setF...
@Override public PosixFileAttributeView view( FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) { return new View( lookup, (BasicFileAttributeView) inheritedViews.get("basic"), (FileOwnerAttributeView) inheritedViews.get("owner")); }
@Test public void testView() throws IOException { file.setAttribute("owner", "owner", createUserPrincipal("user")); PosixFileAttributeView view = provider.view( fileLookup(), ImmutableMap.of( "basic", new BasicAttributeProvider().view(fileLookup(), NO_INHERITED...
@Override public InputStream open(String path) throws IOException { final File file = new File(path); if (!file.exists()) { throw new FileNotFoundException("File " + file + " not found"); } return new FileInputStream(file); }
@Test void readsFileContents() throws Exception { try (InputStream input = provider.open(getClass().getResource("/example.txt").getFile()); ByteArrayOutputStream output = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int length; while ((lengt...
public static Path mergePaths(Path path1, Path path2) { String path2Str = path2.toUri().getPath(); path2Str = path2Str.substring(startPositionWithoutWindowsDrive(path2Str)); // Add path components explicitly, because simply concatenating two path // string is not safe, for example: // "/" + "/foo" y...
@Test (timeout = 30000) public void testMergePaths() { assertEquals(new Path("/foo/bar"), Path.mergePaths(new Path("/foo"), new Path("/bar"))); assertEquals(new Path("/foo/bar/baz"), Path.mergePaths(new Path("/foo/bar"), new Path("/baz"))); assertEquals(new Path("/foo/bar/baz...
@Override public TimeLimiter timeLimiter(final String name) { return timeLimiter(name, getDefaultConfig(), emptyMap()); }
@Test public void timeLimiterNewWithNullNameAndConfigSupplier() { exception.expect(NullPointerException.class); exception.expectMessage(NAME_MUST_NOT_BE_NULL); TimeLimiterRegistry registry = new InMemoryTimeLimiterRegistry(config); registry.timeLimiter(null, () -> config); }
void initDistCp() throws IOException, RetryException { RunningJobStatus job = getCurrentJob(); if (job != null) { // the distcp has been submitted. if (job.isComplete()) { jobId = null; // unset jobId because the job is done. if (job.isSuccessful()) { updateStage(Stage.DIFF...
@Test public void testInitDistCp() throws Exception { String testRoot = nnUri + "/user/foo/testdir." + getMethodName(); DistributedFileSystem fs = (DistributedFileSystem) FileSystem.get(URI.create(nnUri), conf); createFiles(fs, testRoot, srcfiles); Path src = new Path(testRoot, SRCDAT); P...
public double distanceToAsDouble(final IGeoPoint other) { final double lat1 = DEG2RAD * getLatitude(); final double lat2 = DEG2RAD * other.getLatitude(); final double lon1 = DEG2RAD * getLongitude(); final double lon2 = DEG2RAD * other.getLongitude(); return RADIUS_EARTH_METERS *...
@Test public void test_distanceTo_Equator_Smaller() { final double ratioDelta = 1E-5; final int iterations = 10; final double latitude = 0; double longitudeIncrement = 1; for (int i = 0; i < iterations; i++) { final double longitude1 = getRandomLongitude(); ...
@Override public Double getDouble(K name) { return null; }
@Test public void testGetDouble() { assertNull(HEADERS.getDouble("name1")); }
public Optional<HostFailurePath> worstCaseHostLossLeadingToFailure() { Map<Node, Integer> timesNodeCanBeRemoved = computeMaximalRepeatedRemovals(); return greedyHeuristicFindFailurePath(timesNodeCanBeRemoved); }
@Test public void testIpFailurePaths() { CapacityCheckerTester tester = new CapacityCheckerTester(); tester.createNodes(1, 10, 10, new NodeResources(10, 1000, 10000, 1), 1, 10, new NodeResources(10, 1000, 10000, 1), 1); var failurePath = tester.capacityChecker...
@Override public HttpResponse send(HttpRequest httpRequest) throws IOException { return send(httpRequest, null); }
@Test public void send_whenPostRequest_returnsExpectedHttpResponse() throws IOException { String responseBody = "{ \"test\": \"json\" }"; mockWebServer.enqueue( new MockResponse() .setResponseCode(HttpStatus.OK.code()) .setHeader(CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) ...
public static String pluginSelectorKey(final String pluginName) { return String.join("", pluginName, PLUGIN_SELECTOR); }
@Test public void testPluginSelectorKey() { String mockPlugin = "MockPlugin"; String mockPluginSelectorKey = RedisKeyConstants.pluginSelectorKey(mockPlugin); assertThat(mockPlugin, notNullValue()); assertThat(String.join("", mockPlugin, PLUGIN_SELECTOR), equalTo(mockPluginSelectorKey...
@Override public Long getLocalValue() { return this.min; }
@Test void testGet() { LongMinimum min = new LongMinimum(); assertThat(min.getLocalValue().longValue()).isEqualTo(Long.MAX_VALUE); }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertByte() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.BYTE_TYPE).build(); BasicTypeDefine typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertio...
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testEncryptedNullPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test_...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { ByteBuf newlyByteBuf = payload.getByteBuf().readBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); try { return MySQLJsonValueDecoder.decode(newlyByteBuf); } f...
@Test void assertReadJsonValueWithMeta3() { columnDef.setColumnMeta(3); when(byteBuf.readUnsignedMediumLE()).thenReturn(3); when(byteBuf.readBytes(3)).thenReturn(jsonValueByteBuf); assertThat(new MySQLJsonBinlogProtocolValue().read(columnDef, payload), is(EXPECTED_JSON)); }
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } final Set<String> legacyViewIds = StreamSupport.stream(viewsCollection.find(exists(FIELD_DASHBOARD_STATE)).spliter...
@Test @MongoDBFixtures("V20190805115800_RemoveDashboardStateFromViewsTest.json") public void removesDashboardStateFromExistingViews() { final Migration migration = new V20190805115800_RemoveDashboardStateFromViews(clusterConfigService, mongodb.mongoConnection()); migration.upgrade(); f...
public boolean isSameImageId(final Long id) { return this.id.equals(id); }
@Test void 이미지의_아이디와_다르면_false를_반환한다() { // given Image image = 이미지를_생성한다(); // when boolean result = image.isSameImageId(image.getId() + 1); // then assertThat(result).isFalse(); }
@Override public JobLogDO getJobLog(Long id) { return jobLogMapper.selectById(id); }
@Test public void testGetJobLog() { // mock 数据 JobLogDO dbJobLog = randomPojo(JobLogDO.class, o -> o.setExecuteIndex(1)); jobLogMapper.insert(dbJobLog); // 准备参数 Long id = dbJobLog.getId(); // 调用 JobLogDO jobLog = jobLogService.getJobLog(id); // 断言 ...
@Override public Set<Long> calculateUsers(DelegateExecution execution, String param) { return StrUtils.splitToLongSet(param); }
@Test public void testCalculateUsers() { // 准备参数 String param = "1,2"; // 调用 Set<Long> results = strategy.calculateUsers(null, param); // 断言 assertEquals(asSet(1L, 2L), results); }
@Override protected void runAfterCatalogReady() { try { process(); } catch (Throwable e) { LOG.warn("Failed to process one round of RoutineLoadScheduler", e); } }
@Test public void testNormalRunOneCycle(@Mocked GlobalStateMgr globalStateMgr, @Injectable RoutineLoadMgr routineLoadManager, @Injectable SystemInfoService systemInfoService, @Injectable Database databa...
@Override @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理 public void deleteSmsTemplate(Long id) { // 校验存在 validateSmsTemplateExists(id); // 更新 smsTemplateMapper.deleteById(id); }
@Test public void testDeleteSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsTemplate.getId(); // 调用 smsTemplateService.deleteSmsTemplat...
@Override public PluginInfo getPluginInfo(String key) { checkState(started.get(), NOT_STARTED_YET); PluginInfo info = pluginInfosByKeys.get(key); if (info == null) { throw new IllegalArgumentException(format("Plugin [%s] does not exist", key)); } return info; }
@Test public void getPluginInfo_throws_ISE_if_repo_is_not_started() { assertThatThrownBy(() -> underTest.getPluginInfo("foo")) .isInstanceOf(IllegalStateException.class) .hasMessage("not started yet"); }
public List<Chapter> getChapters() { return chapters; }
@Test public void testReadFullTagWithChapter() throws IOException, ID3ReaderException { byte[] chapter = Id3ReaderTest.concat( Id3ReaderTest.generateFrameHeader(ChapterReader.FRAME_ID_CHAPTER, CHAPTER_WITHOUT_SUBFRAME.length), CHAPTER_WITHOUT_SUBFRAME); byte[] data = ...