focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void when_userDeclaresFields_then_fieldsFromClassNotAdded(boolean key, String prefix) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT,
... |
@Override
public void initialize(Map<String, String> props) {
this.properties = SerializableMap.copyOf(props);
this.gcpProperties = new GCPProperties(properties);
this.storageSupplier =
() -> {
StorageOptions.Builder builder = StorageOptions.newBuilder();
gcpProperties.projec... | @Test
public void testResolvingFileIOLoad() {
ResolvingFileIO resolvingFileIO = new ResolvingFileIO();
resolvingFileIO.setConf(new Configuration());
resolvingFileIO.initialize(ImmutableMap.of());
FileIO result =
DynMethods.builder("io")
.hiddenImpl(ResolvingFileIO.class, String.cla... |
public static String getTableActiveVersionNode(final String databaseName, final String schemaName, final String tableName) {
return String.join("/", getMetaDataNode(), databaseName, SCHEMAS_NODE, schemaName, TABLES_NODE, tableName, ACTIVE_VERSION);
} | @Test
void assertGetTableActiveVersionNode() {
assertThat(TableMetaDataNode.getTableActiveVersionNode("foo_db", "foo_schema", "foo_table"), is("/metadata/foo_db/schemas/foo_schema/tables/foo_table/active_version"));
} |
public boolean isAttached(Appender<E> appender) {
if (appender == null) {
return false;
}
for (Appender<E> a : appenderList) {
if (a == appender) return true;
}
return false;
} | @Test
public void testIsAttached() throws Exception {
NOPAppender<TestEvent> ta = new NOPAppender<TestEvent>();
ta.start();
aai.addAppender(ta);
NOPAppender<TestEvent> tab = new NOPAppender<TestEvent>();
tab.setName("test");
tab.start();
aai.addAppender(tab);
assertTrue("Appender is no... |
@Override
public KStream<K, V> filterNot(final Predicate<? super K, ? super V> predicate) {
return filterNot(predicate, NamedInternal.empty());
} | @Test
public void shouldNotAllowNullPredicateOnFilterNotWithName() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.filterNot(null, Named.as("filter")));
assertThat(exception.getMessage(), equalTo("predicate can't be null"));... |
@Override
public Set<V> readDiff(String... names) {
return get(readDiffAsync(names));
} | @Test
public void testReadDiff() {
RSet<Integer> set = redisson.getSet("set");
set.add(5);
set.add(7);
set.add(6);
RSet<Integer> set1 = redisson.getSet("set1");
set1.add(1);
set1.add(2);
set1.add(5);
RSet<Integer> set2 = redisson.getSet("set2")... |
public <T extends SELF> T setParam(String key, @Nullable String value) {
return (T) setSingleValueParam(key, value);
} | @Test
public void skip_null_value_in_multi_param() {
underTest.setParam("key", asList("v1", null, "", "v3"));
assertMultiValueParameters(entry("key", asList("v1", "", "v3")));
} |
public Result combine(Result other) {
return new Result(this.isPass() && other.isPass(), this.isDescend()
&& other.isDescend());
} | @Test
public void equalsStop() {
Result one = Result.STOP;
Result two = Result.STOP.combine(Result.STOP);
assertEquals(one, two);
} |
@Override
public ConfigDO getConfigByKey(String key) {
return configMapper.selectByKey(key);
} | @Test
public void testGetConfigByKey() {
// mock 数据
ConfigDO dbConfig = randomConfigDO();
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
String key = dbConfig.getConfigKey();
// 调用
ConfigDO config = configService.getConfigByKey(key);
// 断言... |
public static void executeLongPolling(Runnable runnable) {
LONG_POLLING_EXECUTOR.execute(runnable);
} | @Test
void testExecuteLongPolling() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger();
Runnable runnable = atomicInteger::incrementAndGet;
ConfigExecutor.executeLongPolling(runnable);
TimeUnit.MILLISECONDS.sleep(20);
... |
public Optional<RouteContext> loadRouteContext(final OriginSQLRouter originSQLRouter, final QueryContext queryContext, final RuleMetaData globalRuleMetaData,
final ShardingSphereDatabase database, final ShardingCache shardingCache, final ConfigurationProperties props,
... | @Test
void assertCreateRouteContextWithNotCacheableQuery() {
QueryContext queryContext =
new QueryContext(sqlStatementContext, "insert into t values (?), (?)", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class));
when(sharding... |
AccessTokenRetriever getAccessTokenRetriever() {
return accessTokenRetriever;
} | @Test
public void testConfigureWithAccessTokenFile() throws Exception {
String expected = "{}";
File tmpDir = createTempDir("access-token");
File accessTokenFile = createTempFile(tmpDir, "access-token-", ".json", expected);
OAuthBearerLoginCallbackHandler handler = new OAuthBearerL... |
@Udf(description = "Returns a new string encoded using the outputEncoding ")
public String encode(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The input encoding."
+ " If null, the... | @Test
public void shouldReturnNullOnNullValue() {
assertThat(udf.encode(null, "hex", "ascii"), is(nullValue()));
assertThat(udf.encode(null, "utf8", "base64"), is(nullValue()));
assertThat(udf.encode("some string", null, "utf8"), is(nullValue()));
assertThat(udf.encode("some string", "hex", null), is(... |
public void register(final InstanceInfo info) throws Exception {
long expiryTime = System.currentTimeMillis() + getLeaseRenewalOf(info);
batchingDispatcher.process(
taskId("register", info),
new InstanceReplicationTask(targetHost, Action.Register, info, null, true) {
... | @Test
public void testRegistrationBatchReplication() throws Exception {
createPeerEurekaNode().register(instanceInfo);
ReplicationInstance replicationInstance = expectSingleBatchRequest();
assertThat(replicationInstance.getAction(), is(equalTo(Action.Register)));
} |
public static String fromKarateOptionsTags(List<String> tags) {
if (tags == null || tags.isEmpty()) {
return null;
}
return fromKarateOptionsTags(tags.toArray(new String[]{}));
} | @Test
public void testCucumberOptionsTagsConversion() {
assertEquals("anyOf('@foo')", Tags.fromKarateOptionsTags("@foo"));
assertEquals("anyOf('@foo','@bar')", Tags.fromKarateOptionsTags("@foo, @bar"));
assertEquals("anyOf('@foo') && anyOf('@bar')", Tags.fromKarateOptionsTags("@foo", "@bar")... |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchVlanPcpTest() {
Criterion criterion = Criteria.matchVlanPcp((byte) 7);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test(dataProvider = "validClientProtocolVersionDataStreamOnly")
public void testValidReactiveUnstructuredDataRequest(RestLiServer server,
ProtocolVersion clientProtocolVersion,
String headerConstant)
thr... |
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
responseContext.getHeaders().add(HeaderUtils.TIMESTAMP_HEADER, System.currentTimeMillis());
} | @Test
void testFilter() {
final ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
final ContainerResponseContext responseContext = mock(ContainerResponseContext.class);
final MultivaluedMap<String, Object> headers = HeaderUtils.createOutboun... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void transient_maintenance_mode_does_not_override_wanted_down_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMillis(10_000)
.tr... |
@Override
public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap,
String serviceInterface) {
if (!shouldHandle(invokers)) {
return invokers;
}
List<Object> result = getTargetInvokersByRules(invokers, targetSe... | @Test
public void testGetTargetInvokerByTagRules() {
// initialize the routing rule
RuleInitializationUtils.initTagMatchRule();
List<Object> invokers = new ArrayList<>();
ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0");
invokers.add(invoker1);
ApacheInvo... |
public String toFriendlyString() {
return FRIENDLY_FORMAT.format(this).toString();
} | @Test
public void testToFriendlyString() {
assertEquals("1.00 BTC", COIN.toFriendlyString());
assertEquals("1.23 BTC", valueOf(1, 23).toFriendlyString());
assertEquals("0.001 BTC", COIN.divide(1000).toFriendlyString());
assertEquals("-1.23 BTC", valueOf(1, 23).negate().toFriendlyStri... |
@Override
public boolean match(Message msg, StreamRule rule) {
return Optional.ofNullable(rule.getInverted())
// When this rule is inverted, it should never match
.map(inverted -> !inverted)
// If `inverted` is `null`, we always return `true`
.... | @Test
public void matchAlwaysReturnsTrue() throws Exception {
assertThat(matcher.match(
message,
new StreamRuleMock(Map.of("_id", "stream-rule-id"))))
.isTrue();
assertThat(matcher.match(
message,
new StreamRuleMock(Map.... |
public Filter merge(Filter... filters) {
BloomFilter merged = new BloomFilter(this.getHashCount(), (BitSet) this.filter().clone());
if (filters == null) {
return merged;
}
for (Filter filter : filters) {
if (!(filter instanceof BloomFilter)) {
th... | @Test(expected=IllegalArgumentException.class)
public void testMergeException() {
BloomFilter bf3 = new BloomFilter(ELEMENTS*10, 1);
BloomFilter[] bfs = new BloomFilter[1];
bfs[0] = bf;
BloomFilter mergeBf = (BloomFilter) bf3.merge(bf);
} |
@Override
public void resolveArtifacts(
ArtifactApi.ResolveArtifactsRequest request,
StreamObserver<ArtifactApi.ResolveArtifactsResponse> responseObserver) {
responseObserver.onNext(
ArtifactApi.ResolveArtifactsResponse.newBuilder()
.addAllReplacements(resolver.resolveArtifacts(req... | @Test
public void testResolveArtifacts() throws IOException {
RunnerApi.ArtifactInformation artifact = fileArtifact(Paths.get("somePath"));
ArtifactApi.ResolveArtifactsResponse resolved =
retrievalBlockingStub.resolveArtifacts(
ArtifactApi.ResolveArtifactsRequest.newBuilder().addArtifacts(... |
boolean isSetAndInitialized() {
return proxy != null || error != null;
} | @Test
public void isSet_returnsFalse_whenNotSet() {
assertFalse(future.isSetAndInitialized());
} |
@Override
public KubevirtFloatingIp floatingIpByPodName(String podName) {
checkArgument(!Strings.isNullOrEmpty(podName), ERR_NULL_POD_NAME);
return kubevirtRouterStore.floatingIps().stream()
.filter(ips -> podName.equals(ips.podName()))
.findAny().orElse(null);
} | @Test
public void testGetFloatingIpByPodName() {
createBasicFloatingIpAssociated();
assertNotNull("Floating IP did not match", target.floatingIpByPodName(POD_NAME));
assertNull("Floating IP did not match", target.floatingIpByPodName(UNKNOWN_ID));
} |
@Override
public V fetch(final K key, final long time) {
Objects.requireNonNull(key, "key can't be null");
final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType);
for (final ReadOnlyWindowStore<K, V> windowStore : stores) {
try {
... | @Test
public void shouldThrowInvalidStateStoreExceptionIfFetchThrows() {
underlyingWindowStore.setOpen(false);
final CompositeReadOnlyWindowStore<Object, Object> store =
new CompositeReadOnlyWindowStore<>(
new WrappingStoreProvider(singletonList(stubProviderOne), StoreQue... |
public MessageType getMessageType()
{
return messageType;
} | @Test
public void testMapKeyRepetitionLevel()
{
ParquetSchemaConverter schemaConverter = new ParquetSchemaConverter(
ImmutableList.of(mapType(VARCHAR, INTEGER)),
ImmutableList.of("test"));
GroupType mapType = schemaConverter.getMessageType().getType(0).asGroupType... |
public void update(String namespaceName, String extensionName) throws InterruptedException {
if(BuiltInExtensionUtil.isBuiltIn(namespaceName)) {
LOGGER.debug("SKIP BUILT-IN EXTENSION {}", NamingUtil.toExtensionId(namespaceName, extensionName));
return;
}
var extension = ... | @Test
public void testMustUpdateRandomExistsDb() throws InterruptedException {
var namespaceName1 = "foo";
var namespaceUuid1 = UUID.randomUUID().toString();
var extensionName1 = "bar";
var extensionUuid1 = UUID.randomUUID().toString();
var namespace1 = new Namespace();
... |
public String name() { return name; } | @Test
public void metricsAreUnregistered() throws Exception {
Configuration conf = new Configuration();
Server server = new Server("0.0.0.0", 0, LongWritable.class, 1, conf) {
@Override
public Writable call(
RPC.RpcKind rpcKind, String protocol, Writable param,
long receiveTim... |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void format_sets_static_subject_when_change_from_User() {
Set<ChangedIssue> changedIssues = IntStream.range(0, 2 + new Random().nextInt(4))
.mapToObj(i -> newChangedIssue(i + "", randomValidStatus(), newProject("prj_" + i), newRandomNotAHotspotRule("rule_" + i)))
.collect(toSet());
Us... |
@Override
public boolean isEmpty() {
return commandTopic.getEndOffset() == 0;
} | @Test
public void shouldComputeNotEmptyCorrectly() {
// Given:
when(commandTopic.getEndOffset()).thenReturn(1L);
// When/Then:
assertThat(commandStore.isEmpty(), is(false));
} |
@Override
public ConfigErrors errors() {
return errors;
} | @Test
public void shouldValidatePipelineLabelWithEnvironmentVariable() {
String labelFormat = "pipeline-${COUNT}-${env:SOME_VAR}";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(nullValue()... |
public static StrimziPodSet createPodSet(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
ResourceTemplate template,
int replicas,
Map<String, String> annotations,
Labels selectorLabels,
... | @Test
public void testCreateStrimziPodSetFromNodeReferencesWithTemplate() {
List<String> podNames = new ArrayList<>();
StrimziPodSet sps = WorkloadUtils.createPodSet(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
new Resou... |
public Config setProperty(@Nonnull String name, @Nonnull String value) {
if (isNullOrEmptyAfterTrim(name)) {
throw new IllegalArgumentException("argument 'name' can't be null or empty");
}
isNotNull(value, "value");
properties.setProperty(name, value);
return this;
... | @Test(expected = IllegalArgumentException.class)
public void testSetConfigPropertyNameNull() {
config.setProperty(null, "test");
} |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Bui... | @Test
public void setAndRemoveProperties() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.SetProperties(ImmutableMap.of("test", "test"))));
requirements.forEach(req -> req.validate(metadata));
asser... |
@Override
public ClientBuilder dnsServerAddresses(List<InetSocketAddress> addresses) {
for (InetSocketAddress address : addresses) {
String ip = address.getHostString();
checkArgument(InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip),
"DnsSe... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testClientBuilderWithIllegalDNSServerHostname() throws PulsarClientException {
PulsarClient.builder().dnsServerAddresses(
Arrays.asList(new InetSocketAddress("1.2.3.4", 53), new InetSocketAddress("localhost",53)));
} |
public static String getProcessId(Path path) throws IOException {
if (path == null) {
throw new IOException("Trying to access process id from a null path");
}
LOG.debug("Accessing pid from pid file {}", path);
String processId = null;
BufferedReader bufReader = null;
try {
File file... | @Test (timeout = 30000)
public void testSimpleGet() throws IOException {
String rootDir = new File(System.getProperty(
"test.build.data", "/tmp")).getAbsolutePath();
File testFile = null;
String expectedProcessId = Shell.WINDOWS ?
"container_1353742680940_0002_01_000001" :
"56789";
... |
public boolean isSuccess() {
return httpStatus != null && httpStatus >= 200 && httpStatus < 300;
} | @Test
public void isSuccess_returns_true_if_http_response_returns_2xx_code() {
WebhookDelivery delivery = newBuilderTemplate()
.setHttpStatus(204)
.build();
assertThat(delivery.isSuccess()).isTrue();
} |
protected org.graylog2.plugin.indexer.searches.timeranges.TimeRange restrictTimeRange(final org.graylog2.plugin.indexer.searches.timeranges.TimeRange timeRange) {
final DateTime originalFrom = timeRange.getFrom();
final DateTime to = timeRange.getTo();
final DateTime from;
final Searche... | @Test
public void restrictTimeRangeReturnsGivenTimeRangeIfNoLimitHasBeenSet() {
when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault()
.toBuilder()
.queryTimeRangeLimit(Period.ZERO)
.build());
fina... |
public void add(Task task) {
tasks.put('/' + task.getName(), task);
TaskExecutor taskExecutor = new TaskExecutor(task);
try {
final Method executeMethod = task.getClass().getMethod("execute",
Map.class, PrintWriter.class);
if (executeMethod.isAnnotat... | @Test
void testRunsTimedTask() throws Exception {
final ServletInputStream bodyStream = new TestServletInputStream(
new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)));
final Task timedTask = new Task("timed-task") {
@Override
@Timed(name = "vacuum-cle... |
@Override
public String getOperationName(Exchange exchange, Endpoint endpoint) {
Object name = exchange.getProperty(Exchange.TIMER_NAME);
if (name instanceof String) {
return (String) name;
}
return super.getOperationName(exchange, endpoint);
} | @Test
public void testGetOperationName() {
Exchange exchange = Mockito.mock(Exchange.class);
Mockito.when(exchange.getProperty(Exchange.TIMER_NAME)).thenReturn(TEST_NAME);
SpanDecorator decorator = new TimerSpanDecorator() {
@Override
public String getComponent() {
... |
@Override
public int hashCode() {
int hashCode = 0;
for (int hash : hashes) {
hashCode += hash;
}
return hashCode;
} | @Test
public void testHashCode() {
final OAHashSet<Integer> set = new OAHashSet<>(8);
populateSet(set, 10);
final int expectedHashCode = 45;
assertEquals(expectedHashCode, set.hashCode());
} |
protected HashMap<String, Double> computeModularity(Graph graph, CommunityStructure theStructure,
int[] comStructure,
double currentResolution, boolean randomized,
... | @Test
public void testCyclicWithWeightsGraphModularity() {
GraphModel graphModel = GraphModel.Factory.newInstance();
UndirectedGraph undirectedGraph = graphModel.getUndirectedGraph();
Node node1 = graphModel.factory().newNode("0");
Node node2 = graphModel.factory().newNode("1");
... |
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 serialization() {
ULiteral oneLit = ULiteral.intLit(1);
ULiteral twoLit = ULiteral.intLit(2);
ULiteral piLit = ULiteral.doubleLit(Math.PI);
ULiteral trueLit = ULiteral.booleanLit(true);
ULiteral falseLit = ULiteral.booleanLit(false);
SerializableTester.reserializeAndAssert(U... |
public static void readFully(InputStream stream, byte[] bytes, int offset, int length)
throws IOException {
int bytesRead = readRemaining(stream, bytes, offset, length);
if (bytesRead < length) {
throw new EOFException(
"Reached the end of stream with " + (length - bytesRead) + " bytes lef... | @Test
public void testReadFullyUnderflow() {
final byte[] buffer = new byte[11];
final MockInputStream stream = new MockInputStream(2, 3, 3);
assertThatThrownBy(() -> IOUtil.readFully(stream, buffer, 0, buffer.length))
.isInstanceOf(EOFException.class)
.hasMessage("Reached the end of str... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest));
} | @Test
public void containsAtLeastExtraKeyAndMissingKeyAndWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3);
expectFailureWhenTestingThat(actual).containsAtLeast("march", 33, "feb", 2);
assertFailureKeys(
"keys with wrong values",
"for key",
... |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated t... | @Test
void getUnversionedProfileGroupSendEndorsementAccountNotFound() throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
// Expiration must be on a day boundary; we want one in the future
final Instant expiration = Instant.now().plus(Duration.of... |
@Override
public Position offsetToPosition(int offset, Bias bias) {
return position(0, 0).offsetBy(offset, bias);
} | @Test
public void testPositiveOffsetWithBackwardBias() {
Position pos = navigator.offsetToPosition(10, Backward);
assertEquals(0, pos.getMajor());
assertEquals(10, pos.getMinor());
} |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldSelectFirstElementOfTwo() {
// When:
final String el = elt.elt(1, "a", "b");
// Then:
assertThat(el, equalTo("a"));
} |
public static SocketAddress createFrom(String value) {
if (value.startsWith(UNIX_DOMAIN_SOCKET_PREFIX)) {
// Unix Domain Socket address.
// Create the underlying file for the Unix Domain Socket.
String filePath = value.substring(UNIX_DOMAIN_SOCKET_PREFIX.length());
File file = new File(fileP... | @Test
public void testDomainSocket() throws Exception {
File tmpFile = tmpFolder.newFile();
SocketAddress socketAddress =
SocketAddressFactory.createFrom("unix://" + tmpFile.getAbsolutePath());
assertThat(socketAddress, Matchers.instanceOf(DomainSocketAddress.class));
assertEquals(tmpFile.getA... |
@Override
public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) {
comment(properties);
return true;
} | @Test
public void should_verify_fail_if_parameter_not_found() {
Map<String, Object> properties = singletonMap("unknwown", "unknown value");
try {
action.verify(properties, new ArrayList<>(), new AnonymousMockUserSession());
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(Illeg... |
@Udf
public String uuid() {
return java.util.UUID.randomUUID().toString();
} | @Test
public void shouldReturnDistinctValueEachInvocation() {
int capacity = 1000;
final Set<String> outputs = new HashSet<String>(capacity);
for (int i = 0; i < capacity; i++) {
outputs.add(udf.uuid());
}
assertThat(outputs, hasSize(capacity));
} |
public static boolean isFuture(String timestamp) {
return !StringUtils.isEmpty(timestamp) && isFuture(Long.parseLong(timestamp));
} | @Test
public void isFutureManagesNullValues() {
Long longValue = null;
assertFalse(DateUtils.isFuture(longValue));
} |
public List<String> toPrefix(String in) {
List<String> tokens = buildTokens(alignINClause(in));
List<String> output = new ArrayList<>();
List<String> stack = new ArrayList<>();
for (String token : tokens) {
if (isOperand(token)) {
if (token.equals(")")) {
... | @Test
public void testBetween() {
String query = "b between 10 and 15";
List<String> list = parser.toPrefix(query);
assertEquals(Arrays.asList("b", "10", "15", "between"), list);
} |
public void restore(final List<Pair<byte[], byte[]>> backupCommands) {
// Delete the command topic
deleteCommandTopicIfExists();
// Create the command topic
KsqlInternalTopicUtils.ensureTopic(commandTopicName, serverConfig, topicClient);
// Restore the commands
restoreCommandTopic(backupComman... | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT")
@Test
public void shouldThrowIfCannotDescribeTopicExists() {
// Given:
doThrow(new RuntimeException("denied")).when(topicClient).isTopicExists(COMMAND_TOPIC_NAME);
// When:
final Exception e = assertThrows(
RuntimeException.class... |
public static boolean isNullOrEmpty(String str) {
return (str == null) || (str.isEmpty());
} | @Test
public void testIsNullOrEmpty() {
assertThat(StringUtils.isNullOrEmpty(null)).isTrue();
assertThat(StringUtils.isNullOrEmpty("abc")).isFalse();
assertThat(StringUtils.isNullOrEmpty("")).isTrue();
assertThat(StringUtils.isNullOrEmpty(" ")).isFalse();
} |
@Override
public BackgroundException map(final ApiException failure) {
final StringBuilder buffer = new StringBuilder();
if(StringUtils.isNotBlank(failure.getMessage())) {
for(String s : StringUtils.split(failure.getMessage(), ",")) {
this.append(buffer, LocaleFactory.loc... | @Test
public void testRetry() {
final BackgroundException failure = new EueExceptionMappingService().map(new ApiException(429, "",
Collections.singletonMap("Retry-After", Collections.singletonList("5")), ""));
assertTrue(failure instanceof RetriableAccessDeniedException);
ass... |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void readOffset() throws IOException, AlluxioException {
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
int start = CHUNK_SIZE / 4;
int len = CHUNK_SIZE / 2;
try (FileInStream inStream = getStream(ufsPath)) {
byte[] res = new byte[CHUNK_SIZE];
assertEq... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.GAMEMESSAGE && event.getType() != ChatMessageType.SPAM)
{
return;
}
String message = event.getMessage();
if (message.equals("Your Ring of endurance doubles the duration of your stamina potion's effect."))
... | @Test
public void testCheckMessage()
{
String checkMessage = "Your Ring of endurance is charged with 52 stamina doses.";
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", checkMessage, "", 0);
runEnergyPlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(... |
@Override
public Endpoint<Http2RemoteFlowController> remote() {
return remoteEndpoint;
} | @Test
public void serverRemoteIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(server.remote(), MAX_VALUE);
} |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(ur... | @Test
public void testItpcProtocolWithScheme() {
final String in = "itpc://https://example.com";
final String out = UrlChecker.prepareUrl(in);
assertEquals("https://example.com", out);
} |
@Override
public String getName() {
return "readFile";
} | @Test
void testGetName() {
assertEquals("readFile", readFileAction.getName());
} |
public static org.onosproject.security.Permission getOnosPermission(Permission permission) {
if (permission instanceof AppPermission) {
return new org.onosproject.security.Permission(AppPermission.class.getName(), permission.getName(), "");
} else if (permission instanceof FilePermission) {
... | @Test
public void testGetOnosPermission() {
org.onosproject.security.Permission result = null;
if (testJavaPerm instanceof AppPermission) {
result = new org.onosproject.security.Permission(AppPermission.class.getName(), testJavaPerm.getName(), "");
}
assertNotNull(result)... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatStructWithColumnWithReservedWordName() {
final SqlStruct struct = SqlStruct.builder()
.field("RESERVED", SqlTypes.INTEGER)
.build();
assertThat(
ExpressionFormatter.formatExpression(new Type(struct), FormatOptions.none()),
equalTo("STRUCT<`RESERVE... |
protected List<T> getEntities(
@Nonnull final EntityProvider<T, ?> entities,
@Nullable final Pageable pageable,
@Nullable final Class<T> clazz,
@Nullable final Sort sort)
{
Objects.requireNonNull(entities);
Stream<? extends T> entityStream = entities
.stream()
.filter(this.criteria::evaluate);
... | @Test
void getEntities_EmptyCriteria_NoPageable_Sortable_IsSortedByInvalidProperty()
{
final PageableSortableCollectionQuerier<Customer> querier = new PageableSortableCollectionQuerier<>(
new DummyWorkingCopier<>(),
new CriteriaSingleNode<>()
);
final Pageable unpaged = Pageable.unpaged();
final Sort in... |
public static void clearUtm() {
clearMemoryUtm();
clearLocalUtm();
} | @Test
public void clearUtm() {
ChannelUtils.clearUtm();
JSONObject jsonObject = ChannelUtils.getUtmProperties();
Assert.assertEquals(0, jsonObject.length());
} |
String buildCustomMessage(EventNotificationContext ctx, TeamsEventNotificationConfig config, String template) throws PermanentEventNotificationException {
final List<MessageSummary> backlog = getMessageBacklog(ctx, config);
Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog, c... | @Test
public void buildCustomMessage() throws PermanentEventNotificationException {
String expectedCustomMessage = teamsEventNotification.buildCustomMessage(eventNotificationContext, teamsEventNotificationConfig, "test");
assertThat(expectedCustomMessage).isNotEmpty();
} |
public void updateMetrics() {
recordMessagesConsumed(metricCollectors.currentConsumptionRate());
recordTotalMessagesConsumed(metricCollectors.totalMessageConsumption());
recordTotalBytesConsumed(metricCollectors.totalBytesConsumption());
recordMessagesProduced(metricCollectors.currentProductionRate());
... | @Test
public void shouldRecordMinMessagesConsumedByQuery() {
final int numMessagesConsumed = 500;
consumeMessages(numMessagesConsumed, "group1");
consumeMessages(numMessagesConsumed * 100, "group2");
engineMetrics.updateMetrics();
final double value = getMetricValue("messages-consumed-min");
... |
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, Retry retry, String methodName)
throws Throwable {
RetryTransformer<?> retryTransformer = RetryTransformer.of(retry);
Object returnValue = proceedingJoinPoint.proceed();
return executeRxJava3Aspect(retryTransform... | @Test
public void testRxTypes() throws Throwable {
Retry retry = Retry.ofDefaults("test");
when(proceedingJoinPoint.proceed()).thenReturn(Single.just("Test"));
assertThat(rxJava3RetryAspectExt.handle(proceedingJoinPoint, retry, "testMethod"))
.isNotNull();
when(proceedi... |
@Override
public void setParentJobMeta( JobMeta parentJobMeta ) {
JobMeta previous = getParentJobMeta();
super.setParentJobMeta( parentJobMeta );
if ( previous != null ) {
previous.removeCurrentDirectoryChangedListener( this.dirListener );
}
if ( parentJobMeta != null ) {
parentJobMet... | @Test
public void testCurrDirListener() throws Exception {
try ( MockedConstruction<JobMeta> jobMetaMockedConstruction = mockConstruction( JobMeta.class );
MockedConstruction<CurrentDirectoryResolver> currentDirectoryResolverMockedConstruction = mockConstruction(
CurrentDirectoryResolver.cla... |
public void hidePerspective( final String perspectiveId ) {
changePerspectiveVisibility( perspectiveId, true );
} | @Test
public void hidePerspective() {
SpoonPerspectiveManager.PerspectiveManager perspectiveManager = perspectiveManagerMap.get( perspective );
spoonPerspectiveManager.hidePerspective( perspective.getId() );
verify( perspectiveManager ).setPerspectiveHidden( PERSPECTIVE_NAME, true );
} |
@Override
public void onError(Throwable t) {
forwardErrorToLeaderContender(t);
} | @Test
void testErrorForwarding() throws Exception {
new Context() {
{
runTestWithSynchronousEventHandling(
() -> {
final Exception testException = new Exception("test leader exception");
leaderElecti... |
public static void checkGroup(String group) throws MQClientException {
if (UtilAll.isBlank(group)) {
throw new MQClientException("the specified group is blank", null);
}
if (group.length() > CHARACTER_MAX_LENGTH) {
throw new MQClientException("the specified group is long... | @Test
public void testGroupNameBlank() {
try {
Validators.checkGroup(null);
fail("excepted MQClientException for group name is blank");
} catch (MQClientException e) {
assertThat(e.getErrorMessage()).isEqualTo("the specified group is blank");
}
} |
@Override
public int hashCode() {
return Objects.hash(labelStrings);
} | @Test
public void testEqualsAndHashCode() {
MultiLabel a = new MultiLabelFactory().generateOutput("a");
MultiLabel b = new MultiLabelFactory().generateOutput("a");
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
} |
@Override
protected Release findLatestActiveRelease(String configAppId, String configClusterName, String configNamespace,
ApolloNotificationMessages clientMessages) {
return releaseService.findLatestActiveRelease(configAppId, configClusterName,
configNamespace);... | @Test
public void testLoadConfig() throws Exception {
when(releaseService.findLatestActiveRelease(someConfigAppId, someClusterName, defaultNamespaceName))
.thenReturn(someRelease);
Release release = configService
.loadConfig(someClientAppId, someClientIp, someClientLabel, someConfigAppId, som... |
public void prepareExchange(Exchange exchange) {
Message message = exchange.getMessage();
String recipients = matchFilters(exchange);
message.setHeader(RECIPIENT_LIST_HEADER, recipients);
} | @Test
void testPrepareExchange() {
when(exchange.getMessage()).thenReturn(message);
when(filterService.getMatchingEndpointsForExchangeByChannel(exchange, TEST_CHANNEL, true, false))
.thenReturn(MOCK_ENDPOINT);
processor.prepareExchange(exchange);
verify(message, new T... |
public void writeApplicationId(ApplicationId id) {
if ( ! id.tenant().equals(tenantName))
throw new IllegalArgumentException("Cannot write application id '" + id + "' for tenant '" + tenantName + "'");
curator.set(applicationIdPath(), Utf8.toBytes(id.serializedForm()));
} | @Test
public void require_that_application_id_is_written_to_zk() {
ApplicationId id = new ApplicationId.Builder()
.tenant(tenantName)
.applicationName("foo")
.instanceName("bim")
.build();
int sessionId = 3;
SessionZooKeeperClie... |
@Override
public UserAccount upsertDb(final UserAccount userAccount) {
String userId = userAccount.getUserId();
String userName = userAccount.getUserName();
String additionalInfo = userAccount.getAdditionalInfo();
db.getCollection(CachingConstants.USER_ACCOUNT).updateOne(
new Document(USER... | @Test
void upsertDb() {
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.upsertDb(userAccount);});
} |
@Description("a pseudo-random value")
@ScalarFunction(alias = "rand", deterministic = false)
@SqlType(StandardTypes.DOUBLE)
public static double random()
{
return ThreadLocalRandom.current().nextDouble();
} | @Test
public void testRandom()
{
// random is non-deterministic
functionAssertions.tryEvaluateWithAll("rand()", DOUBLE, TEST_SESSION);
functionAssertions.tryEvaluateWithAll("random()", DOUBLE, TEST_SESSION);
functionAssertions.tryEvaluateWithAll("rand(1000)", INTEGER, TEST_SESSIO... |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
return this.processRequest(ctx.channel(), request, true);
} | @Test
public void testSingleAck_OffsetCheck() throws RemotingCommandException {
{
AckMessageRequestHeader requestHeader = new AckMessageRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(0);
requestHeader.setOffset(MIN_OFFSET_IN_QUEUE - 1... |
public ServiceInfo getServiceInfo() {
return serviceInfo;
} | @Test
void testDeserialize() throws JsonProcessingException {
String json = "{\"headers\":{},\"namespace\":\"namespace\",\"serviceName\":\"service\",\"groupName\":\"group\","
+ "\"serviceInfo\":{\"name\":\"service\",\"groupName\":\"group\",\"cacheMillis\":1000,\"hosts\":[],"
... |
public static TaskID forName(String str)
throws IllegalArgumentException {
if(str == null)
return null;
Matcher m = taskIdPattern.matcher(str);
if (m.matches()) {
return new org.apache.hadoop.mapred.TaskID(m.group(1),
Integer.parseInt(m.group(2)),
CharTaskTypeMaps.getTas... | @Test
public void testForName() {
assertEquals("The forName() method did not parse the task ID string "
+ "correctly", "task_1_0001_m_000000",
TaskID.forName("task_1_0001_m_000").toString());
assertEquals("The forName() method did not parse the task ID string "
+ "correctly", "task_23_... |
public int format(String... args) throws UsageException {
CommandLineOptions parameters = processArgs(args);
if (parameters.version()) {
errWriter.println(versionString());
return 0;
}
if (parameters.help()) {
throw new UsageException();
}
JavaFormatterOptions options =
... | @Test
public void dryRunStdinChanged() throws Exception {
StringWriter out = new StringWriter();
StringWriter err = new StringWriter();
String input = "class Test {\n}\n";
Main main =
new Main(
new PrintWriter(out, true),
new PrintWriter(err, true),
new Byte... |
public RegistryBuilder isCheck(Boolean check) {
this.check = check;
return getThis();
} | @Test
void isCheck() {
RegistryBuilder builder = new RegistryBuilder();
builder.isCheck(true);
Assertions.assertTrue(builder.build().isCheck());
} |
public void verifyState(HttpRequest request, HttpResponse response, OAuth2IdentityProvider provider) {
verifyState(request, response, provider, DEFAULT_STATE_PARAMETER_NAME);
} | @Test
public void verify_state() {
String state = "state";
when(request.getCookies()).thenReturn(new Cookie[]{wrapCookie("OAUTHSTATE", sha256Hex(state))});
when(request.getParameter("aStateParameter")).thenReturn(state);
underTest.verifyState(request, response, identityProvider, "aStateParameter");
... |
public static int toSeconds(TimeRange timeRange) {
if (timeRange.getFrom() == null || timeRange.getTo() == null) {
return 0;
}
try {
return Seconds.secondsBetween(timeRange.getFrom(), timeRange.getTo()).getSeconds();
} catch (IllegalArgumentException e) {
... | @Test
public void toSecondsHandlesIncompleteTimeRange() throws Exception {
assertThat(TimeRanges.toSeconds(new TimeRange() {
@Override
public String type() {
return AbsoluteRange.ABSOLUTE;
}
@Override
public DateTime getFrom() {
... |
public static Map<String, String> getConfigMapWithPrefix(Map<String, String> batchConfigMap, String prefix) {
Map<String, String> props = new HashMap<>();
if (!prefix.endsWith(DOT_SEPARATOR)) {
prefix = prefix + DOT_SEPARATOR;
}
for (String configKey : batchConfigMap.keySet()) {
if (configKe... | @Test
public void testGetConfigMapWithPrefix() {
Map<String, String> testMap = ImmutableMap.of("k1", "v1", "k1.k2", "v2", "k1.k3", "v3", "k4", "v4");
Assert.assertEquals(2, IngestionConfigUtils.getConfigMapWithPrefix(testMap, "k1").size());
Assert.assertEquals(2, IngestionConfigUtils.getConfigMapWithPrefi... |
public DockerStopCommand setGracePeriod(int value) {
super.addCommandArguments("time", Integer.toString(value));
return this;
} | @Test
public void testSetGracePeriod() throws Exception {
dockerStopCommand.setGracePeriod(GRACE_PERIOD);
assertEquals("stop", StringUtils.join(",",
dockerStopCommand.getDockerCommandWithArguments()
.get("docker-command")));
assertEquals("foo", StringUtils.join(",",
dockerStopC... |
@Override
public List<AdminUserDO> getUserListByStatus(Integer status) {
return userMapper.selectListByStatus(status);
} | @Test
public void testGetUserListByStatus() {
// mock 数据
AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()));
userMapper.insert(user);
// 测试 status 不匹配
userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getSta... |
@Override
public void delete(final String key) {
try {
if (isExisted(key)) {
client.delete().deletingChildrenIfNeeded().forPath(key);
}
// CHECKSTYLE:OFF
} catch (final Exception ex) {
// CHECKSTYLE:ON
ZookeeperExceptionHand... | @Test
void assertDeleteNotExistKey() {
REPOSITORY.delete("/test/children/1");
verify(client, times(0)).delete();
} |
public static boolean isFastStatsSame(Partition oldPart, Partition newPart) {
// requires to calculate stats if new and old have different fast stats
if ((oldPart != null) && oldPart.isSetParameters() && newPart != null && newPart.isSetParameters()) {
for (String stat : StatsSetupConst.FAST_STATS) {
... | @Test
public void isFastStatsSameWithNullPartitions() {
Partition partition = new Partition();
assertFalse(MetaStoreServerUtils.isFastStatsSame(null, null));
assertFalse(MetaStoreServerUtils.isFastStatsSame(null, partition));
assertFalse(MetaStoreServerUtils.isFastStatsSame(partition, null));
} |
@Override
public ResultSet getTableTypes() throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getTableTypes());
} | @Test
void assertGetTableTypes() throws SQLException {
when(databaseMetaData.getTableTypes()).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getTableTypes(), instanceOf(DatabaseMetaDataResultSet.class));
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final String msg = new String(rawMessage.getPayload(), charset);
try (Timer.Context ignored = this.decodeTime.time()) {
final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress();
f... | @Test
public void testDefaultTimezoneConfig() {
when(configuration.getString("timezone")).thenReturn("MST");
SyslogCodec codec = new SyslogCodec(configuration, metricRegistry, messageFactory);
final Message msgWithoutTimezone = codec.decode(buildRawMessage(UNSTRUCTURED));
final Mess... |
@Override
@SuppressWarnings("unchecked")
public <K, T> void onAllResponsesReceived(Request<T> request, ProtocolVersion protocolVersion,
Map<RequestInfo, Response<T>> successResponses,
Map<RequestInfo, Throwable> failureResponses... | @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocol")
public void testGatherBatchResponse(ProtocolVersion version)
{
Map<RequestInfo, Response<BatchResponse<TestRecord>>> successResponses = new HashMap<>();
successResponses.put(
new RequestInfo(createBatchGetRequest(1L, 2L)... |
public void removeDecorator(TaskDecorator decorator) {
decorators.remove(decorator);
} | @Test
public void testRemoveDecorator() {
TaskDecoratorPlugin plugin = new TaskDecoratorPlugin();
TaskDecorator decorator = runnable -> runnable;
plugin.addDecorator(decorator);
plugin.removeDecorator(decorator);
Assert.assertTrue(plugin.getDecorators().isEmpty());
} |
@Override
public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey,
@Nullable String projectName) {
String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto);
String url = requireNonNull(... | @Test
void createProjectAndBindToDevOpsPlatform_whenPatIsMissing_shouldThrow() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.createProjectAndBindToDevOpsPlatform(mock(DbSession.class), CreationMethod.ALM_IMPORT_API, false, null, null))
.withMessage("personal a... |
@Override
public String getName() {
return "Perl cpanfile Analyzer";
} | @Test
public void testGetName() {
PerlCpanfileAnalyzer instance = new PerlCpanfileAnalyzer();
String expResult = "Perl cpanfile Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
} |
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn, final String regexField) {
return rows.stream()
.map(row -> row.evaluate(columnPairsMap, outputColumn, regexField))
.filter(Optional::isPresent)
.findFirst()
... | @Test
void evaluateKeyFoundMultipleNotMatching() {
KiePMMLInlineTable kiePMMLInlineTable = new KiePMMLInlineTable("name", Collections.emptyList(), ROWS);
Map<String, Object> columnPairsMap = IntStream.range(0, 2).boxed()
.collect(Collectors.toMap(i -> "KEY-1-" + i,
... |
public ValidationResult toValidationResult(String responseBody) {
try {
ValidationResult validationResult = new ValidationResult();
if (isEmpty(responseBody)) return validationResult;
List<Map<String, Object>> errors;
try {
errors = GSON.fromJson... | @Test
public void shouldBuildValidationResultFromResponseBody() {
String responseBody = "[{\"key\":\"key-one\",\"message\":\"incorrect value\"},{\"message\":\"general error\"}]";
ValidationResult validationResult = messageHandler.toValidationResult(responseBody);
assertValidationError(valida... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.