focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public String sendXML( String xml, String service ) throws Exception {
HttpPost method = buildSendXMLMethod( xml.getBytes( Const.XML_ENCODING ), service );
try {
return executeAuth( method );
} finally {
// Release current connection to the connection pool once you are done
method.releaseC... | @Test( expected = NullPointerException.class )
public void testSendXML() throws Exception {
slaveServer.setHostname( "hostNameStub" );
slaveServer.setUsername( "userNAmeStub" );
HttpPost httpPostMock = mock( HttpPost.class );
URI uriMock = new URI( "fake" );
doReturn( uriMock ).when( httpPostMock ... |
@Override
public void addDevice(SnmpDevice device) {
log.info("Adding device {}", device.deviceId());
snmpDeviceMap.put(device.deviceId(), device);
} | @Test
public void addDevice() {
snmpController.addDevice(device);
assertEquals("Controller should contain device", device, snmpController.getDevice(device.deviceId()));
} |
@Override
// not used in the codebase, here just for future API usage
public boolean isEmpty() {
return size() == 0;
} | @Test
public void testIsEmpty() {
final ArrayRingbuffer<String> rb = new ArrayRingbuffer<>(5);
assertTrue(rb.isEmpty());
rb.add("");
assertFalse(rb.isEmpty());
} |
@Override
public void write(String key, InputStream data) {
checkNotNull(data);
try {
write(key, data.readAllBytes());
} catch (IOException e) {
throw new IllegalStateException("Failed to read sensor write cache data", e);
}
} | @Test
public void write_throws_IAE_if_writing_same_key_twice() {
byte[] b1 = new byte[] {1};
byte[] b2 = new byte[] {2};
writeCache.write("key", b1);
assertThatThrownBy(() -> writeCache.write("key", b2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cache already contains key... |
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) {
Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType);
return BINARY_PRO... | @Test
void assertGetBinaryProtocolValueWithMySQLTypeTinyBlob() {
assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.TINY_BLOB), instanceOf(MySQLByteLenencBinaryProtocolValue.class));
} |
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
if (object == null) {
return Collections.emptyMap();
}
try {
ObjectParamMetadata metadata = getMetadata(object.getClass());
Map<String, Object> propertyNameToValue = new HashMap<String, Object>();
f... | @Test
void defaultEncoder_haveSuperClass() {
Map<String, Object> expected = new HashMap<>();
expected.put("page", 1);
expected.put("size", 10);
expected.put("query", "queryString");
SubClass subClass = new SubClass();
subClass.setPage(1);
subClass.setSize(10);
subClass.setQuery("queryS... |
@Override
public CreatePartitionsResult createPartitions(final Map<String, NewPartitions> newPartitions,
final CreatePartitionsOptions options) {
final Map<String, KafkaFutureImpl<Void>> futures = new HashMap<>(newPartitions.size());
final CreatePar... | @Test
public void testCreatePartitions() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
// Test a call where one filter has an error.
env.kafkaClient().prepareResponse(
... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldLexicallyScopeTheParameters() {
PipelineConfig withParams = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
withParams.addParam(param("foo", "pipeline"));
PipelineConfig withoutParams = PipelineConfigMother.createPipelineConfig("mingle", "dev", "an... |
static void cleanStackTrace(Throwable throwable) {
new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet());
} | @Test
public void allFramesBelowJUnitRunnerCleaned() {
Throwable throwable =
createThrowableWithStackTrace(
"com.google.common.truth.StringSubject",
"com.google.example.SomeTest",
SomeRunner.class.getName(),
"com.google.example.SomeClass");
StackTraceCl... |
@VisibleForTesting
public Schema getTableAvroSchema() {
try {
TableSchemaResolver schemaResolver = new TableSchemaResolver(metaClient);
return schemaResolver.getTableAvroSchema();
} catch (Throwable e) {
// table exists but has no written data
LOG.warn("Get table avro schema error, use... | @Test
void testGetTableAvroSchema() {
HoodieTableSource tableSource = getEmptyStreamingSource();
assertNull(tableSource.getMetaClient(), "Streaming source with empty table path is allowed");
final String schemaFields = tableSource.getTableAvroSchema().getFields().stream()
.map(Schema.Field::name)
... |
public int read() throws IOException {
if (input instanceof RandomAccessFile) {
return ((RandomAccessFile) input).read();
} else if (input instanceof DataInputStream) {
return ((DataInputStream) input).read();
} else {
throw new UnsupportedOperationException("... | @Test
public void testRead() throws IOException {
HollowBlobInput inStream = HollowBlobInput.modeBasedSelector(MemoryMode.ON_HEAP, mockBlob);
assertEquals(0, inStream.read()); // first byte is 0
assertEquals(1, inStream.read()); // second byte is 1
HollowBlobInput inBuffer = HollowB... |
public Properties createProperties(Props props, File logDir) {
Log4JPropertiesBuilder log4JPropertiesBuilder = new Log4JPropertiesBuilder(props);
RootLoggerConfig config = newRootLoggerConfigBuilder()
.setNodeNameField(getNodeNameWhenCluster(props))
.setProcessId(ProcessId.ELASTICSEARCH)
.buil... | @Test
public void createProperties_sets_root_logger_to_process_property_if_set() throws IOException {
File logDir = temporaryFolder.newFolder();
Properties properties = underTest.createProperties(newProps("sonar.log.level.es", "DEBUG"), logDir);
assertThat(properties.getProperty("rootLogger.level")).isEq... |
public void writeEncodedValue(EncodedValue encodedValue) throws IOException {
switch (encodedValue.getValueType()) {
case ValueType.BOOLEAN:
writeBooleanEncodedValue((BooleanEncodedValue) encodedValue);
break;
case ValueType.BYTE:
writeInte... | @Test
public void testWriteEncodedValue_enum_withSpaces() throws IOException {
BaksmaliWriter writer = new BaksmaliWriter(output);
writer.writeEncodedValue(new ImmutableEnumEncodedValue(getFieldReferenceWithSpaces()));
Assert.assertEquals(
".enum Ldefining/class/`with space... |
@Override
public ArrayList<ValidationFailure> getValidationFailures() {
return this.failuresCollection;
} | @Test
public void getValidationFailures() {
/** arrange */
FailureCollectorWrapper failureCollectorWrapper = new FailureCollectorWrapper();
String errorMessage = "An error has occurred";
FailureCollectorWrapper emptyFailureCollectorWrapper = new FailureCollectorWrapper();
RuntimeException error ... |
public void updateState(List<TridentTuple> tuples) {
try {
String bulkRequest = buildRequest(tuples);
final Request request = new Request("post", "_bulk");
request.setEntity(new StringEntity(bulkRequest));
Response response = client.performRequest(request);
... | @Test
public void indexMissing() throws Exception {
List<TridentTuple> tuples = tuples("missing", type, documentId, source);
state.updateState(tuples);
} |
@Override
public void check(final String databaseName, final ReadwriteSplittingRuleConfiguration ruleConfig, final Map<String, DataSource> dataSourceMap, final Collection<ShardingSphereRule> builtRules) {
checkDataSources(databaseName, ruleConfig.getDataSourceGroups(), dataSourceMap, builtRules);
ch... | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void assertCheckWhenConfigInvalidReadDataSource() {
ReadwriteSplittingRuleConfiguration config = mock(ReadwriteSplittingRuleConfiguration.class);
List<ReadwriteSplittingDataSourceGroupRuleConfiguration> configs = Arrays.asList(createDataSourceGr... |
public static ExecutionEnvironment createBatchExecutionEnvironment(FlinkPipelineOptions options) {
return createBatchExecutionEnvironment(
options,
MoreObjects.firstNonNull(options.getFilesToStage(), Collections.emptyList()),
options.getFlinkConfDir());
} | @Test
public void shouldSupportIPv4Batch() {
FlinkPipelineOptions options = getDefaultPipelineOptions();
options.setRunner(FlinkRunner.class);
options.setFlinkMaster("192.168.1.1:1234");
ExecutionEnvironment bev = FlinkExecutionEnvironments.createBatchExecutionEnvironment(options);
checkHostAndPo... |
@Override
public String retrieveIPfilePath(String id, String dstDir,
Map<Path, List<String>> localizedResources) {
// Assume .aocx IP file is distributed by DS to local dir
String ipFilePath = null;
LOG.info("Got environment: " + id +
", search IP file in localized resources");
if (null... | @Test
public void testLocalizedIpfileNotFoundWithNoLocalResources() {
String path = plugin.retrieveIPfilePath("fpga", "workDir", null);
assertNull("Retrieved IP file path", path);
} |
public static Map<JobVertexID, ForwardGroup> computeForwardGroups(
final Iterable<JobVertex> topologicallySortedVertices,
final Function<JobVertex, Set<JobVertex>> forwardProducersRetriever) {
final Map<JobVertex, Set<JobVertex>> vertexToGroup = new IdentityHashMap<>();
// iter... | @Test
void testOneInputSplitsIntoTwo() throws Exception {
JobVertex v1 = new JobVertex("v1");
JobVertex v2 = new JobVertex("v2");
JobVertex v3 = new JobVertex("v3");
JobVertex v4 = new JobVertex("v4");
v2.connectNewDataSetAsInput(
v1, DistributionPattern.ALL_... |
public FEELFnResult<Object> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern,
@ParameterName( "replacement" ) String replacement ) {
return invoke(input, pattern, replacement, null);
} | @Test
void invokeWithFlagMultiline() {
FunctionTestUtil.assertResult(replaceFunction.invoke("foo\nbar", "^b", "ttt", "m"), "foo\ntttar");
} |
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
} | @Test
void errors() {
final var e = new BusinessException("unhandled");
final var retry = new RetryExponentialBackoff<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(re... |
public boolean isKeyColumn(final ColumnName columnName) {
return findColumnMatching(withNamespace(Namespace.KEY).and(withName(columnName)))
.isPresent();
} | @Test
public void shouldNotMatchRandomColumnNameAsBeingMetaOrKeyColumns() {
assertThat(SystemColumns.isPseudoColumn(ColumnName.of("well_this_ain't_in_the_schema")), is(false));
assertThat(SOME_SCHEMA.isKeyColumn(ColumnName.of("well_this_ain't_in_the_schema")), is(false));
} |
public final static String getOutputCommand(ReturnObject rObject) {
StringBuilder builder = new StringBuilder();
// TODO Should be configurable
// TODO ADD RETURN MESSAGE TO OTHER OUTPUT COMMAND
builder.append(RETURN_MESSAGE);
if (rObject.isError()) {
builder.append(rObject.getCommandPart());
} else {
... | @Test
public void testGetOutputCommand() {
ReturnObject rObject1 = ReturnObject.getErrorReturnObject();
ReturnObject rObject2 = ReturnObject.getPrimitiveReturnObject(2);
ReturnObject rObject3 = ReturnObject.getPrimitiveReturnObject(2.2);
ReturnObject rObject4 = ReturnObject.getPrimitiveReturnObject(2.2f);
Re... |
public Timer add(long interval, TimerHandler handler, Object... args)
{
if (handler == null) {
return null;
}
return new Timer(timer.add(interval, handler, args));
} | @Test
public void testCancelTwice()
{
Timer timer = timers.add(10, handler);
assertThat(timer, notNullValue());
boolean rc = timer.cancel();
assertThat(rc, is(true));
rc = timer.cancel();
assertThat(rc, is(false));
} |
public final boolean checkIfExecuted(String input) {
return this.validator.isExecuted(Optional.of(ByteString.copyFromUtf8(input)));
} | @Test
public void checkIfExecuted_withNoParameter_executesValidator() {
TestValidatorIsCalledValidator testValidator = new TestValidatorIsCalledValidator();
Payload payload = new Payload("my-payload", testValidator, PAYLOAD_ATTRIBUTES, CONFIG);
payload.checkIfExecuted();
assertTrue(testValidator.wasC... |
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
if (object == null) {
return Collections.emptyMap();
}
ObjectParamMetadata metadata =
classToMetadata.computeIfAbsent(object.getClass(), ObjectParamMetadata::parseObjectType);
return metadata.objectField... | @Test
void defaultEncoder_normalClassWithValues() {
final Map<String, Object> expected = new HashMap<>();
expected.put("foo", "fooz");
expected.put("bar", "barz");
final NormalObject normalObject = new NormalObject("fooz", "barz");
final Map<String, Object> encodedMap = encoder.encode(normalObjec... |
@Override
public void updateMailSendResult(Long logId, String messageId, Exception exception) {
// 1. 成功
if (exception == null) {
mailLogMapper.updateById(new MailLogDO().setId(logId).setSendTime(LocalDateTime.now())
.setSendStatus(MailSendStatusEnum.SUCCESS.getStatus... | @Test
public void testUpdateMailSendResult_exception() {
// mock 数据
MailLogDO log = randomPojo(MailLogDO.class, o -> {
o.setSendStatus(MailSendStatusEnum.INIT.getStatus());
o.setSendTime(null).setSendMessageId(null).setSendException(null)
.setTemplateParam... |
public void setIni(Ini ini) {
this.ini = ini;
} | @Test
public void testSetIni() {
Ini ini = new Ini();
ini.addSection("users").put("foo", "bar");
env = new IniEnvironment();
env.setIni(ini);
env.init();
authenticate();
} |
@Override
public String decrypt(String encryptedText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decodeBase64(StringUtils.trim(encryptedText)));
byte[] iv = new byte[GCM_IV_LENGTH_IN_BYTES];
byteBuffer.g... | @Test
public void decrypt_bad_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt");
AesGCMCipher cipher = new AesGCMCipher(new File(resource.toURI()).getCanonicalPath());
assertThatThrownBy(() -> cipher.decrypt("9mx5Zq4JVyjeChTc... |
@Override
public void trash(final Local file) throws LocalAccessDeniedException {
if(log.isDebugEnabled()) {
log.debug(String.format("Move %s to Trash", file));
}
final ObjCObjectByReference error = new ObjCObjectByReference();
if(!NSFileManager.defaultManager().trashItem... | @Test(expected = LocalAccessDeniedException.class)
public void testTrashNotfound() throws Exception {
Local l = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
assertFalse(l.exists());
new FileManagerTrashFeature().trash(l);
} |
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQBrokerException {
return getConsumeStats(addr, consumerGroup, null, timeou... | @Test
public void assertGetConsumeStats() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
ConsumeStats responseBody = new ConsumeStats();
responseBody.setConsumeTps(1000);
setResponseBody(responseBody);
ConsumeStats actual = mqClientAPI.g... |
@Override
public CompletionStage<V> putAsync(K key, V value) {
return map.putAsync(key, value);
} | @Test
public void testPutAsync() throws Exception {
map.put(42, "oldValue");
Future<String> future = adapter.putAsync(42, "newValue").toCompletableFuture();
String oldValue = future.get();
assertEquals("oldValue", oldValue);
assertEquals("newValue", map.get(42));
} |
@Override
public void writeTo(ByteBuf byteBuf) throws LispWriterException {
WRITER.writeTo(byteBuf, this);
} | @Test
public void testSerialization() throws LispReaderException, LispWriterException,
LispParseError, DeserializationException {
ByteBuf byteBuf = Unpooled.buffer();
ReferralWriter writer = new ReferralWriter();
writer.writeTo(byteBuf, referral1);
... |
public static DataMap getAnnotationsMap(Annotation[] as)
{
return annotationsToData(as, true);
} | @Test(description = "Non-empty annotation, scalar members, default values: data map with annotation + no members")
public void succeedsOnSupportedScalarMembersWithDefaultValues()
{
@SupportedScalarMembers
class LocalClass {
}
final Annotation[] annotations = LocalClass.class.getAnnotations();
f... |
@Override
public boolean reportChecksumFailure(Path p, FSDataInputStream in,
long inPos,
FSDataInputStream sums, long sumsPos) {
try {
// canonicalize f
File f = ((RawLocalFileSystem)fs).pathToFile(p).getCanonicalFile();
... | @Test
public void testReportChecksumFailure() throws IOException {
base.mkdirs();
assertTrue(base.exists() && base.isDirectory());
final File dir1 = new File(base, "dir1");
final File dir2 = new File(dir1, "dir2");
dir2.mkdirs();
assertTrue(dir2.exists() && FileUtil.canWrite(dir2));
... |
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry>... | @Test
public void testFilterAclEntriesByAclSpecAccessMaskCalculated()
throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ))
.add(aclEntry(ACCESS, USER, "diana", READ_WRITE))
... |
public String encode(long... numbers) {
if (numbers.length == 0) {
return "";
}
for (final long number : numbers) {
if (number < 0) {
return "";
}
if (number > MAX_NUMBER) {
throw new IllegalArgumentException("numbe... | @Test
public void test_issue31() {
final long[] numbers = new long[500000];
long current = Hashids.MAX_NUMBER;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = current--;
}
final Hashids a = new Hashids("this is my salt");
Assert.assertNotEq... |
public static RuleDescriptionSectionDtoBuilder builder() {
return new RuleDescriptionSectionDtoBuilder();
} | @Test
void setDefault_whenKeyAlreadySet_shouldThrow() {
RuleDescriptionSectionDto.RuleDescriptionSectionDtoBuilder builderWithKey = RuleDescriptionSectionDto.builder()
.key("tagada");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(builderWithKey::setDefault)
.withMessa... |
@Description("bitwise NOT in 2's complement arithmetic")
@ScalarFunction
@SqlType(StandardTypes.BIGINT)
public static long bitwiseNot(@SqlType(StandardTypes.BIGINT) long num)
{
return ~num;
} | @Test
public void testBitwiseNot()
{
assertFunction("bitwise_not(0)", BIGINT, ~0L);
assertFunction("bitwise_not(-1)", BIGINT, ~-1L);
assertFunction("bitwise_not(8)", BIGINT, ~8L);
assertFunction("bitwise_not(-8)", BIGINT, ~-8L);
assertFunction("bitwise_not(" + Long.MAX_VA... |
public boolean isRoundRobinSelection() {
return roundRobinSelection;
} | @Test
void roundRobinSelection() {
assertThat(builder.build().isRoundRobinSelection()).isFalse();
builder.roundRobinSelection(true);
assertThat(builder.build().isRoundRobinSelection()).isTrue();
} |
public ActionResult apply(Agent agent, Map<String, String> request) {
log.debug("Reading file {} for agent {}", request.get("filename"), agent.getId());
Optional<Document> document = workspace.getDocument(agent.getId(), request.get("filename"));
if (document.isPresent()) {
byte[] art... | @Test
void testApplyWithExistingFile() {
String agentId = "agent1";
String filename = "test.txt";
String fileContent = "This is a test file.";
Map<String, String> request = new HashMap<>();
request.put("filename", filename);
when(agent.getId()).thenReturn(agentId);
... |
protected static void printConsumerProgress(int id,
long bytesRead,
long lastBytesRead,
long messagesRead,
long lastMessagesRead... | @Test
public void testNonDetailedHeaderMatchBody() {
testHeaderMatchContent(false, 2,
() -> ConsumerPerformance.printConsumerProgress(1, 1024 * 1024, 0, 1, 0, 0, 1, dateFormat, 1L));
} |
public void updateTableSchema(String tableName, Schema schema, List<String> partitionFields) {
Table existingTable = bigquery.getTable(TableId.of(projectId, datasetName, tableName));
ExternalTableDefinition definition = existingTable.getDefinition();
Schema remoteTableSchema = definition.getSchema();
Li... | @Test
void skipUpdatingSchema_partitioned() throws Exception {
BigQuerySyncConfig config = new BigQuerySyncConfig(properties);
client = new HoodieBigQuerySyncClient(config, mockBigQuery);
Table mockTable = mock(Table.class);
ExternalTableDefinition mockTableDefinition = mock(ExternalTableDefinition.cl... |
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) {
return metricEvaluationResult != null
&& metricEvaluationResult.evaluationResult.level() != Measure.Level.OK
&& METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric... | @Test
public void ignore_errors_about_new_coverage_for_small_changesets() {
mapSettings.setProperty(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES, true);
QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR);
Component project = genera... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
final Path found = this.search(file, listener);
return found != null;
}
catch(Notfound... | @Test
public void testCaseInsensitive() throws Exception {
assertTrue(new DefaultFindFeature(new NullSession(new Host(new TestProtocol())) {
@Override
public Protocol.Case getCaseSensitivity() {
return Protocol.Case.insensitive;
}
@Override
... |
public static List<String> splitPlainTextLines(String text, int maxTokensPerLine) {
return internalSplitLines(text, maxTokensPerLine, true, s_plaintextSplitOptions);
} | @Test
public void canSplitPlainTextLinesLongStringWithSmallTokenCount() {
String input = "This is a very very very very very very very very very very very long string.";
List<String> expected = Arrays.asList(
"This is a",
"very very",
"very very",
"ver... |
@Override
public Num calculate(BarSeries series, Position position) {
return position.hasLoss() ? series.one() : series.zero();
} | @Test
public void calculateWithNoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
assertNumEquals(0, getCriterion().calculate(series, new BaseTradingRecord()));
} |
@Override
public final String toString() {
StringJoiner result = new StringJoiner(", ", "(", ")");
for (int i = 0; i < values.size(); i++) {
result.add(getValue(i));
}
return result.toString();
} | @Test
void assertToString() {
List<ExpressionSegment> expressionSegments = new ArrayList<>(4);
ParameterMarkerExpressionSegment parameterMarkerExpressionSegment = new ParameterMarkerExpressionSegment(1, 1, 1);
ParameterMarkerExpressionSegment positionalParameterMarkerExpressionSegment = new ... |
public String getOldValue() {
return oldValue;
} | @Test
void getOldValue() {
ConfigurationChangeEvent event = new ConfigurationChangeEvent();
event.setOldValue("oldValue");
Assertions.assertEquals("oldValue", event.getOldValue());
} |
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception {
Http2HeadersSink sink = new Http2HeadersSink(
streamId, headers, maxHeaderListSize, validateHeaders);
// Check for dynamic table size updates, which must occur at the beginning:
... | @Test
public void responsePseudoHeaderInRequest() throws Exception {
final ByteBuf in = Unpooled.buffer(200);
try {
HpackEncoder hpackEncoder = new HpackEncoder(true);
Http2Headers toEncode = new DefaultHttp2Headers();
toEncode.add(":method", "GET");
... |
@Override
public BeamSqlTable buildBeamSqlTable(Table tableDefinition) {
ObjectNode tableProperties = tableDefinition.getProperties();
try {
RowJson.RowJsonDeserializer deserializer =
RowJson.RowJsonDeserializer.forSchema(getSchemaIOProvider().configurationSchema())
.withNullBeh... | @Test
public void testBuildIOReader() {
TestSchemaIOTableProviderWrapper provider = new TestSchemaIOTableProviderWrapper();
BeamSqlTable beamSqlTable = provider.buildBeamSqlTable(testTable);
PCollection<Row> result = beamSqlTable.buildIOReader(pipeline.begin());
PAssert.that(result).containsInAnyOrde... |
boolean isEncodable(DiscreteResource resource) {
return resource.valueAs(Object.class)
.map(Object::getClass)
.map(codecs::containsKey)
.orElse(Boolean.FALSE);
} | @Test
public void isVlanEncodable() {
DiscreteResource resource = Resources.discrete(DID, PN, VLAN).resource();
assertThat(sut.isEncodable(resource), is(true));
} |
@Override
public Integer getJavaVersion() {
return jarJavaVersion;
} | @Test
public void testGetJavaVersion() {
SpringBootExplodedProcessor springBootExplodedProcessor =
new SpringBootExplodedProcessor(Paths.get("ignore"), Paths.get("ignore"), 8);
assertThat(springBootExplodedProcessor.getJavaVersion()).isEqualTo(8);
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchAfterPartitionWithFetchedRecordsIsUnassigned() {
buildFetcher(2);
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 1);
// Returns 3 records while `max.poll.records` is configured to 2
client.prepareResponse(matchesOffset(tidp0, 1), fullFetc... |
public Map<String, PartitionsSpec> materialize() {
HashMap<String, PartitionsSpec> all = new HashMap<>();
for (Map.Entry<String, PartitionsSpec> entry : map.entrySet()) {
String topicName = entry.getKey();
PartitionsSpec partitions = entry.getValue();
for (String expa... | @Test
public void testMaterialize() {
Map<String, PartitionsSpec> parts = FOO.materialize();
assertTrue(parts.containsKey("topicA0"));
assertTrue(parts.containsKey("topicA1"));
assertTrue(parts.containsKey("topicA2"));
assertTrue(parts.containsKey("topicB"));
assertEq... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldPropagateErrorOnSRClientError() throws Exception {
// Given:
givenStatement("CREATE STREAM sink WITH(value_format='AVRO') AS SELECT * FROM SOURCE;");
when(schemaRegistryClient.register(anyString(), any(ParsedSchema.class)))
.thenThrow(new IOException("FUBAR"));
// When... |
@Override
public void calculate() {
} | @Test
public void testCalculate() {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), LARGE_VALUE);
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), SMALL_VALUE);
function.calculate();
assertThat(function.getValue()).isEqualTo(LARGE_VALUE);... |
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) {
return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive();
} | @Test
public void withTurnRestriction() {
// here 0-1-2-3 would be a circle and thus belong to same connected component. but if there is a
// turn restriction for going 0->2->3 this splits the graph into multiple components
// 0->1
// | |
// 3<-2->4
g.edge(0, 1).setD... |
public static String readFile(String path, String fileName) {
File file = openFile(path, fileName);
if (file.exists()) {
return readFile(file);
}
return null;
} | @Test
void testReadFileWithInputStream() throws FileNotFoundException {
assertNotNull(DiskUtils.readFile(new FileInputStream(testFile)));
} |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException {
String relayState = request.getParameter(RELAY_STATE_PARAMETER);
if (isSamlValidation(relayState)) {
URI redirectionEndpointUrl = URI.create(server.getContextPath() + "/")
.resolv... | @Test
public void do_filter_validation_wrong_SAML_response() throws IOException {
HttpRequest servletRequest = mock(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
FilterChain filterChain = mock(FilterChain.class);
String maliciousSaml = "test\"</input><script>/*hack webs... |
PubSubMessage rowToMessage(Row row) {
row = castRow(row, row.getSchema(), schema);
PubSubMessage.Builder builder = PubSubMessage.newBuilder();
if (schema.hasField(MESSAGE_KEY_FIELD)) {
byte[] bytes = row.getBytes(MESSAGE_KEY_FIELD);
if (bytes != null) {
builder.setKey(ByteString.copyFrom... | @Test
public void rowToMessageFailures() {
Schema payloadSchema = Schema.builder().addStringField("def").build();
Schema schema = Schema.builder().addRowField(RowHandler.PAYLOAD_FIELD, payloadSchema).build();
RowHandler rowHandler = new RowHandler(schema, serializer);
// badRow cannot be cast to schem... |
@Override
public long[] getValues() {
return Arrays.copyOf(values, values.length);
} | @Test
public void hasValues() {
assertThat(snapshot.getValues())
.containsOnly(1, 2, 3, 4, 5);
} |
public void inject(Inspector inspector, Inserter inserter) {
if (inspector.valid()) {
injectValue(inserter, inspector, null);
}
} | @Test
public void invalidInjectionIsIgnored() {
inject(f1.arrayValue.get(), new SlimeInserter(f2.slime1));
assertEquals(3, f2.slime1.get().entries());
inject(f1.longValue.get(), new ArrayInserter(f2.slime1.get()));
assertEquals(4, f2.slime1.get().entries());
inject(f1.doubleV... |
private CompletableFuture<Boolean> verifyTxnOwnership(TxnID txnID) {
assert ctx.executor().inEventLoop();
return service.pulsar().getTransactionMetadataStoreService()
.verifyTxnOwnership(txnID, getPrincipal())
.thenComposeAsync(isOwner -> {
if (isOwner... | @Test(timeOut = 30000)
public void sendAddSubscriptionToTxnResponseFailed() throws Exception {
final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class);
when(txnStore.getTxnMeta(any())).thenReturn(CompletableFuture.completedFuture(mock(TxnMeta.class)));
wh... |
protected static List<URL> filterEmpty(URL url, List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
List<URL> result = new ArrayList<>(1);
result.add(url.setProtocol(EMPTY_PROTOCOL));
return result;
}
return urls;
} | @Test
void filterEmptyTest() {
// check parameters
try {
AbstractRegistry.filterEmpty(null, null);
Assertions.fail();
} catch (Exception e) {
Assertions.assertTrue(e instanceof NullPointerException);
}
// check parameters
List<URL>... |
public QueryBuilders.QueryBuilder convert(Expr conjunct) {
return visit(conjunct);
} | @Test
public void testTranslateCompoundPredicate() {
SlotRef col1SlotRef = mockSlotRef("col1", Type.INT);
IntLiteral intLiteral1 = new IntLiteral(100);
SlotRef col2SlotRef = mockSlotRef("col2", Type.INT);
IntLiteral intLiteral2 = new IntLiteral(200);
BinaryPredicate bp1 = ne... |
public MessageQueueListener getMessageQueueListener() {
if (null == defaultMQPushConsumer) {
return null;
}
return defaultMQPushConsumer.getMessageQueueListener();
} | @Test
public void testGetMessageQueueListener() {
assertNull(defaultMQPushConsumerImpl.getMessageQueueListener());
} |
@Override
public V pollLastAndOfferFirstTo(String queueName, long timeout, TimeUnit unit) throws InterruptedException {
return commandExecutor.getInterrupted(pollLastAndOfferFirstToAsync(queueName, timeout, unit));
} | @Test
public void testPollLastAndOfferFirstTo() throws InterruptedException {
final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("{queue}1");
queue1.trySetCapacity(10);
Executors.newSingleThreadScheduledExecutor().schedule(() -> {
try {
... |
@Override
public CompletableFuture<TopicList> queryTopicsByConsumer(String address,
QueryTopicsByConsumerRequestHeader requestHeader, long timeoutMillis) {
CompletableFuture<TopicList> future = new CompletableFuture<>();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestC... | @Test
public void assertQueryTopicsByConsumerWithSuccess() throws Exception {
TopicList responseBody = new TopicList();
setResponseSuccess(RemotingSerializable.encode(responseBody));
QueryTopicsByConsumerRequestHeader requestHeader = mock(QueryTopicsByConsumerRequestHeader.class);
Co... |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void slidingWindowedCogroupedNamedMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.cogroup((key, value, aggregate) -> value)
.windowedBy(SlidingWindo... |
public static <K, V> HashMap<K, V> toMap(Iterable<Entry<K, V>> entryIter) {
return IterUtil.toMap(entryIter);
} | @Test
public void toMapTest() {
final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d");
final Map<String, String> map = CollUtil.toMap(keys, new HashMap<>(), (value) -> "key" + value);
assertEquals("a", map.get("keya"));
assertEquals("b", map.get("keyb"));
assertEquals("c", map.get("keyc")... |
public static Tidy getParser() {
log.debug("Start : getParser1");
Tidy tidy = new Tidy();
tidy.setInputEncoding(StandardCharsets.UTF_8.name());
tidy.setOutputEncoding(StandardCharsets.UTF_8.name());
tidy.setQuiet(true);
tidy.setShowWarnings(false);
if (log.isDebu... | @Test
public void testGetParser() throws Exception {
HtmlParsingUtils.getParser();
} |
public void submitEtlJob(long loadJobId, String loadLabel, EtlJobConfig etlJobConfig, SparkResource resource,
BrokerDesc brokerDesc, SparkLoadAppHandle handle, SparkPendingTaskAttachment attachment,
Long sparkLoadSubmitTimeout)
throws LoadException {... | @Test(expected = LoadException.class)
public void testSubmitEtlJobFailed(@Mocked BrokerUtil brokerUtil, @Mocked SparkLauncher launcher,
@Injectable Process process,
@Mocked SparkLoadAppHandle handle) throws IOException, LoadException {
... |
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
} | @Test
void testIsTraceEnabled() {
jobRunrDashboardLogger.isTraceEnabled();
verify(slfLogger).isTraceEnabled();
} |
public static int toMonths(int year, int months)
{
try {
return addExact(multiplyExact(year, 12), months);
}
catch (ArithmeticException e) {
throw new IllegalArgumentException(e);
}
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testOverflow()
{
int days = (Integer.MAX_VALUE / 12) + 1;
toMonths(days, 0);
} |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testPrimitiveTypes() throws Exception {
Schema schema =
Schema.of(
Schema.Field.of("f0", FieldType.DATETIME),
Schema.Field.of("f1", FieldType.DATETIME),
Schema.Field.of("f2", FieldType.FLOAT),
Schema.Field.of("f3", FieldType.DOUBLE),
... |
public static String resolveMainClass(
@Nullable String configuredMainClass, ProjectProperties projectProperties)
throws MainClassInferenceException, IOException {
if (configuredMainClass != null) {
if (isValidJavaClass(configuredMainClass)) {
return configuredMainClass;
}
thro... | @Test
public void testResolveMainClass_multipleInferredWithInvalidMainClassFromJarPlugin()
throws URISyntaxException, IOException {
Mockito.when(mockProjectProperties.getMainClassFromJarPlugin()).thenReturn("${start-class}");
Mockito.when(mockProjectProperties.getClassFiles())
.thenReturn(
... |
public static <InputT, OutputT> PTransformRunnerFactory<?> forValueMapFnFactory(
ValueMapFnFactory<InputT, OutputT> fnFactory) {
return new Factory<>(new CompressedValueOnlyMapperFactory<>(fnFactory));
} | @Test
public void testValueOnlyMapping() throws Exception {
PTransformRunnerFactoryTestContext context =
PTransformRunnerFactoryTestContext.builder(EXPECTED_ID, EXPECTED_PTRANSFORM)
.processBundleInstructionId("57")
.pCollections(Collections.singletonMap("inputPC", INPUT_PCOLLECTIO... |
static boolean shouldStoreMessage(final Message message) {
// XEP-0334: Implement the <no-store/> hint to override offline storage
if (message.getChildElement("no-store", "urn:xmpp:hints") != null) {
return false;
}
// OF-2083: Prevent storing offline message that is already... | @Test
public void shouldNotStoreEmptyChatMessagesWithOnlyChatStatesAndThread() {
Message message = new Message();
message.setType(Message.Type.chat);
message.setThread("1234");
PacketExtension chatState = new PacketExtension("composing", "http://jabber.org/protocol/chatstates");
... |
public void setFilePath(String filePath) {
if (filePath == null) {
throw new IllegalArgumentException("File path cannot be null.");
}
// TODO The job-submission web interface passes empty args (and thus empty
// paths) to compute the preview graph. The following is a workaro... | @Test
void testSetPathNullString() {
assertThatThrownBy(() -> new DummyFileInputFormat().setFilePath((String) null))
.isInstanceOf(IllegalArgumentException.class);
} |
@GET
@Path("{netId}")
@Produces(MediaType.APPLICATION_JSON)
public Response allocateIp(@PathParam("netId") String netId) {
log.trace("Received IP allocation request of network " + netId);
K8sNetwork network =
nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND... | @Test
public void testAllocateIp() {
expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
expect(mockIpamService.allocateIp(anyObject()))
.andReturn(IpAddress.valueOf("10.10.10.2"));
replay(mockNetworkService);
replay(mockIpamService);
fina... |
public String migrateIfNecessary(String rawXml) throws Exception {
String fileVersion = extractVersion(rawXml);
ThrowingConsumer<Document> migrator = getMigrationStrategy().start();
boolean supported;
switch (fileVersion) {
case "1.0":
migrator = migrator.andT... | @Test
public void migrateIfNecessary() throws Exception {
assertThatThrownBy(() -> instance.migrateIfNecessary("<ScenarioSimulationModel version=\"9999999999.99999999999\" />"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Version 9999999999.99999999999 of the f... |
@Override
public Output run(RunContext runContext) throws Exception {
URI from = new URI(runContext.render(this.from));
final PebbleExpressionPredicate predicate = getExpressionPredication(runContext);
final Path path = runContext.workingDir().createTempFile(".ion");
long processe... | @Test
void shouldFilterGivenValidBooleanExpressionForExclude() throws Exception {
// Given
RunContext runContext = runContextFactory.of();
FilterItems task = FilterItems
.builder()
.from(generateKeyValueFile(TEST_VALID_ITEMS, runContext).toString())
.filt... |
@Override
public String toString() {
if (mUriString != null) {
return mUriString;
}
StringBuilder sb = new StringBuilder();
if (mUri.getScheme() != null) {
sb.append(mUri.getScheme());
sb.append("://");
}
if (hasAuthority()) {
if (mUri.getScheme() == null) {
sb.... | @Test
public void toStringTests() {
String[] uris =
new String[] {"/", "/a", "/a/ b", "alluxio://a/b/c d.txt",
"alluxio://localhost:8080/a/b.txt", "foo", "foo/bar", "/foo/bar#boo", "foo/bar#boo",
"file:///foo/bar"};
for (String uri : uris) {
AlluxioURI turi = new AlluxioU... |
public static int ARC(@NonNull final byte[] data, final int offset, final int length) {
return CRC(0x8005, 0x0000, data, offset, length, true, true, 0x0000);
} | @Test
public void ARC_123456789() {
final byte[] data = "123456789".getBytes();
assertEquals(0xBB3D, CRC16.ARC(data, 0, 9));
} |
@SafeVarargs
public static <T> Set<T> unionDistinct(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
final Set<T> result;
if (isEmpty(coll1)) {
result = new LinkedHashSet<>();
} else {
result = new LinkedHashSet<>(coll1);
}
if (isNotEmpty(coll2)) {
result.addAll(coll2);
}
... | @SuppressWarnings("ConstantValue")
@Test
public void unionDistinctNullTest() {
final List<String> list1 = new ArrayList<>();
final List<String> list2 = null;
final List<String> list3 = null;
final Set<String> set = CollUtil.unionDistinct(list1, list2, list3);
assertNotNull(set);
} |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchMapSomeKeys() {
Map<Object, String> data = new HashMap<>();
data.put(1, "abc");
data.put("wrong", "it's as easy as one two three");
assertThrows(DataException.class,
() -> ConnectSchema.validateValue(MAP_INT_STRING_SCHEMA, data))... |
public FEELFnResult<Boolean> invoke(@ParameterName( "point1" ) Comparable point1, @ParameterName( "point2" ) Comparable point2) {
if ( point1 == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point1", "cannot be null"));
}
if ( point2 == null ) {
... | @Test
void invokeParamSingleAndRange() {
FunctionTestUtil.assertResult( afterFunction.invoke( "a",
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED )),
Boolean.FALSE );
FunctionTestUtil.assertResult( afterFunction.invoke( "f",
... |
public static List<String> filterMatches(@Nullable List<String> candidates,
@Nullable Pattern[] positivePatterns,
@Nullable Pattern[] negativePatterns) {
if (candidates == null || candidates.isEmpty()) {
return Collections.e... | @Test
public void filterMatchesMultiple() {
List<String> candidates = ImmutableList.of("a", "b", "any", "boom", "hello");
List<String> patterns = ImmutableList.of("^a", "!y$");
List<String> expected = ImmutableList.of("a");
assertThat(filterMatches(candidates, new Pattern[]{Pattern.compile("^a")}, new... |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
try {
return new DriveSearchListService(session, fileid, regex.toString()).list(workdir, listener);
}
catch(NotfoundExcepti... | @Test
public void testSearchFolderRecursively() throws Exception {
final String name = new AlphanumericRandomStringService().random();
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path workdir = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHome... |
public static void tryCloseConnections(HazelcastInstance hazelcastInstance) {
if (hazelcastInstance == null) {
return;
}
HazelcastInstanceImpl factory = (HazelcastInstanceImpl) hazelcastInstance;
closeSockets(factory);
} | @Test
public void testTryCloseConnections_shouldDoNothingWithNullInstance() {
tryCloseConnections(null);
} |
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
if (conf != null) {
bytesPerChecksum = conf.getInt(LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_KEY,
LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_DEFAULT);
Preconditions.checkState(byt... | @Test
public void testSetConf() {
Configuration conf = new Configuration();
conf.setInt(LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_KEY, 0);
try {
localFs.setConf(conf);
fail("Should have failed because zero bytes per checksum is invalid");
} catch (IllegalStateException ignored... |
public static boolean isIpV6Endpoint(NetworkEndpoint networkEndpoint) {
return hasIpAddress(networkEndpoint)
&& networkEndpoint.getIpAddress().getAddressFamily().equals(AddressFamily.IPV6);
} | @Test
public void isIpV6Endpoint_withIpV6Endpoint_returnsFalse() {
NetworkEndpoint ipV6Endpoint =
NetworkEndpoint.newBuilder()
.setType(NetworkEndpoint.Type.IP)
.setIpAddress(
IpAddress.newBuilder().setAddress("3ffe::1").setAddressFamily(AddressFamily.IPV6))
... |
@VisibleForTesting
ArtifactFetcher getFetcher(URI uri) {
if ("local".equals(uri.getScheme())) {
return localFetcher;
}
if (isRawHttp(uri.getScheme()) || "https".equals(uri.getScheme())) {
return httpFetcher;
}
return fsFetcher;
} | @Test
void testGetFetcher() throws Exception {
configuration.set(ArtifactFetchOptions.RAW_HTTP_ENABLED, true);
ArtifactFetchManager fetchManager = new ArtifactFetchManager(configuration);
ArtifactFetcher fetcher = fetchManager.getFetcher(new URI("local:///a.jar"));
assertThat(fetche... |
protected VersionedSecretsExtension getVersionedSecretsExtension(String pluginId) {
final String resolvedExtensionVersion = pluginManager.resolveExtensionVersion(pluginId, SECRETS_EXTENSION, goSupportedVersions());
return secretsExtensionMap.get(resolvedExtensionVersion);
} | @Test
void shouldHaveVersionedSecretsExtensionForAllSupportedVersions() {
for (String supportedVersion : SUPPORTED_VERSIONS) {
final String message = String.format("Must define versioned extension class for %s extension with version %s", SECRETS_EXTENSION, supportedVersion);
when(pl... |
public Seckill getSeckill(long seckillId) {
String key = "seckill:" + seckillId;
Seckill seckill = (Seckill) redisTemplate.opsForValue().get(key);
if (seckill != null) {
return seckill;
} else {
seckill = seckillMapper.selectById(seckillId);
if (seckil... | @Test
void getSeckillSuccessCache() {
long seckillId = 1001L;
String key = "seckill:" + seckillId;
ValueOperations valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.get(key)).thenReturn(null);
... |
@Override
public int hashCode()
{
return Objects.hash(value, precision, sessionTimeZoneKey);
} | @Test
public void testEqualsHashcodeMillis()
{
SqlTimestamp t1Millis = new SqlTimestamp(0, MILLISECONDS);
SqlTimestamp t2Millis = new SqlTimestamp(0, MILLISECONDS);
assertEquals(t1Millis, t2Millis);
assertEquals(t1Millis.hashCode(), t2Millis.hashCode());
SqlTimestamp t3... |
@Override
public Set<Entry<K, V>> cachedEntrySet() {
return localCacheView.cachedEntrySet();
} | @Test
public void testExpiration() {
testWithParams(redisson -> {
RLocalCachedMap<String, String> m = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test"));
m.put("12", "32");
assertThat(m.cachedEntrySet()).hasSize(1);
m.expire(Duration.ofSeconds(1));... |
@VisibleForTesting
CompleteMultipartUploadResponse multipartCopy(
S3ResourceId sourcePath, S3ResourceId destinationPath, HeadObjectResponse sourceObjectHead)
throws SdkServiceException {
CreateMultipartUploadRequest initiateUploadRequest =
CreateMultipartUploadRequest.builder()
.bu... | @Test
public void testMultipartCopy() throws IOException {
testMultipartCopy(s3Config("s3"));
testMultipartCopy(s3Config("other"));
testMultipartCopy(s3ConfigWithSSECustomerKey("s3"));
testMultipartCopy(s3ConfigWithSSECustomerKey("other"));
} |
@Override
public boolean complete() {
if (snapshotInProgress) {
return false;
}
while (emitFromTraverser(pendingTraverser)) {
try {
Message t = consumer.receiveNoWait();
if (t == null) {
pendingTraverser = eventTimeM... | @Test
public void when_queue() throws Exception {
String queueName = randomString();
logger.info("using queue: " + queueName);
String message1 = sendMessage(queueName, true);
String message2 = sendMessage(queueName, true);
initializeProcessor(queueName, true, null);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.