focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T> List<List<T>> splitAvg(List<T> list, int limit) {
if (CollUtil.isEmpty(list)) {
return empty();
}
return (list instanceof RandomAccess)
? new RandomAccessAvgPartition<>(list, limit)
: new AvgPartition<>(list, limit);
} | @Test
public void splitAvgNotZero() {
assertThrows(IllegalArgumentException.class, () -> {
// limit不能小于等于0
ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 0);
});
} |
@Override
public boolean containsAll(Collection<?> c) {
return get(containsAllAsync(c));
} | @Test
public void testContainsAll() {
RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple");
for (int i = 0; i < 200; i++) {
set.add(i, i);
}
Assertions.assertTrue(set.containsAll(Arrays.asList(30, 11)));
Assertions.assertFalse(set.containsAll(Arr... |
protected String getFileName(double lat, double lon) {
lon = 1 + (180 + lon) / LAT_DEGREE;
int lonInt = (int) lon;
lat = 1 + (60 - lat) / LAT_DEGREE;
int latInt = (int) lat;
if (Math.abs(latInt - lat) < invPrecision / LAT_DEGREE)
latInt--;
// replace String.... | @Test
public void testFileNotFound() {
File file = new File(instance.getCacheDir(), instance.getFileName(46, -20) + ".gh");
File zipFile = new File(instance.getCacheDir(), instance.getFileName(46, -20) + ".zip");
file.delete();
zipFile.delete();
instance.setDownloader(new Do... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
if(containerService.isContainer(folder)) {
final S3BucketCreateService service = new S3BucketCreateService(session);
service.create(folder, StringUtils.isBlank(status.getRegion())... | @Test
public void testCreatePlaceholder() throws Exception {
final AtomicBoolean b = new AtomicBoolean();
final String name = new AlphanumericRandomStringService().random();
session.withListener(new TranscriptListener() {
@Override
public void log(final Type request, ... |
ApolloNotificationMessages transformMessages(String messagesAsString) {
ApolloNotificationMessages notificationMessages = null;
if (!Strings.isNullOrEmpty(messagesAsString)) {
try {
notificationMessages = gson.fromJson(messagesAsString, ApolloNotificationMessages.class);
} catch (Throwable e... | @Test
public void testTransformMessages() throws Exception {
String someKey = "someKey";
long someNotificationId = 1;
String anotherKey = "anotherKey";
long anotherNotificationId = 2;
ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
notificationMessages.put(s... |
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException {
final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class);
... | @Test
void parseArtifactResolveFailed() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException {
ArtifactResponse artifactResponse = artifactResponseService.buildArtifactResponse(getArtifactResolveRequest("failed", true,false, SAML_COMBICONNECT, Encrypti... |
@Override
public void add(T item) {
final int sizeAtTimeOfAdd;
synchronized (items) {
items.add(item);
sizeAtTimeOfAdd = items.size();
}
/*
WARNING: It is possible that the item that was just added to the list
has been processed by an ... | @Test
public void readyMaxTrigger() {
TestAccumulator accumulator = new TestAccumulator();
accumulator.ready = false;
accumulator.add(new TestItem("a"));
accumulator.add(new TestItem("b"));
accumulator.add(new TestItem("c"));
accumulator.add(new TestItem("d"));
... |
public BaseIdentityProvider.Context newContext(HttpRequest request, HttpResponse response, BaseIdentityProvider identityProvider) {
return new ContextImpl(request, response, identityProvider);
} | @Test
public void authenticate() {
JavaxHttpRequest httpRequest = new JavaxHttpRequest(request);
JavaxHttpResponse httpResponse = new JavaxHttpResponse(response);
BaseIdentityProvider.Context context = underTest.newContext(httpRequest, httpResponse, identityProvider);
ArgumentCaptor<UserDto> userArgu... |
@Nullable static String route(ContainerRequest request) {
ExtendedUriInfo uriInfo = request.getUriInfo();
List<UriTemplate> templates = uriInfo.getMatchedTemplates();
int templateCount = templates.size();
if (templateCount == 0) return "";
StringBuilder builder = null; // don't allocate unless you n... | @Test void ignoresEventsExceptFinish() {
setBaseUri("/");
when(uriInfo.getMatchedTemplates()).thenReturn(Arrays.asList(
new PathTemplate("/"),
new PathTemplate("/items/{itemId}")
));
assertThat(SpanCustomizingApplicationEventListener.route(request))
.isEqualTo("/items/{itemId}");
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
new SFTPAttributesFinderFeature(session).find(file, listener);
return true;
}
catch(No... | @Test
public void testFindFile() throws Exception {
final Path file = new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new SFTPTouchFeature(session).touch(file, new TransferStatus());
assertTrue(new SFTPFindFe... |
@Override
public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {
getExecuteClientProxy(instance).registerService(serviceName, groupName, instance);
} | @Test
void testRegisterPersistentServiceByHttp() throws NacosException, NoSuchFieldException, IllegalAccessException {
NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class);
Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy");
... |
final void logJobFilterTime(JobFilter jobFilter, long durationInNanos) {
if (NANOSECONDS.toMillis(durationInNanos) > 10) {
getLogger().warn("JobFilter of type '{}' has slow performance of {}ms (a Job Filter should run under 10ms) which negatively impacts the overall functioning of JobRunr. JobRunr P... | @Test
void ifJobFilterIsTooSlowAMessageIsLogged() {
MyJobFilter myJobFilter = new MyJobFilter();
JobCreationFilters jobCreationFilters = new JobCreationFilters(anEnqueuedJob().build(), new JobDefaultFilters(myJobFilter));
final ListAppender<ILoggingEvent> logger = LoggerAssert.initFor(jobCre... |
public ParResponse requestPushedUri(
URI pushedAuthorizationRequestUri, ParBodyBuilder parBodyBuilder) {
var headers =
List.of(
new Header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON),
new Header(HttpHeaders.CONTENT_TYPE, UrlFormBodyBuilder.MEDIA_TYPE));
var req = new ... | @Test
void requestPushedUri_badStatus(WireMockRuntimeInfo wm) {
var path = "/auth/par";
stubFor(post(path).willReturn(badRequest()));
var base = URI.create(wm.getHttpBaseUrl());
var parUri = base.resolve(path);
var e =
assertThrows(
HttpException.class, () -> client.requestPu... |
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
} | @Test
public void testIsWarnEnabled() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.getName()).thenReturn("foo");
when(mockLogger.isWarnEnabled()).thenReturn(true);
InternalLogger logger = new Slf4JLogger(mockLogger);
assertTrue(logger.isWarnEnabled());
... |
public ProtocolBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
} | @Test
void telnet() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.telnet("mocktelnethandler");
Assertions.assertEquals("mocktelnethandler", builder.build().getTelnet());
} |
public static InstancePort swapStaleLocation(InstancePort instPort) {
return DefaultInstancePort.builder()
.deviceId(instPort.oldDeviceId())
.portNumber(instPort.oldPortNumber())
.state(instPort.state())
.ipAddress(instPort.ipAddress())
... | @Test
public void testSwapStaleLocation() {
InstancePort swappedInstancePort = swapStaleLocation(instancePort3);
assertEquals(instancePort3.oldDeviceId(), swappedInstancePort.deviceId());
assertEquals(instancePort3.oldPortNumber(), swappedInstancePort.portNumber());
} |
public MetadataReportBuilder syncReport(Boolean syncReport) {
this.syncReport = syncReport;
return getThis();
} | @Test
void syncReport() {
MetadataReportBuilder builder = new MetadataReportBuilder();
builder.syncReport(true);
Assertions.assertTrue(builder.build().getSyncReport());
builder.syncReport(false);
Assertions.assertFalse(builder.build().getSyncReport());
builder.syncRep... |
public static DataSchema avroToDataSchema(String avroSchemaInJson, AvroToDataSchemaTranslationOptions options)
throws IllegalArgumentException
{
ValidationOptions validationOptions = SchemaParser.getDefaultSchemaParserValidationOptions();
validationOptions.setAvroUnionMode(true);
SchemaParserFactory ... | @Test
public void testAvroPartialDefaultFields() throws IOException
{
String schemaWithPartialDefaultFields = "{" +
" \"type\": \"record\"," +
" \"name\": \"testRecord\"," +
" \"fields\": [" +
" {" +
" \"name\": \"recordFieldWithDefault\"," +
" \"t... |
public List<KuduPredicate> convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testLt() {
ConstantOperator value = ConstantOperator.createInt(5);
ScalarOperator op = new BinaryPredicateOperator(BinaryType.LT, F0, value);
List<KuduPredicate> result = CONVERTER.convert(op);
Assert.assertEquals(result.get(0).toString(), "`f0` < 5");
} |
public boolean deleteRole(Role role) {
return rolesConfig.remove(role);
} | @Test
public void shouldReturnTrueIfDeletingARoleGoesThroughSuccessfully() throws Exception {
SecurityConfig securityConfig = security(passwordFileAuthConfig(), admins());
securityConfig.deleteRole(ROLE1);
assertUserRoles(securityConfig, "chris", ROLE2);
assertUserRoles(securityConf... |
@Override
public ByteBuf writeLongLE(long value) {
ensureWritable0(8);
_setLongLE(writerIndex, value);
writerIndex += 8;
return this;
} | @Test
public void testWriteLongLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeLongLE(1);
}
});
} |
protected ThrowableHandlingConverter createThrowableProxyConverter(LoggerContext context) {
if (exceptionFormat == null) {
return new RootCauseFirstThrowableProxyConverter();
}
ThrowableHandlingConverter throwableHandlingConverter;
if (exceptionFormat.isRootFirst()) {
... | @Test
void testCreateThrowableProxyConverter_Default() throws Exception {
EventJsonLayoutBaseFactory factory = new EventJsonLayoutBaseFactory();
ThrowableHandlingConverter converter = factory.createThrowableProxyConverter(new LoggerContext());
converter.start();
assertThat(converte... |
@VisibleForTesting
static void persistIndexMaps(List<IndexEntry> entries, PrintWriter writer) {
for (IndexEntry entry : entries) {
persistIndexMap(entry, writer);
}
} | @Test
public void testPersistIndexMaps() {
ByteArrayOutputStream output = new ByteArrayOutputStream(1024 * 1024);
try (PrintWriter pw = new PrintWriter(output)) {
List<IndexEntry> entries = Arrays
.asList(new IndexEntry(new IndexKey("foo", StandardIndexes.inverted()), 0, 1024),
n... |
@Override
public void deleteFileConfig(Long id) {
// 校验存在
FileConfigDO config = validateFileConfigExists(id);
if (Boolean.TRUE.equals(config.getMaster())) {
throw exception(FILE_CONFIG_DELETE_FAIL_MASTER);
}
// 删除
fileConfigMapper.deleteById(id);
... | @Test
public void testDeleteFileConfig_master() {
// mock 数据
FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(true);
fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbFileConfig.getId();
// 调用, 并断言异常
assertServiceExcepti... |
@Override
public Iterable<ConnectPoint> getEdgePoints() {
checkPermission(TOPOLOGY_READ);
ImmutableSet.Builder<ConnectPoint> builder = ImmutableSet.builder();
connectionPoints.forEach((k, v) -> v.forEach(builder::add));
return builder.build();
} | @Test
public void testDeviceUpdates() {
//Setup
Device referenceDevice;
DeviceEvent event;
int numDevices = 10;
int numInfraPorts = 5;
totalPorts = 10;
defaultPopulator(numDevices, numInfraPorts);
events.clear();
//Test response to device a... |
public InterpreterResult hidePasswords(InterpreterResult ret) {
if (ret == null) {
return null;
}
return new InterpreterResult(ret.code(), replacePasswords(ret.message()));
} | @Test
void hidePasswordsNoResult() {
UserCredentials userCredentials = mock(UserCredentials.class);
CredentialInjector testee = new CredentialInjector(userCredentials);
assertNull(testee.hidePasswords(null));
} |
public static Comparator<StructLike> forType(Types.StructType struct) {
return new StructLikeComparator(struct);
} | @Test
public void testTime() {
assertComparesCorrectly(Comparators.forType(Types.TimeType.get()), 111, 222);
} |
@Override
public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) {
AbstractConfig config = new AbstractConfig(CONFIG_DEF, connectorConfig);
String filename = config.getString(FILE_CONFIG);
if (filename == null || filename.isEmpty()) {
... | @Test
public void testAlterOffsetsOffsetPositionValues() {
Function<Object, Boolean> alterOffsets = offset -> connector.alterOffsets(sourceProperties, Collections.singletonMap(
Collections.singletonMap(FILENAME_FIELD, FILENAME),
Collections.singletonMap(POSITION_FIELD, offset... |
public void process()
throws Exception {
if (_segmentMetadata.getTotalDocs() == 0) {
LOGGER.info("Skip preprocessing empty segment: {}", _segmentMetadata.getName());
return;
}
// Segment processing has to be done with a local directory.
File indexDir = new File(_indexDirURI);
// ... | @Test
public void testV3UpdateDefaultColumns()
throws Exception {
constructV3Segment();
SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(_indexDir);
assertEquals(segmentMetadata.getVersion(), SegmentVersion.v3);
IngestionConfig ingestionConfig = new IngestionConfig();
ingestion... |
@Override
public Set<EntityExcerpt> listEntityExcerpts() {
return dataAdapterService.findAll().stream()
.map(this::createExcerpt)
.collect(Collectors.toSet());
} | @Test
@MongoDBFixtures("LookupDataAdapterFacadeTest.json")
public void listEntityExcerpts() {
final EntityExcerpt expectedEntityExcerpt = EntityExcerpt.builder()
.id(ModelId.of("5adf24a04b900a0fdb4e52c8"))
.type(ModelTypes.LOOKUP_ADAPTER_V1)
.title("HTTP D... |
public static Character toChar(Object value, Character defaultValue) {
return convertQuietly(Character.class, value, defaultValue);
} | @Test
public void toCharTest() {
final String str = "aadfdsfs";
final Character c = Convert.toChar(str);
assertEquals(Character.valueOf('a'), c);
// 转换失败
final Object str2 = "";
final Character c2 = Convert.toChar(str2);
assertNull(c2);
} |
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
if (null == source) {
return null;
}
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
} | @Test
public void issueI41WKPTest() {
final Test1 t1 = new Test1().setStrList(ListUtil.toList("list"));
final Test2 t2_hu = new Test2();
BeanUtil.copyProperties(t1, t2_hu, CopyOptions.create().setIgnoreError(true));
assertNull(t2_hu.getStrList());
} |
@Override
public Set<Link> getDeviceLinks(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_NULL);
return manager.getVirtualLinks(this.networkId())
.stream()
.filter(link -> (deviceId.equals(link.src().elementId()) ||
deviceId.equals(link.dst(... | @Test(expected = NullPointerException.class)
public void testGetDeviceLinksByNullId() {
manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
LinkService linkService = manager.get(virtualN... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<Explain> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
return StatementExecutorResponse.handled(Optional
.of(Expla... | @Test
public void shouldExplainPersistentStatement() {
// Given:
engine.givenSource(DataSourceType.KSTREAM, "Y");
final String statementText = "CREATE STREAM X AS SELECT * FROM Y;";
final ConfiguredStatement<?> explain = engine.configure("EXPLAIN " + statementText);
// When:
final QueryDescri... |
public static int readVInt(ByteData arr, long position) {
byte b = arr.get(position++);
if(b == (byte) 0x80)
throw new RuntimeException("Attempting to read null value as int");
int value = b & 0x7F;
while ((b & 0x80) != 0) {
b = arr.get(position++);
valu... | @Test
public void testReadVIntInputStream() throws IOException {
InputStream is = new ByteArrayInputStream(BYTES_VALUE_129);
Assert.assertEquals(129, VarInt.readVInt(is));
} |
@Override
public PageResult<AiVideoConfigDO> getAiVideoConfigPage(AiVideoConfigPageReqVO pageReqVO) {
return aiVideoConfigMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetAiVideoConfigPage() {
// mock 数据
AiVideoConfigDO dbAiVideoConfig = randomPojo(AiVideoConfigDO.class, o -> { // 等会查询到
o.setType(null);
o.setValue(null);
o.setStatus(null);
o.setC... |
@Action(name = "purge", resourceLevel = ResourceLevel.COLLECTION)
public int purge()
{
final int numPurged = _db.getData().size();
_db.getData().clear();
AlbumEntryResource.purge(_entryDb, null, null);
return numPurged;
} | @Test
public void testResourcePurge()
{
// photo database is initialized to have 1 photo
// at any time of the test, that initial photo should present for purge
Assert.assertTrue(_res.purge() > 0);
} |
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "{namespace}/files", consumes = MediaType.MULTIPART_FORM_DATA)
@Operation(tags = {"Files"}, summary = "Create a file")
public void createFile(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The i... | @Test
void createFile() throws IOException {
MultipartBody body = MultipartBody.builder()
.addPart("fileContent", "test.txt", "Hello".getBytes())
.build();
client.toBlocking().exchange(
HttpRequest.POST("/api/v1/namespaces/" + NAMESPACE + "/files?path=/test.txt", ... |
public static Application fromServicesXml(String xml, Networking networking) {
Path applicationDir = StandaloneContainerRunner.createApplicationPackage(xml);
return new Application(applicationDir, networking, true);
} | @Test
void http_interface_is_on_when_networking_is_enabled() throws Exception {
int httpPort = getFreePort();
try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.enable)) {
try (DefaultHttpClient client = new org.apache.http.impl.client.... |
@Override
public Object convert(String value) {
if (isNullOrEmpty(value)) {
return value;
}
if (value.contains("=")) {
final Map<String, String> fields = new HashMap<>();
Matcher m = PATTERN.matcher(value);
while (m.find()) {
... | @Test
public void testFilterWithKVAtEnd() {
TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>());
@SuppressWarnings("unchecked")
Map<String, String> result = (Map<String, String>) f.convert("lolwat Awesome! k1=v1");
assertEquals(1, result.size());
ass... |
public void start() {
if (isRunning()) {
return;
}
super.start();
if (getCookieStore() != null) {
getCookieStore().start();
}
} | @Test
public void testNoResponse() throws Exception {
NoResponseServer noResponseServer = new NoResponseServer("localhost", 7780);
noResponseServer.start();
// Give the server time to start up:
Thread.sleep(1000);
// CrawlURI curi = makeCrawlURI("http://stats.bbc.co... |
@Override
public byte[] serialize(FileSourceSplit split) throws IOException {
checkArgument(
split.getClass() == FileSourceSplit.class,
"Cannot serialize subclasses of FileSourceSplit");
// optimization: the splits lazily cache their own serialized form
if (s... | @Test
void repeatedSerializationCaches() throws Exception {
final FileSourceSplit split =
new FileSourceSplit(
"random-id",
new Path("hdfs://namenode:14565/some/path/to/a/file"),
100_000_000,
64_0... |
@Override
public void loadConfiguration(NacosLoggingProperties loggingProperties) {
Log4j2NacosLoggingPropertiesHolder.setProperties(loggingProperties);
String location = loggingProperties.getLocation();
loadConfiguration(location);
} | @Test
void testLoadConfigurationWithoutLocation() {
System.setProperty("nacos.logging.default.config.enabled", "false");
nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties());
log4J2NacosLoggingAdapter = new Log4J2NacosLoggingAdapter();
... |
public byte[] encode(String val, String delimiters) {
return codecs[0].encode(val);
} | @Test
public void testEncodeChinesePersonNameGB18030() {
assertArrayEquals(CHINESE_PERSON_NAME_GB18030_BYTES,
gb18030().encode(CHINESE_PERSON_NAME_GB18030, PN_DELIMS));
} |
public static Read read() {
return new AutoValue_MongoDbIO_Read.Builder()
.setMaxConnectionIdleTime(60000)
.setNumSplits(0)
.setBucketAuto(false)
.setSslEnabled(false)
.setIgnoreSSLCertificate(false)
.setSslInvalidHostNameAllowed(false)
.setQueryFn(FindQuery.c... | @Test
public void testReadWithCustomConnectionOptions() {
MongoDbIO.Read read =
MongoDbIO.read()
.withUri("mongodb://localhost:" + port)
.withMaxConnectionIdleTime(10)
.withDatabase(DATABASE_NAME)
.withCollection(COLLECTION_NAME);
assertEquals(10, read.m... |
@Nullable
public String getInstanceRegion(InstanceInfo instanceInfo) {
if (instanceInfo.getDataCenterInfo() == null || instanceInfo.getDataCenterInfo().getName() == null) {
logger.warn("Cannot get region for instance id:{}, app:{} as dataCenterInfo is null. Returning local:{} by default",
... | @Test
public void testDefaultOverride() throws Exception {
ConfigurationManager.getConfigInstance().setProperty("eureka.us-east-1.availabilityZones", "abc,def");
PropertyBasedAzToRegionMapper azToRegionMapper = new PropertyBasedAzToRegionMapper(new DefaultEurekaClientConfig());
InstanceRegio... |
@PostMapping("create")
public String createProduct(NewProductPayload payload,
Model model,
HttpServletResponse response) {
try {
Product product = this.productsRestClient.createProduct(payload.title(), payload.details());
... | @Test
@DisplayName("createProduct создаст новый товар и перенаправит на страницу товара")
void createProduct_RequestIsValid_ReturnsRedirectionToProductPage() {
// given
var payload = new NewProductPayload("Новый товар", "Описание нового товара");
var model = new ConcurrentModel();
... |
boolean canFilterPlayer(String playerName)
{
boolean isMessageFromSelf = playerName.equals(client.getLocalPlayer().getName());
return !isMessageFromSelf &&
(config.filterFriends() || !client.isFriended(playerName, false)) &&
(config.filterFriendsChat() || !isFriendsChatMember(playerName)) &&
(config.filte... | @Test
public void testMessageFromFriendIsFiltered()
{
when(chatFilterConfig.filterFriends()).thenReturn(true);
assertTrue(chatFilterPlugin.canFilterPlayer("Iron Mammal"));
} |
@Override
public List<Intent> compile(HostToHostIntent intent, List<Intent> installable) {
// If source and destination are the same, there are never any installables.
if (Objects.equals(intent.one(), intent.two())) {
return ImmutableList.of();
}
boolean isAsymmetric = i... | @Test
public void testBandwidthConstrainedIntentAllocation() {
final double bpsTotal = 1000.0;
final double bpsToReserve = 100.0;
ContinuousResource resourceSw1P1 =
Resources.continuous(DID_S1, PORT_1, Bandwidth.class)
.resource(bpsToReserve);
... |
public static Read<DynamicMessage> readProtoDynamicMessages(
ProtoDomain domain, String fullMessageName) {
SerializableFunction<PubsubMessage, DynamicMessage> parser =
message -> {
try {
return DynamicMessage.parseFrom(
domain.getDescriptor(fullMessageName), messa... | @Test
public void testProtoDynamicMessages() {
ProtoCoder<Primitive> coder = ProtoCoder.of(Primitive.class);
ImmutableList<Primitive> inputs =
ImmutableList.of(
Primitive.newBuilder().setPrimitiveInt32(42).build(),
Primitive.newBuilder().setPrimitiveBool(true).build(),
... |
@Deprecated
static Class<?> loadInjectorSourceFromProperties(Map<String, String> properties) {
String injectorSourceClassName = properties.get(GUICE_INJECTOR_SOURCE_KEY);
if (injectorSourceClassName == null) {
return null;
}
log.warn(
() -> format("The '%s' ... | @Test
void failsToLoadNonExistantClass() {
Map<String, String> properties = new HashMap<>();
properties.put(GUICE_INJECTOR_SOURCE_KEY, "some.bogus.Class");
InjectorSourceInstantiationFailed actualThrown = assertThrows(InjectorSourceInstantiationFailed.class,
() -> InjectorSource... |
@Override
protected void refresh(final List<SelectorData> data) {
if (CollectionUtils.isEmpty(data)) {
LOG.info("clear all selector cache, old cache");
data.forEach(pluginDataSubscriber::unSelectorSubscribe);
pluginDataSubscriber.refreshSelectorDataAll();
} else {... | @Test
public void testRefreshCoverage() {
final SelectorDataRefresh selectorDataRefresh = mockSelectorDataRefresh;
SelectorData selectorData = new SelectorData();
List<SelectorData> selectorDataList = new ArrayList<>();
selectorDataRefresh.refresh(selectorDataList);
selectorD... |
public void destroy() {
ensureOperational();
destroyServices();
log.info("Server [{}] shutdown!", name);
log.info("======================================================");
if (!Boolean.getBoolean("test.circus")) {
LogManager.shutdown();
}
status = Status.SHUTDOWN;
} | @Test(expected = IllegalStateException.class)
@TestDir
public void illegalState1() throws Exception {
Server server = new Server("server", TestDirHelper.getTestDir().getAbsolutePath(), new Configuration(false));
server.destroy();
} |
public boolean checkIfEnabled() {
try {
this.gitCommand = locateDefaultGit();
MutableString stdOut = new MutableString();
this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute();
return stdOut.string != null && stdOut.string.startsWith("git version"... | @Test
public void git_should_not_be_detected() {
NativeGitBlameCommand blameCommand = new NativeGitBlameCommand("randomcmdthatwillneverbefound", System2.INSTANCE, processWrapperFactory);
assertThat(blameCommand.checkIfEnabled()).isFalse();
} |
@Config("function-implementation-type")
public SqlFunctionLanguageConfig setFunctionImplementationType(String implementationType)
{
this.functionImplementationType = FunctionImplementationType.valueOf(implementationType.toUpperCase());
return this;
} | @Test
public void testExplicitPropertyMappings()
{
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("function-implementation-type", "THRIFT")
.build();
SqlFunctionLanguageConfig expected = new SqlFunctionLanguageConfig()
... |
@Override public HashSlotCursor12byteKey cursor() {
return new CursorIntKey2();
} | @Test
public void testCursor_key2() {
final long key1 = randomKey();
final int key2 = randomKey();
insert(key1, key2);
HashSlotCursor12byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(key2, cursor.key2());
} |
@Override
public HttpResponse get() throws InterruptedException, ExecutionException {
try {
final Object result = process(0, null);
if (result instanceof Throwable) {
throw new ExecutionException((Throwable) result);
}
return (HttpResponse) res... | @Test(expected = ExecutionException.class)
public void errGetExecution() throws ExecutionException, InterruptedException, TimeoutException {
get(new ExecutionException(new Exception("wrong")), false);
} |
InputFile.Status status(String moduleKeyWithBranch, DefaultInputFile inputFile, String hash) {
InputFile.Status statusFromScm = findStatusFromScm(inputFile);
if (statusFromScm != null) {
return statusFromScm;
}
return checkChangedWithProjectRepositories(moduleKeyWithBranch, inputFile, hash);
} | @Test
public void detect_status_branches_exclude() {
ScmChangedFiles changedFiles = new ScmChangedFiles(Set.of());
StatusDetection statusDetection = new StatusDetection(projectRepositories, changedFiles);
// normally changed
assertThat(statusDetection.status("foo", createFile("src/Foo.java"), "XXXXX"... |
private AlarmId(DeviceId id, String uniqueIdentifier) {
super(id.toString() + ":" + uniqueIdentifier);
checkNotNull(id, "device id must not be null");
checkNotNull(uniqueIdentifier, "unique identifier must not be null");
checkArgument(!uniqueIdentifier.isEmpty(), "unique identifier must ... | @Test
public void testEquals() {
final AlarmId id1 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_1);
final AlarmId sameAsId1 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_1);
final AlarmId id2 = AlarmId.alarmId(DEVICE_ID, UNIQUE_ID_2);
new EqualsTester()
.addEqualityGroup(id1, sam... |
public static String resolveRaw(String str) {
int len = str.length();
if (len <= 4) {
return null;
}
int endPos = len - 1;
char last = str.charAt(endPos);
// optimize to not create new objects
if (last == ')') {
char char1 = str.charAt(0)... | @Test
void testNotRawURIScanner() {
final String resolvedRaw = URIScanner.resolveRaw("foo");
Assertions.assertNull(resolvedRaw);
} |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAddTimecodeMssNoChapters() {
final String timeStr = "1:12";
final long time = 60 * 1000 + 12 * 1000;
String shownotes = "<p> Some test text with a timecode " + timeStr + " here.</p>";
ShownotesCleaner t = new ShownotesCleaner(context, shownotes,... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into a DATE value.")
public Date parseDate(
@UdfParameter(
description = "The string representation of a date.") final String formattedDate,
@UdfParameter(
description = "The format pattern sh... | @Test
public void shouldThrowIfParseFails() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.parseDate("invalid", "yyyy-MM-dd")
);
// Then:
assertThat(e.getMessage(), containsString("Failed to parse date 'invalid' with formatter 'yyyy-MM-dd'"));
... |
protected boolean configDevice(DeviceId deviceId) {
// Returns true if config was successful, false if not and a clean up is
// needed.
final Device device = deviceService.getDevice(deviceId);
if (device == null || !device.is(IntProgrammable.class)) {
return true;
}
... | @Test
public void testConfigPostcardOnlyDevice() {
reset(deviceService, hostService);
Device device = getMockDevice(true, DEVICE_ID);
IntProgrammable intProg = getMockIntProgrammable(false, false, false, true);
setUpDeviceTest(device, intProg, true, true);
IntObjective intObj... |
public static Request.Builder buildRequestBuilder(final String url, final Map<String, ?> form,
final HTTPMethod method) {
switch (method) {
case GET:
return new Request.Builder()
.url(buildHttpUrl(url, form))
.get();
case HE... | @Test
public void buildRequestBuilderForGETTest() {
Request.Builder builder = HttpUtils.buildRequestBuilder(TEST_URL, formMap, HttpUtils.HTTPMethod.GET);
Assert.assertNotNull(builder);
Assert.assertEquals(builder.build().method(), HttpUtils.HTTPMethod.GET.value());
Assert.assertEqual... |
@Override
public boolean next() throws SQLException {
if (orderByValuesQueue.isEmpty()) {
return false;
}
if (isFirstNext) {
isFirstNext = false;
return true;
}
OrderByValue firstOrderByValue = orderByValuesQueue.poll();
if (firstOr... | @Test
void assertNextForCaseSensitive() throws SQLException {
List<QueryResult> queryResults = Arrays.asList(mock(QueryResult.class), mock(QueryResult.class), mock(QueryResult.class));
for (int i = 0; i < 3; i++) {
QueryResultMetaData metaData = mock(QueryResultMetaData.class);
... |
@Override
public void start() throws Exception {
LOG.info("Starting split enumerator for source {}.", operatorName);
// we mark this as started first, so that we can later distinguish the cases where
// 'start()' wasn't called and where 'start()' failed.
started = true;
// ... | @Test
void testStart() throws Exception {
sourceCoordinator.start();
waitForCoordinatorToProcessActions();
assertThat(getEnumerator().isStarted()).isTrue();
} |
@Override
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException {
return getTaskManagerPodTemplateFile()
.map(
FunctionUtils.uncheckedFunction(
file -> {
final Map<String,... | @Test
void testBuildAccompanyingKubernetesResourcesAddsPodTemplateAsConfigMap() throws IOException {
KubernetesTestUtils.createTemporyFile(
POD_TEMPLATE_DATA, flinkConfDir, POD_TEMPLATE_FILE_NAME);
final List<HasMetadata> additionalResources =
podTemplateMountDecorat... |
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) {
if ( point == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null"));
}
if ( range == null ) {
ret... | @Test
void invokeParamsCantBeCompared() {
FunctionTestUtil.assertResultError( finishesFunction.invoke(
new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED ),
new RangeImpl( Range.RangeBoundary.CLOSED, 1, 2, Range.RangeBoundary.CLOSED ) ), InvalidP... |
@Override
public void dropFunction(QualifiedObjectName functionName, Optional<List<TypeSignature>> parameterTypes, boolean exists)
{
checkCatalog(functionName);
jdbi.useTransaction(handle -> {
FunctionNamespaceDao transactionDao = handle.attach(functionNamespaceDaoClass);
... | @Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Function not found: unittest\\.memory\\.tangent\\(double\\)")
public void testDropFunctionFailed()
{
dropFunction(TANGENT, Optional.of(ImmutableList.of(parseTypeSignature(DOUBLE))), false);
} |
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return AuthSystemTypes.LDAP.name().equalsIgnoreCase(EnvUtil.getProperty(Constants.Auth.NACOS_CORE_AUTH_SYSTEM_TYPE));
} | @Test
void matches() {
boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata);
assertFalse(matches);
} |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testUnknownProducerErrorShouldBeRetriedWhenLogStartOffsetIsUnknown() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
prepareAndReceiveInitProducerI... |
@Override
public boolean test(final Path test) {
return this.equals(new CaseInsensitivePathPredicate(test));
} | @Test
public void testCollision() {
final Path t = new Path("/d/2R", EnumSet.of(Path.Type.directory));
assertFalse(new SimplePathPredicate(t).test(new Path("/d/33", EnumSet.of(Path.Type.directory))));
} |
public Canvas canvas() {
Canvas canvas = new Canvas(getLowerBound(), getUpperBound());
canvas.add(this);
if (name != null) {
canvas.setTitle(name);
}
return canvas;
} | @Test
public void testHeatmap() throws Exception {
System.out.println("Heatmap");
var canvas = Heatmap.of(Z, Palette.jet(256)).canvas();
canvas.window();
} |
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_tryCompleteExceptionallyOnReturnedFuture_then_fails() {
// Given
final MockTasklet t = new MockTasklet().callsBeforeDone(Integer.MAX_VALUE);
CompletableFuture<Void> f = tes.beginExecute(singletonList(t), cancellationFuture, classLoader);
// When - Then
... |
public static UpdateTableRequest fromJson(String json) {
return JsonUtil.parse(json, UpdateTableRequestParser::fromJson);
} | @Test
public void invalidRequirements() {
assertThatThrownBy(
() ->
UpdateTableRequestParser.fromJson(
"{\"identifier\":{\"namespace\":[\"ns1\"],\"name\":\"table1\"},"
+ "\"requirements\":[23],\"updates\":[]}"))
.isInstanceOf(IllegalA... |
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
boolean... | @Test
public void testExecute() throws SubCommandException {
CleanUnusedTopicCommand cmd = new CleanUnusedTopicCommand();
Options options = ServerUtil.buildCommandlineOptions(new Options());
String[] subargs = new String[] {"-b 127.0.0.1:" + listenPort(), "-c default-cluster"};
final... |
public String format(Date then)
{
if (then == null)
then = now();
Duration d = approximateDuration(then);
return format(d);
} | @Test
public void testMonthsFromNow() throws Exception
{
PrettyTime t = new PrettyTime(now);
Assert.assertEquals("3 months from now", t.format(now.plusMonths(3)));
} |
public void unschedule(String eventDefinitionId) {
final EventDefinitionDto eventDefinition = getEventDefinitionOrThrowIAE(eventDefinitionId);
if (SystemNotificationEventEntityScope.NAME.equals(eventDefinition.scope())) {
LOG.debug("Ignoring disable for system notification events");
... | @Test
@MongoDBFixtures("event-processors.json")
public void unschedule() {
assertThat(eventDefinitionService.get("54e3deadbeefdeadbeef0000")).isPresent();
assertThat(jobDefinitionService.get("54e3deadbeefdeadbeef0001")).isPresent();
assertThat(jobTriggerService.get("54e3deadbeefdeadbeef0... |
@Override
public String toString() {
return "EmbeddedRocksDBStateBackend{"
+ ", localRocksDbDirectories="
+ Arrays.toString(localRocksDbDirectories)
+ ", enableIncrementalCheckpointing="
+ enableIncrementalCheckpointing
+ ", num... | @TestTemplate
public void testSmallFilesCompaction() throws Exception {
ValueStateDescriptor<String> kvId = new ValueStateDescriptor<>("id", String.class);
SharedStateRegistry sharedStateRegistry = new SharedStateRegistryImpl();
CheckpointStreamFactory streamFactory = createStreamFactory();
... |
public Command create(
final ConfiguredStatement<? extends Statement> statement,
final KsqlExecutionContext context) {
return create(statement, context.getServiceContext(), context);
} | @Test
public void shouldCreateCommandForPlannedQuery() {
// Given:
givenPlannedQuery();
// When:
final Command command = commandFactory.create(configuredStatement, executionContext);
// Then:
assertThat(command, is(Command.of(ConfiguredKsqlPlan.of(A_PLAN, SessionConfig.of(config, overrides))... |
public static String generateResourceId(
String baseString,
Pattern illegalChars,
String replaceChar,
int targetLength,
DateTimeFormatter timeFormat) {
// first, make sure the baseString, typically the test ID, is not empty
checkArgument(baseString.length() != 0, "baseString cannot... | @Test
public void testGenerateResourceIdShouldReplaceDollarSignWithHyphen() {
String testBaseString = "test$instance";
String actual =
generateResourceId(
testBaseString,
ILLEGAL_INSTANCE_CHARS,
REPLACE_INSTANCE_CHAR,
MAX_INSTANCE_ID_LENGTH,
... |
public static <T> VerboseCondition<T> verboseCondition(Predicate<T> predicate, String description,
Function<T, String> objectUnderTestDescriptor) {
return new VerboseCondition<>(predicate, description, objectUnderTestDescriptor);
} | @Test
public void should_throw_NullPointerException_if_condition_predicate_is_null() {
assertThatNullPointerException().isThrownBy(() -> verboseCondition(null, "description", t -> ""));
} |
@Override
@CheckForNull
public EmailMessage format(Notification notif) {
if (!(notif instanceof ChangesOnMyIssuesNotification)) {
return null;
}
ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif;
if (notification.getChange() instanceof AnalysisChange) {
... | @Test
public void formats_returns_html_message_with_projects_ordered_by_name_when_user_change() {
Project project1 = newProject("1");
Project project1Branch1 = newBranch("1", "a");
Project project1Branch2 = newBranch("1", "b");
Project project2 = newProject("B");
Project project2Branch1 = newBranc... |
public static int calculateDefaultNumSlots(
ResourceProfile totalResourceProfile, ResourceProfile defaultSlotResourceProfile) {
// For ResourceProfile.ANY in test case, return the maximum integer
if (totalResourceProfile.equals(ResourceProfile.ANY)) {
return Integer.MAX_VALUE;
... | @Test
void testCalculateDefaultNumSlotsFailZeroDefaultSlotProfile() {
assertThatThrownBy(
() ->
SlotManagerUtils.calculateDefaultNumSlots(
ResourceProfile.fromResources(1.0, 1),
... |
@Override
public ObjectNode encode(Instruction instruction, CodecContext context) {
checkNotNull(instruction, "Instruction cannot be null");
return new EncodeInstructionCodecHelper(instruction, context).encode();
} | @Test
public void modIPv6DstInstructionTest() {
final Ip6Address ip = Ip6Address.valueOf("1111::2222");
final L3ModificationInstruction.ModIPInstruction instruction =
(L3ModificationInstruction.ModIPInstruction)
Instructions.modL3IPv6Dst(ip);
final Obj... |
@Override
public void writeFiltered(List<FilteredMessage> filteredMessages) throws Exception {
final var messages = filteredMessages.stream()
.filter(message -> !message.destinations().get(FILTER_KEY).isEmpty())
.toList();
writes.mark(messages.size());
ignore... | @Test
public void writeFilteredWithMultipleStreams() throws Exception {
final List<Message> messageList = buildMessages(2);
messageList.forEach(message -> message.addStream(testStream));
output.writeFiltered(List.of(
// The first message should not be written to the output ... |
@Override
public NodeHealth get() {
Health nodeHealth = healthChecker.checkNode();
this.nodeHealthBuilder
.clearCauses()
.setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name()));
nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause);
return this.nodeHealthBuilder
... | @Test
public void get_returns_host_from_property_if_set_at_constructor_time() {
String host = randomAlphanumeric(4);
mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3));
mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4));
mapSettings.setProperty(CLUSTE... |
public static StreamingService getServiceByUrl(final String url) throws ExtractionException {
for (final StreamingService service : ServiceList.all()) {
if (service.getLinkTypeByUrl(url) != StreamingService.LinkType.NONE) {
return service;
}
}
throw new Ex... | @Test
public void getServiceWithUrl() throws Exception {
assertEquals(getServiceByUrl("https://www.youtube.com/watch?v=_r6CgaFNAGg"), YouTube);
assertEquals(getServiceByUrl("https://www.youtube.com/channel/UCi2bIyFtz-JdI-ou8kaqsqg"), YouTube);
assertEquals(getServiceByUrl("https://www.youtub... |
public WorkflowInstance getWorkflowInstance(
String workflowId, long workflowInstanceId, String workflowRun, boolean aggregated) {
long runId = Constants.LATEST_ONE;
if (!Constants.LATEST_INSTANCE_RUN.equalsIgnoreCase(workflowRun)) {
runId = Long.parseLong(workflowRun);
}
WorkflowInstance in... | @Test
public void testGetWorkflowInstance() {
WorkflowInstance instanceRun =
instanceDao.getWorkflowInstance(
wfi.getWorkflowId(), wfi.getWorkflowInstanceId(), Constants.LATEST_INSTANCE_RUN, false);
instanceRun.setModifyTime(null);
assertEquals(wfi, instanceRun);
instanceRun =
... |
public static String getOperatingSystemCompleteName() {
return OS_COMPLETE_NAME;
} | @Test
@EnabledOnOs(OS.WINDOWS)
public void shouldGetCompleteNameOnWindows() {
assertThat(SystemInfo.getOperatingSystemCompleteName()).matches("Windows( \\w+)? [0-9.]+( \\(.*\\))?");
} |
public static Map<String, Object> getRowDataMap(Row source) {
Map<String, Object> toReturn = new HashMap<>();
List<Element> elements = source.getContent().stream()
.filter(Element.class::isInstance)
.map(Element.class::cast)
.collect(Collectors.toList());
... | @Test
void getRowDataMap() {
Row source = getRandomRowWithCells();
Map<String, Object> retrieved = ModelUtils.getRowDataMap(source);
InputCell inputCell = source.getContent().stream()
.filter(InputCell.class::isInstance)
.map(InputCell.class::cast)
... |
public static Builder builder() {
return new Builder();
} | @Test
public void testBuilder_fail() {
try {
CachedLayer.builder().build();
Assert.fail("missing required");
} catch (NullPointerException ex) {
MatcherAssert.assertThat(ex.getMessage(), CoreMatchers.containsString("layerDigest"));
}
try {
CachedLayer.builder().setLayerDigest... |
@Override
public Collection<RedisServer> masters() {
List<Map<String, String>> masters = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_MASTERS);
return toRedisServersList(masters);
} | @Test
public void testMasters() {
Collection<RedisServer> masters = connection.masters();
assertThat(masters).hasSize(1);
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final Map<String, Object> event;
try {
event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT);
} catch (IOException e) {
... | @Test
public void decodeMessagesHandlesGenericBeatWithCloudGCE() throws Exception {
final Message message = codec.decode(messageFromJson("generic-with-cloud-gce.json"));
assertThat(message).isNotNull();
assertThat(message.getMessage()).isEqualTo("null");
assertThat(message.getSource(... |
static HttpRequest setOperation(HttpRequest request, com.yahoo.jdisc.http.HttpRequest.Method method) {
return switch (method) {
case GET -> request.setHttpOperation(HttpRequest.HttpOp.GET);
case POST -> request.setHttpOperation(HttpRequest.HttpOp.POST);
case PUT -> request.se... | @Test
void testInvalidMethod() {
try {
HttpRequest request = new HttpRequest();
JDiscHttpRequestHandler.setOperation(request, com.yahoo.jdisc.http.HttpRequest.Method.CONNECT);
fail("Control should not reach here");
} catch (IllegalStateException e) {
a... |
@Deprecated
@SuppressWarnings("InlineMeSuggester")
public static final <T extends Activity> T setupActivity(Class<T> activityClass) {
return buildActivity(activityClass).setup().get();
} | @Test
@Config(sdk = Config.NEWEST_SDK)
public void setupActivity_returnsAVisibleActivity() throws Exception {
LifeCycleActivity activity = Robolectric.setupActivity(LifeCycleActivity.class);
assertThat(activity.isCreated()).isTrue();
assertThat(activity.isStarted()).isTrue();
assertThat(activity.is... |
public void setMaxApps(int max) {
maxApps.set(max);
} | @Test
public void testSetMaxApps() {
FSQueueMetrics metrics = setupMetrics(RESOURCE_NAME);
metrics.setMaxApps(25);
assertEquals(getErrorMessage("maxApps"), 25L, metrics.getMaxApps());
} |
public static PMML4Result evaluate(final KiePMMLModel model, final PMMLRuntimeContext context) {
if (logger.isDebugEnabled()) {
logger.debug("evaluate {} {}", model, context);
}
addStep(() -> getStep(START, model, context.getRequestData()), context);
final ProcessingDTO proce... | @Test
public void evaluateWithPMMLContextListeners() {
modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME);
final List<PMMLStep> pmmlSteps = new ArrayList<>();
PMMLRuntimeContext pmmlContext = getPMMLContext(FILE_NAME, MODEL_NAME,
... |
static String normalizeMemory(String memory) {
return formatMemory(parseMemory(memory));
} | @Test
public void testNormalizeMemory() {
assertThat(normalizeMemory("1K"), is("1000"));
assertThat(normalizeMemory("1Ki"), is("1024"));
assertThat(normalizeMemory("1M"), is("1000000"));
assertThat(normalizeMemory("1Mi"), is("1048576"));
assertThat(normalizeMemory("12345"), i... |
public MemoryManager(float ratio, long minAllocation) {
checkRatio(ratio);
memoryPoolRatio = ratio;
minMemoryAllocation = minAllocation;
totalMemoryPool = Math.round((double)
ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax()
* ratio);
LOG.debug("Allocated total m... | @Test
public void testMemoryManager() throws Exception {
long poolSize = ParquetOutputFormat.getMemoryManager().getTotalMemoryPool();
long rowGroupSize = poolSize / 2;
conf.setLong(ParquetOutputFormat.BLOCK_SIZE, rowGroupSize);
Assert.assertTrue("Pool should hold 2 full row groups", (2 * rowGroupSize... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.