focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public ScopeModel getScopeModel() {
return Optional.ofNullable(RpcContext.getServiceContext().getConsumerUrl())
.map(URL::getScopeModel)
.orElse(super.getScopeModel());
} | @Test
void test2() {
RpcServiceContext.getServiceContext().setConsumerUrl(null);
Assertions.assertNull(instanceURL.getScopeModel());
ModuleModel moduleModel = Mockito.mock(ModuleModel.class);
RpcServiceContext.getServiceContext().setConsumerUrl(URL.valueOf("").setScopeModel(moduleMo... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeNull() {
assertNull(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.NULL));
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void portValuesForPodWithMultipleContainer() throws JsonProcessingException {
PodList podList = new PodList();
List<Pod> pods = new ArrayList<>();
for (int i = 0; i <= 1; i++) {
Pod pod = new PodBuilder()
.withMetadata(new ObjectMetaBuilder()
... |
public static List<String> filterMatches(@Nullable List<String> candidates,
@Nullable Pattern[] positivePatterns,
@Nullable Pattern[] negativePatterns) {
if (candidates == null || candidates.isEmpty()) {
return Collections.e... | @Test
public void filterMatchesEmpty() {
List<String> candidates = ImmutableList.of("foo", "bar");
assertThat(filterMatches(candidates, null, null), is(candidates));
assertThat(filterMatches(null, null, null), is(Collections.emptyList()));
} |
@Nullable
public Object sanitize(String key, @Nullable Object value) {
for (Pattern pattern : sanitizeKeysPatterns) {
if (pattern.matcher(key).matches()) {
return SANITIZED_VALUE;
}
}
return value;
} | @Test
void obfuscateCredentialsWithDefinedPatterns() {
final var sanitizer = new KafkaConfigSanitizer(true, Arrays.asList("kafka.ui", ".*test.*"));
assertThat(sanitizer.sanitize("consumer.kafka.ui", "secret")).isEqualTo("******");
assertThat(sanitizer.sanitize("this.is.test.credentials", "secret")).isEqua... |
public static OffsetBasedPagination forStartRowNumber(int startRowNumber, int pageSize) {
checkArgument(startRowNumber >= 1, "startRowNumber must be >= 1");
checkArgument(pageSize >= 1, "page size must be >= 1");
return new OffsetBasedPagination(startRowNumber - 1, pageSize);
} | @Test
void equals_whenSameObjects_shouldBeTrue() {
OffsetBasedPagination offsetBasedPagination = OffsetBasedPagination.forStartRowNumber(15, 20);
Assertions.assertThat(offsetBasedPagination).isEqualTo(offsetBasedPagination);
} |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_serializable_complex_object_with_serializable_nested_object() {
Map<String, List<SerializableObject>> map = new LinkedHashMap<>();
map.put("key1", Lists.newArrayList(new SerializableObject("name1")));
map.put("key2", Lists.newArrayList(
new Serializ... |
@Override
public int run(String[] args) throws Exception {
parseArgs(args);
// Disable using the RPC tailing mechanism for bootstrapping the standby
// since it is less efficient in this case; see HDFS-14806
conf.setBoolean(DFSConfigKeys.DFS_HA_TAILEDITS_INPROGRESS_KEY, false);
parseConfAndFindOth... | @Test
public void testStandbyDirsAlreadyExist() throws Exception {
// Should not pass since standby dirs exist, force not given
int rc = BootstrapStandby.run(
new String[]{"-nonInteractive"},
cluster.getConfiguration(1));
assertEquals(BootstrapStandby.ERR_CODE_ALREADY_FORMATTED, rc);
... |
@Override
public WanReplicationConfig setName(@Nonnull String name) {
this.name = checkNotNull(name, "Name must not be null");
return this;
} | @Test
public void testSerialization_withEmpyConfigs() {
config.setName("name");
SerializationService serializationService = new DefaultSerializationServiceBuilder().build();
Data serialized = serializationService.toData(config);
WanReplicationConfig deserialized = serializationServi... |
@Override
public void close() {
// Acquire the lock so that drain is guaranteed to complete the current batch
appendLock.lock();
List<CompletedBatch<T>> unwritten;
try {
unwritten = drain(Long.MAX_VALUE);
} finally {
appendLock.unlock();
}
... | @Test
public void testCloseWhenEmpty() {
int leaderEpoch = 17;
long baseOffset = 157;
int lingerMs = 50;
int maxBatchSize = 256;
BatchAccumulator<String> acc = buildAccumulator(
leaderEpoch,
baseOffset,
lingerMs,
maxBatchSize
... |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldThrowIfRetentionConfigPresentInCreateTable() {
// Given:
givenStatement("CREATE TABLE foo_bar (FOO STRING PRIMARY KEY, BAR STRING) WITH (kafka_topic='doesntexist', partitions=2, format='avro', retention_ms=30000);");
// When:
final Exception e = assertThrows(
KsqlExcep... |
public void setWriteTimeout(int writeTimeout) {
this.writeTimeout = writeTimeout;
} | @Test
public void testThrowIOException() throws IOException {
when(mockLowLevelRequest.execute())
.thenThrow(new IOException("Fake Error"))
.thenReturn(mockLowLevelResponse);
when(mockLowLevelResponse.getStatusCode()).thenReturn(200);
Storage.Buckets.Get result = storage.buckets().get("te... |
public ConvertCommand(Logger console) {
super(console);
} | @Test
public void testConvertCommand() throws IOException {
File file = toAvro(parquetFile());
ConvertCommand command = new ConvertCommand(createLogger());
command.targets = Arrays.asList(file.getAbsolutePath());
File output = new File(getTempFolder(), "converted.avro");
command.outputPath = outpu... |
Map<String, String> describeInstances(AwsCredentials credentials) {
Map<String, String> attributes = createAttributesDescribeInstances();
Map<String, String> headers = createHeaders(attributes, credentials);
String response = callAwsService(attributes, headers);
return parseDescribeInsta... | @Test
public void describeInstances() {
// given
String requestUrl = "/?Action=DescribeInstances"
+ "&Filter.1.Name=tag%3Aaws-test-cluster"
+ "&Filter.1.Value.1=cluster1"
+ "&Filter.2.Name=tag-key"
+ "&Filter.2.Value.1=another-tag-key"
+ "&... |
public RMNode selectAnyNode(Set<String> blacklist, Resource request) {
List<NodeId> nodeIds = getCandidatesForSelectAnyNode();
int size = nodeIds.size();
if (size <= 0) {
return null;
}
Random rand = new Random();
int startIndex = rand.nextInt(size);
for (int i = 0; i < size; ++i) {
... | @Test
public void testSelectAnyNode() {
NodeQueueLoadMonitor selector = new NodeQueueLoadMonitor(
NodeQueueLoadMonitor.LoadComparator.QUEUE_LENGTH);
RMNode h1 = createRMNode("h1", 1, "rack1", -1, 2, 5);
RMNode h2 = createRMNode("h2", 2, "rack2", -1, 5, 5);
RMNode h3 = createRMNode("h3", 3, "r... |
public static L3ModificationInstruction modL3IPv6Dst(IpAddress addr) {
checkNotNull(addr, "Dst l3 IPv6 address cannot be null");
return new ModIPInstruction(L3SubType.IPV6_DST, addr);
} | @Test
public void testModL3IPv6DstMethod() {
final Instruction instruction = Instructions.modL3IPv6Dst(ip61);
final L3ModificationInstruction.ModIPInstruction modIPInstruction =
checkAndConvert(instruction,
Instruction.Type.L3MODIFICATION,
... |
@Override
public Date getStartedAt() {
String dateString = settings.get(CoreProperties.SERVER_STARTTIME).orElseThrow(() -> new IllegalStateException("Mandatory"));
return DateUtils.parseDateTime(dateString);
} | @Test(expected = RuntimeException.class)
public void invalid_startup_date_throws_exception() {
MapSettings settings = new MapSettings();
settings.setProperty(CoreProperties.SERVER_STARTTIME, "invalid");
DefaultScannerWsClient client = mock(DefaultScannerWsClient.class);
DefaultServer metadata = new De... |
@Override
public boolean syncVerifyData(DistroData verifyData, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
// replace target server as self server so that can callback.
verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd... | @Test
void testSyncVerifyDataFailure() throws NacosException {
DistroData verifyData = new DistroData();
verifyData.setDistroKey(new DistroKey());
when(memberManager.hasMember(member.getAddress())).thenReturn(true);
when(memberManager.find(member.getAddress())).thenReturn(member);
... |
public boolean isAlwaysFalse() {
if (conditions.isEmpty()) {
return false;
}
for (ShardingCondition each : conditions) {
if (!(each instanceof AlwaysFalseShardingCondition)) {
return false;
}
}
return true;
} | @Test
void assertIsAlwaysFalse() {
ShardingConditions shardingConditions = new ShardingConditions(Collections.emptyList(), mock(SQLStatementContext.class), mock(ShardingRule.class));
assertFalse(shardingConditions.isAlwaysFalse());
} |
public Set<MapperConfig> load(InputStream inputStream) throws IOException {
final PrometheusMappingConfig config = ymlMapper.readValue(inputStream, PrometheusMappingConfig.class);
return config.metricMappingConfigs()
.stream()
.flatMap(this::mapMetric)
.c... | @Test
void unknownType() {
final Map<String, ImmutableList<Serializable>> config = Collections.singletonMap("metric_mappings",
ImmutableList.of(
ImmutableMap.of(
"type", "unknown",
"metric_name", "test1",... |
@PostMapping(path = "/proxyGateway")
public void proxyGateway(@RequestBody @Valid final ProxyGatewayDTO proxyGatewayDTO,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
sandboxService.requestProxyGateway(proxy... | @Test
public void testProxyGateway() throws Exception {
AppAuthDO appAuthDO = buildAppAuthDO();
ProxyGatewayDTO proxyGatewayDTO = buildProxyGatewayDTO();
when(this.appAuthService.findByAppKey(any())).thenReturn(appAuthDO);
MockHttpServletResponse response = mockMvc.perform(MockMvcReq... |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializabl... | @Test
public void should_clone_collection_of_non_serializable_object() {
List<NonSerializableObject> original = new ArrayList<>();
original.add(new NonSerializableObject("value"));
List<NonSerializableObject> cloned = serializer.clone(original);
assertEquals(original, cloned);
... |
@Bean("EsClient")
public EsClient provide(Configuration config) {
Settings.Builder esSettings = Settings.builder();
// mandatory property defined by bootstrap process
esSettings.put("cluster.name", config.get(CLUSTER_NAME.getKey()).get());
boolean clusterEnabled = config.getBoolean(CLUSTER_ENABLED.g... | @Test
public void provide_whenHttpEncryptionEnabled_shouldUseHttps() throws GeneralSecurityException, IOException {
settings.setProperty(CLUSTER_ENABLED.getKey(), true);
Path keyStorePath = temp.newFile("keystore.p12").toPath();
EsClientTest.createCertificate("localhost", keyStorePath, "password");
se... |
public static SnapshotRef fromJson(String json) {
Preconditions.checkArgument(
json != null && !json.isEmpty(), "Cannot parse snapshot ref from invalid JSON: %s", json);
return JsonUtil.parse(json, SnapshotRefParser::fromJson);
} | @Test
public void testTagFromJsonAllFields() {
String json = "{\"snapshot-id\":1,\"type\":\"tag\",\"max-ref-age-ms\":1}";
SnapshotRef ref = SnapshotRef.tagBuilder(1L).maxRefAgeMs(1L).build();
assertThat(SnapshotRefParser.fromJson(json))
.as("Should be able to deserialize tag with all fields")
... |
@Override
public Mono<GetCurrencyConversionsResponse> getCurrencyConversions(final GetCurrencyConversionsRequest request) {
AuthenticationUtil.requireAuthenticatedDevice();
final CurrencyConversionEntityList currencyConversionEntityList = currencyManager
.getCurrencyConversions()
.orElseThrow... | @Test
public void testUnauthenticated() throws Exception {
assertStatusException(Status.UNAUTHENTICATED, () -> unauthenticatedServiceStub().getCurrencyConversions(
GetCurrencyConversionsRequest.newBuilder().build()));
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) {
if ( from == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));... | @Test
void invokeEmptyGroup() {
FunctionTestUtil.assertResultError(numberFunction.invoke("1 000", "", null), InvalidParametersEvent.class);
} |
@Nonnull
@Override
public Collection<DataConnectionResource> listResources() {
try (AdminClient client = AdminClient.create(getConfig().getProperties())) {
return client.listTopics().names().get()
.stream()
.sorted()
.map(n -> new D... | @Test
public void list_resources_should_return_empty_list_for_no_topics() {
kafkaDataConnection = createKafkaDataConnection(kafkaTestSupport);
Collection<DataConnectionResource> resources = kafkaDataConnection.listResources();
List<DataConnectionResource> withoutConfluent =
... |
public void useModules(String... names) {
checkNotNull(names, "names cannot be null");
Set<String> deduplicateNames = new HashSet<>();
for (String name : names) {
if (!loadedModules.containsKey(name)) {
throw new ValidationException(
String.for... | @Test
void testUseModules() {
ModuleMock x = new ModuleMock("x");
ModuleMock y = new ModuleMock("y");
ModuleMock z = new ModuleMock("z");
manager.loadModule(x.getType(), x);
manager.loadModule(y.getType(), y);
manager.loadModule(z.getType(), z);
assertThat(ma... |
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 testIntegerIn() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, in("id", INT_MIN_VALUE - 25, INT_MIN_VALUE - 24))
.eval(FILE);
assertThat(shouldRead).as("Should not read: id below lower bound (5 < 30, 6 < 30)").isFalse();
shouldRead =
new Inclusi... |
public boolean couldHoldIgnoringSharedMemory(NormalizedResources other, double thisTotalMemoryMb, double otherTotalMemoryMb) {
if (this.cpu < other.getTotalCpu()) {
return false;
}
return couldHoldIgnoringSharedMemoryAndCpu(other, thisTotalMemoryMb, otherTotalMemoryMb);
} | @Test
public void testCouldHoldWithTooLittleMemory() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 1)));
NormalizedResources resourcesToCheck = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 1)));
... |
public String createAndUploadPolicyExample(IamClient iam, String accountID, String policyName) {
// Build the policy.
IamPolicy policy = IamPolicy.builder() // 'version' defaults to "2012-10-17".
.addStatement(IamStatement.builder()
... | @Test
@Tag("IntegrationTest")
void createAndUploadPolicyExample() {
String accountId = examples.getAccountID();
String policyName = "AllowPutItemToExampleTable";
String jsonPolicy = examples.createAndUploadPolicyExample(iam, accountId, policyName);
logger.info(jsonPolicy);
... |
public static void verifyChunkedSums(int bytesPerSum, int checksumType,
ByteBuffer sums, ByteBuffer data, String fileName, long basePos)
throws ChecksumException {
nativeComputeChunkedSums(bytesPerSum, checksumType,
sums, sums.position(),
data, data.position(), data.remaining(),
... | @Test
public void testVerifyChunkedSumsSuccessOddSize() throws ChecksumException {
// Test checksum with an odd number of bytes. This is a corner case that
// is often broken in checksum calculation, because there is an loop which
// handles an even multiple or 4 or 8 bytes and then some additional code
... |
public static HazelcastInstance newHazelcastInstance(Config config) {
if (config == null) {
config = Config.load();
}
return newHazelcastInstance(
config,
config.getInstanceName(),
new DefaultNodeContext()
);
} | @Test(expected = ExpectedRuntimeException.class)
public void test_NewInstance_failed_afterNodeStart() throws Exception {
NodeContext context = new TestNodeContext() {
@Override
public NodeExtension createNodeExtension(Node node) {
NodeExtension nodeExtension = super.c... |
public void shutdown(final Callback<None> callback)
{
_managerStarted = false;
for (ZooKeeperAnnouncer server : _servers)
{
server.shutdown();
}
Callback<None> zkCloseCallback = new CallbackAdapter<None, None>(callback)
{
@Override
protected None convertResponse(None none) th... | @Test
public void testMarkDownAndUpDuringDisconnection()
throws Exception
{
ZooKeeperAnnouncer announcer = getZooKeeperAnnouncer(_cluster, _uri, WEIGHT);
ZooKeeperConnectionManager manager = createManager(true, announcer);
ZooKeeperEphemeralStore<UriProperties> store = createAndStartUriStore();
... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the number of days since 1970-01-01 00:00:00 UTC/GMT.")
public int stringToDate(
@UdfParameter(
description = "The string representation of a date.") final String formattedDate,
@UdfParameter(
... | @Test
public void shouldThrowIfParseFails() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.stringToDate("invalid", "yyyy-MM-dd")
);
// Then:
assertThat(e.getMessage(), containsString("Failed to parse date 'invalid' with formatter 'yyyy-MM-dd'")... |
@Override
public Map<String, Table> getTables() {
return ImmutableMap.copyOf(tables);
} | @Test
public void testGetTables() throws Exception {
store.createTable(mockTable("hello"));
store.createTable(mockTable("world"));
assertEquals(2, store.getTables().size());
assertThat(store.getTables(), Matchers.hasValue(mockTable("hello")));
assertThat(store.getTables(), Matchers.hasValue(mockT... |
@Override
public boolean storesMixedCaseQuotedIdentifiers() {
return false;
} | @Test
void assertStoresMixedCaseQuotedIdentifiers() {
assertFalse(metaData.storesMixedCaseQuotedIdentifiers());
} |
@Override
public void execute(Context context) {
context.setResolution(resolution);
} | @Test
public void execute() {
SetResolution function = new SetResolution("FIXED");
Function.Context context = mock(Function.Context.class);
function.execute(context);
verify(context, times(1)).setResolution("FIXED");
} |
@Nonnull
public static ToConverter getToConverter(QueryDataType type) {
if (type.getTypeFamily() == QueryDataTypeFamily.OBJECT) {
// User-defined types are subject to the same conversion rules as ordinary OBJECT.
type = QueryDataType.OBJECT;
}
return Objects.requireNo... | @Test
public void test_dateConversion() {
OffsetDateTime time = OffsetDateTime.of(2020, 9, 8, 11, 4, 0, 123, UTC);
Object converted = getToConverter(TIMESTAMP_WITH_TZ_DATE).convert(time);
assertThat(converted).isEqualTo(Date.from(time.toInstant()));
} |
@Override
public <T> CompletableFuture<T> submit(Callable<T> callable) {
final CompletableFuture<T> promise = new CompletableFuture<>();
try {
CompletableFuture.supplyAsync(ContextPropagator.decorateSupplier(config.getContextPropagator(),() -> {
try {
... | @Test
public void testSupplierThreadLocalContextPropagator() {
TestThreadLocalContextHolder.put("ValueShouldCrossThreadBoundary");
CompletableFuture<Object> future = fixedThreadPoolBulkhead
.submit(() -> TestThreadLocalContextHolder.get().orElse(null));
waitAtMost(5, TimeUnit.... |
@Override
public synchronized CompletableFuture<MastershipEvent> setMaster(NetworkId networkId,
NodeId nodeId, DeviceId deviceId) {
Map<DeviceId, NodeId> masterMap = getMasterMap(networkId);
MastershipRole role = getRole(networkId, nodeId, dev... | @Test
public void setMaster() {
put(VNID1, VDID1, N1, false, false);
assertEquals("wrong event", MASTER_CHANGED,
Futures.getUnchecked(sms.setMaster(VNID1, N1, VDID1)).type());
assertEquals("wrong role", MASTER, sms.getRole(VNID1, N1, VDID1));
//set node that's al... |
public void writeEncodedValue(EncodedValue encodedValue) throws IOException {
switch (encodedValue.getValueType()) {
case ValueType.BOOLEAN:
writer.write(Boolean.toString(((BooleanEncodedValue) encodedValue).getValue()));
break;
case ValueType.BYTE:
... | @Test
public void testWriteEncodedValue_double() throws IOException {
DexFormattedWriter writer = new DexFormattedWriter(output);
writer.writeEncodedValue(new ImmutableDoubleEncodedValue(12.34));
Assert.assertEquals("12.34", output.toString());
} |
@Override
public double rand() {
if (MathEx.random() < q) {
return 0;
} else {
return 1;
}
} | @Test
public void testSd() {
System.out.println("sd");
BernoulliDistribution instance = new BernoulliDistribution(0.3);
instance.rand();
assertEquals(Math.sqrt(0.21), instance.sd(), 1E-7);
} |
public int getConnectionCount() {
return connectionCount;
} | @Test
public void test_constructor_connectionCountDefaultBehavior() {
ClientTpcConfig config = new ClientTpcConfig();
assertEquals(1, config.getConnectionCount());
System.setProperty("hazelcast.client.tpc.connectionCount", "5");
config = new ClientTpcConfig();
assertEquals(5... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
LOG.warn(
"{} class does not perform actual GSUB substitutions. Perhaps the selected language is not yet supported by the FontBox library.",
getClass().getSimpleName());
// Make the r... | @Test
@DisplayName("Transformation result is actually a read-only version of the argument")
void applyTransforms()
{
// given
DefaultGsubWorker sut = new DefaultGsubWorker();
List<Integer> originalGlyphIds = Arrays.asList(1, 2, 3, 4, 5);
// when
List<Integer> pseudoT... |
public Response request(Request request) throws NacosException {
return request(request, rpcClientConfig.timeOutMills());
} | @Test
void testRequestWhenTimeoutThenThrowException() throws NacosException {
assertThrows(NacosException.class, () -> {
rpcClient.rpcClientStatus.set(RpcClientStatus.RUNNING);
rpcClient.currentConnection = connection;
doReturn(null).when(connection).request(any(), anyLon... |
@Operation(
summary = "Monitor the given search keys in the key transparency log",
description = """
Enforced unauthenticated endpoint. Return proofs proving that the log tree
has been constructed correctly in later entries for each of the given search keys .
"""
)
@ApiResp... | @Test
void monitorAuthenticated() {
final Invocation.Builder request = resources.getJerseyTest()
.target("/v1/key-transparency/monitor")
.request()
.header(HttpHeaders.AUTHORIZATION, AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD));
try (Response response = r... |
@Override
public boolean canRescaleMaxParallelism(int desiredMaxParallelism) {
// Technically a valid parallelism value, but one that cannot be rescaled to
if (desiredMaxParallelism == JobVertex.MAX_PARALLELISM_DEFAULT) {
return false;
}
return !rescaleMaxValidator
... | @Test
void canRescaleMaxDefault() {
DefaultVertexParallelismInfo info = new DefaultVertexParallelismInfo(1, 1, ALWAYS_VALID);
assertThat(info.canRescaleMaxParallelism(JobVertex.MAX_PARALLELISM_DEFAULT)).isFalse();
} |
@Override
public void merge(Accumulator<Integer, Integer> other) {
this.min = Math.min(this.min, other.getLocalValue());
} | @Test
void testMerge() {
IntMinimum min1 = new IntMinimum();
min1.add(1234);
IntMinimum min2 = new IntMinimum();
min2.add(5678);
min2.merge(min1);
assertThat(min2.getLocalValue().intValue()).isEqualTo(1234);
min1.merge(min2);
assertThat(min1.getLoca... |
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 testCaseInsensitiveIntegerNotEqRewritten() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, not(equal("ID", INT_MIN_VALUE - 25)), false)
.eval(FILE);
assertThat(shouldRead).as("Should read: id below lower bound").isTrue();
shouldRead =
new Inclusi... |
@Override
public CompletableFuture<Boolean> checkAndUpdateConfigMap(
String configMapName,
Function<KubernetesConfigMap, Optional<KubernetesConfigMap>> updateFunction) {
return FutureUtils.retry(
() -> attemptCheckAndUpdateConfigMap(configMapName, updateFunction),
... | @Test
void testCheckAndUpdateConfigMap() throws Exception {
this.flinkKubeClient.createConfigMap(buildTestingConfigMap());
// Checker pass
final boolean updated =
this.flinkKubeClient
.checkAndUpdateConfigMap(
TESTING_C... |
SortedReplicas(Broker broker,
Set<Function<Replica, Boolean>> selectionFuncs,
List<Function<Replica, Integer>> priorityFuncs,
Function<Replica, Double> scoreFunction) {
this(broker, null, selectionFuncs, priorityFuncs, scoreFunction, true);
} | @Test
public void testPriorityFunction() {
Broker broker = generateBroker(NUM_REPLICAS);
new SortedReplicasHelper().addPriorityFunc(PRIORITY_FUNC)
.setScoreFunc(SCORE_FUNC)
.trackSortedReplicasFor(SORT_NAME, broker);
SortedReplicas sr = broker.tr... |
@Override
public byte getByte(int index) {
checkIndex(index);
return _getByte(index);
} | @Test
public void getByteBoundaryCheck1() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.getByte(-1);
}
});
} |
@Override
protected void init() throws ServiceException {
Configuration hConf = new Configuration(false);
ConfigurationUtils.copy(getServiceConfig(), hConf);
hGroups = new org.apache.hadoop.security.Groups(hConf);
} | @Test(expected = RuntimeException.class)
@TestDir
public void invalidGroupsMapping() throws Exception {
String dir = TestDirHelper.getTestDir().getAbsolutePath();
Configuration conf = new Configuration(false);
conf.set("server.services", StringUtils.join(",", Arrays.asList(GroupsService.class.getName())... |
public CompletableFuture<ForwardMessageToDeadLetterQueueResponse> forwardMessageToDeadLetterQueue(ProxyContext ctx,
ForwardMessageToDeadLetterQueueRequest request) {
CompletableFuture<ForwardMessageToDeadLetterQueueResponse> future = new CompletableFuture<>();
try {
validateTopicAndC... | @Test
public void testForwardMessageToDeadLetterQueueWhenHasMappingHandle() throws Throwable {
ArgumentCaptor<ReceiptHandle> receiptHandleCaptor = ArgumentCaptor.forClass(ReceiptHandle.class);
when(this.messagingProcessor.forwardMessageToDeadLetterQueue(any(), receiptHandleCaptor.capture(), anyStrin... |
public static FusedPipeline fuse(Pipeline p) {
return new GreedyPipelineFuser(p).fusedPipeline;
} | @Test
public void sanitizedTransforms() throws Exception {
PCollection flattenOutput = pc("flatten.out");
PCollection read1Output = pc("read1.out");
PCollection read2Output = pc("read2.out");
PCollection impulse1Output = pc("impulse1.out");
PCollection impulse2Output = pc("impulse2.out");
PTr... |
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) {
log.info("Starting to validate internal topics {}.", topicConfigs.keySet());
final long now = time.milliseconds();
final long deadline = now + retryTimeoutMs;
final ValidationResult validationResult... | @Test
public void shouldReportMissingTopics() {
final String missingTopic1 = "missingTopic1";
final String missingTopic2 = "missingTopic2";
setupTopicInMockAdminClient(topic1, repartitionTopicConfig());
final InternalTopicConfig internalTopicConfig1 = setupRepartitionTopicConfig(topi... |
@Override
public boolean offer(final T element) {
return offer(element, 1);
} | @Test
public void testStreamSummary() {
ConcurrentStreamSummary<String> vs = new ConcurrentStreamSummary<String>(3);
String[] stream = {"X", "X", "Y", "Z", "A", "B", "C", "X", "X", "A", "A", "A"};
for (String i : stream) {
vs.offer(i);
/*
for(String s : vs.poll(3))
... |
@Override
public int size()
{
return _size;
} | @Test
public void testRemoveLast()
{
List<Integer> control = new ArrayList<>(Arrays.asList(1, 2, 3));
LinkedDeque<Integer> q = new LinkedDeque<>(control);
Assert.assertEquals(q.removeLast(), control.remove(control.size() - 1));
Assert.assertEquals(q, control);
} |
public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
... | @Test
void isDirectoryReturnsTrueForURLEncodedDirectoriesInJarsWithoutTrailingSlashes() throws Exception {
final URL url = new URL("jar:" + resourceJar.toExternalForm() + "!/dir%20with%20space");
assertThat(url.getProtocol()).isEqualTo("jar");
assertThat(ResourceURL.isDirectory(url)).isTrue... |
@Override
public HadoopConf buildHadoopConfWithReadOnlyConfig(ReadonlyConfig readonlyConfig) {
Configuration configuration = loadHiveBaseHadoopConfig(readonlyConfig);
Config config = fillBucket(readonlyConfig, configuration);
config =
config.withValue(
... | @Test
void fillBucketInHadoopConfPath() throws URISyntaxException {
URL resource = CosStorageTest.class.getResource("/cos");
String filePath = Paths.get(resource.toURI()).toString();
HashMap<String, Object> map = new HashMap<>();
map.put("hive.hadoop.conf-path", filePath);
ma... |
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId)
throws IOException, InterruptedException {
// We map the input ConnectionID to a new value to restrict the number of tcp connections
connectionId =
new ConnectionID(
co... | @TestTemplate
void testNettyClientConnectRetryFailure() throws Exception {
NettyTestUtil.NettyServerAndClient serverAndClient = createNettyServerAndClient();
UnstableNettyClient unstableNettyClient =
new UnstableNettyClient(serverAndClient.client(), 3);
try {
Par... |
@ApiOperation(value = "Get a user’s picture", produces = "application/octet-stream", tags = {
"Users" }, notes = "The response body contains the raw picture data, representing the user’s picture. The Content-type of the response corresponds to the mimeType that was set when creating the picture.")
@ApiR... | @Test
public void testUpdatePictureWithCustomMimeType() throws Exception {
User savedUser = null;
try {
User newUser = identityService.newUser("testuser");
newUser.setFirstName("Fred");
newUser.setLastName("McDonald");
newUser.setEmail("no-reply@activi... |
@Override
public ObjectiveTranslation doTranslate(NextObjective obj)
throws FabricPipelinerException {
final ObjectiveTranslation.Builder resultBuilder =
ObjectiveTranslation.builder();
switch (obj.type()) {
case SIMPLE:
simpleNext(obj, resul... | @Test
public void testMplsHashedOutput() throws Exception {
TrafficTreatment treatment1 = DefaultTrafficTreatment.builder()
.setEthSrc(ROUTER_MAC)
.setEthDst(SPINE1_MAC)
.pushMpls()
.copyTtlOut()
.setMpls(MPLS_10)
... |
public static Select select(String fieldName) { return new Select(fieldName);
} | @Test
void select_specific_fields() {
String q = Q.select("f1", "f2")
.from("sd1")
.where("f1").contains("v1")
.build();
assertEquals(q, "yql=select f1, f2 from sd1 where f1 contains \"v1\"");
} |
public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, Timer timer) {
return beginningOrEndOffset(partitions, ListOffsetsRequest.LATEST_TIMESTAMP, timer);
} | @Test
public void testEndOffsetsMultipleTopicPartitions() {
buildFetcher();
Map<TopicPartition, Long> expectedOffsets = new HashMap<>();
expectedOffsets.put(tp0, 5L);
expectedOffsets.put(tp1, 7L);
expectedOffsets.put(tp2, 9L);
assignFromUser(expectedOffsets.keySet());... |
public PrepareAndActivateResult deploy(CompressedApplicationInputStream in, PrepareParams prepareParams) {
DeployHandlerLogger logger = DeployHandlerLogger.forPrepareParams(prepareParams);
File tempDir = uncheck(() -> Files.createTempDirectory("deploy")).toFile();
ThreadLockStats threadLockStats... | @Test
public void testResolveConfigForMultipleApps() {
Version vespaVersion = VespaModelFactory.createTestFactory().version();
applicationRepository.deploy(app1, new PrepareParams.Builder()
.applicationId(applicationId())
.vespaVersion(vespaVersion)
.b... |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvWithSingleCarriageReturn() {
CharSequence value = "\r";
CharSequence expected = "\"\r\"";
escapeCsv(value, expected);
} |
@Override
protected Result check() throws Exception {
return timeBoundHealthCheck.check(() -> {
try (Handle handle = jdbi.open()) {
if (validationQuery.isPresent()) {
handle.execute(validationQuery.get());
} else if (!handle.get... | @Test
void tesHealthyAfterWhenMissingValidationQuery() throws Exception {
when(connection.isValid(anyInt())).thenReturn(true);
HealthCheck.Result result = healthCheck().check();
assertThat(result.isHealthy()).isTrue();
verify(connection).isValid(anyInt());
} |
@Override
public Mono<SetRegistrationLockResponse> setRegistrationLock(final SetRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
if (request.getRegistrationLock().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDes... | @Test
void setRegistrationLockEmptySecret() {
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> authenticatedServiceStub().setRegistrationLock(SetRegistrationLockRequest.newBuilder()
.build()));
verify(accountsManager, never())... |
public Matrix transpose() {
return transpose(true);
} | @Test
public void testTranspose() {
Matrix t = matrix.transpose();
assertEquals(Layout.COL_MAJOR, matrix.layout());
assertEquals(Layout.ROW_MAJOR, t.layout());
assertEquals(3, t.nrow());
assertEquals(3, t.ncol());
assertEquals(0.9, matrix.get(0, 0), 1E-7);
as... |
@Override
public void remove(NamedNode master) {
connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName());
} | @Test
public void testRemove() {
Collection<RedisServer> masters = connection.masters();
connection.remove(masters.iterator().next());
} |
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise);
} | @Test
public void headersWithNoPriority() {
writeAllFlowControlledFrames();
final int streamId = 6;
ChannelPromise promise = newPromise();
encoder.writeHeaders(ctx, streamId, EmptyHttp2Headers.INSTANCE, 0, false, promise);
verify(writer).writeHeaders(eq(ctx), eq(streamId), eq... |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
void onFailureAfterAllRetriesExceptionIsLoggedToError() {
Job job = aFailedJobWithRetries().withEnqueuedState(Instant.now()).build();
when(backgroundJobServer.getBackgroundJobRunner(job)).thenReturn(null);
BackgroundJobPerformer backgroundJobPerformer = new BackgroundJobPerformer(back... |
public void deleteAfnemersindicatie(String aNummer) {
AfnemersberichtAanDGL afnemersberichtAanDGL = afnemersberichtAanDGLFactory.createAfnemersberichtAanDGL(dglMessageFactory.createAv01(aNummer));
Afnemersbericht afnemersbericht = new Afnemersbericht();
afnemersbericht.setANummer(aNummer);
... | @Test
public void testDeleteAfnemersindicatie(){
Av01 av01 = new Av01();
when(dglMessageFactory.createAv01(anyString())).thenReturn(av01);
AfnemersberichtAanDGL afnemersberichtAanDGL = new AfnemersberichtAanDGL();
BerichtHeaderType berichtHeader = new BerichtHeaderType();
be... |
public static BadRequestException create(String... errorMessages) {
return create(asList(errorMessages));
} | @Test
public void fail_when_creating_exception_with_one_empty_element() {
assertThatThrownBy(() -> BadRequestException.create(asList("error", "")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Message cannot be empty");
} |
@Override
public Integer doCall() throws Exception {
JsonObject pluginConfig = loadConfig();
JsonObject plugins = pluginConfig.getMap("plugins");
Object plugin = plugins.remove(name);
if (plugin != null) {
printer().printf("Plugin %s removed%n", name);
saveCo... | @Test
public void shouldDeletePlugin() throws Exception {
PluginHelper.enable(PluginType.CAMEL_K);
PluginDelete command = new PluginDelete(new CamelJBangMain().withPrinter(printer));
command.name = "camel-k";
command.doCall();
Assertions.assertEquals("Plugin camel-k removed... |
public static String encodeMessage(String raw) {
if (StringUtils.isEmpty(raw)) {
return "";
}
return encodeComponent(raw);
} | @Test
void encodeMessage() {
Assertions.assertTrue(TriRpcStatus.encodeMessage(null).isEmpty());
Assertions.assertTrue(TriRpcStatus.encodeMessage("").isEmpty());
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamIsNull() {
FunctionTestUtil.assertResultError(finishesFunction.invoke((Comparable) null, new RangeImpl()), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(finishesFunction.invoke("a", null), InvalidParametersEvent.class);
} |
@Override
public Set<ConfigOption<?>> requiredOptions() {
return Collections.singleton(FlinkOptions.PATH);
} | @Test
void testRequiredOptions() {
ResolvedSchema schema1 = SchemaBuilder.instance()
.field("f0", DataTypes.INT().notNull())
.field("f1", DataTypes.VARCHAR(20))
.field("f2", DataTypes.TIMESTAMP(3))
.build();
final MockContext sourceContext1 = MockContext.getInstance(this.conf, ... |
private void fail(final ChannelHandlerContext ctx, int length) {
fail(ctx, String.valueOf(length));
} | @Test
public void testNotFailFast() throws Exception {
EmbeddedChannel ch = new EmbeddedChannel(new LineBasedFrameDecoder(2, false, false));
assertFalse(ch.writeInbound(wrappedBuffer(new byte[] { 0, 1, 2 })));
assertFalse(ch.writeInbound(wrappedBuffer(new byte[]{ 3, 4 })));
try {
... |
@Override
public boolean containsLong(K name, long value) {
return false;
} | @Test
public void testContainsLong() {
assertFalse(HEADERS.containsLong("name1", 1));
} |
@Override
protected void processOptions(LinkedList<String> args)
throws IOException {
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE,
OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN,
OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE,
OPTION_MTIME, OPTION_SIZE, OPTION_A... | @Test
public void processPathFiles() throws IOException {
TestFile testfile01 = new TestFile("testDir01", "testFile01");
TestFile testfile02 = new TestFile("testDir02", "testFile02");
TestFile testfile03 = new TestFile("testDir03", "testFile03");
TestFile testfile04 = new TestFile("testDir04", "testFi... |
public static <T> List<List<T>> groupPartitions(List<T> elements, int numGroups) {
if (numGroups <= 0)
throw new IllegalArgumentException("Number of groups must be positive.");
List<List<T>> result = new ArrayList<>(numGroups);
// Each group has either n+1 or n raw partitions
... | @Test
public void testGroupPartitions() {
List<List<Integer>> grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 1);
assertEquals(Collections.singletonList(FIVE_ELEMENTS), grouped);
grouped = ConnectorUtils.groupPartitions(FIVE_ELEMENTS, 2);
assertEquals(Arrays.asList(Arrays.a... |
public static void verifyMessage(final Address address,
final String message,
final String signatureBase64) throws SignatureException {
try {
final ScriptType scriptType = address.getOutputScriptType();
switch (sc... | @Test
public void testMessageSignatureVerification() {
final AddressParser addressParser = AddressParser.getDefault(testVector.networkParameters.network());
try {
MessageVerifyUtils.verifyMessage(
addressParser.parseAddress(testVector.address),
tes... |
@Override
public ListenableFuture<SplitBatch> getNextBatch(ConnectorPartitionHandle partitionHandle, Lifespan lifespan, int maxSize)
{
checkArgument(maxSize > 0, "Cannot fetch a batch of zero size");
return GetNextBatch.fetchNextBatchAsync(source, Math.min(bufferSize, maxSize), maxSize, partitio... | @Test
public void testFailImmediate()
{
MockSplitSource mockSource = new MockSplitSource()
.setBatchSize(1)
.atSplitCompletion(FAIL);
try (SplitSource source = new BufferingSplitSource(mockSource, 100)) {
assertFutureFailsWithMockFailure(getNextBatch(s... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetName() {
assertEquals("Pipfile Analyzer", analyzer.getName());
} |
@Override
public Proxy find(final String target) {
final String route = this.findNative(target);
if(null == route) {
if(log.isInfoEnabled()) {
log.info(String.format("No proxy configuration found for target %s", target));
}
// Direct
re... | @Test
public void testFind() {
final SystemConfigurationProxy proxy = new SystemConfigurationProxy();
assertEquals(Proxy.Type.DIRECT, proxy.find("http://cyberduck.io").getType());
assertEquals(Proxy.Type.DIRECT, proxy.find("sftp://cyberduck.io").getType());
assertEquals(Proxy.Type.DI... |
@Override
public TimestampedSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final TimestampedSegment segment = super.getOrCreateSegmentIfLiv... | @Test
public void futureEventsShouldNotCauseSegmentRoll() {
updateStreamTimeAndCreateSegment(0);
verifyCorrectSegments(0, 1);
updateStreamTimeAndCreateSegment(1);
verifyCorrectSegments(0, 2);
updateStreamTimeAndCreateSegment(2);
verifyCorrectSegments(0, 3);
up... |
public void upgrade() {
for (final Document document : collection.find()) {
LOG.debug("Migrate view sharing: {}", document);
final ObjectId sharingId = document.getObjectId("_id");
final String sharingType = document.get("type", String.class);
final String viewId... | @Test
@DisplayName("migrate all-of-instance shares")
void migrateAllOfInstanceShares() throws Exception {
final GRN everyone = GRNRegistry.GLOBAL_USER_GRN;
when(roleService.load(anyString())).thenThrow(new NotFoundException());
final GRN dashboard2 = GRNTypes.DASHBOARD.toGRN("54e3deadb... |
@VisibleForTesting
public void validateDictTypeExists(String type) {
DictTypeDO dictType = dictTypeService.getDictType(type);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) {
... | @Test
public void testValidateDictTypeExists_success() {
// mock 方法,数据类型被禁用
String type = randomString();
when(dictTypeService.getDictType(eq(type))).thenReturn(randomDictTypeDO(type));
// 调用, 成功
dictDataService.validateDictTypeExists(type);
} |
@Override
public GlobalBeginRequestProto convert2Proto(GlobalBeginRequest globalBeginRequest) {
final short typeCode = globalBeginRequest.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNumber(typeCode)).b... | @Test
public void convert2Proto() {
GlobalBeginRequest globalBeginRequest = new GlobalBeginRequest();
globalBeginRequest.setTimeout(3000);
globalBeginRequest.setTransactionName("taa");
GlobalBeginRequestConvertor convertor = new GlobalBeginRequestConvertor();
GlobalBeginRequ... |
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case PostgreSql.ID -> "SMALLINT";
case Oracle.ID -> "NUMBER(3)";
case MsSql.ID, H2.ID -> "TINYINT";
default -> throw new UnsupportedOperationException(String.format("Unknown dialect '%s'", dialect.... | @Test
public void fail_with_UOE_to_generate_sql_type_when_unknown_dialect() {
assertThatThrownBy(() -> {
TinyIntColumnDef def = new TinyIntColumnDef.Builder()
.setColumnName("foo")
.setIsNullable(true)
.build();
Dialect dialect = mock(Dialect.class);
when(dialect.getId()... |
@Override
public DataSink createDataSink(Context context) {
// Validate the configuration
FactoryHelper.createFactoryHelper(this, context).validate();
// Get the configuration directly from the context
Configuration configuration =
Configuration.fromMap(context.getFa... | @Test
void testPrefixedRequiredOption() {
DataSinkFactory sinkFactory = getElasticsearchDataSinkFactory();
Configuration conf =
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("hosts", "localhost:9200")
... |
@Override
public void trackInstallation(String eventName, JSONObject properties, boolean disableCallback) {
} | @Test
public void testTrackInstallation() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
... |
@Override
public ConfigErrors errors() {
return errors;
} | @Test
public void shouldValidateCorrectPipelineLabelWithTruncationSyntax() {
String labelFormat = "pipeline-${COUNT}-${git[:7]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(nullVa... |
public void visit(Entry entry) {
final AFreeplaneAction action = new EntryAccessor().getAction(entry);
if (action != null) {
entries.unregisterEntry(action, entry);
if(! entries.contains(action))
acceleratorMap.removeActionAccelerator(freeplaneActions, action);
}
} | @Test
public void unregistersEntryWithAction() {
Entry actionEntry = new Entry();
final AFreeplaneAction action = mock(AFreeplaneAction.class);
IAcceleratorMap acceleratorMap= mock(IAcceleratorMap.class);
FreeplaneActions freeplaneActions= mock(FreeplaneActions.class);
new EntryAccessor().setAction(actionEnt... |
@Override
public final void isEqualTo(@Nullable Object other) {
super.isEqualTo(other);
} | @Test
@GwtIncompatible("Math.nextAfter")
public void testFloatConstants_matchNextAfter() {
assertThat(Math.nextAfter(Float.MAX_VALUE, 0.0f)).isEqualTo(NEARLY_MAX);
assertThat(Math.nextAfter(-1.0f * Float.MAX_VALUE, 0.0f)).isEqualTo(NEGATIVE_NEARLY_MAX);
assertThat(Math.nextAfter(Float.MIN_VALUE, 1.0f)).... |
@Override
public void bounce(final Local file) {
synchronized(NSWorkspace.class) {
NSDistributedNotificationCenter.defaultCenter().postNotification(
NSNotification.notificationWithName("com.apple.DownloadFileFinished", file.getAbsolute())
);
}
} | @Test
public void testBounce() throws Exception {
new WorkspaceApplicationLauncher().bounce(new NullLocal("t"));
final NullLocal file = new NullLocal(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
LocalTouchFactory.get().touch(file);
new WorkspaceApplicationLaun... |
public CompletableFuture<Void> commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets) {
if (offsets.isEmpty()) {
log.debug("Skipping commit of empty offsets");
return CompletableFuture.completedFuture(null);
}
OffsetCommitRequestState commitRequest = createOffs... | @Test
public void testPollSkipIfCoordinatorUnknown() {
CommitRequestManager commitRequestManager = create(false, 0);
assertPoll(false, 0, commitRequestManager);
Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
offsets.put(new TopicPartition("t1", 0), new OffsetAndMe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.