focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public Measure.Level getLevel() {
return level;
} | @Test
public void getLevel_returns_object_passed_in_constructor() {
assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, SOME_VALUE).getLevel()).isSameAs(SOME_LEVEL);
} |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Map.Entry<Path, TransferStatus> file : files.entrySet()) {
try {
callback.delete(file.getKey());
final StoregateApiClient client = session.getClient();
final HttpRequestBase request;
request = new HttpDelete(String.format("%s/v4.2/files/%s", client.getBasePath(), fileid.getFileId(file.getKey())));
if(file.getValue().getLockId() != null) {
request.addHeader("X-Lock-Id", file.getValue().getLockId().toString());
}
request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
final HttpResponse response = client.getClient().execute(request);
try {
switch(response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_NO_CONTENT:
break;
default:
throw new StoregateExceptionMappingService(fileid).map("Cannot delete {0}",
new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()), file.getKey());
}
}
finally {
EntityUtils.consume(response.getEntity());
}
fileid.cache(file.getKey(), null);
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map("Cannot delete {0}", e, file.getKey());
}
}
} | @Test
public void testDeleteFileWithLock() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new Path("/My files", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path fileInRoom = new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new StoregateTouchFeature(session, nodeid).touch(fileInRoom, new TransferStatus());
final String lock = new StoregateLockFeature(session, nodeid).lock(fileInRoom);
assertTrue(new DefaultFindFeature(session).find(fileInRoom));
new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonMap(fileInRoom, new TransferStatus().withLockId(lock)), new DisabledLoginCallback(), new Delete.DisabledCallback());
assertFalse(new DefaultFindFeature(session).find(fileInRoom));
} |
@Override
public void clear() {
throw new UnsupportedOperationException("RangeSet is immutable");
} | @Test(expected = UnsupportedOperationException.class)
public void clear() throws Exception {
RangeSet rs = new RangeSet(5);
rs.clear();
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @Test
void testFunctionDependingOnInputWithFunctionHierarchy() {
IdentityMapper4<String> function = new IdentityMapper4<String>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(function, BasicTypeInfo.STRING_TYPE_INFO);
assertThat(ti).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO);
} |
public void putValue(String fieldName, @Nullable Object value) {
_fieldToValueMap.put(fieldName, value);
} | @Test
public void testDifferentNumberOfKeysWithSomeSameValueNotEqual() {
GenericRow first = new GenericRow();
first.putValue("one", 1);
first.putValue("two", 2);
GenericRow second = new GenericRow();
second.putValue("one", 1);
Assert.assertNotEquals(first, second);
} |
@Override
public void updateSmsSendResult(Long id, Boolean success,
String apiSendCode, String apiSendMsg,
String apiRequestId, String apiSerialNo) {
SmsSendStatusEnum sendStatus = success ? SmsSendStatusEnum.SUCCESS : SmsSendStatusEnum.FAILURE;
smsLogMapper.updateById(SmsLogDO.builder().id(id)
.sendStatus(sendStatus.getStatus()).sendTime(LocalDateTime.now())
.apiSendCode(apiSendCode).apiSendMsg(apiSendMsg)
.apiRequestId(apiRequestId).apiSerialNo(apiSerialNo).build());
} | @Test
public void testUpdateSmsSendResult() {
// mock 数据
SmsLogDO dbSmsLog = randomSmsLogDO(
o -> o.setSendStatus(SmsSendStatusEnum.IGNORE.getStatus()));
smsLogMapper.insert(dbSmsLog);
// 准备参数
Long id = dbSmsLog.getId();
Boolean success = randomBoolean();
String apiSendCode = randomString();
String apiSendMsg = randomString();
String apiRequestId = randomString();
String apiSerialNo = randomString();
// 调用
smsLogService.updateSmsSendResult(id, success,
apiSendCode, apiSendMsg, apiRequestId, apiSerialNo);
// 断言
dbSmsLog = smsLogMapper.selectById(id);
assertEquals(success ? SmsSendStatusEnum.SUCCESS.getStatus() : SmsSendStatusEnum.FAILURE.getStatus(),
dbSmsLog.getSendStatus());
assertNotNull(dbSmsLog.getSendTime());
assertEquals(apiSendCode, dbSmsLog.getApiSendCode());
assertEquals(apiSendMsg, dbSmsLog.getApiSendMsg());
assertEquals(apiRequestId, dbSmsLog.getApiRequestId());
assertEquals(apiSerialNo, dbSmsLog.getApiSerialNo());
} |
@Nonnull
@Override
public Optional<Signature> parse(
@Nullable String str, @Nonnull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
final String generalizedStr = str.toLowerCase().trim();
if (!generalizedStr.contains("with")) {
return map(str, detectionLocation);
}
int hashEndPos = generalizedStr.indexOf("with");
String digestStr = str.substring(0, hashEndPos);
JcaMessageDigestMapper jcaMessageDigestMapper = new JcaMessageDigestMapper();
final Optional<MessageDigest> messageDigestOptional =
jcaMessageDigestMapper.parse(digestStr, detectionLocation);
int encryptStartPos = hashEndPos + 4;
String signatureStr = str.substring(encryptStartPos);
final String format;
if (generalizedStr.contains("in") && generalizedStr.contains("format")) {
int inStartPos = generalizedStr.indexOf("in");
int inEndPos = inStartPos + 2;
signatureStr = str.substring(encryptStartPos, inStartPos);
format = str.substring(inEndPos);
} else {
format = null;
}
return map(signatureStr, detectionLocation)
.map(
signature -> {
messageDigestOptional.ifPresent(signature::put);
if (format != null) {
signature.put(new OutputFormat(format, detectionLocation));
}
return signature;
});
} | @Test
void RSASSA_PSS() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaSignatureMapper jcaSignatureMapper = new JcaSignatureMapper();
Optional<Signature> signatureOptional =
jcaSignatureMapper.parse("RSASSA-PSS", testDetectionLocation);
assertThat(signatureOptional).isPresent();
assertThat(signatureOptional.get()).isInstanceOf(RSAssaPSS.class);
assertThat(signatureOptional.get().getName()).isEqualTo("RSASSA-PSS");
assertThat(signatureOptional.get().getFormat()).isEmpty();
assertThat(signatureOptional.get().isProbabilisticSignatureScheme()).isTrue();
} |
@Override
@CheckForNull
public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) {
String bundleKey = propertyToBundles.get(key);
String value = null;
if (bundleKey != null) {
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(bundleKey, locale, classloader, control);
value = resourceBundle.getString(key);
} catch (MissingResourceException e1) {
// ignore
}
}
if (value == null) {
value = defaultValue;
}
return formatMessage(value, parameters);
} | @Test
public void return_default_value_if_missing_key() {
assertThat(underTest.message(Locale.ENGLISH, "bla_bla_bla", "default")).isEqualTo("default");
assertThat(underTest.message(Locale.FRENCH, "bla_bla_bla", "default")).isEqualTo("default");
} |
public BigtableRowToBeamRowFlat(Schema schema, Map<String, Set<String>> columnsMapping) {
this.schema = schema;
this.columnsMapping = columnsMapping;
} | @Test
public void testBigtableRowToBeamRowFlat() {
Map<String, Set<String>> columnsMapping =
ImmutableMap.of(
FAMILY_TEST, ImmutableSet.of(BOOL_COLUMN, LONG_COLUMN, STRING_COLUMN, DOUBLE_COLUMN));
PCollection<Row> rows =
pipeline
.apply(Create.of(bigtableRow(1), bigtableRow(2)))
.setCoder(ProtoCoder.of(TypeDescriptor.of(com.google.bigtable.v2.Row.class)))
.apply(new BigtableRowToBeamRowFlat(TEST_FLAT_SCHEMA, columnsMapping))
.setRowSchema(TEST_FLAT_SCHEMA);
PAssert.that(rows).containsInAnyOrder(row(1), row(2));
pipeline.run().waitUntilFinish();
} |
public static <T> MutationDetector forValueWithCoder(T value, Coder<T> coder)
throws CoderException {
if (value == null) {
return noopMutationDetector();
} else {
return new CodedValueMutationDetector<>(value, coder);
}
} | @Test
public void testMutationBasedOnStructuralValue() throws Exception {
AtomicInteger value = new AtomicInteger();
MutationDetector detector =
MutationDetectors.forValueWithCoder(value, new ForSDKMutationDetectionTestCoder());
// Even though we modified the value, we are relying on the fact that the structural
// value will be used to compare equality
value.incrementAndGet();
detector.verifyUnmodified();
} |
public static <T> KryoCoder<T> of() {
return of(PipelineOptionsFactory.create(), Collections.emptyList());
} | @Test
public void testBasicCoding() throws IOException {
final KryoCoder<ClassToBeEncoded> coder =
KryoCoder.of(OPTIONS, k -> k.register(ClassToBeEncoded.class));
assertEncoding(coder);
} |
public boolean containsDatabase(final String databaseName) {
return databases.containsKey(databaseName);
} | @Test
void assertContainsDatabase() {
ShardingSphereRule globalRule = mock(ShardingSphereRule.class);
ShardingSphereDatabase database = mockDatabase(mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), new MockedDataSource(), globalRule);
Map<String, ShardingSphereDatabase> databases = new HashMap<>(Collections.singletonMap("foo_db", database));
ConfigurationProperties configProps = new ConfigurationProperties(new Properties());
ShardingSphereMetaData metaData = new ShardingSphereMetaData(databases, mock(ResourceMetaData.class), new RuleMetaData(Collections.singleton(globalRule)), configProps);
assertTrue(metaData.containsDatabase("foo_db"));
} |
private GetRegisterLeasePResponse acquireRegisterLease(
final long workerId, final int estimatedBlockCount) throws IOException {
return retryRPC(() -> {
LOG.info("Requesting lease with workerId {}, blockCount {}", workerId, estimatedBlockCount);
return mClient.requestRegisterLease(GetRegisterLeasePRequest.newBuilder()
.setWorkerId(workerId).setBlockCount(estimatedBlockCount).build());
}, LOG, "GetRegisterLease", "workerId=%d, estimatedBlockCount=%d",
workerId, estimatedBlockCount);
} | @Test
public void acquireRegisterLeaseFailure() {
assertThrows(FailedToAcquireRegisterLeaseException.class,
() -> acquireRegisterLease(false));
} |
static final String addFunctionParameter(ParameterDescriptor descriptor, RuleBuilderStep step) {
final String parameterName = descriptor.name(); // parameter name needed by function
final Map<String, Object> parameters = step.parameters();
if (Objects.isNull(parameters)) {
return null;
}
final Object value = parameters.get(parameterName); // parameter value set by rule definition
String syntax = " " + parameterName + " : ";
if (value == null) {
return null;
} else if (value instanceof String valueString) {
if (StringUtils.isEmpty(valueString)) {
return null;
} else if (valueString.startsWith("$")) { // value set as variable
syntax += valueString.substring(1);
} else {
syntax += "\"" + StringEscapeUtils.escapeJava(valueString) + "\""; // value set as string
}
} else {
syntax += value;
}
return syntax;
} | @Test
public void addFunctionParameterSyntaxOk_WhenVariableParameterStringContainsBadChar() {
String parameterName = "foo";
String parameterValue = "bar\"123";
RuleBuilderStep step = mock(RuleBuilderStep.class);
Map<String, Object> params = Map.of(parameterName, parameterValue);
when(step.parameters()).thenReturn(params);
ParameterDescriptor descriptor = mock(ParameterDescriptor.class);
when(descriptor.name()).thenReturn(parameterName);
assertThat(ParserUtil.addFunctionParameter(descriptor, step))
.isEqualTo(" foo : \"bar\\\"123\"");
} |
public static void executeAsyncNotify(Runnable runnable) {
ASYNC_NOTIFY_EXECUTOR.execute(runnable);
} | @Test
void testExecuteAsyncNotify() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger();
Runnable runnable = atomicInteger::incrementAndGet;
ConfigExecutor.executeAsyncNotify(runnable);
TimeUnit.MILLISECONDS.sleep(20);
assertEquals(1, atomicInteger.get());
} |
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) {
if (ONLY_UNDERSCORES.matcher(identifierName).matches()) {
// Degenerate case of names which contain only underscore
return ImmutableList.of(identifierName);
}
return TERM_SPLITTER
.splitToStream(identifierName)
.map(String::toLowerCase)
.collect(toImmutableList());
} | @Test
public void splitToLowercaseTerms_separatesTerms_withUnderscoreSeparator() {
String identifierName = "UNDERSCORE_SEPARATED";
ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName);
assertThat(terms).containsExactly("underscore", "separated");
} |
public double logp(int[] o, int[] s) {
if (o.length != s.length) {
throw new IllegalArgumentException("The observation sequence and state sequence are not the same length.");
}
int n = s.length;
double p = MathEx.log(pi[s[0]]) + MathEx.log(b.get(s[0], o[0]));
for (int i = 1; i < n; i++) {
p += MathEx.log(a.get(s[i - 1], s[i])) + MathEx.log(b.get(s[i], o[i]));
}
return p;
} | @Test
public void testJointLogp() {
System.out.println("joint logp");
HMM hmm = new HMM(pi, Matrix.of(a), Matrix.of(b));
int[] o = {0, 0, 1, 1, 0, 1, 1, 0};
int[] s = {0, 0, 1, 1, 1, 1, 1, 0};
double expResult = -9.51981;
double result = hmm.logp(o, s);
assertEquals(expResult, result, 1E-5);
} |
@Override
public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) {
throw new ReadOnlyBufferException();
} | @Test
public void shouldRejectSetBytes1() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() throws IOException {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (InputStream) null, 0);
}
});
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
return this.toAttributes(session.toPath(file));
}
catch(IOException e) {
throw new LocalExceptionMappingService().map("Failure to read attributes of {0}", e, file);
}
} | @Test
public void testFindRoot() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelCallback());
session.login(new DisabledLoginCallback(), new DisabledCancelCallback());
final LocalAttributesFinderFeature f = new LocalAttributesFinderFeature(session);
assertNotNull(f.find(new Path("/", EnumSet.of(Path.Type.directory))));
assertNotEquals(PathAttributes.EMPTY, f.find(new Path("/", EnumSet.of(Path.Type.directory))));
} |
@Override
public NodeId getMasterFor(DeviceId deviceId) {
checkPermission(CLUSTER_READ);
checkNotNull(deviceId, DEVICE_ID_NULL);
return store.getMaster(deviceId);
} | @Test
public void getMasterFor() {
mgr.setRole(NID_LOCAL, DEV_MASTER, MASTER);
mgr.setRole(NID_OTHER, DEV_OTHER, MASTER);
assertEquals("wrong master:", NID_LOCAL, mgr.getMasterFor(DEV_MASTER));
assertEquals("wrong master:", NID_OTHER, mgr.getMasterFor(DEV_OTHER));
//have NID_OTHER hand over DEV_OTHER to NID_LOCAL
mgr.setRole(NID_LOCAL, DEV_OTHER, MASTER);
assertEquals("wrong master:", NID_LOCAL, mgr.getMasterFor(DEV_OTHER));
} |
static boolean waitUntil(Duration timeout, BooleanSupplier condition) throws InterruptedException {
int waited = 0;
while (!condition.getAsBoolean() && waited < timeout.toMillis()) {
Thread.sleep(100L);
waited += 100;
}
return condition.getAsBoolean();
} | @Test
@DisplayName("resend unconfirmed messages")
void resendUnconfirmedMessagesIntegration() throws Exception {
Channel ch = connection.createChannel();
ch.confirmSelect();
Map<Long, String> outstandingConfirms = resendUnconfirmedMessages(ch);
assertThat(waitUntil(Duration.ofSeconds(5), () -> outstandingConfirms.isEmpty())).isTrue();
ch.close();
Set<String> receivedMessages = ConcurrentHashMap.newKeySet(messageCount);
CountDownLatch latch = new CountDownLatch(messageCount);
ch = connection.createChannel();
ch.basicConsume(queue, true, ((consumerTag, message) -> {
receivedMessages.add(new String(message.getBody()));
latch.countDown();
}), consumerTag -> {
});
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
assertThat(receivedMessages).hasSize(messageCount);
} |
void writeConfigToDisk() {
VespaTlsConfig config = VespaZookeeperTlsContextUtils.tlsContext()
.map(ctx -> new VespaTlsConfig(ctx, TransportSecurityUtils.getInsecureMixedMode()))
.orElse(VespaTlsConfig.tlsDisabled());
writeConfigToDisk(config);
} | @Test
public void config_is_written_correctly_with_tls_for_quorum_communication_tls_without_mixed_mode() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
TlsContext tlsContext = createTlsContext();
new Configurator(builder.build()).writeConfigToDisk(new VespaTlsConfig(tlsContext, MixedMode.DISABLED));
validateConfigFileTlsWithoutMixedMode(cfgFile, false);
} |
public void completeDefaults(Props props) {
// init string properties
for (Map.Entry<Object, Object> entry : defaults().entrySet()) {
props.setDefault(entry.getKey().toString(), entry.getValue().toString());
}
boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false);
if (!clusterEnabled) {
props.setDefault(SEARCH_HOST.getKey(), InetAddress.getLoopbackAddress().getHostAddress());
props.setDefault(SEARCH_PORT.getKey(), "9001");
fixPortIfZero(props, Property.SEARCH_HOST.getKey(), SEARCH_PORT.getKey());
fixEsTransportPortIfNull(props);
}
} | @Test
public void completeDefaults_sets_default_values_for_sonar_search_host_and_sonar_search_port_and_random_port_for_sonar_es_port_in_non_cluster_mode() throws Exception {
Properties p = new Properties();
p.setProperty("sonar.cluster.enabled", "false");
Props props = new Props(p);
processProperties.completeDefaults(props);
String address = props.value("sonar.search.host");
assertThat(address).isNotEmpty();
assertThat(InetAddress.getByName(address).isLoopbackAddress()).isTrue();
assertThat(props.valueAsInt("sonar.search.port")).isEqualTo(9001);
assertThat(props.valueAsInt("sonar.es.port")).isPositive();
} |
@Override
public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix,
final PS prefixKeySerializer) {
return new KeyValueIteratorFacade<>(inner.prefixScan(prefix, prefixKeySerializer));
} | @Test
public void shouldReturnPlainKeyValuePairsForPrefixScan() {
final StringSerializer stringSerializer = new StringSerializer();
when(mockedKeyValueTimestampIterator.next())
.thenReturn(KeyValue.pair("key1", ValueAndTimestamp.make("value1", 21L)))
.thenReturn(KeyValue.pair("key2", ValueAndTimestamp.make("value2", 42L)));
when(mockedKeyValueTimestampStore.prefixScan("key", stringSerializer)).thenReturn(mockedKeyValueTimestampIterator);
final KeyValueIterator<String, String> iterator = readOnlyKeyValueStoreFacade.prefixScan("key", stringSerializer);
assertThat(iterator.next(), is(KeyValue.pair("key1", "value1")));
assertThat(iterator.next(), is(KeyValue.pair("key2", "value2")));
} |
private RemotingCommand consumeMessageDirectly(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final ConsumeMessageDirectlyResultRequestHeader requestHeader =
(ConsumeMessageDirectlyResultRequestHeader) request
.decodeCommandCustomHeader(ConsumeMessageDirectlyResultRequestHeader.class);
final MessageExt msg = MessageDecoder.clientDecode(ByteBuffer.wrap(request.getBody()), true);
ConsumeMessageDirectlyResult result =
this.mqClientFactory.consumeMessageDirectly(msg, requestHeader.getConsumerGroup(), requestHeader.getBrokerName());
if (null != result) {
response.setCode(ResponseCode.SUCCESS);
response.setBody(result.encode());
} else {
response.setCode(ResponseCode.SYSTEM_ERROR);
response.setRemark(String.format("The Consumer Group <%s> not exist in this consumer", requestHeader.getConsumerGroup()));
}
return response;
} | @Test
public void testConsumeMessageDirectly() throws Exception {
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
RemotingCommand request = mock(RemotingCommand.class);
when(request.getCode()).thenReturn(RequestCode.CONSUME_MESSAGE_DIRECTLY);
when(request.getBody()).thenReturn(getMessageResult());
ConsumeMessageDirectlyResult directlyResult = mock(ConsumeMessageDirectlyResult.class);
when(mQClientFactory.consumeMessageDirectly(any(MessageExt.class), anyString(), anyString())).thenReturn(directlyResult);
ConsumeMessageDirectlyResultRequestHeader requestHeader = new ConsumeMessageDirectlyResultRequestHeader();
requestHeader.setConsumerGroup(defaultGroup);
requestHeader.setBrokerName(defaultBroker);
when(request.decodeCommandCustomHeader(ConsumeMessageDirectlyResultRequestHeader.class)).thenReturn(requestHeader);
RemotingCommand command = processor.processRequest(ctx, request);
assertNotNull(command);
assertEquals(ResponseCode.SUCCESS, command.getCode());
} |
public static CurlOption parse(String cmdLine) {
List<String> args = ShellWords.parse(cmdLine);
URI url = null;
HttpMethod method = HttpMethod.PUT;
List<Entry<String, String>> headers = new ArrayList<>();
Proxy proxy = NO_PROXY;
while (!args.isEmpty()) {
String arg = args.remove(0);
if (arg.equals("-X")) {
String methodArg = removeArgFor(arg, args);
method = HttpMethod.parse(methodArg);
} else if (arg.equals("-H")) {
String headerArg = removeArgFor(arg, args);
SimpleEntry<String, String> e = parseHeader(headerArg);
headers.add(e);
} else if (arg.equals("-x")) {
String proxyArg = removeArgFor(arg, args);
proxy = parseProxy(proxyArg);
} else {
if (url != null) {
throw new IllegalArgumentException("'" + cmdLine + "' was not a valid curl command");
}
url = parseUrl(arg);
}
}
if (url == null) {
throw new IllegalArgumentException("'" + cmdLine + "' was not a valid curl command");
}
return new CurlOption(proxy, method, url, headers);
} | @Test
public void must_provide_valid_method() {
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> CurlOption.parse("https://example.com -X NO-SUCH-METHOD"));
assertThat(exception.getMessage(), is("NO-SUCH-METHOD was not a http method"));
} |
@Override
public void removeRule(final RuleData ruleData) {
Optional.ofNullable(ruleData).ifPresent(s ->
CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData)));
} | @Test
public void testRemoveRule() {
this.requestPluginHandler.handlerRule(this.ruleData);
RuleData ruleData = new RuleData();
ruleData.setSelectorId("test");
ruleData.setId("test");
this.requestPluginHandler.removeRule(this.ruleData);
assertNull(RequestPluginHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(this.ruleData)));
this.requestPluginHandler.removeRule(ruleData);
assertNull(RequestPluginHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(ruleData)));
this.requestPluginHandler.removeRule(null);
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowStartBounds, windowEndBounds);
final Instant upper = calculateUpperBound(windowStartBounds, windowEndBounds);
final WindowKeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query =
WindowKeyQuery.withKeyAndWindowStartRange(key, lower, upper);
StateQueryRequest<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> request =
inStore(stateStore.getStateStoreName()).withQuery(query);
if (position.isPresent()) {
request = request.withPositionBound(PositionBound.at(position.get()));
}
final KafkaStreams streams = stateStore.getKafkaStreams();
final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> result =
streams.query(request);
final QueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> queryResult =
result.getPartitionResults().get(partition);
if (queryResult.isFailure()) {
throw failedQueryException(queryResult);
}
if (queryResult.getResult() == null) {
return KsMaterializedQueryResult.rowIteratorWithPosition(
Collections.emptyIterator(), queryResult.getPosition());
}
try (WindowStoreIterator<ValueAndTimestamp<GenericRow>> it
= queryResult.getResult()) {
final Builder<WindowedRow> builder = ImmutableList.builder();
while (it.hasNext()) {
final KeyValue<Long, ValueAndTimestamp<GenericRow>> next = it.next();
final Instant windowStart = Instant.ofEpochMilli(next.key);
if (!windowStartBounds.contains(windowStart)) {
continue;
}
final Instant windowEnd = windowStart.plus(windowSize);
if (!windowEndBounds.contains(windowEnd)) {
continue;
}
final TimeWindow window =
new TimeWindow(windowStart.toEpochMilli(), windowEnd.toEpochMilli());
final WindowedRow row = WindowedRow.of(
stateStore.schema(),
new Windowed<>(key, window),
next.value.value(),
next.value.timestamp()
);
builder.add(row);
}
return KsMaterializedQueryResult.rowIteratorWithPosition(
builder.build().iterator(), queryResult.getPosition());
}
} catch (final NotUpToBoundException | MaterializationException e) {
throw e;
} catch (final Exception e) {
throw new MaterializationException("Failed to get value from materialized table", e);
}
} | @Test
@SuppressWarnings("unchecked")
public void shouldSupportRangeAll() {
// When:
final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> partitionResult =
new StateQueryResult<>();
final QueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> result = QueryResult.forResult(fetchIterator);
result.setPosition(POSITION);
partitionResult.addResult(PARTITION, result);
when(kafkaStreams.query(any(StateQueryRequest.class))).thenReturn(partitionResult);
table.get(A_KEY, PARTITION, Range.all(), Range.all());
// Then:
verify(kafkaStreams).query(queryTypeCaptor.capture());
StateQueryRequest<?> request = queryTypeCaptor.getValue();
assertThat(request.getQuery(), instanceOf(WindowKeyQuery.class));
WindowKeyQuery<GenericKey,GenericRow> keyQuery = (WindowKeyQuery<GenericKey,GenericRow>) request.getQuery();
assertThat(keyQuery.getKey(), is(A_KEY));
} |
public byte[] getSignature() {
return signature;
} | @Test
public void testGetSignature() {
assertEquals(TestParameters.VP_ISTP_SIGNATURE,
new String(chmItspHeader.getSignature(), UTF_8));
} |
static UnixResolverOptions parseEtcResolverOptions() throws IOException {
return parseEtcResolverOptions(new File(ETC_RESOLV_CONF_FILE));
} | @Test
public void defaultValueReturnedIfNdotsOptionsNotPresent(@TempDir Path tempDir) throws IOException {
File f = buildFile(tempDir, "search localdomain\n" +
"nameserver 127.0.0.11\n");
assertEquals(1, parseEtcResolverOptions(f).ndots());
} |
@Override
public Region updateRegion(RegionId regionId, String name, Region.Type type,
Annotations annots, List<Set<NodeId>> masterNodeIds) {
return regionsRepo.compute(regionId, (id, region) -> {
nullIsNotFound(region, NO_REGION);
return new DefaultRegion(regionId, name, type, annots, masterNodeIds);
}).value();
} | @Test(expected = ItemNotFoundException.class)
public void missingUpdate() {
store.updateRegion(RID1, "R1", METRO, NO_ANNOTS, MASTERS);
} |
boolean isModified(Namespace namespace) {
Release release = releaseService.findLatestActiveRelease(namespace);
List<Item> items = itemService.findItemsWithoutOrdered(namespace.getId());
if (release == null) {
return hasNormalItems(items);
}
Map<String, String> releasedConfiguration = GSON.fromJson(release.getConfigurations(), GsonType.CONFIG);
Map<String, String> configurationFromItems = generateConfigurationFromItems(namespace, items);
MapDifference<String, String> difference = Maps.difference(releasedConfiguration, configurationFromItems);
return !difference.areEqual();
} | @Test
public void testChildNamespaceModified() {
long childNamespaceId = 1, parentNamespaceId = 2;
Namespace childNamespace = createNamespace(childNamespaceId);
Namespace parentNamespace = createNamespace(parentNamespaceId);
Release childRelease = createRelease("{\"k1\":\"v1\", \"k2\":\"v2\"}");
List<Item> childItems = Collections.singletonList(createItem("k1", "v3"));
Release parentRelease = createRelease("{\"k1\":\"v1\", \"k2\":\"v2\"}");
when(releaseService.findLatestActiveRelease(childNamespace)).thenReturn(childRelease);
when(releaseService.findLatestActiveRelease(parentNamespace)).thenReturn(parentRelease);
when(itemService.findItemsWithoutOrdered(childNamespaceId)).thenReturn(childItems);
when(namespaceService.findParentNamespace(childNamespace)).thenReturn(parentNamespace);
boolean isModified = namespaceUnlockAspect.isModified(childNamespace);
Assert.assertTrue(isModified);
} |
@Override
public String getGroupKeyColumnName(int groupKeyColumnIndex) {
throw new AssertionError("No group key column name for result table");
} | @Test(expectedExceptions = AssertionError.class)
public void testGetGroupKeyColumnName() {
// Run the test
_resultTableResultSetUnderTest.getGroupKeyColumnName(0);
} |
@Override
public Boolean login(Properties properties) {
if (ramContext.validate()) {
return true;
}
loadRoleName(properties);
loadAccessKey(properties);
loadSecretKey(properties);
loadRegionId(properties);
return true;
} | @Test
void testLoginWithAkSk() {
assertTrue(ramClientAuthService.login(akSkProperties));
assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey());
assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey());
assertNull(ramContext.getRamRoleName());
assertTrue(ramClientAuthService.login(roleProperties));
assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey());
assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey());
assertNull(ramContext.getRamRoleName());
} |
public static File getResourceAsFile(String resource) throws IOException {
return new File(getResourceUrl(resource).getFile());
} | @Test
void testGetResourceAsFileByLoader() throws IOException {
File file = ResourceUtils.getResourceAsFile(ResourceUtils.class.getClassLoader(), "resource_utils_test.properties");
assertNotNull(file);
} |
public void start() throws Exception {
start(StartMode.NORMAL);
} | @Test
public void testModes() throws Exception {
Timing timing = new Timing();
CuratorFramework client = CuratorFrameworkFactory.newClient(
server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
client.start();
try {
client.create().forPath("/test");
for (boolean cacheData : new boolean[] {false, true}) {
internalTestMode(client, cacheData);
client.delete().forPath("/test/one");
client.delete().forPath("/test/two");
}
} finally {
TestCleanState.closeAndTestClean(client);
}
} |
@Override
public ParsedLine parse(final String line, final int cursor, final ParseContext context) {
final ParsedLine parsed = delegate.parse(line, cursor, context);
if (context != ParseContext.ACCEPT_LINE) {
return parsed;
}
if (UnclosedQuoteChecker.isUnclosedQuote(line)) {
throw new EOFError(-1, -1, "Missing end quote", "end quote char");
}
final String bare = CommentStripper.strip(parsed.line());
if (bare.isEmpty()) {
return parsed;
}
if (cliCmdPredicate.test(bare)) {
return parsed;
}
if (!bare.endsWith(TERMINATION_CHAR)) {
throw new EOFError(-1, -1, "Missing termination char", "termination char");
}
return parsed;
} | @Test
public void shouldReturnResultIfNotAcceptLine() {
// Given:
givenDelegateWillReturn(UNTERMINATED_LINE);
// When:
final ParsedLine result = parser.parse("what ever", 0, ParseContext.COMPLETE);
// Then:
assertThat(result, is(parsedLine));
} |
@Override
public void processElement(final StreamRecord<T> element) throws Exception {
final T event = element.getValue();
final long previousTimestamp =
element.hasTimestamp() ? element.getTimestamp() : Long.MIN_VALUE;
final long newTimestamp = timestampAssigner.extractTimestamp(event, previousTimestamp);
element.setTimestamp(newTimestamp);
output.collect(element);
watermarkGenerator.onEvent(event, newTimestamp, wmOutput);
} | @Test
void punctuatedWatermarksBatchMode() throws Exception {
OneInputStreamOperatorTestHarness<Tuple2<Boolean, Long>, Tuple2<Boolean, Long>>
testHarness =
createBatchHarness(
WatermarkStrategy.forGenerator(
(ctx) -> new PunctuatedWatermarkGenerator())
.withTimestampAssigner((ctx) -> new TupleExtractor()));
testHarness.processElement(new StreamRecord<>(new Tuple2<>(true, 2L), 1));
assertThat(pollNextStreamRecord(testHarness))
.is(matching(streamRecord(new Tuple2<>(true, 2L), 2L)));
assertThat(pollNextLegacyWatermark(testHarness)).isNull();
testHarness.processElement(new StreamRecord<>(new Tuple2<>(true, 4L), 1));
assertThat(pollNextStreamRecord(testHarness))
.is(matching(streamRecord(new Tuple2<>(true, 4L), 4L)));
assertThat(pollNextLegacyWatermark(testHarness)).isNull();
} |
@Override
public KTable<K, V> reduce(final Reducer<V> adder,
final Reducer<V> subtractor,
final Materialized<K, V, KeyValueStore<Bytes, byte[]>> materialized) {
return reduce(adder, subtractor, NamedInternal.empty(), materialized);
} | @Test
public void shouldReduceWithInternalStoreName() {
final KeyValueMapper<String, Number, KeyValue<String, Integer>> intProjection =
(key, value) -> KeyValue.pair(key, value.intValue());
final KTable<String, Integer> reduced = builder
.table(
topic,
Consumed.with(Serdes.String(), Serdes.Double()),
Materialized.<String, Double, KeyValueStore<Bytes, byte[]>>as("store")
.withKeySerde(Serdes.String())
.withValueSerde(Serdes.Double()))
.groupBy(intProjection)
.reduce(MockReducer.INTEGER_ADDER, MockReducer.INTEGER_SUBTRACTOR);
final MockApiProcessorSupplier<String, Integer, Void, Void> supplier = getReducedResults(reduced);
try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props)) {
assertReduced(supplier.theCapturedProcessor().lastValueAndTimestampPerKey(), topic, driver);
assertNull(reduced.queryableStoreName());
}
} |
public void setBatchSize(int batchSize) {
this.batchSize = checkPositive(batchSize, "batchSize");
} | @Test
public void test_setBatchSize_whenZero() {
ReactorBuilder builder = newBuilder();
assertThrows(IllegalArgumentException.class, () -> builder.setBatchSize(0));
} |
public static ByteBuffer serializeSubscription(final Subscription subscription) {
return serializeSubscription(subscription, ConsumerProtocolSubscription.HIGHEST_SUPPORTED_VERSION);
} | @Test
public void serializeSubscriptionShouldOrderTopics() {
assertEquals(
ConsumerProtocol.serializeSubscription(
new Subscription(Arrays.asList("foo", "bar"), null, Arrays.asList(tp1, tp2))
),
ConsumerProtocol.serializeSubscription(
new Subscription(Arrays.asList("bar", "foo"), null, Arrays.asList(tp1, tp2))
)
);
} |
public ProxyConfiguration swap(final YamlProxyConfiguration yamlConfig) {
Map<String, DatabaseConfiguration> databaseConfigs = swapDatabaseConfigurations(yamlConfig.getDatabaseConfigurations());
ProxyGlobalConfiguration globalConfig = swapGlobalConfiguration(yamlConfig.getServerConfiguration());
return new ProxyConfiguration(databaseConfigs, globalConfig);
} | @Test
void assertSwap() throws IOException {
YamlProxyConfiguration yamlProxyConfig = ProxyConfigurationLoader.load("/conf/swap");
ProxyConfiguration actual = new YamlProxyConfigurationSwapper().swap(yamlProxyConfig);
assertDataSources(actual);
assertDatabaseRules(actual);
assertAuthorityRuleConfiguration(actual);
assertProxyConfigurationProps(actual);
} |
public static PartitionAwareOperationFactory extractPartitionAware(OperationFactory operationFactory) {
if (operationFactory instanceof PartitionAwareOperationFactory factory) {
return factory;
}
if (operationFactory instanceof OperationFactoryWrapper wrapper) {
OperationFactory unwrapped = wrapper.getOperationFactory();
if (unwrapped instanceof PartitionAwareOperationFactory factory) {
return factory;
}
}
return null;
} | @Test
public void returns_partition_aware_factory_when_supplied_factory_is_partition_aware() {
PartitionAwareOpFactory factory = new PartitionAwareOpFactory();
PartitionAwareOperationFactory extractedFactory = extractPartitionAware(factory);
assertInstanceOf(PartitionAwareOperationFactory.class, extractedFactory);
} |
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 testInvalidJSONByteStringToDataMap() throws MimeTypeParseException, IOException
{
bytesToDataMap("application/json", ByteString.copy("helloWorld".getBytes()));
} |
public static <T, S> T copy(S source, T target, String... ignore) {
return copy(source, target, DEFAULT_CONVERT, ignore);
} | @Test
public void test() throws InvocationTargetException, IllegalAccessException {
Source source = new Source();
source.setAge(100);
source.setName("测试");
source.setIds(new String[]{"1", "2", "3"});
source.setAge2(2);
source.setBoy2(true);
source.setColor(Color.RED);
source.setNestObject2(Collections.singletonMap("name", "mapTest"));
NestObject nestObject = new NestObject();
nestObject.setAge(10);
nestObject.setPassword("1234567");
nestObject.setName("测试2");
source.setNestObject(nestObject);
source.setNestObject3(nestObject);
Target target = new Target();
FastBeanCopier.copy(source, target);
System.out.println(source);
System.out.println(target);
System.out.println(target.getNestObject() == source.getNestObject());
} |
@Override
public @Nullable Instant currentSynchronizedProcessingTime() {
return watermarks.getSynchronizedProcessingInputTime();
} | @Test
public void getSynchronizedProcessingTimeIsWatermarkSynchronizedInputTime() {
when(watermarks.getSynchronizedProcessingInputTime()).thenReturn(new Instant(12345L));
assertThat(internals.currentSynchronizedProcessingTime(), equalTo(new Instant(12345L)));
} |
public static Map<String, String> getLogicAndActualTableMap(final RouteUnit routeUnit, final SQLStatementContext sqlStatementContext, final ShardingRule shardingRule) {
if (!(sqlStatementContext instanceof TableAvailable)) {
return Collections.emptyMap();
}
Collection<String> tableNames = ((TableAvailable) sqlStatementContext).getTablesContext().getTableNames();
Map<String, String> result = new CaseInsensitiveMap<>(tableNames.size(), 1F);
for (RouteMapper each : routeUnit.getTableMappers()) {
result.put(each.getLogicName(), each.getActualName());
result.putAll(shardingRule.getLogicAndActualTablesFromBindingTable(routeUnit.getDataSourceMapper().getLogicName(), each.getLogicName(), each.getActualName(), tableNames));
}
return result;
} | @Test
void assertGetLogicAndActualTablesFromRouteUnit() {
Map<String, String> actual = TokenUtils.getLogicAndActualTableMap(getRouteUnit(), mockSQLStatementContext(), mockShardingRule());
assertThat(actual.get("foo_table"), is("foo_table_0"));
assertThat(actual.get("bar_table"), is("bar_table_0"));
} |
@ReadOperation
public Map<String, Object> circuitBreaker(@Selector String dstService) {
List<CircuitBreakerProto.CircuitBreakerRule> rules = serviceRuleManager.getServiceCircuitBreakerRule(
MetadataContext.LOCAL_NAMESPACE,
MetadataContext.LOCAL_SERVICE,
dstService
);
Map<String, Object> polarisCircuitBreakerInfo = new HashMap<>();
polarisCircuitBreakerInfo.put("namespace", MetadataContext.LOCAL_NAMESPACE);
polarisCircuitBreakerInfo.put("service", MetadataContext.LOCAL_SERVICE);
List<Object> circuitBreakerRules = new ArrayList<>();
if (CollectionUtils.isNotEmpty(rules)) {
for (CircuitBreakerProto.CircuitBreakerRule rule : rules) {
circuitBreakerRules.add(parseCircuitBreakerRule(rule));
}
}
polarisCircuitBreakerInfo.put("circuitBreakerRules", circuitBreakerRules);
return polarisCircuitBreakerInfo;
} | @Test
public void testPolarisCircuitBreaker() {
contextRunner.run(context -> {
PolarisCircuitBreakerEndpoint endpoint = new PolarisCircuitBreakerEndpoint(serviceRuleManager);
Map<String, Object> circuitBreakerInfo = endpoint.circuitBreaker("test");
assertThat(circuitBreakerInfo).isNotNull();
assertThat(circuitBreakerInfo.get("namespace")).isNotNull();
assertThat(circuitBreakerInfo.get("service")).isNotNull();
assertThat(circuitBreakerInfo.get("circuitBreakerRules")).asList().isNotEmpty();
});
} |
public int run() throws IOException {
Set<MasterInfoField> masterInfoFilter = new HashSet<>(Arrays
.asList(MasterInfoField.LEADER_MASTER_ADDRESS, MasterInfoField.WEB_PORT,
MasterInfoField.RPC_PORT, MasterInfoField.START_TIME_MS,
MasterInfoField.UP_TIME_MS, MasterInfoField.VERSION,
MasterInfoField.SAFE_MODE, MasterInfoField.ZOOKEEPER_ADDRESSES,
MasterInfoField.RAFT_JOURNAL, MasterInfoField.RAFT_ADDRESSES,
MasterInfoField.MASTER_VERSION));
MasterInfo masterInfo = mMetaMasterClient.getMasterInfo(masterInfoFilter);
Set<BlockMasterInfoField> blockMasterInfoFilter = new HashSet<>(Arrays
.asList(BlockMasterInfoField.LIVE_WORKER_NUM, BlockMasterInfoField.LOST_WORKER_NUM,
BlockMasterInfoField.CAPACITY_BYTES, BlockMasterInfoField.USED_BYTES,
BlockMasterInfoField.FREE_BYTES, BlockMasterInfoField.CAPACITY_BYTES_ON_TIERS,
BlockMasterInfoField.USED_BYTES_ON_TIERS));
BlockMasterInfo blockMasterInfo = mBlockMasterClient.getBlockMasterInfo(blockMasterInfoFilter);
ObjectMapper objectMapper = new ObjectMapper();
SummaryOutput summaryInfo = new SummaryOutput(masterInfo, blockMasterInfo);
try {
String json = objectMapper.writeValueAsString(summaryInfo);
mPrintStream.println(json);
} catch (JsonProcessingException e) {
mPrintStream.println("Failed to convert summaryInfo output to JSON. "
+ "Check the command line log for the detailed error message.");
LOG.error("Failed to output JSON object {}", summaryInfo);
e.printStackTrace();
return -1;
}
return 0;
} | @Test
public void ZkHaSummary() throws IOException {
MasterVersion primaryVersion = MasterVersion.newBuilder()
.setVersion(RuntimeConstants.VERSION).setState("Primary").setAddresses(
NetAddress.newBuilder().setHost("hostname1").setRpcPort(10000).build()
).build();
MasterVersion standby1Version = MasterVersion.newBuilder()
.setVersion(RuntimeConstants.VERSION).setState("Standby").setAddresses(
NetAddress.newBuilder().setHost("hostname2").setRpcPort(10001).build()
).build();
MasterVersion standby2Version = MasterVersion.newBuilder()
.setVersion(RuntimeConstants.VERSION).setState("Standby").setAddresses(
NetAddress.newBuilder().setHost("hostname3").setRpcPort(10002).build()
).build();
mMasterInfo = MasterInfo.newBuilder(mMasterInfo)
.addAllZookeeperAddresses(Arrays.asList("[zookeeper_hostname1]:2181",
"[zookeeper_hostname2]:2181", "[zookeeper_hostname3]:2181"))
.addAllMasterVersions(Arrays.asList(primaryVersion, standby1Version, standby2Version))
.setRaftJournal(false)
.build();
when(mMetaMasterClient.getMasterInfo(any())).thenReturn(mMasterInfo);
SummaryCommand summaryCommand = new SummaryCommand(mMetaMasterClient,
mBlockMasterClient, sConf.getString(PropertyKey.USER_DATE_FORMAT_PATTERN), mPrintStream);
summaryCommand.run();
checkIfOutputValid(sConf.getString(PropertyKey.USER_DATE_FORMAT_PATTERN), "zk");
} |
protected void doHttpRequest(final Request request, final ClientResponseCallback callback) {
// Highly memory inefficient,
// but buffer the request content to allow it to be replayed for
// authentication retries
final Request.Content content = request.getBody();
if (content instanceof InputStreamRequestContent) {
InputStreamRequestContent inputStreamRequestContent = (InputStreamRequestContent) content;
final List<ByteBuffer> buffers = new ArrayList<>();
while (true) {
Content.Chunk chunk = inputStreamRequestContent.read();
if (chunk.isLast()) {
break;
} else {
buffers.add(chunk.getByteBuffer());
}
}
request.body(new ByteBufferRequestContent(buffers.toArray(new ByteBuffer[0])));
buffers.clear();
}
inflightRequests.register();
// execute the request
request.send(new BufferingResponseListener(httpClient.getMaxContentLength()) {
@Override
public void onComplete(Result result) {
try {
Response response = result.getResponse();
final Map<String, String> headers = determineHeadersFrom(response);
if (result.isFailed()) {
// Failure!!!
// including Salesforce errors reported as exception
// from SalesforceSecurityHandler
Throwable failure = result.getFailure();
if (failure instanceof SalesforceException) {
httpClient.getWorkerPool()
.execute(() -> callback.onResponse(null, headers, (SalesforceException) failure));
} else {
final String msg = String.format("Unexpected error {%s:%s} executing {%s:%s}", response.getStatus(),
response.getReason(), request.getMethod(),
request.getURI());
httpClient.getWorkerPool().execute(() -> callback.onResponse(null, headers,
new SalesforceException(msg, response.getStatus(), failure)));
}
} else {
// HTTP error status
final int status = response.getStatus();
HttpRequest request
= (HttpRequest) ((HttpRequest) result.getRequest()).getConversation()
.getAttribute(SalesforceSecurityHandler.AUTHENTICATION_REQUEST_ATTRIBUTE);
if (status == HttpStatus.BAD_REQUEST_400 && request != null) {
// parse login error
ContentResponse contentResponse
= new HttpContentResponse(response, getContent(), getMediaType(), getEncoding());
try {
session.parseLoginResponse(contentResponse, getContentAsString());
final String msg = String.format("Unexpected Error {%s:%s} executing {%s:%s}", status,
response.getReason(), request.getMethod(), request.getURI());
httpClient.getWorkerPool()
.execute(() -> callback.onResponse(null, headers, new SalesforceException(msg, null)));
} catch (SalesforceException e) {
final String msg = String.format("Error {%s:%s} executing {%s:%s}", status,
response.getReason(), request.getMethod(), request.getURI());
httpClient.getWorkerPool().execute(() -> callback.onResponse(null, headers,
new SalesforceException(msg, response.getStatus(), e)));
}
} else if (status < HttpStatus.OK_200 || status >= HttpStatus.MULTIPLE_CHOICES_300) {
// Salesforce HTTP failure!
final SalesforceException exception = createRestException(response, getContentAsInputStream());
// for APIs that return body on status 400, such as
// Composite API we need content as well
httpClient.getWorkerPool()
.execute(() -> callback.onResponse(getContentAsInputStream(), headers, exception));
} else {
// Success!!!
httpClient.getWorkerPool()
.execute(() -> callback.onResponse(getContentAsInputStream(), headers, null));
}
}
} finally {
inflightRequests.arriveAndDeregister();
}
}
@Override
public InputStream getContentAsInputStream() {
if (getContent().length == 0) {
return null;
}
return super.getContentAsInputStream();
}
});
} | @Test
public void shouldTimeoutWhenRequestsAreStillOngoing() throws Exception {
client.doHttpRequest(mock(Request.class), (response, headers, exception) -> {
});
// the request never completes
StopWatch watch = new StopWatch();
// will wait for 1 second
client.stop();
final long elapsed = watch.taken();
assertTrue(elapsed > 900 && elapsed < 1100);
} |
void parseArgAndAppend(String entityName, String fieldName, Object arg) {
if (entityName == null || fieldName == null || arg == null) {
return;
}
if (arg instanceof Collection) {
for (Object o : (Collection<?>) arg) {
String matchedValue = String.valueOf(o);
api.appendDataInfluence(entityName, ApolloAuditConstants.ANY_MATCHED_ID, fieldName, matchedValue);
}
} else {
String matchedValue = String.valueOf(arg);
api.appendDataInfluence(entityName, ApolloAuditConstants.ANY_MATCHED_ID, fieldName, matchedValue);
}
} | @Test
public void testParseArgAndAppendCaseCollectionTypeArg() {
final String entityName = "App";
final String fieldName = "Name";
List<Object> list = Arrays.asList(new Object(), new Object(), new Object());
{
doNothing().when(api).appendDataInfluence(any(), any(), any(), any());
}
aspect.parseArgAndAppend(entityName, fieldName, list);
verify(api, times(list.size())).appendDataInfluence(eq(entityName),
eq(ApolloAuditConstants.ANY_MATCHED_ID), eq(fieldName), any());
} |
@Override
public List<Intent> compile(SinglePointToMultiPointIntent intent,
List<Intent> installable) {
Set<Link> links = new HashSet<>();
final boolean allowMissingPaths = intentAllowsPartialFailure(intent);
boolean hasPaths = false;
boolean missingSomePaths = false;
for (ConnectPoint egressPoint : intent.egressPoints()) {
if (egressPoint.deviceId().equals(intent.ingressPoint().deviceId())) {
// Do not need to look for paths, since ingress and egress
// devices are the same.
if (deviceService.isAvailable(egressPoint.deviceId())) {
hasPaths = true;
} else {
missingSomePaths = true;
}
continue;
}
Path path = getPath(intent, intent.ingressPoint().deviceId(), egressPoint.deviceId());
if (path != null) {
hasPaths = true;
links.addAll(path.links());
} else {
missingSomePaths = true;
}
}
// Allocate bandwidth if a bandwidth constraint is set
ConnectPoint ingressCP = intent.filteredIngressPoint().connectPoint();
List<ConnectPoint> egressCPs =
intent.filteredEgressPoints().stream()
.map(fcp -> fcp.connectPoint())
.collect(Collectors.toList());
List<ConnectPoint> pathCPs =
links.stream()
.flatMap(l -> Stream.of(l.src(), l.dst()))
.collect(Collectors.toList());
pathCPs.add(ingressCP);
pathCPs.addAll(egressCPs);
allocateBandwidth(intent, pathCPs);
if (!hasPaths) {
throw new IntentException("Cannot find any path between ingress and egress points.");
} else if (!allowMissingPaths && missingSomePaths) {
throw new IntentException("Missing some paths between ingress and egress points.");
}
Intent result = LinkCollectionIntent.builder()
.appId(intent.appId())
.key(intent.key())
.selector(intent.selector())
.treatment(intent.treatment())
.links(links)
.filteredIngressPoints(ImmutableSet.of(intent.filteredIngressPoint()))
.filteredEgressPoints(intent.filteredEgressPoints())
.priority(intent.priority())
.applyTreatmentOnEgress(true)
.constraints(intent.constraints())
.resourceGroup(intent.resourceGroup())
.build();
return Collections.singletonList(result);
} | @Test
public void testSingleLongPathCompilation() {
FilteredConnectPoint ingress =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
Set<FilteredConnectPoint> egress =
Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_2)));
SinglePointToMultiPointIntent intent =
makeIntent(ingress, egress);
assertThat(intent, is(notNullValue()));
String[] hops = {S2, S3, S4, S5, S6, S7};
SinglePointToMultiPointIntentCompiler compiler = makeCompiler(hops);
assertThat(compiler, is(notNullValue()));
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(Matchers.notNullValue()));
assertThat(result, hasSize(1));
Intent resultIntent = result.get(0);
assertThat(resultIntent instanceof LinkCollectionIntent, is(true));
if (resultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent;
assertThat(linkIntent.links(), hasSize(7));
assertThat(linkIntent.links(), linksHasPath(S1, S2));
assertThat(linkIntent.links(), linksHasPath(S2, S3));
assertThat(linkIntent.links(), linksHasPath(S3, S4));
assertThat(linkIntent.links(), linksHasPath(S4, S5));
assertThat(linkIntent.links(), linksHasPath(S5, S6));
assertThat(linkIntent.links(), linksHasPath(S6, S7));
assertThat(linkIntent.links(), linksHasPath(S7, S8));
}
assertThat("key is inherited", resultIntent.key(), is(intent.key()));
} |
public static Builder builder() {
return new AutoValue_HttpHeaders.Builder();
} | @Test
public void builderAddHeader_withNullName_throwsNullPointerException() {
assertThrows(
NullPointerException.class, () -> HttpHeaders.builder().addHeader(null, "test_value"));
} |
public static String getGlobalRuleActiveVersionNode(final String rulePath) {
return String.join("/", getGlobalRuleRootNode(), rulePath, ACTIVE_VERSION);
} | @Test
void assertGetGlobalRuleActiveVersionNode() {
assertThat(GlobalNode.getGlobalRuleActiveVersionNode("transaction"), is("/rules/transaction/active_version"));
} |
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (listClass != null || inner != null) {
log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner);
throw new ConfigException("List deserializer was already initialized using a non-default constructor");
}
configureListClass(configs, isKey);
configureInnerSerde(configs, isKey);
} | @Test
public void testListValueDeserializerNoArgConstructorsShouldThrowKafkaExceptionDueInvalidTypeClass() {
props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS, new FakeObject());
props.put(CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_INNER_CLASS, Serdes.StringSerde.class);
final KafkaException exception = assertThrows(
KafkaException.class,
() -> listDeserializer.configure(props, false)
);
assertEquals("Could not determine the list class instance using "
+ "\"" + CommonClientConfigs.DEFAULT_LIST_VALUE_SERDE_TYPE_CLASS + "\" property.", exception.getMessage());
} |
public static RuntimeException peel(final Throwable t) {
return (RuntimeException) peel(t, null, null, HAZELCAST_EXCEPTION_WRAPPER);
} | @Test
public void testPeel_whenThrowableIsExecutionExceptionWithCustomFactory_thenReturnCustomException() {
IOException expectedException = new IOException();
RuntimeException result = (RuntimeException) ExceptionUtil.peel(new ExecutionException(expectedException),
null, null, (throwable, message) -> new IllegalStateException(message, throwable));
assertEquals(IllegalStateException.class, result.getClass());
assertEquals(result.getCause(), expectedException);
} |
@Override
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria)
{
Map<String, String> variables = new HashMap<>();
if (userRegex.isPresent()) {
Matcher userMatcher = userRegex.get().matcher(criteria.getUser());
if (!userMatcher.matches()) {
return Optional.empty();
}
addVariableValues(userRegex.get(), criteria.getUser(), variables);
}
if (sourceRegex.isPresent()) {
String source = criteria.getSource().orElse("");
if (!sourceRegex.get().matcher(source).matches()) {
return Optional.empty();
}
addVariableValues(sourceRegex.get(), source, variables);
}
if (principalRegex.isPresent()) {
String principal = criteria.getPrincipal().orElse("");
if (!principalRegex.get().matcher(principal).matches()) {
return Optional.empty();
}
addVariableValues(principalRegex.get(), principal, variables);
}
if (!clientTags.isEmpty() && !criteria.getTags().containsAll(clientTags)) {
return Optional.empty();
}
if (clientInfoRegex.isPresent() && !clientInfoRegex.get().matcher(criteria.getClientInfo().orElse(EMPTY_CRITERIA_STRING)).matches()) {
return Optional.empty();
}
if (selectorResourceEstimate.isPresent() && !selectorResourceEstimate.get().match(criteria.getResourceEstimates())) {
return Optional.empty();
}
if (queryType.isPresent()) {
String contextQueryType = criteria.getQueryType().orElse(EMPTY_CRITERIA_STRING);
if (!queryType.get().equalsIgnoreCase(contextQueryType)) {
return Optional.empty();
}
}
if (schema.isPresent() && criteria.getSchema().isPresent()) {
if (criteria.getSchema().get().compareToIgnoreCase(schema.get()) != 0) {
return Optional.empty();
}
}
variables.putIfAbsent(USER_VARIABLE, criteria.getUser());
// Special handling for source, which is an optional field that is part of the standard variables
variables.putIfAbsent(SOURCE_VARIABLE, criteria.getSource().orElse(""));
variables.putIfAbsent(SCHEMA_VARIABLE, criteria.getSchema().orElse(""));
VariableMap map = new VariableMap(variables);
ResourceGroupId id = group.expandTemplate(map);
OptionalInt firstDynamicSegment = group.getFirstDynamicSegment();
return Optional.of(new SelectionContext<>(id, map, firstDynamicSegment));
} | @Test
public void testSelectorResourceEstimate()
{
ResourceGroupId resourceGroupId = new ResourceGroupId(new ResourceGroupId("global"), "foo");
StaticSelector smallQuerySelector = new StaticSelector(
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(new SelectorResourceEstimate(
Optional.of(new Range<>(
Optional.empty(),
Optional.of(Duration.valueOf("5m")))),
Optional.empty(),
Optional.of(new Range<>(
Optional.empty(),
Optional.of(DataSize.valueOf("500MB")))))),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
new ResourceGroupIdTemplate("global.foo"));
assertEquals(
smallQuerySelector.match(
newSelectionCriteria(
"userA",
null,
ImmutableSet.of("tag1", "tag2"),
new ResourceEstimates(
Optional.of(Duration.valueOf("4m")),
Optional.empty(),
Optional.of(DataSize.valueOf("400MB")),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.of(resourceGroupId));
assertEquals(
smallQuerySelector.match(
newSelectionCriteria(
"A.user",
"a source b",
ImmutableSet.of("tag1"),
new ResourceEstimates(
Optional.of(Duration.valueOf("4m")),
Optional.empty(),
Optional.of(DataSize.valueOf("600MB")),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.empty());
assertEquals(
smallQuerySelector.match(
newSelectionCriteria(
"userB",
"source",
ImmutableSet.of(),
new ResourceEstimates(
Optional.of(Duration.valueOf("4m")),
Optional.empty(),
Optional.empty(),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.empty());
StaticSelector largeQuerySelector = new StaticSelector(
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.of(new SelectorResourceEstimate(
Optional.empty(),
Optional.empty(),
Optional.of(new Range<>(
Optional.of(DataSize.valueOf("5TB")),
Optional.empty())))),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
new ResourceGroupIdTemplate("global.foo"));
assertEquals(
largeQuerySelector.match(
newSelectionCriteria(
"userA",
null,
ImmutableSet.of("tag1", "tag2"),
new ResourceEstimates(
Optional.of(Duration.valueOf("100h")),
Optional.empty(),
Optional.of(DataSize.valueOf("4TB")),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.empty());
assertEquals(
largeQuerySelector.match(
newSelectionCriteria(
"A.user",
"a source b",
ImmutableSet.of("tag1"),
new ResourceEstimates(
Optional.empty(),
Optional.empty(),
Optional.of(DataSize.valueOf("6TB")),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.of(resourceGroupId));
assertEquals(
largeQuerySelector.match(
newSelectionCriteria(
"userB",
"source",
ImmutableSet.of(),
new ResourceEstimates(
Optional.of(Duration.valueOf("1s")),
Optional.of(Duration.valueOf("1s")),
Optional.of(DataSize.valueOf("6TB")),
Optional.empty())))
.map(SelectionContext::getResourceGroupId),
Optional.of(resourceGroupId));
} |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalStructAsColumns() {
// Given:
final Schema structSchema = SchemaBuilder.struct()
.field("COL1", Schema.OPTIONAL_STRING_SCHEMA)
.field("COL4", SchemaBuilder
.array(Schema.OPTIONAL_FLOAT64_SCHEMA)
.optional()
.build())
.field("COL5", SchemaBuilder
.map(Schema.OPTIONAL_STRING_SCHEMA, Schema.OPTIONAL_FLOAT64_SCHEMA)
.optional()
.build())
.optional()
.build();
final SqlSchemaFormatter formatter = new SqlSchemaFormatter(
DO_NOT_ESCAPE_COLUMN_NAMES,
Option.AS_COLUMN_LIST,
Option.APPEND_NOT_NULL
);
// When:
final String result = formatter.format(structSchema);
// Then:
assertThat(result, is(
"COL1 VARCHAR, "
+ "COL4 ARRAY<DOUBLE>, "
+ "COL5 MAP<VARCHAR, DOUBLE>"));
} |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed!");
return;
}
final List<ViewWidgetLimitMigration> widgetLimitMigrations = StreamSupport.stream(this.views.find().spliterator(), false)
.flatMap(document -> {
final String viewId = document.get("_id", ObjectId.class).toHexString();
final Map<String, Document> state = document.get("state", Collections.emptyMap());
return state.entrySet().stream()
.flatMap(entry -> {
final String queryId = entry.getKey();
final List<Document> widgets = entry.getValue().get("widgets", Collections.emptyList());
return EntryStream.of(widgets)
.filter(widget -> "aggregation".equals(widget.getValue().getString("type")))
.flatMap(widgetEntry -> {
final Document widget = widgetEntry.getValue();
final Integer widgetIndex = widgetEntry.getKey();
final Document config = widget.get("config", new Document());
final boolean hasRowLimit = config.containsKey("row_limit");
final boolean hasColumnLimit = config.containsKey("column_limit");
final Optional<Integer> rowLimit = Optional.ofNullable(config.getInteger("row_limit"));
final Optional<Integer> columnLimit = Optional.ofNullable(config.getInteger("column_limit"));
if (widgetIndex != null && (hasRowLimit || hasColumnLimit)) {
return Stream.of(new ViewWidgetLimitMigration(viewId, queryId, widgetIndex, rowLimit, columnLimit));
}
return Stream.empty();
});
});
})
.collect(Collectors.toList());
final List<WriteModel<Document>> operations = widgetLimitMigrations.stream()
.flatMap(widgetMigration -> {
final ImmutableList.Builder<WriteModel<Document>> builder = ImmutableList.builder();
builder.add(
updateView(
widgetMigration.viewId,
doc("$unset", doc(widgetConfigPath(widgetMigration) + ".row_limit", 1))
)
);
builder.add(
updateView(
widgetMigration.viewId,
doc("$set", doc(widgetConfigPath(widgetMigration) + ".row_pivots.$[config].config.limit", widgetMigration.rowLimit.orElse(DEFAULT_LIMIT))),
matchValuePivots
)
);
builder.add(
updateView(
widgetMigration.viewId,
doc("$unset", doc(widgetConfigPath(widgetMigration) + ".column_limit", 1))
)
);
builder.add(
updateView(
widgetMigration.viewId,
doc("$set", doc(widgetConfigPath(widgetMigration) + ".column_pivots.$[config].config.limit", widgetMigration.columnLimit.orElse(DEFAULT_LIMIT))),
matchValuePivots
)
);
return builder.build().stream();
})
.collect(Collectors.toList());
if (!operations.isEmpty()) {
LOG.debug("Updating {} widgets ...", widgetLimitMigrations.size());
this.views.bulkWrite(operations);
}
clusterConfigService.write(new MigrationCompleted(widgetLimitMigrations.size()));
} | @Test
@MongoDBFixtures("V20230113095300_MigrateGlobalPivotLimitsToGroupingsInViewsTest_empty.json")
void notMigratingAnythingIfViewsAreEmpty() {
this.migration.upgrade();
assertThat(migrationCompleted().migratedViews()).isZero();
} |
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) {
if (filter.accept(operation.getOperationId())) {
final String methodName = method.name().toLowerCase();
emitter.emit(methodName, path);
emit("id", operation.getOperationId());
emit("description", operation.getDescription());
Set<String> operationLevelConsumes = new LinkedHashSet<>();
if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) {
operationLevelConsumes.addAll(operation.getRequestBody().getContent().keySet());
}
emit("consumes", operationLevelConsumes);
Set<String> operationLevelProduces = new LinkedHashSet<>();
if (operation.getResponses() != null) {
for (ApiResponse response : operation.getResponses().values()) {
if (response.getContent() != null) {
operationLevelProduces.addAll(response.getContent().keySet());
}
}
ApiResponse response = operation.getResponses().get(ApiResponses.DEFAULT);
if (response != null && response.getContent() != null) {
operationLevelProduces.addAll(response.getContent().keySet());
}
}
emit("produces", operationLevelProduces);
if (ObjectHelper.isNotEmpty(operation.getParameters())) {
operation.getParameters().forEach(this::emit);
}
if (ObjectHelper.isNotEmpty(pathItem.getParameters())) {
pathItem.getParameters().forEach(this::emit);
}
emitOperation(operation);
emitter.emit("to", destinationGenerator.generateDestinationFor(operation));
}
} | @Test
public void shouldEmitReferenceType() {
final Builder method = MethodSpec.methodBuilder("configure");
final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method);
final OperationVisitor<?> visitor = new OperationVisitor<>(
emitter, new OperationFilter(), "/path", new DefaultDestinationGenerator(), "camel.sample");
final OpenAPI document = new OpenAPIV3Parser().read(
"src/test/resources/org/apache/camel/generator/openapi/openapi-v3-ref-schema.yaml", null, null);
final PathItem pathItem = document.getPaths().get("/pet");
visitor.visit(PathItem.HttpMethod.PUT, pathItem.getPut(), pathItem);
assertThat(method.build().toString()).isEqualTo("void configure() {\n"
+ " put(\"/path\")\n"
+ " .id(\"updatePet\")\n"
+ " .description(\"Update an existing pet by Id\")\n"
+ " .consumes(\"application/json\")\n"
+ " .produces(\"application/json\")\n"
+ " .param()\n"
+ " .name(\"body\")\n"
+ " .type(org.apache.camel.model.rest.RestParamType.body)\n"
+ " .required(true)\n"
+ " .description(\"Update an existent pet in the store\")\n"
+ " .endParam()\n"
+ " .type(\"camel.sample.Pet[]\")\n"
+ " .outType(\"camel.sample.Pet[]\")\n"
+ " .to(\"direct:updatePet\")\n"
+ " }\n");
} |
@Override
public void execute(GraphModel graphModel) {
Graph graph = graphModel.getGraphVisible();
execute(graph);
} | @Test
public void testColumnReplace() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1);
graphModel.getNodeTable().addColumn(Degree.DEGREE, String.class);
Degree d = new Degree();
d.execute(graphModel);
} |
@Override
public T addInt(K name, int value) {
throw new UnsupportedOperationException("read only");
} | @Test
public void testAddInt() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
HEADERS.addInt("name", 0);
}
});
} |
@Override
public Comparison compare(final Path.Type type, final PathAttributes local, final PathAttributes remote) {
switch(type) {
case directory:
if(log.isDebugEnabled()) {
log.debug(String.format("Compare local attributes %s with remote %s using %s", local, remote, directories));
}
return directories.compare(type, local, remote);
case symboliclink:
return symlinks.compare(type, local, remote);
default:
if(log.isDebugEnabled()) {
log.debug(String.format("Compare local attributes %s with remote %s using %s", local, remote, files));
}
return files.compare(type, local, remote);
}
} | @Test
public void testCompareSymlink() {
final DefaultComparisonService c = new DefaultComparisonService(new TestProtocol());
assertEquals(Comparison.equal, c.compare(Path.Type.symboliclink, new PathAttributes().withModificationDate(1680879106939L), new PathAttributes().withModificationDate(1680879106939L)));
assertEquals(Comparison.local, c.compare(Path.Type.symboliclink, new PathAttributes().withModificationDate(1680879107939L), new PathAttributes().withModificationDate(1680879106939L)));
} |
@Override
public void onTaskFinished(TaskAttachment attachment) {
if (attachment instanceof BrokerPendingTaskAttachment) {
onPendingTaskFinished((BrokerPendingTaskAttachment) attachment);
} else if (attachment instanceof BrokerLoadingTaskAttachment) {
onLoadingTaskFinished((BrokerLoadingTaskAttachment) attachment);
}
} | @Test
public void testLoadingTaskOnFinishedPartialUpdate(@Injectable BrokerPendingTaskAttachment attachment1,
@Injectable LoadTask loadTask1,
@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database database) throws DdlException {
BrokerLoadJob brokerLoadJob = new BrokerLoadJob();
Map<String, String> properties = Maps.newHashMap();
properties.put(LoadStmt.PARTIAL_UPDATE_MODE, "column");
properties.put(LoadStmt.MERGE_CONDITION, "v1");
brokerLoadJob.setJobProperties(properties);
brokerLoadJob.onTaskFinished(attachment1);
} |
@Override
public String getString(final int columnIndex) throws SQLException {
return (String) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, String.class), String.class);
} | @Test
void assertGetStringWithColumnLabel() throws SQLException {
when(mergeResultSet.getValue(1, String.class)).thenReturn("value");
assertThat(shardingSphereResultSet.getString("label"), is("value"));
} |
@Override
public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Errors.forCode(response.errorCode())
);
throw new IllegalArgumentException(errorMessage);
}
MemberState state = state();
if (state == MemberState.LEAVING) {
log.debug("Ignoring heartbeat response received from broker. Member {} with epoch {} is " +
"already leaving the group.", memberId, memberEpoch);
return;
}
if (state == MemberState.UNSUBSCRIBED && maybeCompleteLeaveInProgress()) {
log.debug("Member {} with epoch {} received a successful response to the heartbeat " +
"to leave the group and completed the leave operation. ", memberId, memberEpoch);
return;
}
if (isNotInGroup()) {
log.debug("Ignoring heartbeat response received from broker. Member {} is in {} state" +
" so it's not a member of the group. ", memberId, state);
return;
}
// Update the group member id label in the client telemetry reporter if the member id has
// changed. Initially the member id is empty, and it is updated when the member joins the
// group. This is done here to avoid updating the label on every heartbeat response. Also
// check if the member id is null, as the schema defines it as nullable.
if (response.memberId() != null && !response.memberId().equals(memberId)) {
clientTelemetryReporter.ifPresent(reporter -> reporter.updateMetricsLabels(
Collections.singletonMap(ClientTelemetryProvider.GROUP_MEMBER_ID, response.memberId())));
}
this.memberId = response.memberId();
updateMemberEpoch(response.memberEpoch());
ConsumerGroupHeartbeatResponseData.Assignment assignment = response.assignment();
if (assignment != null) {
if (!state.canHandleNewAssignment()) {
// New assignment received but member is in a state where it cannot take new
// assignments (ex. preparing to leave the group)
log.debug("Ignoring new assignment {} received from server because member is in {} state.",
assignment, state);
return;
}
Map<Uuid, SortedSet<Integer>> newAssignment = new HashMap<>();
assignment.topicPartitions().forEach(topicPartition ->
newAssignment.put(topicPartition.topicId(), new TreeSet<>(topicPartition.partitions())));
processAssignmentReceived(newAssignment);
}
} | @Test
public void testUpdateStateFailsOnResponsesWithErrors() {
ConsumerMembershipManager membershipManager = createMembershipManagerJoiningGroup();
// Updating state with a heartbeat response containing errors cannot be performed and
// should fail.
ConsumerGroupHeartbeatResponse unknownMemberResponse =
createConsumerGroupHeartbeatResponseWithError(Errors.UNKNOWN_MEMBER_ID);
assertThrows(IllegalArgumentException.class,
() -> membershipManager.onHeartbeatSuccess(unknownMemberResponse.data()));
} |
public NodeList findElementsAndTypes() throws XPathExpressionException {
return (NodeList) xPath.compile("/xs:schema/xs:element")
.evaluate(document, XPathConstants.NODESET);
} | @Test
public void testFindElementsAndTypes() throws Exception {
Document document = XmlHelper.buildNamespaceAwareDocument(
ResourceUtils.getResourceAsFile("xmls/3_elements.xml"));
XPath xPath = XmlHelper.buildXPath(new CamelSpringNamespace());
domFinder = new DomFinder(document, xPath);
NodeList elements = domFinder.findElementsAndTypes();
assertEquals(3, elements.getLength());
} |
static BlockStmt getConstantVariableDeclaration(final String variableName, final Constant constant) {
final MethodDeclaration methodDeclaration =
CONSTANT_TEMPLATE.getMethodsByName(GETKIEPMMLCONSTANT).get(0).clone();
final BlockStmt toReturn =
methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration)));
final VariableDeclarator variableDeclarator =
getVariableDeclarator(toReturn, CONSTANT).orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, CONSTANT, toReturn)));
variableDeclarator.setName(variableName);
final ObjectCreationExpr objectCreationExpr = variableDeclarator.getInitializer()
.orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, CONSTANT
, toReturn)))
.asObjectCreationExpr();
final StringLiteralExpr nameExpr = new StringLiteralExpr(variableName);
final Expression valueExpr = getExpressionForObject(constant.getValue());
final Expression dataTypeExpression = getExpressionForDataType(constant.getDataType());
objectCreationExpr.getArguments().set(0, nameExpr);
objectCreationExpr.getArguments().set(2, valueExpr);
objectCreationExpr.getArguments().set(3, dataTypeExpression);
return toReturn;
} | @Test
void getConstantVariableDeclaration() throws IOException {
String variableName = "variableName";
Object value = 2342.21;
Constant constant = new Constant();
constant.setValue(value);
BlockStmt retrieved = KiePMMLConstantFactory.getConstantVariableDeclaration(variableName, constant);
String text = getFileContent(TEST_01_SOURCE);
Statement expected = JavaParserUtils.parseBlock(String.format(text, variableName, value));
assertThat(JavaParserUtils.equalsNode(expected, retrieved)).isTrue();
List<Class<?>> imports = Arrays.asList(KiePMMLConstant.class, Collections.class);
commonValidateCompilationWithImports(retrieved, imports);
} |
static Long replicationThrottle(CruiseControlRequestContext requestContext, KafkaCruiseControlConfig config) {
Long value = getLongParam(requestContext, REPLICATION_THROTTLE_PARAM, config.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG));
if (value != null && value < 0) {
throw new UserRequestException(String.format("Requested rebalance throttle must be non-negative (Requested: %s).", value));
}
return value;
} | @Test
public void testParseReplicationThrottleWithDefault() {
CruiseControlRequestContext mockRequest = EasyMock.mock(CruiseControlRequestContext.class);
KafkaCruiseControlConfig controlConfig = EasyMock.mock(KafkaCruiseControlConfig.class);
// No parameter string value in the parameter map
EasyMock.expect(mockRequest.getParameterMap()).andReturn(Collections.emptyMap()).once();
EasyMock.expect(controlConfig.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG))
.andReturn(Long.valueOf(DEFAULT_REPLICATION_THROTTLE_STRING));
EasyMock.replay(mockRequest, controlConfig);
Long replicationThrottle = ParameterUtils.replicationThrottle(mockRequest, controlConfig);
Assert.assertEquals(Long.valueOf(DEFAULT_REPLICATION_THROTTLE_STRING), replicationThrottle);
EasyMock.verify(mockRequest, controlConfig);
} |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (docStringTypes.isEmpty()) {
if (docString.getContentType() == null) {
throw new CucumberDocStringException(format(
"It appears you did not register docstring type for %s",
targetType.getTypeName()));
}
throw new CucumberDocStringException(format(
"It appears you did not register docstring type for '%s' or %s",
docString.getContentType(),
targetType.getTypeName()));
}
if (docStringTypes.size() > 1) {
List<String> suggestedContentTypes = suggestedContentTypes(docStringTypes);
if (docString.getContentType() == null) {
throw new CucumberDocStringException(format(
"Multiple converters found for type %s, add one of the following content types to your docstring %s",
targetType.getTypeName(),
suggestedContentTypes));
}
throw new CucumberDocStringException(format(
"Multiple converters found for type %s, and the content type '%s' did not match any of the registered types %s. Change the content type of the docstring or register a docstring type for '%s'",
targetType.getTypeName(),
docString.getContentType(),
suggestedContentTypes,
docString.getContentType()));
}
return (T) docStringTypes.get(0).transform(docString.getContent());
} | @Test
void json_to_string_with_registered_json_for_json_node_uses_default() {
registry.defineDocStringType(jsonNodeForJson);
DocString docString = DocString.create("hello world", "json");
assertThat(converter.convert(docString, String.class), is("hello world"));
} |
@Override
public void stopThreads() {
super.stopThreads();
try {
if (tokenCache != null) {
tokenCache.close();
}
} catch (Exception e) {
LOG.error("Could not stop Delegation Token Cache", e);
}
try {
if (delTokSeqCounter != null) {
delTokSeqCounter.close();
}
} catch (Exception e) {
LOG.error("Could not stop Delegation Token Counter", e);
}
try {
if (keyIdSeqCounter != null) {
keyIdSeqCounter.close();
}
} catch (Exception e) {
LOG.error("Could not stop Key Id Counter", e);
}
try {
if (keyCache != null) {
keyCache.close();
}
} catch (Exception e) {
LOG.error("Could not stop KeyCache", e);
}
try {
if (!isExternalClient && (zkClient != null)) {
zkClient.close();
}
} catch (Exception e) {
LOG.error("Could not stop Curator Framework", e);
}
} | @SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testStopThreads() throws Exception {
DelegationTokenManager tm1 = null;
String connectString = zkServer.getConnectString();
// let's make the update interval short and the shutdown interval
// comparatively longer, so if the update thread runs after shutdown,
// it will cause an error.
final long updateIntervalSeconds = 1;
final long shutdownTimeoutMillis = updateIntervalSeconds * 1000 * 5;
Configuration conf = getSecretConf(connectString);
conf.setLong(DelegationTokenManager.UPDATE_INTERVAL, updateIntervalSeconds);
conf.setLong(DelegationTokenManager.REMOVAL_SCAN_INTERVAL, updateIntervalSeconds);
conf.setLong(DelegationTokenManager.RENEW_INTERVAL, updateIntervalSeconds);
conf.setLong(ZKDelegationTokenSecretManager.ZK_DTSM_ZK_SHUTDOWN_TIMEOUT, shutdownTimeoutMillis);
tm1 = new DelegationTokenManager(conf, new Text("foo"));
tm1.init();
Token<DelegationTokenIdentifier> token =
(Token<DelegationTokenIdentifier>)
tm1.createToken(UserGroupInformation.getCurrentUser(), "foo");
Assert.assertNotNull(token);
tm1.destroy();
} |
@Override
public void updateDictType(DictTypeSaveReqVO updateReqVO) {
// 校验自己存在
validateDictTypeExists(updateReqVO.getId());
// 校验字典类型的名字的唯一性
validateDictTypeNameUnique(updateReqVO.getId(), updateReqVO.getName());
// 校验字典类型的类型的唯一性
validateDictTypeUnique(updateReqVO.getId(), updateReqVO.getType());
// 更新字典类型
DictTypeDO updateObj = BeanUtils.toBean(updateReqVO, DictTypeDO.class);
dictTypeMapper.updateById(updateObj);
} | @Test
public void testUpdateDictType_success() {
// mock 数据
DictTypeDO dbDictType = randomDictTypeDO();
dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据
// 准备参数
DictTypeSaveReqVO reqVO = randomPojo(DictTypeSaveReqVO.class, o -> {
o.setId(dbDictType.getId()); // 设置更新的 ID
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus());
});
// 调用
dictTypeService.updateDictType(reqVO);
// 校验是否更新正确
DictTypeDO dictType = dictTypeMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, dictType);
} |
static Map<String, Object> of(final Task task) {
return Map.of(
"id", task.getId(),
"type", task.getType()
);
} | @Test
void shouldGetVariablesGivenTrigger() {
Map<String, Object> variables = new RunVariables.DefaultBuilder()
.withTrigger(new AbstractTrigger() {
@Override
public String getId() {
return "id-value";
}
@Override
public String getType() {
return "type-value";
}
})
.build(new RunContextLogger());
Assertions.assertEquals(Map.of("id", "id-value", "type", "type-value"), variables.get("trigger"));
} |
@Override
public OFAgent removeAgent(NetworkId networkId) {
checkNotNull(networkId, ERR_NULL_NETID);
synchronized (this) {
OFAgent existing = ofAgentStore.ofAgent(networkId);
if (existing == null) {
final String error = String.format(MSG_OFAGENT, networkId, ERR_NOT_EXIST);
throw new IllegalStateException(error);
}
if (existing.state() == STARTED) {
final String error = String.format(MSG_OFAGENT, networkId, ERR_IN_USE);
throw new IllegalStateException(error);
}
log.info(String.format(MSG_OFAGENT, networkId, MSG_REMOVED));
return ofAgentStore.removeOfAgent(networkId);
}
} | @Test(expected = IllegalStateException.class)
public void testRemoveNotFoundAgent() {
target.removeAgent(NETWORK_1);
} |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSupplier, "transformerSupplier can't be null");
final String name = builder.newProcessorName(TRANSFORM_NAME);
return flatTransform(transformerSupplier, Named.as(name), stateStoreNames);
} | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowBadTransformerSupplierOnFlatTransform() {
final org.apache.kafka.streams.kstream.Transformer<String, String, Iterable<KeyValue<String, String>>> transformer = flatTransformerSupplier.get();
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> testStream.flatTransform(() -> transformer)
);
assertThat(exception.getMessage(), containsString("#get() must return a new object each time it is called."));
} |
public static CharSequence escapeCsv(CharSequence value) {
return escapeCsv(value, false);
} | @Test
public void escapeCsvEmpty() {
CharSequence value = "";
escapeCsv(value, value);
} |
@Delete(uri = "{namespace}/{id}")
@ExecuteOn(TaskExecutors.IO)
@Operation(tags = {"Flows"}, summary = "Delete a flow")
@ApiResponse(responseCode = "204", description = "On success")
public HttpResponse<Void> delete(
@Parameter(description = "The flow namespace") @PathVariable String namespace,
@Parameter(description = "The flow id") @PathVariable String id
) {
Optional<Flow> flow = flowRepository.findById(tenantService.resolveTenant(), namespace, id);
if (flow.isPresent()) {
flowRepository.delete(flow.get());
return HttpResponse.status(HttpStatus.NO_CONTENT);
} else {
return HttpResponse.status(HttpStatus.NOT_FOUND);
}
} | @Test
void importFlowsWithZip() throws IOException {
// create a ZIP file using the extract endpoint
byte[] zip = client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/export/by-query?namespace=io.kestra.tests"),
Argument.of(byte[].class));
File temp = File.createTempFile("flows", ".zip");
Files.write(temp.toPath(), zip);
var body = MultipartBody.builder()
.addPart("fileUpload", "flows.zip", temp)
.build();
var response = client.toBlocking().exchange(POST("/api/v1/flows/import", body).contentType(MediaType.MULTIPART_FORM_DATA));
assertThat(response.getStatus(), is(NO_CONTENT));
temp.delete();
} |
long getTime() {
return System.currentTimeMillis();
} | @Test (timeout=10000)
public void testClock(){
Clock clock= new Clock();
long templateTime=System.currentTimeMillis();
long time=clock.getTime();
assertEquals(templateTime, time,30);
} |
@Override
public Optional<FunctionDefinition> getFunctionDefinition(String name) {
final String normalizedName = name.toUpperCase(Locale.ROOT);
return Optional.ofNullable(normalizedFunctions.get(normalizedName));
} | @Test
void testGetNonExistFunction() {
assertThat(CoreModule.INSTANCE.getFunctionDefinition("nonexist")).isEmpty();
} |
@Override
@SuppressWarnings("nullness")
public synchronized List<Map<String, Object>> runSQLQuery(String sql) {
try (Statement stmt = driver.getConnection(getUri(), username, password).createStatement()) {
List<Map<String, Object>> result = new ArrayList<>();
ResultSet resultSet = stmt.executeQuery(sql);
while (resultSet.next()) {
Map<String, Object> row = new HashMap<>();
ResultSetMetaData metadata = resultSet.getMetaData();
// Columns list in table metadata is 1-indexed
for (int i = 1; i <= metadata.getColumnCount(); i++) {
row.put(metadata.getColumnName(i), resultSet.getObject(i));
}
result.add(row);
}
return result;
} catch (Exception e) {
throw new JDBCResourceManagerException("Failed to execute SQL statement: " + sql, e);
}
} | @Test
public void testRunSQLStatementShouldNotThrowErrorIfJDBCDoesNotThrowAnyError()
throws SQLException {
when(container.getHost()).thenReturn(HOST);
when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT);
testManager.runSQLQuery("SQL statement");
verify(driver.getConnection(any(), any(), any()).createStatement()).executeQuery(anyString());
} |
public static boolean isRuncContainerRequested(Configuration daemonConf,
Map<String, String> env) {
String type = (env == null)
? null : env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE);
if (type == null) {
type = daemonConf.get(YarnConfiguration.LINUX_CONTAINER_RUNTIME_TYPE);
}
return type != null && type.equals(
ContainerRuntimeConstants.CONTAINER_RUNTIME_RUNC);
} | @Test
public void testSelectRuncContainerType() {
Map<String, String> envRuncType = new HashMap<>();
Map<String, String> envOtherType = new HashMap<>();
envRuncType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE,
ContainerRuntimeConstants.CONTAINER_RUNTIME_RUNC);
envOtherType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, "other");
Assert.assertFalse(RuncContainerRuntime
.isRuncContainerRequested(conf, null));
Assert.assertTrue(RuncContainerRuntime
.isRuncContainerRequested(conf, envRuncType));
Assert.assertFalse(RuncContainerRuntime
.isRuncContainerRequested(conf, envOtherType));
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message);
Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message);
Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message);
Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message);
Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message);
Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message);
Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message);
Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message);
Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message);
Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message);
Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message);
Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message);
Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message);
Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message);
Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message);
Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message);
Matcher bloodEssenceCheckMatcher = BLOOD_ESSENCE_CHECK_PATTERN.matcher(message);
Matcher bloodEssenceExtractMatcher = BLOOD_ESSENCE_EXTRACT_PATTERN.matcher(message);
Matcher braceletOfClayCheckMatcher = BRACELET_OF_CLAY_CHECK_PATTERN.matcher(message);
if (message.contains(RING_OF_RECOIL_BREAK_MESSAGE))
{
notifier.notify(config.recoilNotification(), "Your Ring of Recoil has shattered");
}
else if (dodgyBreakMatcher.find())
{
notifier.notify(config.dodgyNotification(), "Your dodgy necklace has crumbled to dust.");
updateDodgyNecklaceCharges(MAX_DODGY_CHARGES);
}
else if (dodgyCheckMatcher.find())
{
updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1)));
}
else if (dodgyProtectMatcher.find())
{
updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1)));
}
else if (amuletOfChemistryCheckMatcher.find())
{
updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1)));
}
else if (amuletOfChemistryUsedMatcher.find())
{
final String match = amuletOfChemistryUsedMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateAmuletOfChemistryCharges(charges);
}
else if (amuletOfChemistryBreakMatcher.find())
{
notifier.notify(config.amuletOfChemistryNotification(), "Your amulet of chemistry has crumbled to dust.");
updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES);
}
else if (amuletOfBountyCheckMatcher.find())
{
updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1)));
}
else if (amuletOfBountyUsedMatcher.find())
{
updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1)));
}
else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT))
{
updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES);
}
else if (message.contains(BINDING_BREAK_TEXT))
{
notifier.notify(config.bindingNotification(), BINDING_BREAK_TEXT);
// This chat message triggers before the used message so add 1 to the max charges to ensure proper sync
updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1);
}
else if (bindingNecklaceUsedMatcher.find())
{
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
if (equipment.contains(ItemID.BINDING_NECKLACE))
{
updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1);
}
}
else if (bindingNecklaceCheckMatcher.find())
{
final String match = bindingNecklaceCheckMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateBindingNecklaceCharges(charges);
}
else if (ringOfForgingCheckMatcher.find())
{
final String match = ringOfForgingCheckMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateRingOfForgingCharges(charges);
}
else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY))
{
final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY);
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
// Determine if the player smelted with a Ring of Forging equipped.
if (equipment == null)
{
return;
}
if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1))
{
int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES);
updateRingOfForgingCharges(charges);
}
}
else if (message.equals(RING_OF_FORGING_BREAK_TEXT))
{
notifier.notify(config.ringOfForgingNotification(), "Your ring of forging has melted.");
// This chat message triggers before the used message so add 1 to the max charges to ensure proper sync
updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES + 1);
}
else if (chronicleAddMatcher.find())
{
final String match = chronicleAddMatcher.group(1);
if (match.equals("one"))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1);
}
else
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match));
}
}
else if (chronicleUseAndCheckMatcher.find())
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1)));
}
else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1);
}
else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0);
}
else if (message.equals(CHRONICLE_FULL_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000);
}
else if (slaughterActivateMatcher.find())
{
final String found = slaughterActivateMatcher.group(1);
if (found == null)
{
updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES);
notifier.notify(config.slaughterNotification(), BRACELET_OF_SLAUGHTER_BREAK_TEXT);
}
else
{
updateBraceletOfSlaughterCharges(Integer.parseInt(found));
}
}
else if (slaughterCheckMatcher.find())
{
updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1)));
}
else if (expeditiousActivateMatcher.find())
{
final String found = expeditiousActivateMatcher.group(1);
if (found == null)
{
updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES);
notifier.notify(config.expeditiousNotification(), EXPEDITIOUS_BRACELET_BREAK_TEXT);
}
else
{
updateExpeditiousBraceletCharges(Integer.parseInt(found));
}
}
else if (expeditiousCheckMatcher.find())
{
updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1)));
}
else if (bloodEssenceCheckMatcher.find())
{
updateBloodEssenceCharges(Integer.parseInt(bloodEssenceCheckMatcher.group(1)));
}
else if (bloodEssenceExtractMatcher.find())
{
updateBloodEssenceCharges(getItemCharges(ItemChargeConfig.KEY_BLOOD_ESSENCE) - Integer.parseInt(bloodEssenceExtractMatcher.group(1)));
}
else if (message.contains(BLOOD_ESSENCE_ACTIVATE_TEXT))
{
updateBloodEssenceCharges(MAX_BLOOD_ESSENCE_CHARGES);
}
else if (braceletOfClayCheckMatcher.find())
{
updateBraceletOfClayCharges(Integer.parseInt(braceletOfClayCheckMatcher.group(1)));
}
else if (message.equals(BRACELET_OF_CLAY_USE_TEXT) || message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN))
{
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
// Determine if the player mined with a Bracelet of Clay equipped.
if (equipment != null && equipment.contains(ItemID.BRACELET_OF_CLAY))
{
final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY);
// Charge is not used if only 1 inventory slot is available when mining in Prifddinas
boolean ignore = inventory != null
&& inventory.count() == 27
&& message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN);
if (!ignore)
{
int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_BRACELET_OF_CLAY) - 1, 0, MAX_BRACELET_OF_CLAY_CHARGES);
updateBraceletOfClayCharges(charges);
}
}
}
else if (message.equals(BRACELET_OF_CLAY_BREAK_TEXT))
{
notifier.notify(config.braceletOfClayNotification(), "Your bracelet of clay has crumbled to dust");
updateBraceletOfClayCharges(MAX_BRACELET_OF_CLAY_CHARGES);
}
}
} | @Test
public void testChronicleAddSingleChargeFull()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_ADD_SINGLE_CHARGE_FULL, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_CHRONICLE, 1000);
} |
public String build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
StringBuilder sql = new StringBuilder().append("ALTER TABLE ").append(tableName).append(" ");
switch (dialect.getId()) {
case PostgreSql.ID:
addColumns(sql, "ADD COLUMN ");
break;
case MsSql.ID:
sql.append("ADD ");
addColumns(sql, "");
break;
default:
sql.append("ADD (");
addColumns(sql, "");
sql.append(")");
}
return sql.toString();
} | @Test
public void add_columns_on_oracle() {
assertThat(createSampleBuilder(new Oracle()).build())
.isEqualTo("ALTER TABLE issues ADD (date_in_ms NUMBER (38) NULL, name VARCHAR2 (10 CHAR) NOT NULL, col_with_default NUMBER(1) DEFAULT 0 NOT NULL, varchar_col_with_default VARCHAR2 (3 CHAR) DEFAULT 'foo' NOT NULL)");
} |
@PublicAPI(usage = ACCESS)
public Set<Dependency> getDirectDependenciesFromSelf() {
return javaClassDependencies.getDirectDependenciesFromClass();
} | @Test
public void direct_dependencies_from_self_finds_correct_set_of_target_types() {
JavaClass javaClass = importPackagesOf(getClass()).get(ClassWithAnnotationDependencies.class);
Set<JavaClass> targets = javaClass.getDirectDependenciesFromSelf().stream().map(GET_TARGET_CLASS).collect(toSet());
assertThatTypes(targets).matchInAnyOrder(
B.class, AhavingMembersOfTypeB.class, Object.class, String.class,
List.class, Serializable.class, SomeSuperclass.class,
WithType.class, WithNestedAnnotations.class, OnClass.class, OnMethod.class, OnMethodParam.class,
OnConstructor.class, OnField.class, MetaAnnotated.class, WithEnum.class, WithPrimitive.class,
WithOtherEnum.class, WithOtherType.class,
SomeEnumAsAnnotationParameter.class, SomeEnumAsAnnotationArrayParameter.class,
SomeEnumAsNestedAnnotationParameter.class, SomeEnumAsDefaultParameter.class,
SomeOtherEnumAsAnnotationParameter.class, SomeOtherEnumAsDefaultParameter.class,
SomeOtherEnumAsAnnotationArrayParameter.class, SomeTypeAsDefaultParameter.class);
} |
String buildUrl( JmsDelegate delegate, boolean debug ) {
StringBuilder finalUrl = new StringBuilder( delegate.amqUrl.trim() );
// verify user hit the checkbox on the dialogue *and* also has not specified these values on the URL already
// end result: default to SSL settings in the URL if present, otherwise use data from the security tab
if ( delegate.sslEnabled && !finalUrl.toString().contains( "sslEnabled" ) ) {
appendSslOptions( delegate, finalUrl, debug );
}
return finalUrl.toString();
} | @Test public void testUrlBuildSslOptionsNoSsl() {
ActiveMQProvider provider = new ActiveMQProvider();
JmsDelegate delegate = new JmsDelegate( Collections.singletonList( provider ) );
delegate.amqUrl = AMQ_URL_BASE;
delegate.sslEnabled = false;
delegate.sslTruststorePath = TRUST_STORE_PATH_VAL;
delegate.sslTruststorePassword = TRUST_STORE_PASS_VAL;
String urlString = provider.buildUrl( delegate, false );
try {
URI url = new URI( urlString );
} catch ( URISyntaxException e ) {
fail( e.getMessage() );
}
assertFalse( "SSL disabled; should ignore params", urlString.contains( TRUST_STORE_PATH_VAL ) );
assertTrue( "URL base incorrect", urlString.compareTo( AMQ_URL_BASE ) == 0 );
} |
@Override
public TypeInformation<Tuple2<K, V>> getProducedType() {
return new TupleTypeInfo<Tuple2<K, V>>(
TypeExtractor.createTypeInfo(keyClass), TypeExtractor.createTypeInfo(valueClass));
} | @Test
void checkTypeInformation() throws Exception {
HadoopInputFormat<Void, Long> hadoopInputFormat =
new HadoopInputFormat<>(
new DummyVoidKeyInputFormat<Long>(),
Void.class,
Long.class,
Job.getInstance());
TypeInformation<Tuple2<Void, Long>> tupleType = hadoopInputFormat.getProducedType();
TypeInformation<Tuple2<Void, Long>> expectedType =
new TupleTypeInfo<>(BasicTypeInfo.VOID_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO);
assertThat(tupleType.isTupleType()).isTrue();
assertThat(tupleType).isEqualTo(expectedType);
} |
public boolean include(NotificationFilter filter) {
return pipelineName.equals(filter.pipelineName)
&& stageName.equals(filter.stageName)
&& event.include(filter.event);
} | @Test
void filterWithSameEventShouldIncludeOthers() {
assertThat(new NotificationFilter("cruise", "dev", StageEvent.Fixed, false).include(
new NotificationFilter("cruise", "dev", StageEvent.Fixed, true))).isTrue();
} |
@Override
public NacosLoggingAdapter build() {
return new LogbackNacosLoggingAdapter();
} | @Test
void build() {
LogbackNacosLoggingAdapterBuilder builder = new LogbackNacosLoggingAdapterBuilder();
NacosLoggingAdapter adapter = builder.build();
assertNotNull(adapter);
assertTrue(adapter instanceof LogbackNacosLoggingAdapter);
} |
@Override
public void removeAllVpls() {
Set<VplsData> allVplses = ImmutableSet.copyOf(vplsStore.getAllVpls());
allVplses.forEach(this::removeVpls);
} | @Test
public void testRemoveAllVpls() {
VplsData vplsData = VplsData.of(VPLS1);
vplsData.state(ADDED);
vplsStore.addVpls(vplsData);
vplsData = VplsData.of(VPLS2, VLAN);
vplsData.state(ADDED);
vplsStore.addVpls(vplsData);
vplsManager.removeAllVpls();
assertEquals(0, vplsStore.getAllVpls().size());
} |
public void addNote(Note note, AuthenticationInfo subject) throws IOException {
addOrUpdateNoteNode(new NoteInfo(note), true);
noteCache.putNote(note);
} | @Test
void testAddNoteRejectsDuplicatePath() throws IOException {
assertThrows(NotePathAlreadyExistsException.class,
() -> {
Note note1 = createNote("/prod/note");
Note note2 = createNote("/prod/note");
noteManager.addNote(note1, AuthenticationInfo.ANONYMOUS);
noteManager.addNote(note2, AuthenticationInfo.ANONYMOUS);
},
"Note '/prod/note' existed");
} |
public ConnectionAuthContext authorizePeer(X509Certificate cert) { return authorizePeer(List.of(cert)); } | @Test
void auth_context_contains_union_of_granted_capabilities_from_policies() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
createPolicy(POLICY_1, List.of(Capability.SLOBROK__API, Capability.CONTENT__DOCUMENT_API), List.of(cnRequirement)),
createPolicy(POLICY_2, List.of(Capability.SLOBROK__API, Capability.CONTENT__SEARCH_API), List.of(sanRequirement)));
var result = peerAuthorizer
.authorizePeer(createCertificate("foo.matching.cn", List.of("foo.matching.san"), List.of()));
assertAuthorized(result);
assertCapabiltiesGranted(result, Set.of(Capability.SLOBROK__API, Capability.CONTENT__DOCUMENT_API, Capability.CONTENT__SEARCH_API));
} |
public int getDepth() {
String path = mUri.getPath();
if (path.isEmpty() || CUR_DIR.equals(path)) {
return 0;
}
if (hasWindowsDrive(path, true)) {
path = path.substring(3);
}
int depth = 0;
int slash = path.length() == 1 && path.charAt(0) == '/' ? -1 : 0;
while (slash != -1) {
depth++;
slash = path.indexOf(SEPARATOR, slash + 1);
}
return depth;
} | @Test
public void getDepthTests() {
assertEquals(0, new AlluxioURI("").getDepth());
assertEquals(0, new AlluxioURI(".").getDepth());
assertEquals(0, new AlluxioURI("/").getDepth());
assertEquals(1, new AlluxioURI("/a").getDepth());
assertEquals(3, new AlluxioURI("/a/b/c.txt").getDepth());
assertEquals(2, new AlluxioURI("/a/b/").getDepth());
assertEquals(2, new AlluxioURI("a\\b").getDepth());
assertEquals(1, new AlluxioURI("C:\\a").getDepth());
assertEquals(1, new AlluxioURI("C:\\\\a").getDepth());
assertEquals(0, new AlluxioURI("C:\\\\").getDepth());
assertEquals(0, new AlluxioURI("alluxio://localhost:19998/").getDepth());
assertEquals(1, new AlluxioURI("alluxio://localhost:19998/a").getDepth());
assertEquals(2, new AlluxioURI("alluxio://localhost:19998/a/b.txt").getDepth());
} |
public JunctionTree junctionTree(List<OpenBitSet> cliques, boolean init) {
return junctionTree(null, null, null, cliques, init);
} | @Test
public void testJunctionWithPruning1() {
Graph<BayesVariable> graph = new BayesNetwork();
GraphNode x0 = addNode(graph);
GraphNode x1 = addNode(graph);
GraphNode x2 = addNode(graph);
GraphNode x3 = addNode(graph);
GraphNode x4 = addNode(graph);
GraphNode x5 = addNode(graph);
GraphNode x6 = addNode(graph);
GraphNode x7 = addNode(graph);
List<OpenBitSet> list = new ArrayList<OpenBitSet>();
OpenBitSet OpenBitSet1 = bitSet("00001111");
OpenBitSet OpenBitSet2 = bitSet("00111100");
OpenBitSet OpenBitSet3 = bitSet("11100001"); // links to 2 and 1, but should still result in a single path. As the 3 -> 1 link, gets pruned
OpenBitSet intersect1And2 = OpenBitSet2.clone();
intersect1And2.and(OpenBitSet1);
OpenBitSet intersect2And3 = OpenBitSet2.clone();
intersect2And3.and(OpenBitSet3);
list.add(OpenBitSet1);
list.add(OpenBitSet2);
list.add(OpenBitSet3);
JunctionTreeBuilder jtBuilder = new JunctionTreeBuilder( graph );
JunctionTreeClique jtNode = jtBuilder.junctionTree(list, false).getRoot();
assertThat(jtNode.getBitSet()).isEqualTo(OpenBitSet1);
assertThat(jtNode.getChildren().size()).isEqualTo(2);
JunctionTreeSeparator sep = jtNode.getChildren().get(0);
assertThat(sep.getParent().getBitSet()).isEqualTo(OpenBitSet1);
assertThat(sep.getChild().getBitSet()).isEqualTo(OpenBitSet2);
assertThat(sep.getChild().getChildren().size()).isEqualTo(0);
sep = jtNode.getChildren().get(1);
assertThat(sep.getParent().getBitSet()).isEqualTo(OpenBitSet1);
assertThat(sep.getChild().getBitSet()).isEqualTo(OpenBitSet3);
assertThat(sep.getChild().getChildren().size()).isEqualTo(0);
} |
@Override
public Optional<OffsetExpirationCondition> offsetExpirationCondition() {
throw new UnsupportedOperationException("offsetExpirationCondition is not supported for Share Groups.");
} | @Test
public void testOffsetExpirationCondition() {
ShareGroup shareGroup = createShareGroup("group-foo");
assertThrows(UnsupportedOperationException.class, shareGroup::offsetExpirationCondition);
} |
@Override
public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) {
StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES");
String[] queryParams = null;
switch (scope.type()) {
case ROOT:
// account-level listing
baseQuery.append(" IN ACCOUNT");
break;
case DATABASE:
// database-level listing
baseQuery.append(" IN DATABASE IDENTIFIER(?)");
queryParams = new String[] {scope.toIdentifierString()};
break;
case SCHEMA:
// schema-level listing
baseQuery.append(" IN SCHEMA IDENTIFIER(?)");
queryParams = new String[] {scope.toIdentifierString()};
break;
default:
throw new IllegalArgumentException(
String.format("Unsupported scope type for listIcebergTables: %s", scope));
}
final String finalQuery = baseQuery.toString();
final String[] finalQueryParams = queryParams;
List<SnowflakeIdentifier> tables;
try {
tables =
connectionPool.run(
conn ->
queryHarness.query(conn, finalQuery, TABLE_RESULT_SET_HANDLER, finalQueryParams));
} catch (SQLException e) {
throw snowflakeExceptionToIcebergException(
scope, e, String.format("Failed to list tables for scope '%s'", scope));
} catch (InterruptedException e) {
throw new UncheckedInterruptedException(
e, "Interrupted while listing tables for scope '%s'", scope);
}
tables.forEach(
table ->
Preconditions.checkState(
table.type() == SnowflakeIdentifier.Type.TABLE,
"Expected TABLE, got identifier '%s' for scope '%s'",
table,
scope));
return tables;
} | @SuppressWarnings("unchecked")
@Test
public void testListIcebergTablesInterruptedException()
throws SQLException, InterruptedException {
Exception injectedException = new InterruptedException("Fake interrupted exception");
when(mockClientPool.run(any(ClientPool.Action.class))).thenThrow(injectedException);
assertThatExceptionOfType(UncheckedInterruptedException.class)
.isThrownBy(() -> snowflakeClient.listIcebergTables(SnowflakeIdentifier.ofDatabase("DB_1")))
.withMessageContaining("Interrupted while listing tables for scope 'DATABASE: 'DB_1''")
.withCause(injectedException);
} |
public ConfigResponse resolveConfig(GetConfigRequest req, ConfigResponseFactory responseFactory) {
long start = System.currentTimeMillis();
metricUpdater.incrementRequests();
ConfigKey<?> configKey = req.getConfigKey();
String defMd5 = req.getRequestDefMd5();
if (defMd5 == null || defMd5.isEmpty()) {
defMd5 = ConfigUtils.getDefMd5(req.getDefContent().asList());
}
ConfigCacheKey cacheKey = new ConfigCacheKey(configKey, defMd5);
log.log(Level.FINE, () -> TenantRepository.logPre(getId()) + ("Resolving config " + cacheKey));
ConfigResponse config;
if (useCache(req)) {
config = cache.computeIfAbsent(cacheKey, (ConfigCacheKey key) -> {
var response = createConfigResponse(configKey, req, responseFactory);
metricUpdater.setCacheConfigElems(cache.configElems());
metricUpdater.setCacheChecksumElems(cache.checkSumElems());
return response;
});
} else {
config = createConfigResponse(configKey, req, responseFactory);
}
metricUpdater.incrementProcTime(System.currentTimeMillis() - start);
return config;
} | @Test(expected = UnknownConfigDefinitionException.class)
public void require_that_def_file_must_exist() {
handler.resolveConfig(createRequest("unknown", "namespace", emptySchema));
} |
@Override
@Nonnull
public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) {
throwRejectedExecutionExceptionIfShutdown();
ArrayList<Future<T>> result = new ArrayList<>();
for (Callable<T> task : tasks) {
try {
result.add(new CompletedFuture<>(task.call(), null));
} catch (Exception e) {
result.add(new CompletedFuture<>(null, e));
}
}
return result;
} | @Test
void testRejectedInvokeAnyWithTimeout() {
testRejectedExecutionException(
testInstance ->
testInstance.invokeAll(
Collections.singleton(() -> null), 1L, TimeUnit.DAYS));
} |
public static Setting getFirstFound(String... names) {
for (String name : names) {
try {
return get(name);
} catch (NoResourceException e) {
//ignore
}
}
return null;
} | @Test
public void getFirstFoundTest() {
//noinspection ConstantConditions
String driver = SettingUtil.getFirstFound("test2", "test")
.get("demo", "driver");
assertEquals("com.mysql.jdbc.Driver", driver);
} |
public static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length) {
return CRC(0x1021, 0x1D0F, data, offset, length, false, false, 0x0000);
} | @Test
public void AUG_CCITT_A() {
final byte[] data = new byte[] { 'A' };
assertEquals(0x9479, CRC16.AUG_CCITT(data, 0, 1));
} |
public static List<ConsumerGroupMemberMetadataValue.ClassicProtocol> classicProtocolListFromJoinRequestProtocolCollection(
JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols
) {
List<ConsumerGroupMemberMetadataValue.ClassicProtocol> newSupportedProtocols = new ArrayList<>();
protocols.forEach(protocol ->
newSupportedProtocols.add(
new ConsumerGroupMemberMetadataValue.ClassicProtocol()
.setName(protocol.name())
.setMetadata(protocol.metadata())
)
);
return newSupportedProtocols;
} | @Test
public void testClassicProtocolListFromJoinRequestProtocolCollection() {
JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestData.JoinGroupRequestProtocolCollection();
protocols.addAll(Arrays.asList(
new JoinGroupRequestData.JoinGroupRequestProtocol()
.setName("range")
.setMetadata(new byte[]{1, 2, 3})
));
assertEquals(
toClassicProtocolCollection("range"),
classicProtocolListFromJoinRequestProtocolCollection(protocols)
);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.