focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public <T> T select(final List<T> elements) {
if (elements == null) {
throw new NullPointerException("elements");
}
final int size = elements.size();
if (size == 1) {
return elements.get(0);
}
final int roundRobinIndex = indexUpdat... | @Test
public void selectTest() {
List<Integer> elements = Lists.newArrayList();
elements.add(0);
elements.add(1);
elements.add(2);
elements.add(3);
elements.add(4);
RoundRobinLoadBalancer balancer1 = RoundRobinLoadBalancer.getInstance(1);
Assert.assert... |
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
} | @Test
void testIsValidAddress() {
assertFalse(NetUtils.isValidV4Address((InetAddress) null));
InetAddress address = mock(InetAddress.class);
when(address.isLoopbackAddress()).thenReturn(true);
assertFalse(NetUtils.isValidV4Address(address));
address = mock(InetAddress.class);... |
boolean isQueueEmpty() {
return queue == null || queue.isEmpty();
} | @Test
public void testFlowAutoReadOn() throws Exception {
final CountDownLatch latch = new CountDownLatch(3);
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
ChannelInboundHandlerAdapter handler = new ChannelDuplexHandler() {
@Override
public void chann... |
@Override
public CompletableFuture<Collection<TaskManagerLocation>> getPreferredLocations(
final ExecutionVertexID executionVertexId,
final Set<ExecutionVertexID> producersToIgnore) {
checkNotNull(executionVertexId);
checkNotNull(producersToIgnore);
final Collection... | @Test
void testStateLocationsWillBeReturnedIfExist() {
final TaskManagerLocation stateLocation = new LocalTaskManagerLocation();
final TestingInputsLocationsRetriever.Builder locationRetrieverBuilder =
new TestingInputsLocationsRetriever.Builder();
final ExecutionVertexID c... |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testDocumentDividedViaHorizontalRules() {
MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
.withHorizontalRuleCreateDocument(true)
.build();
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/horizontal-rules.md", config);
List<Document> document... |
@Override
public Object convertData( ValueMetaInterface meta2, Object data2 ) throws KettleValueException {
switch ( meta2.getType() ) {
case TYPE_STRING:
return convertStringToInternetAddress( meta2.getString( data2 ) );
case TYPE_INTEGER:
return convertIntegerToInternetAddress( meta2... | @Test
public void testConvertStringIPv6() throws Exception {
ValueMetaInterface vmia = new ValueMetaInternetAddress( "Test" );
ValueMetaString vms = new ValueMetaString( "aString" );
Object convertedIPv6 = vmia.convertData( vms, SAMPLE_IPV6_AS_STRING );
assertNotNull( convertedIPv6 );
assertTrue(... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
try {
if (statement.getStatement() instanceof CreateAsSelect) {
registerForCreateAs((ConfiguredStatement<? extends CreateAsSelect>) statement);
... | @Test
public void shouldThrowWrongKeyFormatExceptionWithOverrideSchema() throws Exception {
// Given:
final SchemaAndId keySchemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCHEMA, 1);
final SchemaAndId valueSchemaAndId = SchemaAndId.schemaAndId(SCHEMA.value(), AVRO_SCHEMA, 2);
givenStatement... |
@SuppressFBWarnings(value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
public int encode(CacheScope scopeInfo) {
if (!mScopeToId.containsKey(scopeInfo)) {
synchronized (this) {
if (!mScopeToId.containsKey(scopeInfo)) {
// NOTE: If update mScopeToId ahead of updating mIdToScope,
//... | @Test
public void testConcurrentEncodeDecode() throws Exception {
List<Runnable> runnables = new ArrayList<>();
for (int k = 0; k < DEFAULT_THREAD_AMOUNT; k++) {
runnables.add(() -> {
for (int i = 0; i < NUM_SCOPES * 16; i++) {
int r = ThreadLocalRandom.current().nextInt(NUM_SCOPES);
... |
@Override
public Consumer createConsumer(Processor processor) throws Exception {
DebeziumConsumer consumer = new DebeziumConsumer(this, processor);
configureConsumer(consumer);
return consumer;
} | @Test
void testIfCreatesConsumer() throws Exception {
final Consumer debeziumConsumer = debeziumEndpoint.createConsumer(processor);
assertNotNull(debeziumConsumer);
} |
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList();
} | @Test
void usersToUserDTOsShouldMapOnlyNonNullUsers() {
List<User> users = new ArrayList<>();
users.add(user);
users.add(null);
List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users);
assertThat(userDTOS).isNotEmpty().size().isEqualTo(1);
} |
@VisibleForTesting
public ConfigDO validateConfigExists(Long id) {
if (id == null) {
return null;
}
ConfigDO config = configMapper.selectById(id);
if (config == null) {
throw exception(CONFIG_NOT_EXISTS);
}
return config;
} | @Test
public void testValidateConfigExist_notExists() {
assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS);
} |
public static int ge0(int value, String name) {
return (int) ge0((long) value, name);
} | @Test
public void checkGEZero() {
assertEquals(Check.ge0(120, "test"), 120);
assertEquals(Check.ge0(0, "test"), 0);
} |
@Override
public void encode(Event event, OutputStream output) throws IOException {
String outputString = (format == null
? event.toString()
: StringInterpolation.evaluate(event, format));
output.write(outputString.getBytes(charset));
} | @Test
public void testEncodeWithUtf8() throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String message = new String("München 安装中文输入法".getBytes(), Charset.forName("UTF-8"));
Map<String, Object> config = new HashMap<>();
config.put("format", "%{mes... |
public static <E> List<E> ensureImmutable(List<E> list) {
if (list.isEmpty()) return Collections.emptyList();
// Faster to make a copy than check the type to see if it is already a singleton list
if (list.size() == 1) return Collections.singletonList(list.get(0));
if (isImmutable(list)) return list;
... | @Test void ensureImmutable_singletonListStaysSingleton() {
List<Object> list = Collections.singletonList("foo");
assertThat(Lists.ensureImmutable(list).getClass().getSimpleName())
.isEqualTo("SingletonList");
} |
@Override
public Object toKsqlRow(final Schema connectSchema, final Object connectObject) {
final Object avroCompatibleRow = innerTranslator.toKsqlRow(connectSchema, connectObject);
if (avroCompatibleRow == null) {
return null;
}
return ConnectSchemas.withCompatibleSchema(ksqlSchema, avroCompat... | @Test
public void shouldReturnBytes() {
// When:
final AvroDataTranslator translator =
new AvroDataTranslator(Schema.BYTES_SCHEMA, AvroProperties.DEFAULT_AVRO_SCHEMA_FULL_NAME);
// Then:
assertThat(
translator.toKsqlRow(Schema.BYTES_SCHEMA, new byte[] {123}),
is(ByteBuffer.wra... |
public ProviderBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
} | @Test
void accepts() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.accepts(35);
Assertions.assertEquals(35, builder.build().getAccepts());
} |
public void createRole( IRole newRole ) throws KettleException {
normalizeRoleInfo( newRole );
if ( !validateRoleInfo( newRole ) ) {
throw new KettleException( BaseMessages.getString( PurRepositorySecurityManager.class,
"PurRepositorySecurityManager.ERROR_0001_INVALID_NAME" ) );
}
userRo... | @Test
public void createRole_NormalizesInfo_PassesIfNoViolations() throws Exception {
IRole info = new EERoleInfo( "role ", "" );
ArgumentCaptor<IRole> captor = ArgumentCaptor.forClass( IRole.class );
manager.createRole( info );
verify( roleDelegate ).createRole( captor.capture() );
info = capt... |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
if (isGrayImage(image))
{
return createFromGrayImage(image, document);
}
// We try to encode the image with predictor
if (USE_PREDICTOR_ENCODER... | @Test
void testCreateLosslessFromImageINT_BGR() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(this.getClass().getResourceAsStream("png.png"));
BufferedImage imgBgr = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TY... |
public static GSBlobIdentifier getTemporaryBlobIdentifier(
GSBlobIdentifier finalBlobIdentifier,
UUID temporaryObjectId,
GSFileSystemOptions options) {
String temporaryBucketName = BlobUtils.getTemporaryBucketName(finalBlobIdentifier, options);
String temporaryObjectN... | @Test
public void shouldProperlyConstructTemporaryBlobIdentifierWithDefaultBucket() {
Configuration flinkConfig = new Configuration();
GSFileSystemOptions options = new GSFileSystemOptions(flinkConfig);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryO... |
@GET
@Path("/conversions")
@Produces(MediaType.APPLICATION_JSON)
public CurrencyConversionEntityList getConversions(final @ReadOnly @Auth AuthenticatedDevice auth) {
return currencyManager.getCurrencyConversions().orElseThrow();
} | @Test
void testGetCurrencyConversions() {
CurrencyConversionEntityList conversions =
resources.getJerseyTest()
.target("/v1/payments/conversions")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWOR... |
@Override
public Set<K> keySet() {
Set<IdentityObject<K>> set = mInternalMap.keySet();
return new Set<K>() {
@Override
public int size() {
return set.size();
}
@Override
public boolean isEmpty() {
return set.isEmpty();
}
@Override
public boole... | @Test
public void keySet() {
String x = new String("x");
String xx = new String("x");
assertNull(mMap.put(x, "x"));
assertNull(mMap.put(xx, "x2"));
assertEquals(2, mMap.size());
Set<String> km = mMap.keySet();
assertEquals(2, km.size());
assertTrue(km.contains(x));
assertTrue(km.co... |
public EvaluationResult evaluate(Condition condition, Measure measure) {
checkArgument(SUPPORTED_METRIC_TYPE.contains(condition.getMetric().getType()), "Conditions on MetricType %s are not supported", condition.getMetric().getType());
Comparable measureComparable = parseMeasure(measure);
if (measureCompara... | @Test
public void test_condition_on_rating() {
Metric metric = createMetric(RATING);
Measure measure = newMeasureBuilder().create(4, "D");
assertThat(underTest.evaluate(new Condition(metric, GREATER_THAN.getDbValue(), "4"), measure)).hasLevel(OK).hasValue(4);
assertThat(underTest.evaluate(new Conditi... |
@Override
public boolean serverHealthy() {
return grpcClientProxy.serverHealthy() || httpClientProxy.serverHealthy();
} | @Test
void testServerHealthy() {
Mockito.when(mockGrpcClient.serverHealthy()).thenReturn(true);
assertTrue(delegate.serverHealthy());
} |
@Override
public Iterator<Object> iterateObjects() {
return new CompositeObjectIterator(concreteStores, true);
} | @Test
public void isOkayToReinsertSameTypeThenQuery() throws Exception {
insertObjectWithFactHandle(new SubClass());
insertObjectWithFactHandle(new SubClass());
Collection<Object> result = collect(underTest.iterateObjects(SuperClass.class));
assertThat(result).hasSize(2);
... |
public static Optional<File> getFileFromFileNameOrFilePath(String fileName, String filePath) {
Optional<File> fromClassloader = getFileByFileNameFromClassloader(fileName, Thread.currentThread().getContextClassLoader());
return fromClassloader.isPresent() ? fromClassloader : getFileByFilePath(filePath);... | @Test
void getFileFromFileNameOrFilePathExisting() {
Optional<File> retrieved = MemoryFileUtils.getFileFromFileNameOrFilePath(TEST_FILE, TEST_FILE);
assertThat(retrieved).isNotNull().isNotEmpty();
String path = String.format("target%1$stest-classes%1$s%2$s", File.separator, TEST_FILE);
... |
static ManifestFile fromJson(JsonNode jsonNode) {
Preconditions.checkArgument(jsonNode != null, "Invalid JSON node for manifest file: null");
Preconditions.checkArgument(
jsonNode.isObject(), "Invalid JSON node for manifest file: non-object (%s)", jsonNode);
String path = JsonUtil.getString(PATH, j... | @Test
public void invalidJsonNode() throws Exception {
String jsonStr = "{\"str\":\"1\", \"arr\":[]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.reader().readTree(jsonStr);
assertThatThrownBy(() -> ManifestFileParser.fromJson(rootNode.get("str")))
.isInstanceOf(Ille... |
public Set<String> exposedHeaders() {
return Collections.unmodifiableSet(exposeHeaders);
} | @Test
public void exposeHeaders() {
final CorsConfig cors = forAnyOrigin().exposeHeaders("custom-header1", "custom-header2").build();
assertThat(cors.exposedHeaders(), hasItems("custom-header1", "custom-header2"));
} |
@Override
public void destroy() {
super.destroy();
cache.clear();
listener.remove();
} | @Test
public void testSubscriptionTimeout() {
Config config = new Config();
config.useSingleServer()
.setSubscriptionsPerConnection(2)
.setSubscriptionConnectionPoolSize(1)
.setAddress(redisson.getConfig().useSingleServer().getAddress());
Redis... |
public static TraceTransferBean encoderFromContextBean(TraceContext ctx) {
if (ctx == null) {
return null;
}
//build message trace of the transferring entity content bean
TraceTransferBean transferBean = new TraceTransferBean();
StringBuilder sb = new StringBuilder(25... | @Test
public void testTraceKeys() {
TraceContext endTrxContext = new TraceContext();
endTrxContext.setTraceType(TraceType.EndTransaction);
endTrxContext.setGroupName("PID-test");
endTrxContext.setRegionId("DefaultRegion");
endTrxContext.setTimeStamp(time);
TraceBean e... |
@PublicEvolving
public static AIMDScalingStrategyBuilder builder(int rateThreshold) {
return new AIMDScalingStrategyBuilder(rateThreshold);
} | @Test
void testInvalidRateThreshold() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() ->
AIMDScalingStrategy.builder(0)
.setIncreaseRate(1)
... |
@Operation(summary = "delete", description = "Delete a host")
@DeleteMapping("/{id}")
public ResponseEntity<Boolean> delete(@PathVariable Long clusterId, @PathVariable Long id) {
return ResponseEntity.success(hostService.delete(id));
} | @Test
void deleteReturnsFalseForInvalidHostId() {
Long clusterId = 1L;
Long hostId = 999L;
when(hostService.delete(hostId)).thenReturn(false);
ResponseEntity<Boolean> response = hostController.delete(clusterId, hostId);
assertTrue(response.isSuccess());
assertFalse(... |
@Override
public String rpcType() {
return RpcTypeEnum.SOFA.getName();
} | @Test
public void testRpcType() {
String rpcType = shenyuClientRegisterSofaService.rpcType();
assertEquals(RpcTypeEnum.SOFA.getName(), rpcType);
} |
@Override
public CompletableFuture<Void> authorizeConfigRequest(Request request) {
return doAsyncAuthorization(request, this::doConfigRequestAuthorization);
} | @Test
public void tenant_node_cannot_access_lbservice_config() throws ExecutionException, InterruptedException {
RpcAuthorizer authorizer = createAuthorizer(new NodeIdentity.Builder(NodeType.tenant).build(), new HostRegistry());
Request configRequest = createConfigRequest(
new Confi... |
public static BadRequestException clusterAlreadyExists(String clusterName) {
return new BadRequestException("cluster already exists for clusterName:%s", clusterName);
} | @Test
public void testClusterAlreadyExists(){
BadRequestException clusterAlreadyExists = BadRequestException.clusterAlreadyExists(clusterName);
assertEquals("cluster already exists for clusterName:test", clusterAlreadyExists.getMessage());
} |
private void announceBackgroundJobServer() {
final BackgroundJobServerStatus serverStatus = backgroundJobServer.getServerStatus();
storageProvider.announceBackgroundJobServer(serverStatus);
determineIfCurrentBackgroundJobServerIsMaster();
lastSignalAlive = serverStatus.getLastHeartbeat()... | @Test
void onStartServerAnnouncesItselfAndDoesNotBecomeMasterIfItIsNotTheFirstToBeOnline() {
final BackgroundJobServerStatus master = anotherServer();
storageProvider.announceBackgroundJobServer(master);
backgroundJobServer.start();
await().untilAsserted(() -> assertThat(storagePro... |
@Override
public Usuario getUsuarioByUsername(String username) {
Usuario usuario = usuarioRepository.findByUsername(username).orElseThrow(
() -> new ResourceNotFoundException("Usuario no encontrado con el id: " + username));
// Obtengo las calificaciones usando RestTemplate
... | @Test
void testGetUsuarioByUsername() {
when(usuarioRepository.findByUsername(anyString())).thenReturn(Optional.of(usuario));
when(restTemplate.getForObject(anyString(), eq(Calificacion[].class))).thenReturn(new Calificacion[0]);
Usuario foundUsuario = usuarioService.getUsuarioByUsername("j... |
public OffsetRange[] getNextOffsetRanges(Option<String> lastCheckpointStr, long sourceLimit, HoodieIngestionMetrics metrics) {
// Come up with final set of OffsetRanges to read (account for new partitions, limit number of events)
long maxEventsToReadFromKafka = getLongWithAltKeys(props, KafkaSourceConfig.MAX_EV... | @Test
public void testGetNextOffsetRangesFromSingleOffsetCheckpoint() {
HoodieTestDataGenerator dataGenerator = new HoodieTestDataGenerator();
testUtils.createTopic(testTopicName, 1);
testUtils.sendMessages(testTopicName, Helpers.jsonifyRecords(dataGenerator.generateInserts("000", 1000)));
KafkaOffset... |
@Override
public ChannelFuture writeGoAway(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData,
ChannelPromise promise) {
return lifecycleManager.goAway(ctx, lastStreamId, errorCode, debugData, promise);
} | @Test
public void encoderDelegatesGoAwayToLifeCycleManager() {
ChannelPromise promise = newPromise();
encoder.writeGoAway(ctx, STREAM_ID, Http2Error.INTERNAL_ERROR.code(), null, promise);
verify(lifecycleManager).goAway(eq(ctx), eq(STREAM_ID), eq(Http2Error.INTERNAL_ERROR.code()),
... |
int sendBackups0(BackupAwareOperation backupAwareOp) {
int requestedSyncBackups = requestedSyncBackups(backupAwareOp);
int requestedAsyncBackups = requestedAsyncBackups(backupAwareOp);
int requestedTotalBackups = requestedTotalBackups(backupAwareOp);
if (requestedTotalBackups == 0) {
... | @Test(expected = IllegalArgumentException.class)
public void backup_whenTooLargeSyncBackupCount() {
setup(BACKPRESSURE_ENABLED);
BackupAwareOperation op = makeOperation(MAX_BACKUP_COUNT + 1, 0);
backupHandler.sendBackups0(op);
} |
public int getTargetDocsPerChunk() {
return _targetDocsPerChunk;
} | @Test
public void withNegativeTargetDocsPerChunk()
throws JsonProcessingException {
String confStr = "{\"targetDocsPerChunk\": \"-1\"}";
ForwardIndexConfig config = JsonUtils.stringToObject(confStr, ForwardIndexConfig.class);
assertEquals(config.getTargetDocsPerChunk(), -1, "Unexpected defaultTarge... |
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
ApolloListener apolloListener = listeners.computeIfAbsent(group + key, k -> createTargetListener(key, group));
apolloListener.addListener(listener);
dubboConfig.addChangeListener(apolloListener, Col... | @Test
void testAddListener() throws Exception {
String mockKey = "mockKey3";
String mockValue = String.valueOf(new Random().nextInt());
final SettableFuture<org.apache.dubbo.common.config.configcenter.ConfigChangedEvent> future =
SettableFuture.create();
apolloDynam... |
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final List<MavenArtifact> result = new ArrayList<>();
try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
JsonParser ... | @Test
public void shouldProcessCorrectlyArtifactoryAnswerMisMatchMd5() throws IOException {
// Given
Dependency dependency = new Dependency();
dependency.setSha1sum("c5b4c491aecb72e7c32a78da0b5c6b9cda8dee0f");
dependency.setSha256sum("512b4bf6927f4864acc419b8c5109c23361c30ed1f5798170... |
public Lifecycle getLifecycle() {
return lifecycle;
} | @Test
public void testGetLifecycle() throws Exception {
assertEquals(Lifecycle.UNINITIALIZED, status.getLifecycle());
} |
public static TemplateEngine createEngine() {
return TemplateFactory.create();
} | @Test
public void enjoyEngineTest() {
// 字符串模板
TemplateEngine engine = TemplateUtil.createEngine(
new TemplateConfig("templates").setCustomEngine(EnjoyEngine.class));
Template template = engine.getTemplate("#(x + 123)");
String result = template.render(Dict.create().set("x", 1));
assertEquals("124", resu... |
@Override
public boolean setAlertFilter(String severity) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().deviceId... | @Test
public void testInvalidSetAlertFilterInput() throws Exception {
String target;
boolean result;
for (int i = ZERO; i < INVALID_SET_TCS.length; i++) {
target = INVALID_SET_TCS[i];
result = voltConfig.setAlertFilter(target);
assertFalse("Incorrect resp... |
@Override
protected long getEncodedElementByteSize(BigInteger value) throws Exception {
checkNotNull(value, String.format("cannot encode a null %s", BigInteger.class.getSimpleName()));
return BYTE_ARRAY_CODER.getEncodedElementByteSize(value.toByteArray());
} | @Test
public void testGetEncodedElementByteSize() throws Exception {
TestElementByteSizeObserver observer = new TestElementByteSizeObserver();
for (BigInteger value : TEST_VALUES) {
TEST_CODER.registerByteSizeObserver(value, observer);
observer.advance();
assertThat(
observer.getSu... |
@Override
public void populateCxfRequestFromExchange(
org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange,
Map<String, Object> requestContext) {
// propagate request context
Map<String, Object> camelHeaders = camelExchange.getIn().getHeaders();
extrac... | @Test
public void testPopulateCxfRequestFromExchange() {
DefaultCxfBinding cxfBinding = new DefaultCxfBinding();
cxfBinding.setHeaderFilterStrategy(new DefaultHeaderFilterStrategy());
Exchange exchange = new DefaultExchange(context);
org.apache.cxf.message.Exchange cxfExchange = new ... |
@Override
public HttpHeaders add(HttpHeaders headers) {
if (headers instanceof DefaultHttpHeaders) {
this.headers.add(((DefaultHttpHeaders) headers).headers);
return this;
} else {
return super.add(headers);
}
} | @Test
public void nullHeaderNameNotAllowed() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
new DefaultHttpHeaders().add(null, "foo");
}
});
} |
private KafkaPool(
Reconciliation reconciliation,
Kafka kafka,
KafkaNodePool pool,
String componentName,
OwnerReference ownerReference,
NodeIdAssignment idAssignment,
SharedEnvironmentProvider sharedEnvironmentProvider
) {
s... | @Test
public void testKafkaPool() {
KafkaPool kp = KafkaPool.fromCrd(
Reconciliation.DUMMY_RECONCILIATION,
KAFKA,
POOL,
new NodeIdAssignment(Set.of(10, 11, 13), Set.of(10, 11, 13), Set.of(), Set.of(), Set.of()),
new JbodStorage... |
@Override
public Stream<ColumnName> resolveSelectStar(
final Optional<SourceName> sourceName
) {
return getSource().resolveSelectStar(sourceName)
.map(name -> aliases.getOrDefault(name, name));
} | @Test
public void shouldAddAliasOnResolveSelectStarWhenAliased() {
// Given:
when(source.resolveSelectStar(any()))
.thenReturn(ImmutableList.of(COL_1, COL_0, COL_2).stream());
// When:
final Stream<ColumnName> result = projectNode.resolveSelectStar(Optional.empty());
// Then:
final L... |
static Map<String, String> getSparkConf(String configFile, List<String> variables) {
Config appConfig = ConfigBuilder.of(configFile, variables);
return appConfig.getConfig("env").entrySet().stream()
.collect(
Collectors.toMap(
Map.E... | @Test
public void testGetSparkConf() throws URISyntaxException, FileNotFoundException {
URI uri = ClassLoader.getSystemResource("spark_application.conf").toURI();
String file = new File(uri).toString();
Map<String, String> sparkConf = SparkStarter.getSparkConf(file, null);
assertEqua... |
@Override
public String toString() {
return String.format(
Locale.US,
"%s '%s' from %s (id %s), API-%d",
getClass().getName(),
mName,
mPackageName,
mId,
mApiVersion);
} | @Test
public void testToString() {
String toString = new TestableAddOn("id1", "name111", 8).toString();
Assert.assertTrue(toString.contains("name111"));
Assert.assertTrue(toString.contains("id1"));
Assert.assertTrue(toString.contains("TestableAddOn"));
Assert.assertTrue(toString.contains(getAppli... |
static void encodeFlowControlReceiver(
final UnsafeBuffer encodingBuffer,
final int offset,
final int captureLength,
final int length,
final long receiverId,
final int sessionId,
final int streamId,
final String channel,
final int receiverCount)
... | @Test
void encodeFlowControlReceiverShouldWriteChannelLast()
{
final int offset = 48;
final long receiverId = 1947384623864823283L;
final int sessionId = 219;
final int streamId = 3;
final String channel = "my channel";
final int receiverCount = 17;
final ... |
public ClientAuth getClientAuth() {
String clientAuth = getString(SSL_CLIENT_AUTHENTICATION_CONFIG);
if (originals().containsKey(SSL_CLIENT_AUTH_CONFIG)) {
if (originals().containsKey(SSL_CLIENT_AUTHENTICATION_CONFIG)) {
log.warn(
"The {} configuration is deprecated. Since a value has... | @Test
public void shouldUseClientAuthenticationIfClientAuthProvidedRequested() {
// Given:
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(KsqlRestConfig.SSL_CLIENT_AUTH_CONFIG, false)
.put(KsqlRestConfig.SSL_CLIENT_AUTHENTICATION_CONFIG,
... |
public String format() {
return dataSourceName + DELIMITER + tableName;
} | @Test
void assertFormat() {
String expected = "ds_0.tbl_0";
DataNode dataNode = new DataNode(expected);
assertThat(dataNode.format(), is(expected));
} |
public static FunctionDetails convert(SourceConfig sourceConfig, ExtractedSourceDetails sourceDetails)
throws IllegalArgumentException {
FunctionDetails.Builder functionDetailsBuilder = FunctionDetails.newBuilder();
boolean isBuiltin = !StringUtils.isEmpty(sourceConfig.getArchive()) && sour... | @Test
public void testSupportsBatchBuilderWhenProducerConfigExists() {
SourceConfig sourceConfig = createSourceConfig();
sourceConfig.setBatchBuilder("KEY_BASED");
sourceConfig.getProducerConfig().setMaxPendingMessages(123456);
Function.FunctionDetails functionDetails =
... |
public PrimitiveType encodingType()
{
return encodingType;
} | @Test
void shouldHandleEncodingTypesWithNamedTypes() throws Exception
{
try (InputStream in = Tests.getLocalResource("encoding-types-schema.xml"))
{
final MessageSchema schema = parse(in, ParserOptions.DEFAULT);
final List<Field> fields = schema.getMessage(1).fields();
... |
public static <Key extends Comparable, Value, ListType extends List<Value>> MultiMap<Key, Value, ListType> make(final boolean updatable,
final NewSubMapProvider<Value, ListType> newSubMapProvider) {
... | @Test
void changeHandled() throws Exception {
assertThat(MultiMapFactory.make(true) instanceof ChangeHandledMultiMap).isTrue();
} |
@Deprecated
static Optional<GlobalStreamExchangeMode> getGlobalStreamExchangeMode(ReadableConfig config) {
return config.getOptional(ExecutionConfigOptions.TABLE_EXEC_SHUFFLE_MODE)
.map(
value -> {
try {
retu... | @Test
void testLegacyShuffleMode() {
final Configuration configuration = new Configuration();
configuration.set(
ExecutionConfigOptions.TABLE_EXEC_SHUFFLE_MODE,
GlobalStreamExchangeMode.ALL_EDGES_BLOCKING.toString());
assertThat(getGlobalStreamExchangeMode(co... |
@Override
public Object read(final MySQLPacketPayload payload, final boolean unsigned) {
return payload.readStringLenenc();
} | @Test
void assertRead() {
when(payload.readStringLenenc()).thenReturn("value");
assertThat(new MySQLStringLenencBinaryProtocolValue().read(payload, false), is("value"));
} |
public static Schema mergeWideningNullable(Schema schema1, Schema schema2) {
if (schema1.getFieldCount() != schema2.getFieldCount()) {
throw new IllegalArgumentException(
"Cannot merge schemas with different numbers of fields. "
+ "schema1: "
+ schema1
+ " s... | @Test
public void testWidenMap() {
Schema schema1 =
Schema.builder().addMapField("field1", FieldType.INT32, FieldType.INT32).build();
Schema schema2 =
Schema.builder()
.addMapField(
"field1", FieldType.INT32.withNullable(true), FieldType.INT32.withNullable(true))
... |
Object[] getOneRow() throws KettleException {
if ( !openNextFile() ) {
return null;
}
// Build an empty row based on the meta-data
Object[] outputRowData = buildEmptyRow();
try {
// Create new row or clone
if ( meta.getIsInFields() ) {
outputRowData = copyOrCloneArrayFrom... | @Test
public void testGetOneRow() throws Exception {
// string without specified encoding
stepInputFiles.addFile( getFile( "input1.txt" ) );
assertNotNull( stepLoadFileInput.getOneRow() );
assertEquals( "input1 - not empty", new String( stepLoadFileInput.data.filecontent ) );
} |
@Udf
public String concat(@UdfParameter final String... jsonStrings) {
if (jsonStrings == null) {
return null;
}
final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length);
boolean allObjects = true;
for (final String jsonString : jsonStrings) {
if (jsonString == null) {
... | @Test
public void shouldMerge2Arrays() {
// When:
final String result = udf.concat("[1, 2]", "[3, 4]");
// Then:
assertEquals("[1,2,3,4]", result);
} |
public int size() {
return stream.size();
} | @Test
public void testSize() {
writer.write(byteBuffer.asReadOnlyBuffer());
int size = writer.size();
Assertions.assertEquals(size, 13);
} |
public static <E> E findStaticFieldValue(Class clazz, String fieldName) {
try {
Field field = clazz.getField(fieldName);
return (E) field.get(null);
} catch (Exception ignore) {
return null;
}
} | @Test
public void test_whenClassAndFieldExist() {
Integer value = findStaticFieldValue(ClassWithStaticField.class, "staticField");
assertEquals(ClassWithStaticField.staticField, value);
} |
@SuppressWarnings("ConstantConditions")
public boolean addOrReplaceAction(@NonNull Action a) {
if (a == null) {
throw new IllegalArgumentException("Action must be non-null");
}
// CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
List<Actio... | @SuppressWarnings("deprecation")
@Test
public void addOrReplaceAction() {
CauseAction a1 = new CauseAction();
ParametersAction a2 = new ParametersAction();
thing.addAction(a1);
thing.addAction(a2);
CauseAction a3 = new CauseAction();
assertTrue(thing.addOrReplaceA... |
@Override
public void execute(GraphModel graphModel) {
Graph graph;
if (isDirected) {
graph = graphModel.getDirectedGraphVisible();
} else {
graph = graphModel.getUndirectedGraphVisible();
}
execute(graph);
} | @Test
public void testColumnReplace() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1);
graphModel.getNodeTable().addColumn(ClusteringCoefficient.CLUSTERING_COEFF, String.class);
ClusteringCoefficient cc = new ClusteringCoefficient();
cc.execute(graphModel);
... |
@Override
public void dropRuleItemConfiguration(final DropRuleItemEvent event, final MaskRuleConfiguration currentRuleConfig) {
currentRuleConfig.getTables().removeIf(each -> each.getName().equals(((DropNamedRuleItemEvent) event).getItemName()));
} | @Test
void assertDropRuleItemConfiguration() {
MaskRuleConfiguration currentRuleConfig = new MaskRuleConfiguration(
new LinkedList<>(Collections.singleton(new MaskTableRuleConfiguration("foo_tbl", Collections.emptyList()))), Collections.emptyMap());
new MaskTableChangedProcessor().dr... |
@VisibleForTesting
static void initAddrUseFqdn(List<InetAddress> addrs) {
useFqdn = true;
analyzePriorityCidrs();
String fqdn = null;
if (PRIORITY_CIDRS.isEmpty()) {
// Get FQDN from local host by default.
try {
InetAddress localHost = InetAdd... | @Test(expected = IllegalAccessException.class)
public void testGetStartWithFQDNThrowUnknownHostException() {
String oldVal = Config.priority_networks;
Config.priority_networks = "";
testInitAddrUseFqdnCommonMock();
List<InetAddress> hosts = NetUtils.getHosts();
new MockUp<Ine... |
public Mutex mutexFor(Object mutexKey) {
Mutex mutex;
synchronized (mainMutex) {
mutex = mutexMap.computeIfAbsent(mutexKey, Mutex::new);
mutex.referenceCount++;
}
return mutex;
} | @Test
public void testConcurrentMutexOperation() {
final String[] keys = new String[]{"a", "b", "c"};
final Map<String, Integer> timesAcquired = new HashMap<>();
int concurrency = RuntimeAvailableProcessors.get() * 3;
final CyclicBarrier cyc = new CyclicBarrier(concurrency + 1);
... |
@Nullable
public static ValueReference of(Object value) {
if (value instanceof Boolean) {
return of((Boolean) value);
} else if (value instanceof Double) {
return of((Double) value);
} else if (value instanceof Float) {
return of((Float) value);
} ... | @Test
public void serializeInteger() throws IOException {
assertJsonEqualsNonStrict(objectMapper.writeValueAsString(ValueReference.of(1)), "{\"@type\":\"integer\",\"@value\":1}");
assertJsonEqualsNonStrict(objectMapper.writeValueAsString(ValueReference.of(42)), "{\"@type\":\"integer\",\"@value\":42}... |
@Udf(description = "Returns the inverse (arc) cosine of an INT value")
public Double acos(
@UdfParameter(
value = "value",
description = "The value to get the inverse cosine of."
) final Integer value
) {
return acos(value == null ? null : value.doubleValu... | @Test
public void shouldHandlePositive() {
assertThat(udf.acos(0.43), closeTo(1.1263035498590777, 0.000000000000001));
assertThat(udf.acos(0.5), closeTo(1.0471975511965979, 0.000000000000001));
assertThat(udf.acos(1.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.acos(1), closeTo(0.0, 0.000000000... |
@Override
@Transactional(rollbackFor = Exception.class)
public void syncCodegenFromDB(Long tableId) {
// 校验是否已经存在
CodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
// 从数据库中,获得数据库表结构... | @Test
@Disabled // TODO @芋艿:这个单测会随机性失败,需要定位下;
public void testSyncCodegenFromDB() {
// mock 数据(CodegenTableDO)
CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setTableName("t_yunai")
.setDataSourceConfigId(1L).setScene(CodegenSceneEnum.ADMIN.getScene()));
c... |
public void removeAttribute(String name) {
parent.context().remove(name);
} | @Test
void testRemoveAttribute() {
URI uri = URI.create("http://localhost:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
request.setAttribute("some_attr", "some_valu... |
public FEELFnResult<List> invoke(@ParameterName( "list" ) Object list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
// spec requires us to return a new list
final List<Object> result = new ArrayLi... | @Test
void invokeParamNotCollection() {
FunctionTestUtil.assertResult(flattenFunction.invoke(BigDecimal.valueOf(10.2)),
Collections.singletonList(BigDecimal.valueOf(10.2)));
FunctionTestUtil.assertResult(flattenFunction.invoke("test"), Collections.singletonList(... |
public void completeDefaults(Props props) {
// init string properties
for (Map.Entry<Object, Object> entry : defaults().entrySet()) {
props.setDefault(entry.getKey().toString(), entry.getValue().toString());
}
boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), false);
if ... | @Test
public void defaults_throws_exception_on_same_property_defined_more_than_once_in_extensions() {
Props p = new Props(new Properties());
when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of(new FakeExtension1(), new FakeExtension2()));
assertThatThrownBy(() -> processProperties.completeDefaul... |
public static boolean safeCollectionEquals(final Collection<Comparable<?>> sources, final Collection<Comparable<?>> targets) {
List<Comparable<?>> all = new ArrayList<>(sources);
all.addAll(targets);
Optional<Class<?>> clazz = getTargetNumericType(all);
if (!clazz.isPresent()) {
... | @Test
void assertSafeCollectionEqualsForBigInteger() {
List<Comparable<?>> sources = Arrays.asList(10, 12);
List<Comparable<?>> targets = Arrays.asList(BigInteger.valueOf(10L), BigInteger.valueOf(12L));
assertTrue(SafeNumberOperationUtils.safeCollectionEquals(sources, targets));
} |
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_be_enabled_if_version_is_equal_or_greater_than_required_minimum() {
Stream.of(
"git version 2.24.0",
"git version 2.25.2.1",
"git version 2.24.1.1.windows.2",
"git version 2.25.1.msysgit.2"
).forEach(output -> {
ProcessWrapperFactory mockedCmd = mockG... |
@VisibleForTesting
public SmsChannelDO validateSmsChannel(Long channelId) {
SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId);
if (channelDO == null) {
throw exception(SMS_CHANNEL_NOT_EXISTS);
}
if (CommonStatusEnum.isDisable(channelDO.getStatus())) {
... | @Test
public void testValidateSmsChannel_disable() {
// 准备参数
Long channelId = randomLongId();
// mock 方法
SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> {
o.setId(channelId);
o.setStatus(CommonStatusEnum.DISABLE.getStatus()); // 保证 status 禁用,触发失败
... |
public static String jaasConfig(String moduleName, Map<String, String> options) {
StringJoiner joiner = new StringJoiner(" ");
for (Entry<String, String> entry : options.entrySet()) {
String key = Objects.requireNonNull(entry.getKey());
String value = Objects.requireNonNull(entry... | @Test
public void testEmptyModuleName() {
Map<String, String> options = new HashMap<>();
options.put("key1", "value1");
String moduleName = "";
assertThrows(IllegalArgumentException.class, () -> AuthenticationUtils.jaasConfig(moduleName, options));
} |
public void transitionTo(ClassicGroupState groupState) {
assertValidTransition(groupState);
previousState = state;
state = groupState;
currentStateTimestamp = Optional.of(time.milliseconds());
metrics.onClassicGroupStateTransition(previousState, state);
} | @Test
public void testEmptyToStableIllegalTransition() {
assertThrows(IllegalStateException.class, () -> group.transitionTo(STABLE));
} |
@Override
public TCreatePartitionResult createPartition(TCreatePartitionRequest request) throws TException {
LOG.info("Receive create partition: {}", request);
TCreatePartitionResult result;
try {
if (partitionRequestNum.incrementAndGet() >= Config.thrift_server_max_worker_thre... | @Test
public void testCreatePartitionExceedLimit() throws TException {
Database db = GlobalStateMgr.getCurrentState().getDb("test");
Table table = db.getTable("site_access_day");
List<List<String>> partitionValues = Lists.newArrayList();
List<String> values = Lists.newArrayList();
... |
@Override
public void removeAll(Set<? extends K> keys) {
RFuture<Void> future = removeAllAsync(keys);
sync(future);
} | @Test
public void testRemoveAll() throws Exception {
URL configUrl = getClass().getResource("redisson-jcache.yaml");
Config cfg = Config.fromYAML(configUrl);
Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
Cache<String, String> cache = Caching.g... |
public DrlxParseResult drlxParse(Class<?> patternType, String bindingId, String expression) {
return drlxParse(patternType, bindingId, expression, false);
} | @Test
public void testBigDecimalLiteralWithBindVariable() {
SingleDrlxParseSuccess result = (SingleDrlxParseSuccess) parser.drlxParse(Person.class, "$p", "$bd : 10.3B");
assertThat(result.getExpr().toString()).isEqualTo("new java.math.BigDecimal(\"10.3\")");
} |
public static InetSocketAddress toInetSocketAddress(String address) {
String[] ipPortStr = splitIPPortStr(address);
String host;
int port;
if (null != ipPortStr) {
host = ipPortStr[0];
port = Integer.parseInt(ipPortStr[1]);
} else {
host = addr... | @Test
public void testToInetSocketAddress1() {
assertThat(NetUtil.toInetSocketAddress("kadfskl").getHostName()).isEqualTo("kadfskl");
} |
public static String getShortestTableStringFormat(List<List<String>> table)
{
if (table.isEmpty()) {
throw new IllegalArgumentException("Table must include at least one row");
}
int tableWidth = table.get(0).size();
int[] lengthTracker = new int[tableWidth];
for ... | @Test
public void testGetShortestTableStringFormatSimpleSuccess()
{
List<List<String>> table = Arrays.asList(
Arrays.asList("Header1", "Header2", "Headr3"),
Arrays.asList("Value1", "Value2", "Value3"),
Arrays.asList("LongValue1", "SVal2", "SVal3"));
... |
public static WorkflowInstanceAggregatedInfo computeAggregatedView(
WorkflowInstance workflowInstance, boolean statusKnown) {
if (workflowInstance == null) {
// returning empty object since cannot access state of the current instance run
return new WorkflowInstanceAggregatedInfo();
}
Work... | @Test
public void testAggregatedViewSomeNotStarted() {
WorkflowInstance run1 =
getGenericWorkflowInstance(
1, WorkflowInstance.Status.FAILED, RunPolicy.START_FRESH_NEW_RUN, null);
Workflow runtimeWorkflow = mock(Workflow.class);
Map<String, StepRuntimeState> decodedOverview = new Lin... |
@Override
public Set<Host> getHostsByMac(MacAddress mac) {
checkNotNull(mac, "MAC address cannot be null");
return filter(getHostsColl(), host -> Objects.equals(host.mac(), mac));
} | @Test(expected = NullPointerException.class)
public void testGetHostsByNullMac() {
VirtualNetwork vnet = setupEmptyVnet();
HostService hostService = manager.get(vnet.id(), HostService.class);
hostService.getHostsByMac(null);
} |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void default_wip() {
RuntimeOptions options = parser
.parse()
.build();
assertThat(options.isWip(), is(false));
} |
@Operation(summary = "createSchedule", description = "CREATE_SCHEDULE_NOTES")
@Parameters({
@Parameter(name = "processDefinitionCode", description = "PROCESS_DEFINITION_CODE", required = true, schema = @Schema(implementation = long.class, example = "100")),
@Parameter(name = "schedule", desc... | @Test
public void testCreateSchedule() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("processDefinitionCode", "40");
paramsMap.add("schedule",
"{'startTime':'2019-12-16 00:00:00','endTime':'2019-12-17 00:00:00','cronta... |
public static InetSocketAddress parseAddress(String address, int defaultPort) {
return parseAddress(address, defaultPort, false);
} | @Test
void shouldNotParseAddressForIPv6WithNotNumericPort_Strict() {
assertThatIllegalArgumentException()
.isThrownBy(() -> AddressUtils.parseAddress("[1abc:2abc:3abc:0:0:0:5abc:6abc]:abc42", 80, true))
.withMessage("Failed to parse a port from [1abc:2abc:3abc:0:0:0:5abc:6abc]:abc42");
} |
public void verifyBucketAccessible(GcsPath path) throws IOException {
verifyBucketAccessible(path, createBackOff(), Sleeper.DEFAULT);
} | @Test
public void testVerifyBucketAccessible() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
Storage.Buckets mockStorageOb... |
@Override
public void onEvent(ReplicaMigrationEvent event) {
switch (event.getPartitionId()) {
case MIGRATION_STARTED_PARTITION_ID:
migrationListener.migrationStarted(event.getMigrationState());
break;
case MIGRATION_FINISHED_PARTITION_ID:
... | @Test
public void test_migrationProcessCompleted() {
MigrationState migrationSchedule = new MigrationStateImpl();
ReplicaMigrationEvent event = new ReplicaMigrationEventImpl(migrationSchedule, MIGRATION_FINISHED_PARTITION_ID, 0, null, null, true, 0L);
adapter.onEvent(event);
verify(... |
@Override
public void set(V value) {
get(setAsync(value));
} | @Test
public void testIdleTime() throws InterruptedException {
RBucket<Integer> al = redisson.getBucket("test");
al.set(1234);
Thread.sleep(5000);
assertThat(al.getIdleTime()).isBetween(4L, 6L);
} |
public static SeaTunnelRowType convert(RowType rowType, int[] projectionIndex) {
String[] fieldNames = rowType.getFieldNames().toArray(new String[0]);
SeaTunnelDataType<?>[] dataTypes =
rowType.getFields().stream()
.map(field -> field.type().accept(PaimonToSeaTunn... | @Test
public void paimonToSeaTunnelWithProjection() {
int[] projection = {7, 2};
SeaTunnelRowType convert = RowTypeConverter.convert(rowType, projection);
Assertions.assertEquals(convert, seaTunnelProjectionRowType);
} |
public static ExecutableModelClassesContainer drlToExecutableModel(DrlFileSetResource resources, DrlCompilationContext context) {
KnowledgeBuilderConfigurationImpl conf = context.newKnowledgeBuilderConfiguration().as(KnowledgeBuilderConfigurationImpl.KEY);
return pkgDescrToExecModel(buildCompositePackag... | @Test
void getDrlCallableClassesContainerFromFileResource() {
String basePath = UUID.randomUUID().toString();
DrlFileSetResource toProcess = new DrlFileSetResource(drlFiles, basePath);
EfestoCompilationOutput retrieved = DrlCompilerHelper.drlToExecutableModel(toProcess, context);
com... |
public boolean shouldOverwriteHeaderWithName(String headerName) {
notNull(headerName, "Header name");
return headersToOverwrite.get(headerName.toUpperCase());
} | @Test public void
accept_header_is_overwritable_by_default() {
HeaderConfig headerConfig = new HeaderConfig();
assertThat(headerConfig.shouldOverwriteHeaderWithName("content-type"), is(true));
} |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldVisitPrimitives() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitPrimitive(final SqlPrimitiveType type) {
return "Expected";
}
};
primitiveTypes().forEach(type -> {
// When:
final String result = SqlTy... |
@Nonnull
public static <C> SourceBuilder<C>.Batch<Void> batch(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new Batch<>();
} | @Test
public void stream_socketSource_withTimestamps() throws IOException {
// Given
try (ServerSocket serverSocket = new ServerSocket(0)) {
startServer(serverSocket);
// When
int localPort = serverSocket.getLocalPort();
ToLongFunctionEx<String> times... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyArray() {
String[] stringArray = {"a", "b"};
ImmutableList<String[]> iterable = ImmutableList.of(stringArray);
// This test fails w/o the explicit cast
assertThat(iterable).containsExactly((Object) stringArray);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.