focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
try {
return new SchemaAndValue(schema, deserializer.deserialize(topic, value));
} catch (SerializationException e) {
throw new DataException("Failed to deserialize " + typeName + ": ", e);
}
} | @Test
public void testBytesNullToNumber() {
SchemaAndValue data = converter.toConnectData(TOPIC, null);
assertEquals(schema(), data.schema());
assertNull(data.value());
} |
@Override
public void blame(BlameInput input, BlameOutput output) {
File basedir = input.fileSystem().baseDir();
try (Repository repo = JGitUtils.buildRepository(basedir.toPath())) {
File gitBaseDir = repo.getWorkTree();
if (cloneIsInvalid(gitBaseDir)) {
return;
}
Profiler profiler = Profiler.create(LOG);
profiler.startDebug("Collecting committed files");
Map<String, InputFile> inputFileByGitRelativePath = getCommittedFilesToBlame(repo, gitBaseDir, input);
profiler.stopDebug();
BlameAlgorithmEnum blameAlgorithmEnum = this.blameStrategy.getBlameAlgorithm(Runtime.getRuntime().availableProcessors(), inputFileByGitRelativePath.size());
LOG.debug("Using {} strategy to blame files", blameAlgorithmEnum);
if (blameAlgorithmEnum == GIT_FILES_BLAME) {
blameWithFilesGitCommand(output, repo, inputFileByGitRelativePath);
} else {
blameWithNativeGitCommand(output, repo, inputFileByGitRelativePath, gitBaseDir);
}
}
} | @Test
@UseDataProvider("blameAlgorithms")
public void skip_files_not_committed(BlameAlgorithmEnum strategy) throws Exception {
// skip if git not installed
if (strategy == GIT_NATIVE_BLAME) {
assumeTrue(nativeGitBlameCommand.checkIfEnabled());
}
JGitBlameCommand jgit = mock(JGitBlameCommand.class);
BlameCommand blameCmd = new CompositeBlameCommand(analysisWarnings, pathResolver, jgit, nativeGitBlameCommand, (p, f) -> strategy);
File projectDir = createNewTempFolder();
javaUnzip("dummy-git.zip", projectDir);
File baseDir = new File(projectDir, "dummy-git");
setUpBlameInputWithFile(baseDir.toPath());
TestBlameOutput output = new TestBlameOutput();
blameCmd.blame(input, output);
assertThat(output.blame).hasSize(1);
assertThat(output.blame.get(input.filesToBlame().iterator().next())).hasSize(29);
} |
public static String getRootLevelFieldName(String fieldName) {
return fieldName.split("\\.")[0];
} | @Test
public void testGetRootLevelFieldName() {
assertEquals("a", HoodieAvroUtils.getRootLevelFieldName("a.b.c"));
assertEquals("a", HoodieAvroUtils.getRootLevelFieldName("a"));
assertEquals("", HoodieAvroUtils.getRootLevelFieldName(""));
} |
@Override
public List<Namespace> listNamespaces(Namespace namespace) {
SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace);
List<SnowflakeIdentifier> results;
switch (scope.type()) {
case ROOT:
results = snowflakeClient.listDatabases();
break;
case DATABASE:
results = snowflakeClient.listSchemas(scope);
break;
default:
throw new IllegalArgumentException(
String.format(
"listNamespaces must be at either ROOT or DATABASE level; got %s from namespace %s",
scope, namespace));
}
return results.stream().map(NamespaceHelpers::toIcebergNamespace).collect(Collectors.toList());
} | @Test
public void testListNamespaceWithinNonExistentDB() {
// Existence check for nonexistent parent namespaces is optional in the SupportsNamespaces
// interface.
String dbName = "NONEXISTENT_DB";
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> catalog.listNamespaces(Namespace.of(dbName)))
.withMessageContaining("does not exist")
.withMessageContaining(dbName);
} |
public static int readUint16BE(ByteBuffer buf) throws BufferUnderflowException {
return Short.toUnsignedInt(buf.order(ByteOrder.BIG_ENDIAN).getShort());
} | @Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16BEThrowsException3() {
ByteUtils.readUint16BE(new byte[]{1, 2, 3}, -1);
} |
@Override
public ClientPoolHandler addLast(String name, ChannelHandler handler) {
super.addLast(name, handler);
return this;
} | @Test
public void testAddLast() {
ClientPoolHandler handler = new ClientPoolHandler();
Assert.assertTrue(handler.isEmpty());
handler.addLast(test, new TestHandler());
Assert.assertFalse(handler.isEmpty());
} |
public static int nextCapacity(int current) {
assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two.";
if (current < MIN_CAPACITY / 2) {
current = MIN_CAPACITY / 2;
}
current <<= 1;
if (current < 0) {
throw new RuntimeException("Maximum capacity exceeded.");
}
return current;
} | @Test
public void testNextCapacity_withLong() {
long capacity = 16;
long nextCapacity = nextCapacity(capacity);
assertEquals(32, nextCapacity);
} |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperClient sessionZooKeeperClient) {
ApplicationId applicationId = params.getApplicationId();
Preparation preparation = new Preparation(hostValidator, logger, params, activeApplicationVersions,
TenantRepository.getTenantPath(applicationId.tenant()),
serverDbSessionDir, applicationPackage, sessionZooKeeperClient,
onnxModelCost, endpointCertificateSecretStores);
preparation.preprocess();
try {
AllocatedHosts allocatedHosts = preparation.buildModels(now);
preparation.makeResult(allocatedHosts);
if ( ! params.isDryRun()) {
FileReference fileReference = preparation.triggerDistributionOfApplicationPackage();
preparation.writeStateZK(fileReference);
preparation.writeEndpointCertificateMetadataZK();
preparation.writeContainerEndpointsZK();
}
log.log(Level.FINE, () -> "time used " + params.getTimeoutBudget().timesUsed() + " : " + applicationId);
return preparation.result();
}
catch (IllegalArgumentException e) {
if (e instanceof InvalidApplicationException)
throw e;
throw new InvalidApplicationException("Invalid application package", e);
}
} | @Test
public void require_that_cloud_account_is_written() throws Exception {
TestModelFactory modelFactory = new TestModelFactory(version123);
preparer = createPreparer(new ModelFactoryRegistry(List.of(modelFactory)), HostProvisionerProvider.empty());
ApplicationId applicationId = applicationId("test");
CloudAccount expected = CloudAccount.from("012345678912");
PrepareParams params = new PrepareParams.Builder().applicationId(applicationId)
.cloudAccount(expected)
.build();
prepare(new File("src/test/resources/deploy/hosted-app"), params);
SessionZooKeeperClient zkClient = createSessionZooKeeperClient();
assertEquals(expected, zkClient.readCloudAccount().get());
ModelContext modelContext = modelFactory.getModelContext();
Optional<CloudAccount> accountFromModel = modelContext.properties().cloudAccount();
assertEquals(Optional.of(expected), accountFromModel);
} |
@Override
public String encodeKey(String key) {
return key;
} | @Test
public void testEncodeValidKeys() {
assertEquals("foo", strategy.encodeKey("foo"));
assertEquals("foo123bar", strategy.encodeKey("foo123bar"));
assertEquals("CamelFileName", strategy.encodeKey("CamelFileName"));
assertEquals("org.apache.camel.MyBean", strategy.encodeKey("org.apache.camel.MyBean"));
assertEquals("Content-Type", strategy.encodeKey("Content-Type"));
assertEquals("My-Header.You", strategy.encodeKey("My-Header.You"));
} |
public boolean isActive() {
return active;
} | @Test
public void testMvAfterBaseTableRename() throws Exception {
starRocksAssert.withDatabase("test").useDatabase("test")
.withTable("CREATE TABLE test.tbl_to_rename\n" +
"(\n" +
" k1 date,\n" +
" k2 int,\n" +
" v1 int sum\n" +
")\n" +
"PARTITION BY RANGE(k1)\n" +
"(\n" +
" PARTITION p1 values [('2022-02-01'),('2022-02-16')),\n" +
" PARTITION p2 values [('2022-02-16'),('2022-03-01'))\n" +
")\n" +
"DISTRIBUTED BY HASH(k2) BUCKETS 3\n" +
"PROPERTIES('replication_num' = '1');")
.withMaterializedView("create materialized view mv_to_check\n" +
"distributed by hash(k2) buckets 3\n" +
"refresh async\n" +
"as select k2, sum(v1) as total from tbl_to_rename group by k2;");
Database testDb = GlobalStateMgr.getCurrentState().getDb("test");
String alterSql = "alter table tbl_to_rename rename new_tbl_name;";
StatementBase statement = SqlParser.parseSingleStatement(alterSql, connectContext.getSessionVariable().getSqlMode());
StmtExecutor stmtExecutor = new StmtExecutor(connectContext, statement);
stmtExecutor.execute();
MaterializedView mv = ((MaterializedView) testDb.getTable("mv_to_check"));
Assert.assertNotNull(mv);
Assert.assertFalse(mv.isActive());
} |
@Override
public RemotingCommand processRequest(final ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
return this.processRequest(ctx.channel(), request, true);
} | @Test
public void testProcessRequest_NoPermission() throws RemotingCommandException {
this.brokerController.getBrokerConfig().setBrokerPermission(PermName.PERM_WRITE);
RemotingCommand request = createPeekMessageRequest("group","topic",0);
RemotingCommand response = peekMessageProcessor.processRequest(handlerContext, request);
assertThat(response.getCode()).isEqualTo(ResponseCode.NO_PERMISSION);
this.brokerController.getBrokerConfig().setBrokerPermission(PermName.PERM_WRITE | PermName.PERM_READ);
topicConfigManager.getTopicConfigTable().get("topic").setPerm(PermName.PERM_WRITE);
response = peekMessageProcessor.processRequest(handlerContext, request);
assertThat(response.getCode()).isEqualTo(ResponseCode.NO_PERMISSION);
topicConfigManager.getTopicConfigTable().get("topic").setPerm(PermName.PERM_WRITE | PermName.PERM_READ);
when(subscriptionGroupConfig.isConsumeEnable()).thenReturn(false);
response = peekMessageProcessor.processRequest(handlerContext, request);
assertThat(response.getCode()).isEqualTo(ResponseCode.NO_PERMISSION);
} |
@Deprecated
String getPassword(Configuration conf, String alias, String defaultPass) {
String password = defaultPass;
try {
char[] passchars = conf.getPassword(alias);
if (passchars != null) {
password = new String(passchars);
}
} catch (IOException ioe) {
LOG.warn("Exception while trying to get password for alias {}:",
alias, ioe);
}
return password;
} | @Test
public void testConfGetPassword() throws Exception {
File testDir = GenericTestUtils.getTestDir();
Configuration conf = getBaseConf();
final Path jksPath = new Path(testDir.toString(), "test.jks");
final String ourUrl =
JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri();
File file = new File(testDir, "test.jks");
file.delete();
conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, ourUrl);
CredentialProvider provider =
CredentialProviderFactory.getProviders(conf).get(0);
char[] bindpass = {'b', 'i', 'n', 'd', 'p', 'a', 's', 's'};
char[] storepass = {'s', 't', 'o', 'r', 'e', 'p', 'a', 's', 's'};
// ensure that we get nulls when the key isn't there
assertNull(provider.getCredentialEntry(
LdapGroupsMapping.BIND_PASSWORD_KEY));
assertNull(provider.getCredentialEntry(
LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY));
// create new aliases
try {
provider.createCredentialEntry(
LdapGroupsMapping.BIND_PASSWORD_KEY, bindpass);
provider.createCredentialEntry(
LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY, storepass);
provider.flush();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
// make sure we get back the right key
assertArrayEquals(bindpass, provider.getCredentialEntry(
LdapGroupsMapping.BIND_PASSWORD_KEY).getCredential());
assertArrayEquals(storepass, provider.getCredentialEntry(
LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY).getCredential());
LdapGroupsMapping mapping = new LdapGroupsMapping();
Assert.assertEquals("bindpass",
mapping.getPassword(conf, LdapGroupsMapping.BIND_PASSWORD_KEY, ""));
Assert.assertEquals("storepass",
mapping.getPassword(conf, LdapGroupsMapping.LDAP_KEYSTORE_PASSWORD_KEY,
""));
// let's make sure that a password that doesn't exist returns an
// empty string as currently expected and used to trigger a call to
// extract password
Assert.assertEquals("", mapping.getPassword(conf,"invalid-alias", ""));
} |
@Deprecated
public Statement createStatement(String sql)
{
return createStatement(sql, new ParsingOptions());
} | @Test
public void testAllowIdentifierColon()
{
SqlParser sqlParser = new SqlParser(new SqlParserOptions().allowIdentifierSymbol(COLON));
sqlParser.createStatement("select * from foo:bar");
} |
@Override
public String getDataSource() {
return DataSourceConstant.DERBY;
} | @Test
void testGetDataSource() {
String dataSource = historyConfigInfoMapperByDerby.getDataSource();
assertEquals(DataSourceConstant.DERBY, dataSource);
} |
@Override
public String toString() {
return String.format("%s{configMapName='%s'}", getClass().getSimpleName(), configMapName);
} | @Test
void testToStringContainingConfigMap() throws Exception {
new Context() {
{
runTest(
() ->
assertThat(leaderElectionDriver.toString())
.as(
"toString() should contain the ConfigMap name for a human-readable representation of the driver instance.")
.contains(LEADER_CONFIGMAP_NAME));
}
};
} |
@Override
public int getGrace() {
return grace;
} | @Test
public void testDifferingTypesForNumericalParameters() throws Exception {
final AlertCondition alertConditionWithDouble = getDummyAlertCondition(ImmutableMap.of("grace", 3.0));
assertEquals(3, alertConditionWithDouble.getGrace());
final AlertCondition alertConditionWithInteger = getDummyAlertCondition(ImmutableMap.of("grace", 3));
assertEquals(3, alertConditionWithInteger.getGrace());
final AlertCondition alertConditionWithStringDouble = getDummyAlertCondition(ImmutableMap.of("grace", "3.0"));
assertEquals(3, alertConditionWithStringDouble.getGrace());
final AlertCondition alertConditionWithStringInteger = getDummyAlertCondition(ImmutableMap.of("grace", "3"));
assertEquals(3, alertConditionWithStringInteger.getGrace());
} |
public Object clone() {
BlockUntilStepsFinishMeta retval = (BlockUntilStepsFinishMeta) super.clone();
int nrfields = stepName.length;
retval.allocate( nrfields );
System.arraycopy( stepName, 0, retval.stepName, 0, nrfields );
System.arraycopy( stepCopyNr, 0, retval.stepCopyNr, 0, nrfields );
return retval;
} | @Test
public void cloneTest() throws Exception {
BlockUntilStepsFinishMeta meta = new BlockUntilStepsFinishMeta();
meta.allocate( 2 );
meta.setStepName( new String[] { "step1", "step2" } );
meta.setStepCopyNr( new String[] { "copy1", "copy2" } );
BlockUntilStepsFinishMeta aClone = (BlockUntilStepsFinishMeta) meta.clone();
assertFalse( aClone == meta );
assertTrue( Arrays.equals( meta.getStepName(), aClone.getStepName() ) );
assertTrue( Arrays.equals( meta.getStepCopyNr(), aClone.getStepCopyNr() ) );
assertEquals( meta.getXML(), aClone.getXML() );
} |
void put(@Nonnull String name, @Nonnull DataConnectionCatalogEntry dataConnectionCatalogEntry) {
storage().put(wrapDataConnectionKey(name), dataConnectionCatalogEntry);
} | @Test
public void when_put_then_overridesPrevious() {
String name = randomName();
DataConnectionCatalogEntry originalDL = dataConnection(name, "type1", false);
DataConnectionCatalogEntry updatedDL = dataConnection(name, "type2", true);
storage.put(name, originalDL);
storage.put(name, updatedDL);
assertTrue(storage.allObjects().stream().noneMatch(dl -> dl.equals(originalDL)));
assertTrue(storage.allObjects().stream().anyMatch(dl -> dl.equals(updatedDL)));
} |
public static <K, V> Printed<K, V> toFile(final String filePath) {
Objects.requireNonNull(filePath, "filePath can't be null");
if (Utils.isBlank(filePath)) {
throw new TopologyException("filePath can't be an empty string");
}
try {
return new Printed<>(Files.newOutputStream(Paths.get(filePath)));
} catch (final IOException e) {
throw new TopologyException("Unable to write stream to file at [" + filePath + "] " + e.getMessage());
}
} | @Test
public void shouldCreateProcessorThatPrintsToFile() throws IOException {
final File file = TestUtils.tempFile();
final ProcessorSupplier<String, Integer, Void, Void> processorSupplier = new PrintedInternal<>(
Printed.<String, Integer>toFile(file.getPath()))
.build("processor");
final Processor<String, Integer, Void, Void> processor = processorSupplier.get();
processor.process(new Record<>("hi", 1, 0L));
processor.close();
try (final InputStream stream = Files.newInputStream(file.toPath())) {
final byte[] data = new byte[stream.available()];
stream.read(data);
assertThat(new String(data, StandardCharsets.UTF_8.name()), equalTo("[processor]: hi, 1\n"));
}
} |
@Override
@SuppressWarnings("unchecked")
public int run() throws IOException {
Preconditions.checkArgument(targets != null && targets.size() >= 1, "A Parquet file is required.");
Preconditions.checkArgument(targets.size() == 1, "Cannot process multiple Parquet files.");
String source = targets.get(0);
try (ParquetFileReader reader = ParquetFileReader.open(getConf(), qualifiedPath(source))) {
MessageType schema = reader.getFileMetaData().getSchema();
ColumnDescriptor descriptor = Util.descriptor(column, schema);
PrimitiveType type = Util.primitive(column, schema);
Preconditions.checkNotNull(type);
DictionaryPageReadStore dictionaryReader;
int rowGroup = 0;
while ((dictionaryReader = reader.getNextDictionaryReader()) != null) {
DictionaryPage page = dictionaryReader.readDictionaryPage(descriptor);
if (page != null) {
console.info("\nRow group {} dictionary for \"{}\":", rowGroup, column);
Dictionary dict = page.getEncoding().initDictionary(descriptor, page);
printDictionary(dict, type);
} else {
console.info("\nRow group {} has no dictionary for \"{}\"", rowGroup, column);
}
reader.skipNextRowGroup();
rowGroup += 1;
}
}
console.info("");
return 0;
} | @Test
public void testShowDirectoryCommandForFixedLengthByteArray() throws IOException {
File file = parquetFile();
ShowDictionaryCommand command = new ShowDictionaryCommand(createLogger());
command.targets = Arrays.asList(file.getAbsolutePath());
command.column = FIXED_LEN_BYTE_ARRAY_FIELD;
command.setConf(new Configuration());
Assert.assertEquals(0, command.run());
} |
@Override
public String generate(TokenType tokenType) {
String rawToken = generateRawToken();
return buildIdentifiablePartOfToken(tokenType) + rawToken;
} | @Test
public void generated_userToken_should_have_squ_prefix() {
String token = underTest.generate(TokenType.USER_TOKEN);
assertThat(token).matches("squ_.{40}");
} |
public <T> List<T> getList(String path) {
return get(path);
} | @Test public void
automatically_escapes_json_attributes_whose_name_equals_properties() {
// Given
String json = "{\n" +
" \"features\":[\n" +
" {\n" +
" \"type\":\"Feature\",\n" +
" \"geometry\":{\n" +
" \"type\":\"GeometryCollection\",\n" +
" \"geometries\":[\n" +
" {\n" +
" \"type\":\"Point\",\n" +
" \"coordinates\":[\n" +
" 19.883992823270653,\n" +
" 50.02026203045478\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"properties\":{\n" +
" \"gridId\":6\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\":\"Feature\",\n" +
" \"geometry\":{\n" +
" \"type\":\"GeometryCollection\",\n" +
" \"geometries\":[\n" +
" {\n" +
" \"type\":\"Point\",\n" +
" \"coordinates\":[\n" +
" 19.901266347582094,\n" +
" 50.07074684071764\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"properties\":{\n" +
" \"gridId\":7\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
// When
JsonPath jsonPath = new JsonPath(json);
// Then
assertThat(jsonPath.getList("features.properties.gridId", Integer.class), hasItems(7));
} |
public List<T> query(double lat, double lon) {
Envelope searchEnv = new Envelope(lon, lon, lat, lat);
@SuppressWarnings("unchecked")
List<IndexedCustomArea<T>> result = index.query(searchEnv);
Point point = gf.createPoint(new Coordinate(lon, lat));
return result.stream()
.filter(c -> c.intersects(point))
.map(c -> c.area)
.collect(Collectors.toList());
} | @Test
public void testCountries() {
AreaIndex<CustomArea> countryIndex = createCountryIndex();
assertEquals("DE", countryIndex.query(52.52437, 13.41053).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("FR", countryIndex.query(48.86471, 2.349014).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("US-NM", countryIndex.query(35.67514, -105.94665).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("AT", countryIndex.query(48.20448, 16.10788).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("GB", countryIndex.query(51.6730876, 0.0041691).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("BE", countryIndex.query(50.846931, 4.332262).get(0).getProperties().get(State.ISO_3166_2));
assertEquals("NL", countryIndex.query(52.208451, 5.500524).get(0).getProperties().get(State.ISO_3166_2));
} |
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) {
return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration)
< Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration);
} | @Test
void findCloserToShouldReturnNUmber2IfItCloserToGoalThanNumber1() {
// given
int number1 = 1002;
int number2 = 999;
// when
boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2);
// then
assertThat(actual).isFalse();
} |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{
PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name()));
if (userSession.hasSession() && userSession.isLoggedIn()
&& userSession.isSystemAdministrator() && riskConsent == REQUIRED) {
redirectTo(response, request.getContextPath() + PLUGINS_RISK_CONSENT_PATH);
}
chain.doFilter(request, response);
} | @Test
public void doFilter_givenNotLoggedIn_dontRedirect() throws Exception {
PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession);
when(userSession.hasSession()).thenReturn(true);
when(userSession.isLoggedIn()).thenReturn(false);
consentFilter.doFilter(request, response, chain);
verify(response, times(0)).sendRedirect(Mockito.anyString());
} |
public void copyOnlyForQuery(OlapTable olapTable) {
olapTable.id = this.id;
olapTable.name = this.name;
olapTable.type = this.type;
olapTable.fullSchema = Lists.newArrayList(this.fullSchema);
olapTable.nameToColumn = new CaseInsensitiveMap(this.nameToColumn);
olapTable.idToColumn = new CaseInsensitiveMap(this.idToColumn);
olapTable.state = this.state;
olapTable.indexNameToId = Maps.newHashMap(this.indexNameToId);
olapTable.indexIdToMeta = Maps.newHashMap(this.indexIdToMeta);
olapTable.indexes = indexes == null ? null : indexes.shallowCopy();
if (bfColumns != null) {
olapTable.bfColumns = Sets.newTreeSet(ColumnId.CASE_INSENSITIVE_ORDER);
olapTable.bfColumns.addAll(bfColumns);
} else {
olapTable.bfColumns = null;
}
olapTable.keysType = this.keysType;
if (this.relatedMaterializedViews != null) {
olapTable.relatedMaterializedViews = Sets.newHashSet(this.relatedMaterializedViews);
}
if (this.uniqueConstraints != null) {
olapTable.uniqueConstraints = Lists.newArrayList(this.uniqueConstraints);
}
if (this.foreignKeyConstraints != null) {
olapTable.foreignKeyConstraints = Lists.newArrayList(this.foreignKeyConstraints);
}
if (this.partitionInfo != null) {
olapTable.partitionInfo = (PartitionInfo) this.partitionInfo.clone();
}
if (this.defaultDistributionInfo != null) {
olapTable.defaultDistributionInfo = this.defaultDistributionInfo.copy();
}
Map<Long, Partition> idToPartitions = new HashMap<>(this.idToPartition.size());
Map<String, Partition> nameToPartitions = Maps.newLinkedHashMap();
for (Map.Entry<Long, Partition> kv : this.idToPartition.entrySet()) {
Partition copiedPartition = kv.getValue().shallowCopy();
idToPartitions.put(kv.getKey(), copiedPartition);
nameToPartitions.put(kv.getValue().getName(), copiedPartition);
}
olapTable.idToPartition = idToPartitions;
olapTable.nameToPartition = nameToPartitions;
olapTable.physicalPartitionIdToPartitionId = this.physicalPartitionIdToPartitionId;
olapTable.physicalPartitionNameToPartitionId = this.physicalPartitionNameToPartitionId;
olapTable.tempPartitions = new TempPartitions();
for (Partition tempPartition : this.getTempPartitions()) {
olapTable.tempPartitions.addPartition(tempPartition.shallowCopy());
}
olapTable.baseIndexId = this.baseIndexId;
if (this.tableProperty != null) {
olapTable.tableProperty = this.tableProperty.copy();
}
// Shallow copy shared data to check whether the copied table has changed or not.
olapTable.lastSchemaUpdateTime = this.lastSchemaUpdateTime;
olapTable.sessionId = this.sessionId;
if (this.bfColumns != null) {
olapTable.bfColumns = Sets.newHashSet(this.bfColumns);
}
olapTable.bfFpp = this.bfFpp;
if (this.curBinlogConfig != null) {
olapTable.curBinlogConfig = new BinlogConfig(this.curBinlogConfig);
}
} | @Test
public void testCopyOnlyForQuery() {
OlapTable olapTable = new OlapTable();
olapTable.setHasDelete();
OlapTable copied = new OlapTable();
olapTable.copyOnlyForQuery(copied);
Assert.assertEquals(olapTable.hasDelete(), copied.hasDelete());
Assert.assertEquals(olapTable.hasForbiddenGlobalDict(), copied.hasForbiddenGlobalDict());
Assert.assertEquals(olapTable, copied);
} |
public String decode(byte[] val) {
return codecs[0].decode(val, 0, val.length);
} | @Test
public void testDecodeGermanPersonName() {
assertEquals(GERMAN_PERSON_NAME,
iso8859_1().decode(GERMAN_PERSON_NAME_BYTE));
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
new SwiftAttributesFinderFeature(session).find(file, listener);
return true;
}
catch(NotfoundException e) {
return false;
}
} | @Test
public void testFindRoot() throws Exception {
assertTrue(new SwiftFindFeature(session).find(new Path("/", EnumSet.of(Path.Type.directory))));
} |
public static boolean isFolderEmpty(File folder) {
if (folder == null) {
return true;
}
File[] files = folder.listFiles();
return files == null || files.length == 0;
} | @Test
void FolderIsNotEmptyWhenItHasContents() throws Exception {
new File(folder, "subfolder").createNewFile();
assertThat(FileUtil.isFolderEmpty(folder)).isFalse();
} |
@Override
public SQLParserRuleConfiguration build() {
return new SQLParserRuleConfiguration(PARSE_TREE_CACHE_OPTION, SQL_STATEMENT_CACHE_OPTION);
} | @Test
void assertBuild() {
SQLParserRuleConfiguration actual = new DefaultSQLParserRuleConfigurationBuilder().build();
assertThat(actual.getParseTreeCache().getInitialCapacity(), is(128));
assertThat(actual.getParseTreeCache().getMaximumSize(), is(1024L));
assertThat(actual.getSqlStatementCache().getInitialCapacity(), is(2000));
assertThat(actual.getSqlStatementCache().getMaximumSize(), is(65535L));
} |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
final CompletedFetch nextInLineFetch = fetchBuffer.nextInLineFetch();
if (nextInLineFetch == null || nextInLineFetch.isConsumed()) {
final CompletedFetch completedFetch = fetchBuffer.peek();
if (completedFetch == null)
break;
if (!completedFetch.isInitialized()) {
try {
fetchBuffer.setNextInLineFetch(initialize(completedFetch));
} catch (Exception e) {
// Remove a completedFetch upon a parse with exception if (1) it contains no completedFetch, and
// (2) there are no fetched completedFetch with actual content preceding this exception.
// The first condition ensures that the completedFetches is not stuck with the same completedFetch
// in cases such as the TopicAuthorizationException, and the second condition ensures that no
// potential data loss due to an exception in a following record.
if (fetch.isEmpty() && FetchResponse.recordsOrFail(completedFetch.partitionData).sizeInBytes() == 0)
fetchBuffer.poll();
throw e;
}
} else {
fetchBuffer.setNextInLineFetch(completedFetch);
}
fetchBuffer.poll();
} else if (subscriptions.isPaused(nextInLineFetch.partition)) {
// when the partition is paused we add the records back to the completedFetches queue instead of draining
// them so that they can be returned on a subsequent poll if the partition is resumed at that time
log.debug("Skipping fetching records for assigned partition {} because it is paused", nextInLineFetch.partition);
pausedCompletedFetches.add(nextInLineFetch);
fetchBuffer.setNextInLineFetch(null);
} else {
final Fetch<K, V> nextFetch = fetchRecords(nextInLineFetch, recordsRemaining);
recordsRemaining -= nextFetch.numRecords();
fetch.add(nextFetch);
}
}
} catch (KafkaException e) {
if (fetch.isEmpty())
throw e;
} finally {
// add any polled completed fetches for paused partitions back to the completed fetches queue to be
// re-evaluated in the next poll
fetchBuffer.addAll(pausedCompletedFetches);
}
return fetch;
} | @Test
public void testCollectFetchInitializationWithUpdateLastStableOffsetOnNotAssignedPartition() {
final TopicPartition topicPartition0 = new TopicPartition("topic", 0);
final long fetchOffset = 42;
final long highWatermark = 1000;
final long logStartOffset = 10;
final long lastStableOffset = 900;
final SubscriptionState subscriptions = mock(SubscriptionState.class);
when(subscriptions.hasValidPosition(topicPartition0)).thenReturn(true);
when(subscriptions.positionOrNull(topicPartition0)).thenReturn(new SubscriptionState.FetchPosition(fetchOffset));
when(subscriptions.tryUpdatingHighWatermark(topicPartition0, highWatermark)).thenReturn(true);
when(subscriptions.tryUpdatingLogStartOffset(topicPartition0, logStartOffset)).thenReturn(true);
when(subscriptions.tryUpdatingLastStableOffset(topicPartition0, lastStableOffset)).thenReturn(false);
final FetchCollector<String, String> fetchCollector = createFetchCollector(subscriptions);
final Records records = createRecords();
FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData()
.setPartitionIndex(topicPartition0.partition())
.setHighWatermark(highWatermark)
.setRecords(records)
.setLogStartOffset(logStartOffset)
.setLastStableOffset(lastStableOffset);
final CompletedFetch completedFetch = new CompletedFetchBuilder()
.partitionData(partitionData)
.partition(topicPartition0)
.fetchOffset(fetchOffset).build();
final FetchBuffer fetchBuffer = mock(FetchBuffer.class);
when(fetchBuffer.nextInLineFetch()).thenReturn(null);
when(fetchBuffer.peek()).thenReturn(completedFetch).thenReturn(null);
final Fetch<String, String> fetch = fetchCollector.collectFetch(fetchBuffer);
assertTrue(fetch.isEmpty());
verify(fetchBuffer).setNextInLineFetch(null);
} |
public static String fromPersistenceNamingEncoding(String mlName) {
// The managedLedgerName convention is: tenant/namespace/domain/topic
// We want to transform to topic full name in the order: domain://tenant/namespace/topic
if (mlName == null || mlName.length() == 0) {
return mlName;
}
List<String> parts = Splitter.on("/").splitToList(mlName);
String tenant;
String cluster;
String namespacePortion;
String domain;
String localName;
if (parts.size() == 4) {
tenant = parts.get(0);
namespacePortion = parts.get(1);
domain = parts.get(2);
localName = Codec.decode(parts.get(3));
return String.format("%s://%s/%s/%s", domain, tenant, namespacePortion, localName);
} else if (parts.size() == 5) {
tenant = parts.get(0);
cluster = parts.get(1);
namespacePortion = parts.get(2);
domain = parts.get(3);
localName = Codec.decode(parts.get(4));
return String.format("%s://%s/%s/%s/%s", domain, tenant, cluster, namespacePortion, localName);
} else {
throw new IllegalArgumentException("Invalid managedLedger name: " + mlName);
}
} | @Test
public void testFromPersistenceNamingEncoding() {
// case1: V2
String mlName1 = "public_tenant/default_namespace/persistent/test_topic";
String expectedTopicName1 = "persistent://public_tenant/default_namespace/test_topic";
TopicName name1 = TopicName.get(expectedTopicName1);
assertEquals(name1.getPersistenceNamingEncoding(), mlName1);
assertEquals(TopicName.fromPersistenceNamingEncoding(mlName1), expectedTopicName1);
// case2: V1
String mlName2 = "public_tenant/my_cluster/default_namespace/persistent/test_topic";
String expectedTopicName2 = "persistent://public_tenant/my_cluster/default_namespace/test_topic";
TopicName name2 = TopicName.get(expectedTopicName2);
assertEquals(name2.getPersistenceNamingEncoding(), mlName2);
assertEquals(TopicName.fromPersistenceNamingEncoding(mlName2), expectedTopicName2);
// case3: null
String mlName3 = "";
String expectedTopicName3 = "";
assertEquals(expectedTopicName3, TopicName.fromPersistenceNamingEncoding(mlName3));
// case4: Invalid name
try {
String mlName4 = "public_tenant/my_cluster/default_namespace/persistent/test_topic/sub_topic";
TopicName.fromPersistenceNamingEncoding(mlName4);
fail("Should have raised exception");
} catch (IllegalArgumentException e) {
// Exception is expected.
}
// case5: local name with special characters e.g. a:b:c
String topicName = "persistent://tenant/namespace/a:b:c";
String persistentNamingEncoding = "tenant/namespace/persistent/a%3Ab%3Ac";
assertEquals(TopicName.get(topicName).getPersistenceNamingEncoding(), persistentNamingEncoding);
assertEquals(TopicName.fromPersistenceNamingEncoding(persistentNamingEncoding), topicName);
} |
@Override
public String doLayout(ILoggingEvent event) {
StringWriter output = new StringWriter();
try (JsonWriter json = new JsonWriter(output)) {
json.beginObject();
if (!"".equals(nodeName)) {
json.name("nodename").value(nodeName);
}
json.name("process").value(processKey);
for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) {
if (entry.getValue() != null && !exclusions.contains(entry.getKey())) {
json.name(entry.getKey()).value(entry.getValue());
}
}
json
.name("timestamp").value(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp())))
.name("severity").value(event.getLevel().toString())
.name("logger").value(event.getLoggerName())
.name("message").value(NEWLINE_REGEXP.matcher(event.getFormattedMessage()).replaceAll("\r"));
IThrowableProxy tp = event.getThrowableProxy();
if (tp != null) {
json.name("stacktrace").beginArray();
int nbOfTabs = 0;
while (tp != null) {
printFirstLine(json, tp, nbOfTabs);
render(json, tp, nbOfTabs);
tp = tp.getCause();
nbOfTabs++;
}
json.endArray();
}
json.endObject();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("BUG - fail to create JSON", e);
}
output.write(System.lineSeparator());
return output.toString();
} | @Test
public void doLayout_whenMDC_shouldNotContainExcludedFields() {
try {
LogbackJsonLayout logbackJsonLayout = new LogbackJsonLayout("web", "", List.of("fromMdc"));
LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]);
MDC.put("fromMdc", "foo");
String log = logbackJsonLayout.doLayout(event);
JsonLog json = new Gson().fromJson(log, JsonLog.class);
assertThat(json.fromMdc).isNull();
} finally {
MDC.clear();
}
} |
public static Set<String> findKeywordsFromCrashReport(String crashReport) {
Matcher matcher = CRASH_REPORT_STACK_TRACE_PATTERN.matcher(crashReport);
Set<String> result = new HashSet<>();
if (matcher.find()) {
for (String line : matcher.group("stacktrace").split("\\n")) {
Matcher lineMatcher = STACK_TRACE_LINE_PATTERN.matcher(line);
if (lineMatcher.find()) {
String[] method = lineMatcher.group("method").split("\\.");
for (int i = 0; i < method.length - 2; i++) {
if (PACKAGE_KEYWORD_BLACK_LIST.contains(method[i])) {
continue;
}
result.add(method[i]);
}
Matcher moduleMatcher = STACK_TRACE_LINE_MODULE_PATTERN.matcher(line);
if (moduleMatcher.find()) {
for (String module : moduleMatcher.group("tokens").split(",")) {
String[] split = module.split(":");
if (split.length >= 2 && "xf".equals(split[0])) {
if (PACKAGE_KEYWORD_BLACK_LIST.contains(split[1])) {
continue;
}
result.add(split[1]);
}
}
}
}
}
}
return result;
} | @Test
public void bettersprinting() throws IOException {
assertEquals(
new HashSet<>(Arrays.asList("chylex", "bettersprinting")),
CrashReportAnalyzer.findKeywordsFromCrashReport(loadLog("/crash-report/mod/bettersprinting.txt")));
} |
public static Result parse(@NonNull String body, int mode) throws Exception {
Result result = new Result();
Document d;
try{
d = Jsoup.parse(body);
}catch (Exception ignored){
return result;
}
try {
Element ptt = d.getElementsByClass("ptt").first();
if (ptt == null) {
Element searchNav = d.getElementsByClass("searchnav").first();
result.pages = -1;
result.nextPage = -1;
assert searchNav != null;
Element element = searchNav.getElementById("uFirst");
if (element!=null){
result.firstHref = element.attr("href");
}else {
result.firstHref = "";
}
element = searchNav.getElementById("uprev");
if (element!=null){
result.prevHref = element.attr("href");
}else {
result.prevHref = "";
}
element = searchNav.getElementById("unext");
if (element!=null){
result.nextHref = element.attr("href");
}else {
result.nextHref = "";
}
element = searchNav.getElementById("ulast");
if (element!=null){
result.lastHref = element.attr("href");
}else {
result.lastHref = "";
}
element = d.getElementsByClass("searchtext").first();
if (element!=null){
String text = element.text();
Matcher matcher = PATTERN_RESULT_COUNT_PAGE.matcher(text);
if (matcher.find()){
String findString = matcher.group();
String[] resultArr = findString.split(" ");
if (resultArr.length>3){
switch (resultArr[1]){
case "thousands":
result.resultCount = "1,000+";
break;
case "about":
result.resultCount = resultArr[2]+"+";
break;
default:
StringBuilder buffer = new StringBuilder();
for (int i=1;i<resultArr.length-1;i++){
buffer.append(resultArr[i]);
}
result.resultCount = buffer.toString();
break;
}
}else if(resultArr.length == 3){
result.resultCount = resultArr[1];
}else{
result.resultCount = "";
}
}
}else {
result.resultCount = "";
}
} else {
Elements es = ptt.child(0).child(0).children();
result.pages = Integer.parseInt(es.get(es.size() - 2).text().trim());
Element e = es.get(es.size() - 1);
if (e != null) {
e = e.children().first();
if (e != null) {
String href = e.attr("href");
Matcher matcher = PATTERN_NEXT_PAGE.matcher(href);
if (matcher.find()) {
result.nextPage = NumberUtils.parseIntSafely(matcher.group(1), 0);
}
}
}
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
result.noWatchedTags = body.contains("<p>You do not have any watched tags");
if (body.contains("No hits found</p>")) {
result.pages = 0;
//noinspection unchecked
result.galleryInfoList = Collections.EMPTY_LIST;
return result;
} else if (d.getElementsByClass("ptt").isEmpty()) {
result.pages = 1;
} else {
result.pages = Integer.MAX_VALUE;
}
}
try {
Element itg = d.getElementsByClass("itg").first();
Elements es;
assert itg != null;
if ("table".equalsIgnoreCase(itg.tagName())) {
es = itg.child(0).children();
} else {
es = itg.children();
}
List<GalleryInfo> list = new ArrayList<>(es.size());
// First one is table header, skip it
for (int i = 0; i < es.size(); i++) {
GalleryInfo gi = parseGalleryInfo(es.get(i));
if (null != gi) {
list.add(gi);
}
}
if (list.isEmpty()) {
try {
String pageMessage = d.getElementsByClass("itg gltc").get(0).child(0).child(1).child(0).text();
if (pageMessage.isEmpty()) {
throw new ParseException("No gallery", body);
}
} catch (IndexOutOfBoundsException e) {
throw new ParseException("No gallery", body);
}
// throw new ParseException("No gallery", body);
}
result.galleryInfoList = list;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse gallery list", body);
}
new GalleryListTagsSyncTask(result.galleryInfoList).execute();
return result;
} | @Test
public void testParse() throws Exception {
InputStream resource = GalleryPageApiParserTest.class.getResourceAsStream(file);
BufferedSource source = Okio.buffer(Okio.source(resource));
String body = source.readUtf8();
GalleryListParser.Result result = GalleryListParser.parse(body, MODE_NORMAL);
assertEquals(25, result.galleryInfoList.size());
result.galleryInfoList.forEach(gi -> {
// assertNotEquals(0, gi.gid);
// assertNotEquals(0, gi.token);
assertNotNull(gi.title);
//assertNotNull(gi.simpleTags);
// assertNotEquals(0, gi.category);
// assertNotEquals(EhUtils.UNKNOWN, gi.category);
// assertNotEquals(0, gi.thumbWidth);
// assertNotEquals(0, gi.thumbHeight);
assertNotNull(gi.thumb);
assertNotNull(gi.posted);
// assertNotEquals(0.0, gi.rating);
if (E_MINIMAL.equals(file) ||
E_MINIMAL_PLUS.equals(file) ||
E_COMPAT.equals(file) ||
E_EXTENDED.equals(file) ||
EX_MINIMAL.equals(file) ||
EX_MINIMAL_PLUS.equals(file) ||
EX_COMPAT.equals(file) ||
EX_EXTENDED.equals(file)) {
assertNotNull(gi.uploader);
} else {
assertNull(gi.uploader);
}
// assertNotEquals(0, gi.pages);
});
} |
@Override
public boolean apply(InputFile inputFile) {
return originalPredicate.apply(inputFile) && InputFile.Status.SAME != inputFile.status();
} | @Test
public void predicate_is_evaluated_before_file_status() {
when(predicate.apply(inputFile)).thenReturn(false);
Assertions.assertThat(underTest.apply(inputFile)).isFalse();
verify(inputFile, never()).status();
} |
@ScalarOperator(INDETERMINATE)
@SqlType(StandardTypes.BOOLEAN)
public static boolean indeterminate(@SqlType(StandardTypes.SMALLINT) long value, @IsNull boolean isNull)
{
return isNull;
} | @Test
public void testIndeterminate()
throws Exception
{
assertOperator(INDETERMINATE, "cast(null as smallint)", BOOLEAN, true);
assertOperator(INDETERMINATE, "cast(12 as smallint)", BOOLEAN, false);
assertOperator(INDETERMINATE, "cast(0 as smallint)", BOOLEAN, false);
assertOperator(INDETERMINATE, "cast(-23 as smallint)", BOOLEAN, false);
assertOperator(INDETERMINATE, "cast(1.4 as smallint)", BOOLEAN, false);
} |
@Override
public Source getSource(PropertyKey key) {
return mProperties.getSource(key);
} | @Test
public void source() throws Exception {
Properties siteProps = new Properties();
File propsFile = mFolder.newFile(Constants.SITE_PROPERTIES);
siteProps.setProperty(PropertyKey.MASTER_HOSTNAME.toString(), "host-1");
siteProps.setProperty(PropertyKey.MASTER_WEB_PORT.toString(), "1234");
siteProps.store(new FileOutputStream(propsFile), "tmp site properties file");
Map<String, String> sysProps = new HashMap<>();
sysProps.put(PropertyKey.LOGS_DIR.toString(), "/tmp/logs1");
sysProps.put(PropertyKey.MASTER_WEB_PORT.toString(), "4321");
sysProps.put(PropertyKey.SITE_CONF_DIR.toString(), mFolder.getRoot().getAbsolutePath());
sysProps.put(PropertyKey.TEST_MODE.toString(), "false");
try (Closeable p = new SystemPropertyRule(sysProps).toResource()) {
resetConf();
// set only in site prop
assertEquals(Source.Type.SITE_PROPERTY,
mConfiguration.getSource(PropertyKey.MASTER_HOSTNAME).getType());
// set both in site and system prop
assertEquals(Source.SYSTEM_PROPERTY,
mConfiguration.getSource(PropertyKey.MASTER_WEB_PORT));
// set only in system prop
assertEquals(Source.SYSTEM_PROPERTY,
mConfiguration.getSource(PropertyKey.LOGS_DIR));
// set neither in system prop
assertEquals(Source.DEFAULT,
mConfiguration.getSource(PropertyKey.MASTER_RPC_PORT));
}
} |
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sideInputIndex", sideInputIndex)
.add("declaringStep", declaringOperationContext.nameContext())
.toString();
} | @Test
public void testToStringReturnsWellFormedDescriptionString() {
DataflowExecutionContext mockedExecutionContext = mock(DataflowExecutionContext.class);
DataflowOperationContext mockedOperationContext = mock(DataflowOperationContext.class);
final int siIndexId = 3;
ExecutionStateTracker mockedExecutionStateTracker = mock(ExecutionStateTracker.class);
when(mockedExecutionContext.getExecutionStateTracker()).thenReturn(mockedExecutionStateTracker);
Thread mockedThreadObject = mock(Thread.class);
when(mockedExecutionStateTracker.getTrackedThread()).thenReturn(mockedThreadObject);
DataflowSideInputReadCounter testObject =
new DataflowSideInputReadCounter(mockedExecutionContext, mockedOperationContext, siIndexId);
assertThat(
testObject.toString(),
equalTo("DataflowSideInputReadCounter{sideInputIndex=3, declaringStep=null}"));
} |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
return results;
} | @Test
public void optifineIsNotCompatibleWithForge4() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/optifine_is_not_compatible_with_forge5.txt")),
CrashReportAnalyzer.Rule.OPTIFINE_IS_NOT_COMPATIBLE_WITH_FORGE);
} |
public static Object convertValue(final Object value, final Class<?> convertType) throws SQLFeatureNotSupportedException {
ShardingSpherePreconditions.checkNotNull(convertType, () -> new SQLFeatureNotSupportedException("Type can not be null"));
if (null == value) {
return convertNullValue(convertType);
}
if (value.getClass() == convertType) {
return value;
}
if (value instanceof LocalDateTime) {
return convertLocalDateTimeValue((LocalDateTime) value, convertType);
}
if (value instanceof Timestamp) {
return convertTimestampValue((Timestamp) value, convertType);
}
if (URL.class.equals(convertType)) {
return convertURL(value);
}
if (value instanceof Number) {
return convertNumberValue(value, convertType);
}
if (value instanceof Date) {
return convertDateValue((Date) value, convertType);
}
if (value instanceof byte[]) {
return convertByteArrayValue((byte[]) value, convertType);
}
if (boolean.class.equals(convertType)) {
return convertBooleanValue(value);
}
if (String.class.equals(convertType)) {
return value.toString();
}
try {
return convertType.cast(value);
} catch (final ClassCastException ignored) {
throw new SQLFeatureNotSupportedException("getObject with type");
}
} | @Test
void assertConvertByteArrayValueSuccess() throws SQLException {
byte[] bytesValue = {};
assertThat(ResultSetUtils.convertValue(bytesValue, byte.class), is(bytesValue));
assertThat(ResultSetUtils.convertValue(new byte[]{(byte) 1}, byte.class), is((byte) 1));
assertThat(ResultSetUtils.convertValue(Shorts.toByteArray((short) 1), short.class), is((short) 1));
assertThat(ResultSetUtils.convertValue(Ints.toByteArray(1), int.class), is(1));
assertThat(ResultSetUtils.convertValue(Longs.toByteArray(1L), long.class), is(1L));
assertThat(ResultSetUtils.convertValue(Longs.toByteArray(1L), double.class), is(1.0D));
assertThat(ResultSetUtils.convertValue(Longs.toByteArray(1L), float.class), is(1.0F));
assertThat(ResultSetUtils.convertValue(Longs.toByteArray(1L), BigDecimal.class), is(new BigDecimal("1")));
} |
@Override
public ExportedConfig pipelineExport(final String pluginId, final CRPipeline pipeline) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_PIPELINE_EXPORT, new DefaultPluginInteractionCallback<>() {
@Override
public String requestBody(String resolvedExtensionVersion) {
return messageHandlerMap.get(resolvedExtensionVersion).requestMessageForPipelineExport(pipeline);
}
@Override
public ExportedConfig onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) {
return messageHandlerMap.get(resolvedExtensionVersion).responseMessageForPipelineExport(responseBody, responseHeaders);
}
});
} | @Test
public void shouldTalkToPluginToGetPipelineExport() {
CRPipeline pipeline = new CRPipeline();
String serialized = new GsonCodec().getGson().toJson(pipeline);
when(jsonMessageHandler2.responseMessageForPipelineExport(responseBody, responseHeaders)).thenReturn(ExportedConfig.from(serialized, responseHeaders));
when(pluginManager.resolveExtensionVersion(PLUGIN_ID, CONFIG_REPO_EXTENSION, new ArrayList<>(List.of("1.0", "2.0", "3.0")))).thenReturn("2.0");
ExportedConfig response = extension.pipelineExport(PLUGIN_ID, pipeline);
assertRequest(requestArgumentCaptor.getValue(), CONFIG_REPO_EXTENSION, "2.0", ConfigRepoExtension.REQUEST_PIPELINE_EXPORT, null);
verify(jsonMessageHandler2).responseMessageForPipelineExport(responseBody, responseHeaders);
assertSame(response.getContent(), serialized);
} |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(
Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS)))
.visit(treeRootHolder.getRoot());
} | @Test
public void zero_measures_when_nothing_has_changed() {
treeRootHolder.setRoot(FILE_COMPONENT);
when(newLinesRepository.newLinesAvailable()).thenReturn(true);
when(newLinesRepository.getNewLines(FILE_COMPONENT)).thenReturn(Optional.of(Collections.emptySet()));
reportReader.putCoverage(FILE_COMPONENT.getReportAttributes().getRef(),
asList(
ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(true).setConditions(1).setCoveredConditions(1).build(),
ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build()));
underTest.execute(new TestComputationStepContext());
verify_only_zero_measures_on_new_lines_and_conditions_measures(FILE_COMPONENT);
} |
public boolean similarTo(ClusterStateBundle other) {
if (!baselineState.getClusterState().similarToIgnoringInitProgress(other.baselineState.getClusterState())) {
return false;
}
if (clusterFeedIsBlocked() != other.clusterFeedIsBlocked()) {
return false;
}
if (clusterFeedIsBlocked() && !feedBlock.similarTo(other.feedBlock)) {
return false;
}
// Distribution configs must match exactly for bundles to be similar.
// It may be the case that they are both null, in which case they are also considered equal.
if (!Objects.equals(distributionConfig, other.distributionConfig)) {
return false;
}
// FIXME we currently treat mismatching bucket space sets as unchanged to avoid breaking some tests
return derivedBucketSpaceStates.entrySet().stream()
.allMatch(entry -> other.derivedBucketSpaceStates.getOrDefault(entry.getKey(), entry.getValue())
.getClusterState().similarToIgnoringInitProgress(entry.getValue().getClusterState()));
} | @Test
void same_bundle_instance_considered_similar() {
ClusterStateBundle bundle = createTestBundle();
assertTrue(bundle.similarTo(bundle));
} |
@Override
public String toString() {
return SelParserTreeConstants.jjtNodeName[id] + (value == null ? "" : ": " + value);
} | @Test
public void testToString() {
assertEquals("Execute", root.toString());
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testPartialFetchWithPausedPartitions() {
// this test sends creates a completed fetch with 3 records and a max poll of 2 records to assert
// that a fetch that must be returned over at least 2 polls can be cached successfully when its partition is
// paused, then returned successfully after it has been resumed again later
buildFetcher(2);
Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> fetchedRecords;
assignFromUser(mkSet(tp0, tp1));
subscriptions.seek(tp0, 1);
assertEquals(1, sendFetches());
client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0));
networkClientDelegate.poll(time.timer(0));
fetchedRecords = fetchRecords();
assertEquals(2, fetchedRecords.get(tp0).size(), "Should return 2 records from fetch with 3 records");
assertFalse(fetcher.hasCompletedFetches(), "Should have no completed fetches");
subscriptions.pause(tp0);
networkClientDelegate.poll(time.timer(0));
assertEmptyFetch("Should not return records or advance position for paused partitions");
assertTrue(fetcher.hasCompletedFetches(), "Should have 1 entry in completed fetches");
assertFalse(fetcher.hasAvailableFetches(), "Should not have any available (non-paused) completed fetches");
subscriptions.resume(tp0);
networkClientDelegate.poll(time.timer(0));
fetchedRecords = fetchRecords();
assertEquals(1, fetchedRecords.get(tp0).size(), "Should return last remaining record");
assertFalse(fetcher.hasCompletedFetches(), "Should have no completed fetches");
} |
public DoubleValue increment(double increment) {
this.value += increment;
this.set = true;
return this;
} | @Test
public void increment_DoubleVariationValue_increments_by_the_value_of_the_arg() {
DoubleValue source = new DoubleValue().increment(10);
DoubleValue target = new DoubleValue().increment(source);
verifySetVariationValue(target, 10);
} |
@Override
public void write(int b) throws IOException {
throwIfClosed();
inputBuffer[inputPosition++] = (byte) b;
flushIfFull();
} | @Test
void compressed_size_is_less_than_uncompressed() throws IOException {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++) {
builder.append("The quick brown fox jumps over the lazy dog").append('\n');
}
byte[] inputData = builder.toString().getBytes();
ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
try (ZstdOutputStream zstdOut = new ZstdOutputStream(arrayOut)) {
zstdOut.write(inputData);
}
int compressedSize = arrayOut.toByteArray().length;
assertTrue(
compressedSize < inputData.length,
() -> "Compressed size is " + compressedSize + " while uncompressed size is " + inputData.length);
} |
@Override
public void replyComment(ProductCommentReplyReqVO replyVO, Long userId) {
// 校验评论是否存在
validateCommentExists(replyVO.getId());
// 回复评论
productCommentMapper.updateById(new ProductCommentDO().setId(replyVO.getId())
.setReplyTime(LocalDateTime.now()).setReplyUserId(userId)
.setReplyStatus(Boolean.TRUE).setReplyContent(replyVO.getReplyContent()));
} | @Test
public void testCommentReply_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId();
ProductCommentReplyReqVO replyVO = new ProductCommentReplyReqVO();
replyVO.setId(productCommentId);
replyVO.setReplyContent("测试");
productCommentService.replyComment(replyVO, 1L);
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
assertEquals("测试", productCommentDO.getReplyContent());
} |
public static ShardingTableReferenceRuleConfiguration convertToObject(final String referenceConfig) {
return referenceConfig.contains(":") ? convertYamlConfigurationWithName(referenceConfig) : convertYamlConfigurationWithoutName(referenceConfig);
} | @Test
void assertConvertToObjectForYamlConfigurationWithoutName() {
ShardingTableReferenceRuleConfiguration actual = YamlShardingTableReferenceRuleConfigurationConverter.convertToObject("LOGIC_TABLE,SUB_LOGIC_TABLE");
assertThat(actual.getReference(), is("LOGIC_TABLE,SUB_LOGIC_TABLE"));
} |
public static <InputT> ProjectedBuilder<InputT, InputT> of(PCollection<InputT> input) {
return named(null).of(input);
} | @Test
public void testBuild_Windowing() {
final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings());
final PCollection<String> uniq =
Distinct.of(dataset)
.windowBy(FixedWindows.of(org.joda.time.Duration.standardHours(1)))
.triggeredBy(DefaultTrigger.of())
.accumulationMode(AccumulationMode.DISCARDING_FIRED_PANES)
.output();
final Distinct distinct = (Distinct) TestUtils.getProducer(uniq);
assertTrue(distinct.getWindow().isPresent());
@SuppressWarnings("unchecked")
final WindowDesc<?> windowDesc = WindowDesc.of((Window) distinct.getWindow().get());
assertEquals(
FixedWindows.of(org.joda.time.Duration.standardHours(1)), windowDesc.getWindowFn());
assertEquals(DefaultTrigger.of(), windowDesc.getTrigger());
} |
public static HistoryConfigCleaner getHistoryConfigCleaner(String name) {
return historyConfigCleanerMap.getOrDefault(name, historyConfigCleanerMap.get("nacos"));
} | @Test
public void testHistoryConfigCleanerManangerTest() {
HistoryConfigCleaner cleaner = HistoryConfigCleanerManager.getHistoryConfigCleaner(
HistoryConfigCleanerConfig.getInstance().getActiveHistoryConfigCleaner());
assertEquals(cleaner.getName(), "nacos");
} |
public static String evaluate(final co.elastic.logstash.api.Event event, final String template)
throws JsonProcessingException {
if (event instanceof Event) {
return evaluate((Event) event, template);
} else {
throw new IllegalStateException("Unknown event concrete class: " + event.getClass().getName());
}
} | @Test
public void testMissingKey() throws IOException {
Event event = getTestEvent();
String path = "/full/%{do-not-exist}";
assertEquals("/full/%{do-not-exist}", StringInterpolation.evaluate(event, path));
} |
protected final boolean isConnected() {
return service != null;
} | @Test
void testIsConnected() {
AbstractServiceConnectionManager<Object> connectionManager =
new TestServiceConnectionManager();
assertThat(connectionManager.isConnected()).isFalse();
connectionManager.connect(new Object());
assertThat(connectionManager.isConnected()).isTrue();
connectionManager.disconnect();
assertThat(connectionManager.isConnected()).isFalse();
connectionManager.close();
assertThat(connectionManager.isConnected()).isFalse();
} |
List<MethodSpec> buildFunctions(AbiDefinition functionDefinition)
throws ClassNotFoundException {
return buildFunctions(functionDefinition, true);
} | @Test
public void testBuildFunctionConstantInvalid() throws Exception {
AbiDefinition functionDefinition =
new AbiDefinition(
true,
Collections.singletonList(new NamedType("param", "uint8")),
"functionName",
Collections.emptyList(),
"type",
false);
List<MethodSpec> methodSpecs = solidityFunctionWrapper.buildFunctions(functionDefinition);
assertTrue(methodSpecs.isEmpty());
} |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void mod() {
assertUnifiesAndInlines(
"4 % 17", UBinary.create(Kind.REMAINDER, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
public static <T> Bounded<T> from(BoundedSource<T> source) {
return new Bounded<>(null, source);
} | @Test
public void failsWhenCustomBoundedSourceIsNotSerializable() {
thrown.expect(IllegalArgumentException.class);
Read.from(new NotSerializableBoundedSource());
} |
private boolean isNotEmptyConfig() {
return header.isNotEmptyConfig() || parameter.isNotEmptyConfig() || cookie.isNotEmptyConfig();
} | @Test
public void testShenyuRequestParameter() {
RequestHandle handle = new RequestHandle();
RequestHandle.ShenyuRequestParameter parameter = handle.new ShenyuRequestParameter(
ImmutableMap.of("addKey", "addValue"), ImmutableMap.of("replaceKey", "newKey"),
ImmutableMap.of("setKey", "newValue"), Sets.newSet("removeKey")
);
assertThat(parameter.isNotEmptyConfig(), is(true));
assertThat(parameter.getAddParameters(), hasEntry("addKey", "addValue"));
assertThat(parameter.getReplaceParameterKeys(), hasEntry("replaceKey", "newKey"));
assertThat(parameter.getSetParameters(), hasEntry("setKey", "newValue"));
assertThat(parameter.getRemoveParameterKeys(), hasItems("removeKey"));
RequestHandle.ShenyuRequestParameter parameter1 = handle.new ShenyuRequestParameter();
parameter1.setAddParameters(ImmutableMap.of("addKey", "addValue"));
parameter1.setReplaceParameterKeys(ImmutableMap.of("replaceKey", "newKey"));
parameter1.setSetParameters(ImmutableMap.of("setKey", "newValue"));
parameter1.setRemoveParameterKeys(ImmutableSet.of("removeKey"));
assertThat(ImmutableSet.of(parameter, parameter1), hasSize(1));
} |
@Override
public long read() {
return gaugeSource.read();
} | @Test
public void whenNoProbeSet() {
LongGauge gauge = metricsRegistry.newLongGauge("foo");
long actual = gauge.read();
assertEquals(0, actual);
} |
public static <T> boolean isEmpty(List<T> list) {
return list == null || list.isEmpty();
} | @Test
void isEmpty() {
assertThat(ListUtils.isEmpty(null), is(true));
assertThat(ListUtils.isEmpty(Collections.emptyList()), is(true));
assertThat(ListUtils.isEmpty(List.of("1")), is(false));
} |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void testBuildWithIllegalQueueCapacity() {
ThreadPoolBulkheadConfig.custom()
.queueCapacity(-1)
.build();
} |
@Override
public Map<Path, Path> normalize(final Map<Path, Path> files) {
final Map<Path, Path> normalized = new HashMap<>();
Iterator<Path> sourcesIter = files.keySet().iterator();
Iterator<Path> destinationsIter = files.values().iterator();
while(sourcesIter.hasNext()) {
Path source = sourcesIter.next();
Path destination = destinationsIter.next();
boolean duplicate = false;
for(Iterator<Path> normalizedIter = normalized.keySet().iterator(); normalizedIter.hasNext(); ) {
Path n = normalizedIter.next();
if(source.isChild(n)) {
if(log.isDebugEnabled()) {
log.debug(String.format("Remove path %s already included by directory", source.getAbsolute()));
}
// The selected file is a child of a directory already included
duplicate = true;
break;
}
if(n.isChild(source)) {
if(log.isDebugEnabled()) {
log.debug(String.format("Remove path %s already included by directory", n.getAbsolute()));
}
// Remove the previously added file as it is a child
// of the currently evaluated file
normalizedIter.remove();
}
}
if(!duplicate) {
normalized.put(source, destination);
}
}
return normalized;
} | @Test
public void testNormalize2() {
CopyRootPathsNormalizer normalizer = new CopyRootPathsNormalizer();
final HashMap<Path, Path> files = new HashMap<>();
files.put(new Path("/p/child", EnumSet.of(Path.Type.directory)), new Path("/d/child", EnumSet.of(Path.Type.directory)));
files.put(new Path("/p", EnumSet.of(Path.Type.directory)), new Path("/d", EnumSet.of(Path.Type.directory)));
assertEquals(Collections.singletonMap(new Path("/p", EnumSet.of(Path.Type.directory)), new Path("/d", EnumSet.of(Path.Type.directory))), normalizer.normalize(files));
} |
@Override
public ObjectNode encode(Meter meter, CodecContext context) {
checkNotNull(meter, "Meter cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(ID, meter.meterCellId().toString())
.put(LIFE, meter.life())
.put(PACKETS, meter.packetsSeen())
.put(BYTES, meter.bytesSeen())
.put(REFERENCE_COUNT, meter.referenceCount())
.put(UNIT, meter.unit().toString())
.put(BURST, meter.isBurst())
.put(DEVICE_ID, meter.deviceId().toString());
if (meter.appId() != null) {
result.put(APP_ID, meter.appId().name());
}
if (meter.state() != null) {
result.put(STATE, meter.state().toString());
}
ArrayNode bands = context.mapper().createArrayNode();
meter.bands().forEach(band -> {
ObjectNode bandJson = context.codec(Band.class).encode(band, context);
bands.add(bandJson);
});
result.set(BANDS, bands);
return result;
} | @Test
public void testMeterEncode() {
Band band1 = DefaultBand.builder()
.ofType(Band.Type.DROP)
.burstSize(10)
.withRate(10).build();
Band band2 = DefaultBand.builder()
.ofType(Band.Type.REMARK)
.burstSize(10)
.withRate(10)
.dropPrecedence((short) 10).build();
Meter meter = DefaultMeter.builder()
.fromApp(APP_ID)
.withId(MeterId.meterId(1L))
.forDevice(NetTestTools.did("d1"))
.withBands(ImmutableList.of(band1, band2))
.withUnit(Meter.Unit.KB_PER_SEC).build();
ObjectNode meterJson = meterCodec.encode(meter, context);
assertThat(meterJson, matchesMeter(meter));
} |
@VisibleForTesting
static SortedMap<OffsetRange, Integer> computeOverlappingRanges(Iterable<OffsetRange> ranges) {
ImmutableSortedMap.Builder<OffsetRange, Integer> rval =
ImmutableSortedMap.orderedBy(OffsetRangeComparator.INSTANCE);
List<OffsetRange> sortedRanges = Lists.newArrayList(ranges);
if (sortedRanges.isEmpty()) {
return rval.build();
}
Collections.sort(sortedRanges, OffsetRangeComparator.INSTANCE);
// Stores ranges in smallest 'from' and then smallest 'to' order
// e.g. [2, 7), [3, 4), [3, 5), [3, 5), [3, 6), [4, 0)
PriorityQueue<OffsetRange> rangesWithSameFrom =
new PriorityQueue<>(OffsetRangeComparator.INSTANCE);
Iterator<OffsetRange> iterator = sortedRanges.iterator();
// Stored in reverse sorted order so that when we iterate and re-add them back to
// overlappingRanges they are stored in sorted order from smallest to largest range.to
List<OffsetRange> rangesToProcess = new ArrayList<>();
while (iterator.hasNext()) {
OffsetRange current = iterator.next();
// Skip empty ranges
if (current.getFrom() == current.getTo()) {
continue;
}
// If the current range has a different 'from' then a prior range then we must produce
// ranges in [rangesWithSameFrom.from, current.from)
while (!rangesWithSameFrom.isEmpty()
&& rangesWithSameFrom.peek().getFrom() != current.getFrom()) {
rangesToProcess.addAll(rangesWithSameFrom);
Collections.sort(rangesToProcess, OffsetRangeComparator.INSTANCE);
rangesWithSameFrom.clear();
int i = 0;
long lastTo = rangesToProcess.get(i).getFrom();
// Output all the ranges that are strictly less then current.from
// e.g. current.to := 7 for [3, 4), [3, 5), [3, 5), [3, 6) will produce
// [3, 4) := 4
// [4, 5) := 3
// [5, 6) := 1
for (; i < rangesToProcess.size(); ++i) {
if (rangesToProcess.get(i).getTo() > current.getFrom()) {
break;
}
// Output only the first of any subsequent duplicate ranges
if (i == 0 || rangesToProcess.get(i - 1).getTo() != rangesToProcess.get(i).getTo()) {
rval.put(
new OffsetRange(lastTo, rangesToProcess.get(i).getTo()),
rangesToProcess.size() - i);
lastTo = rangesToProcess.get(i).getTo();
}
}
// We exitted the loop with 'to' > current.from, we must add the range [lastTo,
// current.from) if it is non-empty
if (lastTo < current.getFrom() && i != rangesToProcess.size()) {
rval.put(new OffsetRange(lastTo, current.getFrom()), rangesToProcess.size() - i);
}
// The remaining ranges have a 'to' that is greater then 'current.from' and will overlap
// with current so add them back to rangesWithSameFrom with the updated 'from'
for (; i < rangesToProcess.size(); ++i) {
rangesWithSameFrom.add(
new OffsetRange(current.getFrom(), rangesToProcess.get(i).getTo()));
}
rangesToProcess.clear();
}
rangesWithSameFrom.add(current);
}
// Process the last chunk of overlapping ranges
while (!rangesWithSameFrom.isEmpty()) {
// This range always represents the range with with the smallest 'to'
OffsetRange current = rangesWithSameFrom.remove();
rangesToProcess.addAll(rangesWithSameFrom);
Collections.sort(rangesToProcess, OffsetRangeComparator.INSTANCE);
rangesWithSameFrom.clear();
rval.put(current, rangesToProcess.size() + 1 /* include current */);
// Shorten all the remaining ranges such that they start with current.to
for (OffsetRange rangeWithDifferentFrom : rangesToProcess) {
// Skip any duplicates of current
if (rangeWithDifferentFrom.getTo() > current.getTo()) {
rangesWithSameFrom.add(new OffsetRange(current.getTo(), rangeWithDifferentFrom.getTo()));
}
}
rangesToProcess.clear();
}
return rval.build();
} | @Test
public void testRandomRanges() {
Random random =
new Random(123892154890L); // use an arbitrary seed to make this test deterministic
for (int i = 0; i < 1000; ++i) {
List<OffsetRange> ranges = new ArrayList<>();
for (int j = 0; j < 20; ++j) {
long start = random.nextInt(10);
ranges.add(range(start, start + random.nextInt(10) + 1));
Map<OffsetRange, Integer> nonOverlappingRangesToNumElementsPerPosition =
computeOverlappingRanges(ranges);
assertNonEmptyRangesAndPositions(ranges, nonOverlappingRangesToNumElementsPerPosition);
}
}
} |
public Disjunction addOperand(Predicate operand) {
operands.add(operand);
return this;
} | @Test
void requireThatEqualsIsImplemented() {
Disjunction lhs = new Disjunction(SimplePredicates.newString("foo"),
SimplePredicates.newString("bar"));
assertEquals(lhs, lhs);
assertNotEquals(lhs, new Object());
Disjunction rhs = new Disjunction();
assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("foo"));
assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("bar"));
assertEquals(lhs, rhs);
} |
boolean matchesNonValueField(final Optional<SourceName> source, final ColumnName column) {
if (!source.isPresent()) {
return sourceSchemas.values().stream()
.anyMatch(schema ->
SystemColumns.isPseudoColumn(column) || schema.isKeyColumn(column));
}
final SourceName sourceName = source.get();
final LogicalSchema sourceSchema = sourceSchemas.get(sourceName);
if (sourceSchema == null) {
throw new IllegalArgumentException("Unknown source: " + sourceName);
}
return sourceSchema.isKeyColumn(column) || SystemColumns.isPseudoColumn(column);
} | @Test(expected = IllegalArgumentException.class)
public void shouldThrowOnUnknownSourceWhenMatchingNonValueFields() {
sourceSchemas.matchesNonValueField(Optional.of(SourceName.of("unknown")), K0);
} |
@Override
public LocalResourceId resolve(String other, ResolveOptions resolveOptions) {
checkState(isDirectory(), "Expected the path is a directory, but had [%s].", pathString);
checkArgument(
resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE)
|| resolveOptions.equals(StandardResolveOptions.RESOLVE_DIRECTORY),
"ResolveOptions: [%s] is not supported.",
resolveOptions);
checkArgument(
!(resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) && other.endsWith("/")),
"The resolved file: [%s] should not end with '/'.",
other);
if (SystemUtils.IS_OS_WINDOWS) {
return resolveLocalPathWindowsOS(other, resolveOptions);
} else {
return resolveLocalPath(other, resolveOptions);
}
} | @Test
public void testResolveInUnix() {
if (SystemUtils.IS_OS_WINDOWS) {
// Skip tests
return;
}
// Tests for local files without the scheme.
assertEquals(
toResourceIdentifier("/root/tmp/aa"),
toResourceIdentifier("/root/tmp/").resolve("aa", StandardResolveOptions.RESOLVE_FILE));
assertEquals(
toResourceIdentifier("/root/tmp/aa/bb/cc/"),
toResourceIdentifier("/root/tmp/")
.resolve("aa", StandardResolveOptions.RESOLVE_DIRECTORY)
.resolve("bb", StandardResolveOptions.RESOLVE_DIRECTORY)
.resolve("cc", StandardResolveOptions.RESOLVE_DIRECTORY));
// Tests absolute path.
assertEquals(
toResourceIdentifier("/root/tmp/aa"),
toResourceIdentifier("/root/tmp/bb/")
.resolve("/root/tmp/aa", StandardResolveOptions.RESOLVE_FILE));
// Tests empty authority and path.
assertEquals(
toResourceIdentifier("file:/aa"),
toResourceIdentifier("file:///").resolve("aa", StandardResolveOptions.RESOLVE_FILE));
} |
public static CacheScope create(String id) {
Preconditions.checkArgument(id != null && id.length() > 0,
"scope id can not be null or empty string");
if (GLOBAL_ID.equals(id)) {
return GLOBAL;
} else if (Level.SCHEMA.matches(id)) {
return new CacheScope(id, id.length(), Level.SCHEMA);
} else if (Level.TABLE.matches(id)) {
return new CacheScope(id, id.length(), Level.TABLE);
} else if (Level.PARTITION.matches(id)) {
return new CacheScope(id, id.length(), Level.PARTITION);
}
throw new IllegalArgumentException("Failed to parse cache scope: " + id);
} | @Test
public void scopeEquals() {
assertEquals(CacheScope.GLOBAL, CacheScope.create("."));
assertEquals(CacheScope.create("."), CacheScope.create("."));
assertEquals(CacheScope.create("schema"), CacheScope.create("schema"));
assertEquals(CacheScope.create("schema.table"), CacheScope.create("schema.table"));
assertEquals(CacheScope.create("schema.table.partition"),
CacheScope.create("schema.table.partition"));
assertNotEquals(CacheScope.create("schema1"), CacheScope.create("schema2"));
assertNotEquals(CacheScope.create("schema.table1"), CacheScope.create("schema.table2"));
assertNotEquals(CacheScope.create("schema.Atable"), CacheScope.create("schema.Btable"));
assertNotEquals(CacheScope.create("schema.table"), CacheScope.create("schema.table.partition"));
assertNotEquals(CacheScope.create("schema.table.partition1"),
CacheScope.create("schema.table.partition2"));
} |
static void setStringProperty(Message message, String name, String value) {
try {
message.setStringProperty(name, value);
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error setting property {0} on message {1}", name, message);
}
} | @Test void setStringProperty() throws Exception {
MessageProperties.setStringProperty(message, "b3", "1");
assertThat(message.getObjectProperty("b3"))
.isEqualTo("1");
} |
static boolean isNewDatabase(String uppercaseProductName) {
if (SUPPORTED_DATABASE_NAMES.contains(uppercaseProductName)) {
return false;
}
return DETECTED_DATABASE_NAMES.add(uppercaseProductName);
} | @Test
public void testH2() {
String dbName = "H2";
boolean newDB = SupportedDatabases.isNewDatabase(dbName);
assertThat(newDB).isFalse();
} |
@Override
protected void run(Environment environment, Namespace namespace, T configuration) throws Exception {
final Server server = configuration.getServerFactory().build(environment);
try {
server.addEventListener(new LifeCycleListener());
cleanupAsynchronously();
server.start();
new Thread(() -> {
try {
server.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "dw-awaiter").start();
} catch (Exception e) {
LOGGER.error("Unable to start server, shutting down", e);
try {
server.stop();
} catch (Exception e1) {
LOGGER.warn("Failure during stop server", e1);
}
try {
cleanup();
} catch (Exception e2) {
LOGGER.warn("Failure during cleanup", e2);
}
throw e;
}
} | @Test
void stopsAServerIfThereIsAnErrorStartingIt() {
this.throwException = true;
server.addBean(new AbstractLifeCycle() {
@Override
protected void doStart() throws Exception {
throw new IOException("oh crap");
}
});
assertThatIOException()
.isThrownBy(() -> command.run(environment, namespace, configuration))
.withMessage("oh crap");
assertThat(server.isStarted())
.isFalse();
this.throwException = false;
} |
@Override
public List<String> getServerList() {
return serverList.isEmpty() ? serversFromEndpoint : serverList;
} | @Test
void testConstructEndpointContextPathIsEmpty() throws Exception {
clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "");
clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb");
clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CLUSTER_NAME, "ccc");
clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1");
Mockito.reset(nacosRestTemplate);
Mockito.when(nacosRestTemplate.get(eq("http://127.0.0.1:8080/bbb/ccc"), any(), any(), any()))
.thenReturn(httpRestResult);
serverListManager = new ServerListManager(clientProperties, "test");
List<String> serverList = serverListManager.getServerList();
assertEquals(1, serverList.size());
assertEquals("127.0.0.1:8848", serverList.get(0));
} |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (iconIds == null)
{
return;
}
switch (chatMessage.getType())
{
case PUBLICCHAT:
case MODCHAT:
case FRIENDSCHAT:
case CLAN_CHAT:
case CLAN_GUEST_CHAT:
case CLAN_GIM_CHAT:
case PRIVATECHAT:
case PRIVATECHATOUT:
case MODPRIVATECHAT:
break;
default:
return;
}
final MessageNode messageNode = chatMessage.getMessageNode();
final String message = messageNode.getValue();
final String updatedMessage = updateMessage(message);
if (updatedMessage == null)
{
return;
}
messageNode.setValue(updatedMessage);
} | @Test
public void testOnChatMessage()
{
MessageNode messageNode = mock(MessageNode.class);
// With chat recolor, message may be wrapped in col tags
when(messageNode.getValue()).thenReturn("<col=ff0000>:) :) :)</col>");
ChatMessage chatMessage = new ChatMessage();
chatMessage.setType(ChatMessageType.PUBLICCHAT);
chatMessage.setMessageNode(messageNode);
emojiPlugin.onChatMessage(chatMessage);
verify(messageNode).setValue("<col=ff0000><img=0> <img=0> <img=0></col>");
} |
@Override
public void executeUpdate(final AlterStorageUnitStatement sqlStatement, final ContextManager contextManager) {
checkBefore(sqlStatement);
Map<String, DataSourcePoolProperties> propsMap = DataSourceSegmentsConverter.convert(database.getProtocolType(), sqlStatement.getStorageUnits());
validateHandler.validate(propsMap, getExpectedPrivileges(sqlStatement));
try {
contextManager.getPersistServiceFacade().getMetaDataManagerPersistService().alterStorageUnits(database.getName(), propsMap);
} catch (final SQLException | ShardingSphereExternalException ex) {
throw new StorageUnitsOperateException("alter", propsMap.keySet(), ex);
}
} | @Test
void assertExecuteUpdateWithAlterDatabase() {
ResourceMetaData resourceMetaData = mock(ResourceMetaData.class, RETURNS_DEEP_STUBS);
StorageUnit storageUnit = mock(StorageUnit.class, RETURNS_DEEP_STUBS);
ConnectionProperties connectionProps = mockConnectionProperties("ds_1");
when(storageUnit.getConnectionProperties()).thenReturn(connectionProps);
when(resourceMetaData.getStorageUnits()).thenReturn(Collections.singletonMap("ds_0", storageUnit));
when(database.getResourceMetaData()).thenReturn(resourceMetaData);
assertThrows(AlterStorageUnitConnectionInfoException.class,
() -> executor.executeUpdate(createAlterStorageUnitStatement("ds_0"), mockContextManager(mock(MetaDataContexts.class, RETURNS_DEEP_STUBS))));
} |
public String convert(ILoggingEvent le) {
long timestamp = le.getTimeStamp();
return cachingDateFormatter.format(timestamp);
} | @Test
public void convertsDateWithEnglishLocaleByDefault() {
Locale origLocale = Locale.getDefault();
Locale.setDefault(Locale.FRANCE);
assertEquals(ENGLISH_TIME_UTC, convert(_timestamp, DATETIME_PATTERN, "UTC"));
Locale.setDefault(origLocale);
} |
public Optional<LocalSession> getActiveLocalSession(Tenant tenant, ApplicationId applicationId) {
TenantApplications applicationRepo = tenant.getApplicationRepo();
return applicationRepo.activeSessionOf(applicationId).map(aLong -> tenant.getSessionRepository().getLocalSession(aLong));
} | @Test
public void redeploy() {
long firstSessionId = deployApp(testApp).sessionId();
long secondSessionId = deployApp(testApp).sessionId();
assertNotEquals(firstSessionId, secondSessionId);
Session session = applicationRepository.getActiveLocalSession(tenant(), applicationId()).get();
assertEquals(firstSessionId, session.getMetaData().getPreviousActiveGeneration());
} |
@Nullable
protected String findWebJarResourcePath(String pathStr) {
Path path = Paths.get(pathStr);
if (path.getNameCount() < 2) return null;
String version = swaggerUiConfigProperties.getVersion();
if (version == null) return null;
Path first = path.getName(0);
Path rest = path.subpath(1, path.getNameCount());
return first.resolve(version).resolve(rest).toString();
} | @Test
void findWebJarResourcePath() {
String path = "swagger-ui/swagger-initializer.js";
String actual = abstractSwaggerResourceResolver.findWebJarResourcePath(path);
assertEquals("swagger-ui" + File.separator + "4.18.2" + File.separator + "swagger-initializer.js", actual);
} |
@Override
public SerializationServiceBuilder setInitialOutputBufferSize(int initialOutputBufferSize) {
if (initialOutputBufferSize <= 0) {
throw new IllegalArgumentException("Initial buffer size must be positive!");
}
this.initialOutputBufferSize = initialOutputBufferSize;
return this;
} | @Test(expected = IllegalArgumentException.class)
public void test_exceptionThrown_whenInitialOutputBufferSizeNegative() {
getSerializationServiceBuilder().setInitialOutputBufferSize(-1);
} |
@Override
public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException {
Collection<TableMetaData> tableMetaDataList = new LinkedList<>();
Map<String, Collection<ColumnMetaData>> columnMetaDataMap = loadColumnMetaDataMap(material.getDataSource(), material.getActualTableNames());
if (!columnMetaDataMap.isEmpty()) {
Map<String, Collection<IndexMetaData>> indexMetaDataMap = loadIndexMetaData(material.getDataSource(), columnMetaDataMap.keySet());
for (Entry<String, Collection<ColumnMetaData>> entry : columnMetaDataMap.entrySet()) {
Collection<IndexMetaData> indexMetaDataList = indexMetaDataMap.getOrDefault(entry.getKey(), Collections.emptyList());
tableMetaDataList.add(new TableMetaData(entry.getKey(), entry.getValue(), indexMetaDataList, Collections.emptyList()));
}
}
return Collections.singleton(new SchemaMetaData(material.getDefaultSchemaName(), tableMetaDataList));
} | @Test
void assertLoadWithTablesWithLowVersion() throws SQLException {
DataSource dataSource = mockDataSource();
ResultSet resultSet = mockTableMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(LOAD_COLUMN_META_DATA_WITH_TABLES_LOW_VERSION).executeQuery()).thenReturn(resultSet);
ResultSet indexResultSet = mockIndexMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(LOAD_INDEX_META_DATA)
.executeQuery()).thenReturn(indexResultSet);
when(dataSource.getConnection().getMetaData().getDatabaseMajorVersion()).thenReturn(14);
Collection<SchemaMetaData> actual = getDialectTableMetaDataLoader().load(new MetaDataLoaderMaterial(Collections.singletonList("tbl"), dataSource, new SQLServerDatabaseType(), "sharding_db"));
assertTableMetaDataMap(actual);
TableMetaData actualTableMetaData = actual.iterator().next().getTables().iterator().next();
Iterator<ColumnMetaData> columnsIterator = actualTableMetaData.getColumns().iterator();
assertThat(columnsIterator.next(), is(new ColumnMetaData("id", Types.INTEGER, false, true, true, true, false, false)));
assertThat(columnsIterator.next(), is(new ColumnMetaData("name", Types.VARCHAR, false, false, false, true, false, true)));
} |
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) {
return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context);
} | @Test
public void testShowEmpty() throws AnalysisException, DdlException {
ShowProcedureStmt stmt = new ShowProcedureStmt();
ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx);
Assert.assertFalse(resultSet.next());
} |
public CustomFieldMappings mergeWith(final CustomFieldMapping changedMapping) {
final Set<CustomFieldMapping> modifiedMappings = new HashSet<>(this);
modifiedMappings.removeIf(m -> changedMapping.fieldName().equals(m.fieldName()));
modifiedMappings.add(changedMapping);
return new CustomFieldMappings(modifiedMappings);
} | @Test
void testReturnsOriginalMappingsIfMergedWithEmptyMappings() {
CustomFieldMappings customFieldMappings = new CustomFieldMappings(List.of());
assertSame(customFieldMappings, customFieldMappings.mergeWith(new CustomFieldMappings()));
} |
@VisibleForTesting
List<Page> getAllPages() {
return requireNonNull(pages, "Pages haven't been initialized yet");
} | @Test
public void fail_if_pages_called_before_server_startup() {
assertThatThrownBy(() -> underTest.getAllPages())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("Pages haven't been initialized yet");
} |
@Override
public void handleRequest(HttpServerExchange httpServerExchange) {
if (!httpServerExchange.getRequestMethod().equals(HttpString.tryFromString("GET"))) {
httpServerExchange.setStatusCode(HTTP_METHOD_NOT_ALLOWED);
httpServerExchange.getResponseSender().send("");
} else {
// For now if this endpoint is reachable then the service is up.
// There is no hard dependency that could be down.
httpServerExchange.setStatusCode(HTTP_OK);
httpServerExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
httpServerExchange.getResponseSender().send(STATUS_UP);
}
} | @Test
void get() {
var sut = new HealthEndpoint();
// when
var httpServerExchange = mock(HttpServerExchange.class);
var headers = mock(HeaderMap.class);
var sender = mock(Sender.class);
when(httpServerExchange.getResponseHeaders()).thenReturn(headers);
when(httpServerExchange.getResponseSender()).thenReturn(sender);
when(httpServerExchange.getRequestMethod()).thenReturn(HttpString.tryFromString("GET"));
sut.handleRequest(httpServerExchange);
// then
verify(httpServerExchange).setStatusCode(Status.OK.getStatusCode());
} |
public Capacity getCapacityWithDefault(String group, String tenant) {
Capacity capacity;
boolean isTenant = StringUtils.isNotBlank(tenant);
if (isTenant) {
capacity = getTenantCapacity(tenant);
} else {
capacity = getGroupCapacity(group);
}
if (capacity == null) {
return null;
}
Integer quota = capacity.getQuota();
if (quota == 0) {
if (isTenant) {
capacity.setQuota(PropertyUtil.getDefaultTenantQuota());
} else {
if (GroupCapacityPersistService.CLUSTER.equals(group)) {
capacity.setQuota(PropertyUtil.getDefaultClusterQuota());
} else {
capacity.setQuota(PropertyUtil.getDefaultGroupQuota());
}
}
}
Integer maxSize = capacity.getMaxSize();
if (maxSize == 0) {
capacity.setMaxSize(PropertyUtil.getDefaultMaxSize());
}
Integer maxAggrCount = capacity.getMaxAggrCount();
if (maxAggrCount == 0) {
capacity.setMaxAggrCount(PropertyUtil.getDefaultMaxAggrCount());
}
Integer maxAggrSize = capacity.getMaxAggrSize();
if (maxAggrSize == 0) {
capacity.setMaxAggrSize(PropertyUtil.getDefaultMaxAggrSize());
}
return capacity;
} | @Test
void testGetCapacityWithDefault() {
TenantCapacity tenantCapacity = new TenantCapacity();
tenantCapacity.setQuota(0);
tenantCapacity.setMaxSize(0);
tenantCapacity.setMaxAggrCount(0);
tenantCapacity.setMaxAggrSize(0);
when(tenantCapacityPersistService.getTenantCapacity(anyString())).thenReturn(tenantCapacity);
GroupCapacity groupCapacity1 = new GroupCapacity();
groupCapacity1.setQuota(0);
groupCapacity1.setMaxSize(0);
groupCapacity1.setMaxAggrCount(0);
groupCapacity1.setMaxAggrSize(0);
when(groupCapacityPersistService.getGroupCapacity(anyString())).thenReturn(groupCapacity1);
//group is null
Capacity resCapacity1 = service.getCapacityWithDefault(null, "testTenant");
assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity1.getQuota().intValue());
assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity1.getMaxSize().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity1.getMaxAggrCount().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity1.getMaxAggrSize().intValue());
//group is GroupCapacityPersistService.CLUSTER
Capacity resCapacity2 = service.getCapacityWithDefault(GroupCapacityPersistService.CLUSTER, null);
assertEquals(PropertyUtil.getDefaultClusterQuota(), resCapacity2.getQuota().intValue());
assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity2.getMaxSize().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity2.getMaxAggrCount().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity2.getMaxAggrSize().intValue());
GroupCapacity groupCapacity2 = new GroupCapacity();
groupCapacity2.setQuota(0);
groupCapacity2.setMaxSize(0);
groupCapacity2.setMaxAggrCount(0);
groupCapacity2.setMaxAggrSize(0);
when(groupCapacityPersistService.getGroupCapacity(anyString())).thenReturn(groupCapacity2);
//tenant is null
Capacity resCapacity3 = service.getCapacityWithDefault("testGroup", null);
assertEquals(PropertyUtil.getDefaultGroupQuota(), resCapacity3.getQuota().intValue());
assertEquals(PropertyUtil.getDefaultMaxSize(), resCapacity3.getMaxSize().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrCount(), resCapacity3.getMaxAggrCount().intValue());
assertEquals(PropertyUtil.getDefaultMaxAggrSize(), resCapacity3.getMaxAggrSize().intValue());
} |
public int size()
{
return pfbdata.length;
} | @Test
void testPfbPDFBox5713() throws IOException
{
Type1Font font;
try (InputStream is = new FileInputStream("target/fonts/DejaVuSerifCondensed.pfb"))
{
font = Type1Font.createWithPFB(is);
}
Assertions.assertEquals("Version 2.33", font.getVersion());
Assertions.assertEquals("DejaVuSerifCondensed", font.getFontName());
Assertions.assertEquals("DejaVu Serif Condensed", font.getFullName());
Assertions.assertEquals("DejaVu Serif Condensed", font.getFamilyName());
Assertions.assertEquals("Copyright [c] 2003 by Bitstream, Inc. All Rights Reserved.", font.getNotice());
Assertions.assertEquals(false, font.isFixedPitch());
Assertions.assertEquals(false, font.isForceBold());
Assertions.assertEquals(0, font.getItalicAngle());
Assertions.assertEquals("Book", font.getWeight());
Assertions.assertTrue(font.getEncoding() instanceof BuiltInEncoding);
Assertions.assertEquals(5959, font.getASCIISegment().length);
Assertions.assertEquals(1056090, font.getBinarySegment().length);
Assertions.assertEquals(3399, font.getCharStringsDict().size());
} |
@Override
public boolean supports(Class<?> authentication) {
return (JWTBearerAssertionAuthenticationToken.class.isAssignableFrom(authentication));
} | @Test
public void should_support_JWTBearerAssertionAuthenticationToken() {
assertThat(jwtBearerAuthenticationProvider.supports(JWTBearerAssertionAuthenticationToken.class), is(true));
} |
public Reader getReader(InputStream in, String declaredEncoding) {
fDeclaredEncoding = declaredEncoding;
try {
setText(in);
CharsetMatch match = detect();
if (match == null) {
return null;
}
return match.getReader();
} catch (IOException e) {
return null;
}
} | @Test
public void testEmptyOrNullDeclaredCharset() throws IOException {
try (InputStream in = getResourceAsStream("/test-documents/resume.html")) {
CharsetDetector detector = new CharsetDetector();
Reader reader = detector.getReader(in, null);
assertTrue(reader.ready());
reader = detector.getReader(in, "");
assertTrue(reader.ready());
}
} |
@Override
public void setSessionIntervalTime(int sessionIntervalTime) {
} | @Test
public void setSessionIntervalTime() {
mSensorsAPI.setSessionIntervalTime(50 * 100);
Assert.assertEquals(30 * 1000, mSensorsAPI.getSessionIntervalTime());
} |
public static String escapeString(String identifier) {
return "'" + identifier.replace("\\", "\\\\").replace("'", "\\'") + "'";
} | @Test
public void testEscapeStringNoSpecialCharacters() {
assertEquals("'asdasd asd ad'", SingleStoreUtil.escapeString("asdasd asd ad"));
} |
public static void preserve(FileSystem targetFS, Path path,
CopyListingFileStatus srcFileStatus,
EnumSet<FileAttribute> attributes,
boolean preserveRawXattrs) throws IOException {
// strip out those attributes we don't need any more
attributes.remove(FileAttribute.BLOCKSIZE);
attributes.remove(FileAttribute.CHECKSUMTYPE);
// If not preserving anything from FileStatus, don't bother fetching it.
FileStatus targetFileStatus = attributes.isEmpty() ? null :
targetFS.getFileStatus(path);
String group = targetFileStatus == null ? null :
targetFileStatus.getGroup();
String user = targetFileStatus == null ? null :
targetFileStatus.getOwner();
boolean chown = false;
if (attributes.contains(FileAttribute.ACL)) {
List<AclEntry> srcAcl = srcFileStatus.getAclEntries();
List<AclEntry> targetAcl = getAcl(targetFS, targetFileStatus);
if (!srcAcl.equals(targetAcl)) {
targetFS.removeAcl(path);
targetFS.setAcl(path, srcAcl);
}
// setAcl doesn't preserve sticky bit, so also call setPermission if needed.
if (srcFileStatus.getPermission().getStickyBit() !=
targetFileStatus.getPermission().getStickyBit()) {
targetFS.setPermission(path, srcFileStatus.getPermission());
}
} else if (attributes.contains(FileAttribute.PERMISSION) &&
!srcFileStatus.getPermission().equals(targetFileStatus.getPermission())) {
targetFS.setPermission(path, srcFileStatus.getPermission());
}
final boolean preserveXAttrs = attributes.contains(FileAttribute.XATTR);
if (preserveXAttrs || preserveRawXattrs) {
final String rawNS =
StringUtils.toLowerCase(XAttr.NameSpace.RAW.name());
Map<String, byte[]> srcXAttrs = srcFileStatus.getXAttrs();
Map<String, byte[]> targetXAttrs = getXAttrs(targetFS, path);
if (srcXAttrs != null && !srcXAttrs.equals(targetXAttrs)) {
for (Entry<String, byte[]> entry : srcXAttrs.entrySet()) {
String xattrName = entry.getKey();
if (xattrName.startsWith(rawNS) || preserveXAttrs) {
targetFS.setXAttr(path, xattrName, entry.getValue());
}
}
}
}
// The replication factor can only be preserved for replicated files.
// It is ignored when either the source or target file are erasure coded.
if (attributes.contains(FileAttribute.REPLICATION) &&
!targetFileStatus.isDirectory() &&
!targetFileStatus.isErasureCoded() &&
!srcFileStatus.isErasureCoded() &&
srcFileStatus.getReplication() != targetFileStatus.getReplication()) {
targetFS.setReplication(path, srcFileStatus.getReplication());
}
if (attributes.contains(FileAttribute.GROUP) &&
!group.equals(srcFileStatus.getGroup())) {
group = srcFileStatus.getGroup();
chown = true;
}
if (attributes.contains(FileAttribute.USER) &&
!user.equals(srcFileStatus.getOwner())) {
user = srcFileStatus.getOwner();
chown = true;
}
if (chown) {
targetFS.setOwner(path, user, group);
}
if (attributes.contains(FileAttribute.TIMES)) {
targetFS.setTimes(path,
srcFileStatus.getModificationTime(),
srcFileStatus.getAccessTime());
}
} | @Test
public void testPreserveNothingOnDirectory() throws IOException {
FileSystem fs = FileSystem.get(config);
EnumSet<FileAttribute> attributes = EnumSet.noneOf(FileAttribute.class);
Path dst = new Path("/tmp/abc");
Path src = new Path("/tmp/src");
createDirectory(fs, src);
createDirectory(fs, dst);
fs.setPermission(src, fullPerm);
fs.setOwner(src, "somebody", "somebody-group");
fs.setTimes(src, 0, 0);
fs.setPermission(dst, noPerm);
fs.setOwner(dst, "nobody", "nobody-group");
fs.setTimes(dst, 100, 100);
CopyListingFileStatus srcStatus = new CopyListingFileStatus(fs.getFileStatus(src));
DistCpUtils.preserve(fs, dst, srcStatus, attributes, false);
CopyListingFileStatus dstStatus = new CopyListingFileStatus(fs.getFileStatus(dst));
// FileStatus.equals only compares path field, must explicitly compare all fields
Assert.assertFalse(srcStatus.getPermission().equals(dstStatus.getPermission()));
Assert.assertFalse(srcStatus.getOwner().equals(dstStatus.getOwner()));
Assert.assertFalse(srcStatus.getGroup().equals(dstStatus.getGroup()));
Assert.assertTrue(dstStatus.getAccessTime() == 100);
Assert.assertTrue(dstStatus.getModificationTime() == 100);
Assert.assertTrue(dstStatus.getReplication() == 0);
} |
File putIfAbsent(String userId, boolean saveToDisk) throws IOException {
String idKey = getIdStrategy().keyFor(userId);
String directoryName = idToDirectoryNameMap.get(idKey);
File directory = null;
if (directoryName == null) {
synchronized (this) {
directoryName = idToDirectoryNameMap.get(idKey);
if (directoryName == null) {
directory = createDirectoryForNewUser(userId);
directoryName = directory.getName();
idToDirectoryNameMap.put(idKey, directoryName);
if (saveToDisk) {
save();
}
}
}
}
return directory == null ? new File(usersDirectory, directoryName) : directory;
} | @Test
public void testDirectoryFormatMixed() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "a$b!c^d~e@f";
File directory1 = mapper.putIfAbsent(user1, true);
assertThat(directory1.getName(), startsWith("abcdef_"));
} |
@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
// Retrieve the message body as input stream
InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, graph);
// and covert that to XML
Document document = exchange.getContext().getTypeConverter().convertTo(Document.class, exchange, is);
if (null != keyCipherAlgorithm
&& (keyCipherAlgorithm.equals(XMLCipher.RSA_v1dot5) || keyCipherAlgorithm.equals(XMLCipher.RSA_OAEP)
|| keyCipherAlgorithm.equals(XMLCipher.RSA_OAEP_11))) {
encryptAsymmetric(exchange, document, stream);
} else if (null != recipientKeyAlias) {
encryptAsymmetric(exchange, document, stream);
} else {
encryptSymmetric(exchange, document, stream);
}
} | @Test
public void testPartialPayloadXMLElementEncryptionWithByteKeyAndAlgorithm() throws Exception {
final byte[] bits192 = {
(byte) 0x24, (byte) 0xf2, (byte) 0xd3, (byte) 0x45,
(byte) 0xc0, (byte) 0x75, (byte) 0xb1, (byte) 0x00,
(byte) 0x30, (byte) 0xd4, (byte) 0x3d, (byte) 0xf5,
(byte) 0x6d, (byte) 0xaa, (byte) 0x7d, (byte) 0xc2,
(byte) 0x85, (byte) 0x32, (byte) 0x2a, (byte) 0xb6,
(byte) 0xfe, (byte) 0xed, (byte) 0xbe, (byte) 0xef };
final Charset passCodeCharset = StandardCharsets.UTF_8;
final String passCode = new String(bits192, passCodeCharset);
byte[] bytes = passCode.getBytes(passCodeCharset);
assertNotEquals(bits192.length, bytes.length);
context.addRoutes(new RouteBuilder() {
public void configure() {
from("direct:start")
.marshal().xmlSecurity("//cheesesites/netherlands", false, bits192, XMLCipher.AES_192)
.to("mock:encrypted");
}
});
xmlsecTestHelper.testEncryption(context);
} |
@Override
@Nullable
public float[] readFloatArray(@Nonnull String fieldName) throws IOException {
return readIncompatibleField(fieldName, FLOAT_ARRAY, super::readFloatArray);
} | @Test
public void testReadFloatArray() throws Exception {
assertNull(reader.readFloatArray("NO SUCH FIELD"));
} |
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
} | @Test public void nullKeyThrows() throws Exception {
try {
cache.edit(null);
Assert.fail();
} catch (NullPointerException expected) {
}
} |
public static byte[] writeUtf8(final String in) {
if (in == null) {
return null;
}
if (UnsafeUtil.hasUnsafe()) {
// Calculate the encoded length.
final int len = UnsafeUtf8Util.encodedLength(in);
final byte[] outBytes = new byte[len];
UnsafeUtf8Util.encodeUtf8(in, outBytes, 0, len);
return outBytes;
} else {
return in.getBytes(StandardCharsets.UTF_8);
}
} | @Test
public void toUtf8BytesTest() {
for (int i = 0; i < 100000; i++) {
String in = UUID.randomUUID().toString();
assertArrayEquals(Utils.getBytes(in), BytesUtil.writeUtf8(in));
}
} |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void testToObject10() {
assertThrows(Exception.class, () -> {
JacksonUtils.toObj("{not_A}Json:String}".getBytes(), new TypeReference<Object>() {
});
});
} |
@Override
public void check(final EncryptRule encryptRule, final ShardingSphereSchema schema, final SelectStatementContext sqlStatementContext) {
checkSelect(encryptRule, sqlStatementContext);
for (SelectStatementContext each : sqlStatementContext.getSubqueryContexts().values()) {
checkSelect(encryptRule, each);
}
} | @Test
void assertCheckWhenCombineStatementContainsEncryptColumn() {
SelectStatementContext sqlStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(sqlStatementContext.isContainsCombine()).thenReturn(true);
when(sqlStatementContext.getSqlStatement().getCombine().isPresent()).thenReturn(true);
CombineSegment combineSegment = mock(CombineSegment.class, RETURNS_DEEP_STUBS);
when(sqlStatementContext.getSqlStatement().getCombine().get()).thenReturn(combineSegment);
ColumnProjection orderIdColumn = new ColumnProjection("o", "order_id", null, new MySQLDatabaseType());
orderIdColumn.setOriginalTable(new IdentifierValue("t_order"));
orderIdColumn.setOriginalColumn(new IdentifierValue("order_id"));
ColumnProjection userIdColumn = new ColumnProjection("o", "user_id", null, new MySQLDatabaseType());
userIdColumn.setOriginalTable(new IdentifierValue("t_order"));
userIdColumn.setOriginalColumn(new IdentifierValue("user_id"));
SelectStatementContext leftSelectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(leftSelectStatementContext.getProjectionsContext().getExpandProjections()).thenReturn(Arrays.asList(orderIdColumn, userIdColumn));
ColumnProjection merchantIdColumn = new ColumnProjection("m", "merchant_id", null, new MySQLDatabaseType());
merchantIdColumn.setOriginalTable(new IdentifierValue("t_merchant"));
merchantIdColumn.setOriginalColumn(new IdentifierValue("merchant_id"));
ColumnProjection merchantNameColumn = new ColumnProjection("m", "merchant_name", null, new MySQLDatabaseType());
merchantNameColumn.setOriginalTable(new IdentifierValue("t_merchant"));
merchantNameColumn.setOriginalColumn(new IdentifierValue("merchant_name"));
SelectStatementContext rightSelectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(rightSelectStatementContext.getProjectionsContext().getExpandProjections()).thenReturn(Arrays.asList(merchantIdColumn, merchantNameColumn));
Map<Integer, SelectStatementContext> subqueryContexts = new LinkedHashMap<>(2, 1F);
subqueryContexts.put(0, leftSelectStatementContext);
subqueryContexts.put(1, rightSelectStatementContext);
when(sqlStatementContext.getSubqueryContexts()).thenReturn(subqueryContexts);
when(combineSegment.getLeft().getStartIndex()).thenReturn(0);
when(combineSegment.getRight().getStartIndex()).thenReturn(1);
assertThrows(UnsupportedSQLOperationException.class, () -> new EncryptSelectProjectionSupportedChecker().check(mockEncryptRule(), null, sqlStatementContext));
} |
@Override
public Optional<ExecuteResult> getSaneQueryResult(final SQLStatement sqlStatement, final SQLException ex) {
if (ER_PARSE_ERROR == ex.getErrorCode()) {
return Optional.empty();
}
if (sqlStatement instanceof SelectStatement) {
return createQueryResult((SelectStatement) sqlStatement);
}
if (sqlStatement instanceof MySQLShowOtherStatement) {
return Optional.of(createQueryResult());
}
if (sqlStatement instanceof MySQLSetStatement) {
return Optional.of(new UpdateResult(0, 0L));
}
return Optional.empty();
} | @Test
void assertGetSaneQueryResultForSyntaxError() {
SQLException ex = new SQLException("", "", 1064, null);
assertThat(new MySQLDialectSaneQueryResultEngine().getSaneQueryResult(null, ex), is(Optional.empty()));
} |
public static int findName(String expectedLogName) {
int count = 0;
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
String logName = logList.get(i).getLogName();
if (logName.contains(expectedLogName)) {
count++;
}
}
return count;
} | @Test
void testFindName() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogName()).thenReturn("a");
assertThat(LogUtil.findName("a"), equalTo(1));
} |
@Override
public Statement createStatement() {
return new CircuitBreakerStatement();
} | @Test
void assertCreateStatement() {
assertThat(connection.createStatement(), instanceOf(CircuitBreakerStatement.class));
assertThat(connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY), instanceOf(CircuitBreakerStatement.class));
assertThat(connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT), instanceOf(CircuitBreakerStatement.class));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.