focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public IssueDto addImpact(ImpactDto impact) { impacts.stream().filter(impactDto -> impactDto.getSoftwareQuality() == impact.getSoftwareQuality()).findFirst() .ifPresent(impactDto -> { throw new IllegalStateException(format("Impact already defined on issue for Software Quality [%s]", impact.getSoftware...
@Test void addImpact_whenSoftwareQualityAlreadyDefined_shouldThrowISE() { IssueDto dto = new IssueDto(); dto.addImpact(newImpactDto(MAINTAINABILITY, LOW)); ImpactDto duplicatedImpact = newImpactDto(MAINTAINABILITY, HIGH); assertThatThrownBy(() -> dto.addImpact(duplicatedImpact)) .isInstanceOf(...
public List<FileStoreInfo> listFileStore() throws DdlException { try { return client.listFileStore(serviceId); } catch (StarClientException e) { throw new DdlException("Failed to list file store, error: " + e.getMessage()); } }
@Test public void testListFileStore() throws StarClientException, DdlException { S3FileStoreInfo s3FsInfo = S3FileStoreInfo.newBuilder() .setRegion("region").setEndpoint("endpoint").build(); FileStoreInfo fsInfo = FileStoreInfo.newBuilder().setFsKey("test-fskey") .set...
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 testDeclareIncompatibleExchangeFails() throws Exception { RabbitMqIO.Read read = RabbitMqIO.read().withExchange("IncompatibleExchange", "direct", "unused"); try { doExchangeTest(new ExchangeTestPlan(read, 1), true); fail("Expected to have failed to declare an incompatible...
public static UriTemplate create(String template, Charset charset) { return new UriTemplate(template, true, charset); }
@Test void nullTemplate() { assertThrows(IllegalArgumentException.class, () -> UriTemplate.create(null, Util.UTF_8)); }
@Deprecated public PassiveCompletableFuture<TaskExecutionState> deployLocalTask( @NonNull TaskGroup taskGroup) { return deployLocalTask( taskGroup, Thread.currentThread().getContextClassLoader(), emptyList()); }
@Test public void testCriticalCallTime() throws InterruptedException { AtomicBoolean stopMark = new AtomicBoolean(false); CopyOnWriteArrayList<Long> stopTime = new CopyOnWriteArrayList<>(); int count = 100; // Must be the same as the timer timeout int callTime = 50; ...
public boolean isVersionActive(final ClientPlatform platform, final Semver version) { final Map<Semver, ClientRelease> releasesByVersion = clientReleasesByPlatform.get(platform); return releasesByVersion != null && releasesByVersion.containsKey(version) && releasesByVersion.get(version).expirat...
@Test void isVersionActive() { final Semver iosVersion = new Semver("1.2.3"); final Semver desktopVersion = new Semver("4.5.6"); when(clientReleases.getClientReleases()).thenReturn(Map.of( ClientPlatform.DESKTOP, Map.of(desktopVersion, new ClientRelease(ClientPlatform.DESKTOP, desktopVersion, clo...
@Override public void publish(ScannerReportWriter writer) { Optional<String> targetBranch = getTargetBranch(); if (targetBranch.isPresent()) { Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG); int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get()); ...
@Test public void skip_if_not_pr() { when(branchConfiguration.isPullRequest()).thenReturn(false); publisher.publish(writer); verifyNoInteractions(inputComponentStore, inputModuleHierarchy, provider); assertNotPublished(); }
@Override public MetadataNode child(String name) { if (name.equals(ClusterImageBrokersNode.NAME)) { return new ClusterImageBrokersNode(image); } else if (name.equals(ClusterImageControllersNode.NAME)) { return new ClusterImageControllersNode(image); } else { ...
@Test public void testBrokersChild() { MetadataNode child = NODE.child("brokers"); assertNotNull(child); assertEquals(ClusterImageBrokersNode.class, child.getClass()); }
@Override public State cancel() throws IOException { State state = delegate.cancel(); this.terminalMetrics = delegate.metrics(); this.terminalState = state; this.cancel.run(); return state; }
@Test public void cancelStopsExecutable_reportsTerminalState() throws IOException { PipelineResult delegate = mock(PipelineResult.class); when(delegate.cancel()).thenReturn(PipelineResult.State.CANCELLED); PrismPipelineResult underTest = new PrismPipelineResult(delegate, exec::stop); assertThat(underT...
public static String getAppName() { String appName; appName = getAppNameByProjectName(); if (appName != null) { return appName; } appName = getAppNameByServerHome(); if (appName != null) { return appName; } ...
@Test void testGetAppNameByServerTypeForJboss() { System.setProperty("jboss.server.home.dir", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); }
@ShellMethod(key = "clean showpartitions", value = "Show partition level details of a clean") public String showCleanPartitions( @ShellOption(value = {"--clean"}, help = "clean to show") final String instantTime, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer ...
@Test public void testShowCleanPartitions() { // Check properties file exists. assertNotNull(propsFilePath, "Not found properties file"); // First, run clean with two partition SparkMain.clean(jsc(), HoodieCLI.basePath, propsFilePath.toString(), new ArrayList<>()); assertEquals(1, metaClient.getA...
@Override public Metrics toDay() { MaxLabeledFunction metrics = (MaxLabeledFunction) createNew(); metrics.setEntityId(getEntityId()); metrics.setTimeBucket(toTimeBucketInDay()); metrics.setServiceId(getServiceId()); metrics.getValue().copyFrom(getValue()); return metr...
@Test public void testToDay() { function.accept( MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1 ); function.accept( MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_2 ); ...
public static boolean isEntropyInjecting(FileSystem fs, Path target) { final EntropyInjectingFileSystem entropyFs = getEntropyFs(fs); return entropyFs != null && entropyFs.getEntropyInjectionKey() != null && target.getPath().contains(entropyFs.getEntropyInjectionKey()); ...
@Test void testIsEntropyFs() throws Exception { final String entropyKey = "_test_"; final FileSystem efs = new TestEntropyInjectingFs(entropyKey, "ignored"); final File folder = TempDirUtils.newFolder(tempFolder); final Path path = new Path(Path.fromLocalFile(folder), entropyKey + "/...
public NodeResources availableCapacityOf(Node host) { return availableCapacityOf(host, false, true); }
@Test public void availableCapacityOf() { assertEquals(new NodeResources(5, 40, 80, 2, NodeResources.DiskSpeed.fast, NodeResources.StorageType.remote, NodeResources.Architecture.x86_64), capacity.availableCapacityOf(host1)); assertEquals(ne...
public static ChannelBuffer wrappedBuffer(byte[] array, int offset, int length) { if (array == null) { throw new NullPointerException("array == null"); } byte[] dest = new byte[length]; System.arraycopy(array, offset, dest, 0, length); return wrappedBuffer(dest); ...
@Test void testWrappedBuffer() { byte[] bytes = new byte[16]; ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytes, 0, 15); Assertions.assertTrue(channelBuffer instanceof HeapChannelBuffer); Assertions.assertEquals(channelBuffer.capacity(), 15); channelBuffer = C...
String substituteParametersInSqlString(String sql, SqlParameterSource paramSource) { ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); List<SqlParameter> declaredParams = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource); if (declaredParams.isEmpty()) { ...
@Test public void substituteParametersInSqlString_UuidListType() { List<UUID> guids = List.of(UUID.fromString("634a8d03-6871-4e01-94d0-876bf3e67dff"), UUID.fromString("3adbb5b8-4dc6-4faf-80dc-681a7b518b5e"), UUID.fromString("63a50f0c-2058-4d1d-8f15-812eb7f84412")); String sql = "Select * from Tabl...
@VisibleForTesting Database getDatabase( LoggingObjectInterface parentObject, PGBulkLoaderMeta pgBulkLoaderMeta ) { DatabaseMeta dbMeta = pgBulkLoaderMeta.getDatabaseMeta(); // If dbNameOverride is present, clone the origin db meta and override the DB name String dbNameOverride = environmentSubstitute( pg...
@Test public void testDBNameNOTOverridden_IfDbNameOverrideEmpty() throws Exception { // Db Name Override is empty PGBulkLoaderMeta pgBulkLoaderMock = getPgBulkLoaderMock( DB_NAME_EMPTY ); Database database = pgBulkLoader.getDatabase( pgBulkLoader, pgBulkLoaderMock ); assertNotNull( database ); // ...
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for eac...
@Test(expected=AclException.class) public void testReplaceAclEntriesMissingGroup() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); L...
public WorkerService getWorkerService() throws UnsupportedOperationException { return functionWorkerService.orElseThrow(() -> new UnsupportedOperationException("Pulsar Function Worker " + "is not enabled, probably functionsWorkerEnabled is set to false")); }
@Test public void testGetWorkerService() throws Exception { ServiceConfiguration configuration = new ServiceConfiguration(); configuration.setMetadataStoreUrl("zk:localhost"); configuration.setClusterName("clusterName"); configuration.setFunctionsWorkerEnabled(true); configur...
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new K...
@Test public void shouldIgnoreOuterJoinsWhenComputingViableKeys() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(a); when(j2.getRightSource()).thenReturn(c); when(j1.getType()).thenReturn(JoinType.OUTER); wh...
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { ...
@Test public void testCollectFetchInitializationOffsetOutOfRangeErrorWithNullPosition() { final TopicPartition topicPartition0 = new TopicPartition("topic", 0); final SubscriptionState subscriptions = mock(SubscriptionState.class); when(subscriptions.hasValidPosition(topicPartition0)).thenRe...
public static Void unwrapAndThrowException(ServiceException se) throws IOException, YarnException { Throwable cause = se.getCause(); if (cause == null) { // SE generated by the RPC layer itself. throw new IOException(se); } else { if (cause instanceof RemoteException) { Remot...
@Test void testRPCServiceExceptionUnwrapping() { String message = "ServiceExceptionMessage"; ServiceException se = new ServiceException(message); Throwable t = null; try { RPCUtil.unwrapAndThrowException(se); } catch (Throwable thrown) { t = thrown; } assertTrue(IOException.c...
@Override public VirtualNetwork getVirtualNetwork(NetworkId networkId) { checkNotNull(networkId, NETWORK_NULL); return store.getNetwork(networkId); }
@Test(expected = NullPointerException.class) public void testGetVirtualForNullVirtualNetworkId() { manager.getVirtualNetwork(null); }
public Header setContentType(String contentType) { if (contentType == null) { contentType = MediaType.APPLICATION_JSON; } return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType); }
@Test void testSetContentType() { Header header = Header.newInstance(); header.setContentType(null); assertEquals(MediaType.APPLICATION_JSON, header.getValue(HttpHeaderConsts.CONTENT_TYPE)); header.setContentType(MediaType.MULTIPART_FORM_DATA); assertEquals(MediaType.MULTIPAR...
public Collection<String> getTrimmedStringCollection(String name) { String valueString = get(name); if (null == valueString) { Collection<String> empty = new ArrayList<String>(); return empty; } return StringUtils.getTrimmedStringCollection(valueString); }
@Test public void testGetTrimmedStringCollection() { Configuration c = new Configuration(); c.set("x", "a, b, c"); Collection<String> strs = c.getStringCollection("x"); assertEquals(3, strs.size()); assertArrayEquals(new String[]{ "a", " b", " c" }, strs.toArray(new String[0])); // Ch...
@Override protected Result[] run(String value) { final Grok grok = grokPatternRegistry.cachedGrokForPattern(this.pattern, this.namedCapturesOnly); // the extractor instance is rebuilt every second anyway final Match match = grok.match(value); final Map<String, Object> matches = matc...
@Test public void testFlattenValue() { final Map<String, Object> config = new HashMap<>(); final GrokExtractor extractor1 = makeExtractor("%{TWOBASENUMS}", config); /* Test flatten with a multiple non unique result [ 22, 23 ] */ Extractor.Result[] result1 = extractor1.run("22 23");...
@VisibleForTesting void validateMobileUnique(Long id, String mobile) { if (StrUtil.isBlank(mobile)) { return; } AdminUserDO user = userMapper.selectByMobile(mobile); if (user == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的用户 if (id ==...
@Test public void testValidateMobileUnique_mobileExistsForUpdate() { // 准备参数 Long id = randomLongId(); String mobile = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); // 调用,校验异常 assertServiceException(() -> userServi...
public static String format(Object x) { if (x != null) { return format(x.toString()); } else { return StrUtil.EMPTY; } }
@Test public void issue3579Test() { assertEquals("ZERO AND CENTS TEN ONLY", NumberWordFormatter.format(0.1)); assertEquals("ZERO AND CENTS ONE ONLY", NumberWordFormatter.format(0.01)); }
@Override public void setBigNumber( BigDecimal number ) { string = number.toString(); }
@Test public void testSetBigNumber() { ValueString vs = new ValueString(); try { vs.setBigNumber( null ); // assertNull(vs.getString()); fail( "expected NullPointerException" ); } catch ( NullPointerException ex ) { // This is the original behaviour } vs.setBigNumber( Big...
public Properties getProperties() { return properties; }
@Test public void testGetProperties() { }
@Override public synchronized Snapshot record(long duration, TimeUnit durationUnit, Outcome outcome) { totalAggregation.record(duration, durationUnit, outcome); moveWindowByOne().record(duration, durationUnit, outcome); return new SnapshotImpl(totalAggregation); }
@Test public void testRecordSlowSuccess() { Metrics metrics = new FixedSizeSlidingWindowMetrics(5); Snapshot snapshot = metrics .record(100, TimeUnit.MILLISECONDS, Metrics.Outcome.SLOW_SUCCESS); assertThat(snapshot.getTotalNumberOfCalls()).isEqualTo(1); assertThat(snapsh...
public Map<MetricId, Number> metrics() { return metrics; }
@Test public void builder_applies_output_names() { String ONE = "one"; String TWO = "two"; String THREE = "three"; String NON_EXISTENT = "non-existent"; MetricId ONE_ID = toMetricId(ONE); MetricId TWO_ID = toMetricId(TWO); ...
public double getZ() { return position.z(); }
@Test public void testGetZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getZ(), EPSILON); }
public void setBuildFile(String buildFile) { this.buildFile = buildFile; }
@Test public void antTaskShouldNormalizeBuildFile() { AntTask task = new AntTask(); task.setBuildFile("pavan\\build.xml"); assertThat(task.arguments(), containsString("\"pavan/build.xml\"")); }
public static NacosAsyncRestTemplate getNacosAsyncRestTemplate(Logger logger) { return getNacosAsyncRestTemplate(new DefaultHttpClientFactory(logger)); }
@Test void testGetNacosAsyncRestTemplateWithCustomFactory() { assertTrue(restAsyncMap.isEmpty()); HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null); assertEquals(1, restAsyncMap.size()); NacosAsyncRestTemplate actual = HttpClientBeanHolder.getNacosAsyncRestTemplate(mockFa...
@Override public String getRomOAID() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { try { String oaid = Settings.Global.getString(mContext.getContentResolver(), "pps_oaid"); if (!TextUtils.isEmpty(oaid)) { SALog.i(TAG, "Get oaid from g...
@Test public void getRomOAID() { HuaweiImpl huawei = new HuaweiImpl(mApplication); // if (huawei.isSupported()) { // Assert.assertNull(huawei.getRomOAID()); // } }
public static void setField( final Object object, final String fieldName, final Object fieldNewValue) { try { traverseClassHierarchy( object.getClass(), NoSuchFieldException.class, (InsideTraversal<Void>) traversalClass -> { Field field = trave...
@Test public void setFieldReflectively_setsInheritedFields() { ExampleDescendant example = new ExampleDescendant(); example.setNotOverridden(5); ReflectionHelpers.setField(example, "notOverridden", 10); assertThat(example.getNotOverridden()).isEqualTo(10); }
@Override public CiConfiguration loadConfiguration() { // https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin#GitHubpullrequestbuilderplugin-EnvironmentVariables // https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project String revision = system.envVariable("ghpr...
@Test public void loadConfiguration_of_git_repo_with_branch_plugin_without_git_repo() throws IOException { // prepare fake git clone Path baseDir = temp.newFolder().toPath(); when(project.getBaseDir()).thenReturn(baseDir); setEnvVariable("CHANGE_ID", "3"); setEnvVariable("GIT_BRANCH", "PR-3"); ...
@Override public void handle(final RoutingContext routingContext) { routingContext.addEndHandler(ar -> { // After the response is complete, log results here. final int status = routingContext.request().response().getStatusCode(); if (!loggingRateLimiter.shouldLog(logger, routingContext.request()...
@Test public void shouldProduceLogWithRandomFilter() { // Given: when(response.getStatusCode()).thenReturn(200); config = new KsqlRestConfig( ImmutableMap.of(KsqlRestConfig.KSQL_ENDPOINT_LOGGING_IGNORED_PATHS_REGEX_CONFIG, ".*random.*") ); when(server.getConfig()).thenReturn(config); l...
@Override public boolean supports(Job job) { JobDetails jobDetails = job.getJobDetails(); return !jobDetails.hasStaticFieldName() && Modifier.isStatic(getJobMethod(jobDetails).getModifiers()); }
@Test void doesNotSupportJobIfJobMethodIsNotStatic() { Job job = anEnqueuedJob() .<TestService>withJobDetails(ts -> ts.doWorkThatFails()) .build(); assertThat(backgroundStaticJobWithoutIocRunner.supports(job)).isFalse(); }
public void onRequest(FilterRequestContext requestContext, RestLiFilterResponseContextFactory filterResponseContextFactory) { // Initiate the filter chain iterator. The RestLiCallback will be passed to the method invoker at the end of the // filter chain. _filterChainIterator.onReq...
@SuppressWarnings("unchecked") @Test public void testFilterInvocationRequestThrowsError() throws Exception { _restLiFilterChain = new RestLiFilterChain(Arrays.asList(_filters), _mockFilterChainDispatcher, _mockFilterChainCallback); _filters[1] = new CountFilterRequestThrowsError(); when(_respo...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void comparisonInFixOp() { String inputExpression = "foo >= bar * 10"; BaseNode infix = parse( inputExpression ); assertThat( infix).isInstanceOf(InfixOpNode.class); assertThat( infix.getResultType()).isEqualTo(BuiltInType.BOOLEAN); assertThat( infix.getText()).isEqual...
@Udf public String lcase( @UdfParameter(description = "The string to lower-case") final String input) { if (input == null) { return null; } return input.toLowerCase(); }
@Test public void shouldReturnEmptyForEmptyInput() { final String result = udf.lcase(""); assertThat(result, is("")); }
@Override public void add(Component file, Duplication duplication) { checkFileComponentArgument(file); checkNotNull(duplication, "duplication can not be null"); duplications.put(file.getKey(), duplication); }
@Test @UseDataProvider("allComponentTypesButFile") public void addDuplication_inner_throws_IAE_if_file_type_is_not_FILE(Component.Type type) { assertThatThrownBy(() -> { Component component = mockComponentGetType(type); underTest.add(component, SOME_DUPLICATION); }) .isInstanceOf(IllegalAr...
@Override public void onGestureTypingInput(int x, int y, long eventTime) {}
@Test public void testOnGestureTypingInput() { mUnderTest.onGestureTypingInput(66, 99, 1231); Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction); }
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testAnalyzePinnedInstallJsonV010() throws Exception { try (Engine engine = new Engine(getSettings())) { final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "maven_install_v010.json")); engine.addDependency(result); analyzer.analyze(...
@Override public boolean syncVerifyData(DistroData verifyData, String targetServer) { if (isNoExistTarget(targetServer)) { return true; } // replace target server as self server so that can callback. verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd...
@Test void testSyncVerifyDataWithCallbackException2() throws NacosException { DistroData verifyData = new DistroData(); verifyData.setDistroKey(new DistroKey()); when(memberManager.hasMember(member.getAddress())).thenReturn(true); when(memberManager.find(member.getAddress())).thenRet...
public static Schema schemaFromPojoClass( TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) { return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier); }
@Test public void testSimplePOJO() { Schema schema = POJOUtils.schemaFromPojoClass( new TypeDescriptor<SimplePOJO>() {}, JavaFieldTypeSupplier.INSTANCE); assertEquals(SIMPLE_POJO_SCHEMA, schema); }
@Override @MethodNotAvailable public void evictAll() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testEvictAll() { adapter.evictAll(); }
@SuppressWarnings("unchecked") public static Builder fromMap(final Map<String, Object> data) { final String tableName = ObjectHelper.cast(String.class, data.get(TABLE_NAME)); final StitchSchema schema = StitchSchema.builder() .addKeywords(ObjectHelper.cast(Map.class, data.getOrDefaul...
@Test void testIfNotCreateRequestBodyFromInvalidMap() { final Map<String, Object> data = new LinkedHashMap<>(); data.put(StitchRequestBody.TABLE_NAME, "table"); data.put(StitchRequestBody.SCHEMA, 1); data.put(StitchRequestBody.MESSAGES, Collections.emptyList()); data.put(Stit...
@Override public void characters(char[] ch, int start, int length) throws SAXException { filter(ch, start, length, charactersOutput); }
@Test public void testInvalidCharacters() throws SAXException { safe.characters("ab\u0007".toCharArray(), 0, 3); safe.characters("a\u000Bc".toCharArray(), 0, 3); safe.characters("\u0019bc".toCharArray(), 0, 3); assertEquals("ab\ufffda\ufffdc\ufffdbc", output.toString()); }
public static String getOperatingSystemCompleteName() { return OS_COMPLETE_NAME; }
@Test @EnabledOnOs(OS.LINUX) public void shouldGetCompleteNameOnLinux() { assertThat(SystemInfo.getOperatingSystemCompleteName()).matches("[ \\w]+ [0-9.]+( \\w+)?( \\(.*\\))?"); }
@Override public List<? extends SortKey> getSortKeys() { return isSorted() ? Collections.singletonList(sortkey) : Collections.emptyList(); }
@Test public void toggleSortOrder_none() { assertSame(emptyList(), sorter.getSortKeys()); }
@Override public Graph<EntityDescriptor> resolveNativeEntity(EntityDescriptor entityDescriptor) { final MutableGraph<EntityDescriptor> mutableGraph = GraphBuilder.directed().build(); mutableGraph.addNode(entityDescriptor); final ModelId modelId = entityDescriptor.id(); final Optiona...
@Test @MongoDBFixtures({"LookupCacheFacadeTest.json", "LookupDataAdapterFacadeTest.json", "LookupTableFacadeTest.json"}) public void resolveEntityDescriptor() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf24dd4b900a0fdb4e530d", ModelTypes.LOOKUP_TABLE_V1); final Graph<Entit...
public Span nextSpan(TraceContextOrSamplingFlags extracted) { if (extracted == null) throw new NullPointerException("extracted == null"); TraceContext context = extracted.context(); if (context != null) return newChild(context); TraceIdContext traceIdContext = extracted.traceIdContext(); if (traceI...
@Test void localRootId_nextSpan_ids_sampled() { TraceIdContext context1 = TraceIdContext.newBuilder().traceId(1).sampled(true).build(); TraceIdContext context2 = TraceIdContext.newBuilder().traceId(2).sampled(true).build(); localRootId(context1, context2, ctx -> tracer.nextSpan(ctx)); }
static Timestamp toTimestamp(final JsonNode object) { if (object instanceof NumericNode) { return new Timestamp(object.asLong()); } if (object instanceof TextNode) { try { return new Timestamp(Long.parseLong(object.textValue())); } catch (final NumberFormatException e) { th...
@Test public void shouldConvertStringToTimestampCorrectly() { final Timestamp d = JsonSerdeUtils.toTimestamp(JsonNodeFactory.instance.textNode("100")); assertThat(d.getTime(), equalTo(100L)); }
public URI qualifiedURI(String filename) throws IOException { try { URI fileURI = new URI(filename); if (RESOURCE_URI_SCHEME.equals(fileURI.getScheme())) { return fileURI; } } catch (URISyntaxException ignore) { } return qualifiedPath(filename).toUri(); }
@Test public void qualifiedURITest() throws IOException { URI uri = this.command.qualifiedURI(FILE_PATH); Assert.assertEquals("/var/tmp/test.parquet", uri.getPath()); }
@Override public Iterator<Map.Entry<String, Object>> getIterator() { return variables.getIterator(); }
@Test public void testGetIteratorIsUnmodifable() { Iterator<Map.Entry<String, Object>> iterator = unmodifiables.getIterator(); assertThat(iterator.hasNext(), CoreMatchers.is(true)); iterator.next(); assertThrowsUnsupportedOperation(iterator::remove); }
public static String normalizeUri(String uri) throws URISyntaxException { // try to parse using the simpler and faster Camel URI parser String[] parts = CamelURIParser.fastParseUri(uri); if (parts != null) { // we optimized specially if an empty array is returned if (part...
@Test public void testRawParameterCurly() throws Exception { String out = URISupport.normalizeUri( "xmpp://camel-user@localhost:123/test-user@localhost?password=RAW{++?w0rd}&serviceName=some chat"); assertEquals("xmpp://camel-user@localhost:123/test-user@localhost?password=RAW{++?w0r...
@Override public CiConfiguration loadConfiguration() { String revision = system.envVariable(PROPERTY_COMMIT); if (isEmpty(revision)) { LoggerFactory.getLogger(getClass()).warn("Missing environment variable " + PROPERTY_COMMIT); } return new CiConfigurationImpl(revision, getName()); }
@Test public void configuration_of_pull_request() { setEnvVariable("CIRRUS_PR", "1234"); setEnvVariable("CIRRUS_BASE_SHA", "abd12fc"); setEnvVariable("CIRRUS_CHANGE_IN_REPO", "fd355db"); assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("fd355db"); }
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new K...
@Test public void shouldIncludeOnlyColFromLastInViableKeyEvenWithoutOverlap() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(a); when(j2.getRightSource()).thenReturn(c); when(j1.getLeftJoinExpression()).thenRetu...
public static synchronized String getFullName(String cweId) { final String name = getName(cweId); if (name != null) { return cweId + " " + name; } return cweId; }
@Test public void testGetFullName() { String cweId = "CWE-16"; String expResult = "CWE-16 Configuration"; String result = CweDB.getFullName(cweId); assertEquals(expResult, result); cweId = "CWE-260000"; expResult = "CWE-260000"; result = CweDB.getFullName(cwe...
public void ensureActiveGroup() { while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) { log.warn("still waiting to ensure active group"); } }
@Test public void testWakeupInOnJoinComplete() throws Exception { setupCoordinator(); coordinator.wakeupOnJoinComplete = true; mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(joinGroupFollowerResponse(1, memberId, leaderId, Errors....
@Override public void pluginLoaded(GoPluginDescriptor pluginDescriptor) { if (notificationExtension.canHandlePlugin(pluginDescriptor.id())) { try { notificationPluginRegistry.registerPlugin(pluginDescriptor.id()); List<String> notificationsInterestedIn = notificat...
@Test public void shouldLogWarningIfPluginTriesToRegisterForInvalidNotificationType() { NotificationPluginRegistrar notificationPluginRegistrar = new NotificationPluginRegistrar(pluginManager, notificationExtension, notificationPluginRegistry); try (LogFixture logging = LogFixture.logFixtureFor(Not...
@Override public DescribeTopicsResult describeTopics(final TopicCollection topics, DescribeTopicsOptions options) { if (topics instanceof TopicIdCollection) return DescribeTopicsResult.ofTopicIds(handleDescribeTopicsByIds(((TopicIdCollection) topics).topicIds(), options)); else if (topic...
@SuppressWarnings({"NPathComplexity", "CyclomaticComplexity"}) @Test public void testDescribeTopicsWithDescribeTopicPartitionsApiEdgeCase() throws ExecutionException, InterruptedException { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersi...
public static String getValue( Object object, Field field ) { try { Method getMethod = getDeclaredMethod( object.getClass(), GET_PREFIX + StringUtils.capitalize( field.getName() ) ); return (String) getMethod.invoke( object ); } catch ( NoSuchMethodException | IllegalAccessException | Invoca...
@Test public void testGetValue() throws NoSuchFieldException { TestConnectionWithBucketsDetailsChild testConnectionDetails = new TestConnectionWithBucketsDetailsChild(); testConnectionDetails.setPassword( PASSWORD ); testConnectionDetails.setPassword3( PASSWORD3 ); String value = EncryptUtils.getValue...
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double variance = 0; for (int i = 0; i < values.length; i++) { final doubl...
@Test public void calculatesTheStdDev() { assertThat(snapshot.getStdDev()) .isEqualTo(1.2688, offset(0.0001)); }
public int getCurrentTableCapacity() { return table.length; }
@Test void testSizeComparator() { KeyMap<String, String> map1 = new KeyMap<>(5); KeyMap<String, String> map2 = new KeyMap<>(80); assertThat(map1.getCurrentTableCapacity()).isLessThan(map2.getCurrentTableCapacity()); assertThat(KeyMap.CapacityDescendingComparator.INSTANCE.compare(ma...
public static void main(String[] args) throws IOException, ClassNotFoundException { final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); // Initializing Country Object China final var China = new Country( 86, "China", "A...
@Test void shouldExecuteSerializedEntityWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public String doLayout(ILoggingEvent event) { if (!isStarted()) { return CoreConstants.EMPTY_STRING; } return writeLoopOnConverters(event); }
@Test public void testNopExeptionHandler() { pl.setPattern("%nopex %m%n"); pl.start(); String val = pl.doLayout(makeLoggingEvent(aMessage, ex)); assertTrue(!val.contains("java.lang.Exception: Bogus exception")); }
public static <T> DequeCoder<T> of(Coder<T> elemCoder) { return new DequeCoder<>(elemCoder); }
@Test public void structuralValueDecodeEncodeEqualIterable() throws Exception { DequeCoder<byte[]> coder = DequeCoder.of(ByteArrayCoder.of()); Deque<byte[]> value = new ArrayDeque<>(Collections.singletonList(new byte[] {1, 2, 3, 4})); CoderProperties.structuralValueDecodeEncodeEqualIterable(coder, value);...
public T allowDuplicateContentLengths(boolean allow) { this.allowDuplicateContentLengths = allow; return get(); }
@Test void allowDuplicateContentLengths() { checkDefaultAllowDuplicateContentLengths(conf); conf.allowDuplicateContentLengths(true); assertThat(conf.allowDuplicateContentLengths()).as("allow duplicate Content-Length headers").isTrue(); checkDefaultMaxInitialLineLength(conf); checkDefaultMaxHeaderSize(conf...
@Override public OAuth2AccessTokenDO grantImplicit(Long userId, Integer userType, String clientId, List<String> scopes) { return oauth2TokenService.createAccessToken(userId, userType, clientId, scopes); }
@Test public void testGrantImplicit() { // 准备参数 Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); String clientId = randomString(); List<String> scopes = Lists.newArrayList("read", "write"); // mock 方法 OAuth2AccessTo...
@Override public boolean nukeExistingCluster() throws Exception { log.info("Nuking metadata of existing cluster, ledger root path: {}", ledgersRootPath); if (!store.exists(ledgersRootPath + "/" + INSTANCEID).get(BLOCKING_CALL_TIMEOUT, MILLISECONDS)) { log.info("There is no existing clus...
@Test(dataProvider = "impl") public void testNukeExistingCluster(String provider, Supplier<String> urlSupplier) throws Exception { methodSetup(urlSupplier); assertTrue(registrationManager.initNewCluster()); assertClusterExists(); assertTrue(registrationManager.nukeExistingCluster());...
public static String composeFullyQualifiedTableName(String catalog, String schema, String tableName, char separator) { StringBuilder sb = new StringBuilder(); if (stringHasValue(catalog)) { sb.append(catalog); sb.append(separator); } if (stringHasVal...
@Test void testNoSchema() { String answer = StringUtility.composeFullyQualifiedTableName("catalog", null, "table", '.'); assertEquals("catalog..table", answer); }
@Override public boolean putRowWait( RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu ) { return putRow( rowMeta, rowData ); }
@Test public void testPutRowWait() throws Exception { rowSet.putRowWait( new RowMeta(), row, 1, TimeUnit.SECONDS ); assertSame( row, rowSet.getRowWait( 1, TimeUnit.SECONDS ) ); }
public ControllerResult<ElectMasterResponseHeader> electMaster(final ElectMasterRequestHeader request, final ElectPolicy electPolicy) { final String brokerName = request.getBrokerName(); final Long brokerId = request.getBrokerId(); final ControllerResult<ElectMasterResponseHeader> result...
@Test public void testElectMasterPreferHigherPriorityWhenEpochAndOffsetEquals() { mockMetaData(); final ElectMasterRequestHeader request = new ElectMasterRequestHeader(DEFAULT_BROKER_NAME); ElectPolicy electPolicy = new DefaultElectPolicy(this.heartbeatManager::isBrokerActive, this.heartbeat...
public void replayEndTransactionMarker( long producerId, TransactionResult result ) throws RuntimeException { Offsets pendingOffsets = pendingTransactionalOffsets.remove(producerId); if (pendingOffsets == null) { log.debug("Replayed end transaction marker with result {} ...
@Test public void testOffsetCommitsNumberMetricWithTransactionalOffsets() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Add pending transactional commit for producer id 4. verifyTransactionalReplay(context, 4L, "foo", "bar", 0, new O...
public static String getSchemaKind(String json) { int i = json.indexOf("\"kind\""); if (i >= 0) { int s = json.indexOf("\"", i + 6); if (s >= 0) { int e = json.indexOf("\"", s + 1); if (e >= 0) { return json.substring(s + 1, e);...
@Test public void testGetSchemaKind() throws Exception { File file = ResourceUtils.getResourceAsFile("json/aop.json"); String json = PackageHelper.loadText(file); assertEquals("model", PackageHelper.getSchemaKind(json)); }
@Override public Table getTable(long id, String name, List<Column> schema, String dbName, String catalogName, Map<String, String> properties) throws DdlException { Map<String, String> newProp = new HashMap<>(properties); newProp.putIfAbsent(JDBCTable.JDBC_TABLENAME, "\"" + ...
@Test public void testGetTable() throws SQLException { new Expectations() { { dataSource.getConnection(); result = connection; minTimes = 0; connection.getCatalog(); result = "t1"; minTimes = 0; ...
public static String getRootCauseMessage(Throwable t) { return formatMessageCause(getRootCause(t)); }
@Test public void getRootCauseMessage() { assertThat(ExceptionUtils.getRootCauseMessage(new Exception("cause1", new Exception("root")))).satisfies(m -> { assertThat(m).isNotBlank(); assertThat(m).isEqualTo("root."); }); }
@Override public int partition(StatisticsOrRecord wrapper, int numPartitions) { if (wrapper.hasStatistics()) { this.delegatePartitioner = delegatePartitioner(wrapper.statistics()); return (int) (roundRobinCounter(numPartitions).getAndIncrement() % numPartitions); } else { if (delegatePartiti...
@Test public void testRoundRobinStatisticsWrapper() { RangePartitioner partitioner = new RangePartitioner(SCHEMA, SORT_ORDER); Set<Integer> results = Sets.newHashSetWithExpectedSize(numPartitions); for (int i = 0; i < numPartitions; ++i) { GlobalStatistics statistics = GlobalStatistics.fro...
@Override public ObjectNode encode(OpenstackNode node, CodecContext context) { checkNotNull(node, "Openstack node cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(HOST_NAME, node.hostname()) .put(TYPE, node.type().name()) ...
@Test public void testOpenstackDpdkComputeNodeEncode() { DpdkInterface dpdkInterface1 = DefaultDpdkInterface.builder() .deviceName("br-int") .intf("dpdk0") .mtu(Long.valueOf(1600)) .pciAddress("0000:85:00.0") .type(DpdkInterface...
public synchronized Topology addSource(final String name, final String... topics) { internalTopologyBuilder.addSource(null, name, null, null, null, topics); return this; }
@Test public void shouldNotAllowToAddTopicTwice() { topology.addSource("source", "topic-1"); try { topology.addSource("source-2", "topic-1"); fail("Should throw TopologyException for already used topic"); } catch (final TopologyException expected) { } }
@Override public synchronized void editSchedule() { updateConfigIfNeeded(); long startTs = clock.getTime(); CSQueue root = scheduler.getRootQueue(); Resource clusterResources = Resources.clone(scheduler.getClusterResource()); containerBasedPreemptOrKill(root, clusterResources); if (LOG.isDe...
@Test public void testSkipAMContainer() { int[][] qData = new int[][] { // / A B { 100, 50, 50 }, // abs { 100, 100, 100 }, // maxcap { 100, 100, 0 }, // used { 70, 20, 50 }, // pending { 0, 0, 0 }, // reserved { 5, 4, 1 }, // apps { -1, 1, 1 },...
@Override public int getMaxCatalogNameLength() { return 0; }
@Test void assertGetMaxCatalogNameLength() { assertThat(metaData.getMaxCatalogNameLength(), is(0)); }
public static String formatTM(TimeZone tz, Date date) { return formatTM(tz, date, new DatePrecision()); }
@Test public void testFormatTM() { assertEquals("020000.000", DateUtils.formatTM(tz, new Date(0))); }
public static List<FieldSchema> convert(Schema schema) { return schema.columns().stream() .map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc())) .collect(Collectors.toList()); }
@Test public void testComplexSchemaConvertToIcebergSchema() { assertThat(HiveSchemaUtil.convert(COMPLEX_HIVE_SCHEMA).asStruct()) .isEqualTo(COMPLEX_ICEBERG_SCHEMA.asStruct()); }
public static Labels fromString(String stringLabels) throws IllegalArgumentException { Map<String, String> labels = new HashMap<>(); try { if (stringLabels != null && !stringLabels.isEmpty()) { String[] labelsArray = stringLabels.split(","); for (String label...
@Test public void testParseNullLabels() { String validLabels = null; assertThat(Labels.fromString(validLabels), is(Labels.EMPTY)); }
public static void forceMkdir(String path) throws IOException { FileUtils.forceMkdir(new File(path)); }
@Test void testForceMkdirWithPath() throws IOException { Path path = Paths.get(TMP_PATH, UUID.randomUUID().toString(), UUID.randomUUID().toString()); DiskUtils.forceMkdir(path.toString()); File file = path.toFile(); assertTrue(file.exists()); file.deleteOnExit(); }
@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 shouldThrowExceptionIfSourceDoesNotExist() { // Given: final ConfiguredStatement<DropStream> dropStatement = givenStatement( "DROP SOMETHING", new DropStream(SourceName.of("SOMETHING_ELSE"), false, true)); // When: final Exception e = assertThrows( RuntimeException.c...
@Override public void getFields( RowMetaInterface r, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore metaStore ) { // Check compatibility mode boolean compatibilityMode = ValueMetaBase.convertStringToBoolean( space.getVariable( Const....
@Test public void testGetFields() { final String stepName = "this step name"; MemoryGroupByMeta meta = new MemoryGroupByMeta(); meta.setDefault(); meta.allocate( 1, 17 ); // Declare input fields RowMetaInterface rm = getInputRowMeta(); String[] groupFields = new String[2]; groupField...
@Override public Health health() { final Health.Builder health = Health.unknown(); if (!jobRunrProperties.getBackgroundJobServer().isEnabled()) { health .up() .withDetail("backgroundJobServer", "disabled"); } else { final Backgr...
@Test void givenEnabledBackgroundJobServerAndBackgroundJobServerStopped_ThenHealthIsDown() { when(backgroundJobServerProperties.isEnabled()).thenReturn(true); when(backgroundJobServer.isRunning()).thenReturn(false); assertThat(jobRunrHealthIndicator.health().getStatus()).isEqualTo(Status.DO...
protected final AnyKeyboardViewBase getMiniKeyboard() { return mMiniKeyboard; }
@Test public void testShortPressWithLabelWhenNoPrimaryKeyAndNoPopupItemsShouldNotOutput() throws Exception { ExternalAnyKeyboard anyKeyboard = new ExternalAnyKeyboard( new DefaultAddOn(getApplicationContext(), getApplicationContext()), getApplicationContext(), key...
@Override public CompletableFuture<Versioned<Set<BookieId>>> getReadOnlyBookies() { return getBookiesThenFreshCache(bookieReadonlyRegistrationPath); }
@Test(dataProvider = "impl") public void testGetReadonlyBookies(String provider, Supplier<String> urlSupplier) throws Exception { @Cleanup MetadataStoreExtended store = MetadataStoreExtended.create(urlSupplier.get(), MetadataStoreConfig.builder().fsyncEnable(false).build()); ...
public static URI getProxyUri(URI originalUri, URI proxyUri, ApplicationId id) { try { String path = getPath(id, originalUri == null ? "/" : originalUri.getPath()); return new URI(proxyUri.getScheme(), proxyUri.getAuthority(), path, originalUri == null ? null : originalUri.getQuery(), ...
@Test void testGetProxyUri() throws Exception { URI originalUri = new URI("http://host.com/static/foo?bar=bar"); URI proxyUri = new URI("http://proxy.net:8080/"); ApplicationId id = BuilderUtils.newApplicationId(6384623l, 5); URI expected = new URI("http://proxy.net:8080/proxy/application_6384623_0005...
public static void substituteDeprecatedConfigPrefix( Configuration config, String deprecatedPrefix, String designatedPrefix) { // set the designated key only if it is not set already final int prefixLen = deprecatedPrefix.length(); Configuration replacement = new Configuration(); ...
@Test void testSubstituteConfigKeyPrefix() { String deprecatedPrefix1 = "deprecated-prefix"; String deprecatedPrefix2 = "-prefix-2"; String deprecatedPrefix3 = "prefix-3"; String designatedPrefix1 = "p1"; String designatedPrefix2 = "ppp"; String designatedPrefix3 = "...
@Override public Long getSmsTemplateCountByChannelId(Long channelId) { return smsTemplateMapper.selectCountByChannelId(channelId); }
@Test public void testGetSmsTemplateCountByChannelId() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomPojo(SmsTemplateDO.class, o -> o.setChannelId(1L)); smsTemplateMapper.insert(dbSmsTemplate); // 测试 channelId 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTem...
protected boolean init() { return true; }
@Test public void testEmbedSetup() { avroInput.init( (StepMetaInterface) mockStepMeta, mockStepDataInterface ); }
@Override public void validateKeyPresent(final SourceName sinkName) { getSource().validateKeyPresent(sinkName, projection); }
@Test public void shouldValidateKeysByCallingSourceWithProjection() { // When: projectNode.validateKeyPresent(SOURCE_NAME); // Then: verify(source).validateKeyPresent(SOURCE_NAME, Projection.of(selects)); }