focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat(
String groupId,
String memberId,
int memberEpoch,
String instanceId,
String rackId,
int rebalanceTimeoutMs,
String clientId,
String clientHost,
... | @Test
public void testShouldThrowFencedInstanceIdExceptionWhenStaticMemberWithDifferentMemberIdLeaves() {
String groupId = "fooup";
// Use a static member id as it makes the test easier.
String memberId1 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
St... |
@Override
public String convertDestination(ProtocolConverter converter, Destination d) {
if (d == null) {
return null;
}
ActiveMQDestination activeMQDestination = (ActiveMQDestination)d;
String physicalName = activeMQDestination.getPhysicalName();
String rc = con... | @Test(timeout = 10000)
public void testConvertCompositeQueues() throws Exception {
String destinationA = "destinationA";
String destinationB = "destinationB";
String composite = "/queue/" + destinationA + ",/queue/" + destinationB;
ActiveMQDestination destination = translator.conve... |
@Override
public String getTargetRestEndpointURL() {
return "/jobs/:" + JobIDPathParameter.KEY + "/metrics";
} | @Test
void testUrl() {
assertThat(jobMetricsHeaders.getTargetRestEndpointURL())
.isEqualTo("/jobs/:" + JobIDPathParameter.KEY + "/metrics");
} |
@Override
public double mean() {
return k * theta;
} | @Test
public void testMean() {
System.out.println("var");
GammaDistribution instance = new GammaDistribution(3, 2.1);
instance.rand();
assertEquals(6.3, instance.mean(), 1E-7);
} |
@Override
public void publishLeaderInformation(String componentId, LeaderInformation leaderInformation) {
Preconditions.checkState(running.get());
if (!leaderLatch.hasLeadership()) {
return;
}
final String connectionInformationPath =
ZooKeeperUtils.gener... | @Test
void testPublishLeaderInformation() throws Exception {
new Context() {
{
runTest(
() -> {
leaderElectionListener.await(LeaderElectionEvent.IsLeaderEvent.class);
final String componentId = "retr... |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
return createFromImage(document, image, 0.75f);
} | @Test
void testCreateFromImageINT_ARGB() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(JPEGFactoryTest.class.getResourceAsStream("jpeg.jpg"));
// create an ARGB image
int width = image.getWidth();
int height = image.getHe... |
public static Map<String, Object> appendDeserializerToConfig(Map<String, Object> configs,
Deserializer<?> keyDeserializer,
Deserializer<?> valueDeserializer) {
// validate deserializ... | @Test
public void testAppendDeserializerToConfig() {
Map<String, Object> configs = new HashMap<>();
configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializerClass);
configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializerClass);
Map<String, Object... |
public Set<Route> getRoutes() {
ImmutableSet.Builder<Route> routes = ImmutableSet.builder();
array.forEach(route -> {
try {
IpPrefix prefix = IpPrefix.valueOf(route.path(PREFIX).asText());
IpAddress nextHop = IpAddress.valueOf(route.path(NEXTHOP).asText());
... | @Test
public void getRoutes() throws Exception {
assertThat(config.getRoutes(), is(EXPECTED_ROUTES));
assertThat(config.getRoutes(), not(UNEXPECTED_ROUTES));
} |
public static ByteBuffer serializeSubscription(final Subscription subscription) {
return serializeSubscription(subscription, ConsumerProtocolSubscription.HIGHEST_SUPPORTED_VERSION);
} | @Test
public void serializeSubscriptionShouldOrderOwnedPartitions() {
assertEquals(
ConsumerProtocol.serializeSubscription(
new Subscription(Arrays.asList("foo", "bar"), null, Arrays.asList(tp1, tp2))
),
ConsumerProtocol.serializeSubscription(
... |
@Override
public String toString() {
return toStringHelper(getClass())
.add("chassisId", Arrays.toString(chassisId.getValue()))
.add("portId", Arrays.toString(portId.getValue()))
.add("ttl", Arrays.toString(ttl.getValue()))
.add("ethType", Shor... | @Test
public void testToStringLLDP() throws Exception {
LLDP lldp = deserializer.deserialize(bytes, 0, bytes.length);
String str = lldp.toString();
// TODO: need to add LLDP toString unit test
} |
Object getCellValue(Cell cell, Schema.FieldType type) {
ByteString cellValue = cell.getValue();
int valueSize = cellValue.size();
switch (type.getTypeName()) {
case BOOLEAN:
checkArgument(valueSize == 1, message("Boolean", 1));
return cellValue.toByteArray()[0] != 0;
case BYTE:
... | @Test
public void shouldFailParseInt16TypeTooLong() {
byte[] value = new byte[6];
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> PARSER.getCellValue(cell(value), INT16));
checkMessage(exception.getMessage(), "Int16 has to be 2-bytes long bytearray");
} |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnNonInstantiableActionReturnTypeRef() {
@RestLiCollection(name = "invalidActionReturnType")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> {
@Action(name = "nonInstantiableTypeRef", returnTyperef = Broke... |
public void launch(Monitored mp) {
if (!lifecycle.tryToMoveTo(Lifecycle.State.STARTING)) {
throw new IllegalStateException("Already started");
}
monitored = mp;
Logger logger = LoggerFactory.getLogger(getClass());
try {
launch(logger);
} catch (Exception e) {
logger.warn("Fail... | @Test
public void terminate_if_startup_error() throws IOException {
Props props = createProps();
final ProcessEntryPoint entryPoint = new ProcessEntryPoint(props, exit, commands, runtime);
final Monitored process = mock(Monitored.class);
doThrow(IllegalStateException.class).when(process).start();
... |
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
} | @Test
public void shouldPostQueryRequest() {
// Given:
List<StreamedRow> expectedResponse = new ArrayList<>();
for (int i = 0; i < 10; i++) {
GenericRow row = GenericRow.genericRow("foo", 123, true);
StreamedRow sr = StreamedRow.pushRow(row);
expectedResponse.add(sr);
}
server.s... |
public static String decapitalize(String string) {
return string == null ? null : string.substring( 0, 1 ).toLowerCase( Locale.ROOT ) + string.substring( 1 );
} | @Test
public void testDecapitalize() {
assertThat( Strings.decapitalize( null ) ).isNull();
assertThat( Strings.decapitalize( "c" ) ).isEqualTo( "c" );
assertThat( Strings.decapitalize( "capitalize" ) ).isEqualTo( "capitalize" );
assertThat( Strings.decapitalize( "AlreadyCapitalized"... |
public URI executionUrl(Execution execution) {
return this.build("/ui/" +
(execution.getTenantId() != null ? execution.getTenantId() + "/" : "") +
"executions/" +
execution.getNamespace() + "/" +
execution.getFlowId() + "/" +
execution.getId());
} | @Test
void executionUrl() {
Flow flow = TestsUtils.mockFlow();
Execution execution = TestsUtils.mockExecution(flow, ImmutableMap.of());
assertThat(uriProvider.executionUrl(execution).toString(), containsString("mysuperhost.com/subpath/ui"));
assertThat(uriProvider.executionUrl(execu... |
public int listOpenFiles(String[] argv) throws IOException {
String path = null;
List<OpenFilesType> types = new ArrayList<>();
if (argv != null) {
List<String> args = new ArrayList<>(Arrays.asList(argv));
if (StringUtils.popOption("-blockingDecommission", args)) {
types.add(OpenFilesTyp... | @Test(timeout = 300000L)
public void testListOpenFiles() throws Exception {
redirectStream();
final Configuration dfsConf = new HdfsConfiguration();
dfsConf.setInt(
DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 500);
dfsConf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1);
dfsConf.set... |
static boolean isInvalidLocalHost(String host) {
return StringUtils.isBlank(host)
|| isAnyHost(host)
|| isLocalHost(host);
} | @Test
public void isInvalidLocalHost() throws Exception {
Assert.assertTrue(NetUtils.isInvalidLocalHost("0.0.0.0"));
Assert.assertTrue(NetUtils.isInvalidLocalHost("127.0.0.1"));
Assert.assertTrue(NetUtils.isInvalidLocalHost(""));
Assert.assertTrue(NetUtils.isInvalidLocalHost(" "));
... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "date_format", argTypes = {DATETIME, VARCHAR}, returnType = VARCHAR, isMonotonic = true),
@ConstantFunction(name = "date_format", argTypes = {DATE, VARCHAR}, returnType = VARCHAR, isMonotonic = true)
})
public static ConstantOperat... | @Test
public void dateFormat() {
Locale.setDefault(Locale.ENGLISH);
ConstantOperator testDate = ConstantOperator.createDatetime(LocalDateTime.of(2001, 1, 9, 13, 4, 5));
assertEquals("1",
ScalarOperatorFunctions.dateFormat(testDate, ConstantOperator.createVarchar("%c")).getVar... |
@Override
public void deregisterInstance(String serviceName, String ip, int port) throws NacosException {
deregisterInstance(serviceName, ip, port, Constants.DEFAULT_CLUSTER_NAME);
} | @Test
void testDeregisterInstance4() throws NacosException {
//given
String serviceName = "service1";
String groupName = "group1";
String clusterName = "cluster1";
String ip = "1.1.1.1";
int port = 10000;
//when
client.deregisterInstance(serviceName, g... |
public static ParameterizedType mapOf(Type keyType, Type valueType) {
return parameterizedType(Map.class, keyType, valueType);
} | @Test
public void createMapType() {
ParameterizedType type = Types.mapOf(String.class, Person.class);
assertThat(type.getRawType()).isEqualTo(Map.class);
assertThat(type.getActualTypeArguments()).isEqualTo(new Type[] {String.class, Person.class});
} |
@Override
public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) {
for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) {
Map<String, ?> sourceOffset = offsetEntry.getValue();
if (sourceOffset == null)... | @Test
public void testAlterOffsetsIncorrectPartitionKey() {
MirrorSourceConnector connector = new MirrorSourceConnector();
assertThrows(ConnectException.class, () -> connector.alterOffsets(null, Collections.singletonMap(
Collections.singletonMap("unused_partition_key", "unused_partit... |
String deleteAll(int n) {
return deleteAllQueries.computeIfAbsent(n, deleteAllFactory);
} | @Test
public void testDeleteAllIsEscaped() {
Queries queries = new Queries(mappingEscape, idColumnEscape, columnMetadataEscape);
String result = queries.deleteAll(2);
assertEquals("DELETE FROM \"my\"\"mapping\" WHERE \"i\"\"d\" IN (?, ?)", result);
} |
@Override
@SuppressWarnings("unchecked")
public int run() throws IOException {
Preconditions.checkArgument(targets != null && targets.size() == 1, "Parquet file is required.");
if (targets.size() > 1) {
Preconditions.checkArgument(outputPath == null, "Cannot output multiple schemas to file %s", outpu... | @Test(expected = FileAlreadyExistsException.class)
public void testSchemaCommandOverwriteExistentFileWithoutOverwriteOption() throws IOException {
File inputFile = parquetFile();
File outputFile = new File(getTempFolder(), getClass().getSimpleName() + ".avsc");
FileUtils.touch(outputFile);
SchemaComma... |
public char getLeftSymbol() {
return leftSymbol;
} | @Test
public void testGetLeftSymbol() {
char expectedLeftSymbol = '"';
EscapeSymbol escapeSymbol = new EscapeSymbol(expectedLeftSymbol, '"');
assertEquals(expectedLeftSymbol, escapeSymbol.getLeftSymbol(),
"The left symbol should be '" + expectedLeftSymbol + "'");
} |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void floatLiteral() {
String inputExpression = "10.5";
BaseNode number = parse( inputExpression );
assertThat( number).isInstanceOf(NumberNode.class);
assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertLocation( inputExpression, number );
} |
public static UExpressionStatement create(UExpression expression) {
return new AutoValue_UExpressionStatement(expression);
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UExpressionStatement.create(
UBinary.create(Kind.PLUS, ULiteral.intLit(5), ULiteral.intLit(2))));
} |
@Override
public void init(Collection<T> allObjectsToTest) {
condition.init(allObjectsToTest);
} | @Test
public void inits_inverted_condition() {
ConditionWithInitAndFinish original = someCondition("anything");
ArchCondition<String> never = never(original);
never.init(Collections.singleton("something"));
assertThat(original.allObjectsToTest).containsExactly("something");
} |
protected String buildPrefix(String pluginName, String apiVersion) {
GroupVersion groupVersion = GroupVersion.parseAPIVersion(apiVersion);
if (StringUtils.hasText(groupVersion.group())) {
// apis/{group}/{version}
return String.format("/apis/%s/%s", groupVersion.group(), groupVer... | @Test
void buildPrefix() {
String s = handlerMapping.buildPrefix("fakePlugin", "v1");
assertThat(s).isEqualTo("/apis/api.plugin.halo.run/v1/plugins/fakePlugin");
s = handlerMapping.buildPrefix("fakePlugin", "fake.halo.run/v1alpha1");
assertThat(s).isEqualTo("/apis/fake.halo.run/v1al... |
@Override
public ConsumeStats examineConsumeStats(
String consumerGroup) throws RemotingException, MQClientException, InterruptedException,
MQBrokerException {
return examineConsumeStats(consumerGroup, null);
} | @Ignore
@Test
public void testExamineConsumeStats() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
ConsumeStats consumeStats = defaultMQAdminExt.examineConsumeStats("default-consumer-group", "unit-test");
assertThat(consumeStats.getConsumeTps()).isGreaterT... |
private synchronized RemotingCommand updateAndCreateTopic(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
long startTime = System.currentTimeMillis();
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final CreateTopicRequ... | @Test
public void testUpdateAndCreateTopic() throws Exception {
//test system topic
for (String topic : systemTopicSet) {
RemotingCommand request = buildCreateTopicRequest(topic);
RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request);
... |
public static int nextCapacity(int current) {
assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two.";
if (current < MIN_CAPACITY / 2) {
current = MIN_CAPACITY / 2;
}
current <<= 1;
if (current < 0) {
throw new RuntimeExcep... | @Test
public void testNextCapacity_withLong_shouldIncreaseToHalfOfMinCapacity() {
long capacity = 1;
long nextCapacity = nextCapacity(capacity);
assertEquals(4, nextCapacity);
} |
public void initializeSession(AuthenticationRequest authenticationRequest, SAMLBindingContext bindingContext) throws SamlSessionException, SharedServiceClientException {
final String httpSessionId = authenticationRequest.getRequest().getSession().getId();
if (authenticationRequest.getFederationName() !... | @Test
public void noSupportedIDPTest() throws SamlSessionException, SharedServiceClientException {
IDPList idpList = OpenSAMLUtils.buildSAMLObject(IDPList.class);
IDPEntry idpEntry = OpenSAMLUtils.buildSAMLObject(IDPEntry.class);
idpEntry.setProviderID("OtherIdP");
Scoping scoping =... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testDifferentCodecCausesRecompression() {
List<byte[]> records = Arrays.asList(
"somedata".getBytes(),
"moredata".getBytes()
);
// Records from the producer were created with gzip max level
Compression gzipMax = Compression.gzip().le... |
@VisibleForTesting
WriteOptions getOptions() {
return options;
} | @Test
public void testDefaultWriteOptionsHaveDisabledWAL() throws Exception {
WriteOptions options;
try (RocksDB db = RocksDB.open(folder.newFolder().getAbsolutePath());
RocksDBWriteBatchWrapper writeBatchWrapper =
new RocksDBWriteBatchWrapper(db, null, 200, 5... |
public static LeaderInformationRegister clear(
@Nullable LeaderInformationRegister leaderInformationRegister, String componentId) {
if (leaderInformationRegister == null
|| !leaderInformationRegister.getRegisteredComponentIds().iterator().hasNext()) {
return LeaderInforma... | @Test
void testClear() {
final String componentId = "component-id";
final LeaderInformation leaderInformation =
LeaderInformation.known(UUID.randomUUID(), "address");
final LeaderInformationRegister initialRegister =
LeaderInformationRegister.of(componentId, ... |
@Override
public BasicTypeDefine reconvert(Column column) {
BasicTypeDefine.BasicTypeDefineBuilder builder =
BasicTypeDefine.builder()
.name(column.getName())
.nullable(column.isNullable())
.comment(column.getComment())
... | @Test
public void testReconvertBoolean() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.BOOLEAN_TYPE).build();
BasicTypeDefine typeDefine = SapHanaTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getNa... |
public JChannel getChannel() {
return channel;
} | @Test
public void shouldCreateChannel() {
// When
JGroupsEndpoint endpoint = getMandatoryEndpoint("my-default-jgroups:" + CLUSTER_NAME, JGroupsEndpoint.class);
JGroupsComponent component = (JGroupsComponent) endpoint.getComponent();
// Then
assertNotNull(component.getChannel... |
Span handleStart(HttpRequest request, Span span) {
if (span.isNoop()) return span;
try {
parseRequest(request, span);
} catch (Throwable t) {
propagateIfFatal(t);
Platform.get().log("error parsing request {0}", request, t);
} finally {
// all of the above parsing happened before... | @Test void handleStart_addsRemoteEndpointWhenParsed() {
handler = new HttpHandler(HttpRequestParser.DEFAULT, HttpResponseParser.DEFAULT) {
@Override void parseRequest(HttpRequest request, Span span) {
span.remoteIpAndPort("1.2.3.4", 0);
}
};
handler.handleStart(request, span);
veri... |
@Override
public Iterable<FileInfo> listPrefix(String prefix) {
Path prefixToList = new Path(prefix);
FileSystem fs = Util.getFs(prefixToList, hadoopConf.get());
return () -> {
try {
return Streams.stream(
new AdaptingIterator<>(fs.listFiles(prefixToList, true /* recursive *... | @Test
public void testListPrefix() {
Path parent = new Path(tempDir.toURI());
List<Integer> scaleSizes = Lists.newArrayList(1, 1000, 2500);
scaleSizes
.parallelStream()
.forEach(
scale -> {
Path scalePath = new Path(parent, Integer.toString(scale));
... |
@Bean
public ShenyuPlugin dividePlugin() {
return new DividePlugin();
} | @Test
public void testDividePlugin() {
applicationContextRunner.run(context -> {
ShenyuPlugin plugin = context.getBean("dividePlugin", ShenyuPlugin.class);
assertNotNull(plugin);
}
);
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
new BrickAttributesFinderFeature(session).find(file);
return true;
}
catch(NotfoundException e) {
return false;
}
} | @Test
public void testFindFile() throws Exception {
final Path file = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new BrickTouchFeature(session).touch(file, new TransferStatus());
assertTrue(new BrickFind... |
@Override
public boolean checkCredentials(String username, String password) {
if (username == null || password == null) {
return false;
}
Credentials credentials = new Credentials(username, password);
if (validCredentialsCache.contains(credentials)) {
return ... | @Test
public void testPBKDF2WithHmacSHA1_withoutColon() throws Exception {
String algorithm = "PBKDF2WithHmacSHA1";
int iterations = 1000;
int keyLength = 128;
String hash =
"17:87:CA:B9:14:73:60:36:8B:20:82:87:92:58:43:B8:A3:85:66:BC:C1:6D:C3:31:6C:1D:47:48:C7:F2:E4:... |
public static <T extends Message> ProtoCoder<T> of(Class<T> protoMessageClass) {
return new ProtoCoder<>(protoMessageClass, ImmutableSet.of());
} | @Test
public void testCoderEncodeDecodeEqualNestedContext() throws Exception {
MessageA value1 =
MessageA.newBuilder()
.setField1("hello")
.addField2(MessageB.newBuilder().setField1(true).build())
.addField2(MessageB.newBuilder().setField1(false).build())
.b... |
public CompletableFuture<InetSocketAddress> resolveAndCheckTargetAddress(String hostAndPort) {
int pos = hostAndPort.lastIndexOf(':');
String host = hostAndPort.substring(0, pos);
int port = Integer.parseInt(hostAndPort.substring(pos + 1));
if (!isPortAllowed(port)) {
return ... | @Test
public void shouldAllowIPv6AddressNumeric() throws Exception {
BrokerProxyValidator brokerProxyValidator = new BrokerProxyValidator(
createMockedAddressResolver("fd4d:801b:73fa:abcd:0000:0000:0000:0001"),
"*"
, "fd4d:801b:73fa:abcd::/64"
... |
@Override
public AppResponse process(Flow flow, ActivateWithCodeRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
Map<String, Object> result = digidClient.activateAccountWithCode(appSession.getAccountId(), request.getActivationCode());
if (result.get(lowerUnd... | @Test
public void responseTestNOK() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
//given
when(digidClientMock.activateAccountWithCode(anyLong(), any())).thenReturn(Map.of(
lowerUnderscore(STATUS), "NOK"
));
//when
AppResponse result = ac... |
public void parse( RepositoryElementReadListener repositoryElementReadListener )
throws SAXException, ParserConfigurationException, IOException {
this.repositoryElementReadListener = repositoryElementReadListener;
SAXParserFactory factory = XMLParserFactoryProducer.createSecureSAXParserFactory();
this.... | @Test
public void testNoExceptionOccurs_WhenNameContainsJapaneseCharacters() throws Exception {
repExpSAXParser = new RepositoryExportSaxParser( getRepositoryFile().getCanonicalPath(), repImpPgDlg );
try {
repExpSAXParser.parse( repImpMock );
} catch ( Exception e ) {
Assert.fail( "No exceptio... |
Object getFromSignal(String signalName, String paramName) {
try {
return executor
.submit(() -> fromSignal(signalName, paramName))
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(
e,
"getFromSignal throws ... | @Test
public void testGetFromSignal() {
SignalInitiator initiator = Mockito.mock(SignalInitiator.class);
when(instanceWrapper.getInitiator()).thenReturn(initiator);
when(initiator.getType()).thenReturn(Initiator.Type.SIGNAL);
when(initiator.getParams())
.thenReturn(
twoItemMap(
... |
public static int cityHash32(byte[] data) {
return CityHash.hash32(data);
} | @Test
public void cityHash32Test(){
String s="Google发布的Hash计算算法:CityHash64 与 CityHash128";
final int hash = HashUtil.cityHash32(StrUtil.utf8Bytes(s));
assertEquals(0xa8944fbe, hash);
} |
public ProtocolBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
} | @Test
void isDefault() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.isDefault(true);
Assertions.assertTrue(builder.build().isDefault());
} |
@Override
public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) {
AuthorityRule rule = ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class);
if (MySQLConnecti... | @Test
void assertAuthenticateFailedWithAbsentUser() {
setConnectionPhase(MySQLConnectionPhase.AUTH_PHASE_FAST_PATH);
AuthorityRule rule = mock(AuthorityRule.class);
when(rule.getAuthenticatorType(any())).thenReturn("");
when(rule.findUser(new Grantee("root", "127.0.0.1"))).thenReturn... |
private static void addInputPath(JobConf conf, Path path, Schema inputSchema) {
String schemaMapping = path.toString() + ";" + toBase64(inputSchema.toString());
String schemas = conf.get(SCHEMA_KEY);
conf.set(SCHEMA_KEY, schemas == null ? schemaMapping : schemas + "," + schemaMapping);
conf.setInputF... | @Test
void job() throws Exception {
JobConf job = new JobConf();
Path inputPath1 = new Path(INPUT_DIR_1.getPath());
Path inputPath2 = new Path(INPUT_DIR_2.getPath());
Path outputPath = new Path(OUTPUT_DIR.getPath());
outputPath.getFileSystem(job).delete(outputPath, true);
writeNamesFiles(new... |
public void hasValue(@Nullable Object expected) {
if (expected == null) {
throw new NullPointerException("Optional cannot have a null value.");
}
if (actual == null) {
failWithActual("expected an optional with value", expected);
} else if (!actual.isPresent()) {
failWithoutActual(fact(... | @Test
public void hasValue_failingWithWrongValue() {
expectFailureWhenTestingThat(Optional.of("foo")).hasValue("boo");
assertFailureValue("value of", "optional.get()");
} |
public static MountTable newInstance() {
MountTable record = StateStoreSerializer.newRecord(MountTable.class);
record.init();
return record;
} | @Test
public void testValidation() throws IOException {
Map<String, String> destinations = new HashMap<>();
destinations.put("ns0", "/testValidate-dest");
try {
MountTable.newInstance("testValidate", destinations);
fail("Mount table entry should be created failed.");
} catch (Exception e) ... |
public String format() {
final StringBuilder sb = new StringBuilder();
if (betweenMs > 0) {
long day = betweenMs / DateUnit.DAY.getMillis();
long hour = betweenMs / DateUnit.HOUR.getMillis() - day * 24;
long minute = betweenMs / DateUnit.MINUTE.getMillis() - day * 24 * 60 - hour * 60;
final long Betwee... | @Test
public void formatTest() {
long betweenMs = DateUtil.betweenMs(DateUtil.parse("2017-01-01 22:59:59"), DateUtil.parse("2017-01-02 23:59:58"));
BetweenFormatter formater = new BetweenFormatter(betweenMs, Level.MILLISECOND, 1);
assertEquals(formater.toString(), "1天");
} |
@Override
@SuppressWarnings("ProtoFieldNullComparison")
public List<IncomingMessage> pull(
long requestTimeMsSinceEpoch,
SubscriptionPath subscription,
int batchSize,
boolean returnImmediately)
throws IOException {
PullRequest request =
new PullRequest().setReturnImmediatel... | @Test
public void pullOneMessageEmptyAttributes() throws IOException {
client = new PubsubJsonClient(null, null, mockPubsub);
String expectedSubscription = SUBSCRIPTION.getPath();
PullRequest expectedRequest = new PullRequest().setReturnImmediately(true).setMaxMessages(10);
PubsubMessage expectedPubsu... |
@Deprecated
public URLNormalizer addTrailingSlash() {
return addDirectoryTrailingSlash();
} | @Test
public void testAddTrailingSlash() {
s = "http://www.example.com/alice";
t = "http://www.example.com/alice/";
assertEquals(t, n(s).addDirectoryTrailingSlash().toString());
s = "http://www.example.com/alice.html";
t = "http://www.example.com/alice.html";
assertEq... |
@Override
protected void validateDataImpl(TenantId tenantId, Alarm alarm) {
validateString("Alarm type", alarm.getType());
if (alarm.getOriginator() == null) {
throw new DataValidationException("Alarm originator should be specified!");
}
if (alarm.getSeverity() == null) {... | @Test
void testValidateNameInvocation() {
Alarm alarm = new Alarm();
alarm.setType("overheating");
alarm.setOriginator(tenantId);
alarm.setSeverity(AlarmSeverity.CRITICAL);
alarm.setCleared(false);
alarm.setAcknowledged(false);
alarm.setTenantId(tenantId);
... |
static void run(
final SystemExit systemExit,
final String... args
) throws Throwable {
final Arguments arguments = new Arguments.Builder()
.parseArgs(args)
.build();
if (arguments.help) {
usage();
return;
}
final Properties props = getProperties(arguments);
... | @Test(expected = IllegalArgumentException.class)
public void shouldThrowIfKeyFieldDoesNotExist() throws Throwable {
DataGen.run(
mockSystem,
"key=not_a_field",
"schema=./src/main/resources/purchase.avro",
"format=avro",
"topic=foo"
);
} |
public static int symLink(String target, String linkname) throws IOException{
if (target == null || linkname == null) {
LOG.warn("Can not create a symLink with a target = " + target
+ " and link =" + linkname);
return 1;
}
// Run the input paths through Java's File so that they are c... | @Test (timeout = 30000)
public void testSymlinkRenameTo() throws Exception {
File file = new File(del, FILE);
file.createNewFile();
File link = new File(del, "_link");
// create the symlink
FileUtil.symLink(file.getAbsolutePath(), link.getAbsolutePath());
Verify.exists(file);
Verify.exis... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_File() throws Exception {
String input = getPath("secret.json").toAbsolutePath().toString();
String output = resolve("${readFile:" + input + "}");
assertThat(output, equalTo(FILE.lookup(input)));
assertThat(output, containsString("\"Our secret\": \"Hello Wor... |
public static JibContainerBuilder toJibContainerBuilder(
ArtifactProcessor processor,
CommonCliOptions commonCliOptions,
CommonContainerConfigCliOptions commonContainerConfigCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {
String baseImage = common... | @Test
public void testToJibContainerBuilder_noProgramArgumentsSpecified()
throws IOException, InvalidImageReferenceException {
JibContainerBuilder containerBuilder =
WarFiles.toJibContainerBuilder(
mockStandardWarExplodedProcessor,
mockCommonCliOptions,
mockCommon... |
protected void acknowledgeTask(TaskAcknowledgeOperation ackOperation) {
final long checkpointId = ackOperation.getBarrier().getId();
final PendingCheckpoint pendingCheckpoint = pendingCheckpoints.get(checkpointId);
if (pendingCheckpoint == null) {
LOG.info("skip already ack checkpoin... | @Test
void testACKNotExistPendingCheckpoint() throws CheckpointStorageException {
CheckpointConfig checkpointConfig = new CheckpointConfig();
checkpointConfig.setStorage(new CheckpointStorageConfig());
Map<Integer, CheckpointPlan> planMap = new HashMap<>();
planMap.put(1, CheckpointP... |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void build_query_which_created_from_Q_b_without_select_and_sources() {
String q = Q.p("f1").contains("v1")
.build();
assertEquals(q, "yql=select * from sources * where f1 contains \"v1\"");
} |
@Override
public ExplodedPlugin explode(PluginInfo info) {
try {
File dir = unzipFile(info.getNonNullJarFile());
return explodeFromUnzippedDir(info, info.getNonNullJarFile(), dir);
} catch (Exception e) {
throw new IllegalStateException(String.format("Fail to open plugin [%s]: %s", info.getK... | @Test
public void extract_only_libs() throws IOException {
File jar = loadFile("sonar-checkstyle-plugin-2.8.jar");
underTest.explode(PluginInfo.create(jar));
assertThat(new File(jar.getParent(), "sonar-checkstyle-plugin-2.8.jar")).exists();
assertThat(new File(jar.getParent(), "sonar-checkstyle-plug... |
public static void main(String[] args) {
LOGGER.info("Use superpower: sky launch");
var skyLaunch = new SkyLaunch();
skyLaunch.activate();
LOGGER.info("Use superpower: ground dive");
var groundDive = new GroundDive();
groundDive.activate();
} | @Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static String getSpaces( int SpacesCount ) {
//
if ( SpacesCount < 0 ) return "?";
//
String Info = "";
//
for ( int K = 1; K <= SpacesCount; K ++ ) {
Info += " ";
}
//
//
return Info;
} | @Test
public void testgetSpaces() throws Exception {
//
assertEquals( "?", BTools.getSpaces( -3 ) );
assertEquals( "", BTools.getSpaces( 0 ) );
assertEquals( " ", BTools.getSpaces( 4 ) );
//
} |
@Override
public void reset() throws IOException {
createDirectory(PATH_DATA.getKey());
createDirectory(PATH_WEB.getKey());
createDirectory(PATH_LOGS.getKey());
File tempDir = createOrCleanTempDirectory(PATH_TEMP.getKey());
try (AllProcessesCommands allProcessesCommands = new AllProcessesCommands(... | @Test
public void fail_if_required_directory_is_a_file() throws Exception {
// <home>/data is missing
FileUtils.forceMkdir(webDir);
FileUtils.forceMkdir(logsDir);
FileUtils.touch(dataDir);
assertThatThrownBy(() -> underTest.reset())
.isInstanceOf(IllegalStateException.class)
.hasMessa... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testNotFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
int[] expectedHistorySnapshot = {1, 2};
testHistory(history, expectedHistorySnapshot);
} |
@Operation(summary = "updateTenant", description = "UPDATE_TENANT_NOTES")
@Parameters({
@Parameter(name = "id", description = "TENANT_ID", required = true, schema = @Schema(implementation = int.class, example = "100")),
@Parameter(name = "tenantCode", description = "TENANT_CODE", required = ... | @Test
public void testUpdateTenant() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("id", "9");
paramsMap.add("tenantCode", "cxc_te");
paramsMap.add("queueId", "1");
paramsMap.add("description", "tenant description");
... |
public void generate() throws IOException
{
packageNameByTypes.clear();
generatePackageInfo();
generateTypeStubs();
generateMessageHeaderStub();
for (final List<Token> tokens : ir.messages())
{
final Token msgToken = tokens.get(0);
final List<... | @Test
void shouldCreateTypesInSamePackageIfSupportDisabled() throws Exception
{
try (InputStream in = Tests.getLocalResource("explicit-package-test-schema.xml"))
{
final ParserOptions options = ParserOptions.builder().stopOnError(true).build();
final MessageSchema schema ... |
public static String ltrim( String source ) {
if ( source == null ) {
return null;
}
int from = 0;
while ( from < source.length() && isSpace( source.charAt( from ) ) ) {
from++;
}
return source.substring( from );
} | @Test
public void testLtrim() {
assertEquals( null, Const.ltrim( null ) );
assertEquals( "", Const.ltrim( "" ) );
assertEquals( "", Const.ltrim( " " ) );
assertEquals( "test ", Const.ltrim( "test " ) );
assertEquals( "test ", Const.ltrim( " test " ) );
} |
public Command create(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext context) {
return create(statement, context.getServiceContext(), context);
} | @Test
public void shouldCreateCommandForTerminateQuery() {
// Given:
givenTerminate();
// When:
final Command command = commandFactory.create(configuredStatement, executionContext);
// Then:
assertThat(command, is(Command.of(configuredStatement)));
} |
@Override
public int size() {
return to - from;
} | @Test
void testSize() {
RangeSet rangeSet = new RangeSet(5, 10);
assertEquals(5, rangeSet.size());
} |
@Override
public String getPonLinks(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId();
... | @Test
public void testInvalidGetPonLinksInput() throws Exception {
String reply;
String target;
for (int i = ZERO; i < INVALID_GET_TCS.length; i++) {
target = INVALID_GET_TCS[i];
reply = voltConfig.getPonLinks(target);
assertNull("Incorrect response for I... |
@Override
public String[] filterCipherSuites(Iterable<String> ciphers, List<String> defaultCiphers,
Set<String> supportedCiphers) {
if (ciphers == null) {
return defaultToDefaultCiphers ?
defaultCiphers.toArray(EmptyArrays.EMPTY_STRINGS) :
supp... | @Test
public void regularInstanceDefaultsToDefaultCiphers() {
List<String> defaultCiphers = Arrays.asList("FOO", "BAR");
Set<String> supportedCiphers = new HashSet<String>(Arrays.asList("BAZ", "QIX"));
String[] filtered = IdentityCipherSuiteFilter.INSTANCE
.filterCipherSuites... |
@Override
public void replay(
long offset,
long producerId,
short producerEpoch,
CoordinatorRecord record
) throws RuntimeException {
ApiMessageAndVersion key = record.key();
ApiMessageAndVersion value = record.value();
switch (key.version()) {
... | @Test
public void testReplayShareGroupMemberMetadataWithNullValue() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics... |
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
throws IOException {
EthCall ethCall =
web3j.ethCall(
Transaction.createEthCallTransaction(getFromAddress(), to, data),
... | @Test
void sendCallErrorRevertByCode() throws IOException {
EthCall lookupDataHex = new EthCall();
Response.Error error = new Response.Error();
error.setCode(10);
error.setData(responseData);
lookupDataHex.setError(error);
Request request = mock(Request.class);
... |
@PublicAPI(usage = ACCESS)
public JavaClasses importUrl(URL url) {
return importUrls(singletonList(url));
} | @Test
public void creates_relations_between_super_and_subclasses() {
JavaClasses classes = new ClassFileImporter().importUrl(getClass().getResource("testexamples/classhierarchyimport"));
JavaClass baseClass = classes.get(BaseClass.class);
JavaClass subclass = classes.get(Subclass.class);
... |
@Override
public double calculateDistance(int txPower, double rssi) {
if (mDistanceCalculator == null) {
LogManager.w(TAG, "distance calculator has not been set");
return -1.0;
}
return mDistanceCalculator.calculateDistance(txPower, rssi);
} | @Test
public void testCalculatesDistance() {
org.robolectric.shadows.ShadowLog.stream = System.err;
ModelSpecificDistanceCalculator distanceCalculator = new ModelSpecificDistanceCalculator(null, null);
Double distance = distanceCalculator.calculateDistance(-59, -59);
assertEquals("D... |
@Override
public String toString() {
return mOwnerBits.toString() + mGroupBits.toString() + mOtherBits.toString();
} | @Test
public void toStringTest() {
assertEquals("rwxrwxrwx", new Mode((short) 0777).toString());
assertEquals("rw-r-----", new Mode((short) 0640).toString());
assertEquals("rw-------", new Mode((short) 0600).toString());
assertEquals("---------", new Mode((short) 0000).toString());
} |
@Override
public void unregister(URL url) {
super.unregister(url);
unregistered(url);
} | @Test
void testUnregister() {
Set<URL> registered;
// register first
registry.register(serviceUrl);
registered = registry.getRegistered();
assertTrue(registered.contains(serviceUrl));
// then unregister
registered = registry.getRegistered();
registry... |
public void removeBe(long be) {
if (numHardwareCoresPerBe.remove(be) != null) {
cachedAvgNumHardwareCores.set(-1);
}
LOG.info("remove numHardwareCores of be [{}], current cpuCores stats: {}", be, numHardwareCoresPerBe);
if (memLimitBytesPerBe.remove(be) != null) {
... | @Test
public void testRemoveBe() {
BackendResourceStat stat = BackendResourceStat.getInstance();
stat.setNumHardwareCoresOfBe(0L, 8);
stat.setNumHardwareCoresOfBe(1L, 4);
assertThat(stat.getAvgNumHardwareCoresOfBe()).isEqualTo(6);
stat.setMemLimitBytesOfBe(0L, 100);
... |
@Override
public void loginFailure(HttpRequest request, AuthenticationException e) {
checkRequest(request);
requireNonNull(e, "AuthenticationException can't be null");
if (!LOGGER.isDebugEnabled()) {
return;
}
Source source = e.getSource();
LOGGER.debug("login failure [cause|{}][method|{... | @Test
public void login_failure_creates_DEBUG_log_with_empty_login_if_AuthenticationException_has_no_login() {
AuthenticationException exception = newBuilder().setSource(Source.sso()).setMessage("message").build();
underTest.loginFailure(mockRequest(), exception);
verifyLog("login failure [cause|message]... |
private int getNodeId() {
int nodeId = getNodeId(System.nanoTime());
assert nodeId > 0 || nodeId == NODE_ID_OUT_OF_RANGE : "getNodeId() returned invalid value: " + nodeId;
return nodeId;
} | @Test
public void when_nodeIdUpdated_then_pickedUpAfterUpdateInterval() {
when(clusterService.getMemberListJoinVersion()).thenReturn(20);
assertEquals(20, gen.getNodeId(0));
when(clusterService.getMemberListJoinVersion()).thenReturn(30);
assertEquals(20, gen.getNodeId(0));
a... |
@Override
public void preflight(final Path workdir, final String filename) throws BackgroundException {
if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) {
throw new AccessDeniedException(MessageFormat.f... | @Test
public void testNoAddChildrenFolder() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path folder = new Path("/ORG 1 - DeepBox Desktop App/ORG1:Box1/Documents/Bookkeeping", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttribute... |
void setHealth(Health health) {
model.setHealth(health);
} | @Test
void testSetHealth() {
final var model = new GiantModel("giant1", Health.HEALTHY, Fatigue.ALERT,
Nourishment.SATURATED);
assertEquals(Health.HEALTHY, model.getHealth());
var messageFormat = "Giant giant1, The giant looks %s, alert and saturated.";
for (final var health : Health.values())... |
@VisibleForTesting
static void validateWorkerSettings(DataflowPipelineWorkerPoolOptions workerOptions) {
DataflowPipelineOptions dataflowOptions = workerOptions.as(DataflowPipelineOptions.class);
validateSdkContainerImageOptions(workerOptions);
GcpOptions gcpOptions = workerOptions.as(GcpOptions.class);... | @Test
public void testAliasForLegacyWorkerHarnessContainerImage() {
DataflowPipelineWorkerPoolOptions options =
PipelineOptionsFactory.as(DataflowPipelineWorkerPoolOptions.class);
String testImage = "image.url:worker";
options.setWorkerHarnessContainerImage(testImage);
DataflowRunner.validateW... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testNonEquiOuterJoin()
{
analyze("SELECT * FROM t1 LEFT JOIN t2 ON t1.a + t2.a = 1");
analyze("SELECT * FROM t1 RIGHT JOIN t2 ON t1.a + t2.a = 1");
analyze("SELECT * FROM t1 LEFT JOIN t2 ON t1.a = t2.a OR t1.b = t2.b");
} |
public static String[][] assignExecutors(
List<? extends ScanTaskGroup<?>> taskGroups, List<String> executorLocations) {
Map<Integer, JavaHash<StructLike>> partitionHashes = Maps.newHashMap();
String[][] locations = new String[taskGroups.size()][];
for (int index = 0; index < taskGroups.size(); index... | @TestTemplate
public void testFileScanTaskWithoutDeletes() {
List<ScanTask> tasks =
ImmutableList.of(
new MockFileScanTask(mockDataFile(Row.of(1, "a")), SCHEMA, SPEC_1),
new MockFileScanTask(mockDataFile(Row.of(2, "b")), SCHEMA, SPEC_1),
new MockFileScanTask(mockDataFil... |
@Override
public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException {
} | @Test
void testUpdateInstance() throws Exception {
//TODO thrown.expect(UnsupportedOperationException.class);
client.updateInstance(SERVICE_NAME, GROUP_NAME, instance);
} |
@Bean
public ShenyuPlugin redirectPlugin(final DispatcherHandler dispatcherHandler) {
return new RedirectPlugin(dispatcherHandler);
} | @Test
public void testRedirectPlugin() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RedirectPluginConfiguration.class))
.withBean(RedirectPluginConfigurationTest.class)
.withBean(DispatcherHandler.class)
.withPropertyValues("debug=... |
public void validate(CreateReviewAnswerRequest request) {
Question question = questionRepository.findById(request.questionId())
.orElseThrow(() -> new SubmittedQuestionNotFoundException(request.questionId()));
validateNotIncludingOptions(request);
validateQuestionRequired(questio... | @Test
void 텍스트형_질문에_선택형_응답을_하면_예외가_발생한다() {
// given
Question savedQuestion
= questionRepository.save(new Question(true, QuestionType.TEXT, "질문", "가이드라인", 1));
CreateReviewAnswerRequest request = new CreateReviewAnswerRequest(savedQuestion.getId(), List.of(1L), "응답");
... |
public static Nazgul getInstance(NazgulName name) {
return nazguls.get(name);
} | @Test
void testGetInstance() {
for (final var name : NazgulName.values()) {
final var nazgul = Nazgul.getInstance(name);
assertNotNull(nazgul);
assertSame(nazgul, Nazgul.getInstance(name));
assertEquals(name, nazgul.getName());
}
} |
@VisibleForTesting
static boolean isInPriorNetwork(String ip) {
ip = ip.trim();
for (String cidr : PRIORITY_CIDRS) {
cidr = cidr.trim();
IPAddressString network = new IPAddressString(cidr);
IPAddressString address = new IPAddressString(ip);
if (network... | @Test
public void cidrTest2() {
List<String> priorityCidrs = FrontendOptions.PRIORITY_CIDRS;
priorityCidrs.add("2408:4001:258::/48");
FrontendOptions frontendOptions = new FrontendOptions();
boolean inPriorNetwork = frontendOptions.isInPriorNetwork("2408:4001:258:3780:f3f4:5acd:d53d... |
@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_jsonnode() {
Object original = mapper.getObjectMapper().createArrayNode()
.add(BigDecimal.ONE)
.add(1.0)
.add("string");
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(origin... |
@Override
public MetadataRequest.Builder buildRequest(Set<BrokerKey> keys) {
validateLookupKeys(keys);
// Send empty `Metadata` request. We are only interested in the brokers from the response
return new MetadataRequest.Builder(new MetadataRequestData());
} | @Test
public void testBuildRequestWithInvalidLookupKeys() {
AllBrokersStrategy strategy = new AllBrokersStrategy(logContext);
AllBrokersStrategy.BrokerKey key1 = new AllBrokersStrategy.BrokerKey(OptionalInt.empty());
AllBrokersStrategy.BrokerKey key2 = new AllBrokersStrategy.BrokerKey(Option... |
List<MappingField> resolveFields(
@Nonnull String[] externalName,
@Nullable String dataConnectionName,
@Nonnull Map<String, String> options,
@Nonnull List<MappingField> userFields,
boolean stream
) {
Predicate<MappingField> pkColumnName = Options.g... | @Test
public void testResolvesMappingFieldsViaSampleInStream() {
try (MongoClient client = MongoClients.create(mongoContainer.getConnectionString())) {
String databaseName = "testDatabase";
String collectionName = "testResolvesMappingFieldsViaSampleInStream";
MongoDatabas... |
public static DataMap bytesToDataMap(Map<String, String> headers, ByteString bytes) throws MimeTypeParseException, IOException
{
return getContentType(headers).getCodec().readMap(bytes);
} | @Test(expectedExceptions = IOException.class)
public void testByteStringToDataMapWithInvalidContentType() throws MimeTypeParseException, IOException
{
DataMap dataMap = createTestDataMap();
ByteString byteString = ByteString.copy(JACKSON_DATA_CODEC.mapToBytes(dataMap));
bytesToDataMap("application/x-pso... |
@Override
public int getMaxCursorNameLength() {
return 0;
} | @Test
void assertGetMaxCursorNameLength() {
assertThat(metaData.getMaxCursorNameLength(), is(0));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.