focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static URI parse(String gluePath) {
requireNonNull(gluePath, "gluePath may not be null");
if (gluePath.isEmpty()) {
return rootPackageUri();
}
// Legacy from the Cucumber Eclipse plugin
// Older versions of Cucumber allowed it.
if (CLASSPATH_SCHEME_PRE... | @Test
void can_parse_relative_path_form() {
URI uri = GluePath.parse("com/example/app");
assertAll(
() -> assertThat(uri.getScheme(), is("classpath")),
() -> assertThat(uri.getSchemeSpecificPart(), is("/com/example/app")));
} |
public static SlidingWindows ofTimeDifferenceAndGrace(final Duration timeDifference, final Duration afterWindowEnd) throws IllegalArgumentException {
final String timeDifferenceMsgPrefix = prepareMillisCheckFailMsgPrefix(timeDifference, "timeDifference");
final long timeDifferenceMs = validateMillisecon... | @Test
public void equalsAndHashcodeShouldNotBeEqualForDifferentGracePeriod() {
final long timeDifference = 1L + (long) (Math.random() * (10L - 1L));
final long graceOne = 1L + (long) (Math.random() * (10L - 1L));
final long graceTwo = 21L + (long) (Math.random() * (41L - 21L));
verif... |
public Span newChild(TraceContext parent) {
if (parent == null) throw new NullPointerException("parent == null");
return _toSpan(parent, decorateContext(parent, parent.spanId()));
} | @Test void newChild() {
TraceContext parent = tracer.newTrace().context();
assertThat(tracer.newChild(parent))
.satisfies(c -> {
assertThat(c.context().traceIdString()).isEqualTo(parent.traceIdString());
assertThat(c.context().parentIdString()).isEqualTo(parent.spanIdString());
})
... |
@Override
public Optional<CompletableFuture<TaskManagerLocation>> getTaskManagerLocation(
ExecutionVertexID executionVertexId) {
ExecutionVertex ev = getExecutionVertex(executionVertexId);
if (ev.getExecutionState() != ExecutionState.CREATED) {
return Optional.of(ev.getCurre... | @Test
void testGetNonExistingExecutionVertexWillThrowException() throws Exception {
final JobVertex jobVertex = ExecutionGraphTestUtils.createNoOpVertex(1);
final ExecutionGraph eg =
ExecutionGraphTestUtils.createExecutionGraph(
EXECUTOR_EXTENSION.getExecutor... |
@Override
public void updateInstance(String serviceName, Instance instance) throws NacosException {
updateInstance(serviceName, Constants.DEFAULT_GROUP, instance);
} | @Test
void testUpdateInstance1() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
Instance instance = new Instance();
//when
nacosNamingMaintainService.updateInstance(serviceName, groupName, instance);
//then
... |
@Override
public void visit(Entry entry) {
if(Boolean.FALSE.equals(entry.getAttribute("allowed")))
return;
if (containsSubmenu(entry))
addSubmenu(entry);
else
addActionItem(entry);
} | @Test
public void whenPopupMenuBecomesInvisible_popupListenerIsCalled() throws Exception {
if(Compat.isMacOsX())
return;
Entry parentMenuEntry = new Entry();
final JMenu parentMenu = new JMenu();
new EntryAccessor().setComponent(parentMenuEntry, parentMenu);
parentMenuEntry.addChild(menuEntry);
menuEntr... |
public static PositionBound at(final Position position) {
return new PositionBound(position);
} | @Test
public void shouldNotHash() {
final PositionBound bound = PositionBound.at(Position.emptyPosition());
assertThrows(UnsupportedOperationException.class, bound::hashCode);
// going overboard...
final HashSet<PositionBound> set = new HashSet<>();
assertThrows(UnsupportedO... |
@Override
public List<DeptDO> getDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return deptMapper.selectBatchIds(ids);
} | @Test
public void testGetDeptList_ids() {
// mock 数据
DeptDO deptDO01 = randomPojo(DeptDO.class);
deptMapper.insert(deptDO01);
DeptDO deptDO02 = randomPojo(DeptDO.class);
deptMapper.insert(deptDO02);
// 准备参数
List<Long> ids = Arrays.asList(deptDO01.getId(), dept... |
@Override
public int size() {
return eventHandler.size();
} | @Test
public void testInterruptedWithDeferredEvents() throws Exception {
CompletableFuture<Void> cleanupFuture = new CompletableFuture<>();
try (KafkaEventQueue queue = new KafkaEventQueue(Time.SYSTEM, logContext, "testInterruptedWithDeferredEvents", () -> cleanupFuture.complete(null))) {
... |
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
final HttpServletResponse resp = (HttpServletResponse) respo... | @Test
void setsACacheHeaderOnTheResponse() throws Exception {
filter.doFilter(request, response, chain);
final InOrder inOrder = inOrder(response, chain);
inOrder.verify(response).setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
inOrder.verify(chain).doFilter(request... |
@Override
public String brokerSetIdForReplica(final Replica replica, final ClusterModel clusterModel,
final BrokerSetResolutionHelper brokerSetResolutionHelper) throws ReplicaToBrokerSetMappingException {
String topicName = replica.topicPartition().topic();
Map<String, S... | @Test
public void testSingleBrokerSetMappingPolicy() throws BrokerSetResolutionException, ReplicaToBrokerSetMappingException {
ClusterModel clusterModel = DeterministicCluster.brokerSetSatisfiable1();
Map<String, Set<Integer>> testSingleBrokerSetMapping = Collections.singletonMap("BS1", Set.of(0, 1, 2, 3, 4, ... |
@Override
public void execute() {
invokeMethod();
} | @Test
void can_create_with_no_argument() throws Throwable {
Method method = JavaStaticHookDefinitionTest.class.getMethod("no_arguments");
JavaStaticHookDefinition definition = new JavaStaticHookDefinition(method, 0, lookup);
definition.execute();
assertTrue(invoked);
} |
@Override
public Object initialize(Object obj) {
if (obj instanceof HazelcastInstanceAware aware) {
aware.setHazelcastInstance(instance);
}
if (obj instanceof NodeAware aware) {
aware.setNode(instance.node);
}
if (obj instanceof SerializationServiceAwa... | @Test
public void testInitialize() {
DependencyInjectionUserClass initializedUserClass = (DependencyInjectionUserClass) serializationService.getManagedContext().initialize(userClass);
assertEquals(hazelcastInstance, initializedUserClass.hazelcastInstance);
assertEquals(node, initializedUser... |
static int validatePubsubMessageSize(PubsubMessage message, int maxPublishBatchSize)
throws SizeLimitExceededException {
int payloadSize = message.getPayload().length;
if (payloadSize > PUBSUB_MESSAGE_DATA_MAX_BYTES) {
throw new SizeLimitExceededException(
"Pubsub message data field of len... | @Test
public void testValidatePubsubMessageSizeOnlyPayload() throws SizeLimitExceededException {
byte[] data = new byte[1024];
PubsubMessage message = new PubsubMessage(data, null);
int messageSize =
PreparePubsubWriteDoFn.validatePubsubMessageSize(message, PUBSUB_MESSAGE_MAX_TOTAL_SIZE);
as... |
@Override
public String toString() {
return toString(true);
} | @Test
public void testToString() {
long length = 11111;
long fileCount = 22222;
long directoryCount = 33333;
long quota = 44444;
long spaceConsumed = 55555;
long spaceQuota = 66665;
ContentSummary contentSummary = new ContentSummary.Builder().length(length).
fileCount(fileCount).d... |
public Map<String, MetaProperties> logDirProps() {
return logDirProps;
} | @Test
public void testCopierWriteLogDirChanges() throws Exception {
MetaPropertiesEnsemble.Loader loader = new MetaPropertiesEnsemble.Loader();
loader.addMetadataLogDir(createLogDir(SAMPLE_META_PROPS_LIST.get(0)));
MetaPropertiesEnsemble ensemble = loader.load();
MetaPropertiesEnsemb... |
@VisibleForTesting
static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) {
ImmutableSortedMap.Builder<OffsetRange, Integer> rval =
ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE);
List<OffsetRange> sortedRanges = Lists.newArrayList(ranges);
if (... | @Test
public void testNoOverlapping() {
Iterable<OffsetRange> ranges = Arrays.asList(range(0, 2), range(4, 6));
Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition =
computeOverlappingRanges(ranges);
assertEquals(
ImmutableMap.of(range(0, 2), 1, range(4, 6), 1),
... |
protected void connect0(CertConfig certConfig) {
String caCertPath = certConfig.getCaCertPath();
String remoteAddress = certConfig.getRemoteAddress();
logger.info(
"Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress);
try {... | @Test
void testConnect1() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, null, null);
certManager.connect0(certConfig);
Assertions.ass... |
@Override
public String getSecurityName() {
return securityName;
} | @Test
public void testGetSecurityName() {
assertEquals(securityName, defaultSnmpv3Device.getSecurityName());
} |
public static WorkflowInstance.Status deriveAggregatedStatus(
MaestroWorkflowInstanceDao instanceDao,
WorkflowSummary summary,
WorkflowInstance.Status runStatus,
WorkflowRuntimeOverview overviewToUpdate) {
if (!summary.isFreshRun() && runStatus == WorkflowInstance.Status.SUCCEEDED) {
W... | @Test
public void testDeriveAggregatedStatus() {
WorkflowInstance instance =
getGenericWorkflowInstance(
2,
WorkflowInstance.Status.SUCCEEDED,
RunPolicy.RESTART_FROM_SPECIFIC,
RestartPolicy.RESTART_FROM_BEGINNING);
instance.getRuntimeDag().remove("step1"... |
static MapKeyLoader.Role assignRole(boolean isPartitionOwner, boolean isMapNamePartition,
boolean isMapNamePartitionFirstReplica) {
if (isMapNamePartition) {
if (isPartitionOwner) {
// map-name partition owner is the SENDER
retu... | @Test
public void assignRole_NONE_insignificantFlagFalse() {
boolean isPartitionOwner = false;
boolean isMapNamePartition = false;
boolean insignificant = false;
Role role = MapKeyLoaderUtil.assignRole(isPartitionOwner, isMapNamePartition, insignificant);
assertEquals(NONE,... |
@Override
public Iterator<T> iterator() {
return new LinkedSetIterator();
} | @Test
public void testRemoveMulti() {
LOG.info("Test remove multi");
for (Integer i : list) {
assertTrue(set.add(i));
}
for (int i = 0; i < NUM / 2; i++) {
assertTrue(set.remove(list.get(i)));
}
// the deleted elements should not be there
for (int i = 0; i < NUM / 2; i++) {
... |
public static boolean instanceOfSupportListMenuItemView(Object view) {
return ReflectUtil.isInstance(view, "android.support.v7.view.menu.ListMenuItemView");
} | @Test
public void instanceOfSupportListMenuItemView() {
CheckBox textView1 = new CheckBox(mApplication);
textView1.setText("child1");
Assert.assertFalse(SAViewUtils.instanceOfSupportListMenuItemView(textView1));
} |
public static FindKV findKV(String regex, int keyGroup, int valueGroup) {
return findKV(Pattern.compile(regex), keyGroup, valueGroup);
} | @Test
@Category(NeedsRunner.class)
public void testKVMatchesNameNone() {
PCollection<KV<String, String>> output =
p.apply(Create.of("x y z"))
.apply(Regex.findKV("a (?<keyname>b) (?<valuename>c)", "keyname", "valuename"));
PAssert.that(output).empty();
p.run();
} |
@Override
public int writeTo(TransferableChannel destChannel, int previouslyWritten, int remaining) throws IOException {
long position = this.position + previouslyWritten;
int count = Math.min(remaining, sizeInBytes() - previouslyWritten);
// safe to cast to int since `count` is an int
... | @Test
public void testWriteTo() throws IOException {
org.apache.kafka.common.requests.ByteBufferChannel channel = new org.apache.kafka.common.requests.ByteBufferChannel(fileRecords.sizeInBytes());
int size = fileRecords.sizeInBytes();
UnalignedFileRecords records1 = fileRecords.sliceUnalig... |
@Override
@Transactional
public boolean updateAfterApproval(Long userId, Integer userType, String clientId, Map<String, Boolean> requestedScopes) {
// 如果 requestedScopes 为空,说明没有要求,则返回 true 通过
if (CollUtil.isEmpty(requestedScopes)) {
return true;
}
// 更新批准的信息
... | @Test
public void testUpdateAfterApproval_reject() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String clientId = randomString();
Map<String, Boolean> requestedScopes = new LinkedHashMap<>();
requestedScopes.p... |
public static InetSocketAddress getInetSocketAddressFromRpcURL(String rpcURL) throws Exception {
// Pekko URLs have the form schema://systemName@host:port/.... if it's a remote Pekko URL
try {
final Address address = getAddressFromRpcURL(rpcURL);
if (address.host().isDefined() &... | @Test
void getHostFromRpcURLReturnsHostAfterAtSign() throws Exception {
final String url = "pekko.tcp://flink@localhost:1234/user/jobmanager";
final InetSocketAddress expected = new InetSocketAddress("localhost", 1234);
final InetSocketAddress result = PekkoUtils.getInetSocketAddressFromRpc... |
private void processNestedMap(Map<String, Object> map) {
for(String key : map.keySet()) {
String value = (String) map.get(key);
if (value.contains("\n")) {
Object valueObject = processNestedString(value);
map.put(key, valueObject);
}
}
... | @Test
public void testProcessNestedMap() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("test1",
"\n" +
" languages:\n" +
" - Ruby\n" +
" - Perl\n" +
" - Python \n" +
" w... |
@Override
public void dump(OutputStream output) {
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
for (long value : values) {
out.printf("%d%n", value);
}
}
} | @Test
public void dumpsToAStream() throws Exception {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
snapshot.dump(output);
assertThat(output.toString())
.isEqualTo(String.format("1%n2%n3%n4%n5%n"));
} |
@Override
public <T> ReducingState<T> getReducingState(ReducingStateDescriptor<T> stateProperties) {
KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties);
stateProperties.initializeSerializerUnlessSet(this::createSerializer);
return keyedStateStore.getRe... | @Test
void testV2ReducingStateInstantiation() throws Exception {
final ExecutionConfig config = new ExecutionConfig();
SerializerConfig serializerConfig = config.getSerializerConfig();
serializerConfig.registerKryoType(Path.class);
final AtomicReference<Object> descriptorCapture = n... |
@SuppressWarnings("unchecked")
public static D2CanaryDistributionStrategy toConfig(CanaryDistributionStrategy properties)
{
D2CanaryDistributionStrategy config = new D2CanaryDistributionStrategy();
StrategyType type = strategyTypes.get(properties.getStrategy());
if (type == null)
{
LOG.warn("U... | @Test(dataProvider = "getEdgeCasesDistributionPropertiesAndConfigs")
public void testToConfigEdgeCases(String strategyType, Map<String, Object> percentageProperties, Map<String, Object> targetHostsProperties,
Map<String, Object> targetAppsProperties, D2CanaryDistributionStrategy expect... |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new ... | @Test
public void testParseStepParameterWith4Underscore() {
StringParameter bar =
StringParameter.builder().name("bar").expression("_step1____foo + '-1';").build();
paramEvaluator.parseStepParameter(
Collections.singletonMap("_step1_", Collections.emptyMap()),
Collections.emptyMap(),
... |
@Override public FilterBindings get() { return filterBindings; } | @Test
void requireThatCorrectlyConfiguredFiltersAreIncluded() {
final String requestFilter1Id = "requestFilter1";
final String requestFilter2Id = "requestFilter2";
final String requestFilter3Id = "requestFilter3";
final String responseFilter1Id = "responseFilter1";
final Stri... |
@Nullable
static ProxyProvider createFrom(Properties properties) {
Objects.requireNonNull(properties, "properties");
if (properties.containsKey(HTTP_PROXY_HOST) || properties.containsKey(HTTPS_PROXY_HOST)) {
return createHttpProxyFrom(properties);
}
if (properties.containsKey(SOCKS_PROXY_HOST)) {
return... | @Test
void proxyFromSystemProperties_errorWhenSocksPortIsNotANumber() {
Properties properties = new Properties();
properties.setProperty(ProxyProvider.SOCKS_PROXY_HOST, "host");
properties.setProperty(ProxyProvider.SOCKS_PROXY_PORT, "8080Hello");
assertThatIllegalArgumentException()
.isThrownBy(() -> Prox... |
public boolean liveness() {
if (!Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(webServerStatusNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(ceStatusNodeCheck.check().getStatu... | @Test
public void fail_when_es_check_fail() {
when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN);
when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN);
when(ceStatusNodeCheck.check()).thenReturn(Health.GREEN);
when(esStatusNodeCheck.check()).thenReturn(RED);
Assertions.assert... |
public String toSnapshot(boolean hOption) {
return String.format(SNAPSHOT_FORMAT, formatSize(snapshotLength, hOption),
formatSize(snapshotFileCount, hOption),
formatSize(snapshotDirectoryCount, hOption),
formatSize(snapshotSpaceConsumed, hOption));
} | @Test
public void testToSnapshotHumanReadable() {
long snapshotLength = Long.MAX_VALUE;
long snapshotFileCount = 222222222;
long snapshotDirectoryCount = 33333;
long snapshotSpaceConsumed = 222256578;
ContentSummary contentSummary = new ContentSummary.Builder()
.snapshotLength(snapshotLen... |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastString() {
// When:
final BigDecimal decimal = DecimalUtil.cast("1.1", 3, 2);
// Then:
assertThat(decimal, is(new BigDecimal("1.10")));
} |
public static byte[] scrambleCachingSha2(byte[] password, byte[] seed) throws DigestException {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException ex) {
throw new DigestException(ex);
}
byte[] dig1 = new b... | @Test
public void testScrambleCachingSha2() throws DigestException {
byte[] bytes1 = new byte[]{73, -38, 6, -106, 14, -28, -98, -32,
-80, -49, -88, -66, -116, -101, -86, 25, -7, 32, 44, -118,
24, -128, -8, 12, 10, -38, 111, -11, 42, -111, 43, -123};
byte[] bytes2 = n... |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_UINT16_BE() {
final MutableData data = new MutableData(new byte[2]);
data.setValue(26576, Data.FORMAT_UINT16_BE, 0);
assertArrayEquals(new byte[] { 0x67, (byte) 0xD0 } , data.getValue());
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback connectionCallback) throws BackgroundException {
final MantaHttpHeaders headers = new MantaHttpHeaders();
try {
try {
if(status.isAppend()) {
final... | @Test
public void testReadRangeUnknownLength() throws Exception {
final Path drive = new MantaDirectoryFeature(session).mkdir(randomDirectory(), new TransferStatus());
final Path test = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new MantaTouc... |
public static Config loadFromStream(InputStream source) {
return loadFromStream(source, System.getProperties());
} | @Test
public void testLoadFromStream() {
InputStream xmlStream = new ByteArrayInputStream(
getSimpleXmlConfigStr(
"instance-name", "hz-instance-name",
"cluster-name", "${cluster.name}"
).getBytes()
);
InputStrea... |
public String csvCpeConfidence(Set<Identifier> ids) {
if (ids == null || ids.isEmpty()) {
return "\"\"";
}
boolean addComma = false;
final StringBuilder sb = new StringBuilder();
for (Identifier id : ids) {
if (addComma) {
sb.append(", ");
... | @Test
public void testCsvCpeConfidence() {
EscapeTool instance = new EscapeTool();
Set<Identifier> ids = null;
String expResult = "\"\"";
String result = instance.csvCpeConfidence(ids);
assertEquals(expResult, result);
ids = new HashSet<>();
expResult = "\"\"... |
@VisibleForTesting
Path getStagingDir(FileSystem defaultFileSystem) throws IOException {
final String configuredStagingDir =
flinkConfiguration.get(YarnConfigOptions.STAGING_DIRECTORY);
if (configuredStagingDir == null) {
return defaultFileSystem.getHomeDirectory();
... | @Test
void testGetStagingDirWithoutSpecifyingStagingDir() throws IOException {
try (final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptor()) {
YarnConfiguration yarnConfig = new YarnConfiguration();
yarnConfig.set("fs.defaultFS", "file://tmp");
F... |
public static boolean isEIP3668(String data) {
if (data == null || data.length() < 10) {
return false;
}
return EnsUtils.EIP_3668_CCIP_INTERFACE_ID.equals(data.substring(0, 10));
} | @Test
void isEIP3668WhenNotRightPrefix() {
assertFalse(EnsUtils.isEIP3668("123456789012"));
} |
@Udf(description = "Returns the inverse (arc) tangent of y / x")
public Double atan2(
@UdfParameter(
value = "y",
description = "The ordinate (y) coordinate."
) final Integer y,
@UdfParameter(
value = "x",
descriptio... | @Test
public void shouldHandlePositiveYNegativeX() {
assertThat(udf.atan2(1.1, -0.24), closeTo(1.7856117271965553, 0.000000000000001));
assertThat(udf.atan2(6.0, -7.1), closeTo(2.4399674339361113, 0.000000000000001));
assertThat(udf.atan2(2, -3), closeTo(2.5535900500422257, 0.000000000000001));
assert... |
@Override
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
StringBuilder sb = new StringBuilder();
long timestamp = event.getTimeStamp();
sb.append(cachingDateFormatter.format(timestamp));
sb.append("... | @Test
public void nullMessage() {
LoggingEvent event = new LoggingEvent("", logger, Level.INFO, null, null, null);
event.setTimeStamp(0);
String result = layout.doLayout(event);
String resultSuffix = result.substring(13).trim();
assertTrue(resultSuffix.matches("\\[.*\\] INF... |
@Override
@Transactional(value="defaultTransactionManager")
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException {
if (Strings.isNullOrEmpty(refreshTokenValue)) {
// throw an invalid token exception if there's no refresh token val... | @Test
public void refreshAccessToken_expiration() {
Integer accessTokenValiditySeconds = 3600;
when(client.getAccessTokenValiditySeconds()).thenReturn(accessTokenValiditySeconds);
long start = System.currentTimeMillis();
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenReque... |
@Override
public void upload(final List<Image> images, final List<MultipartFile> fileImages) {
IntStream.range(0, images.size())
.forEach(index -> saveFile(
fileImages.get(index),
images.get(index).getUniqueName()
));
} | @Test
void 이미지를_업로드한다() {
// given
List<Image> images = List.of(이미지를_생성한다());
List<MultipartFile> fileImages = List.of(file);
// when & then
assertDoesNotThrow(() -> imageUploader.upload(images, fileImages));
} |
public List<LispAfiAddress> getAddresses() {
return ImmutableList.copyOf(addresses);
} | @Test
public void testConstruction() {
LispListLcafAddress listLcafAddress = address1;
LispAfiAddress ipv4Address1 = new LispIpv4Address(IpAddress.valueOf("192.168.1.1"));
LispAfiAddress ipv6Address1 = new LispIpv6Address(IpAddress.valueOf("1111:2222:3333:4444:5555:6666:7777:8885"));
... |
@RequiresApi(Build.VERSION_CODES.R)
@Override
public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions();
if (inlineSuggestions.size() > 0) {
mInlineSuggestionAction.onNewSuggestions(inline... | @Test
public void testActionStripAdded() {
simulateOnStartInputFlow();
mAnySoftKeyboardUnderTest.onInlineSuggestionsResponse(
mockResponse(Mockito.mock(InlineContentView.class)));
Assert.assertNotNull(
mAnySoftKeyboardUnderTest
.getInputViewContainer()
.findViewById... |
public static byte[] toBytes(int val) {
byte[] b = new byte[4];
for (int i = 3; i > 0; i--) {
b[i] = (byte) val;
val >>>= 8;
}
b[0] = (byte) val;
return b;
} | @Test
public void testToBytes() {
assertArrayEquals(new byte[] {0, 0, 0, 20}, IOUtils.toBytes(20));
assertArrayEquals(new byte[] {0x02, (byte) 0x93, (byte) 0xed, (byte) 0x88}, IOUtils.toBytes(43249032));
assertArrayEquals(new byte[] {0x19, (byte) 0x99, (byte) 0x9a, 0x61}, IOUtils.toBytes(Integer.MAX_VALUE... |
static final String generateForFunction(RuleBuilderStep step, FunctionDescriptor<?> function) {
return generateForFunction(step, function, 1);
} | @Test
public void generateFunctionWithSingleParamGeneration() {
RuleBuilderStep step = RuleBuilderStep.builder().function("function1")
.parameters(Map.of("required", "val1")).build();
final FunctionDescriptor<Boolean> descriptor = FunctionUtil.testFunction(
"function1... |
private boolean destination(Scanner scanner) {
scanner.whitespace();
Position start = scanner.position();
if (!LinkScanner.scanLinkDestination(scanner)) {
return false;
}
String rawDestination = scanner.getSource(start, scanner.position()).getContent();
desti... | @Test
public void testDestination() {
parse("[foo]: /url");
assertEquals(State.START_TITLE, parser.getState());
assertParagraphLines("", parser);
assertEquals(1, parser.getDefinitions().size());
assertDef(parser.getDefinitions().get(0), "foo", "/url", null);
parse("... |
@Override
public ManageSnapshots removeBranch(String name) {
updateSnapshotReferencesOperation().removeBranch(name);
return this;
} | @TestTemplate
public void testRemoveBranch() {
table.newAppend().appendFile(FILE_A).commit();
long snapshotId = table.currentSnapshot().snapshotId();
// Test a basic case of creating and then removing a branch and tag
table.manageSnapshots().createBranch("branch1", snapshotId).commit();
table.mana... |
@Override
public boolean remove(final Local file) {
return this.update(file, null);
} | @Test
public void testRemove() throws Exception {
final WorkspaceIconService s = new WorkspaceIconService();
final Local file = new Local(PreferencesFactory.get().getProperty("tmp.dir"),
UUID.randomUUID().toString());
assertFalse(s.remove(file));
LocalTouchFactory.get... |
public Value evalForValue(String exp) {
return context.eval(JS, exp);
} | @Test
void testJavaFunction() {
Value v = je.evalForValue("Java.type('com.intuit.karate.graal.StaticPojo').sayHello");
assertFalse(v.isMetaObject());
assertFalse(v.isHostObject());
assertTrue(v.canExecute());
} |
public static boolean allZeros(byte[] buf) {
return Arrays.areAllZeroes(buf, 0, buf.length);
} | @Test
void all_zeros_checks_length_and_array_contents() {
assertTrue(SideChannelSafe.allZeros(new byte[0]));
assertFalse(SideChannelSafe.allZeros(new byte[]{ 1 }));
assertTrue(SideChannelSafe.allZeros(new byte[]{ 0 }));
assertFalse(SideChannelSafe.allZeros(new byte[]{ 0, 0, 127, 0 })... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testIntegerEq() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, equal("id", INT_MIN_VALUE - 25)).eval(FILE);
assertThat(shouldRead).as("Should not read: id below lower bound").isFalse();
shouldRead = new InclusiveMetricsEvaluator(SCHEMA, equal("id", INT_MIN_VALUE - ... |
public static SanitizerConfig load() {
return new SanitizerConfig(CONFIG_NAME);
} | @Test
public void testLoad() {
SanitizerConfig config = SanitizerConfig.load();
assert(config != null);
} |
@Override
public ReadBufferResult readBuffer(
TieredStoragePartitionId partitionId,
TieredStorageSubpartitionId subpartitionId,
int segmentId,
int bufferIndex,
MemorySegment memorySegment,
BufferRecycler recycler,
@Nullable ReadProg... | @Test
void testReadBuffer() throws IOException {
for (int subpartitionId = 0; subpartitionId < DEFAULT_NUM_SUBPARTITION; ++subpartitionId) {
for (int segmentId = 0; segmentId < DEFAULT_SEGMENT_NUM; ++segmentId) {
for (int bufferIndex = 0; bufferIndex < DEFAULT_BUFFER_PER_SEGMENT;... |
@Override
protected double maintain() {
List<Node> provisionedSnapshot;
try {
NodeList nodes;
// Host and child nodes are written in separate transactions, but both are written while holding the
// unallocated lock. Hold the unallocated lock while reading nodes to... | @Test
public void deprovision_node_when_no_allocation_and_past_ttl() {
tester = new DynamicProvisioningTester();
ManualClock clock = (ManualClock) tester.nodeRepository.clock();
tester.hostProvisioner.with(Behaviour.failProvisioning);
tester.provisioningTester.makeReadyHosts(2, new N... |
@Override
public void doRegister(@NonNull ThreadPoolPluginSupport support) {
enableThreadPoolPluginRegistrars.values().forEach(registrar -> registrar.doRegister(support));
enableThreadPoolPlugins.values().forEach(support::tryRegister);
} | @Test
public void testDoRegister() {
GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager();
manager.enableThreadPoolPlugin(new TestPlugin("1"));
manager.enableThreadPoolPlugin(new TestPlugin("2"));
manager.enableThreadPoolPluginRegistrar(new TestRegistrar... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
locks.computeIfAbsent(msg.getOriginator(), SemaphoreWithTbMsgQueue::new)
.addToQueueAndTryProcess(msg, ctx, this::processMsgAsync);
} | @Test
public void test_sqrt_5_to_attribute_and_metadata() {
var node = initNode(TbRuleNodeMathFunctionType.SQRT,
new TbMathResult(TbMathArgumentType.ATTRIBUTE, "result", 3, false, true, DataConstants.SERVER_SCOPE),
new TbMathArgument(TbMathArgumentType.MESSAGE_BODY, "a")
... |
@Override
public boolean acquirePermit(String nsId) {
if (contains(nsId)) {
return super.acquirePermit(nsId);
}
return super.acquirePermit(DEFAULT_NS);
} | @Test
public void testHandlerAllocationPreconfigured() {
Configuration conf = createConf(40);
conf.setDouble(DFS_ROUTER_FAIR_HANDLER_PROPORTION_KEY_PREFIX + "ns1", 0.5);
RouterRpcFairnessPolicyController routerRpcFairnessPolicyController =
FederationUtil.newFairnessPolicyController(conf);
// ... |
void badRequest(String s) {
setStatus(HttpServletResponse.SC_BAD_REQUEST);
String title = "Bad request: ";
setTitle((s != null) ? join(title, s) : title);
} | @Test
public void testBadRequestWithNullMessage() {
// It should not throw NullPointerException
appController.badRequest(null);
verifyExpectations(StringUtils.EMPTY);
} |
public Optional<GroupDto> findGroup(DbSession dbSession, String groupName) {
return dbClient.groupDao().selectByName(dbSession, groupName);
} | @Test
public void findGroup_whenGroupDoesntExist_returnsEmtpyOptional() {
when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME))
.thenReturn(Optional.empty());
assertThat(groupService.findGroup(dbSession, GROUP_NAME)).isEmpty();
} |
public static FallbackMethod create(String fallbackMethodName, Method originalMethod,
Object[] args, Object original, Object proxy) throws NoSuchMethodException {
MethodMeta methodMeta = new MethodMeta(
fallbackMethodName,
originalMethod.getParamet... | @Test
public void notFoundFallbackMethod_shouldThrowsNoSuchMethodException() throws Throwable {
FallbackMethodTest target = new FallbackMethodTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
assertThatThrownBy(
() -> FallbackMethod.create("noMe... |
@Override
public SecretsPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
String pluginId = descriptor.id();
return new SecretsPluginInfo(descriptor, securityConfigSettings(pluginId), image(pluginId));
} | @Test
public void shouldBuildPluginInfoWithPluginDescriptor() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
SecretsPluginInfo pluginInfo = new SecretsPluginInfoBuilder(extension).pluginInfoFor(descriptor);
assertThat(pluginInfo.getDescriptor(), is(de... |
protected final AnyKeyboardViewBase getMiniKeyboard() {
return mMiniKeyboard;
} | @Test
public void testLongPressWhenNoPrimaryKeyButTextShouldOpenMiniKeyboard() throws Exception {
ExternalAnyKeyboard anyKeyboard =
new ExternalAnyKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
keyboard_with_keys_w... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testValueEmpty() throws Exception {
JmxCollector jc =
new JmxCollector(
"\n---\nrules:\n- pattern: `.*`\n name: foo\n value:"
.replace('`', '"'))
.register(prometheusRegistry);... |
public Object execute(ProceedingJoinPoint proceedingJoinPoint, Method method, String fallbackMethodValue, CheckedSupplier<Object> primaryFunction) throws Throwable {
String fallbackMethodName = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), fallbackMethodValue);
FallbackMethod fallbackMeth... | @Test
public void testPrimaryMethodExecutionWithFallback() throws Throwable {
Method method = this.getClass().getMethod("getName", String.class);
final CheckedSupplier<Object> primaryFunction = () -> getName("Name");
final String fallbackMethodValue = "getNameValidFallback";
when(pr... |
static int loadRequiredIntProp(
Properties props,
String keyName
) {
String value = props.getProperty(keyName);
if (value == null) {
throw new RuntimeException("Failed to find " + keyName);
}
try {
return Integer.parseInt(value);
} catc... | @Test
public void loadNonIntegerRequiredIntProp() {
Properties props = new Properties();
props.setProperty("foo.bar", "b");
assertEquals("Unable to read foo.bar as a base-10 number.",
assertThrows(RuntimeException.class,
() -> PropertiesUtils.loadRequiredIntProp(p... |
@Override
public Object plugin(final Object target) {
return Plugin.wrap(target, this);
} | @Test
public void pluginTest() {
final PostgreSqlUpdateInterceptor postgreSqlUpdateInterceptor = new PostgreSqlUpdateInterceptor();
Assertions.assertDoesNotThrow(() -> postgreSqlUpdateInterceptor.plugin(new Object()));
} |
public static Node build(final List<JoinInfo> joins) {
Node root = null;
for (final JoinInfo join : joins) {
if (root == null) {
root = new Leaf(join.getLeftSource());
}
if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) {
throw new K... | @Test
public void shouldComputeEquivalenceSetWithoutOverlap() {
// Given:
when(j1.getLeftSource()).thenReturn(a);
when(j1.getRightSource()).thenReturn(b);
when(j2.getLeftSource()).thenReturn(a);
when(j2.getRightSource()).thenReturn(c);
when(j1.getLeftJoinExpression()).thenReturn(e1);
when... |
@Operation(summary = "queryWorkflowInstanceById", description = "QUERY_WORKFLOW_INSTANCE_BY_ID")
@Parameters({
@Parameter(name = "workflowInstanceId", description = "WORKFLOW_INSTANCE_ID", schema = @Schema(implementation = Integer.class, example = "123456", required = true))
})
@GetMapping(value... | @Test
public void testQueryWorkflowInstanceById() {
User loginUser = getLoginUser();
Map<String, Object> result = new HashMap<>();
result.put(DATA_LIST, new ProcessInstance());
putMsg(result, Status.SUCCESS);
Mockito.when(processInstanceService.queryProcessInstanceById(any(... |
public String toStringNoColon() {
final StringBuilder builder = new StringBuilder();
for (final byte b : this.address) {
builder.append(String.format("%02X", b & 0xFF));
}
return builder.toString();
} | @Test
public void testToStringNoColon() throws Exception {
assertEquals(MAC_ONOS_STR_NO_COLON, MAC_ONOS.toStringNoColon());
} |
public static StructType partitionType(Table table) {
Collection<PartitionSpec> specs = table.specs().values();
return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
} | @Test
public void testPartitionTypeWithAddingBackSamePartitionFieldInV2Table() {
TestTables.TestTable table =
TestTables.create(tableDir, "test", SCHEMA, BY_DATA_SPEC, V2_FORMAT_VERSION);
table.updateSpec().removeField("data").commit();
table.updateSpec().addField("data").commit();
// in v2... |
@Udf
public Long trunc(@UdfParameter final Long val) {
return val;
} | @Test
public void shouldTruncateSimpleBigDecimalNegative() {
assertThat(udf.trunc(new BigDecimal("-1.23")), is(new BigDecimal("-1")));
assertThat(udf.trunc(new BigDecimal("-1.0")), is(new BigDecimal("-1")));
assertThat(udf.trunc(new BigDecimal("-1.5")), is(new BigDecimal("-1")));
assertThat(udf.trunc(... |
@Override
public void handle(ContainersLauncherEvent event) {
// TODO: ContainersLauncher launches containers one by one!!
Container container = event.getContainer();
ContainerId containerId = container.getContainerId();
switch (event.getType()) {
case LAUNCH_CONTAINER:
Application app =... | @SuppressWarnings("unchecked")
@Test
public void testRelaunchContainerEvent()
throws IllegalArgumentException {
Map<ContainerId, ContainerLaunch> dummyMap = spy.running;
when(event.getType())
.thenReturn(ContainersLauncherEventType.RELAUNCH_CONTAINER);
assertEquals(0, dummyMap.size());
... |
public void inviteDirectly(EntityBareJid address) throws NotConnectedException, InterruptedException {
inviteDirectly(address, null, null, false, null);
} | @Test
public void testInviteDirectly() throws Throwable {
EntityBareJid roomJid = JidCreate.entityBareFrom("room@example.com");
EntityBareJid userJid = JidCreate.entityBareFrom("user@example.com");
AtomicBoolean updateRequestSent = new AtomicBoolean();
InvokeDirectlyResponder server... |
public static KiePMMLDroolsAST getKiePMMLDroolsAST(final List<Field<?>> fields,
final TreeModel model,
final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap,
... | @Test
void getKiePMMLDroolsIrisAST() {
final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = getFieldTypeMap(irisPmml.getDataDictionary(), irisPmml.getTransformationDictionary(), irisModel.getLocalTransformations());
List<KiePMMLDroolsType> types = Collections.emptyList();
KieP... |
@Override
public Reiterator<Object> get(int tag) {
return new SubIterator(tag);
} | @Test
public void testPartialIteration() {
TaggedReiteratorList iter = create(6, new String[] {"a", "b", "c"});
Iterator<?> get0 = iter.get(0);
Iterator<?> get1 = iter.get(1);
Iterator<?> get3 = iter.get(3);
assertEquals(asList(get0, 1), "a0");
assertEquals(asList(get1, 2), "a1", "b1");
as... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Optional<ValueRange> valueRange = getValueRangeBody(message);
String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString();
String majorDimension = message
... | @Test
public void testTransformToValueRangeMultipleColumns() throws Exception {
Exchange inbound = new DefaultExchange(camelContext);
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:B2");
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX... |
EventLoopGroup getSharedOrCreateEventLoopGroup(EventLoopGroup eventLoopGroupShared) {
if (eventLoopGroupShared != null) {
return eventLoopGroupShared;
}
return this.eventLoopGroup = new NioEventLoopGroup();
} | @Test
public void givenNull_whenGetEventLoop_ThenReturnShared() {
eventLoop = client.getSharedOrCreateEventLoopGroup(null);
assertThat(eventLoop, instanceOf(NioEventLoopGroup.class));
} |
public static NetworkMultiplexer dedicated(Network net) {
return new NetworkMultiplexer(net, false);
} | @Test
void testDedicated() {
MockNetwork net = new MockNetwork();
MockOwner owner = new MockOwner();
NetworkMultiplexer dedicated = NetworkMultiplexer.dedicated(net);
assertEquals(Set.of(dedicated), net.attached);
assertEquals(Set.of(), net.registered);
assertFalse(ne... |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void ensure_order_type_reverse_is_used() {
RuntimeOptions options = parser
.parse("--order", "reverse")
.build();
Pickle a = createPickle("file:path/file1.feature", "a");
Pickle b = createPickle("file:path/file2.feature", "b");
assertThat(options... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PiOptionalFieldMatch that = (PiOptionalFieldMatch) o;
return Objects.equal(this.fieldId(), that.fieldId()... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(piOptionalFieldMatch1, sameAsPiOptionalFieldMatch1)
.addEqualityGroup(piOptionalFieldMatch2)
.testEquals();
} |
Bootstrap getBootstrap() {
return bootstrap;
} | @Test
void testSetKeepaliveOptionWithNioNotConfigurable() throws Exception {
assumeThat(keepaliveForNioConfigurable()).isFalse();
final Configuration config = new Configuration();
config.set(NettyShuffleEnvironmentOptions.TRANSPORT_TYPE, "nio");
config.set(NettyShuffleEnvironmentOpt... |
public BigInteger getD() {
return d;
} | @Test
public void shouldConvertPrivateFactor() {
assertEquals(D, new EcPrivateKey(new ECPrivateKeyParameters(D, PARAMS)).getD());
} |
protected static DataSource getDataSourceFromJndi( String dsName, Context ctx ) throws NamingException {
if ( Utils.isEmpty( dsName ) ) {
throw new NamingException( BaseMessages.getString( PKG, "DatabaseUtil.DSNotFound", String.valueOf( dsName ) ) );
}
Object foundDs = FoundDS.get( dsName );
if ( ... | @Test( expected = NamingException.class )
public void testNullName() throws NamingException {
DatabaseUtil.getDataSourceFromJndi( null, context );
} |
public void expand(String key, long value, RangeHandler rangeHandler, EdgeHandler edgeHandler) {
if (value < lowerBound || value > upperBound) {
// Value outside bounds -> expand to nothing.
return;
}
int maxLevels = value > 0 ? maxPositiveLevels : maxNegativeLevels;
... | @Test
void requireThatLargeRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = List.of(
"key=123456789012345670-123456789012345679",
"key=123456789012345600-123456789012345699",
... |
public static Stream<ItemSet> apply(FPTree tree) {
FPGrowth growth = new FPGrowth(tree);
return StreamSupport.stream(growth.spliterator(), false);
} | @Test
public void testSinglePath() {
System.out.println("single path");
FPTree tree = FPTree.of(1, itemsets2);
assertEquals(15, FPGrowth.apply(tree).count());
} |
@Override
public Num calculate(BarSeries series, Position position) {
if (position.isClosed()) {
final int exitIndex = position.getExit().getIndex();
final int entryIndex = position.getEntry().getIndex();
return series.numOf(exitIndex - entryIndex + 1);
}
... | @Test
public void calculateWithTwoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series));
... |
public static DateTimeFormatter createDateTimeFormatter(String format, Mode mode)
{
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
boolean formatContainsHourOfAMPM = false;
for (Token token : tokenize(format)) {
switch (token.getType()) {
case ... | @Test(expectedExceptions = PrestoException.class)
public void testInvalidTokenCreate1()
{
DateFormatParser.createDateTimeFormatter("ala", FORMATTER);
} |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
return this.processRequest(ctx.channel(), request, true);
} | @Test
public void testProcessRequest() throws RemotingCommandException {
RemotingCommand request = createPeekMessageRequest("group","topic",0);
GetMessageResult getMessageResult = new GetMessageResult();
getMessageResult.setStatus(GetMessageStatus.FOUND);
ByteBuffer bb = ByteBuffer.a... |
public ManagedProcess launch(AbstractCommand command) {
EsInstallation esInstallation = command.getEsInstallation();
if (esInstallation != null) {
cleanupOutdatedEsData(esInstallation);
writeConfFiles(esInstallation);
}
Process process;
if (command instanceof JavaCommand<?> javaCommand)... | @Test
public void temporary_properties_file_can_be_avoided() throws Exception {
File tempDir = temp.newFolder();
TestProcessBuilder processBuilder = new TestProcessBuilder();
ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, () -> processBuilder);
JavaCommand<JvmOptions<?>> comman... |
protected Object[] copyOrCloneArrayFromLoadFile( Object[] outputRowData, Object[] readrow ) {
// if readrow array is shorter than outputRowData reserved space, then we can not clone it because we have to
// preserve the outputRowData reserved space. Clone, creates a new array with a new length, equals to the
... | @Test
public void testCopyOrCloneArrayFromLoadFileWithBiggerSizedReadRowArray() {
int size = 5;
Object[] rowData = new Object[ size ];
Object[] readrow = new Object[ size + 1 ];
LoadFileInput loadFileInput = mock( LoadFileInput.class );
Mockito.when( loadFileInput.copyOrCloneArrayFromLoadFile( ro... |
@Override
public void add(Integer value) {
this.min = Math.min(this.min, value);
} | @Test
void testAdd() {
IntMinimum min = new IntMinimum();
min.add(1234);
min.add(9876);
min.add(-987);
min.add(-123);
assertThat(min.getLocalValue().intValue()).isEqualTo(-987);
} |
@Override
public synchronized Response handle(Request req) { // note the [synchronized]
if (corsEnabled && "OPTIONS".equals(req.getMethod())) {
Response response = new Response(200);
response.setHeader("Allow", ALLOWED_METHODS);
response.setHeader("Access-Control-Allow-Or... | @Test
void testGraalJavaClassLoading() {
background().scenario(
"pathMatches('/hello')",
"def Utils = Java.type('com.intuit.karate.core.MockUtils')",
"def response = Utils.testBytes"
);
request.path("/hello");
handle();
match(re... |
@JsonProperty
public String getId() {
return message.getId();
} | @Test
public void testGetId() throws Exception {
assertEquals(message.getId(), messageSummary.getId());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.