focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public TriRpcStatus withCause(Throwable cause) {
return new TriRpcStatus(this.code, cause, this.description);
} | @Test
void withCause() {
TriRpcStatus origin = TriRpcStatus.NOT_FOUND;
TriRpcStatus withCause = origin.withCause(new IllegalStateException("test"));
Assertions.assertNull(origin.cause);
Assertions.assertTrue(withCause.cause.getMessage().contains("test"));
} |
public boolean isFound() {
return found;
} | @Test
public void testCalcAverageSpeedDetails() {
Weighting weighting = new SpeedWeighting(carAvSpeedEnc);
Path p = new Dijkstra(pathDetailGraph, weighting, TraversalMode.NODE_BASED).calcPath(1, 5);
assertTrue(p.isFound());
Map<String, List<PathDetail>> details = PathDetailsFromEdg... |
@Override
public AppResponse process(Flow flow, ActivateAppRequest body) {
String decodedPin = ChallengeService.decodeMaskedPin(appSession.getIv(), appAuthenticator.getSymmetricKey(), body.getMaskedPincode());
if ((decodedPin == null || !Pattern.compile("\\d{5}").matcher(decodedPin).matches())) {
... | @Test
void processPendingRequestAccountAndAppFlow(){
Map<String, String> finishRegistrationResponse = Map.of(lowerUnderscore(STATUS), "PENDING",
lowerUnderscore(ACTIVATION_CODE), "abcd",
... |
@Override
public byte[] getBytes(final int columnIndex) throws SQLException {
return (byte[]) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, byte[].class), byte[].class);
} | @Test
void assertGetBytesWithColumnLabel() throws SQLException {
when(mergeResultSet.getValue(1, byte[].class)).thenReturn(new byte[]{(byte) 1});
assertThat(shardingSphereResultSet.getBytes("label"), is(new byte[]{(byte) 1}));
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void timeWindowZeroArgCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.windowedBy(TimeWindows.of(ofMillis(1)))
.count();
final Topology topology = builde... |
public String convert(Object o) {
StringBuilder buf = new StringBuilder();
Converter<Object> p = headTokenConverter;
while (p != null) {
buf.append(p.convert(o));
p = p.getNext();
}
return buf.toString();
} | @Test
public void date() {
Calendar cal = Calendar.getInstance();
cal.set(2003, 4, 20, 17, 55);
FileNamePattern pp = new FileNamePattern("foo%d{yyyy.MM.dd}", context);
assertEquals("foo2003.05.20", pp.convert(cal.getTime()));
pp = new FileNamePattern("foo%d{yyyy.MM.dd HH:mm}", context);
ass... |
public static boolean matchIpExpression(String pattern, String address) throws UnknownHostException {
if (address == null) {
return false;
}
String host = address;
int port = 0;
// only works for ipv4 address with 'ip:port' format
if (address.endsWith(":")) {... | @Test
void testMatchIpMatch() throws UnknownHostException {
assertTrue(NetUtils.matchIpExpression("192.168.1.*", "192.168.1.63", 90));
assertTrue(NetUtils.matchIpExpression("192.168.1.192/26", "192.168.1.199", 90));
} |
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
} | @Test
void parse() throws IOException {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource("classpath:/MybatisXMLConfigBuilderTest.xml");
MybatisXMLConfigBuilder builder = new MybatisXMLConfigBuilder(resource.getInputStream(), null);
Configura... |
@Override
public void verify(String value) {
long l = Long.parseLong(value);
if (l < min || l > max) {
throw new RuntimeException(format("value is not in range(%d, %d)", min, max));
}
} | @Test
public void verify_ValueLessThanMin_ThrowsRuntimeException() {
RuntimeException exception = assertThrows(RuntimeException.class, () -> longRangeAttribute.verify("-1"));
assertEquals("value is not in range(0, 100)", exception.getMessage());
} |
public static boolean createFile(final Path filePath) {
try {
final Path parent = filePath.getParent();
if (parent == null) {
return false;
}
if (Files.notExists(parent)) {
Files.createDirectories(parent);
}
... | @Test
void testCreateFileRealDir() {
Path realDirHistoryFile = Paths.get(realFolder.toFile().getPath(), "history.file");
CliUtils.createFile(realDirHistoryFile);
assertThat(Files.exists(realDirHistoryFile)).isTrue();
} |
@GetMapping("/by-namespace-and-releases-not-in")
public List<InstanceDTO> getByReleasesNotIn(@RequestParam("appId") String appId,
@RequestParam("clusterName") String clusterName,
@RequestParam("namespaceName") String namespace... | @Test
public void testGetByReleasesNotIn() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
long someReleaseId = 1;
long anotherReleaseId = 2;
String releaseIds = J... |
public PathAttributes deserialize(final T serialized) {
final Deserializer<T> dict = factory.create(serialized);
final PathAttributes attributes = new PathAttributes();
final String sizeObj = dict.stringForKey("Size");
if(sizeObj != null) {
attributes.setSize(Long.parseLong(s... | @Test
public void testSerializeHashCode() {
PathAttributes attributes = new PathAttributes();
attributes.setPermission(new Permission(644));
attributes.setDuplicate(true);
attributes.setVersionId("v-1");
attributes.setFileId("myUniqueId");
attributes.setDisplayname("m... |
@Override
public void close() {
this.displayResultExecutorService.shutdown();
} | @Test
void testFailedBatchResult() {
final Configuration testConfig = new Configuration();
testConfig.set(EXECUTION_RESULT_MODE, ResultMode.TABLEAU);
testConfig.set(RUNTIME_MODE, RuntimeExecutionMode.BATCH);
ResultDescriptor resultDescriptor =
new ResultDescriptor(Cli... |
public static L3ModificationInstruction modArpTha(MacAddress addr) {
checkNotNull(addr, "Dst l3 ARP address cannot be null");
return new ModArpEthInstruction(L3SubType.ARP_THA, addr);
} | @Test
public void testModArpThaMethod() {
final Instruction instruction = Instructions.modArpTha(mac1);
final L3ModificationInstruction.ModArpEthInstruction modArpEthInstruction =
checkAndConvert(instruction,
Instruction.Type.L3MODIFICATION,
... |
@Udf
public Integer length(@UdfParameter final String jsonArray) {
if (jsonArray == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonArray);
if (node.isMissingNode() || !node.isArray()) {
return null;
}
return node.size();
} | @Test
public void shouldReturnNullForNumber() {
// When:
final Integer result = udf.length("123");
// Then:
assertNull(result);
} |
@Override
public double sd() {
return PI_SQRT3 * scale;
} | @Test
public void testSd() {
System.out.println("sd");
LogisticDistribution instance = new LogisticDistribution(2.0, 1.0);
instance.rand();
assertEquals(Math.PI/Math.sqrt(3), instance.sd(), 1E-7);
} |
public static BigDecimal[] toDecimalArray(String name, Object value) {
try {
if (value instanceof BigDecimal[]) {
return (BigDecimal[]) value;
} else if (value instanceof double[]) {
return Arrays.stream((double[]) value)
.mapToObj(val -> new BigDecimal(String.valueOf(val)))
... | @Test
public void testDecimalArrayToDecimalArray() {
BigDecimal[] val =
new BigDecimal[] {new BigDecimal("1.2"), new BigDecimal("3.4"), new BigDecimal("5.6")};
BigDecimal[] actual = ParamHelper.toDecimalArray("foo", val);
assertArrayEquals(val, actual);
} |
@Override
public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) {
selectedBundlesCache.clear();
final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0;
final Map<String, Long> recentlyUnlo... | @Test
public void testBrokerWithMultipleBundles() {
int numBundles = 10;
LoadData loadData = new LoadData();
LocalBrokerData broker1 = new LocalBrokerData();
broker1.setBandwidthIn(new ResourceUsage(999, 1000));
broker1.setBandwidthOut(new ResourceUsage(999, 1000));
... |
public PipelineColumnMetaData getColumnMetaData(final int columnIndex) {
return getColumnMetaData(columnNames.get(columnIndex - 1));
} | @Test
void assertIsPrimaryKey() {
assertTrue(pipelineTableMetaData.getColumnMetaData(1).isUniqueKey());
} |
public static boolean isNotEmpty(Collection coll) {
return !CollectionUtils.isEmpty(coll);
} | @Test
void testIsNotEmpty() {
assertTrue(CollectionUtils.isNotEmpty(Collections.singletonList("target")));
assertFalse(CollectionUtils.isNotEmpty(Collections.emptyList()));
assertFalse(CollectionUtils.isNotEmpty(null));
} |
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) {
return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive();
} | @Test
public void smallGraph() {
// 3<-0->2-1
g.edge(0, 2).setDistance(1).set(speedEnc, 10, 0); // edge-keys 0,1
g.edge(0, 3).setDistance(1).set(speedEnc, 10, 0); // edge-keys 2,3
g.edge(2, 1).setDistance(1).set(speedEnc, 10, 10); // edge-keys 4,5
ConnectedComponents result =... |
@Override
@TpsControl(pointName = "ConfigPublish")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
@ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class)
public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta meta) throws NacosException {
... | @Test
void testPublishAggrCheckFail() throws NacosException, InterruptedException {
RequestMeta requestMeta = new RequestMeta();
String clientIp = "127.0.0.1";
requestMeta.setClientIp(clientIp);
String dataId = "testPublishAggrCheckFail";
String group = "gro... |
@VisibleForTesting
static String getProjectCacheDirectoryFromProject(Path path) {
try {
byte[] hashedBytes =
MessageDigest.getInstance("SHA-256")
.digest(path.toFile().getCanonicalPath().getBytes(Charsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder(2 * hashedBytes.... | @Test
public void testGetProjectCacheDirectoryFromProject_sameFileDifferentPaths() throws IOException {
temporaryFolder.newFolder("ignored");
Path path = temporaryFolder.getRoot().toPath();
Path indirectPath = temporaryFolder.getRoot().toPath().resolve("ignored").resolve("..");
assertThat(path).isNot... |
@Override
public EntityStatementJWS establishIdpTrust(URI issuer) {
var trustedFederationStatement = fetchTrustedFederationStatement(issuer);
// the federation statement from the master will establish trust in the JWKS and the issuer URL
// of the idp,
// we still need to fetch the entity configurat... | @Test
void establishTrust_badFedmasterConfigSignature() {
var client = new FederationMasterClientImpl(FEDERATION_MASTER, federationApiClient, clock);
var issuer = URI.create("https://idp-tk.example.com");
var fedmasterKeypair = ECKeyGenerator.example();
var unrelatedKeypair = ECKeyGenerator.generat... |
@Override
public ResourceAllocationResult tryFulfillRequirements(
Map<JobID, Collection<ResourceRequirement>> missingResources,
TaskManagerResourceInfoProvider taskManagerResourceInfoProvider,
BlockedTaskManagerChecker blockedTaskManagerChecker) {
final ResourceAllocation... | @Test
void testExcessPendingResourcesCouldReleaseEvenly() {
final JobID jobId = new JobID();
final List<ResourceRequirement> requirements = new ArrayList<>();
final TaskManagerResourceInfoProvider taskManagerResourceInfoProvider =
TestingTaskManagerResourceInfoProvider.newBui... |
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY);
} | @Test
public void testRule() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.... |
public Map<String, String> getTasksStates(String taskType)
throws IOException, HttpException {
HttpGet httpGet = createHttpGetRequest(MinionRequestURLBuilder.baseUrl(_controllerUrl).forTasksStates(taskType));
try (CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet)) {
int statusCode = resp... | @Test
public void testTasksStates()
throws IOException, HttpException {
HttpServer httpServer = startServer(14203, "/tasks/SegmentGenerationAndPushTask/taskstates",
createHandler(200, "{\"Task_SegmentGenerationAndPushTask_1607470525615\":\"IN_PROGRESS\"}", 0));
MinionClient minionClient = new Mi... |
@Override
public <K> HostToKeyMapper<K> getPartitionInformation(URI serviceUri, Collection<K> keys,
int limitHostPerPartition,
int hash)
throws ServiceUnavailableException
{
if (limitHostPer... | @Test
public void testGetPartitionInfoOrdering()
throws Exception
{
String serviceName = "articles";
String clusterName = "cluster";
String path = "path";
String strategyName = "degrader";
// setup 3 partitions. Partition 1 and Partition 2 both have server1 - server3. Partition 3 only has s... |
@Override
public ExportResult<MediaContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation)
throws UploadErrorException, FailedToListAlbumsException, InvalidTokenException, PermissionDeniedException, IOException, FailedToListMediaItemsExcepti... | @Test
public void testExportPhotosContainer_photosRetrying() throws IOException, InvalidTokenException, PermissionDeniedException, UploadErrorException, FailedToListAlbumsException, FailedToListMediaItemsException {
String photoIdToFail1 = "photo3";
String photoIdToFail2 = "photo5";
ImmutableList<PhotoAl... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatInnerJoin() {
final Join join = new Join(leftAlias, ImmutableList.of(new JoinedSource(
Optional.empty(),
rightAlias,
JoinedSource.Type.INNER,
criteria,
Optional.of(new WithinExpression(10, TimeUnit.SECONDS)))));
final String expected = "`l... |
@Override
public void onChange(List<JobRunrMetadata> metadataList) {
if (this.serversWithPollIntervalInSecondsTimeBoxTooSmallMetadataList == null || this.serversWithPollIntervalInSecondsTimeBoxTooSmallMetadataList.size() != metadataList.size()) {
problems.removeProblemsOfType(PollIntervalInSecon... | @Test
void ifNoChangesOnPollIntervalInSecondsTimeBoxIsTooSmallThenNoProblemsCreated() {
pollIntervalInSecondsTimeBoxIsTooSmallProblemHandler.onChange(emptyList());
verifyNoInteractions(problems);
} |
public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
return index(keyFunction, Function.identity());
} | @Test
public void index_empty_stream_returns_empty_map() {
assertThat(Stream.<MyObj>empty().collect(index(MyObj::getId)).size()).isZero();
assertThat(Stream.<MyObj>empty().collect(index(MyObj::getId, MyObj::getText)).size()).isZero();
} |
public static Set<HostInfo> getRemoteHosts(
final List<PersistentQueryMetadata> currentQueries,
final KsqlHostInfo localHost
) {
return currentQueries.stream()
// required filter else QueryMetadata.getAllMetadata() throws
.filter(q -> q.getState().isRunningOrRebalancing())
.ma... | @Test
public void shouldFilterQueryMetadataByState() {
// When:
final Set<HostInfo> info = DiscoverRemoteHostsUtil.getRemoteHosts(
ImmutableList.of(runningQuery, notRunningQuery),
THIS_HOST_INFO
);
// Then:
assertThat(info, contains(OTHER_HOST_INFO));
verify(notRunningQuery, ... |
public static RecordBatchingStateRestoreCallback adapt(final StateRestoreCallback restoreCallback) {
Objects.requireNonNull(restoreCallback, "stateRestoreCallback must not be null");
if (restoreCallback instanceof RecordBatchingStateRestoreCallback) {
return (RecordBatchingStateRestoreCallba... | @Test
public void shouldThrowOnRestoreAll() {
assertThrows(UnsupportedOperationException.class, () -> adapt(mock(StateRestoreCallback.class)).restoreAll(null));
} |
public void go(boolean shouldLoop, AgentBootstrapperArgs bootstrapperArgs) {
loop = shouldLoop;
launcherThread = Thread.currentThread();
validate();
cleanupTempFiles();
int returnValue = 0;
DefaultAgentLaunchDescriptorImpl descriptor = new DefaultAgentLaunchDescriptorIm... | @Test
@Timeout(10)
public void shouldNotRelaunchAgentLauncherWhenItReturnsAnIrrecoverableCode() {
final boolean[] destroyCalled = new boolean[1];
final AgentBootstrapper bootstrapper = new AgentBootstrapper(){
@Override
AgentLauncherCreator getLauncherCreator() {
... |
@VisibleForTesting
void handleResponse(DiscoveryResponseData response)
{
ResourceType resourceType = response.getResourceType();
switch (resourceType)
{
case NODE:
handleD2NodeResponse(response);
break;
case D2_URI_MAP:
handleD2URIMapResponse(response);
break;... | @Test
public void testHandleD2NodeUpdateWithEmptyResponse()
{
XdsClientImplFixture fixture = new XdsClientImplFixture();
fixture._xdsClientImpl.handleResponse(DISCOVERY_RESPONSE_WITH_EMPTY_NODE_RESPONSE);
fixture.verifyAckSent(1);
} |
public void execute() {
if (report.rules != null) {
importNewFormat();
} else {
importDeprecatedFormat();
}
} | @Test
public void execute_whenNewFormatWithZeroIssues() {
ExternalIssueReport report = new ExternalIssueReport();
ExternalIssueReport.Rule rule = createRule();
report.issues = new ExternalIssueReport.Issue[0];
report.rules = new ExternalIssueReport.Rule[]{rule};
ExternalIssueImporter underTest = ... |
public void updateToRemovedBlock(boolean add, long blockId) {
if (add) {
if (mBlocks.contains(blockId)) {
mToRemoveBlocks.add(blockId);
}
} else {
mToRemoveBlocks.remove(blockId);
}
} | @Test
public void updateToRemovedBlock() {
// remove a non-existing block
mInfo.updateToRemovedBlock(true, 10L);
assertTrue(mInfo.getToRemoveBlocks().isEmpty());
// remove block 1
mInfo.updateToRemovedBlock(true, 1L);
assertTrue(mInfo.getToRemoveBlocks().contains(1L));
// cancel the remova... |
List<StatisticsEntry> takeStatistics() {
if (reporterEnabled)
throw new IllegalStateException("Cannot take consistent snapshot while reporter is enabled");
var ret = new ArrayList<StatisticsEntry>();
consume((metric, value) -> ret.add(new StatisticsEntry(metric, value)));
ret... | @Test
void retrieving_statistics_resets_the_counters() {
testRequest("http", 200, "GET");
testRequest("http", 200, "GET");
var stats = collector.takeStatistics();
assertStatisticsEntry(stats, "http", "GET", MetricDefinitions.RESPONSES_2XX, "read", 200, 2L);
testRequest("htt... |
@Override
public String getAuthorizeUrl(Integer socialType, Integer userType, String redirectUri) {
// 获得对应的 AuthRequest 实现
AuthRequest authRequest = buildAuthRequest(socialType, userType);
// 生成跳转地址
String authorizeUri = authRequest.authorize(AuthStateUtils.createState());
r... | @Test
public void testGetAuthorizeUrl() {
try (MockedStatic<AuthStateUtils> authStateUtilsMock = mockStatic(AuthStateUtils.class)) {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(UserTypeEnum.class).getValue();
... |
@Override
public Optional<Object> invoke(Function<InvokerContext, Object> invokeFunc, Function<Throwable, Object> exFunc,
String serviceName) {
return invoke(invokeFunc, exFunc, serviceName, getRetry(null));
} | @Test
public void invokeWithNoInstances() {
Object exResult = new Object();
final Function<InvokerContext, Object> invokerFunc = invokerContext -> null;
final Function<Throwable, Object> exFunc = ex -> exResult;
Optional<Object> invoke = retryService.invoke(invokerFunc, exFunc, servi... |
public static long[] colSums(int[][] matrix) {
long[] x = new long[matrix[0].length];
for (int[] row : matrix) {
for (int j = 0; j < x.length; j++) {
x[j] += row[j];
}
}
return x;
} | @Test
public void testColSums() {
System.out.println("colSums");
double[][] A = {
{0.7220180, 0.07121225, 0.6881997},
{-0.2648886, -0.89044952, 0.3700456},
{-0.6391588, 0.44947578, 0.6240573}
};
double[] r = {-0.1820294, -0.3697615, 1.6823026};
... |
@Override
public Dimension render(Graphics2D graphics)
{
Font originalFont = null;
if (font != null)
{
originalFont = graphics.getFont();
graphics.setFont(font);
}
final FontMetrics fontMetrics = graphics.getFontMetrics();
Matcher matcher = COL_TAG_PATTERN.matcher(text);
Color textColor = color;... | @Test
public void testRender2()
{
TextComponent textComponent = new TextComponent();
textComponent.setText("<col=0000ff>test");
textComponent.render(graphics);
verify(graphics, times(2)).drawString(eq("test"), anyInt(), anyInt());
verify(graphics).setColor(Color.BLUE);
} |
public static void registerApplicationNodeInCollectServer(String applicationName,
URL collectServerUrl, URL applicationNodeUrl) {
if (collectServerUrl == null || applicationNodeUrl == null) {
throw new IllegalArgumentException(
"collectServerUrl and applicationNodeUrl must not be null");
}
final String... | @Test
public void testRegisterApplicationNodeInCollectServer() throws MalformedURLException {
MonitoringFilter.registerApplicationNodeInCollectServer(null,
new URL("http://localhost:8080"), new URL("http://localhost:8081"));
MonitoringFilter.registerApplicationNodeInCollectServer("test",
new URL("http://lo... |
public void registerBot(
String botPath,
Function<Update, BotApiMethod<?>> updateHandler,
Runnable setWebhook,
Runnable deleteWebhook
) throws TelegramApiException {
registerBot(DefaultTelegramWebhookBot
.builder()
.botPath(botP... | @Test
public void testWhenUpdateIsReceivedOnWebhookUpdateReceivedIsCalledOnCorrectBot() throws TelegramApiException, IOException {
application.registerBot(telegramWebhookBot);
TestTelegramWebhookBot telegramWebhookBot2 = new TestTelegramWebhookBot("/test2");
application.registerBot(telegramW... |
public static <T> T autobox(Object value, Class<T> type) {
return Autoboxer.autobox(value, type);
} | @Test
void testAutoboxClob() throws SQLException {
Clob clob = Mockito.mock(Clob.class);
String result = "the result";
Mockito.when(clob.length()).thenReturn((long) result.length());
Mockito.when(clob.getSubString(1, result.length())).thenReturn(result);
assertThat(Reflecti... |
@Override
public void removeSelector(final SelectorData selectorData) {
UpstreamCacheManager.getInstance().removeByKey(selectorData.getId());
CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(selectorData.getId(), Constants.DEFAULT_RULE));
} | @Test
public void testRemoveSelector() throws NoSuchFieldException, IllegalAccessException {
UpstreamCacheManager instance = UpstreamCacheManager.getInstance();
instance.submit("1", upstreamList);
Field field = instance.getClass().getDeclaredField("UPSTREAM_MAP");
field.setAccessible... |
@Override
public String getName() {
return name;
} | @Test
void shouldReturnRightName() {
assertEquals("fake-controller", controller.getName());
} |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/{executionId}/file/preview")
@Operation(tags = {"Executions"}, summary = "Get file preview for an execution")
public HttpResponse<?> filePreview(
@Parameter(description = "The execution id") @PathVariable String executionId,
@Parameter(description = ... | @Test
void filePreview() throws TimeoutException {
Execution defaultExecution = runnerUtils.runOne(null, TESTS_FLOW_NS, "inputs", null, (flow, execution1) -> flowIO.typedInputs(flow, execution1, inputs));
assertThat(defaultExecution.getTaskRunList(), hasSize(13));
String defaultPath = (Stri... |
@Override
public boolean othersDeletesAreVisible(final int type) {
return false;
} | @Test
void assertOthersDeletesAreVisible() {
assertFalse(metaData.othersDeletesAreVisible(0));
} |
public static int[] clone(int[] array) {
int[] clone = new int[array.length];
System.arraycopy(array, 0, clone, 0, array.length);
return clone;
} | @Test
public void testClone() {
assertArrayEquals(new int[]{3, 2, 1}, Replicas.clone(new int[]{3, 2, 1}));
assertArrayEquals(new int[]{}, Replicas.clone(new int[]{}));
assertArrayEquals(new int[]{2}, Replicas.clone(new int[]{2}));
} |
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
nonXmlCharFilterer.filter(text, start, len);
writer.writeCharacters(text, start, len);
} | @Test
public void testWriteCharacters3Args() throws XMLStreamException {
char[] buffer = new char[] { 'a', 'b', 'c' };
filteringXmlStreamWriter.writeCharacters(buffer, 2, 3);
verify(xmlStreamWriterMock).writeCharacters(same(buffer), eq(2), eq(3));
} |
public static Read read() {
// 1000 for batch size is good enough in many cases,
// ex: if document size is large, around 10KB, the response's size will be around 10MB
// if document seize is small, around 1KB, the response's size will be around 1MB
return new AutoValue_SolrIO_Read.Builder().setBatchSiz... | @Test
public void testRead() throws Exception {
SolrIOTestUtils.insertTestDocuments(SOLR_COLLECTION, NUM_DOCS, solrClient);
PCollection<SolrDocument> output =
pipeline.apply(
SolrIO.read()
.withConnectionConfiguration(connectionConfiguration)
.from(SOLR_COL... |
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC))
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericService.c... | @Test
void testInvokeWithJavaException() throws Exception {
// temporary enable native java generic serialize
System.setProperty(ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, "true");
Assertions.assertThrows(RpcException.class, () -> {
Method genericInvoke = GenericService.class.getMetho... |
protected String messageToString(Message message) {
switch (message.getMessageType()) {
case SYSTEM:
return message.getContent();
case USER:
return humanPrompt + message.getContent();
case ASSISTANT:
return assistantPrompt + mes... | @Test
public void testSingleAssistantMessage() {
Message assistantMessage = new AssistantMessage("Assistant message");
String expected = "Assistant message";
Assert.assertEquals(expected, converter.messageToString(assistantMessage));
} |
public static boolean isEnumCanonicalName(String className) {
return Enum.class.getCanonicalName().equals(className);
} | @Test
public void isEnumCanonicalName() {
assertThat(ScenarioSimulationSharedUtils.isEnumCanonicalName(Enum.class.getCanonicalName())).isTrue();
assertThat(ScenarioSimulationSharedUtils.isEnumCanonicalName(Enum.class.getSimpleName())).isFalse();
} |
@Override
public String getName() {
return FUNCTION_NAME;
} | @Test
public void testPowerNullColumn() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("power(%s,%s)", INT_SV_NULL_COLUMN, 0));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transformFunction inst... |
public <T extends VFSConnectionDetails> boolean test( @NonNull ConnectionManager manager,
@NonNull T details,
@Nullable VFSConnectionTestOptions options )
throws KettleException {
if ( options == nul... | @Test
public void testTestReturnsFalseWhenRootPathFileDoesNotExist() throws Exception {
when( connectionRootProviderFileObject.exists() ).thenReturn( false );
assertFalse( vfsConnectionManagerHelper.test( connectionManager, vfsConnectionDetails, getTestOptionsCheckRootPath() ) );
} |
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
addField(sb, "\"edition\": ", this.edition, true);
endString(sb);
return sb.toString();
} | @Test
void toStringHasEdition() {
LicenseNewValue newValue = new LicenseNewValue("Developer");
assertThat(newValue.toString()).contains("edition");
} |
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) {
final List<FieldInfo> allFields = schema.columns().stream()
.map(EntityUtil::toFieldInfo)
.collect(Collectors.toList());
if (allFields.isEmpty()) {
throw new IllegalArgumentException("Root schema should co... | @Test
public void shouldBuildCorrectMapField() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.valueColumn(ColumnName.of("field"), SqlTypes.map(SqlTypes.BIGINT, SqlTypes.INTEGER))
.build();
// When:
final List<FieldInfo> fields = EntityUtil.buildSourceSchemaEntity(sc... |
@Override
public ImportResult importItem(
UUID jobId,
IdempotentImportExecutor idempotentExecutor,
TokenSecretAuthData authData,
MediaContainerResource data)
throws Exception {
// Make the data smugmug compatible
data.transmogrify(transmogrificationConfig);
try {
Smug... | @Test
public void importStoresAlbumInJobStore() throws Exception {
// setup test objects
UUID jobId = UUID.randomUUID();
MediaAlbum mediaAlbum1 = new MediaAlbum("albumId1", "albumName1", "albumDescription1");
PhotoModel photoModel1 =
new PhotoModel(
"PHOTO_TITLE",
"FET... |
@Override
public Write.Append append(final Path file, final TransferStatus status) throws BackgroundException {
return new Write.Append(status.isExists()).withStatus(status);
} | @Test
public void testAppend() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback());... |
private void validateHmsUri(String catalogHmsUri) {
if (catalogHmsUri == null) {
return;
}
Configuration conf = SparkSession.active().sessionState().newHadoopConf();
String envHmsUri = conf.get(HiveConf.ConfVars.METASTOREURIS.varname, null);
if (envHmsUri == null) {
return;
}
P... | @Test
public void testValidateHmsUri() {
// HMS uris match
assertThat(spark.sessionState().catalogManager().v2SessionCatalog().defaultNamespace()[0])
.isEqualTo("default");
// HMS uris doesn't match
spark.sessionState().catalogManager().reset();
String catalogHmsUri = "RandomString";
... |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (boolean.class == type) {
return resultSet.getBoolean(columnIndex);
}
if (byte.class == type) {
return resultSet.getByte(columnIndex);
}
if (short.cla... | @Test
void assertGetValueByBytes() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
byte[] value = {(byte) 1};
when(resultSet.getBytes(1)).thenReturn(value);
assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, byte[].class), is(value));
} |
@Bean
public RateLimiterRegistry rateLimiterRegistry(
RateLimiterConfigurationProperties rateLimiterProperties,
EventConsumerRegistry<RateLimiterEvent> rateLimiterEventsConsumerRegistry,
RegistryEventConsumer<RateLimiter> rateLimiterRegistryEventConsumer,
@Qualifier("compositeRateLim... | @Test
public void testRateLimiterRegistry() {
io.github.resilience4j.common.ratelimiter.configuration.CommonRateLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new io.github.resilience4j.common.ratelimiter.configuration.CommonRateLimiterConfigurationProperties.InstanceProperties();
... |
@Override
public Long sendSingleNotifyToAdmin(Long userId, String templateCode, Map<String, Object> templateParams) {
return sendSingleNotify(userId, UserTypeEnum.ADMIN.getValue(), templateCode, templateParams);
} | @Test
public void testSendSingleNotifyToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock Notify... |
public FEELFnResult<Boolean> invoke(@ParameterName( "string" ) String string, @ParameterName( "match" ) String match) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
}
if ( match == null ) {
re... | @Test
void invokeParamsNull() {
FunctionTestUtil.assertResultError(endsWithFunction.invoke((String) null, null), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(endsWithFunction.invoke(null, "test"), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(endsWith... |
public static void checkNotNullAndNotEmpty(@Nullable String value, String propertyName) {
Preconditions.checkNotNull(value, "Property '" + propertyName + "' cannot be null");
Preconditions.checkArgument(
!value.trim().isEmpty(), "Property '" + propertyName + "' cannot be an empty string");
} | @Test
public void testCheckNotEmpty_collectionFailNull() {
try {
Validator.checkNotNullAndNotEmpty((Collection<?>) null, "test");
Assert.fail();
} catch (NullPointerException npe) {
Assert.assertEquals("Property 'test' cannot be null", npe.getMessage());
}
} |
DatanodeStorageInfo getStorageInfo(int index) {
assert this.triplets != null : "BlockInfo is not initialized";
assert index >= 0 && index * 3 < triplets.length : "Index is out of bound";
return (DatanodeStorageInfo)triplets[index * 3];
} | @Test
public void testReplaceStorage() throws Exception {
// Create two dummy storages.
final DatanodeStorageInfo storage1 = DFSTestUtil.createDatanodeStorageInfo(
"storageID1", "127.0.0.1");
final DatanodeStorageInfo storage2 = new DatanodeStorageInfo(
storage1.getDatanodeDescriptor(), n... |
@Subscribe
public void onGraphicChanged(GraphicChanged graphicChanged)
{
Player player = client.getLocalPlayer();
if (graphicChanged.getActor() != player)
{
return;
}
if (player.getGraphic() == GraphicID.WINE_MAKE && config.fermentTimer())
{
Optional<FermentTimer> fermentTimerOpt = infoBoxManager.... | @Test
public void testOnGraphicChanged()
{
Player player = mock(Player.class);
when(player.getGraphic()).thenReturn(GraphicID.WINE_MAKE);
when(config.fermentTimer()).thenReturn(true);
when(client.getLocalPlayer()).thenReturn(player);
GraphicChanged graphicChanged = new GraphicChanged();
graphicChanged.s... |
@Override
public String getDriverClass() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
} | @Test
public void testGetDriverClass() throws Exception {
assertEquals( "com.microsoft.sqlserver.jdbc.SQLServerDriver", dbMeta.getDriverClass() );
} |
@GuardedBy("lock")
private boolean isLeader(ResourceManager<?> resourceManager) {
return running && this.leaderResourceManager == resourceManager;
} | @Test
void grantLeadership_stopped_doesNotStartNewRm() throws Exception {
final CompletableFuture<UUID> startRmFuture = new CompletableFuture<>();
rmFactoryBuilder.setInitializeConsumer(startRmFuture::complete);
createAndStartResourceManager();
resourceManagerService.close();
... |
@Description("Returns the bounding rectangle of a Geometry expanded by distance.")
@ScalarFunction("expand_envelope")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice expandEnvelope(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(DOUBLE) double distance)
{
if (isNaN(distance)) {
t... | @Test
public void testExpandEnvelope()
{
assertFunction("ST_IsEmpty(expand_envelope(ST_GeometryFromText('POINT EMPTY'), 1))", BOOLEAN, true);
assertFunction("ST_IsEmpty(expand_envelope(ST_GeometryFromText('POLYGON EMPTY'), 1))", BOOLEAN, true);
assertFunction("ST_AsText(expand_envelope(S... |
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) {
if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) {
return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(),
schemaDefinition.getSchema... | @Test
public void testGetNativeSchema() throws SchemaValidationException {
AvroSchema<StructWithAnnotations> schema2 = AvroSchema.of(StructWithAnnotations.class);
org.apache.avro.Schema avroSchema2 = (Schema) schema2.getNativeSchema().get();
assertSame(schema2.schema, avroSchema2);
} |
DecodedJWT verifyJWT(PublicKey publicKey,
String publicKeyAlg,
DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new... | @Test
public void ensureFutureNBFFails() throws Exception {
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
addValidMandatoryClaims(defaultJwtBuilder, basicProviderAudience);
// Override the exp set in the ab... |
@InvokeOnHeader(CONTROL_ACTION_SUBSCRIBE)
public void performSubscribe(final Message message, AsyncCallback callback) {
String filterId;
if (message.getBody() instanceof DynamicRouterControlMessage) {
filterId = subscribeFromMessage(dynamicRouterControlService, message, false);
}... | @Test
void performSubscribeActionWithMessageInBodyAndPredicateBean() {
String subscribeChannel = "testChannel";
DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder()
.subscribeChannel(subscribeChannel)
.subscriptionId("testId")
... |
public <M> Flowable<M> getMessages(Class<M> type) {
ReplayProcessor<M> p = ReplayProcessor.create();
return p.doOnRequest(new LongConsumer() {
@Override
public void accept(long n) throws Exception {
AtomicLong counter = new AtomicLong(n);
RFuture<I... | @Test
public void testLong() throws InterruptedException {
RTopicRx topic = redisson.getTopic("test");
Flowable<String> messages = topic.getMessages(String.class);
List<String> list = new ArrayList<>();
messages.subscribe(new Subscriber<String>() {
@Override
... |
@Override
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
//if (!descriptor.equals("Lorg/pf4j/Extension;")) {
if (!Type.getType(descriptor).getClassName().equals(Extension.class.getName())) {
return super.visitAnnotation(descriptor, visible);
}
... | @Test
void visitArrayShouldHandleOrdinalAttribute() {
ExtensionInfo extensionInfo = new ExtensionInfo("org.pf4j.asm.ExtensionInfo");
ClassVisitor extensionVisitor = new ExtensionVisitor(extensionInfo);
AnnotationVisitor annotationVisitor = extensionVisitor.visitAnnotation("Lorg/pf4j/Extensi... |
public static synchronized void configure(DataflowWorkerLoggingOptions options) {
if (!initialized) {
throw new RuntimeException("configure() called before initialize()");
}
// For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions
// to config the logging for l... | @Test
public void testSystemOutLevelOverrides() throws IOException {
DataflowWorkerLoggingOptions options =
PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class);
options.setWorkerSystemOutMessageLevel(DataflowWorkerLoggingOptions.Level.WARN);
DataflowWorkerLoggingInitializer.configure(op... |
protected File getOutputFile(final String path, final String baseFileName) throws IOException {
makeDir(path);
final String now = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
final String fileName = baseFileName + "." + now;
final File file = Paths.get(path, fileName).... | @Test
public void testGetOutputFileWithEmptyPath() throws IOException {
final File f = getOutputFile("", "test1.log");
assertTrue(f.exists());
FileUtils.forceDelete(f);
} |
@Override
public Map<String, Object> load(String configKey) {
if (targetFilePath != null) {
try {
Map<String, Object> raw = (Map<String, Object>) Utils.readYamlFile(targetFilePath);
if (raw != null) {
return (Map<String, Object>) raw.get(config... | @Test
public void testFileNotThere() {
Config conf = new Config();
conf.put(DaemonConfig.SCHEDULER_CONFIG_LOADER_URI, FILE_SCHEME_PREFIX + "/file/not/exist/");
FileConfigLoader testLoader = new FileConfigLoader(conf);
Map<String, Object> result = testLoader.load(DaemonConfig.MULTITEN... |
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to spli... | @Test
public void shouldSplitAndAddEmptySpacesIfDelimiterStringIsFoundInContiguousPositions() {
assertThat(splitUdf.split("A||A", "|"), contains("A", "", "A"));
assertThat(splitUdf.split("z||A||z", "|"), contains("z", "", "A", "", "z"));
assertThat(splitUdf.split("||A||A", "|"), contains("", "", "A", "", ... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void do_filter_on_auth2_identity_provider() {
when(request.getRequestURI()).thenReturn("/oauth2/callback/" + OAUTH2_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(oAuth2IdentityProvider);
when(threadLocalUserSession.hasSession()).thenReturn(true);
when(threadLocalUserSessio... |
@Override
public void registerSuperProperties(JSONObject superProperties) {
} | @Test
public void registerSuperProperties() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("super", "super");
} catch (JSONException e) {
e.printStackTrace();
}
mSensorsAPI.registerSuperProperties(jsonObject);
Assert.assertEqu... |
public static boolean isPunctuationCodePoint(int codePoint) {
switch (Character.getType(codePoint)) {
// General category "P" (punctuation)
case Character.DASH_PUNCTUATION:
case Character.START_PUNCTUATION:
case Character.END_PUNCTUATION:
case Characte... | @Test
public void isPunctuation() {
// From https://spec.commonmark.org/0.29/#ascii-punctuation-character
char[] chars = {
'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', // (U+0021–2F)
':', ';', '<', '=', '>', '?', '@', // (U+003A–0040)
... |
public static NamenodeRole convert(NamenodeRoleProto role) {
switch (role) {
case NAMENODE:
return NamenodeRole.NAMENODE;
case BACKUP:
return NamenodeRole.BACKUP;
case CHECKPOINT:
return NamenodeRole.CHECKPOINT;
}
return null;
} | @Test
public void testConvertRecoveringBlock() {
DatanodeInfo di1 = DFSTestUtil.getLocalDatanodeInfo();
DatanodeInfo di2 = DFSTestUtil.getLocalDatanodeInfo();
DatanodeInfo[] dnInfo = new DatanodeInfo[] { di1, di2 };
RecoveringBlock b = new RecoveringBlock(getExtendedBlock(), dnInfo, 3);
Recovering... |
public boolean changesSpecTemplate() {
return changesSpecTemplate;
} | @Test
public void testSpecVolumesIgnored() {
StatefulSet ss1 = new StatefulSetBuilder()
.withNewMetadata()
.withNamespace("test")
.withName("foo")
.endMetadata()
.withNewSpec().
withNewTemplate()
.withNew... |
public static PathOutputCommitter createCommitter(Path outputPath,
TaskAttemptContext context) throws IOException {
return getCommitterFactory(outputPath,
context.getConfiguration())
.createOutputCommitter(outputPath, context);
} | @Test
public void testCommitterNullOutputPath() throws Throwable {
// bind http to schema
Configuration conf = newBondedConfiguration();
// then ask committers for a null path
FileOutputCommitter committer = createCommitter(
FileOutputCommitterFactory.class,
FileOutputCommitter.class,
... |
@Override
public List<V> removeAll(Object key) {
return (List<V>) get(removeAllAsync(key));
} | @Test
public void testRemoveAll() {
RListMultimap<String, String> map = redisson.getListMultimap("test1");
map.put("0", "1");
map.put("0", "1");
map.put("0", "2");
map.put("0", "3");
RList<String> set = map.get("0");
set.removeAll(Arrays.asList("4", "5"));
... |
static void setStringProperty(Message message, String name, String value) {
try {
message.setStringProperty(name, value);
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error setting property {0} on message {1}", name, message);
}
} | @Test void setStringProperty() throws Exception {
MessageProperties.setStringProperty(message, "b3", "1");
assertThat(message.getObjectProperty("b3"))
.isEqualTo("1");
} |
public static Iterable<String> expandAtNFilepattern(String filepattern) {
ImmutableList.Builder<String> builder = ImmutableList.builder();
Matcher match = AT_N_SPEC.matcher(filepattern);
if (!match.find()) {
builder.add(filepattern);
} else {
int numShards = Integer.parseInt(match.group("N")... | @Test
public void testExpandAtNFilepatternNoPattern() throws Exception {
assertThat(
Filepatterns.expandAtNFilepattern("gs://bucket/object@google.ism"),
contains("gs://bucket/object@google.ism"));
} |
@VisibleForTesting
@SuppressWarnings("nullness") // ok to have nullable elements on stream
static String renderName(String prefix, MetricResult<?> metricResult) {
MetricKey key = metricResult.getKey();
MetricName name = key.metricName();
String step = key.stepName();
return Streams.concat(
... | @Test
public void testRenderNameWithPrefix() {
MetricResult<Object> metricResult =
MetricResult.create(
MetricKey.create(
"myStep.one.two(three)", MetricName.named("myNameSpace//", "myName()")),
123,
456);
String renderedName = SparkBeamMetric.render... |
public PatchRequest<T> generatePatchRequest()
{
return PatchRequest.createFromPatchDocument(generatePatchTree().getDataMap());
} | @Test
public void testPatchGenerateAndPatchRequestRecorderGenerateIdenticalPatches()
throws CloneNotSupportedException
{
TestRecord t1 = new TestRecord();
TestRecord t2 = new TestRecord(t1.data().copy());
t2.setId(1L);
t2.setMessage("Foo Bar Baz");
PatchRequest<TestRecord> patchFromGenerat... |
@Override
public SinkWriter<WindowedValue<IsmRecord<V>>> writer() throws IOException {
return new IsmSinkWriter(FileSystems.create(resourceId, MimeTypes.BINARY));
} | @Test
public void testWriteKeyWhichIsProperPrefixOfPreviousSecondaryKeyIsError() throws Throwable {
IsmSink<byte[]> sink =
new IsmSink<>(
FileSystems.matchNewResource(tmpFolder.newFile().getPath(), false),
CODER,
BLOOM_FILTER_SIZE_LIMIT);
SinkWriter<WindowedValue<Is... |
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (! (o instanceof ConfigSourceSet)) {
return false;
}
ConfigSourceSet css = (ConfigSourceSet)o;
return sources.equals(css.sources);
} | @Test
public void testEquals() {
assertEquals(new ConfigSourceSet(), new ConfigSourceSet());
assertNotEquals(new ConfigSourceSet(), new ConfigSourceSet(new String[]{"a"}));
assertEquals(new ConfigSourceSet(new String[]{"a"}), new ConfigSourceSet(new String[]{"a"}));
assertEquals(new... |
public static UTypeApply create(UExpression type, List<UExpression> typeArguments) {
return new AutoValue_UTypeApply(type, ImmutableList.copyOf(typeArguments));
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UTypeApply.create(
UClassIdent.create("java.util.List"), UClassIdent.create("java.lang.String")))
.addEqualityGroup(
UTypeApply.create(
UClassIdent.create("java.util.Set"), ... |
public BigDecimal calculateTDEE(ActiveLevel activeLevel) {
if(activeLevel == null) return BigDecimal.valueOf(0);
BigDecimal multiplayer = BigDecimal.valueOf(activeLevel.getMultiplayer());
return multiplayer.multiply(BMR).setScale(2, RoundingMode.HALF_DOWN);
} | @Test
void calculateTDEE_MODERATELY_ACTIVE() {
BigDecimal TDEE = bmrCalculator.calculate(attributes).calculateTDEE(ActiveLevel.MODERATELY);
assertEquals(new BigDecimal("3165.87"), TDEE);
} |
@Subscribe
public void reportLocalProcesses(final ReportLocalProcessesEvent event) {
if (!event.getInstanceId().equals(contextManager.getComputeNodeInstanceContext().getInstance().getMetaData().getId())) {
return;
}
Collection<Process> processes = ProcessRegistry.getInstance().li... | @Test
void assertReportLocalProcesses() {
Process process = mock(Process.class);
String processId = "foo_id";
when(process.getId()).thenReturn(processId);
when(process.isInterrupted()).thenReturn(false);
when(process.isIdle()).thenReturn(false);
when(process.getComple... |
public void giveCompliments(Royalty r) {
r.receiveCompliments();
} | @Test
void testGiveCompliments() {
final var royalty = mock(Royalty.class);
final var servant = new Servant("test");
servant.giveCompliments(royalty);
verify(royalty).receiveCompliments();
verifyNoMoreInteractions(royalty);
} |
public MultiMap<Value, T, List<T>> get(final KeyDefinition keyDefinition) {
return tree.get(keyDefinition);
} | @Test
void testFindByAge() throws Exception {
final MultiMap<Value, Person, List<Person>> age = map.get(KeyDefinition.newKeyDefinition()
.withId("age")
.build());
assertThat(age.keySet()).extracting(x -> x.getComparable()).containsExactly(20, 30);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.