focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static String format(String source, Object... parameters) { String current = source; for (Object parameter : parameters) { if (!current.contains("{}")) { return current; } current = current.replaceFirst("\\{\\}", String.valueOf(parameter)); ...
@Test public void testFormat0() { String fmt = "Some string 1 2 3"; assertEquals("Some string 1 2 3", format(fmt)); }
public static <K, V> RedistributeByKey<K, V> byKey() { return new RedistributeByKey<>(false); }
@Test public void testByKeyUrn() { assertThat( PTransformTranslation.urnForTransform(Redistribute.byKey()), equalTo(REDISTRIBUTE_BY_KEY_URN)); }
@Override public String format(final Schema schema) { final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema); return options.contains(Option.AS_COLUMN_LIST) ? stripTopLevelStruct(converted) : converted; }
@Test public void shouldFormatBoolean() { assertThat(DEFAULT.format(Schema.BOOLEAN_SCHEMA), is("BOOLEAN")); assertThat(STRICT.format(Schema.BOOLEAN_SCHEMA), is("BOOLEAN NOT NULL")); }
@Override @SneakyThrows public String createFile(String name, String path, byte[] content) { // 计算默认的 path 名 String type = FileTypeUtils.getMineType(content, name); if (StrUtil.isEmpty(path)) { path = FileUtils.generatePath(content, name); } // 如果 name 为空,则使用 ...
@Test public void testCreateFile_success() throws Exception { // 准备参数 String path = randomString(); byte[] content = ResourceUtil.readBytes("file/erweima.jpg"); // mock Master 文件客户端 FileClient client = mock(FileClient.class); when(fileConfigService.getMasterFileClient...
@Override public String getXML() { StringBuilder retval = new StringBuilder( 800 ); final String INDENT = " "; retval.append( INDENT ).append( XMLHandler.addTagValue( FILE_NAME, filename ) ); parentStepMeta.getParentTransMeta().getNamedClusterEmbedManager().registerUrl( filename ); retval.appe...
@Test public void getXmlTest() { metaBase.getXML(); verify( embedManager ).registerUrl( nullable( String.class ) ); }
boolean isWriteEnclosureForFieldName( ValueMetaInterface v, String fieldName ) { return ( isWriteEnclosed( v ) ) || isEnclosureFixDisabledAndContainsSeparatorOrEnclosure( fieldName.getBytes() ); }
@Test public void testWriteEnclosureForFieldNameWithoutEnclosureFixDisabled() { TextFileOutputData data = new TextFileOutputData(); data.binarySeparator = new byte[1]; data.binaryEnclosure = new byte[1]; data.writer = new ByteArrayOutputStream(); TextFileOutputMeta meta = getTextFileOutputMeta(); ...
@Override public void start() { try { forceMkdir(downloadDir); for (File tempFile : listTempFile(this.downloadDir)) { deleteQuietly(tempFile); } } catch (IOException e) { throw new IllegalStateException("Fail to create the directory: " + downloadDir, e); } }
@Test public void clean_temporary_files_at_startup() throws Exception { touch(new File(downloadDir, "sonar-php.jar")); touch(new File(downloadDir, "sonar-js.jar.tmp")); assertThat(downloadDir.listFiles()).hasSize(2); pluginDownloader.start(); File[] files = downloadDir.listFiles(); assertThat...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateTypeForCreateArrayExpression() { // Given: Expression expression = new CreateArrayExpression( ImmutableList.of(new UnqualifiedColumnReferenceExp(COL0)) ); // When: final SqlType type = expressionTypeManager.getExpressionSqlType(expression); // Then: ...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuilder buf = new StringBuilder(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_ST...
@Test public void colon() throws ScanException { String input = "a:b"; Tokenizer tokenizer = new Tokenizer(input); List<Token> tokenList = tokenizer.tokenize(); witnessList.add(new Token(Token.Type.LITERAL, "a")); witnessList.add(new Token(Token.Type.LITERAL, ":b")); ...
public Expression rewrite(final Expression expression) { return new ExpressionTreeRewriter<>(new OperatorPlugin()::process) .rewrite(expression, null); }
@Test public void shouldNotReplaceComparisonRowTimeAndNonString() { // Given: final Expression predicate = getPredicate( "SELECT * FROM orders where ROWTIME > 10.25;"); // When: final Expression rewritten = rewriter.rewrite(predicate); // Then: assertThat(rewritten, is(predicate)); ...
@GetMapping( path = "/api/{namespace}/{extension}", produces = MediaType.APPLICATION_JSON_VALUE ) @CrossOrigin @Operation(summary = "Provides metadata of the latest version of an extension") @ApiResponses({ @ApiResponse( responseCode = "200", description =...
@Test public void testLatestExtensionVersionAlpineLinuxTarget() throws Exception { var extVersion = mockExtension("alpine-arm64"); extVersion.setDisplayName("Foo Bar (alpine arm64)"); Mockito.when(repositories.findExtensionVersion("foo", "bar", "alpine-arm64", VersionAlias.LATEST)).thenRetur...
public boolean cancelQuery(String queryId) { Preconditions.checkState(_queryFuturesById != null, "Query cancellation is not enabled on server"); // Keep the future as it'll be cleaned up by the thread executing the query. Future<byte[]> future = _queryFuturesById.get(queryId); if (future == null) { ...
@Test public void testCancelQuery() { PinotConfiguration config = new PinotConfiguration(); config.setProperty("pinot.server.enable.query.cancellation", "true"); QueryScheduler qs = createQueryScheduler(config); InstanceRequestHandler handler = new InstanceRequestHandler("server01", config, qs...
public static void setConnectTimeout(int connectTimeout) { ParamUtil.connectTimeout = connectTimeout; }
@Test void testSetConnectTimeout() { int defaultVal = ParamUtil.getConnectTimeout(); assertEquals(defaultConnectTimeout, defaultVal); int expect = 50; ParamUtil.setConnectTimeout(expect); assertEquals(expect, ParamUtil.getConnectTimeout()); }
@Override public boolean containsKey(Object key) { return underlyingMap.containsKey(key); }
@Test public void testContains() { Map<String, Integer> underlying = createTestMap(); TranslatedValueMapView<String, String, Integer> view = new TranslatedValueMapView<>(underlying, v -> v.toString()); assertTrue(view.containsKey("foo")); assertTrue(view.containsKey("bar"...
public Map<String, Parameter> generateMergedWorkflowParams( WorkflowInstance instance, RunRequest request) { Workflow workflow = instance.getRuntimeWorkflow(); Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>(); Map<String, ParamDefinition> defaultWorkflowParams = defaultParamMa...
@Test public void testWorkflowParamRunParamsUpstreamMergeInitiator() { Map<String, ParamDefinition> defaultParams = singletonMap( "TARGET_RUN_DATE", ParamDefinition.buildParamDefinition("TARGET_RUN_DATE", 1000).toBuilder() .mode(ParamMode.MUTABLE_ON_START) ...
public final void isSameInstanceAs(@Nullable Object expected) { if (actual != expected) { failEqualityCheck( SAME_INSTANCE, expected, /* * Pass through *whether* the values are equal so that failEqualityCheck() can print that * information. But remove the de...
@Test public void isSameInstanceAsFailureWithNulls() { Object o = null; expectFailure.whenTesting().that(o).isSameInstanceAs("a"); assertFailureKeys("expected specific instance", "but was"); assertFailureValue("expected specific instance", "a"); }
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testReadFieldsPojoInTuple() { String[] readFields = {"f0; f2.int1; f2.string1"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, null, readFields, pojoInTupleType, pojo2Type); ...
public static Result find(List<Path> files, Consumer<LogEvent> logger) { List<String> mainClasses = new ArrayList<>(); for (Path file : files) { // Makes sure classFile is valid. if (!Files.exists(file)) { logger.accept(LogEvent.debug("MainClassFinder: " + file + " does not exist; ignoring")...
@Test public void testFindMainClass_simple() throws URISyntaxException, IOException { Path rootDirectory = Paths.get(Resources.getResource("core/class-finder-tests/simple").toURI()); MainClassFinder.Result mainClassFinderResult = MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEvent...
@VisibleForTesting static void verifyImageMetadata(ImageMetadataTemplate metadata, Path metadataCacheDirectory) throws CacheCorruptedException { List<ManifestAndConfigTemplate> manifestsAndConfigs = metadata.getManifestsAndConfigs(); if (manifestsAndConfigs.isEmpty()) { throw new CacheCorruptedExc...
@Test public void testVerifyImageMetadata_validV22() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V22ManifestTemplate(), new ContainerConfigurationTemplate()); ImageMetadataTemplate metadata = new ImageMetadataTem...
public static Read<String> readStrings() { return Read.newBuilder( (PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8)) .setCoder(StringUtf8Coder.of()) .build(); }
@Test public void testValueProviderTopic() { StaticValueProvider<String> provider = StaticValueProvider.of("projects/project/topics/topic"); Read<String> pubsubRead = PubsubIO.readStrings().fromTopic(provider); Pipeline.create().apply(pubsubRead); assertThat(pubsubRead.getTopicProvider(), not(nullValu...
public Object evaluate( final GenericRow row, final Object defaultValue, final ProcessingLogger logger, final Supplier<String> errorMsg ) { try { return expressionEvaluator.evaluate(new Object[]{ spec.resolveArguments(row), defaultValue, logger, ...
@Test public void shouldEvaluateExpressionWithUdfsSpecs() throws Exception { // Given: spec.addFunction( FunctionName.of("foo"), udf ); spec.addParameter( ColumnName.of("foo1"), Integer.class, 0 ); compiledExpression = new CompiledExpression( ex...
public final void containsKey(@Nullable Object key) { check("keySet()").that(checkNotNull(actual).keySet()).contains(key); }
@Test public void failMapContainsKey() { ImmutableMap<String, String> actual = ImmutableMap.of("a", "A"); expectFailureWhenTestingThat(actual).containsKey("b"); assertFailureKeys("value of", "expected to contain", "but was", "map was"); assertFailureValue("value of", "map.keySet()"); assertFailure...
static Map<String, String> generateConfig(int scale, Function<Integer, String> zkNodeAddress) { Map<String, String> servers = new HashMap<>(scale); for (int i = 0; i < scale; i++) { // The Zookeeper server IDs starts with 1, but pod index starts from 0 String key = String.form...
@Test public void testGenerateConfigThreeNodes() { Map<String, String> expected = new HashMap<>(3); expected.put("server.1", "my-cluster-zookeeper-0.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181"); expected.put("server.2", "my-cluster-zookeeper-1.my-cluster-z...
@Override public boolean onGestureTypingInputStart(int x, int y, AnyKeyboard.AnyKey key, long eventTime) { // no gesture in mini-keyboard return false; }
@Test public void testOnGestureTypingInputStart() { Assert.assertFalse( mUnderTest.onGestureTypingInputStart(66, 80, Mockito.mock(AnyKeyboard.AnyKey.class), 8888)); Mockito.verifyZeroInteractions(mMockParentListener, mMockKeyboardDismissAction); }
public void cache() { for(Map.Entry<Path, AttributedList<Path>> entry : contents.entrySet()) { final AttributedList<Path> list = entry.getValue(); if(!(AttributedList.<Path>emptyList() == list)) { if(log.isDebugEnabled()) { log.debug(String.format("Cac...
@Test public void testNoChunk() { final PathCache cache = new PathCache(1); final Path directory = new Path("/", EnumSet.of(Path.Type.directory)); final CachingListProgressListener listener = new CachingListProgressListener(cache); listener.cache(); assertFalse(cache.isCached...
public void setDisplayName(String displayName) throws IOException { this.displayName = Util.fixEmptyAndTrim(displayName); save(); }
@Test public void testSetDisplayName() throws Exception { final String displayName = "testDisplayName"; StubAbstractItem i = new StubAbstractItem(); i.setDisplayName(displayName); assertEquals(displayName, i.getDisplayName()); }
public static String[] decodeArray(String s) { if (s == null) return null; String[] escaped = StringUtils.split(s); String[] plain = new String[escaped.length]; for (int i = 0; i < escaped.length; ++i) plain[i] = StringUtils.unEscapeString(escaped[i]); return plain; }
@Test public void testDecodeArray() { Assert.assertTrue(TempletonUtils.encodeArray((String[]) null) == null); String[] tmp = new String[3]; tmp[0] = "fred"; tmp[1] = null; tmp[2] = "peter,lisa,, barney"; String[] tmp2 = TempletonUtils.decodeArray(TempletonUtils.encodeArray(tmp)); try { ...
public static String getKey(String dataId, String group) { StringBuilder sb = new StringBuilder(); GroupKey.urlEncode(dataId, sb); sb.append('+'); GroupKey.urlEncode(group, sb); return sb.toString(); }
@Test public void getKeySpecialTest() { String key = Md5ConfigUtil.getKey("DataId+", "Group"); Assert.isTrue(Objects.equals("DataId%2B+Group", key)); String key1 = Md5ConfigUtil.getKey("DataId%", "Group"); Assert.isTrue(Objects.equals("DataId%25+Group", key1)); }
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) { checkArgument( OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp); return new AutoValue_UBinary(binaryOp, lhs, rhs); }
@Test public void bitwiseOr() { assertUnifiesAndInlines( "4 | 17", UBinary.create(Kind.OR, ULiteral.intLit(4), ULiteral.intLit(17))); }
@Override public UpdateFeaturesResult updateFeatures(final Map<String, FeatureUpdate> featureUpdates, final UpdateFeaturesOptions options) { if (featureUpdates.isEmpty()) { throw new IllegalArgumentException("Feature updates can not be null or empty...
@Test public void testUpdateFeaturesShouldFailRequestForEmptyUpdates() { try (final AdminClientUnitTestEnv env = mockClientEnv()) { assertThrows( IllegalArgumentException.class, () -> env.adminClient().updateFeatures( new HashMap<>(), new Updat...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { Map<String, Object> fields = new HashMap<>(); if (flatten) { final String json = new String(rawMessage.getPayload(), charset); try { fields = flatten(json); } catch (Js...
@Test public void testReadResultingInDoubleFullJson() throws Exception { RawMessage json = new RawMessage("{\"url\":\"https://api.github.com/repos/Graylog2/graylog2-server/releases/assets/22660\",\"some_double\":0.50,\"id\":22660,\"name\":\"graylog2-server-0.20.0-preview.1.tgz\",\"label\":\"graylog2-server-...
public static String builderData(final String paramType, final String paramName, final ServerWebExchange exchange) { return newInstance(paramType).builder(paramName, exchange); }
@Test public void testBuildHeaderData() { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/http") .remoteAddress(new InetSocketAddress("localhost", 8080)) .header("shenyu", "shenyuHeader") .build()); assertEquals("she...
@Override public Object decode(Response response, Type type) throws IOException, DecodeException { if (response.status() == 404 || response.status() == 204) if (JSONObject.class.isAssignableFrom((Class<?>) type)) return new JSONObject(); else if (JSONArray.class.isAssignableFrom((Class<?>) typ...
@Test void nullBodyDecodesToNullString() throws IOException { Response response = Response.builder() .status(204) .reason("OK") .headers(Collections.emptyMap()) .request(request) .build(); assertThat(new JsonDecoder().decode(response, String.class)).isNull(); }
public SchemaRegistryClient get() { if (schemaRegistryUrl.equals("")) { return new DefaultSchemaRegistryClient(); } final RestService restService = serviceSupplier.get(); // This call sets a default sslSocketFactory. final SchemaRegistryClient client = schemaRegistryClientFactory.create( ...
@Test public void shouldUseDefaultSchemaRegistryClientWhenUrlNotSpecified() { // Given final KsqlConfig config1 = config(); final Map<String, Object> schemaRegistryClientConfigs = ImmutableMap.of( "ksql.schema.registry.url", " " ); final KsqlConfig config2 = new KsqlConfig(schemaRegis...
public MaterializedConfiguration getConfiguration() { MaterializedConfiguration conf = new SimpleMaterializedConfiguration(); FlumeConfiguration fconfig = getFlumeConfiguration(); AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName()); if (agentConf != null) { ...
@Test public void testSinkThrowsExceptionDuringConfiguration() throws Exception { String agentName = "agent1"; String sourceType = "seq"; String channelType = "memory"; String sinkType = UnconfigurableSink.class.getName(); Map<String, String> properties = getProperties(agentN...
@Override public boolean dropDatabase(String catName, String dbName) throws NoSuchObjectException, MetaException { boolean succ = rawStore.dropDatabase(catName, dbName); if (succ && !canUseEvents) { // in case of event based cache update, cache will be updated during commit. sharedCache .r...
@Test public void testDropDatabase() throws Exception { Configuration conf = MetastoreConf.newMetastoreConf(); MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true); MetastoreConf.setVar(conf, MetastoreConf.ConfVars.CACHED_RAW_STORE_MAX_CACHE_MEMORY, "-1Kb"); MetaStoreTestUtils.setCo...
public JunctionTree build() { return build(true); }
@Test public void testFullExample2() { // Bayesian Networks - A Self-contained introduction with implementation remarks // http://www.mathcs.emory.edu/~whalen/Papers/BNs/Intros/BayesianNetworksTutorial.pdf Graph<BayesVariable> graph = new BayesNetwork(); GraphNode xElectricity = add...
public OmemoFingerprint getFingerprint(OmemoDevice userDevice) throws CorruptedOmemoKeyException, IOException { T_IdKeyPair keyPair = loadOmemoIdentityKeyPair(userDevice); if (keyPair == null) { return null; } return keyUtil().getFingerprintOfIdentityKey(keyUtil...
@Test public void getFingerprint() throws IOException, CorruptedOmemoKeyException { assertNull("Method must return null for a non-existent fingerprint.", store.getFingerprint(alice)); store.storeOmemoIdentityKeyPair(alice, store.generateOmemoIdentityKeyPair()); OmemoFingerprint fingerprint =...
@ScalarOperator(CAST) @SqlType(StandardTypes.BOOLEAN) public static boolean castToBoolean(@SqlType(StandardTypes.REAL) long value) { return intBitsToFloat((int) value) != 0.0f; }
@Test public void testCastToBoolean() { assertFunction("CAST(REAL'754.1985' AS BOOLEAN)", BOOLEAN, true); assertFunction("CAST(REAL'0.0' AS BOOLEAN)", BOOLEAN, false); assertFunction("CAST(REAL'-0.0' AS BOOLEAN)", BOOLEAN, false); }
@Override public boolean addAll(Collection<? extends V> c) { return get(addAllAsync(c)); }
@Test public void testAddAll() { RSetCache<String> cache = redisson.getSetCache("list"); cache.add("a", 1, TimeUnit.SECONDS); Map<String, Duration> map = new HashMap<>(); map.put("a", Duration.ofSeconds(2)); map.put("b", Duration.ofSeconds(2)); map.put("c", Duration.o...
@Override public void subscribe(Subscriber<? super T>[] subscribers) { if (!validate(subscribers)) { return; } @SuppressWarnings("unchecked") Subscriber<? super T>[] newSubscribers = new Subscriber[subscribers.length]; for (int i = 0; i < subscribers.length; i++) { AutoDisposingSubscr...
@Test public void ifParallelism_and_subscribersCount_dontMatch_shouldFail() { TestSubscriber<Integer> subscriber = new TestSubscriber<>(); CompletableSubject scope = CompletableSubject.create(); //noinspection unchecked Subscriber<Integer>[] subscribers = new Subscriber[] {subscriber}; Flowable.j...
public static void validate(Properties props, GroupCoordinatorConfig groupCoordinatorConfig) { validateNames(props); Map<?, ?> valueMaps = CONFIG.parse(props); validateValues(valueMaps, groupCoordinatorConfig); }
@Test public void testInvalidConfigName() { Properties props = new Properties(); props.put(GroupConfig.CONSUMER_SESSION_TIMEOUT_MS_CONFIG, "10"); props.put("invalid.config.name", "10"); assertThrows(InvalidConfigurationException.class, () -> GroupConfig.validate(props, createGroupCoo...
public ExportMessagesCommand buildFromRequest(MessagesRequest request) { ExportMessagesCommand.Builder builder = ExportMessagesCommand.builder() .timeRange(toAbsolute(request.timeRange())) .queryString(request.queryString()) .streams(request.streams()) ...
@Test void buildsCommandFromRequest() { MessagesRequest request = MessagesRequest.builder().build(); ExportMessagesCommand command = sut.buildFromRequest(request); assertAll( () -> assertThat(command.queryString()).isEqualTo(request.queryString()), () -> asse...
public RuleInformation createCustomRule(NewCustomRule newCustomRule) { try (DbSession dbSession = dbClient.openSession(false)) { return createCustomRule(newCustomRule, dbSession); } }
@Test public void createCustomRule_shouldReturnExceptedRuleInformation() { when(ruleCreator.create(Mockito.any(), Mockito.any(NewCustomRule.class))).thenReturn(new RuleDto().setUuid("uuid")); when(dbClient.ruleDao().selectRuleParamsByRuleUuids(any(), eq(List.of("uuid")))).thenReturn(List.of(new RuleParamDto()...
@Override public int responseCode() { return responseCode; }
@Test public void shouldBeAbleToInitializeResponse() throws Exception { int responseCode = 0; GoApiResponse response = new DefaultGoApiResponse(responseCode); assertThat(response.responseCode(), is(responseCode)); }
@Udf(description = "Returns the hyperbolic sine of an INT value") public Double sinh( @UdfParameter( value = "value", description = "The value in radians to get the hyperbolic sine of." ) final Integer value ) { return sinh(value == null ? null : value.dou...
@Test public void shouldHandleZero() { assertThat(udf.sinh(0.0), closeTo(0.0, 0.000000000000001)); assertThat(udf.sinh(0), closeTo(0.0, 0.000000000000001)); assertThat(udf.sinh(0L), closeTo(0.0, 0.000000000000001)); }
public static List<HttpCookie> decodeCookies(List<String> cookieStrs) { List<HttpCookie> cookies = new ArrayList<>(); if (cookieStrs == null) { return cookies; } for (String cookieStr : cookieStrs) { if (cookieStr == null) { continue; } StringTokenizer to...
@Test public void testDecodeSingleCookieWithAttr() { String cookieStr = cookieA.toString(); Assert.assertEquals(CookieUtil.decodeCookies(Collections.singletonList(cookieStr)), Collections.singletonList(cookieA)); }
public static List<ZKAuthInfo> parseAuth(String authString) throws BadAuthFormatException{ List<ZKAuthInfo> ret = Lists.newArrayList(); if (authString == null) { return ret; } List<String> authComps = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults() ...
@Test public void testNullAuth() { List<ZKAuthInfo> result = ZKUtil.parseAuth(null); assertTrue(result.isEmpty()); }
@Override public Executor getExecutor() { return null; }
@Test void testGetExecutor() { // Default listener executor is null. assertNull(new AbstractListener() { @Override public void receiveConfigInfo(String configInfo) { } }.getExecutor()); }
@Override public void configure(ResourceGroup group, SelectionContext<VariableMap> criteria) { Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry = getMatchingSpec(group, criteria); if (groups.putIfAbsent(group.getId(), group) == null) { // If a new spec replaces the spec re...
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "No matching configuration found for: missing") public void testMissing() { H2DaoProvider daoProvider = setup("test_missing"); H2ResourceGroupsDao dao = daoProvider.get(); dao.createResourceGroupsGl...
public static JsonElement parseString(String json) throws JsonSyntaxException { return parseReader(new StringReader(json)); }
@Test public void testParseMixedArray() { String json = "[{},13,\"stringValue\"]"; JsonElement e = JsonParser.parseString(json); assertThat(e.isJsonArray()).isTrue(); JsonArray array = e.getAsJsonArray(); assertThat(array.get(0).toString()).isEqualTo("{}"); assertThat(array.get(1).getAsInt())...
@Override public JibContainerBuilder createJibContainerBuilder( JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode) { try { FileCollection projectDependencies = project.files( project.getConfigurations().getByName(configurationName).getResolvedConf...
@Test public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() throws IOException, InvalidImageReferenceException { temporaryFolder.newFolder("WEB-INF", "classes"); setUpWarProject(temporaryFolder.getRoot().toPath()); assertThat( gradleProjectProperties.createJibContainer...
@Beta public static Application fromBuilder(Builder builder) throws Exception { return builder.build(); }
@Test void get_search_handler() throws Exception { try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container().search(true))))) { SearchHandler searchHandler = (SearchHandler) app.getRequestHandlerB...
@Override public boolean containsAny(Set<DiscreteResource> other) { return false; }
@Test public void testContainsAny() { DiscreteResource res1 = Resources.discrete(DeviceId.deviceId("a")).resource(); DiscreteResource res2 = Resources.discrete(DeviceId.deviceId("b")).resource(); assertThat(sut.containsAny(ImmutableSet.of(res1)), is(false)); assertThat(sut.containsA...
@Override public PluggableTaskPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { final TaskPreference[] tp = {null}; extension.doOnTask(descriptor.id(), (task, pluginDescriptor) -> tp[0] = new TaskPreference(task)); TaskConfig config = tp[0].getConfig(); TaskView view = tp[0]...
@Test public void shouldBuildPluginInfo() throws Exception { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); PluggableTaskPluginInfo pluginInfo = new PluggableTaskPluginInfoBuilder(extension) .pluginInfoFor(descriptor); List<PluginConfiguration> pluginCo...
@Override public String toString() { try { return JsonUtils.objectToString(unwrapIndexes()); } catch (JsonProcessingException e) { return "Unserializable value due to " + e.getMessage(); } }
@Test public void testToString() throws IOException { IndexType index1 = Mockito.mock(IndexType.class); Mockito.when(index1.getId()).thenReturn("index1"); IndexConfig indexConf = new IndexConfig(false); FieldIndexConfigs fieldIndexConfigs = new FieldIndexConfigs.Builder() .add(index1, in...
public static Expression fromJson(String json) { return fromJson(json, null); }
@Test public void invalidValues() { assertThatThrownBy( () -> ExpressionParser.fromJson( "{\n" + " \"type\" : \"not-nan\",\n" + " \"term\" : \"x\",\n" + " \"value\" : 34.0\n" ...
public static String getKey(String dataId, String group) { StringBuilder sb = new StringBuilder(); GroupKey.urlEncode(dataId, sb); sb.append('+'); GroupKey.urlEncode(group, sb); return sb.toString(); }
@Test public void getKeyTest() { String key = Md5ConfigUtil.getKey("DataId", "Group"); Assert.isTrue(Objects.equals("DataId+Group", key)); }
public static void addToRequest(Crypto crypto, SecretKey key, byte[] requestBody, String signatureAlgorithm, Request request) { Mac mac; try { mac = crypto.mac(signatureAlgorithm); } catch (NoSuchAlgorithmException e) { throw new ConnectException(e); } by...
@Test public void addToRequestShouldThrowExceptionOnInvalidSignatureAlgorithm() throws NoSuchAlgorithmException { Request request = mock(Request.class); Crypto crypto = mock(Crypto.class); when(crypto.mac(anyString())).thenThrow(new NoSuchAlgorithmException("doesn'texist")); assertTh...
List<Integer> allocatePorts(NetworkPortRequestor service, int wantedPort) { PortAllocBridge allocator = new PortAllocBridge(this, service); service.allocatePorts(wantedPort, allocator); return allocator.result(); }
@Test void allocating_overlapping_ports_throws_exception() { assertThrows(RuntimeException.class, () -> { HostPorts host = new HostPorts("myhostname"); MockRoot root = new MockRoot(); TestService service2 = new TestService(root, 2); TestService service1 = new ...
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void piInstructionEncodingTest() { PiActionId actionId = PiActionId.of("set_egress_port"); PiActionParamId actionParamId = PiActionParamId.of("port"); PiActionParam actionParam = new PiActionParam(actionParamId, ImmutableByteSequence.copyFrom(10)); PiTableAction action =...
@Override public List<MenuDO> getMenuList() { return menuMapper.selectList(); }
@Test public void testGetMenuList_ids() { // mock 数据 MenuDO menu100 = randomPojo(MenuDO.class); menuMapper.insert(menu100); MenuDO menu101 = randomPojo(MenuDO.class); menuMapper.insert(menu101); // 准备参数 Collection<Long> ids = Collections.singleton(menu100.getI...
static byte[] getBytes(ByteBuffer buffer) { int remaining = buffer.remaining(); if (buffer.hasArray() && buffer.arrayOffset() == 0) { // do not copy data if the ByteBuffer is a simple wrapper over an array byte[] array = buffer.array(); if (array.length == remaining) ...
@Test public void testGetBytesOffsetNonZero() { byte[] originalArray = {1, 2, 3}; ByteBuffer wrapped = ByteBuffer.wrap(originalArray); wrapped.position(1); assertEquals(1, wrapped.position()); wrapped = wrapped.slice(); assertEquals(1, wrapped.arrayOffset()); ...
void addGetModelForKieBaseMethod(StringBuilder sb) { sb.append( " public java.util.List<Model> getModelsForKieBase(String kieBaseName) {\n"); if (!modelMethod.getKieBaseNames().isEmpty()) { sb.append( " switch (kieBaseName) {\n"); for (String kBase : mod...
@Test public void addGetModelForKieBaseMethodMatchingModelsByKBaseValuesTest() { KieBaseModel kieBaseModel = getKieBaseModel("ModelTest"); Map<String, KieBaseModel> kBaseModels = new HashMap<>(); kBaseModels.put("default-kie", kieBaseModel); List<String> modelByKBaseValues = Collecti...
@Override public Column convert(BasicTypeDefine typeDefine) { Long typeDefineLength = typeDefine.getLength(); PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.get...
@Test public void testConvertDecimal() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("numeric(38,2)") .dataType("numeric") .precision(38L) ...
public void deregister(Operation operation) { Map<Long, Operation> operations = liveOperations.get(operation.getCallerAddress()); if (operations == null) { throw new IllegalStateException("Missing address during de-registration of operation=" + operation); } if (operations....
@Test public void when_deregisterNotExistingAddress_then_fail() throws UnknownHostException { Operation op1 = createOperation("1.2.3.4", 1234, 2222L); assertThrows(IllegalStateException.class, () -> r.deregister(op1)); }
@Override public int getFactoryId() { throw new UnsupportedOperationException(getClass().getName() + " is only used locally!"); }
@Test(expected = UnsupportedOperationException.class) public void testGetFactoryId() { operation.getFactoryId(); }
public List<R> scanForResourcesInClasspathRoot(URI root, Predicate<String> packageFilter) { requireNonNull(root, "root must not be null"); requireNonNull(packageFilter, "packageFilter must not be null"); BiFunction<Path, Path, Resource> createResource = createClasspathRootResource(); ret...
@Test void scanForResourcesInClasspathRootWithPackage() { URI classpathRoot = new File("src/test/resources").toURI(); List<URI> resources = resourceScanner.scanForResourcesInClasspathRoot(classpathRoot, aPackage -> true); assertThat(resources, containsInAnyOrder( URI.create("clas...
public static String randomNumeric(int length) { int leftLimit = 48; // letter '0' int rightLimit = 57; // letter '9' Random random = new Random(); return random.ints(leftLimit, rightLimit + 1) .limit(length) .collect(StringBuilder::new, StringBuilder::ap...
@Test public void testNumeric() { System.out.println(ByteUtil.randomNumeric(100)); }
@Override public ConnectionProperties parse(final String url, final String username, final String catalog) { Matcher matcher = URL_PATTERN.matcher(url); ShardingSpherePreconditions.checkState(matcher.find(), () -> new UnrecognizedDatabaseURLException(url, URL_PATTERN.pattern())); return new ...
@Test void assertNewConstructorFailure() { assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("xxx:xxxx:xxxxxxxx", null, null)); }
@Override protected Optional<ErrorResponse> filter(DiscFilterRequest request) { String method = request.getMethod(); URI uri = request.getUri(); for (Rule rule : rules) { if (rule.matches(method, uri)) { log.log(Level.FINE, () -> String.for...
@Test void performs_default_action_if_no_rule_matches() throws IOException { RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder() .dryrun(false) .defaultRule(new DefaultRule.Builder() .action(DefaultRule.Action.Enum.BLOCK) ...
public void command(String primaryCommand, SecureConfig config, String... allArguments) { terminal.writeLine(""); final Optional<CommandLine> commandParseResult; try { commandParseResult = Command.parse(primaryCommand, allArguments); } catch (InvalidCommandException e) { ...
@Test public void testAddWithoutCreatedKeystore() { cli.command("add", newStoreConfig.clone(), UUID.randomUUID().toString()); assertThat(terminal.out).containsIgnoringCase("ERROR: Logstash keystore not found. Use 'create' command to create one."); }
@Override public CompletableFuture<Void> relinquishMastership(DeviceId deviceId) { return store.relinquishRole(networkId, localNodeId, deviceId) .thenAccept(this::post) .thenApply(v -> null); }
@Test public void relinquishMastership() { //no backups - should just turn to NONE for device. mastershipMgr1.setRole(NID_LOCAL, VDID1, MASTER); assertEquals("wrong role:", MASTER, mastershipMgr1.getLocalRole(VDID1)); mastershipMgr1.relinquishMastership(VDID1); assertNull("wr...
@Nonnull @Override public Optional<? extends Algorithm> parse( @Nullable final String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } String algorithmStr; Optional<Mode> modeOptional = Optional.empty(); ...
@Test void rsa() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaCipherMapper jcaAlgorithmMapper = new JcaCipherMapper(); Optional<? extends Algorithm> algorithm = jcaAlgorithmMapper.parse(...
@Override public void execute(Context context) { Collection<CeTaskMessages.Message> warnings = new ArrayList<>(); try (CloseableIterator<ScannerReport.AnalysisWarning> it = reportReader.readAnalysisWarnings()) { it.forEachRemaining(w -> warnings.add(new CeTaskMessages.Message(w.getText(), w.getTimestamp...
@Test public void execute_persists_warnings_from_reportReader() { ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableLis...
@InvokeOnHeader(Web3jConstants.SHH_NEW_GROUP) void shhNewGroup(Message message) throws IOException { Request<?, ShhNewGroup> request = web3j.shhNewGroup(); setRequestId(message, request); ShhNewGroup response = request.send(); boolean hasError = checkForError(message, response); ...
@Test public void shhNewGroupTest() throws Exception { ShhNewGroup response = Mockito.mock(ShhNewGroup.class); Mockito.when(mockWeb3j.shhNewGroup()).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getAddress()).thenReturn("test"); ...
@Override public void persist(MessageQueue mq) { if (mq == null) { return; } ControllableOffset offset = this.offsetTable.get(mq); if (offset != null) { OffsetSerializeWrapper offsetSerializeWrapper = null; try { offsetSerializeWrap...
@Test public void testPersist() throws Exception { OffsetStore offsetStore = new LocalFileOffsetStore(mQClientFactory, group); MessageQueue messageQueue0 = new MessageQueue(topic, brokerName, 0); offsetStore.updateOffset(messageQueue0, 1024, false); offsetStore.persist(messageQueue0...
@Override public Name getLocation(final Path file) throws BackgroundException { if(StringUtils.isNotBlank(session.getHost().getRegion())) { return new S3Region(session.getHost().getRegion()); } final Path bucket = containerService.getContainer(file); return this.getLocati...
@Test public void testAccessPathStyleBucketEuCentral() throws Exception { final Host host = new Host(new S3Protocol(), new S3Protocol().getDefaultHostname(), new Credentials( PROPERTIES.get("s3.key"), PROPERTIES.get("s3.secret") )) { @Override public String ge...
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(new String(getSignature(), UTF_8)).append(" "); sb.append(getVersion()).append(" "); sb.append(getHeaderLen()).append(" "); sb.append(getUnknown_000c()).append(" "); sb.append(getLastModified())....
@Test public void testToString() { assertTrue(chmItsfHeader.toString().contains(TestParameters.VP_ISTF_SIGNATURE)); }
@Override public CeWorker create(int ordinal) { String uuid = uuidFactory.create(); CeWorkerImpl ceWorker = new CeWorkerImpl(ordinal, uuid, queue, taskProcessorRepository, ceWorkerController, executionListeners); ceWorkers = Stream.concat(ceWorkers.stream(), Stream.of(ceWorker)).collect(Collectors.toSet()...
@Test public void create_allows_multiple_calls_with_same_ordinal() { IntStream.range(0, new Random().nextInt(50)).forEach(ignored -> { CeWorker ceWorker = underTest.create(randomOrdinal); assertThat(ceWorker.getOrdinal()).isEqualTo(randomOrdinal); }); }
@Override public JobMetricsMessageParameters getUnresolvedMessageParameters() { return new JobMetricsMessageParameters(); }
@Test void testMessageParameters() { assertThat(jobMetricsHeaders.getUnresolvedMessageParameters()) .isInstanceOf(JobMetricsMessageParameters.class); }
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception { return newGetter(object, parent, modifier, field.getType(), field::get, (t, et) -> new FieldGetter(parent, field, modifier, t, et)); }
@Test public void newFieldGetter_whenExtractingFromSimpleField_thenInferTypeFromFieldType() throws Exception { OuterObject object = new OuterObject("name"); Getter getter = GetterFactory.newFieldGetter(object, null, outerNameField, null); Class<?> returnType = getter.getReturnType(); ...
@Override public Set<String> getHandledCeTaskTypes() { return HANDLED_TYPES; }
@Test public void getHandledCeTaskTypes() { Assertions.assertThat(underTest.getHandledCeTaskTypes()).containsExactly(BRANCH_ISSUE_SYNC); }
@VisibleForTesting void validateParentMenu(Long parentId, Long childId) { if (parentId == null || ID_ROOT.equals(parentId)) { return; } // 不能设置自己为父菜单 if (parentId.equals(childId)) { throw exception(MENU_PARENT_ERROR); } MenuDO menu = menuMapper...
@Test public void testValidateParentMenu_canNotSetSelfToBeParent() { // 调用,并断言异常 assertServiceException(() -> menuService.validateParentMenu(1L, 1L), MENU_PARENT_ERROR); }
@Override public boolean isDirectory() { return key.endsWith("/"); }
@Test public void testIsDirectory() { assertTrue(S3ResourceId.fromUri("s3://my_bucket/tmp dir/").isDirectory()); assertTrue(S3ResourceId.fromUri("s3://my_bucket/").isDirectory()); assertTrue(S3ResourceId.fromUri("s3://my_bucket").isDirectory()); assertFalse(S3ResourceId.fromUri("s3://my_bucket/file")....
public static <EventT> Write<EventT> write() { return new AutoValue_JmsIO_Write.Builder<EventT>().build(); }
@Test public void testWriteMessage() throws Exception { ArrayList<String> data = new ArrayList<>(); for (int i = 0; i < 100; i++) { data.add("Message " + i); } pipeline .apply(Create.of(data)) .apply( JmsIO.<String>write() .withConnectionFactory(conne...
@Override public void filter(final ContainerRequestContext requestContext, ContainerResponseContext response) { final Object entity = response.getEntity(); if (isEmptyOptional(entity)) { response.setStatus(Response.Status.NO_CONTENT.getStatusCode()); re...
@Test void doesNothingOnPresentOptional() { doReturn(Optional.of(new Object())).when(response).getEntity(); toTest.filter(requestContext, response); verifyNoMoreInteractions(response); }
public String toRegexForFixedDate(Date date) { StringBuilder buf = new StringBuilder(); Converter<Object> p = headTokenConverter; while (p != null) { if (p instanceof LiteralConverter) { buf.append(p.convert(null)); } else if (p instanceof IntegerTokenConverter) { buf.append(File...
@Test public void asRegexByDate() { Calendar cal = Calendar.getInstance(); cal.set(2003, 4, 20, 17, 55); { FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); String regex = fnp.toRegexForFixedDate(cal.getTime()); assertEquals("foo-2003.05.20-" + ...
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test public void testAddressToOctetsIPv4() { Ip4Address ipAddress; byte[] value; value = new byte[] {1, 2, 3, 4}; ipAddress = Ip4Address.valueOf("1.2.3.4"); assertThat(ipAddress.toOctets(), is(value)); value = new byte[] {0, 0, 0, 0}; ipAddress = Ip4Address...
public static Future<Void> unregisterNodes( Reconciliation reconciliation, Vertx vertx, AdminClientProvider adminClientProvider, PemTrustSet pemTrustSet, PemAuthIdentity pemAuthIdentity, List<Integer> nodeIdsToUnregister ) { try { ...
@Test void testFailingNodeUnregistration(VertxTestContext context) { Admin mockAdmin = ResourceUtils.adminClient(); ArgumentCaptor<Integer> unregisteredNodeIdCaptor = ArgumentCaptor.forClass(Integer.class); when(mockAdmin.unregisterBroker(unregisteredNodeIdCaptor.capture())).thenAnswer(i ->...
@Nullable public InheritanceVertex getVertex(@Nonnull String name) { InheritanceVertex vertex = vertices.get(name); if (vertex == null && !stubs.contains(name)) { // Vertex does not exist and was not marked as a stub. // We want to look up the vertex for the given class and figure out if its valid or needs t...
@Test void getFamilyOfThrowable() { String notFoodExceptionName = Inheritance.NotFoodException.class.getName().replace('.', '/'); ClassPathNode classPath = workspace.findJvmClass(notFoodExceptionName); assertNotNull(classPath, "Could not find class 'NotFoodException'"); // Assert that looking at child types o...
public boolean hasEnvironmentAssociated() { if (environmentName != null) { return true; } return false; }
@Test public void hasEnvironmentAssociated_shouldReturnTrueWhenAPipelineIsAssociatedWithAnEnvironment() { EnvironmentPipelineModel foo = new EnvironmentPipelineModel("foo"); assertThat(foo.hasEnvironmentAssociated(), is(false)); }
public static Builder newBuilder() { return new Builder(); }
@Test public void builder_set_methods_do_not_fail_if_login_is_null() { AuthenticationException.newBuilder().setSource(null).setLogin(null).setMessage(null); }
@Override @CheckForNull public Language get(String languageKey) { return languages.get(languageKey); }
@Test public void should_return_null_when_language_not_found() { WsTestUtil.mockReader(wsClient, "/api/languages/list", new InputStreamReader(getClass().getResourceAsStream("DefaultLanguageRepositoryTest/languages-ws.json"))); when(properties.getStringArray("sonar.java.file.suffixes")).thenReturn(JAVA_...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Counter) { final Counter other = (Counter) obj; return Objects.equals(this.total, other.total) && Objects.equals(this.start, other.start)...
@Test public void equals() { long start = 100L; long total = 300L; long end = 200L; Counter tt = new Counter(start, total, end); Counter same = new Counter(start, total, end); Counter diff = new Counter(300L, 700L, 400L); new EqualsTester() .ad...
private AttributeScope getScope(String mdScopeValue) { if (StringUtils.isNotEmpty(mdScopeValue)) { return AttributeScope.valueOf(mdScopeValue); } return AttributeScope.valueOf(config.getScope()); }
@Test void givenDefaultConfig_whenVerify_thenOK() { TbMsgDeleteAttributesNodeConfiguration defaultConfig = new TbMsgDeleteAttributesNodeConfiguration().defaultConfiguration(); assertThat(defaultConfig.getScope()).isEqualTo(DataConstants.SERVER_SCOPE); assertThat(defaultConfig.getKeys()).isEq...
public void onKeyEvent(@NotNull TypeAheadEvent keyEvent) { if (!myTerminalModel.isTypeAheadEnabled()) return; myTerminalModel.lock(); try { if (myTerminalModel.isUsingAlternateBuffer()) { resetState(); return; } TypeAheadTermina...
@Test public void testCursorMovePrediction() throws Exception { new TestRunner() { @Override void run() { model.currentLine += 'a'; manager.onKeyEvent(new TypeAheadEvent(TypeAheadEvent.EventType.RightArrow)); boolean found = false; ...
void start() throws TransientKinesisException { ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder(); for (ShardCheckpoint checkpoint : initialCheckpoint) { shardsMap.put(checkpoint.getShardId(), createShardIterator(kinesis, checkpoint)); } shardIteratorsMap.set(sh...
@Test public void shouldStopReadersPoolWhenLastShardReaderStopped() throws Exception { when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class); when(firstIterator.findSuccessiveShardRecordIterators()).thenReturn(Collections.emptyList()); shardReadersPool.start(); verify(firs...
@Override public Class<? extends Event> subscribeType() { return ServerListChangedEvent.class; }
@Test void testSubscribeType() { assertEquals(ServerListChangedEvent.class, clientProxy.subscribeType()); }
@Override public void write(final OutputStream out) { // CHECKSTYLE_RULES.ON: CyclomaticComplexity try { out.write("[".getBytes(StandardCharsets.UTF_8)); write(out, buildHeader()); final BlockingRowQueue rowQueue = queryMetadata.getRowQueue(); while (!connectionClosed && queryMetadat...
@Test public void shouldHandleWindowedTableRows() { // Given: when(queryMetadata.getResultType()).thenReturn(ResultType.WINDOWED_TABLE); doAnswer(windowedTableRows("key1", "Row1", "key2", null, "key3", "Row3")) .when(rowQueue).drainTo(any()); createWriter(); forceWriterToNotBlock(); ...