focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void updateConfig(ConfigSaveReqVO updateReqVO) {
// 校验自己存在
validateConfigExists(updateReqVO.getId());
// 校验参数配置 key 的唯一性
validateConfigKeyUnique(updateReqVO.getId(), updateReqVO.getKey());
// 更新参数配置
ConfigDO updateObj = ConfigConvert.INSTANCE.convert... | @Test
public void testUpdateConfig_success() {
// mock 数据
ConfigDO dbConfig = randomConfigDO();
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
ConfigSaveReqVO reqVO = randomPojo(ConfigSaveReqVO.class, o -> {
o.setId(dbConfig.getId()); // 设置更新的 ID
... |
@Deprecated
public String createToken(Authentication authentication) {
return createToken(authentication.getName());
} | @Test
void testInvalidSecretKey() {
assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
} |
public long stamp() {
long s = stamp;
if (s == 0) {
s = calculateStamp(partitions);
stamp = s;
}
return s;
} | @Test
public void test_getStamp() throws Exception {
InternalPartition[] partitions = createRandomPartitions();
PartitionTableView table = new PartitionTableView(partitions);
assertEquals(calculateStamp(partitions), table.stamp());
} |
public void updateConfig(DynamicConfigEvent event) {
if (!isTargetConfig(event)) {
return;
}
if (updateWithDefaultMode(event)) {
afterUpdateConfig();
}
} | @Test
public void testRegistrySwitchConfig() {
RegistryConfigResolver configResolver = new OriginRegistrySwitchConfigResolver();
final DynamicConfigEvent event = Mockito.mock(DynamicConfigEvent.class);
Mockito.when(event.getContent()).thenReturn("origin.__registry__.needClose: true");
... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testInfoSlash() throws JSONException, Exception {
// test with trailing "/" to make sure acts same as without slash
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("info/").accept(MediaType.APPLICATION_JSON)
.get(ClientR... |
public static void verifyKafkaBrokers(Properties props) {
//ensure bootstrap.servers is assigned
String brokerList = getString(BOOTSTRAP_SERVERS_CONFIG, props); //usually = "bootstrap.servers"
String[] brokers = brokerList.split(",");
for (String broker : brokers) {
checkAr... | @Test
public void verifyKafkaBrokers_noPort() {
Properties props = new Properties();
props.setProperty("bootstrap.servers", "localhost");
assertThrows(
IllegalArgumentException.class,
() -> verifyKafkaBrokers(props)
);
} |
@Override
public SmsTemplateDO getSmsTemplate(Long id) {
return smsTemplateMapper.selectById(id);
} | @Test
public void testGetSmsTemplate() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO();
smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbSmsTemplate.getId();
// 调用
SmsTemplateDO smsTemplate = smsTemplateService... |
Image getIcon(String pluginId) {
return getVersionedElasticAgentExtension(pluginId).getIcon(pluginId);
} | @Test
public void shouldCallTheVersionedExtensionBasedOnResolvedVersion() {
when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ELASTIC_AGENT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success("{\"content_type\":\"image/png\",\"data\":\"Zm9vYmEK\"}"));
extension.g... |
public Optional<String> evaluate(Number toEvaluate) {
return interval.isIn(toEvaluate) ? Optional.of(binValue) : Optional.empty();
} | @Test
void evaluateClosedClosed() {
KiePMMLDiscretizeBin kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(null, 20,
CLOSURE.CLOSED_CLOSED));
Optional<String> retrieved = kiePMMLDiscretiz... |
public void checkExistsName(final String name) {
if (baseballTeamRepository.existsByNameIn(List.of(name))) {
throw new DuplicateTeamNameException();
}
} | @Test
void 이미_존재하는_이름의_구단을_중복_저장할_수_없다() {
// given
String duplicateName = "두산 베어스";
// when
// then
assertThatThrownBy(() -> createBaseballTeamService.checkExistsName(duplicateName))
.isInstanceOf(DuplicateTeamNameException.class);
} |
public static <R> R callStaticMethod(
ClassLoader classLoader,
String fullyQualifiedClassName,
String methodName,
ClassParameter<?>... classParameters) {
Class<?> clazz = loadClass(classLoader, fullyQualifiedClassName);
return callStaticMethod(clazz, methodName, classParameters);
} | @Test
public void callStaticMethodReflectively_wrapsCheckedException() {
try {
ReflectionHelpers.callStaticMethod(ExampleDescendant.class, "staticThrowCheckedException");
fail("Expected exception not thrown");
} catch (RuntimeException e) {
assertThat(e.getCause()).isInstanceOf(TestException... |
@Override
public Optional<IndexSetConfig> findOne(DBQuery.Query query) {
return Optional.ofNullable(collection.findOne(query));
} | @Test
@MongoDBFixtures("MongoIndexSetServiceTest.json")
public void findOne() throws Exception {
final Optional<IndexSetConfig> config3 = indexSetService.findOne(DBQuery.is("title", "Test 2"));
assertThat(config3).isPresent();
assertThat(config3.get().id()).isEqualTo("57f3d721a43c2d59cb7... |
public static long getLastModified(URL resourceURL) {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final... | @Test
void getLastModifiedReturnsTheLastModifiedTimeOfAFile(@TempDir Path tempDir) throws Exception {
final URL url = tempDir.toUri().toURL();
final long lastModified = ResourceURL.getLastModified(url);
assertThat(lastModified)
.isPositive()
.isEqualTo(tempDi... |
public NugetPackage parse(InputStream stream) throws NuspecParseException {
try {
final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
final Document d = db.parse(stream);
final XPath xpath = XPathFactory.newInstance().newXPath();
final NugetPackage ... | @Test(expected = NuspecParseException.class)
public void testMissingDocument() throws Exception {
XPathNuspecParser parser = new XPathNuspecParser();
//InputStream is = XPathNuspecParserTest.class.getClassLoader().getResourceAsStream("dependencycheck.properties");
InputStream is = BaseTest.g... |
public final void isAtLeast(int other) {
asDouble.isAtLeast(other);
} | @Test
public void isAtLeast_int() {
expectFailureWhenTestingThat(2.0f).isAtLeast(3);
assertThat(2.0f).isAtLeast(2);
assertThat(2.0f).isAtLeast(1);
} |
public void createDir(File dir) {
Path dirPath = requireNonNull(dir, "dir can not be null").toPath();
if (dirPath.toFile().exists()) {
checkState(dirPath.toFile().isDirectory(), "%s is not a directory", dirPath);
} else {
try {
createDirectories(dirPath);
} catch (IOException e) {
... | @Test
public void createDir_creates_specified_directory() throws IOException {
File dir = new File(temp.newFolder(), "someDir");
assertThat(dir).doesNotExist();
underTest.createDir(dir);
assertThat(dir).exists();
} |
public static <T, R> R unaryCall(Invoker<?> invoker, MethodDescriptor methodDescriptor, T request) {
return (R) call(invoker, methodDescriptor, new Object[] {request});
} | @Test
void testUnaryCall() throws Throwable {
when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> result);
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<Object> atomicReference = new AtomicReference<>();
StreamObserver<Object> responseObserver = new S... |
@Udf
public List<String> keys(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final List<String> ret = new ArrayList<>();
node.fi... | @Test
public void shouldReturnKeysForEmptyObject() {
// When:
final List<String> result = udf.keys("{}");
// Then:
assertEquals(Collections.emptyList(), result);
} |
public long getMsgOutCounter() {
return msgOutFromRemovedConsumer.longValue() + sumConsumers(Consumer::getMsgOutCounter);
} | @Test
public void testGetMsgOutCounter() {
subscription.msgOutFromRemovedConsumer.add(1L);
when(consumer.getMsgOutCounter()).thenReturn(2L);
assertEquals(subscription.getMsgOutCounter(), 3L);
} |
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
List<EurekaEndpoint> candidateHosts = null;
int endpointIdx = 0;
for (int retry = 0; retry < numberOfRetries; retry++) {
EurekaHttpClient currentHttpClient = delegate.get();
Eu... | @Test(expected = TransportException.class)
public void testErrorResponseIsReturnedIfRetryLimitIsReached() throws Exception {
simulateTransportError(0, NUMBER_OF_RETRIES + 1);
retryableClient.execute(requestExecutor);
} |
public ProjectStatusResponse.ProjectStatus format() {
if (!optionalMeasureData.isPresent()) {
return newResponseWithoutQualityGateDetails();
}
JsonObject json = JsonParser.parseString(optionalMeasureData.get()).getAsJsonObject();
ProjectStatusResponse.Status qualityGateStatus = measureLevelToQua... | @Test
public void ignore_period_not_set_on_leak_period() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/non_leak_period.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")... |
public boolean includes(String ipAddress) {
if (all) {
return true;
}
if (ipAddress == null) {
throw new IllegalArgumentException("ipAddress is null.");
}
try {
return includes(addressFactory.getByName(ipAddress));
} catch (UnknownHostException e) {
return fals... | @Test
public void testIPList() {
//create MachineList with a list of of IPs
MachineList ml = new MachineList(IP_LIST, new TestAddressFactory());
//test for inclusion with an known IP
assertTrue(ml.includes("10.119.103.112"));
//test for exclusion with an unknown IP
assertFalse(ml.includes("1... |
public static String[] getAllValueMetaNames() {
List<String> strings = new ArrayList<String>();
List<PluginInterface> plugins = pluginRegistry.getPlugins( ValueMetaPluginType.class );
for ( PluginInterface plugin : plugins ) {
String id = plugin.getIds()[0];
if ( !( "0".equals( id ) ) ) {
... | @Test
public void testGetAllValueMetaNames() {
List<String> dataTypes = Arrays.<String>asList( ValueMetaFactory.getAllValueMetaNames() );
assertTrue( dataTypes.contains( "Number" ) );
assertTrue( dataTypes.contains( "String" ) );
assertTrue( dataTypes.contains( "Date" ) );
assertTrue( dataTypes.c... |
@Override
public void close() throws IOException {
throw new UnsupportedOperationException(
"Caller does not own the underlying output stream " + " and should not call close().");
} | @Test
public void testClosingThrows() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Caller does not own the underlying");
os.close();
} |
@Override
public void shutdown() {
delegate.shutdown();
} | @Test
public void shutdown() {
underTest.shutdown();
verify(executorService).shutdown();
} |
public void skipReserved(final int length) {
byteBuf.skipBytes(length);
} | @Test
void assertSkipReserved() {
new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).skipReserved(10);
verify(byteBuf).skipBytes(10);
} |
public static boolean equals(String left, String right) {
Slime leftSlime = SlimeUtils.jsonToSlimeOrThrow(left);
Slime rightSlime = SlimeUtils.jsonToSlimeOrThrow(right);
return leftSlime.equalTo(rightSlime);
} | @Test
public void implementationSpecificEqualsBehavior() {
// Exception thrown if outside a long
assertTrue( JSON.equals("{\"a\": 9223372036854775807}", "{\"a\": 9223372036854775807}"));
assertRuntimeException(() -> JSON.equals("{\"a\": 9223372036854775808}", "{\"a\": 922337... |
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
} | @Test
public void read_from_DB_if_no_report_and_file_unchanged() {
createDbScmInfoWithOneLine();
when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true);
// should clear revision and author
ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
assertThat(scmInfo.getAllChangesets()).hasSize(... |
@Override
public RefreshSuperUserGroupsConfigurationResponse refreshSuperUserGroupsConfiguration(
RefreshSuperUserGroupsConfigurationRequest request)
throws StandbyException, YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRefreshSuperUserGro... | @Test
public void testRefreshSuperUserGroupsConfiguration() throws Exception {
// null request.
LambdaTestUtils.intercept(YarnException.class,
"Missing RefreshSuperUserGroupsConfiguration request.",
() -> interceptor.refreshSuperUserGroupsConfiguration(null));
// normal request.
// Th... |
@Override
protected CouchbaseEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CouchbaseEndpoint endpoint = new CouchbaseEndpoint(uri, remaining, this);
setProperties(endpoint, parameters);
return endpoint;
} | @Test
public void testEndpointCreated() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("bucket", "bucket");
String uri = "couchbase:http://localhost:9191?bucket=bucket";
String remaining = "http://localhost:9191";
CouchbaseEndpoint endpoint = co... |
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Build lineage based from RelMetadataQ... | @Test
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
{"ST", "b", "TT", "B", "||(b, c)"},
{"ST", "c", "... |
@VisibleForTesting
static String getActualColumnName(String rawTableName, String columnName, @Nullable Map<String, String> columnNameMap,
boolean ignoreCase) {
if ("*".equals(columnName)) {
return columnName;
}
String columnNameToCheck = trimTableName(rawTableName, columnName, ignoreCase);
... | @Test
public void testGetActualColumnNameCaseInSensitive() {
Map<String, String> columnNameMap = new HashMap<>();
columnNameMap.put("student_name", "student_name");
String actualColumnName =
BaseSingleStageBrokerRequestHandler.getActualColumnName("mytable", "MYTABLE.student_name", columnNameMap, t... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefin... | @Test
public void testConvertBigint() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("bigint")
.dataType("bigint")
.build();
Column column = Sql... |
@Deprecated
public static Connection getConnection( LogChannelInterface log, DatabaseMeta dbMeta, String partitionId )
throws Exception {
DataSource ds = getDataSource( log, dbMeta, partitionId );
return ds.getConnection();
} | @Test
public void testGetConnection() throws Exception {
when( dbMeta.getName() ).thenReturn( "CP1" );
when( dbMeta.getPassword() ).thenReturn( PASSWORD );
when( dbMeta.getInitialPoolSize() ).thenReturn( 1 );
when( dbMeta.getMaximumPoolSize() ).thenReturn( 2 );
DataSource conn = ConnectionPoolUtil... |
@Override public Throwable error() {
return error;
} | @Test void error() {
assertThat(response.error()).isSameAs(error);
} |
@Override
public JobStatus getJobStatus() {
return JobStatus.RUNNING;
} | @Test
void testStateDoesNotExposeGloballyTerminalExecutionGraph() throws Exception {
try (MockExecutingContext ctx = new MockExecutingContext()) {
final FinishingMockExecutionGraph finishingMockExecutionGraph =
new FinishingMockExecutionGraph();
Executing executin... |
public <T extends ConnectionProvider<?>> List<String> getNamesByType( Class<T> providerClass ) {
List<String> detailNames = new ArrayList<>();
for ( ConnectionProvider<? extends ConnectionDetails> provider : getProvidersByType( providerClass ) ) {
List<String> names = getNames( provider );
if ( nam... | @Test
public void testGetNamesByType() {
addOne();
List<String> names = connectionManager.getNamesByType( TestConnectionWithBucketsProvider.class );
assertEquals( 1, names.size() );
assertEquals( CONNECTION_NAME, names.get( 0 ) );
} |
@Override
public Collection<SQLToken> generateSQLTokens(final AlterTableStatementContext sqlStatementContext) {
String tableName = sqlStatementContext.getSqlStatement().getTable().getTableName().getIdentifier().getValue();
EncryptTable encryptTable = encryptRule.getEncryptTable(tableName);
C... | @Test
void assertAddColumnGenerateSQLTokens() {
Collection<SQLToken> actual = generator.generateSQLTokens(mockAddColumnStatementContext());
assertThat(actual.size(), is(4));
Iterator<SQLToken> actualIterator = actual.iterator();
assertThat(actualIterator.next(), instanceOf(RemoveToke... |
public static DynamicProtoCoder of(Descriptors.Descriptor protoMessageDescriptor) {
return new DynamicProtoCoder(
ProtoDomain.buildFrom(protoMessageDescriptor),
protoMessageDescriptor.getFullName(),
ImmutableSet.of());
} | @Test
public void testDynamicMessage() throws Exception {
DynamicMessage message =
DynamicMessage.newBuilder(MessageA.getDescriptor())
.setField(
MessageA.getDescriptor().findFieldByNumber(MessageA.FIELD1_FIELD_NUMBER), "foo")
.build();
Coder<DynamicMessage> cod... |
CompletableFuture<Void> beginExecute(
@Nonnull List<? extends Tasklet> tasklets,
@Nonnull CompletableFuture<Void> cancellationFuture,
@Nonnull ClassLoader jobClassLoader
) {
final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture... | @Test
public void when_blockingTaskletIsCancelled_then_completeEarly() {
// Given
final List<MockTasklet> tasklets =
Stream.generate(() -> new MockTasklet().blocking().callsBeforeDone(Integer.MAX_VALUE))
.limit(100).collect(toList());
// When
C... |
@VisibleForTesting
public static <ConfigT> ConfigT payloadToConfig(
ExternalConfigurationPayload payload, Class<ConfigT> configurationClass) {
try {
return payloadToConfigSchema(payload, configurationClass);
} catch (NoSuchSchemaException schemaException) {
LOG.warn(
"Configuration... | @Test
public void testCompoundCodersForExternalConfiguration_schemas() throws Exception {
ExternalTransforms.ExternalConfigurationPayload externalConfig =
encodeRowIntoExternalConfigurationPayload(
Row.withSchema(
Schema.of(
Field.nullable("configKey... |
public void init(ScannerReportWriter writer) {
File analysisLog = writer.getFileStructure().analysisLog();
try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) {
writePlugins(fileWriter);
writeBundledAnalyzers(fileWriter);
writeGlobalSettings(... | @Test
public void shouldNotDumpSensitiveGlobalProperties() throws Exception {
when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.login", "my_token", "sonar.password", "azerty", "sonar.cpp.license.secured", "AZERTY"));
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinit... |
public static synchronized void wtf(final String tag, String text, Object... args) {
if (msLogger.supportsWTF()) {
String msg = getFormattedString(text, args);
addLog(LVL_WTF, tag, msg);
msLogger.wtf(tag, msg);
}
} | @Test
public void testWtf() throws Exception {
Logger.wtf("mTag", "Text with %d digits", 0);
Mockito.verify(mMockLog).wtf("mTag", "Text with 0 digits");
Logger.wtf("mTag", "Text with no digits");
Mockito.verify(mMockLog).wtf("mTag", "Text with no digits");
} |
@Override
public void populateContainer(MigrationContainer container) {
container.add(executorType);
populateFromMigrationSteps(container);
} | @Test
public void populateContainer_adds_MigrationStepsExecutorImpl() {
when(migrationSteps.readAll()).thenReturn(emptyList());
// add MigrationStepsExecutorImpl's dependencies
migrationContainer.add(mock(MigrationHistory.class));
migrationContainer.add(mock(MutableDatabaseMigrationState.class));
... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testNewClusterWithoutVersion(VertxTestContext context) {
VersionChangeCreator vcc = mockVersionChangeCreator(
mockKafka(null, null, null),
mockNewCluster(null, null, List.of())
);
Checkpoint async = context.checkpoint();
vcc.reconcil... |
@Override
public void start() throws Exception {
LOG.debug("Start leadership runner for job {}.", getJobID());
leaderElection.startLeaderElection(this);
} | @Test
void testJobMasterServiceLeadershipRunnerCloseWhenElectionServiceGrantLeaderShip()
throws Exception {
final AtomicReference<LeaderInformationRegister> storedLeaderInformation =
new AtomicReference<>(LeaderInformationRegister.empty());
final AtomicBoolean haBackendLe... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBigint() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("int8").dataType("int8").build();
Column column = PostgresTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), c... |
public void go(PrintStream out) {
KieServices ks = KieServices.Factory.get();
// Install example1 in the local maven repo before to do this
KieContainer kContainer = ks.newKieContainer(ks.newReleaseId("org.drools", "named-kiesession", Drools.getFullVersion()));
KieSession kSession = kC... | @Test
public void testGo() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
new KieContainerFromKieRepoExample().go(ps);
ps.close();
String actual = baos.toString();
String expected = "" +
"... |
@Override
public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) {
File[] allFiles = getFiles(configRepoCheckoutDirectory, context);
// if context had changed files list then we could parse only new content
PartialConfig[] allFragments = parseFiles(al... | @Test
public void shouldFailToLoadDirectoryWithNonXmlFormat() throws Exception {
String content = """
<?xml version="1.0" encoding="utf-8"?>
<cruise xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="cruise-config.xsd" schemaVersion="38">
... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldEscapeEscapedPatternStartSequences() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("2.1-${COUNT}-#######{foo}-bar-####{bar}");
new ParamResolver(new ParamSubstitutionHandlerFactory(... |
public static boolean isValidIpv4Address(String ip) {
boolean matches = IPV4_ADDRESS.matcher(ip).matches();
if (matches) {
String[] split = ip.split("\\.");
for (String num : split) {
int i = Integer.parseInt(num);
if (i > 255) {
... | @Test
public void testIPv4() {
assertThat(IpAndDnsValidation.isValidIpv4Address("127.0.0.1"), is(true));
assertThat(IpAndDnsValidation.isValidIpv4Address("123.123.123.123"), is(true));
assertThat(IpAndDnsValidation.isValidIpv4Address("127.0.0.0.1"), is(false));
assertThat(IpAndDns... |
public static Logger getLogger(Class<?> key) {
return ConcurrentHashMapUtils.computeIfAbsent(
LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name)));
} | @Test
void shouldReturnSameLogger() {
Logger logger1 = LoggerFactory.getLogger(this.getClass().getName());
Logger logger2 = LoggerFactory.getLogger(this.getClass().getName());
assertThat(logger1, is(logger2));
} |
public WriteResult<T, K> update(Bson filter, T object, boolean upsert, boolean multi) {
return update(filter, object, upsert, multi, delegate.getWriteConcern());
} | @Test
void updateWithObjectVariants() {
final var collection = spy(jacksonCollection("simple", Simple.class));
final var foo = new Simple("000000000000000000000001", "foo");
final DBQuery.Query query = DBQuery.empty();
collection.update(query, foo);
verify(collection).update... |
public synchronized Value get(String key) throws IOException {
checkNotClosed();
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
for (File file : entry.cleanFiles) {
// A file must have been deleted manually!
... | @Test public void readingTheSameFileMultipleTimes() throws Exception {
set("a", "a", "b");
DiskLruCache.Value value = cache.get("a");
assertThat(value.getFile(0)).isSameInstanceAs(value.getFile(0));
} |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
public void testAcceptEndpointFailures() {
assertFalse(WebSocketMessageConsumptionTask.acceptEndpoint("localhost:4000/websocket"));
assertFalse(WebSocketMessageConsumptionTask
.acceptEndpoint("microcks-ws.example.com/api/ws/Service/1.0.0/channel/sub/path"));
} |
public static Object parse(Payload payload) {
Class classType = PayloadRegistry.getClassByType(payload.getMetadata().getType());
if (classType != null) {
ByteString byteString = payload.getBody().getValue();
ByteBuffer byteBuffer = byteString.asReadOnlyByteBuffer();
O... | @Test
void testParse() {
Payload requestPayload = GrpcUtils.convert(request);
ServiceQueryRequest request = (ServiceQueryRequest) GrpcUtils.parse(requestPayload);
assertEquals(this.request.getHeaders(), request.getHeaders());
assertEquals(this.request.getCluster(), request.g... |
public ApolloAuditTracer tracer() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
Object tracer = requestAttributes.getAttribute(ApolloAuditConstants.TRACER,
RequestAttributes.SCOPE_REQUEST);
if (tracer != null) {
... | @Test
public void testGetTracerInAnotherThreadButSameRequest() {
ApolloAuditTracer mockTracer = Mockito.mock(ApolloAuditTracer.class);
{
Mockito.when(traceContext.tracer()).thenReturn(mockTracer);
}
CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().submit(() -... |
@Override
public void setValueForKey(int groupKey, double newValue) {
if (groupKey != GroupKeyGenerator.INVALID_ID) {
_resultArray[groupKey] = newValue;
}
} | @Test
void testSetValueForKey() {
GroupByResultHolder resultHolder = new DoubleGroupByResultHolder(INITIAL_CAPACITY, MAX_CAPACITY, DEFAULT_VALUE);
for (int i = 0; i < INITIAL_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
}
testValues(resultHolder, _expected, 0, INITIAL_CAPACITY... |
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
AuthenticationToken token = null;
String tokenStr = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().eq... | @Test
public void testGetToken() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.g... |
public static <T> Iterator<T> skipFirst(Iterator<T> iterator, @Nonnull Predicate<? super T> predicate) {
checkNotNull(iterator, "iterator cannot be null.");
while (iterator.hasNext()) {
T object = iterator.next();
if (!predicate.test(object)) {
continue;
... | @Test
public void elementNotFound() {
var list = List.of(1, 2, 3, 4, 5, 6);
var actual = IterableUtil.skipFirst(list.iterator(), v -> v > 30);
assertThatThrownBy(actual::next).isInstanceOf(NoSuchElementException.class);
} |
public static String generateAsAsciiArt(String content) {
return generateAsAsciiArt(content, 0, 0, 1);
} | @Test
public void generateAsciiArtTest() {
final QrConfig qrConfig = QrConfig.create()
.setForeColor(Color.BLUE)
.setBackColor(Color.MAGENTA)
.setWidth(0)
.setHeight(0).setMargin(1);
final String asciiArt = QrCodeUtil.generateAsAsciiArt("https://hutool.cn/",qrConfig);
Assert.notNull(asciiArt);
... |
void completeQuietly(final Utils.ThrowingRunnable function,
final String msg,
final AtomicReference<Throwable> firstException) {
try {
function.run();
} catch (TimeoutException e) {
log.debug("Timeout expired before the {} operati... | @Test
public void testCompleteQuietly() {
AtomicReference<Throwable> exception = new AtomicReference<>();
CompletableFuture<Object> future = CompletableFuture.completedFuture(null);
consumer = newConsumer();
assertDoesNotThrow(() -> consumer.completeQuietly(() ->
futu... |
public static String unescape(String str) {
if (str == null) {
return null;
}
int len = str.length();
StringWriter writer = new StringWriter(len);
StringBuilder unicode = new StringBuilder(4);
boolean hadSlash = false;
boolean inUnicode = false;
... | @Test
public void testUnescape() {
Assertions.assertNull(Utils.unescape(null));
Assertions.assertEquals("foo", Utils.unescape("foo"));
Assertions.assertEquals("\\", Utils.unescape("\\"));
Assertions.assertEquals("\\", Utils.unescape("\\\\"));
Assertions.assertEquals("\'", Ut... |
@NonNull public static GestureTypingPathDraw create(
@NonNull OnInvalidateCallback callback, @NonNull GestureTrailTheme theme) {
if (theme.maxTrailLength <= 0) return NO_OP;
return new GestureTypingPathDrawHelper(callback, theme);
} | @Test
public void testCreatesImpl() {
final AtomicInteger invalidates = new AtomicInteger();
GestureTypingPathDraw actual =
GestureTypingPathDrawHelper.create(
invalidates::incrementAndGet,
new GestureTrailTheme(
Color.argb(200, 60, 120, 240), Color.argb(100, 30... |
public static Criterion matchEthType(int ethType) {
return new EthTypeCriterion(ethType);
} | @Test
public void testMatchEthTypeMethod() {
EthType ethType = new EthType(12);
Criterion matchEthType = Criteria.matchEthType(new EthType(12));
EthTypeCriterion ethTypeCriterion =
checkAndConvert(matchEthType,
Criterion.Type.ETH_TYPE,
... |
String name(String name) {
return sanitize(name, NAME_RESERVED);
} | @Test
public void truncatesNamesExceedingCustomMaxLength() throws Exception {
Sanitize customSanitize = new Sanitize(70);
String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789";
assertThat(customSanitize.name(longName)).isEqualTo(longName.substri... |
@SuppressWarnings("unchecked")
public <T extends Expression> T rewrite(final T expression, final C context) {
return (T) rewriter.process(expression, context);
} | @Test
public void shouldRewriteCreateArrayExpression() {
// Given:
final CreateArrayExpression parsed = parseExpression("ARRAY['foo', col4[1]]");
final Expression firstVal = parsed.getValues().get(0);
final Expression secondVal = parsed.getValues().get(1);
when(processor.apply(firstVal, context)).... |
@Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry());
} | @Test
public void injectsTheMetricRegistryIntoTheServletContext() {
final ServletContext context = mock(ServletContext.class);
final ServletContextEvent event = mock(ServletContextEvent.class);
when(event.getServletContext()).thenReturn(context);
listener.contextInitialized(event);... |
@PostMapping("/get_logs")
@Operation(summary = "Get paginated account logs")
public DAccountLogsResult getAccountLogs(@RequestBody DAccountLogsRequest deprecatedRequest){
validatePageId(deprecatedRequest);
AppSession appSession = validate(deprecatedRequest);
var request = deprecatedReque... | @Test
public void testInvalidPageId() {
DAccountLogsRequest request = new DAccountLogsRequest();
request.setAppSessionId("id");
DAccountException exc = assertThrows(DAccountException.class, () -> {
accountLogsController.getAccountLogs(request);
});
assertEquals(... |
public static void waitForCommandSequenceNumber(
final CommandQueue commandQueue,
final KsqlRequest request,
final Duration timeout
) throws InterruptedException, TimeoutException {
final Optional<Long> commandSequenceNumber = request.getCommandSequenceNumber();
if (commandSequenceNumber.isP... | @Test
public void shouldNotWaitIfNoSequenceNumberSpecified() throws Exception {
// Given:
when(request.getCommandSequenceNumber()).thenReturn(Optional.empty());
// When:
CommandStoreUtil.waitForCommandSequenceNumber(commandQueue, request, TIMEOUT);
// Then:
verify(commandQueue, never()).ensu... |
public static boolean objectWithTheSameNameExists( SharedObjectInterface object,
Collection<? extends SharedObjectInterface> scope ) {
for ( SharedObjectInterface element : scope ) {
String elementName = element.getName();
if ( elementName != null && elementName.equalsIgnoreCase( object.getName() ... | @Test
public void objectWithTheSameNameExists_false_if_not_exist() {
SharedObjectInterface sharedObject = mock( SharedObjectInterface.class );
when( sharedObject.getName() ).thenReturn( "NEW_TEST_OBJECT" );
assertFalse( objectWithTheSameNameExists( sharedObject, createTestScope( "TEST_OBJECT" ) ) );
} |
@Override
public Address getCaller() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetCaller() {
localCacheWideEventData.getCaller();
} |
@Override
public CRTask deserialize(JsonElement json,
Type type,
JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldThrowExceptionForFetchIfOriginIsInvalid() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "fetch");
jsonObject.addProperty(TypeAdapter.ARTIFACT_ORIGIN, "fsg");
assertThatThrownBy(() -> taskTypeAdapter.deserialize(jsonObject, type, j... |
@Override
public Serde<GenericRow> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
final Optiona... | @Test
public void shouldReturnLoggingSerde() {
// When:
final Serde<GenericRow> result = factory
.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
assertThat(result, is(sameInstance(loggingSerde)));
} |
@Override
public V chooseVolume(List<V> volumes, long replicaSize, String storageId)
throws IOException {
if (volumes.size() < 1) {
throw new DiskOutOfSpaceException("No more available volumes");
}
// As all the items in volumes are with the same storage type,
// so only need to get the st... | @Test(timeout=60000)
public void testAvailableSpaceChanges() throws Exception {
@SuppressWarnings("unchecked")
final AvailableSpaceVolumeChoosingPolicy<FsVolumeSpi> policy =
ReflectionUtils.newInstance(AvailableSpaceVolumeChoosingPolicy.class, null);
initPolicy(policy, BALANCED_SPACE_THRESHOLD, 1... |
public boolean isUnknownOrLessThan(Version version) {
return isUnknown() || compareTo(version) < 0;
} | @Test
public void isUnknownOrLessThan() {
assertFalse(V3_0.isUnknownOrLessThan(of(2, 0)));
assertFalse(V3_0.isUnknownOrLessThan(of(3, 0)));
assertTrue(V3_0.isUnknownOrLessThan(of(3, 1)));
assertTrue(V3_0.isUnknownOrLessThan(of(4, 0)));
assertTrue(V3_0.isUnknownOrLessThan(of(1... |
public Flowable<EthBlock> replayPastBlocksFlowable(
DefaultBlockParameter startBlock,
boolean fullTransactionObjects,
Flowable<EthBlock> onCompleteFlowable) {
// We use a scheduler to ensure this Flowable runs asynchronously for users to be
// consistent with the othe... | @Test
public void testReplayBlocksDescendingFlowable() throws Exception {
List<EthBlock> ethBlocks = Arrays.asList(createBlock(2), createBlock(1), createBlock(0));
OngoingStubbing<EthBlock> stubbing =
when(web3jService.send(any(Request.class), eq(EthBlock.class)));
for (Eth... |
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
public static RestartConfig.RestartNode getCurrentNode(RestartConfig config) {
Checks.checkTrue(
config != null && !ObjectHelper.isCollectionEmptyOrNull(config.getRestartPath()),
"Cannot get restart info in empty restart configuration");
return confi... | @Test
public void testExtractCurrentNodeFromRestartConfig() {
AssertHelper.assertThrows(
"Invalid get",
IllegalArgumentException.class,
"Cannot get restart info in empty restart configuration",
() -> RunRequest.getCurrentNode(RestartConfig.builder().build()));
RestartConfig con... |
public static Type[] getExactParameterTypes(Executable m, Type declaringType) {
return stream(
GenericTypeReflector.getExactParameterTypes(
m, GenericTypeReflector.annotate(declaringType)))
.map(annType -> uncapture(annType.getType()))
.toArray(Type[]::new);
} | @Test
public void getExactParameterTypes() {
var type = Types.parameterizedType(Container.class, Person.class);
var ctor = Container.class.getDeclaredConstructors()[0];
assertThat(Reflection.getExactParameterTypes(ctor, type)).isEqualTo(new Type[] {Person.class});
var method = Container.class.getDec... |
@Override
public ListTopicsResult listTopics(final ListTopicsOptions options) {
final KafkaFutureImpl<Map<String, TopicListing>> topicListingFuture = new KafkaFutureImpl<>();
final long now = time.milliseconds();
runnable.call(new Call("listTopics", calcDeadlineMs(now, options.timeoutMs()),
... | @Test
public void testSuccessfulRetryAfterRequestTimeout() throws Exception {
HashMap<Integer, Node> nodes = new HashMap<>();
MockTime time = new MockTime();
Node node0 = new Node(0, "localhost", 8121);
nodes.put(0, node0);
Cluster cluster = new Cluster("mockClusterId", nodes... |
public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
... | @Test
void isDirectoryThrowsResourceNotFoundExceptionForMissingDirectories() throws Exception {
final URL url = getClass().getResource("/META-INF/");
final URL nurl = new URL(url.toExternalForm() + "missing");
assertThatExceptionOfType(ResourceNotFoundException.class)
.isThrownBy... |
@Bean
public CircuitBreakerRegistry circuitBreakerRegistry(
EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry,
RegistryEventConsumer<CircuitBreaker> circuitBreakerRegistryEventConsumer,
@Qualifier("compositeCircuitBreakerCustomizer") CompositeCustomizer<CircuitBreakerConfigCus... | @Test
public void testCreateCircuitBreakerRegistryWithUnknownConfig() {
CircuitBreakerConfigurationProperties circuitBreakerConfigurationProperties = new CircuitBreakerConfigurationProperties();
InstanceProperties instanceProperties = new InstanceProperties();
instanceProperties.setBaseConfi... |
@Override
public void register(@NonNull ThreadPoolPlugin plugin) {
mainLock.runWithWriteLock(() -> {
String id = plugin.getId();
Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered");
registeredPlugins.put(id, plugin);
forQuic... | @Test
public void testGetPluginOfType() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), TestExecuteAwarePlugin.class).isPresent());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class... |
@GET
public Response getApplication(@PathParam("version") String version,
@HeaderParam("Accept") final String acceptHeader,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept) {
if (!registry.shouldAllowAccess(false)) {
... | @Test
public void testFullAppGet() throws Exception {
Response response = applicationResource.getApplication(
Version.V2.name(),
MediaType.APPLICATION_JSON,
EurekaAccept.full.name()
);
String json = String.valueOf(response.getEntity());
... |
public static InstanceInfo takeFirst(Applications applications) {
for (Application application : applications.getRegisteredApplications()) {
if (!application.getInstances().isEmpty()) {
return application.getInstances().get(0);
}
}
return null;
} | @Test
public void testTakeFirstIfNotNullReturnFirstInstance() {
Application application = createSingleInstanceApp("foo", "foo",
InstanceInfo.ActionType.ADDED);
Applications applications = createApplications(application);
applications.addApplication(application);
Asse... |
public PahoConfiguration getConfiguration() {
return configuration;
} | @Test
public void checkOptions() {
String uri = "paho:/test/topic" + "?clientId=sampleClient" + "&brokerUrl=" + service.serviceAddress()
+ "&qos=2"
+ "&persistence=file";
PahoEndpoint endpoint = getMandatoryEndpoint(uri, PahoEndpoint.class);
// The... |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable <InputT> TransformEvaluator<InputT> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
return createEvaluator((AppliedPTransform) application);
} | @Test
public void noElementsAvailableReaderIncludedInResidual() throws Exception {
// Read with a very slow rate so by the second read there are no more elements
PCollection<Long> pcollection =
p.apply(Read.from(new TestUnboundedSource<>(VarLongCoder.of(), 1L)));
SplittableParDo.convertReadBasedSp... |
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
} | @Test
void testIsNotEmpty() {
assertFalse(StringUtils.isNotEmpty(null));
assertFalse(StringUtils.isNotEmpty(""));
assertTrue(StringUtils.isNotEmpty(" "));
assertTrue(StringUtils.isNotEmpty("bob"));
assertTrue(StringUtils.isNotEmpty(" bob "));
} |
public static Pair<String, Integer> validateHostAndPort(String hostPort, boolean resolveHost) {
hostPort = hostPort.replaceAll("\\s+", "");
if (hostPort.isEmpty()) {
throw new SemanticException("Invalid host port: " + hostPort);
}
String[] hostInfo;
try {
... | @Test
public void testGetHostAndPort() {
String ipv4 = "192.168.1.2:9050";
String ipv6 = "[fe80::5054:ff:fec9:dee0]:9050";
String ipv6Error = "fe80::5054:ff:fec9:dee0:dee0";
try {
Pair<String, Integer> ipv4Addr = SystemInfoService.validateHostAndPort(ipv4, false);
... |
@Override
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
// ask for a mandatory type conversion to avoid a possible NPE beforehand as we do copy from the InputStream
final InputStream is = exchange.getContext().getTypeConverter().mandat... | @Test
public void testMarshalTextToZipDefaultCompression() throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("direct:start")
.marshal().zipDeflater(Deflater.DEFAULT_COMPRESSION)
.process(new Zi... |
@Override
public ConcatIterator<T> iterator() throws IOException {
return new ConcatIterator<T>(
readerFactory, options, executionContext, operationContext, sources);
} | @Test
public void testReadEmptyList() throws Exception {
ConcatReader<String> concat =
new ConcatReader<>(
registry,
null /* options */,
null /* executionContext */,
TestOperationContext.create(),
new ArrayList<Source>());
ConcatReader.Concat... |
@SneakyThrows(IOException.class)
public static JDBCRepositorySQL load(final String type) {
JDBCRepositorySQL result = null;
try (Stream<String> resourceNameStream = ClasspathResourceDirectoryReader.read(JDBCRepositorySQLLoader.class.getClassLoader(), ROOT_DIRECTORY)) {
Iterable<String> r... | @Test
void assertLoad() {
assertThat(JDBCRepositorySQLLoader.load("MySQL").getType(), is("MySQL"));
assertThat(JDBCRepositorySQLLoader.load("EmbeddedDerby").getType(), is("EmbeddedDerby"));
assertThat(JDBCRepositorySQLLoader.load("DerbyNetworkServer").getType(), is("DerbyNetworkServer"));
... |
public static boolean listenByOther(final int port) {
Optional<String> optionalPid = getPortOwner(port);
if (optionalPid.isPresent() && !optionalPid.get().equals(SystemUtils.getCurrentPID())) {
LOGGER.warn("PID {} is listening on port {}.", optionalPid.get(), port);
return true;
... | @Test
void listenByOther() throws IOException {
try (MockedStatic<SystemUtils> systemUtilsMockedStatic = mockStatic(SystemUtils.class)) {
systemUtilsMockedStatic.when(SystemUtils::getCurrentPID).thenReturn("0");
systemUtilsMockedStatic.when(SystemUtils::isWindows).thenReturn(true);
... |
public final ResourceSkyline getResourceSkyline() {
return resourceSkyline;
} | @Test public final void testGetContainerSpec() {
final Resource containerAlloc =
jobMetaData.getResourceSkyline().getContainerSpec();
final Resource containerAlloc2 = Resource.newInstance(1, 1);
Assert.assertEquals(containerAlloc.getMemorySize(),
containerAlloc2.getMemorySize());
Assert.... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = ... | @Test
public void testBraceletOfClayCheck()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_BRACELET_OF_CLAY, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_CLA... |
public final T getLast() {
return this.lastNode;
} | @Test
public void testGetLast() {
assertThat(this.list.getLast()).as("Empty list should return null on getLast()").isNull();
this.list.add( this.node1 );
assertThat(this.node1).as("Last node should be node1").isSameAs(this.list.getLast());
this.list.add( this.node2 );
assertT... |
public static String squeezeStatement(String sql)
{
TokenSource tokens = getLexer(sql, ImmutableSet.of());
StringBuilder sb = new StringBuilder();
while (true) {
Token token = tokens.nextToken();
if (token.getType() == Token.EOF) {
break;
}... | @Test
public void testSqueezeStatementError()
{
String sql = "select * from z#oops";
assertEquals(squeezeStatement(sql), "select * from z#oops");
} |
public void update(int key, int oldValue, int value) {
remove(key, oldValue);
insert(key, value);
} | @Test
public void testUpdate() {
GHSortedCollection instance = new GHSortedCollection();
assertTrue(instance.isEmpty());
instance.insert(0, 10);
instance.insert(1, 11);
assertEquals(10, instance.peekValue());
assertEquals(2, instance.getSize());
instance.updat... |
public int getOutputBufferProcessors() {
return outputBufferProcessors;
} | @Test
public void defaultProcessorNumbers() throws Exception {
// number of buffer processors:
// process, output
final int[][] baseline = {
{1, 1}, // 1 available processor
{1, 1}, // 2 available processors
{2, 1}, // 3 available processors... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenTypeCircle_whenOnMsg_thenFalse() throws TbNodeException {
// GIVEN
var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration();
config.setPerimeterType(PerimeterType.CIRCLE);
node.init(ctx, new TbNodeConfiguration(JacksonUtil.valueToTree(config)))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.