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));
}
return current;
} | @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 为空,则使用 path 填充
if (StrUtil.isEmpty(name)) {
name = path;
}
// 上传到文件存储器
FileClient client = fileConfigService.getMasterFileClient();
Assert.notNull(client, "客户端(master) 不能为空");
String url = client.upload(content, path, type);
// 保存到数据库
FileDO file = new FileDO();
file.setConfigId(client.getId());
file.setName(name);
file.setPath(path);
file.setUrl(url);
file.setType(type);
file.setSize(content.length);
fileMapper.insert(file);
return url;
} | @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()).thenReturn(client);
String url = randomString();
when(client.upload(same(content), same(path), eq("image/jpeg"))).thenReturn(url);
when(client.getId()).thenReturn(10L);
String name = "单测文件名";
// 调用
String result = fileService.createFile(name, path, content);
// 断言
assertEquals(result, url);
// 校验数据
FileDO file = fileMapper.selectOne(FileDO::getPath, path);
assertEquals(10L, file.getConfigId());
assertEquals(path, file.getPath());
assertEquals(url, file.getUrl());
assertEquals("image/jpeg", file.getType());
assertEquals(content.length, file.getSize());
} |
@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.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.OVERRIDE_OUTPUT, overrideOutput ) );
retval.append( " <fields>" ).append( Const.CR );
for ( int i = 0; i < outputFields.size(); i++ ) {
AvroOutputField field = outputFields.get( i );
if ( field.getPentahoFieldName() != null && field.getPentahoFieldName().length() != 0 ) {
retval.append( " <field>" ).append( Const.CR );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( "path", field.getFormatFieldName() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( "name", field.getPentahoFieldName() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( "type", field.getAvroType().getId() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( PRECISION, field.getPrecision() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( SCALE, field.getScale() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( NULLABLE, field.getAllowNull() ) );
retval.append( SPACES_8 ).append( XMLHandler.addTagValue( DEFAULT, field.getDefaultValue() ) );
retval.append( " </field>" ).append( Const.CR );
}
}
retval.append( " </fields>" ).append( Const.CR );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.COMPRESSION, compressionType ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.DATE_FORMAT, dateTimeFormat ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.DATE_IN_FILE_NAME, dateInFileName ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.TIME_IN_FILE_NAME, timeInFileName ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.SCHEMA_FILENAME, schemaFilename ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.NAMESPACE, namespace ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.DOC_VALUE, docValue ) );
retval.append( INDENT ).append( XMLHandler.addTagValue( FieldNames.RECORD_NAME, recordName ) );
return retval.toString();
} | @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();
meta.setEnclosureForced(false);
meta.setEnclosureFixDisabled(true);
stepMockHelper.stepMeta.setStepMetaInterface( meta );
TextFileOutput textFileOutput = getTextFileOutput(data, meta);
ValueMetaBase valueMetaInterface = getValueMetaInterface();
assertFalse(textFileOutput.isWriteEnclosureForFieldName(valueMetaInterface, "fieldName"));
} |
@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(files).hasSize(1);
assertThat(files[0].getName()).isEqualTo("sonar-php.jar");
} |
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:
assertThat(type, is(SqlTypes.array(SqlTypes.BIGINT)));
} |
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_STATE:
handleLiteralState(c, tokenList, buf);
break;
case START_STATE:
handleStartState(c, tokenList, buf);
break;
case DEFAULT_VAL_STATE:
handleDefaultValueState(c, tokenList, buf);
default:
}
}
// EOS
switch (state) {
case LITERAL_STATE:
addLiteralToken(tokenList, buf);
break;
case DEFAULT_VAL_STATE:
// trailing colon. see also LOGBACK-1140
buf.append(CoreConstants.COLON_CHAR);
addLiteralToken(tokenList, buf);
break;
case START_STATE:
// trailing $. see also LOGBACK-1149
buf.append(CoreConstants.DOLLAR);
addLiteralToken(tokenList, buf);
break;
}
return tokenList;
} | @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"));
assertEquals(witnessList, tokenList);
} |
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 = "The extension metadata are returned in JSON format"
),
@ApiResponse(
responseCode = "404",
description = "The specified extension could not be found",
content = @Content()
),
@ApiResponse(
responseCode = "429",
description = "A client has sent too many requests in a given amount of time",
content = @Content(),
headers = {
@Header(
name = "X-Rate-Limit-Retry-After-Seconds",
description = "Number of seconds to wait after receiving a 429 response",
schema = @Schema(type = "integer", format = "int32")
),
@Header(
name = "X-Rate-Limit-Remaining",
description = "Remaining number of requests left",
schema = @Schema(type = "integer", format = "int32")
)
}
)
})
public ResponseEntity<ExtensionJson> getExtension(
@PathVariable @Parameter(description = "Extension namespace", example = "redhat")
String namespace,
@PathVariable @Parameter(description = "Extension name", example = "java")
String extension
) {
for (var registry : getRegistries()) {
try {
return ResponseEntity.ok()
.cacheControl(CacheControl.noCache().cachePublic())
.body(registry.getExtension(namespace, extension, null));
} catch (NotFoundException exc) {
// Try the next registry
}
}
var json = ExtensionJson.error("Extension not found: " + NamingUtil.toExtensionId(namespace, extension));
return new ResponseEntity<>(json, HttpStatus.NOT_FOUND);
} | @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)).thenReturn(extVersion);
Mockito.when(repositories.findLatestVersionForAllUrls(extVersion.getExtension(), "alpine-arm64", false, true)).thenReturn(extVersion);
mockMvc.perform(get("/api/{namespace}/{extension}/{target}/{version}", "foo", "bar", "alpine-arm64", "latest"))
.andExpect(status().isOk())
.andExpect(content().json(extensionJson(e -> {
e.namespace = "foo";
e.name = "bar";
e.version = "1.0.0";
e.verified = false;
e.timestamp = "2000-01-01T10:00Z";
e.displayName = "Foo Bar (alpine arm64)";
e.versionAlias = List.of("latest");
e.targetPlatform = "alpine-arm64";
})));
} |
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) {
return false;
}
boolean done = future.isDone();
if (!done) {
future.cancel(true);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Cancelled query: {} that's done: {}", queryId, done);
}
return true;
} | @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, mock(ServerMetrics.class), mock(AccessControl.class));
Set<String> queryIds = new HashSet<>();
queryIds.add("foo");
queryIds.add("bar");
queryIds.add("baz");
for (String id : queryIds) {
ServerQueryRequest query = mock(ServerQueryRequest.class);
when(query.getQueryId()).thenReturn(id);
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
ChannelFuture chFu = mock(ChannelFuture.class);
when(ctx.writeAndFlush(any())).thenReturn(chFu);
handler.submitQuery(query, ctx, "myTable01", System.currentTimeMillis(), mock(InstanceRequest.class));
}
Assert.assertEquals(handler.getRunningQueryIds(), queryIds);
for (String id : queryIds) {
handler.cancelQuery(id);
}
Assert.assertTrue(handler.getRunningQueryIds().isEmpty());
Assert.assertFalse(handler.cancelQuery("unknown"));
} |
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"));
assertTrue(view.containsKey("baz"));
assertFalse(view.containsKey("quux"));
underlying.put("quux", 101);
assertTrue(view.containsKey("quux"));
} |
public Map<String, Parameter> generateMergedWorkflowParams(
WorkflowInstance instance, RunRequest request) {
Workflow workflow = instance.getRuntimeWorkflow();
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
Map<String, ParamDefinition> defaultWorkflowParams =
defaultParamManager.getDefaultWorkflowParams();
// merge workflow params for start
if (request.isFreshRun()) {
// merge default workflow params
ParamsMergeHelper.mergeParams(
allParamDefs,
defaultWorkflowParams,
ParamsMergeHelper.MergeContext.workflowCreate(ParamSource.SYSTEM_DEFAULT, request));
// merge defined workflow params
if (workflow.getParams() != null) {
ParamsMergeHelper.mergeParams(
allParamDefs,
workflow.getParams(),
ParamsMergeHelper.MergeContext.workflowCreate(ParamSource.DEFINITION, request));
}
}
// merge workflow params from previous instance for restart
if (!request.isFreshRun() && instance.getParams() != null) {
Map<String, ParamDefinition> previousParamDefs =
instance.getParams().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toDefinition()));
// remove reserved params, which should be injected again by the system.
for (String paramName : Constants.RESERVED_PARAM_NAMES) {
previousParamDefs.remove(paramName);
}
ParamsMergeHelper.mergeParams(
allParamDefs,
previousParamDefs,
ParamsMergeHelper.MergeContext.workflowCreate(ParamSource.SYSTEM, false));
}
// merge run params
if (request.getRunParams() != null) {
ParamSource source = getParamSource(request.getInitiator(), request.isFreshRun());
ParamsMergeHelper.mergeParams(
allParamDefs,
request.getRunParams(),
ParamsMergeHelper.MergeContext.workflowCreate(source, request));
}
// merge user provided restart run params
getUserRestartParam(request)
.ifPresent(
userRestartParams -> {
ParamSource source = getParamSource(request.getInitiator(), request.isFreshRun());
ParamsMergeHelper.mergeParams(
allParamDefs,
userRestartParams,
ParamsMergeHelper.MergeContext.workflowCreate(source, request));
});
// cleanup any placeholder params and convert to params
return ParamsMergeHelper.convertToParameters(ParamsMergeHelper.cleanupParams(allParamDefs));
} | @Test
public void testWorkflowParamRunParamsUpstreamMergeInitiator() {
Map<String, ParamDefinition> defaultParams =
singletonMap(
"TARGET_RUN_DATE",
ParamDefinition.buildParamDefinition("TARGET_RUN_DATE", 1000).toBuilder()
.mode(ParamMode.MUTABLE_ON_START)
.build());
Map<String, ParamDefinition> runParams =
singletonMap(
"TARGET_RUN_DATE",
ParamDefinition.buildParamDefinition("TARGET_RUN_DATE", 1001).toBuilder()
.mode(ParamMode.MUTABLE)
.meta(singletonMap(Constants.METADATA_SOURCE_KEY, "DEFINITION"))
.build());
when(defaultParamManager.getDefaultWorkflowParams()).thenReturn(defaultParams);
ParamSource[] expectedSources =
new ParamSource[] {ParamSource.FOREACH, ParamSource.SUBWORKFLOW, ParamSource.TEMPLATE};
Initiator.Type[] initiators =
new Initiator.Type[] {
Initiator.Type.FOREACH, Initiator.Type.SUBWORKFLOW, Initiator.Type.TEMPLATE
};
for (int i = 0; i < initiators.length; i++) {
RunRequest request =
RunRequest.builder()
.initiator(UpstreamInitiator.withType(initiators[i]))
.currentPolicy(RunPolicy.START_FRESH_NEW_RUN)
.runParams(runParams)
.build();
Map<String, Parameter> workflowParams =
paramsManager.generateMergedWorkflowParams(workflowInstance, request);
Assert.assertFalse(workflowParams.isEmpty());
Assert.assertEquals(
1001L, (long) workflowParams.get("TARGET_RUN_DATE").asLongParam().getValue());
Assert.assertEquals(expectedSources[i], workflowParams.get("TARGET_RUN_DATE").getSource());
}
} |
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 description of the difference, which is always about
* content, since people calling isSameInstanceAs() are explicitly not interested in
* content, only object identity.
*/
compareForEquality(expected).withoutDescription());
}
} | @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) {
getSemanticPropsSingleFromString(
result, forwarded, nonForwarded, readSet, inType, outType, false);
} | @Test
void testReadFieldsPojoInTuple() {
String[] readFields = {"f0; f2.int1; f2.string1"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, null, null, readFields, pojoInTupleType, pojo2Type);
FieldSet fs = sp.getReadFields(0);
assertThat(fs).containsExactly(0, 2, 5);
} |
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"));
continue;
}
if (!Files.isRegularFile(file)) {
logger.accept(
LogEvent.debug("MainClassFinder: " + file + " is not a regular file; skipping"));
continue;
}
if (!file.toString().endsWith(".class")) {
logger.accept(
LogEvent.debug("MainClassFinder: " + file + " is not a class file; skipping"));
continue;
}
MainClassVisitor mainClassVisitor = new MainClassVisitor();
try (InputStream classFileInputStream = Files.newInputStream(file)) {
ClassReader reader = new ClassReader(classFileInputStream);
reader.accept(mainClassVisitor, 0);
if (mainClassVisitor.visitedMainClass) {
mainClasses.add(reader.getClassName().replace('/', '.'));
}
} catch (IllegalArgumentException ex) {
throw new UnsupportedOperationException(
"Check the full stace trace, and if the root cause is from ASM ClassReader about "
+ "unsupported class file version, see "
+ "https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md"
+ "#i-am-seeing-unsupported-class-file-major-version-when-building",
ex);
} catch (ArrayIndexOutOfBoundsException ignored) {
// Not a valid class file (thrown by ClassReader if it reads an invalid format)
logger.accept(LogEvent.warn("Invalid class file found: " + file));
} catch (IOException ignored) {
// Could not read class file.
logger.accept(LogEvent.warn("Could not read file: " + file));
}
}
if (mainClasses.size() == 1) {
// Valid class found.
return Result.success(mainClasses.get(0));
}
if (mainClasses.isEmpty()) {
// No main class found anywhere.
return Result.mainClassNotFound();
}
// More than one main class found.
return Result.multipleMainClasses(mainClasses);
} | @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(), logEventConsumer);
Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType());
MatcherAssert.assertThat(
mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("HelloWorld"));
} |
@VisibleForTesting
static void verifyImageMetadata(ImageMetadataTemplate metadata, Path metadataCacheDirectory)
throws CacheCorruptedException {
List<ManifestAndConfigTemplate> manifestsAndConfigs = metadata.getManifestsAndConfigs();
if (manifestsAndConfigs.isEmpty()) {
throw new CacheCorruptedException(metadataCacheDirectory, "Manifest cache empty");
}
if (manifestsAndConfigs.stream().anyMatch(entry -> entry.getManifest() == null)) {
throw new CacheCorruptedException(metadataCacheDirectory, "Manifest(s) missing");
}
if (metadata.getManifestList() == null && manifestsAndConfigs.size() != 1) {
throw new CacheCorruptedException(metadataCacheDirectory, "Manifest list missing");
}
ManifestTemplate firstManifest = manifestsAndConfigs.get(0).getManifest();
if (firstManifest instanceof V21ManifestTemplate) {
if (metadata.getManifestList() != null
|| manifestsAndConfigs.stream().anyMatch(entry -> entry.getConfig() != null)) {
throw new CacheCorruptedException(metadataCacheDirectory, "Schema 1 manifests corrupted");
}
} else if (firstManifest instanceof BuildableManifestTemplate) {
if (manifestsAndConfigs.stream().anyMatch(entry -> entry.getConfig() == null)) {
throw new CacheCorruptedException(metadataCacheDirectory, "Schema 2 manifests corrupted");
}
if (metadata.getManifestList() != null
&& manifestsAndConfigs.stream().anyMatch(entry -> entry.getManifestDigest() == null)) {
throw new CacheCorruptedException(metadataCacheDirectory, "Schema 2 manifests corrupted");
}
} else {
throw new CacheCorruptedException(
metadataCacheDirectory, "Unknown manifest type: " + firstManifest);
}
} | @Test
public void testVerifyImageMetadata_validV22() throws CacheCorruptedException {
ManifestAndConfigTemplate manifestAndConfig =
new ManifestAndConfigTemplate(
new V22ManifestTemplate(), new ContainerConfigurationTemplate());
ImageMetadataTemplate metadata =
new ImageMetadataTemplate(null, Arrays.asList(manifestAndConfig));
CacheStorageReader.verifyImageMetadata(metadata, Paths.get("/cache/dir"));
// should pass without CacheCorruptedException
} |
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(nullValue()));
assertThat(pubsubRead.getTopicProvider().isAccessible(), is(true));
assertThat(pubsubRead.getTopicProvider().get().asPath(), equalTo(provider.get()));
assertThat(
pubsubRead.getTopicProvider().get().dataCatalogSegments(),
equalTo(ImmutableList.of("project", "topic")));
} |
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,
row
});
} catch (final Exception e) {
final Throwable cause = e instanceof InvocationTargetException
? e.getCause()
: e;
logger.error(RecordProcessingError.recordProcessingError(errorMsg.get(), cause, row));
return defaultValue;
}
} | @Test
public void shouldEvaluateExpressionWithUdfsSpecs() throws Exception {
// Given:
spec.addFunction(
FunctionName.of("foo"),
udf
);
spec.addParameter(
ColumnName.of("foo1"),
Integer.class,
0
);
compiledExpression = new CompiledExpression(
expressionEvaluator,
spec.build(),
EXPRESSION_TYPE,
expression
);
// When:
final Object result = compiledExpression
.evaluate(genericRow(123), DEFAULT_VAL, processingLogger, errorMsgSupplier);
// Then:
assertThat(result, equalTo(RETURN_VALUE));
final Map<String, Object> arguments = new HashMap<>();
arguments.put("var1", 123);
arguments.put("foo_0", udf);
verify(expressionEvaluator).evaluate(new Object[]{arguments, DEFAULT_VAL, processingLogger, genericRow(123)});
} |
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()");
assertFailureValue("expected to contain", "b");
assertFailureValue("but was", "[a]");
} |
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.format("server.%d", i + 1);
String value = String.format("%s:%d:%d:participant;127.0.0.1:%d", zkNodeAddress.apply(i), ZookeeperCluster.CLUSTERING_PORT, ZookeeperCluster.LEADER_ELECTION_PORT, ZookeeperCluster.CLIENT_PLAINTEXT_PORT);
servers.put(key, value);
}
return servers;
} | @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-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181");
expected.put("server.3", "my-cluster-zookeeper-2.my-cluster-zookeeper-nodes.myproject.svc:2888:3888:participant;127.0.0.1:12181");
assertThat(ZookeeperScaler.generateConfig(3, zkNodeAddress), is(expected));
} |
@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("Cache directory listing for %s", entry.getKey()));
}
cache.put(entry.getKey(), list);
}
}
} | @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(directory));
} |
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 {
for (int i=0; i< tmp.length; i++) {
Assert.assertEquals((String) tmp[i], (String)tmp2[i]);
}
} catch (Exception e) {
Assert.fail("Arrays were not equal" + e.getMessage());
}
} |
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.");
}
final Map<String, KafkaFutureImpl<Void>> updateFutures = new HashMap<>();
for (final Map.Entry<String, FeatureUpdate> entry : featureUpdates.entrySet()) {
final String feature = entry.getKey();
if (Utils.isBlank(feature)) {
throw new IllegalArgumentException("Provided feature can not be empty.");
}
updateFutures.put(entry.getKey(), new KafkaFutureImpl<>());
}
final long now = time.milliseconds();
final Call call = new Call("updateFeatures", calcDeadlineMs(now, options.timeoutMs()),
new ControllerNodeProvider(true)) {
@Override
UpdateFeaturesRequest.Builder createRequest(int timeoutMs) {
final UpdateFeaturesRequestData.FeatureUpdateKeyCollection featureUpdatesRequestData
= new UpdateFeaturesRequestData.FeatureUpdateKeyCollection();
for (Map.Entry<String, FeatureUpdate> entry : featureUpdates.entrySet()) {
final String feature = entry.getKey();
final FeatureUpdate update = entry.getValue();
final UpdateFeaturesRequestData.FeatureUpdateKey requestItem =
new UpdateFeaturesRequestData.FeatureUpdateKey();
requestItem.setFeature(feature);
requestItem.setMaxVersionLevel(update.maxVersionLevel());
requestItem.setUpgradeType(update.upgradeType().code());
featureUpdatesRequestData.add(requestItem);
}
return new UpdateFeaturesRequest.Builder(
new UpdateFeaturesRequestData()
.setTimeoutMs(timeoutMs)
.setValidateOnly(options.validateOnly())
.setFeatureUpdates(featureUpdatesRequestData));
}
@Override
void handleResponse(AbstractResponse abstractResponse) {
final UpdateFeaturesResponse response =
(UpdateFeaturesResponse) abstractResponse;
ApiError topLevelError = response.topLevelError();
switch (topLevelError.error()) {
case NONE:
for (final UpdatableFeatureResult result : response.data().results()) {
final KafkaFutureImpl<Void> future = updateFutures.get(result.feature());
if (future == null) {
log.warn("Server response mentioned unknown feature {}", result.feature());
} else {
final Errors error = Errors.forCode(result.errorCode());
if (error == Errors.NONE) {
future.complete(null);
} else {
future.completeExceptionally(error.exception(result.errorMessage()));
}
}
}
// The server should send back a response for every feature, but we do a sanity check anyway.
completeUnrealizedFutures(updateFutures.entrySet().stream(),
feature -> "The controller response did not contain a result for feature " + feature);
break;
case NOT_CONTROLLER:
handleNotControllerError(topLevelError.error());
break;
default:
for (final Map.Entry<String, KafkaFutureImpl<Void>> entry : updateFutures.entrySet()) {
entry.getValue().completeExceptionally(topLevelError.exception());
}
break;
}
}
@Override
void handleFailure(Throwable throwable) {
completeAllExceptionally(updateFutures.values(), throwable);
}
};
runnable.call(call, now);
return new UpdateFeaturesResult(new HashMap<>(updateFutures));
} | @Test
public void testUpdateFeaturesShouldFailRequestForEmptyUpdates() {
try (final AdminClientUnitTestEnv env = mockClientEnv()) {
assertThrows(
IllegalArgumentException.class,
() -> env.adminClient().updateFeatures(
new HashMap<>(), new UpdateFeaturesOptions()));
}
} |
@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 (JsonFlattenException e) {
LOG.warn("JSON contains type not supported by flatten method.", e);
} catch (JsonProcessingException e) {
LOG.warn("Could not parse JSON.", e);
}
} else {
if (jsonPath == null) {
return null;
}
final String json = new String(rawMessage.getPayload(), charset);
fields = read(json);
}
final Message message = messageFactory.createMessage(buildShortMessage(fields),
configuration.getString(CK_SOURCE),
rawMessage.getTimestamp());
message.addFields(fields);
return message;
} | @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-0.20.0-preview.1.tgz\",\"content_type\":\"application/octet-stream\",\"state\":\"uploaded\",\"size\":38179285,\"updated_at\":\"2013-09-30T20:05:46Z\"}".getBytes(StandardCharsets.UTF_8));
String path = "$.store.book[?(@.category == 'fiction')].author";
Message result = new JsonPathCodec(configOf(CK_PATH, path, CK_FLATTEN, true), objectMapperProvider.get(), messageFactory).decode(json);
assertThat(result.getField("some_double")).isEqualTo(0.5);
} |
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("shenyuHeader", ParameterDataFactory.builderData("header", "shenyu", exchange));
} |
@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<?>) type))
return new JSONArray();
else if (String.class.equals(type))
return null;
else
throw new DecodeException(response.status(),
format("%s is not a type supported by this decoder.", type), response.request());
if (response.body() == null)
return null;
try (Reader reader = response.body().asReader(response.charset())) {
Reader bodyReader = (reader.markSupported()) ? reader : new BufferedReader(reader);
bodyReader.mark(1);
if (bodyReader.read() == -1) {
return null; // Empty body
}
bodyReader.reset();
return decodeBody(response, type, bodyReader);
} catch (JSONException jsonException) {
if (jsonException.getCause() != null && jsonException.getCause() instanceof IOException) {
throw (IOException) jsonException.getCause();
}
throw new DecodeException(response.status(), jsonException.getMessage(), response.request(),
jsonException);
}
} | @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(
restService,
1000,
ImmutableList.of(
new AvroSchemaProvider(), new ProtobufSchemaProvider(), new JsonSchemaProvider()),
schemaRegistryClientConfigs,
httpHeaders
);
// If we have an sslContext, we use it to set the sslSocketFactory on the restService client.
// We need to do it in this order so that the override here is not reset by the constructor
// above.
if (sslContext != null) {
restService.setSslSocketFactory(sslContext.getSocketFactory());
}
return client;
} | @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(schemaRegistryClientConfigs);
// When:
SchemaRegistryClient client1 = new KsqlSchemaRegistryClientFactory(
config1, restServiceSupplier, SSL_CONTEXT, srClientFactory, Collections.emptyMap()).get();
SchemaRegistryClient client2 = new KsqlSchemaRegistryClientFactory(
config2, restServiceSupplier, SSL_CONTEXT, srClientFactory, Collections.emptyMap()).get();
// Then:
assertThat(client1, instanceOf(DefaultSchemaRegistryClient.class));
assertThat(client2, instanceOf(DefaultSchemaRegistryClient.class));
} |
public MaterializedConfiguration getConfiguration() {
MaterializedConfiguration conf = new SimpleMaterializedConfiguration();
FlumeConfiguration fconfig = getFlumeConfiguration();
AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName());
if (agentConf != null) {
Map<String, ChannelComponent> channelComponentMap = Maps.newHashMap();
Map<String, SourceRunner> sourceRunnerMap = Maps.newHashMap();
Map<String, SinkRunner> sinkRunnerMap = Maps.newHashMap();
try {
loadChannels(agentConf, channelComponentMap);
loadSources(agentConf, channelComponentMap, sourceRunnerMap);
loadSinks(agentConf, channelComponentMap, sinkRunnerMap);
Set<String> channelNames = new HashSet<String>(channelComponentMap.keySet());
for (String channelName : channelNames) {
ChannelComponent channelComponent = channelComponentMap.get(channelName);
if (channelComponent.components.isEmpty()) {
LOGGER.warn("Channel {} has no components connected"
+ " and has been removed.", channelName);
channelComponentMap.remove(channelName);
Map<String, Channel> nameChannelMap =
channelCache.get(channelComponent.channel.getClass());
if (nameChannelMap != null) {
nameChannelMap.remove(channelName);
}
} else {
LOGGER.info("Channel {} connected to {}",
channelName, channelComponent.components.toString());
conf.addChannel(channelName, channelComponent.channel);
}
}
for (Map.Entry<String, SourceRunner> entry : sourceRunnerMap.entrySet()) {
conf.addSourceRunner(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, SinkRunner> entry : sinkRunnerMap.entrySet()) {
conf.addSinkRunner(entry.getKey(), entry.getValue());
}
} catch (InstantiationException ex) {
LOGGER.error("Failed to instantiate component", ex);
} finally {
channelComponentMap.clear();
sourceRunnerMap.clear();
sinkRunnerMap.clear();
}
} else {
LOGGER.warn("No configuration found for this host:{}", getAgentName());
}
return conf;
} | @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(agentName, sourceType,
channelType, sinkType);
MemoryConfigurationProvider provider =
new MemoryConfigurationProvider(agentName, properties);
MaterializedConfiguration config = provider.getConfiguration();
assertEquals(config.getSourceRunners().size(), 1);
assertEquals(config.getChannels().size(), 1);
assertEquals(config.getSinkRunners().size(), 0);
} |
@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
.removeDatabaseFromCache(StringUtils.normalizeIdentifier(catName), StringUtils.normalizeIdentifier(dbName));
}
return succ;
} | @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.setConfForStandloneMode(conf);
CachedStore cachedStore = new CachedStore();
CachedStore.clearSharedCache();
cachedStore.setConfForTest(conf);
ObjectStore objectStore = (ObjectStore) cachedStore.getRawStore();
// Add a db via ObjectStore
String dbName = "testDropDatabase";
String dbOwner = "user1";
Database db = createDatabaseObject(dbName, dbOwner);
objectStore.createDatabase(db);
db = objectStore.getDatabase(DEFAULT_CATALOG_NAME, dbName);
// Prewarm CachedStore
CachedStore.setCachePrewarmedState(false);
CachedStore.prewarm(objectStore);
// Read database via CachedStore
Database dbRead = cachedStore.getDatabase(DEFAULT_CATALOG_NAME, dbName);
Assert.assertEquals(db, dbRead);
List<String> allDatabases = cachedStore.getAllDatabases(DEFAULT_CATALOG_NAME);
Assert.assertEquals(3, allDatabases.size());
// Drop db via CachedStore
cachedStore.dropDatabase(DEFAULT_CATALOG_NAME, dbName);
// Read via ObjectStore
allDatabases = objectStore.getAllDatabases(DEFAULT_CATALOG_NAME);
Assert.assertEquals(2, allDatabases.size());
// Create another db via CachedStore and drop via ObjectStore
String dbName1 = "testDropDatabase1";
Database localDb1 = createDatabaseObject(dbName1, dbOwner);
cachedStore.createDatabase(localDb1);
localDb1 = cachedStore.getDatabase(DEFAULT_CATALOG_NAME, dbName1);
// Read db via ObjectStore
dbRead = objectStore.getDatabase(DEFAULT_CATALOG_NAME, dbName1);
Assert.assertEquals(localDb1, dbRead);
allDatabases = cachedStore.getAllDatabases(DEFAULT_CATALOG_NAME);
Assert.assertEquals(3, allDatabases.size());
objectStore.dropDatabase(DEFAULT_CATALOG_NAME, dbName1);
updateCache(cachedStore);
updateCache(cachedStore);
allDatabases = cachedStore.getAllDatabases(DEFAULT_CATALOG_NAME);
Assert.assertEquals(2, allDatabases.size());
cachedStore.shutdown();
} |
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 = addNode(graph); // 0
GraphNode xTelecom = addNode(graph); // 1
GraphNode xRail = addNode(graph); // 2
GraphNode xAirTravel = addNode(graph); // 3
GraphNode xTransportation = addNode(graph);// 4
GraphNode xUtilities = addNode(graph); // 5
GraphNode xUSBanks = addNode(graph); // 6
GraphNode xUSStocks = addNode(graph); // 7
connectParentToChildren( xElectricity, xRail, xAirTravel, xUtilities, xTelecom );
connectParentToChildren( xTelecom, xUtilities, xUSBanks );
connectParentToChildren( xRail, xTransportation );
connectParentToChildren( xAirTravel, xTransportation );
connectParentToChildren( xUtilities, xUSStocks );
connectParentToChildren( xUSBanks, xUSStocks );
connectParentToChildren( xTransportation, xUSStocks );
OpenBitSet clique1 = bitSet("11110000"); // Utilities, Transportation, USBanks, UStocks
OpenBitSet clique2 = bitSet("01110001"); // Electricity, Transportation, Utilities, USBanks
OpenBitSet clique3 = bitSet("01100011"); // Electricity, Telecom, Utilities, USBanks
OpenBitSet clique4 = bitSet("00011101"); // Electricity, Rail, AirTravel, Transportation
OpenBitSet clique1And2 = bitSet("01110000"); // Utilities, Transportation, USBanks
OpenBitSet clique2And3 = bitSet("01100001"); // Electricity, Utilities, USBanks
OpenBitSet clique2And4 = bitSet("00010001"); // Electricity, Transportation
xElectricity.setContent(new BayesVariable<String>("Electricity", xElectricity.getId(),
new String[]{"Working", "Reduced", "NotWorking"}, new double[][]{{0.6, 0.3, 0.099}}));
xTelecom.setContent(new BayesVariable<String>("Telecom", xTelecom.getId(),
new String[]{"Working", "Reduced", "NotWorking"}, new double[][]{{0.544, 0.304, 0.151}}));
xRail.setContent(new BayesVariable<String>("Rail", xRail.getId(),
new String[]{"Working", "Reduced", "NotWorking"}, new double[][]{{0.579, 0.230, 0.190}}));
xAirTravel.setContent(new BayesVariable<String>("AirTravel", xAirTravel.getId(),
new String[]{"Working", "Reduced", "NotWorking"}, new double[][]{{0.449, 0.330, 0.219}}));
xTransportation.setContent(new BayesVariable<String>("Transportation", xTransportation.getId(),
new String[]{"Working", "Moderate", "Severe", "Failure"}, new double[][]{{0.658, 0.167, 0.097, 0.077}}));
xUtilities.setContent(new BayesVariable<String>("Utilities", xUtilities.getId(),
new String[]{"Working", "Moderate", "Severe", "Failure"}, new double[][]{{0.541, 0.272, 0.097, 0.088}}));
xUSBanks.setContent(new BayesVariable<String>("USBanks", xUSBanks.getId(),
new String[]{"Working", "Reduced", "NotWorking"}, new double[][]{{0.488, 0.370, 0.141}}));
xUSStocks.setContent(new BayesVariable<String>("USStocks", xUSStocks.getId(),
new String[]{"Up", "Down", "Crash"}, new double[][]{{0.433, 0.386, 0.179}}));
JunctionTreeBuilder jtBuilder = new JunctionTreeBuilder( graph );
JunctionTreeClique root = jtBuilder.build(false).getRoot();
// clique1
assertThat(root.getBitSet()).isEqualTo(clique1);
assertThat(root.getChildren().size()).isEqualTo(1);
// clique2
JunctionTreeSeparator sep = root.getChildren().get(0);
assertThat(sep.getBitSet()).isEqualTo(clique1And2);
JunctionTreeClique jtNode2 = sep.getChild();
assertThat(sep.getParent().getBitSet()).isEqualTo(clique1);
assertThat(jtNode2.getBitSet()).isEqualTo(clique2);
assertThat(jtNode2.getChildren().size()).isEqualTo(2);
// clique3
assertThat(jtNode2.getParentSeparator()).isSameAs(sep);
sep = jtNode2.getChildren().get(0);
assertThat(sep.getBitSet()).isEqualTo(clique2And3);
JunctionTreeClique jtNode3 = sep.getChild();
assertThat(sep.getParent().getBitSet()).isEqualTo(clique2);
assertThat(jtNode3.getBitSet()).isEqualTo(clique3);
assertThat(jtNode3.getChildren().size()).isEqualTo(0);
// clique4
sep = jtNode2.getChildren().get(1);
assertThat(sep.getBitSet()).isEqualTo(clique2And4);
JunctionTreeClique jtNode4 = sep.getChild();
assertThat(sep.getParent().getBitSet()).isEqualTo(clique2);
assertThat(jtNode4.getBitSet()).isEqualTo(clique4);
assertThat(jtNode4.getChildren().size()).isEqualTo(0);
} |
public OmemoFingerprint getFingerprint(OmemoDevice userDevice)
throws CorruptedOmemoKeyException, IOException {
T_IdKeyPair keyPair = loadOmemoIdentityKeyPair(userDevice);
if (keyPair == null) {
return null;
}
return keyUtil().getFingerprintOfIdentityKey(keyUtil().identityKeyFromPair(keyPair));
} | @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 = store.getFingerprint(alice);
assertNotNull("fingerprint must not be null", fingerprint);
assertEquals("Fingerprint must be of length 64", 64, fingerprint.length());
store.removeOmemoIdentityKeyPair(alice); //clean up
} |
@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.ofSeconds(2));
assertThat(cache.addAll(map)).isEqualTo(2);
assertThat(cache.size()).isEqualTo(3);
} |
@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++) {
AutoDisposingSubscriberImpl<? super T> subscriber =
new AutoDisposingSubscriberImpl<>(scope, subscribers[i]);
newSubscribers[i] = subscriber;
}
source.subscribe(newSubscribers);
} | @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.just(1, 2)
.parallel(DEFAULT_PARALLELISM)
.to(autoDisposable(scope))
.subscribe(subscribers);
subscriber.assertError(IllegalArgumentException.class);
} |
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, createGroupCoordinatorConfig()));
} |
public ExportMessagesCommand buildFromRequest(MessagesRequest request) {
ExportMessagesCommand.Builder builder = ExportMessagesCommand.builder()
.timeRange(toAbsolute(request.timeRange()))
.queryString(request.queryString())
.streams(request.streams())
.fieldsInOrder(request.fieldsInOrder())
.chunkSize(request.chunkSize());
request.timeZone().ifPresent(builder::timeZone);
request.limit().ifPresent(builder::limit);
return builder.build();
} | @Test
void buildsCommandFromRequest() {
MessagesRequest request = MessagesRequest.builder().build();
ExportMessagesCommand command = sut.buildFromRequest(request);
assertAll(
() -> assertThat(command.queryString()).isEqualTo(request.queryString()),
() -> assertThat(command.streams()).isEqualTo(request.streams()),
() -> assertThat(command.fieldsInOrder()).isEqualTo(request.fieldsInOrder()),
() -> assertThat(command.limit()).isEqualTo(request.limit()),
() -> assertThat(command.chunkSize()).isEqualTo(request.chunkSize())
);
} |
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().setUuid("paramUuid")));
RuleInformation customRule = ruleService.createCustomRule(NewCustomRule.createForCustomRule(RuleKey.of("rep", "key"), RuleKey.of("rep", "custom")));
assertThat(customRule.ruleDto().getUuid()).isEqualTo("uuid");
assertThat(customRule.params()).extracting(RuleParamDto::getUuid).containsExactly("paramUuid");
customRule = ruleService.createCustomRule(NewCustomRule.createForCustomRule(RuleKey.of("rep", "key"), RuleKey.of("rep", "custom")), mock(DbSession.class));
assertThat(customRule.ruleDto().getUuid()).isEqualTo("uuid");
assertThat(customRule.params()).extracting(RuleParamDto::getUuid).containsExactly("paramUuid");
} |
@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.doubleValue());
} | @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 tokenizer = new StringTokenizer(cookieStr, ";");
String nameValuePair;
HttpCookie cookieToBeAdd = null;
while (tokenizer.hasMoreTokens())
{
nameValuePair = tokenizer.nextToken();
int index = nameValuePair.indexOf('=');
if (index != -1)
{
String name = nameValuePair.substring(0, index).trim();
String value = stripOffSurrounding(nameValuePair.substring(index + 1).trim());
if (name.charAt(0) != '$')
{
if (cookieToBeAdd != null)
{
cookies.add(cookieToBeAdd);
}
cookieToBeAdd = new HttpCookie(name, value);
}
else if (cookieToBeAdd != null)
{
if (name.equals("$Path"))
{
cookieToBeAdd.setPath(value);
}
else if (name.equals("$Domain"))
{
cookieToBeAdd.setDomain(value);
}
else if (name.equals("$Port"))
{
cookieToBeAdd.setPortlist(value);
}
}
}
else
{
throw new IllegalArgumentException("Invalid cookie name-value pair");
}
}
if (cookieToBeAdd != null)
{
cookies.add(cookieToBeAdd);
}
}
return cookies;
} | @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()
.split(authString));
for (String comp : authComps) {
String parts[] = comp.split(":", 2);
if (parts.length != 2) {
throw new BadAuthFormatException(
"Auth '" + comp + "' not of expected form scheme:auth");
}
ret.add(new ZKAuthInfo(parts[0],
parts[1].getBytes(StandardCharsets.UTF_8)));
}
return ret;
} | @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 returned from getMatchingSpec the group will be reconfigured on the next run of load().
configuredGroups.computeIfAbsent(entry.getKey(), v -> new LinkedList<>()).add(group.getId());
}
synchronized (getRootGroup(group.getId())) {
configureGroup(group, entry.getValue());
}
} | @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "No matching configuration found for: missing")
public void testMissing()
{
H2DaoProvider daoProvider = setup("test_missing");
H2ResourceGroupsDao dao = daoProvider.get();
dao.createResourceGroupsGlobalPropertiesTable();
dao.createResourceGroupsTable();
dao.createSelectorsTable();
dao.insertResourceGroup(1, "global", "1MB", 1000, 100, 100, "weighted", null, true, "1h", "1d", "1h", "1MB", "1h", 0, null, ENVIRONMENT);
dao.insertResourceGroup(2, "sub", "2MB", 4, 3, 3, null, 5, null, null, null, null, null, null, 0, 1L, ENVIRONMENT);
dao.insertResourceGroupsGlobalProperties("cpu_quota_period", "1h");
dao.insertSelector(2, 1, null, null, null, null, null, null);
DbManagerSpecProvider dbManagerSpecProvider = new DbManagerSpecProvider(daoProvider.get(), ENVIRONMENT, new ReloadingResourceGroupConfig());
ReloadingResourceGroupConfigurationManager manager = new ReloadingResourceGroupConfigurationManager((poolId, listener) -> {}, new ReloadingResourceGroupConfig(), dbManagerSpecProvider);
InternalResourceGroup missing = new InternalResourceGroup.RootInternalResourceGroup("missing", (group, export) -> {}, directExecutor(), ignored -> Optional.empty(), rg -> false, new InMemoryNodeManager());
manager.configure(missing, new SelectionContext<>(missing.getId(), new VariableMap(ImmutableMap.of("USER", "user"))));
} |
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()).isEqualTo(13);
assertThat(array.get(2).getAsString()).isEqualTo("stringValue");
} |
@Override
public JibContainerBuilder createJibContainerBuilder(
JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode) {
try {
FileCollection projectDependencies =
project.files(
project.getConfigurations().getByName(configurationName).getResolvedConfiguration()
.getResolvedArtifacts().stream()
.filter(
artifact ->
artifact.getId().getComponentIdentifier()
instanceof ProjectComponentIdentifier)
.map(ResolvedArtifact::getFile)
.collect(Collectors.toList()));
if (isWarProject()) {
String warFilePath = getWarFilePath();
log(LogEvent.info("WAR project identified, creating WAR image from: " + warFilePath));
Path explodedWarPath = tempDirectoryProvider.newDirectory();
ZipUtil.unzip(Paths.get(warFilePath), explodedWarPath);
return JavaContainerBuilderHelper.fromExplodedWar(
javaContainerBuilder,
explodedWarPath,
projectDependencies.getFiles().stream().map(File::getName).collect(Collectors.toSet()));
}
SourceSet mainSourceSet = getMainSourceSet();
FileCollection classesOutputDirectories =
mainSourceSet.getOutput().getClassesDirs().filter(File::exists);
Path resourcesOutputDirectory = mainSourceSet.getOutput().getResourcesDir().toPath();
FileCollection allFiles =
project.getConfigurations().getByName(configurationName).filter(File::exists);
FileCollection nonProjectDependencies =
allFiles
.minus(classesOutputDirectories)
.minus(projectDependencies)
.filter(file -> !file.toPath().equals(resourcesOutputDirectory));
FileCollection snapshotDependencies =
nonProjectDependencies.filter(file -> file.getName().contains("SNAPSHOT"));
FileCollection dependencies = nonProjectDependencies.minus(snapshotDependencies);
// Adds dependency files
javaContainerBuilder
.addDependencies(
dependencies.getFiles().stream().map(File::toPath).collect(Collectors.toList()))
.addSnapshotDependencies(
snapshotDependencies.getFiles().stream()
.map(File::toPath)
.collect(Collectors.toList()))
.addProjectDependencies(
projectDependencies.getFiles().stream()
.map(File::toPath)
.collect(Collectors.toList()));
switch (containerizingMode) {
case EXPLODED:
// Adds resource files
if (Files.exists(resourcesOutputDirectory)) {
javaContainerBuilder.addResources(resourcesOutputDirectory);
}
// Adds class files
for (File classesOutputDirectory : classesOutputDirectories) {
javaContainerBuilder.addClasses(classesOutputDirectory.toPath());
}
if (classesOutputDirectories.isEmpty()) {
log(LogEvent.warn("No classes files were found - did you compile your project?"));
}
break;
case PACKAGED:
// Add a JAR
Jar jarTask = (Jar) project.getTasks().findByName("jar");
Path jarPath = jarTask.getArchiveFile().get().getAsFile().toPath();
log(LogEvent.debug("Using JAR: " + jarPath));
javaContainerBuilder.addToClasspath(jarPath);
break;
default:
throw new IllegalStateException("unknown containerizing mode: " + containerizingMode);
}
return javaContainerBuilder.toContainerBuilder();
} catch (IOException ex) {
throw new GradleException("Obtaining project build output files failed", ex);
}
} | @Test
public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist()
throws IOException, InvalidImageReferenceException {
temporaryFolder.newFolder("WEB-INF", "classes");
setUpWarProject(temporaryFolder.getRoot().toPath());
assertThat(
gradleProjectProperties.createJibContainerBuilder(
JavaContainerBuilder.from("ignored"), ContainerizingMode.EXPLODED))
.isNotNull();
} |
@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.getRequestHandlerById("com.yahoo.search.handler.SearchHandler");
assertNotNull(searchHandler);
}
} |
@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.containsAny(ImmutableSet.of(res2)), is(false));
} |
@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].getView();
if (config == null) {
throw new RuntimeException(format("Plugin[%s] returned null task configuration", descriptor.id()));
}
if (view == null) {
throw new RuntimeException(format("Plugin[%s] returned null task view", descriptor.id()));
}
String displayName = view.displayValue();
PluggableInstanceSettings taskSettings = new PluggableInstanceSettings(configurations(config), new PluginView(view.template()));
return new PluggableTaskPluginInfo(descriptor, displayName, taskSettings);
} | @Test
public void shouldBuildPluginInfo() throws Exception {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
PluggableTaskPluginInfo pluginInfo = new PluggableTaskPluginInfoBuilder(extension) .pluginInfoFor(descriptor);
List<PluginConfiguration> pluginConfigurations = List.of(
new PluginConfiguration("username", new Metadata(true, false)),
new PluginConfiguration("password", new Metadata(true, true))
);
PluginView pluginView = new PluginView("some html");
assertThat(pluginInfo.getDescriptor(), is(descriptor));
assertThat(pluginInfo.getExtensionName(), is("task"));
assertThat(pluginInfo.getDisplayName(), is("my task plugin"));
assertThat(pluginInfo.getTaskSettings(), is(new PluggableInstanceSettings(pluginConfigurations, pluginView)));
assertNull(pluginInfo.getPluginSettings());
} |
@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, indexConf)
.build();
Assert.assertEquals(fieldIndexConfigs.toString(), "{\"index1\":"
+ JsonUtils.objectToString(indexConf) + "}");
} |
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"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse NOT_NAN predicate: has invalid value field");
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"is-nan\",\n"
+ " \"term\" : \"x\",\n"
+ " \"values\" : [ 34.0, 35.0 ]\n"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse IS_NAN predicate: has invalid values field");
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"lt\",\n"
+ " \"term\" : \"x\",\n"
+ " \"values\" : [ 1 ]\n"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse LT predicate: missing value");
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"lt\",\n"
+ " \"term\" : \"x\",\n"
+ " \"value\" : 34,\n"
+ " \"values\" : [ 1 ]\n"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse LT predicate: has invalid values field");
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"not-in\",\n"
+ " \"term\" : \"x\",\n"
+ " \"value\" : [ 1, 2 ]\n"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse NOT_IN predicate: missing values");
assertThatThrownBy(
() ->
ExpressionParser.fromJson(
"{\n"
+ " \"type\" : \"in\",\n"
+ " \"term\" : \"x\",\n"
+ " \"value\" : \"min\",\n"
+ " \"values\" : [ 1, 2 ]\n"
+ "}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse IN predicate: has invalid value field");
} |
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);
}
byte[] requestSignature = sign(mac, key, requestBody);
request.header(InternalRequestSignature.SIGNATURE_HEADER, Base64.getEncoder().encodeToString(requestSignature))
.header(InternalRequestSignature.SIGNATURE_ALGORITHM_HEADER, signatureAlgorithm);
} | @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"));
assertThrows(ConnectException.class, () -> InternalRequestSignature.addToRequest(crypto, KEY, REQUEST_BODY, "doesn'texist", request));
} |
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 TestService(root, 1);
host.allocatePorts(service2, HostPorts.BASE_PORT);
host.allocatePorts(service1, HostPorts.BASE_PORT + 1);
});
} |
@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 = PiAction.builder().withId(actionId).withParameter(actionParam).build();
final PiInstruction actionInstruction = Instructions.piTableAction(action);
final ObjectNode actionInstructionJson =
instructionCodec.encode(actionInstruction, context);
assertThat(actionInstructionJson, matchesInstruction(actionInstruction));
PiTableAction actionGroupId = PiActionProfileGroupId.of(10);
final PiInstruction actionGroupIdInstruction = Instructions.piTableAction(actionGroupId);
final ObjectNode actionGroupIdInstructionJson =
instructionCodec.encode(actionGroupIdInstruction, context);
assertThat(actionGroupIdInstructionJson, matchesInstruction(actionGroupIdInstruction));
PiTableAction actionProfileMemberId = PiActionProfileMemberId.of(10);
final PiInstruction actionProfileMemberIdInstruction = Instructions.piTableAction(actionProfileMemberId);
final ObjectNode actionProfileMemberIdInstructionJson =
instructionCodec.encode(actionProfileMemberIdInstruction, context);
assertThat(actionProfileMemberIdInstructionJson, matchesInstruction(actionProfileMemberIdInstruction));
} |
@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.getId());
// 调用
List<MenuDO> list = menuService.getMenuList(ids);
// 断言
assertEquals(1, list.size());
assertPojoEquals(menu100, list.get(0));
} |
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) {
return array;
}
}
buffer.mark();
byte[] avroEncodedData = new byte[remaining];
buffer.get(avroEncodedData);
buffer.reset();
return avroEncodedData;
} | @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());
assertEquals(2, wrapped.remaining());
byte[] result = ByteBufferSchemaWrapper.getBytes(wrapped);
assertNotSame(result, originalArray);
assertArrayEquals(result, new byte[] {2,3});
} |
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 : modelMethod.getKieBaseNames()) {
sb.append(" case \"" + kBase + "\": ");
List<String> models = modelsByKBase.get(kBase);
String collected = null;
if (models != null) {
collected = models.stream()
.map(element -> "new " + element + "()")
.collect(Collectors.joining(","));
}
sb.append(collected != null && !collected.isEmpty() ?
"return java.util.Arrays.asList( " + collected + " );\n" :
"return getModels();\n");
}
sb.append(" }\n");
}
sb.append(
" throw new IllegalArgumentException(\"Unknown KieBase: \" + kieBaseName);\n" +
" }\n" +
"\n" );
} | @Test
public void addGetModelForKieBaseMethodMatchingModelsByKBaseValuesTest() {
KieBaseModel kieBaseModel = getKieBaseModel("ModelTest");
Map<String, KieBaseModel> kBaseModels = new HashMap<>();
kBaseModels.put("default-kie", kieBaseModel);
List<String> modelByKBaseValues = Collections.singletonList("ModelTest");
Map<String, List<String>> modelsByKBase = new HashMap<>();
modelsByKBase.put("default-kie", modelByKBaseValues);
ModelSourceClass modelSourceClass = new ModelSourceClass(RELEASE_ID, kBaseModels, modelsByKBase);
StringBuilder sb = new StringBuilder();
modelSourceClass.addGetModelForKieBaseMethod(sb);
String retrieved = sb.toString();
String expected = "switch (kieBaseName) {";
assertThat(retrieved.contains(expected)).isTrue();
expected = "case \"default-kie\": return java.util.Arrays.asList( new ModelTest() );";
assertThat(retrieved.contains(expected)).isTrue();
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
Long typeDefineLength = typeDefine.getLength();
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.columnLength(typeDefineLength)
.scale(typeDefine.getScale())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefine.getDefaultValue())
.comment(typeDefine.getComment());
String irisDataType = typeDefine.getDataType().toUpperCase();
long charOrBinaryLength =
Objects.nonNull(typeDefineLength) && typeDefineLength > 0 ? typeDefineLength : 1;
switch (irisDataType) {
case IRIS_NULL:
builder.dataType(BasicType.VOID_TYPE);
break;
case IRIS_BIT:
builder.dataType(BasicType.BOOLEAN_TYPE);
break;
case IRIS_NUMERIC:
case IRIS_MONEY:
case IRIS_SMALLMONEY:
case IRIS_NUMBER:
case IRIS_DEC:
case IRIS_DECIMAL:
DecimalType decimalType;
if (typeDefine.getPrecision() != null && typeDefine.getPrecision() > 0) {
decimalType =
new DecimalType(
typeDefine.getPrecision().intValue(), typeDefine.getScale());
} else {
decimalType = new DecimalType(DEFAULT_PRECISION, DEFAULT_SCALE);
}
builder.dataType(decimalType);
builder.columnLength(Long.valueOf(decimalType.getPrecision()));
builder.scale(decimalType.getScale());
break;
case IRIS_INT:
case IRIS_INTEGER:
case IRIS_MEDIUMINT:
builder.dataType(BasicType.INT_TYPE);
break;
case IRIS_ROWVERSION:
case IRIS_BIGINT:
case IRIS_SERIAL:
builder.dataType(BasicType.LONG_TYPE);
break;
case IRIS_TINYINT:
builder.dataType(BasicType.BYTE_TYPE);
break;
case IRIS_SMALLINT:
builder.dataType(BasicType.SHORT_TYPE);
break;
case IRIS_FLOAT:
builder.dataType(BasicType.FLOAT_TYPE);
break;
case IRIS_DOUBLE:
case IRIS_REAL:
case IRIS_DOUBLE_PRECISION:
builder.dataType(BasicType.DOUBLE_TYPE);
break;
case IRIS_CHAR:
case IRIS_CHAR_VARYING:
case IRIS_CHARACTER_VARYING:
case IRIS_NATIONAL_CHAR:
case IRIS_NATIONAL_CHAR_VARYING:
case IRIS_NATIONAL_CHARACTER:
case IRIS_NATIONAL_CHARACTER_VARYING:
case IRIS_NATIONAL_VARCHAR:
case IRIS_NCHAR:
case IRIS_SYSNAME:
case IRIS_VARCHAR2:
case IRIS_VARCHAR:
case IRIS_NVARCHAR:
case IRIS_UNIQUEIDENTIFIER:
case IRIS_GUID:
case IRIS_CHARACTER:
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(charOrBinaryLength);
break;
case IRIS_NTEXT:
case IRIS_CLOB:
case IRIS_LONG_VARCHAR:
case IRIS_LONG:
case IRIS_LONGTEXT:
case IRIS_MEDIUMTEXT:
case IRIS_TEXT:
case IRIS_LONGVARCHAR:
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(Long.valueOf(Integer.MAX_VALUE));
break;
case IRIS_DATE:
builder.dataType(LocalTimeType.LOCAL_DATE_TYPE);
break;
case IRIS_TIME:
builder.dataType(LocalTimeType.LOCAL_TIME_TYPE);
break;
case IRIS_DATETIME:
case IRIS_DATETIME2:
case IRIS_SMALLDATETIME:
case IRIS_TIMESTAMP:
case IRIS_TIMESTAMP2:
case IRIS_POSIXTIME:
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
break;
case IRIS_BINARY:
case IRIS_BINARY_VARYING:
case IRIS_RAW:
case IRIS_VARBINARY:
builder.dataType(PrimitiveByteArrayType.INSTANCE);
builder.columnLength(charOrBinaryLength);
break;
case IRIS_LONGVARBINARY:
case IRIS_BLOB:
case IRIS_IMAGE:
case IRIS_LONG_BINARY:
case IRIS_LONG_RAW:
builder.dataType(PrimitiveByteArrayType.INSTANCE);
builder.columnLength(Long.valueOf(Integer.MAX_VALUE));
break;
default:
throw CommonError.convertToSeaTunnelTypeError(
DatabaseIdentifier.IRIS, irisDataType, typeDefine.getName());
}
return builder.build();
} | @Test
public void testConvertDecimal() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("numeric(38,2)")
.dataType("numeric")
.precision(38L)
.scale(2)
.build();
Column column = IrisTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.getName());
Assertions.assertEquals(new DecimalType(38, 2), column.getDataType());
Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType());
typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("numeric")
.dataType("numeric")
.build();
column = IrisTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.getName());
Assertions.assertEquals(new DecimalType(15, 0), column.getDataType());
Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType());
} |
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.remove(operation.getCallId()) == null) {
throw new IllegalStateException("Missing operation during de-registration of operation=" + operation);
}
} | @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();
return findResourcesForUri(root, DEFAULT_PACKAGE_NAME, packageFilter, createResource);
} | @Test
void scanForResourcesInClasspathRootWithPackage() {
URI classpathRoot = new File("src/test/resources").toURI();
List<URI> resources = resourceScanner.scanForResourcesInClasspathRoot(classpathRoot, aPackage -> true);
assertThat(resources, containsInAnyOrder(
URI.create("classpath:io/cucumber/core/resource/test/resource.txt"),
URI.create("classpath:io/cucumber/core/resource/test/other-resource.txt"),
URI.create("classpath:io/cucumber/core/resource/test/spaces%20in%20name%20resource.txt")));
} |
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::appendCodePoint, StringBuilder::append)
.toString();
} | @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 StandardConnectionProperties("", DEFAULT_PORT, "", null);
} | @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.format("Request '%h' with method '%s' and uri '%s' matched rule '%s'", request, method, uri, rule.name));
return responseFor(request, rule.name, rule.response);
}
}
return responseFor(request, "default", defaultResponse);
} | @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)
.blockResponseCode(403)
.blockResponseMessage("my custom message"))
.rule(new Rule.Builder()
.name("rule")
.pathExpressions("/path-to-resource")
.methods(Rule.Methods.Enum.GET)
.action(Rule.Action.Enum.ALLOW))
.build();
Metric metric = mock(Metric.class);
RuleBasedRequestFilter filter = new RuleBasedRequestFilter(metric, config);
MockResponseHandler responseHandler = new MockResponseHandler();
filter.filter(request("POST", "http://myserver:80/"), responseHandler);
assertBlocked(responseHandler, metric, 403, "my custom message");
} |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
terminal.writeLine(String.format("ERROR: %s", e.getMessage()));
return;
}
if (commandParseResult.isEmpty()) {
printHelp();
return;
}
final CommandLine commandLine = commandParseResult.get();
switch (commandLine.getCommand()) {
case CREATE: {
if (commandLine.hasOption(CommandOptions.HELP)){
terminal.writeLine("Creates a new keystore. For example: 'bin/logstash-keystore create'");
return;
}
if (secretStoreFactory.exists(config.clone())) {
terminal.write("An Logstash keystore already exists. Overwrite ? [y/N] ");
if (isYes(terminal.readLine())) {
create(config);
}
} else {
create(config);
}
break;
}
case LIST: {
if (commandLine.hasOption(CommandOptions.HELP)){
terminal.writeLine("List all secret identifiers from the keystore. For example: " +
"`bin/logstash-keystore list`. Note - only the identifiers will be listed, not the secrets.");
return;
}
Collection<SecretIdentifier> ids = secretStoreFactory.load(config).list();
List<String> keys = ids.stream().filter(id -> !id.equals(LOGSTASH_MARKER)).map(id -> id.getKey()).collect(Collectors.toList());
Collections.sort(keys);
keys.forEach(terminal::writeLine);
break;
}
case ADD: {
if (commandLine.hasOption(CommandOptions.HELP)){
terminal.writeLine("Add secrets to the keystore. For example: " +
"`bin/logstash-keystore add my-secret`, at the prompt enter your secret. You will use the identifier ${my-secret} in your Logstash configuration.");
return;
}
if (commandLine.getArguments().isEmpty()) {
terminal.writeLine("ERROR: You must supply an identifier to add. (e.g. bin/logstash-keystore add my-secret)");
return;
}
if (secretStoreFactory.exists(config.clone())) {
final SecretStore secretStore = secretStoreFactory.load(config);
for (String argument : commandLine.getArguments()) {
final SecretIdentifier id = new SecretIdentifier(argument);
final byte[] existingValue = secretStore.retrieveSecret(id);
if (existingValue != null) {
SecretStoreUtil.clearBytes(existingValue);
terminal.write(String.format("%s already exists. Overwrite ? [y/N] ", argument));
if (!isYes(terminal.readLine())) {
continue;
}
}
final String enterValueMessage = String.format("Enter value for %s: ", argument);
char[] secret = null;
while(secret == null) {
terminal.write(enterValueMessage);
final char[] readSecret = terminal.readSecret();
if (readSecret == null || readSecret.length == 0) {
terminal.writeLine("ERROR: Value cannot be empty");
continue;
}
if (!ASCII_ENCODER.canEncode(CharBuffer.wrap(readSecret))) {
terminal.writeLine("ERROR: Value must contain only ASCII characters");
continue;
}
secret = readSecret;
}
add(secretStore, id, SecretStoreUtil.asciiCharToBytes(secret));
}
} else {
terminal.writeLine("ERROR: Logstash keystore not found. Use 'create' command to create one.");
}
break;
}
case REMOVE: {
if (commandLine.hasOption(CommandOptions.HELP)){
terminal.writeLine("Remove secrets from the keystore. For example: " +
"`bin/logstash-keystore remove my-secret`");
return;
}
if (commandLine.getArguments().isEmpty()) {
terminal.writeLine("ERROR: You must supply a value to remove. (e.g. bin/logstash-keystore remove my-secret)");
return;
}
final SecretStore secretStore = secretStoreFactory.load(config);
for (String argument : commandLine.getArguments()) {
SecretIdentifier id = new SecretIdentifier(argument);
if (secretStore.containsSecret(id)) {
secretStore.purgeSecret(id);
terminal.writeLine(String.format("Removed '%s' from the Logstash keystore.", id.getKey()));
} else {
terminal.writeLine(String.format("ERROR: '%s' does not exist in the Logstash keystore.", argument));
}
}
break;
}
}
} | @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("wrong master:", mastershipMgr1.getMasterFor(VDID2));
assertEquals("wrong role:", NONE, mastershipMgr1.getLocalRole(VDID1));
//not master, nothing should happen
mastershipMgr1.setRole(NID_LOCAL, VDID2, NONE);
mastershipMgr1.relinquishMastership(VDID2);
assertNull("wrong role:", mastershipMgr1.getMasterFor(VDID2));
//provide NID_OTHER as backup and relinquish
mastershipMgr1.setRole(NID_LOCAL, VDID1, MASTER);
assertEquals("wrong master:", NID_LOCAL, mastershipMgr1.getMasterFor(VDID1));
mastershipMgr1.setRole(NID_OTHER, VDID1, STANDBY);
mastershipMgr1.relinquishMastership(VDID1);
assertEquals("wrong master:", NID_OTHER, mastershipMgr1.getMasterFor(VDID1));
} |
@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();
Optional<? extends Padding> paddingOptional = Optional.empty();
if (str.contains("/")) {
int slashIndex = str.indexOf("/");
algorithmStr = str.substring(0, slashIndex);
String rest = str.substring(slashIndex + 1);
if (rest.contains("/")) {
slashIndex = rest.indexOf("/");
// mode
final String modeStr = rest.substring(0, slashIndex);
final JcaModeMapper jcaModeMapper = new JcaModeMapper();
modeOptional = jcaModeMapper.parse(modeStr, detectionLocation);
// padding
String paddingStr = rest.substring(slashIndex + 1);
final JcaPaddingMapper jcaPaddingMapper = new JcaPaddingMapper();
paddingOptional = jcaPaddingMapper.parse(paddingStr, detectionLocation);
}
} else {
algorithmStr = str;
}
// check if it is pbe
JcaPasswordBasedEncryptionMapper pbeMapper = new JcaPasswordBasedEncryptionMapper();
Optional<PasswordBasedEncryption> pbeOptional =
pbeMapper.parse(algorithmStr, detectionLocation);
if (pbeOptional.isPresent()) {
// pbe
return pbeOptional;
}
Optional<? extends Algorithm> possibleCipher = map(algorithmStr, detectionLocation);
if (possibleCipher.isEmpty()) {
return Optional.empty();
}
final Algorithm algorithm = possibleCipher.get();
modeOptional.ifPresent(algorithm::put);
paddingOptional.ifPresent(algorithm::put);
return Optional.of(algorithm);
} | @Test
void rsa() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaCipherMapper jcaAlgorithmMapper = new JcaCipherMapper();
Optional<? extends Algorithm> algorithm =
jcaAlgorithmMapper.parse("RSA", testDetectionLocation);
assertThat(algorithm).isPresent();
assertThat(algorithm.get()).isInstanceOf(RSA.class);
} |
@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())));
}
if (!warnings.isEmpty()) {
ceTaskMessages.addAll(warnings);
}
} | @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();
ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2);
reportReader.setAnalysisWarnings(warnings);
underTest.execute(new TestComputationStepContext());
verify(ceTaskMessages, times(1)).addAll(argumentCaptor.capture());
assertThat(argumentCaptor.getValue())
.extracting(CeTaskMessages.Message::getText, CeTaskMessages.Message::getType)
.containsExactly(tuple("warning 1", MessageType.GENERIC), tuple("warning 2", MessageType.GENERIC));
} |
@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);
if (!hasError) {
message.setBody(response.getAddress());
}
} | @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");
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_NEW_GROUP);
template.send(exchange);
String body = exchange.getIn().getBody(String.class);
assertEquals("test", body);
} |
@Override
public void persist(MessageQueue mq) {
if (mq == null) {
return;
}
ControllableOffset offset = this.offsetTable.get(mq);
if (offset != null) {
OffsetSerializeWrapper offsetSerializeWrapper = null;
try {
offsetSerializeWrapper = readLocalOffset();
} catch (MQClientException e) {
log.error("readLocalOffset exception", e);
return;
}
if (offsetSerializeWrapper == null) {
offsetSerializeWrapper = new OffsetSerializeWrapper();
}
offsetSerializeWrapper.getOffsetTable().put(mq, new AtomicLong(offset.getOffset()));
String jsonString = offsetSerializeWrapper.toJson(true);
if (jsonString != null) {
try {
MixAll.string2File(jsonString, this.storePath);
} catch (IOException e) {
log.error("persist consumer offset exception, " + this.storePath, e);
}
}
}
} | @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);
assertThat(offsetStore.readOffset(messageQueue0, ReadOffsetType.READ_FROM_STORE)).isEqualTo(1024);
MessageQueue messageQueue1 = new MessageQueue(topic, brokerName, 1);
assertThat(offsetStore.readOffset(messageQueue1, ReadOffsetType.READ_FROM_STORE)).isEqualTo(-1);
} |
@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.getLocation(bucket.isRoot() ? StringUtils.EMPTY : bucket.getName());
} | @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 getProperty(final String key) {
if("s3.bucket.virtualhost.disable".equals(key)) {
return String.valueOf(true);
}
return super.getProperty(key);
}
};
final S3Session session = new S3Session(host);
assertNotNull(session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback()));
session.login(new DisabledLoginCallback(), new DisabledCancelCallback());
final RegionEndpointCache cache = session.getClient().getRegionEndpointCache();
assertEquals(new S3LocationFeature.S3Region("eu-central-1"), new S3LocationFeature(session, cache).getLocation(
new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory))
));
assertEquals("eu-central-1", cache.getRegionForBucketName("test-eu-central-1-cyberduck"));
session.close();
} |
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()).append(" ");
sb.append(getLangId()).append(" ");
sb.append(Arrays.toString(getDir_uuid())).append(" ");
sb.append(Arrays.toString(getStream_uuid())).append(" ");
sb.append(getUnknownOffset()).append(" ");
sb.append(getUnknownLen()).append(" ");
sb.append(getDirOffset()).append(" ");
sb.append(getDirLen()).append(" ");
sb.append(getDataOffset()).append(" ");
return sb.toString();
} | @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());
return ceWorker;
} | @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();
assertEquals(String.class, returnType);
} |
@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.selectById(parentId);
// 父菜单不存在
if (menu == null) {
throw exception(MENU_PARENT_NOT_EXISTS);
}
// 父菜单必须是目录或者菜单类型
if (!MenuTypeEnum.DIR.getType().equals(menu.getType())
&& !MenuTypeEnum.MENU.getType().equals(menu.getType())) {
throw exception(MENU_PARENT_NOT_DIR_OR_MENU);
}
} | @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").isDirectory());
} |
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(connectionFactory)
.withValueMapper(new TextMessageMapper())
.withRetryConfiguration(retryConfiguration)
.withQueue(QUEUE)
.withUsername(USERNAME)
.withPassword(PASSWORD));
pipeline.run();
assertQueueContainsMessages(100);
} |
@Override
public void filter(final ContainerRequestContext requestContext,
ContainerResponseContext response) {
final Object entity = response.getEntity();
if (isEmptyOptional(entity)) {
response.setStatus(Response.Status.NO_CONTENT.getStatusCode());
response.setEntity(null);
}
} | @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(FileFinder.regexEscapePath("(\\d+)"));
} else if (p instanceof DateTokenConverter) {
DateTokenConverter<Object> dtc = (DateTokenConverter<Object>) p;
if (dtc.isPrimary()) {
buf.append(p.convert(date));
} else {
buf.append(FileFinder.regexEscapePath(dtc.toRegex()));
}
}
p = p.getNext();
}
return buf.toString();
} | @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-" + FileFinder.regexEscapePath("(\\d+)") + ".txt", regex);
}
{
FileNamePattern fnp = new FileNamePattern("\\toto\\foo-%d{yyyy\\MM\\dd}-%i.txt",
context);
String regex = fnp.toRegexForFixedDate(cal.getTime());
assertEquals("/toto/foo-2003/05/20-" + FileFinder.regexEscapePath("(\\d+)") + ".txt", regex);
}
} |
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.valueOf("0.0.0.0");
assertThat(ipAddress.toOctets(), is(value));
value = new byte[] {(byte) 0xff, (byte) 0xff,
(byte) 0xff, (byte) 0xff};
ipAddress = Ip4Address.valueOf("255.255.255.255");
assertThat(ipAddress.toOctets(), is(value));
} |
public static Future<Void> unregisterNodes(
Reconciliation reconciliation,
Vertx vertx,
AdminClientProvider adminClientProvider,
PemTrustSet pemTrustSet,
PemAuthIdentity pemAuthIdentity,
List<Integer> nodeIdsToUnregister
) {
try {
String bootstrapHostname = KafkaResources.bootstrapServiceName(reconciliation.name()) + "." + reconciliation.namespace() + ".svc:" + KafkaCluster.REPLICATION_PORT;
Admin adminClient = adminClientProvider.createAdminClient(bootstrapHostname, pemTrustSet, pemAuthIdentity);
List<Future<Void>> futures = new ArrayList<>();
for (Integer nodeId : nodeIdsToUnregister) {
futures.add(unregisterNode(reconciliation, vertx, adminClient, nodeId));
}
return Future.all(futures)
.eventually(() -> {
adminClient.close();
return Future.succeededFuture();
})
.map((Void) null);
} catch (KafkaException e) {
LOGGER.warnCr(reconciliation, "Failed to unregister nodes", e);
return Future.failedFuture(e);
}
} | @Test
void testFailingNodeUnregistration(VertxTestContext context) {
Admin mockAdmin = ResourceUtils.adminClient();
ArgumentCaptor<Integer> unregisteredNodeIdCaptor = ArgumentCaptor.forClass(Integer.class);
when(mockAdmin.unregisterBroker(unregisteredNodeIdCaptor.capture())).thenAnswer(i -> {
if (i.getArgument(0, Integer.class) == 1919) {
KafkaFutureImpl<Void> unregistrationFuture = new KafkaFutureImpl<>();
unregistrationFuture.completeExceptionally(new TimeoutException("Fake timeout"));
UnregisterBrokerResult ubr = mock(UnregisterBrokerResult.class);
when(ubr.all()).thenReturn(unregistrationFuture);
return ubr;
} else {
UnregisterBrokerResult ubr = mock(UnregisterBrokerResult.class);
when(ubr.all()).thenReturn(KafkaFuture.completedFuture(null));
return ubr;
}
});
AdminClientProvider mockProvider = ResourceUtils.adminClientProvider(mockAdmin);
Checkpoint async = context.checkpoint();
KafkaNodeUnregistration.unregisterNodes(Reconciliation.DUMMY_RECONCILIATION, vertx, mockProvider, null, null, List.of(1874, 1919))
.onComplete(context.failing(v -> context.verify(() -> {
assertThat(unregisteredNodeIdCaptor.getAllValues().size(), is(2));
assertThat(unregisteredNodeIdCaptor.getAllValues(), hasItems(1874, 1919));
async.flag();
})));
} |
@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 to be stubbed.
InheritanceVertex provided = vertexProvider.apply(name);
if (provided == STUB || provided == null) {
// Provider yielded either a stub OR no result. Discard it.
stubs.add(name);
} else {
// Provider yielded a valid vertex. Update the return value and record it in the map.
vertices.put(name, provided);
vertex = provided;
}
}
return vertex;
} | @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 of throwable finds NotFoodException.
// Our class extends Exception, which extends Throwable. So there should be a vertex between Throwable and our type.
JvmClassInfo notFoodException = classPath.getValue().asJvmClass();
List<ClassInfo> exceptionClasses = graph.getVertex("java/lang/Exception").getAllChildren().stream()
.map(InheritanceVertex::getValue)
.toList();
assertTrue(exceptionClasses.contains(notFoodException), "Subtypes of 'Exception' did not yield 'NotFoodException'");
List<ClassInfo> throwableClasses = graph.getVertex("java/lang/Throwable").getAllChildren().stream()
.map(InheritanceVertex::getValue)
.toList();
assertTrue(throwableClasses.contains(notFoodException), "Subtypes of 'Throwable' did not yield 'NotFoodException'");
} |
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_SUFFIXES);
when(properties.getStringArray("sonar.xoo.file.suffixes")).thenReturn(XOO_SUFFIXES);
when(properties.getStringArray("sonar.python.file.suffixes")).thenReturn(PYTHON_SUFFIXES);
assertThat(underTest.get("k1")).isNull();
} |
@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) &&
Objects.equals(this.end, other.end);
}
return false;
} | @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()
.addEqualityGroup(tt, same)
.addEqualityGroup(400)
.addEqualityGroup("")
.addEqualityGroup(diff)
.testEquals();
} |
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()).isEqualTo(Collections.emptyList());
} |
public void onKeyEvent(@NotNull TypeAheadEvent keyEvent) {
if (!myTerminalModel.isTypeAheadEnabled()) return;
myTerminalModel.lock();
try {
if (myTerminalModel.isUsingAlternateBuffer()) {
resetState();
return;
}
TypeAheadTerminalModel.LineWithCursorX lineWithCursorX = myTerminalModel.getCurrentLineWithCursor();
long prevTypedTime = myLastTypedTime;
myLastTypedTime = System.nanoTime();
long autoSyncDelay;
if (myLatencyStatistics.getSampleSize() >= LATENCY_MIN_SAMPLES_TO_TURN_ON) {
autoSyncDelay = Math.min(myLatencyStatistics.getMaxLatency(), MAX_TERMINAL_DELAY);
} else {
autoSyncDelay = MAX_TERMINAL_DELAY;
}
boolean hasTypedRecently = System.nanoTime() - prevTypedTime < autoSyncDelay;
if (hasTypedRecently) {
if (myOutOfSyncDetected) {
return;
}
} else {
myOutOfSyncDetected = false;
}
reevaluatePredictorState(hasTypedRecently);
updateLeftMostCursorPosition(lineWithCursorX.myCursorX);
if (myPredictions.isEmpty() && myClearPredictionsDebouncer != null) {
myClearPredictionsDebouncer.call(); // start a timer that will clear predictions
}
TypeAheadPrediction prediction = createPrediction(lineWithCursorX, keyEvent);
myPredictions.add(prediction);
applyPredictions();
logger.debug("Created " + keyEvent.myEventType + " prediction");
} finally {
myTerminalModel.unlock();
}
} | @Test
public void testCursorMovePrediction() throws Exception {
new TestRunner() {
@Override
void run() {
model.currentLine += 'a';
manager.onKeyEvent(new TypeAheadEvent(TypeAheadEvent.EventType.RightArrow));
boolean found = false;
for (Action action : actions) {
if (action instanceof Action.MoveCursor) {
assertFalse(found);
assertEquals(1, ((Action.MoveCursor) action).index);
found = true;
}
}
assertTrue(found);
}
}.fillLatencyStats().setIsNotPasswordPrompt().run();
} |
void start() throws TransientKinesisException {
ImmutableMap.Builder<String, ShardRecordsIterator> shardsMap = ImmutableMap.builder();
for (ShardCheckpoint checkpoint : initialCheckpoint) {
shardsMap.put(checkpoint.getShardId(), createShardIterator(kinesis, checkpoint));
}
shardIteratorsMap.set(shardsMap.build());
if (!shardIteratorsMap.get().isEmpty()) {
recordsQueue =
new ArrayBlockingQueue<>(queueCapacityPerShard * shardIteratorsMap.get().size());
String streamName = initialCheckpoint.getStreamName();
startReadingShards(shardIteratorsMap.get().values(), streamName);
} else {
// There are no shards to handle when restoring from an empty checkpoint. Empty checkpoints
// are generated when the last shard handled by this pool was closed
recordsQueue = new ArrayBlockingQueue<>(1);
}
} | @Test
public void shouldStopReadersPoolWhenLastShardReaderStopped() throws Exception {
when(firstIterator.readNextBatch()).thenThrow(KinesisShardClosedException.class);
when(firstIterator.findSuccessiveShardRecordIterators()).thenReturn(Collections.emptyList());
shardReadersPool.start();
verify(firstIterator, timeout(TIMEOUT_IN_MILLIS).times(1)).readNextBatch();
} |
@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 && queryMetadata.isRunning() && !limitReached && !complete) {
final KeyValueMetadata<List<?>, GenericRow> row = rowQueue.poll(
disconnectCheckInterval,
TimeUnit.MILLISECONDS
);
if (row != null) {
write(out, buildRow(row));
} else {
// If no new rows have been written, the user may have terminated the connection without
// us knowing. Check by trying to write a single newline.
out.write("\n".getBytes(StandardCharsets.UTF_8));
out.flush();
}
drainAndThrowOnError(out);
}
if (connectionClosed) {
return;
}
drain(out);
if (limitReached) {
objectMapper.writeValue(out, StreamedRow.finalMessage("Limit Reached"));
} else if (complete) {
objectMapper.writeValue(out, StreamedRow.finalMessage("Query Completed"));
}
out.write("]\n".getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (final EOFException exception) {
// The user has terminated the connection; we can stop writing
log.warn("Query terminated due to exception:" + exception.toString());
} catch (final InterruptedException exception) {
// The most likely cause of this is the server shutting down. Should just try to close
// gracefully, without writing any more to the connection stream.
log.warn("Interrupted while writing to connection stream");
} catch (final Exception exception) {
log.error("Exception occurred while writing to connection stream: ", exception);
outputException(out, exception);
} finally {
close();
}
} | @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();
// When:
writer.write(out);
// Then:
final List<String> lines = getOutput(out);
assertThat(lines, hasItems(
containsString("{\"header\":{\"queryId\":\"id\",\"schema\":\"`col1` STRING\"}}"),
containsString("{\"row\":{\"columns\":[\"Row1\"]}}"),
containsString("{\"row\":{\"columns\":[null],\"tombstone\":true}}"),
containsString("{\"row\":{\"columns\":[\"Row3\"]}}")
));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.