focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static FullyQualifiedKotlinType convert(FullyQualifiedJavaType javaType) {
FullyQualifiedKotlinType kotlinType = convertBaseType(javaType);
for (FullyQualifiedJavaType argument : javaType.getTypeArguments()) {
kotlinType.addTypeArgument(convert(argument));
}
return k... | @Test
void testPrimitiveByte() {
FullyQualifiedJavaType jt = new FullyQualifiedJavaType("byte");
FullyQualifiedKotlinType kt = JavaToKotlinTypeConverter.convert(jt);
assertThat(kt.getShortNameWithTypeArguments()).isEqualTo("Byte");
assertThat(kt.getImportList()).isEmpty();
} |
public void clear() throws Exception {
lock.lock();
try {
// Clear caches
blockCache.clear();
notFoundCache.clear();
// Clear file content
((Buffer) buffer).position(0);
long fileLength = randomAccessFile.length();
for (... | @Test
public void clear() throws Exception {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
// Build a new block.
Address to = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TEST... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldHandleTablesWithNoKeyField() {
// Given:
givenSourceTableWithSchema(SerdeFeatures.of(), SerdeFeatures.of());
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(K0, COL0, COL1),
ImmutableList.of(
new StringLiteral("ke... |
protected String decideSource(MappedMessage cef, RawMessage raw) {
// Try getting the host name from the CEF extension "deviceAddress"/"dvc"
final Map<String, Object> fields = cef.mappedExtensions();
if (fields != null && !fields.isEmpty()) {
final String deviceAddress = (String) fie... | @Test
public void decideSourceWithShortDeviceAddressReturnsExtensionValue() throws Exception {
final MappedMessage cefMessage = mock(MappedMessage.class);
when(cefMessage.mappedExtensions()).thenReturn(Collections.singletonMap("dvc", "128.66.23.42"));
final RawMessage rawMessage = new RawMe... |
private URI rebuildUri(String url, URI uri) {
final Optional<URI> optionalUri = formatUri(url, uri);
if (optionalUri.isPresent()) {
return optionalUri.get();
}
throw new IllegalArgumentException("Invalid url: " + url);
} | @Test
public void rebuildUriTest() {
Optional<Method> method = ReflectUtils.findMethod(RestTemplateInterceptor.class, "rebuildUri",
new Class[]{String.class, URI.class});
URI uri = createURI(url);
if (method.isPresent()) {
Optional<Object> uriNew = ReflectUtils
... |
@Override
public boolean canRescaleMaxParallelism(int desiredMaxParallelism) {
// Technically a valid parallelism value, but one that cannot be rescaled to
if (desiredMaxParallelism == JobVertex.MAX_PARALLELISM_DEFAULT) {
return false;
}
return !rescaleMaxValidator
... | @Test
void canRescaleMaxOutOfBounds() {
DefaultVertexParallelismInfo info = new DefaultVertexParallelismInfo(1, 1, ALWAYS_VALID);
assertThatThrownBy(() -> info.canRescaleMaxParallelism(-4))
.withFailMessage("not in valid bounds")
.isInstanceOf(IllegalArgumentExceptio... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testBuildDynamicArrayOfStaticStruct() throws ClassNotFoundException {
// This is a version of testDecodeStaticStructDynamicArray() that builds
// the decoding TypeReferences using inner types.
String rawInput =
"0x00000000000000000000000000000000000000000000... |
public String toJson() {
JsonObject details = new JsonObject();
details.addProperty(FIELD_LEVEL, level.toString());
JsonArray conditionResults = new JsonArray();
for (EvaluatedCondition condition : this.conditions) {
conditionResults.add(toJson(condition));
}
details.add("conditions", cond... | @Test
public void verify_json_when_there_is_no_condition() {
String actualJson = new QualityGateDetailsData(Measure.Level.OK, Collections.emptyList(), false).toJson();
JsonAssert.assertJson(actualJson).isSimilarTo("{" +
"\"level\":\"OK\"," +
"\"conditions\":[]" +
"}");
} |
public void awaitSuccessfulCompletion() throws InterruptedException, ExecutionException {
awaitUninterruptibly();
for (final Future<?> f : futures) {
f.get();
}
} | @Test
public void failsWhenAnyCallableThrowsException() throws Exception {
StatusEnsuringCallable firstTask = new StatusEnsuringCallable(false);
StatusEnsuringCallable secondTask = new StatusEnsuringCallable(false);
subject.submit(firstTask);
subject.submit(secondTask);
try... |
@Override
public QuoteCharacter getQuoteCharacter() {
return QuoteCharacter.QUOTE;
} | @Test
void assertGetQuoteCharacter() {
assertThat(dialectDatabaseMetaData.getQuoteCharacter(), is(QuoteCharacter.QUOTE));
} |
public LoginContext login() throws LoginException {
LoginContext tmpLoginContext = loginContextFactory.createLoginContext(this);
tmpLoginContext.login();
log.info("Successfully logged in.");
loginContext = tmpLoginContext;
subject = loginContext.getSubject();
expiringCred... | @Test
public void testRefreshWithMinPeriodIntrusion() throws Exception {
int numExpectedRefreshes = 1;
boolean clientReloginAllowedBeforeLogout = true;
Subject subject = new Subject();
final LoginContext mockLoginContext = mock(LoginContext.class);
when(mockLoginContext.getSu... |
@Override
public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) {
List<PurgeableAnalysisDto> result = new ArrayList<>();
for (PurgeableAnalysisDto snapshot : history) {
if (snapshot.getDate().before(before)) {
result.add(snapshot);
}
}
return result;
} | @Test
void shouldDeleteAllSnapshotsPriorToDate() {
Filter filter = new DeleteAllFilter(DateUtils.parseDate("2011-12-25"));
List<PurgeableAnalysisDto> toDelete = filter.filter(Arrays.asList(
DbCleanerTestUtils.createAnalysisWithDate("u1", "2010-01-01"),
DbCleanerTestUtils.createAnalysisWithDate("u... |
@ApiOperation(value = "Get a model", tags = { "Models" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the model was found and returned."),
@ApiResponse(code = 404, message = "Indicates the requested model was not found.")
})
@GetMapping(value = "/repository/... | @Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testGetModel() throws Exception {
Model model = null;
try {
Calendar now = Calendar.getInstance();
now.set(Calendar.MILLISECOND, 0);
processEng... |
public boolean hasViewPermissionDefined() {
return !viewConfig.equals(new ViewConfig());
} | @Test
public void shouldReturnTrueIfViewPermissionDefined() {
Authorization authorization = new Authorization(new ViewConfig(new AdminUser(new CaseInsensitiveString("baby"))));
assertThat(authorization.hasViewPermissionDefined(), is(true));
} |
public static FormValidation errorWithMarkup(String message) {
return _errorWithMarkup(message, Kind.ERROR);
} | @Test
public void testMessage() {
assertEquals("test msg", FormValidation.errorWithMarkup("test msg").getMessage());
} |
@Override
public boolean resize(int newSize) throws IOException {
lock.lock();
try {
if (super.resize(newSize)) {
this.lastEntry = lastEntryFromIndexFile();
return true;
} else
return false;
} finally {
lock.... | @Test
public void testResize() throws IOException {
boolean result = idx.resize(maxEntries * idx.entrySize());
assertFalse(result);
result = idx.resize(maxEntries / 2 * idx.entrySize());
assertTrue(result);
result = idx.resize(maxEntries * 2 * idx.entrySize());
asse... |
public Node parse() throws ScanException {
return E();
} | @Test
public void testFormattingInfo() throws Exception {
{
Parser<Object> p = new Parser("%45x");
Node t = p.parse();
FormattingNode witness = new SimpleKeywordNode("x");
witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE));
assertEquals(witness, t);
}
{
Parser... |
public MyNewIssuesNotification newMyNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new MyNewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newMyNewIssuesNotification_DetailsSupplier_getUserNameByUuid_fails_with_NPE_if_uuid_is_null() {
MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap());
DetailsSupplier detailsSupplier = readDetailsSupplier(underTest);
assertThatThrownBy(() -> detailsS... |
@Override
public void acceptPolicy(ApplicationId appId) {
} | @Test
public void testAcceptPolicy() {
assertEquals(SECURED, store.getState(appId));
store.acceptPolicy(appId, getMaximumPermissions(appId));
assertEquals(POLICY_VIOLATED, store.getState(appId));
} |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void new_code_period_does_not_rely_on_date_for_reference_branch_with_analysis_after_sonarqube_94() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
db.components().insertSnapshot... |
@VisibleForTesting
static void verifyImageMetadata(ImageMetadataTemplate metadata, Path metadataCacheDirectory)
throws CacheCorruptedException {
List<ManifestAndConfigTemplate> manifestsAndConfigs = metadata.getManifestsAndConfigs();
if (manifestsAndConfigs.isEmpty()) {
throw new CacheCorruptedExc... | @Test
public void testVerifyImageMetadata_unknownManifestType() {
ManifestAndConfigTemplate manifestAndConfig =
new ManifestAndConfigTemplate(
Mockito.mock(ManifestTemplate.class), new ContainerConfigurationTemplate());
ImageMetadataTemplate metadata =
new ImageMetadataTemplate(nul... |
public static RestSettingBuilder head() {
return all(HttpMethod.HEAD);
} | @Test
public void should_head_with_matcher() throws Exception {
server.resource("targets",
head("1").request(eq(query("name"), "foo")).response(header("ETag", "Moco"))
);
running(server, () -> {
HttpResponse httpResponse = helper.headForResponse(remoteUrl("/targe... |
static String readFileContents(String fileName) {
try {
File file = new File(fileName);
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Could not get " + fileName, e);
}
} | @Test
public void readFileContents()
throws IOException {
// given
String expectedContents = "Hello, world!\nThis is a test with Unicode ✓.";
String testFile = createTestFile(expectedContents);
// when
String actualContents = GcpDiscoveryStrategyFactory.readFileC... |
public static ProxyBackendHandler newInstance(final DatabaseType databaseType, final String sql, final SQLStatement sqlStatement,
final ConnectionSession connectionSession, final HintValueContext hintValueContext) throws SQLException {
if (sqlStatement instanceo... | @Test
void assertNewInstanceWithUnsupportedNonQueryDistSQLInTransaction() {
when(connectionSession.getTransactionStatus().isInTransaction()).thenReturn(true);
String sql = "CREATE SHARDING TABLE RULE t_order (STORAGE_UNITS(ms_group_0,ms_group_1), SHARDING_COLUMN=order_id, TYPE(NAME='hash_mod', PROPE... |
public static UserAgent parse(String userAgentString) {
return UserAgentParser.parse(userAgentString);
} | @Test
public void parseDesktopTest() {
final String uaStr = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1";
final UserAgent ua = UserAgentUtil.parse(uaStr);
assertEquals("Chrome", ua.getBrowser().toString());
assertEquals("14.0.835.163", ua.getVers... |
@CanIgnoreReturnValue
public <K1 extends K, V1 extends V> Caffeine<K1, V1> removalListener(
RemovalListener<? super K1, ? super V1> removalListener) {
requireState(this.removalListener == null,
"removal listener was already set to %s", this.removalListener);
@SuppressWarnings("unchecked")
C... | @Test
public void removalListener() {
RemovalListener<Object, Object> removalListener = (k, v, c) -> {};
var builder = Caffeine.newBuilder().removalListener(removalListener);
assertThat(builder.getRemovalListener(false)).isSameInstanceAs(removalListener);
assertThat(builder.build()).isNotNull();
} |
public static Map<String, String> loadProperties(final File propertiesFile) {
return loadProperties(ImmutableList.of(propertiesFile));
} | @Test
public void shouldThrowIfPropsFileContainsBlackListedProps() {
// Given:
givenPropsFileContains(
"java.some.disallowed.setting=something" + System.lineSeparator()
+ "java.not.another.one=v"
);
// When
final KsqlException e = assertThrows(
KsqlException.class,
... |
public static ProxyProvider.TypeSpec builder() {
return new ProxyProvider.Build();
} | @Test
void shouldNotCreateProxyProviderWithMissingRemoteHostInfo() {
ProxyProvider.Build builder = (ProxyProvider.Build) ProxyProvider.builder().type(ProxyProvider.Proxy.HTTP);
assertThatIllegalArgumentException()
.isThrownBy(builder::build)
.withMessage("Neither address nor host is specified");
} |
long getTotalFileLength(DataSplit split) {
return split.dataFiles().stream().map(DataFileMeta::fileSize).reduce(0L, Long::sum);
} | @Test
public void testTotalFileLength(@Mocked PaimonTable table) {
BinaryRow row1 = new BinaryRow(2);
BinaryRowWriter writer = new BinaryRowWriter(row1, 10);
writer.writeInt(0, 2000);
writer.writeInt(1, 4444);
writer.complete();
List<DataFileMeta> meta1 = new ArrayLi... |
static CounterResult fromJson(String json) {
return JsonUtil.parse(json, CounterResultParser::fromJson);
} | @Test
public void invalidValue() {
assertThatThrownBy(
() -> CounterResultParser.fromJson("{\"unit\":\"count\",\"value\":\"illegal\"}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse to a long value: value: \"illegal\"");
} |
@Deprecated
public B local(String local) {
this.local = local;
return getThis();
} | @Test
void local() {
InterfaceBuilder builder = new InterfaceBuilder();
builder.local("GreetingMock");
Assertions.assertEquals("GreetingMock", builder.build().getLocal());
} |
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 testToObject12() {
assertThrows(Exception.class, () -> {
JacksonUtils.toObj(new ByteArrayInputStream("{not_A}Json:String}".getBytes()),
TypeUtils.parameterize(Map.class, String.class, String.class));
});
} |
public static void removeMatching(Collection<String> values,
String... patterns) {
removeMatching(values, Arrays.asList(patterns));
} | @Test
public void testRemoveMatchingWithNoPatterns() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values);
assertTrue(values.contains("A"));
} |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.ip == null ? 0 : this.ip.hashCode());
result = prime * result + this.port;
return result;
} | @Test
public void testEqualsHashCode() {
final Endpoint ep1 = new Endpoint("192.168.1.1", 8080);
final Endpoint ep2 = new Endpoint("192.168.1.1", 8080);
assertEquals(ep1, ep2);
assertEquals(ep1.hashCode(), ep2.hashCode());
} |
KettleValidatorException assertNumeric( ValueMetaInterface valueMeta,
Object valueData,
Validation field ) throws KettleValueException {
if ( valueMeta.isNumeric() || containsOnlyDigits( valueMeta.getString( valueData ) ) ) {
... | @Test
public void assertNumeric_StringWithDigits() throws Exception {
ValueMetaString metaString = new ValueMetaString( "string-with-digits" );
assertNull( "Strings with digits are allowed", validator.assertNumeric( metaString, "123", new Validation() ) );
} |
public static String findAddress(List<NodeAddress> addresses, NodeAddressType preferredAddressType) {
if (addresses == null) {
return null;
}
Map<String, String> addressMap = addresses.stream()
.collect(Collectors.toMap(NodeAddress::getType, NodeAddress::getAddres... | @Test
public void testFindAddressReturnsExternalAddress() {
String address = NodeUtils.findAddress(ADDRESSES, null);
assertThat(address, is("my.external.address"));
} |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(!session.getClient().setFileType(FTPClient.BINARY_FILE_TYPE)) {
throw new FTPException(session.getClient().getRep... | @Test
@Ignore
public void testWriteRangeEndFirst() throws Exception {
final FTPWriteFeature feature = new FTPWriteFeature(session);
final Path test = new Path(new FTPWorkdirService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final byte[] ... |
@Override
protected int compareFirst(final Path p1, final Path p2) {
// Version with no duplicate flag first
final int duplicateComparison = Boolean.compare(!p1.attributes().isDuplicate(), !p2.attributes().isDuplicate());
if(0 == duplicateComparison) {
final int timestampComparis... | @Test
public void testCompareFirst() {
final Path p1 = new Path("/a", EnumSet.of(Path.Type.file));
final Path p2 = new Path("/b", EnumSet.of(Path.Type.file));
assertEquals(0, new VersionsComparator(true).compareFirst(p1, p2));
p1.attributes().setDuplicate(true);
assertEquals(... |
public static Instant toInstant(Date date) {
return null == date ? null : date.toInstant();
} | @Test
public void toInstantTest() {
final LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME);
Instant instant = DateUtil.toInstant(localDateTime);
assertEquals("2017-05-06T00:30:00Z", instant.toString());
final LocalDate localDate = localDateTime.toLocalD... |
public static <InputT> Builder<InputT> withoutHold(AppliedPTransform<?, ?, ?> transform) {
return new Builder(transform, BoundedWindow.TIMESTAMP_MAX_VALUE);
} | @Test
public void withAdditionalOutputProducedOutputs() {
TransformResult<Integer> result =
StepTransformResult.<Integer>withoutHold(transform)
.withAdditionalOutput(OutputType.PCOLLECTION_VIEW)
.build();
assertThat(result.getOutputTypes(), containsInAnyOrder(OutputType.PCOLLE... |
public Type parse(final String schema) {
try {
final TypeContext typeContext = parseTypeContext(schema);
return getType(typeContext);
} catch (final ParsingException e) {
throw new KsqlStatementException(
"Failed to parse schema",
"Failed to parse: " + schema,
sch... | @Test
public void shouldGetTypeFromDecimal() {
// Given:
final String schemaString = "DECIMAL(2, 1)";
// When:
final Type type = parser.parse(schemaString);
// Then:
assertThat(type, is(new Type(SqlTypes.decimal(2, 1))));
} |
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data.getBytes(encoding));
} finally {
if (null != os) {
os.close();
... | @Test
public void testWriteStringToFile() throws Exception {
File file = new File(testRootDir, "testWriteStringToFile");
assertTrue(!file.exists());
IOTinyUtils.writeStringToFile(file, "testWriteStringToFile", StandardCharsets.UTF_8.name());
assertTrue(file.exists());
} |
public static <T extends ScanTask> List<ScanTaskGroup<T>> planTaskGroups(
List<T> tasks, long splitSize, int lookback, long openFileCost) {
return Lists.newArrayList(
planTaskGroups(CloseableIterable.withNoopClose(tasks), splitSize, lookback, openFileCost));
} | @Test
public void testTaskGroupPlanningCorruptedOffset() {
DataFile dataFile =
DataFiles.builder(TestBase.SPEC)
.withPath("/path/to/data-a.parquet")
.withFileSizeInBytes(10)
.withPartitionPath("data_bucket=0")
.withRecordCount(1)
.withSplitOffset... |
@Override
public String[] getCompressionProviderNames() {
ArrayList<String> providerNames = new ArrayList<String>();
List<PluginInterface> providers = getPlugins();
if ( providers != null ) {
for ( PluginInterface plugin : providers ) {
try {
CompressionProvider provider = PluginR... | @Test
public void getCoreProviderNames() {
@SuppressWarnings( "serial" )
final HashMap<String, Boolean> foundProvider = new HashMap<String, Boolean>() {
{
put( "None", false );
put( "Zip", false );
put( "GZip", false );
put( "Snappy", false );
put( "Hadoop-snappy"... |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithSelectStatementForCurrentUser() {
MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class);
when(selectStatement.getFrom()).thenReturn(Optional.empty());
ProjectionsSegment projectionsSegment = mock(ProjectionsSegment.class);
when(projections... |
public static int hashToIndex(int hash, int length) {
checkPositive("length", length);
if (hash == Integer.MIN_VALUE) {
return 0;
}
return abs(hash) % length;
} | @Test(expected = IllegalArgumentException.class)
public void hashToIndex_whenItemCountZero() {
hashToIndex(Integer.MIN_VALUE, 0);
} |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeDisallowLessRestrictiveMode() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
"{'tomerge': {'type': 'STRING','value': 'hello', 'mode': 'MUTABLE_ON_START'}}");
Map<String, ParamDefinition> paramsToMerge =
parsePa... |
protected void validateImpl(OtaPackageInfo otaPackageInfo) {
validateString("OtaPackage title", otaPackageInfo.getTitle());
if (otaPackageInfo.getTenantId() == null) {
throw new DataValidationException("OtaPackage should be assigned to tenant!");
} else {
if (!getTenantS... | @Test
void testValidateNameInvocation() {
OtaPackageInfo otaPackageInfo = new OtaPackageInfo();
otaPackageInfo.setTitle("fw");
otaPackageInfo.setVersion("1.0");
otaPackageInfo.setType(OtaPackageType.FIRMWARE);
otaPackageInfo.setTenantId(tenantId);
validator.validateI... |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
trackTime(nowNs);
int workCount = 0;
workCount += processTimers(nowNs);
if (!asyncClientCommandInFlight)
{
workCount += clientCommandAdapter.receive();
}
workCount += drainComm... | @Test
void shouldUseExistingChannelEndpointOnAddSubscriptionWithSameTagId()
{
final long id1 = driverProxy.addSubscription(CHANNEL_4000_TAG_ID_1, STREAM_ID_1);
final long id2 = driverProxy.addSubscription(CHANNEL_TAG_ID_1, STREAM_ID_1);
driverConductor.doWork();
driverConductor.... |
@PostMapping("/admin")
public Object createAdminUser(@RequestParam(required = false) String password) {
if (AuthSystemTypes.NACOS.name().equalsIgnoreCase(authConfigs.getNacosAuthSystemType())) {
if (iAuthenticationManager.hasGlobalAdminRole()) {
return RestResultUtils.failed(Http... | @Test
void testCreateAdminUser1() {
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
when(authenticationManager.hasGlobalAdminRole()).thenReturn(true);
RestResult<String> result = (RestResult<String>) userController.createAdminUser("test");
... |
public static String getTypeStrFromProto(Descriptors.FieldDescriptor desc) {
switch (desc.getJavaType()) {
case INT:
return "Integer";
case LONG:
return "Long";
case STRING:
return "String";
case FLOAT:
return "Float";
case DOUBLE:
return "Double... | @Test
public void testGetTypeStrFromProto() throws Exception {
URL jarFile = getClass().getClassLoader().getResource("complex_types.jar");
ClassLoader clsLoader = ProtoBufCodeGenMessageDecoder.loadClass(jarFile.getPath());
Descriptors.Descriptor desc = ProtoBufCodeGenMessageDecoder.getDescriptorForProtoCl... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnInvalidBatchFinderMethodBatchParamParameterType() {
@RestLiCollection(name = "batchFinderWithInvalidBatchParamType")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord>
{
@BatchFinder(value = "batchFinde... |
@Override
public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) {
Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:"
+ " URI path should not be null");
if (checkCOSCredentials(conf)) {
try {
return COSUnderFileSystem.createInstance(new ... | @Test
public void createInstanceWithoutCredentials() {
Configuration.unset(PropertyKey.COS_ACCESS_KEY);
Configuration.unset(PropertyKey.COS_SECRET_KEY);
Configuration.unset(PropertyKey.COS_REGION);
Configuration.unset(PropertyKey.COS_APP_ID);
mAlluxioConf = Configuration.global();
mConf = Unde... |
@Override
public CiConfiguration loadConfiguration() {
String pr = system.envVariable("TRAVIS_PULL_REQUEST");
String revision;
if (isBlank(pr) || "false".equals(pr)) {
revision = system.envVariable("TRAVIS_COMMIT");
} else {
revision = system.envVariable("TRAVIS_PULL_REQUEST_SHA");
}
... | @Test
public void loadConfiguration_of_branch() {
setEnvVariable("CI", "true");
setEnvVariable("TRAVIS", "true");
setEnvVariable("TRAVIS_COMMIT", "abd12fc");
setEnvVariable("TRAVIS_PULL_REQUEST", "false");
setEnvVariable("TRAVIS_PULL_REQUEST_SHA", "");
assertThat(underTest.loadConfiguration()... |
@Override
public PageData<WidgetTypeInfo> findSystemWidgetTypes(WidgetTypeFilter widgetTypeFilter, PageLink pageLink) {
boolean deprecatedFilterEnabled = !DeprecatedFilter.ALL.equals(widgetTypeFilter.getDeprecatedFilter());
boolean deprecatedFilterBool = DeprecatedFilter.DEPRECATED.equals(widgetType... | @Test
public void testFindSystemWidgetTypesForSameName() throws InterruptedException {
List<WidgetTypeDetails> sameNameList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Thread.sleep(2);
var widgetType = saveWidgetType(TenantId.SYS_TENANT_ID, "widgetName");
... |
public ExportMessagesCommand buildWithSearchOnly(Search search, ResultFormat resultFormat) {
Query query = queryFrom(search);
return builderFrom(resultFormat)
.timeRange(resultFormat.timerange().orElse(toAbsolute(query.timerange())))
.queryString(queryStringFrom(search, ... | @Test
void searchWithMultipleQueriesLeadsToExceptionIfNoSearchTypeProvided() {
Search s = searchWithQueries(org.graylog.plugins.views.search.TestData.validQueryBuilder().build(), org.graylog.plugins.views.search.TestData.validQueryBuilder().build());
assertThatExceptionOfType(ExportException.class)... |
public boolean isIp6() {
return address.isIp6();
} | @Test
public void testIsIp6() {
IpPrefix ipPrefix;
// IPv4
ipPrefix = IpPrefix.valueOf("0.0.0.0/0");
assertFalse(ipPrefix.isIp6());
// IPv6
ipPrefix = IpPrefix.valueOf("::/0");
assertTrue(ipPrefix.isIp6());
} |
@Override
public String attemptRequest() throws RemoteServiceException {
evaluateState();
if (state == State.OPEN) {
// return cached response if the circuit is in OPEN state
return this.lastFailureResponse;
} else {
// Make the API request if the circuit is not OPEN
try {
... | @Test
void testApiResponses() throws RemoteServiceException {
RemoteService mockService = new RemoteService() {
@Override
public String call() throws RemoteServiceException {
return "Remote Success";
}
};
var circuitBreaker = new DefaultCircuitBreaker(mockService, 1, 1, 100);
... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDa... | @Test
void assertPreciseDoShardingBeyondTheLastOne() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3", "t_order_4", "t_order_5");
assertThat(shardingAlgorithm.doSharding(availableTargetNames,
new PreciseShardingValue<>("t_order", ... |
public static Optional<ExplicitConstructorInvocationStmt> getExplicitConstructorInvocationStmt(final BlockStmt body) {
return body.getStatements().stream()
.filter(ExplicitConstructorInvocationStmt.class::isInstance)
.map(ExplicitConstructorInvocationStmt.class::cast)
... | @Test
void getExplicitConstructorInvocationStmt() {
BlockStmt body = new BlockStmt();
Optional<ExplicitConstructorInvocationStmt> retrieved = CommonCodegenUtils.getExplicitConstructorInvocationStmt(body);
assertThat(retrieved).isNotNull();
assertThat(retrieved).isNotPresent();
... |
@Override
public ExportResult<ContactsModelWrapper> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) {
if (exportInformation.isPresent()) {
StringPaginationToken stringPaginationToken = (StringPaginationToken)
exportInformation.get().getPagina... | @Test
public void exportFirstPage() throws IOException {
setUpSinglePersonResponse();
// Looking at first page, with at least one page after it
listConnectionsResponse.setNextPageToken(NEXT_PAGE_TOKEN);
ExportResult<ContactsModelWrapper> result = contactsService.export(UUID.randomUUID(), null, Optio... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testJoinUnnest()
{
analyze("SELECT * FROM (VALUES array[2, 2]) a(x) CROSS JOIN UNNEST(x)");
analyze("SELECT * FROM (VALUES array[2, 2]) a(x) LEFT OUTER JOIN UNNEST(x) ON true");
analyze("SELECT * FROM (VALUES array[2, 2]) a(x) RIGHT OUTER JOIN UNNEST(x) ON true");
... |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsTimerValuesDefault() {
final Timer timer = timer();
when(logger.isInfoEnabled(marker)).thenReturn(true);
infoReporter().report(map(),
map(),
map(),
map(),
map("test.another.timer", timer));
ver... |
public static String getWebServiceName(NetworkService networkService) {
if (isWebService(networkService)
&& networkService.getServiceContext().getWebServiceContext().hasSoftware()) {
return Ascii.toLowerCase(
networkService.getServiceContext().getWebServiceContext().getSoftware().getName());... | @Test
public void getWebServiceName_whenWebServiceWithSoftware_returnsWebServiceName() {
assertThat(
NetworkServiceUtils.getWebServiceName(
NetworkService.newBuilder()
.setNetworkEndpoint(forIpAndPort("127.0.0.1", 8080))
.setServiceName("http")
... |
@Override
public void configure(ResourceGroup group, SelectionContext<VariableMap> context)
{
Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry = getMatchingSpec(group, context);
configureGroup(group, entry.getValue());
} | @SuppressWarnings("SimplifiedTestNGAssertion")
@Test
public void testConfiguration() throws IOException
{
ResourceGroupConfigurationManager<VariableMap> manager = parse("resource_groups_config.json");
ResourceGroupId globalId = new ResourceGroupId("global");
ResourceGroup global = ne... |
protected List<E> list(CriteriaQuery<E> criteria) throws HibernateException {
return currentSession().createQuery(requireNonNull(criteria)).getResultList();
} | @Test
void returnsUniqueListsFromJpaCriteriaQueries() throws Exception {
when(session.createQuery(criteriaQuery)).thenReturn(query);
when(query.getResultList()).thenReturn(Collections.singletonList("woo"));
assertThat(dao.list(criteriaQuery))
.containsOnly("woo");
} |
static Map<String, String> fromSystemProperties()
{
final HashMap<String, String> result = new HashMap<>();
final Properties properties = System.getProperties();
for (final Map.Entry<Object, Object> entry : properties.entrySet())
{
result.put((String)entry.getKey(), (Stri... | @Test
void shouldReturnAllSystemProperties()
{
final Map<String, String> values = fromSystemProperties();
assertNotEquals(Collections.emptySet(), values);
} |
@Override
public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) {
log.debug(
"sort catalogue tree based on first letter. catalogueTree: {}, sortTypeEnum: {}",
catalogueTree,
sortTypeEnum);
Collator collator = Collator.ge... | @Test
public void sortDescTest() {
SortTypeEnum sortTypeEnum = SortTypeEnum.DESC;
List<Catalogue> catalogueTree = Lists.newArrayList();
Catalogue catalogue = new Catalogue();
catalogue.setId(1);
catalogue.setName("测试目录");
catalogue.setCreateTime(LocalDateTime.of(2024,... |
private List<Instance> getAllInstancesFromIndex(Service service) {
Set<Instance> result = new HashSet<>();
Set<String> clusters = new HashSet<>();
for (String each : serviceIndexesManager.getAllClientsRegisteredService(service)) {
Optional<InstancePublishInfo> instancePublishInfo = g... | @Test
void testGetAllInstancesFromIndex() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<ServiceStorage> serviceStorageClass = ServiceStorage.class;
Method getAllInstancesFromIndex = serviceStorageClass.getDeclaredMethod("getAllInstancesFromIndex", Service.cl... |
public Optional<String> getUserIdAttribute() {
final Map<Object, Object> attributes = getAttributes();
if (attributes == null) {
return Optional.empty();
}
final Object sessionId;
// A subject can have more than one principal. If that's the case, the user ID is requ... | @Test
public void noPrincipal() {
assertThat(new MongoDbSession(fields).getUserIdAttribute()).isEmpty();
} |
@Override
public void returnLogicalSlot(LogicalSlot logicalSlot) {
LOG.debug("Returning logical slot to shared slot ({})", physicalSlotRequestId);
Preconditions.checkState(
state != State.RELEASED, "The shared slot has already been released.");
Preconditions.checkState(!logi... | @Test
void testReturnLogicalSlotRejectsUnknownSlot() {
assertThatThrownBy(
() -> {
final TestingPhysicalSlot physicalSlot =
TestingPhysicalSlot.builder().build();
final SharedSlot sharedSlot =... |
@SuppressWarnings("unchecked")
public static Object getMockObject(ExtensionDirector extensionDirector, String mockService, Class serviceType) {
boolean isDefault = ConfigUtils.isDefault(mockService);
if (isDefault) {
mockService = serviceType.getName() + "Mock";
}
Class<... | @Test
void testGetMockObject() {
Assertions.assertEquals(
"",
MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", String.class));
Assertions.assertThrows(
IllegalStateException... |
@Override
public String getResourceId() {
if (resourceId == null) {
initResourceId();
}
return resourceId;
} | @Test
public void getResourceIdTest() throws SQLException, NoSuchFieldException, IllegalAccessException {
// Disable 'DataSourceProxy.tableMetaExecutor' to prevent unit tests from being affected
Field enableField = TableMetaCacheFactory.class.getDeclaredField("ENABLE_TABLE_META_CHECKER_ENABLE");
... |
public void seek(long position) throws IOException {
final int block = MathUtils.checkedDownCast(position / segmentSize);
final int positionInBlock = (int) (position % segmentSize);
if (position < 0
|| block >= numBlocksTotal
|| (block == numBlocksTotal - 1 && po... | @Test
void testSeek() throws Exception {
final int PAGE_SIZE = 16 * 1024;
final int NUM_RECORDS = 120000;
// integers across 7.x pages (7 pages = 114.688 bytes, 8 pages = 131.072 bytes)
try (IOManager ioManager = new IOManagerAsync()) {
MemoryManager memMan =
... |
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize) throws NacosException {
return getServicesOfServer(pageNo, pageSize, Constants.DEFAULT_GROUP);
} | @Test
void testGetServicesOfServer4() throws NacosException {
//given
int pageNo = 1;
int pageSize = 10;
String groupName = "group1";
AbstractSelector selector = new AbstractSelector("aaa") {
@Override
public String getType() {
... |
public boolean similarTo(ClusterStateBundle other) {
if (!baselineState.getClusterState().similarToIgnoringInitProgress(other.baselineState.getClusterState())) {
return false;
}
if (clusterFeedIsBlocked() != other.clusterFeedIsBlocked()) {
return false;
}
... | @Test
void similarity_test_considers_cluster_feed_block_state() {
var nonBlockingBundle = createTestBundle(false);
var blockingBundle = createTestBundleWithFeedBlock("foo");
var blockingBundleWithOtherDesc = createTestBundleWithFeedBlock("bar");
assertFalse(nonBlockingBundle.similar... |
public static TableSchema toTableSchema(Schema schema) {
return new TableSchema().setFields(toTableFieldSchema(schema));
} | @Test
public void testToTableSchema_array_row() {
TableSchema schema = toTableSchema(ARRAY_ROW_TYPE);
assertThat(schema.getFields().size(), equalTo(1));
TableFieldSchema field = schema.getFields().get(0);
assertThat(field.getName(), equalTo("rows"));
assertThat(field.getType(), equalTo(StandardSQ... |
public void allocate( int nrfields ) {
fieldName = new String[nrfields];
} | @Test
public void testAllocate() {
CheckSumMeta checkSumMeta = new CheckSumMeta();
Random random = new Random();
int maxAllocation = 50;
// Initially the array should exist but be empty
String[] fieldNames = checkSumMeta.getFieldName();
assertNotNull( fieldNames );
assertEquals( 0, fieldN... |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void overridesArrayWithIndicesReverse() throws Exception {
System.setProperty("dw.type[0]", "overridden");
final Example example = factory.build(configurationSourceProvider, validFile);
assertThat(example.getType())
.containsExactly("overridden", "wizard");
} |
@Override
public Long createCouponTemplate(CouponTemplateCreateReqVO createReqVO) {
// 校验商品范围
validateProductScope(createReqVO.getProductScope(), createReqVO.getProductScopeValues());
// 插入
CouponTemplateDO couponTemplate = CouponTemplateConvert.INSTANCE.convert(createReqVO)
... | @Test
public void testCreateCouponTemplate_success() {
// 准备参数
CouponTemplateCreateReqVO reqVO = randomPojo(CouponTemplateCreateReqVO.class,
o -> o.setProductScope(randomEle(PromotionProductScopeEnum.values()).getScope())
.setValidityType(randomEle(CouponTempl... |
public static synchronized void setCache(Map<Pair<String, String>, String> cache) {
CpeEcosystemCache.cache = cache;
CpeEcosystemCache.changed = new HashMap<>();
} | @Test
public void testSetCache() {
Map<Pair<String, String>, String> map = new HashMap<>();
CpeEcosystemCache.setCache(map);
assertTrue(CpeEcosystemCache.isEmpty());
map = new HashMap<>();
Pair<String, String> key = new Pair<>("apache", "zookeeper");
map.put(key, "ja... |
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) {
V pluginVersion = parseVersion(actualVersion);
// Treat a single version "1.4" as a left bound, equivalent to "[1.4,)"
if (acceptableVersionRange.matches(VERSION_REGEX)) {
return ge(pluginVersion, parseVersion(acc... | @Test
public void testMinimumBound_high() {
Assert.assertTrue(checker.compatibleVersion("2.3", "2.4"));
Assert.assertTrue(checker.compatibleVersion("2.3", "4.0"));
} |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetStreamsConfigProducerPrefixedProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(
Collections.singletonMap(
StreamsConfig.PRODUCER_PREFIX + ProducerConfig.BUFFER_MEMORY_CONFIG, "1024"));
assertThat(ksqlConfig.getKsqlStreamConfigProps()
.get(S... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
@Category(ValidatesRunner.class)
public void testReshuffleAfterFixedWindows() {
PCollection<KV<String, Integer>> input =
pipeline
.apply(
Create.of(ARBITRARY_KVS)
.withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())))
.apply(Win... |
List<PickleStepDefinitionMatch> getMatches() {
return matches;
} | @Test
void can_report_ambiguous_step_definitions() {
Feature feature = TestFeatureParser.parse("" +
"Feature: Test feature\n" +
" Scenario: Test scenario\n" +
" Given I have 4 cukes in my belly\n");
Step mockPickleStep = feature.getPickles().get(... |
@Override
public ObjectNode encode(FlowInfo info, CodecContext context) {
checkNotNull(info, "FlowInfo cannot be null");
ObjectNode result = context.mapper().createObjectNode()
.put(FLOW_TYPE, info.flowType())
.put(DEVICE_ID, info.deviceId().toString())
... | @Test
public void testEncode() {
StatsInfo statsInfo = new DefaultStatsInfo.DefaultBuilder()
.withStartupTime(LONG_VALUE)
.withFstPktArrTime(LONG_VALUE)
.withLstPktOffset(INTEGER_VALUE)
... |
public void incrementIndex(int task_index) {
moveTask(task_index, INCREMENT_INDEX);
} | @Test
public void shouldIncrementIndexOfGivenTask() {
Tasks tasks = new Tasks();
AntTask task1 = antTask("b1", "t1", "w1");
tasks.add(task1);
AntTask task2 = antTask("b2", "t2", "w2");
tasks.add(task2);
AntTask task3 = antTask("b3", "t3", "w3");
tasks.add(task... |
@Override
public RSet<V> get(final K key) {
String keyHash = keyHash(key);
final String setName = getValuesName(keyHash);
return new RedissonSet<V>(codec, commandExecutor, setName, null) {
@Override
public RFuture<Boolean> addAsync(V value) {
... | @Test
public void testGetRemove() {
RSetMultimap<String, Integer> multimap1 = redisson.getSetMultimap("myMultimap1");
Set<Integer> one = multimap1.get("1");
Set<Integer> two = multimap1.get("2");
Set<Integer> four = multimap1.get("4");
one.add(1);
one.add(2);
... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testAbaloneLS() {
test(Loss.ls(), "abalone", Abalone.formula, Abalone.train, 2.2159);
} |
@Override
public org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>> get() {
return new org.apache.kafka.streams.kstream.Transformer<KIn, VIn, Iterable<KeyValue<KOut, VOut>>>() {
private final org.apache.kafka.streams.kstream.Transformer<KIn, VIn, KeyValue<KOu... | @Test
public void shouldCallTransformOfAdaptedTransformerAndReturnEmptyIterable() {
when(transformerSupplier.get()).thenReturn(transformer);
when(transformer.transform(key, value)).thenReturn(null);
final TransformerSupplierAdapter<String, String, Integer, Integer> adapter =
new... |
@Override
public Object getValue(final int columnIndex, final Class<?> type) throws SQLException {
if (boolean.class == type) {
return resultSet.getBoolean(columnIndex);
}
if (byte.class == type) {
return resultSet.getByte(columnIndex);
}
if (short.cla... | @Test
void assertGetValueByShort() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.getShort(1)).thenReturn((short) 1);
assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, short.class), is((short) 1));
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
return new BoxAttributesFinderFeature(session, fileid).find(file, listener) != PathAttributes.EMPTY;
}
... | @Test
public void testFindNotFound() throws Exception {
final BoxFileidProvider fileid = new BoxFileidProvider(session);
assertFalse(new BoxFindFeature(session, fileid).find(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file))));
} |
public static SqlSelect parseSelect(String statement) {
SqlNode sqlNode = null;
try {
sqlNode = getCalciteParser(statement).parseQuery();
} catch (SqlParseException e) {
LOG.error("Statements can not be parsed. {} \n {}", statement, e);
throw new ParseExceptio... | @Test
public void testCalciteRelNode() {
SqlSelect parse =
TransformParser.parseSelect(
"select SUBSTR(id, 1) as uniq_id, * from tb where id is not null");
CalciteSchema rootSchema = CalciteSchema.createRootSchema(true);
Map<String, Object> operand = ... |
public DirectoryEntry lookUp(
File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
DirectoryEntry result = lookUp(workingDirectory, path, options, 0);
if (result == null) {
// an intermediate file in the path... | @Test
public void testLookup_relative_emptyPath() throws IOException {
assertExists(lookup(""), "/", "work");
} |
public boolean stripLastChar() {
return stripLastChar;
} | @Test
public void testStripLastChar() {
String testString = "abc"; // encoded as 1|00000|00, 001|00010, exactly two bytes
MetaStringEncoder encoder = new MetaStringEncoder('_', '$');
MetaString encodedMetaString = encoder.encode(testString);
assertFalse(encodedMetaString.stripLastChar());
testStr... |
@Override
public List<String> getInsertParamsValue() {
List<SQLInsertStatement.ValuesClause> valuesList = ast.getValuesList();
List<String> list = new ArrayList<>();
for (SQLInsertStatement.ValuesClause m : valuesList) {
String values = m.toString().replace("VALUES", "").trim();
... | @Test
public void testGetInsertParamsValue() {
String sql = "INSERT INTO t(a) VALUES (?)";
SQLStatement ast = getSQLStatement(sql);
SqlServerInsertRecognizer recognizer = new SqlServerInsertRecognizer(sql, ast);
Assertions.assertEquals("?", recognizer.getInsertParamsValue().get(0));
... |
public static String getContent(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
throw new IllegalArgumentException("content does not contain separator");
}
return content.substring(index + 1);
} | @Test
void testGetContent() {
String content = "aa" + WORD_SEPARATOR + "bbb";
String content1 = ContentUtils.getContent(content);
assertEquals("bbb", content1);
} |
public static AgentRuntimeInfo fromServer(Agent agent, boolean registeredAlready, String location,
Long freeDiskSpace, String operatingSystem ) {
if (isEmpty(location)) {
throw new RuntimeException("Agent should not register without installation path.")... | @Test
public void shouldThrowOnEmptyLocation() {
assertThatThrownBy(() -> AgentRuntimeInfo.fromServer(new Agent("uuid", "localhost", "127.0.0.1"), false, "", 0L, "linux"))
.isExactlyInstanceOf(RuntimeException.class)
.hasMessageContaining("Agent should not register without in... |
public TolerantLongComparison isWithin(long tolerance) {
return new TolerantLongComparison() {
@Override
public void of(long expected) {
Long actual = LongSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expected);... | @Test
public void isWithinOf() {
assertThat(20000L).isWithin(0L).of(20000L);
assertThat(20000L).isWithin(1L).of(20000L);
assertThat(20000L).isWithin(10000L).of(20000L);
assertThat(20000L).isWithin(10000L).of(30000L);
assertThat(Long.MIN_VALUE).isWithin(1L).of(Long.MIN_VALUE + 1);
assertThat(Lo... |
public static boolean transferLeadership(final ThreadId id, final long logIndex) {
final Replicator r = (Replicator) id.lock();
if (r == null) {
return false;
}
// dummy is unlock in _transfer_leadership
return r.transferLeadership(logIndex);
} | @Test
public void testTransferLeadership() {
final Replicator r = getReplicator();
this.id.unlock();
assertEquals(0, r.getTimeoutNowIndex());
assertTrue(Replicator.transferLeadership(this.id, 11));
assertEquals(11, r.getTimeoutNowIndex());
assertNull(r.getTimeoutNowIn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.