focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
protected final void ensureCapacity(final int index, final int length)
{
if (index < 0 || length < 0)
{
throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length);
}
final long resultingPosition = index + (long)length;
if (resultingPosition > capacity)
{
if (resultingPosition > MAX_ARRAY_LENGTH)
{
throw new IndexOutOfBoundsException(
"index=" + index + " length=" + length + " maxCapacity=" + MAX_ARRAY_LENGTH);
}
final int newCapacity = calculateExpansion(capacity, resultingPosition);
byteArray = Arrays.copyOf(byteArray, newCapacity);
capacity = newCapacity;
}
} | @Test
void ensureCapacityThrowsIndexOutOfBoundsExceptionIfIndexIsNegative()
{
final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(1);
final IndexOutOfBoundsException exception =
assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(-3, 4));
assertEquals("negative value: index=-3 length=4", exception.getMessage());
} |
static String encodeString(Utf8String string) {
byte[] utfEncoded = string.getValue().getBytes(StandardCharsets.UTF_8);
return encodeDynamicBytes(new DynamicBytes(utfEncoded));
} | @Test
public void testUtf8String() {
Utf8String string = new Utf8String("Hello, world!");
assertEquals(
TypeEncoder.encodeString(string),
("000000000000000000000000000000000000000000000000000000000000000d"
+ "48656c6c6f2c20776f726c642100000000000000000000000000000000000000"));
} |
@Override
public CompletableFuture<Acknowledge> requestSlot(
final SlotID slotId,
final JobID jobId,
final AllocationID allocationId,
final ResourceProfile resourceProfile,
final String targetAddress,
final ResourceManagerId resourceManagerId,
final Time timeout) {
// TODO: Filter invalid requests from the resource manager by using the
// instance/registration Id
try (MdcCloseable ignored = MdcUtils.withContext(MdcUtils.asContextData(jobId))) {
log.info(
"Receive slot request {} for job {} from resource manager with leader id {}.",
allocationId,
jobId,
resourceManagerId);
if (!isConnectedToResourceManager(resourceManagerId)) {
final String message =
String.format(
"TaskManager is not connected to the resource manager %s.",
resourceManagerId);
log.debug(message);
return FutureUtils.completedExceptionally(new TaskManagerException(message));
}
tryPersistAllocationSnapshot(
new SlotAllocationSnapshot(
slotId, jobId, targetAddress, allocationId, resourceProfile));
try {
final boolean isConnected =
allocateSlotForJob(
jobId, slotId, allocationId, resourceProfile, targetAddress);
if (isConnected) {
offerSlotsToJobManager(jobId);
}
return CompletableFuture.completedFuture(Acknowledge.get());
} catch (SlotAllocationException e) {
log.debug("Could not allocate slot for allocation id {}.", allocationId, e);
return FutureUtils.completedExceptionally(e);
}
}
} | @Test
void testJobLeaderDetection() throws Exception {
final TaskSlotTable<Task> taskSlotTable =
TaskSlotUtils.createTaskSlotTable(1, EXECUTOR_EXTENSION.getExecutor());
final JobLeaderService jobLeaderService =
new DefaultJobLeaderService(
unresolvedTaskManagerLocation,
RetryingRegistrationConfiguration.defaultConfiguration());
final TestingResourceManagerGateway resourceManagerGateway =
new TestingResourceManagerGateway();
CompletableFuture<Void> initialSlotReportFuture = new CompletableFuture<>();
resourceManagerGateway.setSendSlotReportFunction(
resourceIDInstanceIDSlotReportTuple3 -> {
initialSlotReportFuture.complete(null);
return CompletableFuture.completedFuture(Acknowledge.get());
});
final CompletableFuture<Collection<SlotOffer>> offeredSlotsFuture =
new CompletableFuture<>();
final TestingJobMasterGateway jobMasterGateway =
new TestingJobMasterGatewayBuilder()
.setOfferSlotsFunction(
(resourceID, slotOffers) -> {
offeredSlotsFuture.complete(new ArrayList<>(slotOffers));
return CompletableFuture.completedFuture(slotOffers);
})
.build();
rpc.registerGateway(resourceManagerGateway.getAddress(), resourceManagerGateway);
rpc.registerGateway(jobMasterGateway.getAddress(), jobMasterGateway);
final AllocationID allocationId = new AllocationID();
final TaskExecutorLocalStateStoresManager localStateStoresManager =
createTaskExecutorLocalStateStoresManager();
final TaskManagerServices taskManagerServices =
new TaskManagerServicesBuilder()
.setUnresolvedTaskManagerLocation(unresolvedTaskManagerLocation)
.setTaskSlotTable(taskSlotTable)
.setJobLeaderService(jobLeaderService)
.setTaskStateManager(localStateStoresManager)
.build();
TaskExecutor taskManager = createTaskExecutor(taskManagerServices);
try {
taskManager.start();
final TaskExecutorGateway tmGateway =
taskManager.getSelfGateway(TaskExecutorGateway.class);
// tell the task manager about the rm leader
resourceManagerLeaderRetriever.notifyListener(
resourceManagerGateway.getAddress(),
resourceManagerGateway.getFencingToken().toUUID());
initialSlotReportFuture.get();
requestSlot(
tmGateway,
jobId,
allocationId,
buildSlotID(0),
ResourceProfile.ZERO,
jobMasterGateway.getAddress(),
resourceManagerGateway.getFencingToken());
// now inform the task manager about the new job leader
jobManagerLeaderRetriever.notifyListener(
jobMasterGateway.getAddress(), jobMasterGateway.getFencingToken().toUUID());
final Collection<SlotOffer> offeredSlots = offeredSlotsFuture.get();
final Collection<AllocationID> allocationIds =
offeredSlots.stream()
.map(SlotOffer::getAllocationId)
.collect(Collectors.toList());
assertThat(allocationIds).containsExactlyInAnyOrder(allocationId);
} finally {
RpcUtils.terminateRpcEndpoint(taskManager);
}
} |
public static Serializable decode(final ByteBuf byteBuf) {
int valueType = byteBuf.readUnsignedByte() & 0xff;
StringBuilder result = new StringBuilder();
decodeValue(valueType, 1, byteBuf, result);
return result.toString();
} | @Test
void assertDecodeSmallJsonObjectWithUInt32() {
List<JsonEntry> jsonEntries = new LinkedList<>();
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT32, "key1", Integer.MAX_VALUE));
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT32, "key2", Integer.MIN_VALUE));
ByteBuf payload = mockJsonObjectByteBuf(jsonEntries, true);
String actual = (String) MySQLJsonValueDecoder.decode(payload);
assertThat(actual, is("{\"key1\":2147483647,\"key2\":2147483648}"));
} |
public static SessionWindows ofInactivityGapWithNoGrace(final Duration inactivityGap) {
return ofInactivityGapAndGrace(inactivityGap, ofMillis(NO_GRACE_PERIOD));
} | @Test
public void windowSizeMustNotBeZero() {
assertThrows(IllegalArgumentException.class, () -> SessionWindows.ofInactivityGapWithNoGrace(ofMillis(0)));
} |
@Nonnull
public static String fillLeft(int len, @Nonnull String pattern, @Nullable String string) {
StringBuilder sb = new StringBuilder(string == null ? "" : string);
while (sb.length() < len)
sb.insert(0, pattern);
return sb.toString();
} | @Test
void testFillLeft() {
assertEquals("aaab", StringUtil.fillLeft(4, "a", "b"));
assertEquals("aaaa", StringUtil.fillLeft(4, "a", null));
} |
@Override
public List<byte[]> clusterGetKeysInSlot(int slot, Integer count) {
RFuture<List<byte[]>> f = executorService.readAsync((String)null, ByteArrayCodec.INSTANCE, CLUSTER_GETKEYSINSLOT, slot, count);
return syncFuture(f);
} | @Test
public void testClusterGetKeysInSlot() {
connection.flushAll();
List<byte[]> keys = connection.clusterGetKeysInSlot(12, 10);
assertThat(keys).isEmpty();
} |
@Override
public boolean isInSameDatabaseInstance(final ConnectionProperties connectionProps) {
return hostname.equals(connectionProps.getHostname()) && port == connectionProps.getPort();
} | @Test
void assertIsInSameDatabaseInstance() {
assertTrue(new StandardConnectionProperties("127.0.0.1", 9999, "foo", "foo")
.isInSameDatabaseInstance(new StandardConnectionProperties("127.0.0.1", 9999, "bar", "bar")));
} |
protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor clientInterceptor;
if (this.applicationContext.getBeanNamesForType(interceptorClass).length > 0) {
clientInterceptor = this.applicationContext.getBean(interceptorClass);
} else {
try {
clientInterceptor = interceptorClass.getConstructor().newInstance();
} catch (final Exception e) {
throw new BeanCreationException("Failed to create interceptor instance", e);
}
}
list.add(clientInterceptor);
}
for (final String interceptorName : annotation.interceptorNames()) {
list.add(this.applicationContext.getBean(interceptorName, ClientInterceptor.class));
}
return list;
} | @Test
void testInterceptorsFromAnnotation2() {
final List<ClientInterceptor> beans =
assertDoesNotThrow(() -> this.postProcessor.interceptorsFromAnnotation(new GrpcClient() {
@Override
public Class<? extends Annotation> annotationType() {
return GrpcClient.class;
}
@Override
public String value() {
return "test";
}
@Override
public boolean sortInterceptors() {
return false;
}
@Override
@SuppressWarnings("unchecked")
public Class<? extends ClientInterceptor>[] interceptors() {
return new Class[] {Interceptor2.class};
}
@Override
public String[] interceptorNames() {
return new String[0];
}
}));
assertThat(beans).hasSize(1).doesNotContain(this.interceptor1);
} |
public static NamedFieldsMapping mapping( String[] actualFieldNames, String[] metaFieldNames ) {
LinkedHashMap<String, List<Integer>> metaNameToIndex = new LinkedHashMap<>();
List<Integer> unmatchedMetaFields = new ArrayList<>();
int[] actualToMetaFieldMapping = new int[ actualFieldNames == null ? 0 : actualFieldNames.length];
for ( int i = 0; i < metaFieldNames.length; i++ ) {
List<Integer> coll = metaNameToIndex.getOrDefault( metaFieldNames[i], new ArrayList<>() );
coll.add( i );
metaNameToIndex.put( metaFieldNames[i], coll );
}
if ( actualFieldNames != null ) {
for ( int i = 0; i < actualFieldNames.length; i++ ) {
List<Integer> columnIndexes = metaNameToIndex.get( actualFieldNames[ i ] );
if ( columnIndexes == null || columnIndexes.isEmpty() ) {
unmatchedMetaFields.add( i );
actualToMetaFieldMapping[ i ] = FIELD_DOES_NOT_EXIST;
continue;
}
actualToMetaFieldMapping[ i ] = columnIndexes.remove( 0 );
}
}
Iterator<Integer> remainingMetaIndexes = metaNameToIndex.values().stream()
.flatMap( List::stream )
.sorted()
.iterator();
for ( int idx : unmatchedMetaFields ) {
if ( !remainingMetaIndexes.hasNext() ) {
break;
}
actualToMetaFieldMapping[ idx ] = remainingMetaIndexes.next();
}
return new NamedFieldsMapping( actualToMetaFieldMapping );
} | @Test
public void mapping() {
NamedFieldsMapping mapping =
NamedFieldsMapping.mapping( new String[] { "FIRST", "SECOND", "THIRD" }, new String[] { "SECOND", "THIRD" } );
assertEquals( 0, mapping.fieldMetaIndex( 1 ) );
} |
public static Namespace of(String... levels) {
Preconditions.checkArgument(null != levels, "Cannot create Namespace from null array");
if (levels.length == 0) {
return empty();
}
for (String level : levels) {
Preconditions.checkNotNull(level, "Cannot create a namespace with a null level");
Preconditions.checkArgument(
!CONTAINS_NULL_CHARACTER.test(level),
"Cannot create a namespace with the null-byte character");
}
return new Namespace(levels);
} | @Test
public void testDisallowsNamespaceWithNullByte() {
assertThatThrownBy(() -> Namespace.of("ac", "\u0000c", "b"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot create a namespace with the null-byte character");
assertThatThrownBy(() -> Namespace.of("ac", "c\0", "b"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot create a namespace with the null-byte character");
} |
public static InetSocketAddress getConnectAddress(Server server) {
return getConnectAddress(server.getListenerAddress());
} | @Test
public void testGetConnectAddress() throws IOException {
NetUtils.addStaticResolution("host", "127.0.0.1");
InetSocketAddress addr = NetUtils.createSocketAddrForHost("host", 1);
InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr);
assertEquals(addr.getHostName(), connectAddr.getHostName());
addr = new InetSocketAddress(1);
connectAddr = NetUtils.getConnectAddress(addr);
assertEquals(InetAddress.getLocalHost().getHostName(),
connectAddr.getHostName());
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
return super.read(file, status, callback);
}
catch(AccessDeniedException e) {
headers.clear();
return super.read(file, status, callback);
}
} | @Test
public void testReadConcurrency() throws Exception {
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
final byte[] content = RandomUtils.nextBytes(1023);
final OutputStream out = local.getOutputStream(false);
assertNotNull(out);
IOUtils.write(content, out);
out.close();
new DAVUploadFeature(session).upload(
test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
new TransferStatus().withLength(content.length),
new DisabledConnectionCallback());
final ExecutorService service = Executors.newCachedThreadPool();
final BlockingQueue<Future<Void>> queue = new LinkedBlockingQueue<>();
final CompletionService<Void> completion = new ExecutorCompletionService<>(service, queue);
final int num = 5;
for(int i = 0; i < num; i++) {
completion.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
assertTrue(new MicrosoftIISDAVFindFeature(session).find(test));
assertEquals(content.length, new MicrosoftIISDAVListService(session, new MicrosoftIISDAVAttributesFinderFeature(session)).list(test.getParent(), new DisabledListProgressListener()).get(test).attributes().getSize(), 0L);
final TransferStatus status = new TransferStatus();
status.setLength(-1L);
final InputStream in = new MicrosoftIISDAVReadFeature(session).read(test, status, new DisabledConnectionCallback());
assertNotNull(in);
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
new StreamCopier(status, status).transfer(in, buffer);
final byte[] reference = new byte[content.length];
System.arraycopy(content, 0, reference, 0, content.length);
assertArrayEquals(reference, buffer.toByteArray());
in.close();
return null;
}
});
}
for(int i = 0; i < num; i++) {
completion.take().get();
}
new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
local.delete();
} |
@VisibleForTesting
static void computeAndSetAggregatedInstanceStatus(
WorkflowInstance currentInstance, WorkflowInstanceAggregatedInfo aggregated) {
if (!currentInstance.getStatus().isTerminal()
|| currentInstance.isFreshRun()
|| !currentInstance.getStatus().equals(WorkflowInstance.Status.SUCCEEDED)) {
aggregated.setWorkflowInstanceStatus(currentInstance.getStatus());
return;
}
boolean succeeded = true;
for (StepAggregatedView stepAggregated : aggregated.getStepAggregatedViews().values()) {
WorkflowInstance.Status workflowStatus =
STEP_INSTANCE_STATUS_TO_WORKFLOW_INSTANCE_STATUS.get(stepAggregated.getStatus());
switch (workflowStatus) {
case FAILED:
// if any step is failed overall status is failed
aggregated.setWorkflowInstanceStatus(WorkflowInstance.Status.FAILED);
return;
case TIMED_OUT:
// if any are timed out, we want to keep going to search for failed steps
aggregated.setWorkflowInstanceStatus(WorkflowInstance.Status.TIMED_OUT);
break;
case STOPPED:
// prioritize timed out status before stopped
if (aggregated.getWorkflowInstanceStatus() != WorkflowInstance.Status.TIMED_OUT) {
aggregated.setWorkflowInstanceStatus(WorkflowInstance.Status.STOPPED);
}
break;
case SUCCEEDED:
break;
case CREATED:
// there are steps in NOT_CREATED STATUS and the workflow instance cannot be SUCCEEDED.
succeeded = false;
break;
default:
// should never reach here with IN_PROGRESS status;
throw new MaestroInternalError(
"State %s is not expected during aggregated status computation for"
+ " workflow_id = %s ; workflow_instance_id = %s ; workflow_run_id = %s",
workflowStatus,
currentInstance.getWorkflowId(),
currentInstance.getWorkflowInstanceId(),
currentInstance.getWorkflowRunId());
}
}
if (aggregated.getWorkflowInstanceStatus() == null) {
if (succeeded) {
aggregated.setWorkflowInstanceStatus(WorkflowInstance.Status.SUCCEEDED);
} else {
aggregated.setWorkflowInstanceStatus(
currentInstance.getAggregatedInfo().getWorkflowInstanceStatus());
}
}
} | @Test
public void testAggregatedInstanceStatusFromAggregatedV2() {
WorkflowInstance run1 =
getGenericWorkflowInstance(
2,
WorkflowInstance.Status.SUCCEEDED,
RunPolicy.RESTART_FROM_INCOMPLETE,
RestartPolicy.RESTART_FROM_INCOMPLETE);
WorkflowInstanceAggregatedInfo aggregated = new WorkflowInstanceAggregatedInfo();
aggregated
.getStepAggregatedViews()
.put("1", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("2", generateStepAggregated(StepInstance.Status.TIMED_OUT, 11L, 12L));
aggregated
.getStepAggregatedViews()
.put("3", generateStepAggregated(StepInstance.Status.INTERNALLY_FAILED, 11L, 12L));
AggregatedViewHelper.computeAndSetAggregatedInstanceStatus(run1, aggregated);
assertEquals(WorkflowInstance.Status.FAILED, aggregated.getWorkflowInstanceStatus());
aggregated = new WorkflowInstanceAggregatedInfo();
aggregated
.getStepAggregatedViews()
.put("1", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("2", generateStepAggregated(StepInstance.Status.STOPPED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("3", generateStepAggregated(StepInstance.Status.TIMED_OUT, 1L, 2L));
AggregatedViewHelper.computeAndSetAggregatedInstanceStatus(run1, aggregated);
assertEquals(WorkflowInstance.Status.TIMED_OUT, aggregated.getWorkflowInstanceStatus());
aggregated = new WorkflowInstanceAggregatedInfo();
aggregated
.getStepAggregatedViews()
.put("1", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("2", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("3", generateStepAggregated(StepInstance.Status.STOPPED, 1L, 2L));
AggregatedViewHelper.computeAndSetAggregatedInstanceStatus(run1, aggregated);
assertEquals(WorkflowInstance.Status.STOPPED, aggregated.getWorkflowInstanceStatus());
aggregated = new WorkflowInstanceAggregatedInfo();
aggregated
.getStepAggregatedViews()
.put("1", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("2", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
aggregated
.getStepAggregatedViews()
.put("3", generateStepAggregated(StepInstance.Status.SUCCEEDED, 1L, 2L));
AggregatedViewHelper.computeAndSetAggregatedInstanceStatus(run1, aggregated);
assertEquals(WorkflowInstance.Status.SUCCEEDED, aggregated.getWorkflowInstanceStatus());
} |
@Override
public String getURL( String hostname, String port, String databaseName ) {
String url = "jdbc:sqlserver://" + hostname + ":" + port + ";database=" + databaseName + ";encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
if ( getAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "" ).equals( "true" ) ) {
url += "columnEncryptionSetting=Enabled;keyVaultProviderClientId=" + getAttribute( CLIENT_ID, "" ) + ";keyVaultProviderClientKey=" + getAttribute( CLIENT_SECRET_KEY, "" ) + ";";
}
if ( ACTIVE_DIRECTORY_PASSWORD.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) {
return url + "authentication=ActiveDirectoryPassword;";
} else if ( ACTIVE_DIRECTORY_MFA.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) {
return url + "authentication=ActiveDirectoryInteractive;";
} else if ( ACTIVE_DIRECTORY_INTEGRATED.equals( getAttribute( JDBC_AUTH_METHOD, "" ) ) ) {
return url + "Authentication=ActiveDirectoryIntegrated;";
} else {
return url;
}
} | @Test
public void testAlwaysEncryptionParameterIncludedInUrl() {
dbMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE );
dbMeta.addAttribute( IS_ALWAYS_ENCRYPTION_ENABLED, "true" );
dbMeta.addAttribute( CLIENT_ID, "dummy" );
dbMeta.addAttribute( CLIENT_SECRET_KEY, "xxxxx" );
String expectedUrl = "jdbc:sqlserver://abc.database.windows.net:1433;database=AzureDB;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;columnEncryptionSetting=Enabled;keyVaultProviderClientId=dummy;keyVaultProviderClientKey=xxxxx;";
String actualUrl = dbMeta.getURL( "abc.database.windows.net", "1433", "AzureDB" );
assertEquals( expectedUrl, actualUrl );
} |
@Override
protected ExecuteContext doBefore(ExecuteContext context) {
LogUtils.printHttpRequestBeforePoint(context);
Object[] arguments = context.getArguments();
AbstractClientHttpRequest request = (AbstractClientHttpRequest) arguments[0];
Optional<Object> httpRequest = ReflectUtils.getFieldValue(request, "httpRequest");
if (!httpRequest.isPresent()) {
return context;
}
StringBuilder sb = new StringBuilder();
ReflectUtils.invokeMethod(httpRequest.get(), "assembleRequestUri", new Class[]{StringBuilder.class},
new Object[]{sb});
if (sb.length() == 0) {
return context;
}
String uri = sb.toString();
Map<String, String> uriInfo = RequestInterceptorUtils.recoverUrl(uri);
if (!PlugEffectWhiteBlackUtils.isAllowRun(uriInfo.get(HttpConstants.HTTP_URI_HOST),
uriInfo.get(HttpConstants.HTTP_URI_SERVICE))) {
return context;
}
RequestInterceptorUtils.printRequestLog("webClient(http-client)", uriInfo);
Optional<Object> result = invokerService.invoke(
invokerContext -> buildInvokerFunc(context, invokerContext, request, uriInfo),
ex -> ex,
uriInfo.get(HttpConstants.HTTP_URI_SERVICE));
if (result.isPresent()) {
Object obj = result.get();
if (obj instanceof Exception) {
LOGGER.log(Level.SEVERE, "Webclient(http-client) request is error, uri is " + uri, (Exception) obj);
context.setThrowableOut((Exception) obj);
return context;
}
context.skip(obj);
}
return context;
} | @Test
public void test() {
// Test for normal conditions
AbstractClientHttpRequest request = new HttpComponentsClientHttpRequest(HttpMethod.GET, HELLO_URI,
HttpClientContext.create(), new DefaultDataBufferFactory());
arguments[0] = request;
ReflectUtils.setFieldValue(request, "httpRequest", new BasicHttpRequest(Method.GET, HELLO_URI));
ExecuteContext context = ExecuteContext.forMemberMethod(this, method, arguments, null, null);
interceptor.doBefore(context);
request = (AbstractClientHttpRequest) context.getArguments()[0];
Assert.assertEquals(INSTANCE_URL, request.getURI().toString());
} |
public String get(String key) {
Supplier<String> supplier = evaluatedEntries.get(key);
return supplier != null
? supplier.get()
: null;
} | @Test
public void testNullValue() throws Throwable {
assertThat(context.get(PARAM_PROCESS))
.describedAs("Value of context element %s", PARAM_PROCESS)
.isNull();
} |
public static GeneratedResources getGeneratedResourcesObject(String generatedResourcesString) throws JsonProcessingException {
return objectMapper.readValue(generatedResourcesString, GeneratedResources.class);
} | @Test
void getGeneratedResourcesObjectFromJar() throws Exception {
ClassLoader originalClassLoader = addJarToClassLoader();
Optional<File> optionalIndexFile = getFileFromFileName("IndexFile.testb_json");
assertThat(optionalIndexFile).isNotNull().isPresent();
assertThat(optionalIndexFile).get().isInstanceOf(MemoryFile.class);
MemoryFile memoryFile = (MemoryFile) optionalIndexFile.get();
IndexFile indexFile = new IndexFile((MemoryFile) optionalIndexFile.get());
assertThat(indexFile.getContent()).isEqualTo(memoryFile.getContent());
GeneratedResources retrieved = JSONUtils.getGeneratedResourcesObject(indexFile);
assertThat(retrieved).isNotNull();
String fullClassName = "full.class.Name";
GeneratedResource expected1 = new GeneratedClassResource(fullClassName);
LocalUri modelLocalUriId = new ReflectiveAppRoot("test")
.get(ComponentFoo.class)
.get("this", "is", "fri")
.asLocalUri();
ModelLocalUriId localUriId = new ModelLocalUriId(modelLocalUriId);
GeneratedResource expected2 = new GeneratedExecutableResource(localUriId,
Collections.singletonList(fullClassName));
assertThat(retrieved).contains(expected1);
assertThat(retrieved).contains(expected2);
restoreClassLoader(originalClassLoader);
} |
public static TableSchema.Builder builderWithGivenSchema(TableSchema oriSchema) {
TableSchema.Builder builder = builderWithGivenColumns(oriSchema.getTableColumns());
// Copy watermark specification.
for (WatermarkSpec wms : oriSchema.getWatermarkSpecs()) {
builder.watermark(
wms.getRowtimeAttribute(),
wms.getWatermarkExpr(),
wms.getWatermarkExprOutputType());
}
// Copy primary key constraint.
oriSchema
.getPrimaryKey()
.map(
pk ->
builder.primaryKey(
pk.getName(), pk.getColumns().toArray(new String[0])));
return builder;
} | @Test
void testBuilderWithGivenSchema() {
TableSchema oriSchema =
TableSchema.builder()
.field("a", DataTypes.INT().notNull())
.field("b", DataTypes.STRING())
.field("c", DataTypes.INT(), "a + 1")
.field("t", DataTypes.TIMESTAMP(3))
.primaryKey("ct1", new String[] {"a"})
.watermark("t", "t", DataTypes.TIMESTAMP(3))
.build();
TableSchema newSchema = TableSchemaUtils.builderWithGivenSchema(oriSchema).build();
assertThat(newSchema).isEqualTo(oriSchema);
} |
@Override
@MethodNotAvailable
public boolean evict(K key) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testEvict() {
adapter.evict(23);
} |
public static void setNamespaceDefaultId(String namespaceDefaultId) {
NamespaceUtil.namespaceDefaultId = namespaceDefaultId;
} | @Test
void testSetNamespaceDefaultId() {
NamespaceUtil.setNamespaceDefaultId("Deprecated");
assertEquals("Deprecated", NamespaceUtil.getNamespaceDefaultId());
} |
@Override
public String getFileId(final Path file) throws BackgroundException {
if(StringUtils.isNotBlank(file.attributes().getFileId())) {
return file.attributes().getFileId();
}
if(file.isRoot()
|| new SimplePathPredicate(file).test(DriveHomeFinderService.MYDRIVE_FOLDER)
|| new SimplePathPredicate(file).test(DriveHomeFinderService.SHARED_FOLDER_NAME)
|| new SimplePathPredicate(file).test(DriveHomeFinderService.SHARED_DRIVES_NAME)) {
return DriveHomeFinderService.ROOT_FOLDER_ID;
}
final String cached = super.getFileId(file);
if(cached != null) {
if(log.isDebugEnabled()) {
log.debug(String.format("Return cached fileid %s for file %s", cached, file));
}
return cached;
}
if(new SimplePathPredicate(DriveHomeFinderService.SHARED_DRIVES_NAME).test(file.getParent())) {
final Path found = new DriveTeamDrivesListService(session, this).list(file.getParent(),
new DisabledListProgressListener()).find(new SimplePathPredicate(file)
);
if(null == found) {
throw new NotfoundException(file.getAbsolute());
}
return this.cache(file, found.attributes().getFileId());
}
final Path query;
if(file.isPlaceholder()) {
query = new Path(file.getParent(), FilenameUtils.removeExtension(file.getName()), file.getType(), file.attributes());
}
else {
query = file;
}
final AttributedList<Path> list = new FileidDriveListService(session, this, query).list(file.getParent(), new DisabledListProgressListener());
final Path found = list.filter(new IgnoreTrashedComparator()).find(new SimplePathPredicate(file));
if(null == found) {
throw new NotfoundException(file.getAbsolute());
}
return this.cache(file, found.attributes().getFileId());
} | @Test
public void testGetFileidSameName() throws Exception {
final String filename = new AlphanumericRandomStringService().random();
final Path test1 = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, filename, EnumSet.of(Path.Type.file));
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path p1 = new DriveTouchFeature(session, fileid).touch(test1, new TransferStatus());
assertEquals(p1.attributes().getFileId(), fileid.getFileId(test1));
new DriveDeleteFeature(session, fileid).delete(Collections.singletonList(test1), new DisabledPasswordCallback(), new Delete.DisabledCallback());
final Path test2 = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, filename, EnumSet.of(Path.Type.file));
final Path p2 = new DriveTouchFeature(session, fileid).touch(test2, new TransferStatus());
assertEquals(p2.attributes().getFileId(), fileid.getFileId(test2));
session.getClient().files().delete(p2.attributes().getFileId());
} |
public static Throwable stripException(
Throwable throwableToStrip, Class<? extends Throwable> typeToStrip) {
while (typeToStrip.isAssignableFrom(throwableToStrip.getClass())
&& throwableToStrip.getCause() != null) {
throwableToStrip = throwableToStrip.getCause();
}
return throwableToStrip;
} | @Test
void testExceptionStripping() {
final FlinkException expectedException = new FlinkException("test exception");
final Throwable strippedException =
ExceptionUtils.stripException(
new RuntimeException(new RuntimeException(expectedException)),
RuntimeException.class);
assertThat(strippedException).isEqualTo(expectedException);
} |
public boolean removeWatchedAddresses(final List<Address> addresses) {
List<Script> scripts = new ArrayList<>();
for (Address address : addresses) {
Script script = ScriptBuilder.createOutputScript(address);
scripts.add(script);
}
return removeWatchedScripts(scripts);
} | @Test
public void removeWatchedAddresses() {
List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, TESTNET);
addressesForRemoval.add(watchedAddress);
wallet.addWatchedAddress(watchedAddress);
}
wallet.removeWatchedAddresses(addressesForRemoval);
for (Address addr : addressesForRemoval)
assertFalse(wallet.isAddressWatched(addr));
} |
@Override
public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException {
Collection<TableMetaData> tableMetaDataList = new LinkedList<>();
try (Connection connection = new MetaDataLoaderConnection(TypedSPILoader.getService(DatabaseType.class, "Oracle"), material.getDataSource().getConnection())) {
tableMetaDataList.addAll(getTableMetaDataList(connection, connection.getSchema(), material.getActualTableNames()));
}
return Collections.singletonList(new SchemaMetaData(material.getDefaultSchemaName(), tableMetaDataList));
} | @Test
void assertLoadCondition1() throws SQLException {
DataSource dataSource = mockDataSource();
ResultSet resultSet = mockTableMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(ALL_TAB_COLUMNS_SQL_CONDITION1).executeQuery()).thenReturn(resultSet);
ResultSet indexResultSet = mockIndexMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(ALL_INDEXES_SQL).executeQuery()).thenReturn(indexResultSet);
ResultSet primaryKeys = mockPrimaryKeysMetaDataResultSet();
when(dataSource.getConnection().prepareStatement(ALL_CONSTRAINTS_SQL_WITHOUT_TABLES).executeQuery()).thenReturn(primaryKeys);
when(dataSource.getConnection().getMetaData().getDatabaseMajorVersion()).thenReturn(12);
when(dataSource.getConnection().getMetaData().getDatabaseMinorVersion()).thenReturn(2);
Collection<SchemaMetaData> actual = getDialectTableMetaDataLoader().load(new MetaDataLoaderMaterial(Collections.singleton("tbl"), dataSource, new OracleDatabaseType(), "sharding_db"));
assertTableMetaDataMap(actual);
TableMetaData actualTableMetaData = actual.iterator().next().getTables().iterator().next();
Iterator<ColumnMetaData> columnsIterator = actualTableMetaData.getColumns().iterator();
assertThat(columnsIterator.next(), is(new ColumnMetaData("id", Types.INTEGER, false, true, true, true, false, false)));
assertThat(columnsIterator.next(), is(new ColumnMetaData("name", Types.VARCHAR, false, false, false, false, false, true)));
} |
@Override
public void delete(InputWithExtractors nativeEntity) {
inputService.destroy(nativeEntity.input());
} | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void delete() throws NotFoundException {
final Input input = inputService.find("5acc84f84b900a4ff290d9a7");
final InputWithExtractors inputWithExtractors = InputWithExtractors.create(input);
assertThat(inputService.totalCount()).isEqualTo(4L);
facade.delete(inputWithExtractors);
assertThat(inputService.totalCount()).isEqualTo(3L);
assertThatThrownBy(() -> inputService.find("5acc84f84b900a4ff290d9a7"))
.isInstanceOf(NotFoundException.class);
} |
@Override
public boolean add(V value) {
lock.lock();
try {
checkComparator();
BinarySearchResult<V> res = binarySearch(value);
int index = 0;
if (res.getIndex() < 0) {
index = -(res.getIndex() + 1);
} else {
index = res.getIndex() + 1;
}
get(commandExecutor.evalWriteNoRetryAsync(getRawName(), codec, RedisCommands.EVAL_VOID,
"local len = redis.call('llen', KEYS[1]);"
+ "if tonumber(ARGV[1]) < len then "
+ "local pivot = redis.call('lindex', KEYS[1], ARGV[1]);"
+ "redis.call('linsert', KEYS[1], 'before', pivot, ARGV[2]);"
+ "return;"
+ "end;"
+ "redis.call('rpush', KEYS[1], ARGV[2]);",
Arrays.asList(getRawName()),
index, encode(value)));
return true;
} finally {
lock.unlock();
}
} | @Test
public void testIteratorNextNext() {
RPriorityQueue<String> list = redisson.getPriorityQueue("simple");
list.add("1");
list.add("4");
Iterator<String> iter = list.iterator();
Assertions.assertEquals("1", iter.next());
Assertions.assertEquals("4", iter.next());
Assertions.assertFalse(iter.hasNext());
} |
public static <K, V, R> Map<K, R> map(Map<K, V> map, BiFunction<K, V, R> biFunction) {
if (null == map || null == biFunction) {
return MapUtil.newHashMap();
}
return map.entrySet().stream().collect(CollectorUtil.toMap(Map.Entry::getKey, m -> biFunction.apply(m.getKey(), m.getValue()), (l, r) -> l));
} | @Test
public void mapTest() {
// Add test like a foreigner
final Map<Integer, String> adjectivesMap = MapUtil.<Integer, String>builder()
.put(0, "lovely")
.put(1, "friendly")
.put(2, "happily")
.build();
final Map<Integer, String> resultMap = MapUtil.map(adjectivesMap, (k, v) -> v + " " + PeopleEnum.values()[k].name().toLowerCase());
assertEquals("lovely girl", resultMap.get(0));
assertEquals("friendly boy", resultMap.get(1));
assertEquals("happily child", resultMap.get(2));
// 下单用户,Queue表示正在 .排队. 抢我抢不到的二次元周边!
final Queue<String> customers = new ArrayDeque<>(Arrays.asList("刑部尚书手工耿", "木瓜大盗大漠叔", "竹鼠发烧找华农", "朴实无华朱一旦"));
// 分组
final List<Group> groups = Stream.iterate(0L, i -> ++i).limit(4).map(i -> Group.builder().id(i).build()).collect(Collectors.toList());
// 如你所见,它是一个map,key由用户id,value由用户组成
final Map<Long, User> idUserMap = Stream.iterate(0L, i -> ++i).limit(4).map(i -> User.builder().id(i).name(customers.poll()).build()).collect(Collectors.toMap(User::getId, Function.identity()));
// 如你所见,它是一个map,key由分组id,value由用户ids组成,典型的多对多关系
final Map<Long, List<Long>> groupIdUserIdsMap = groups.stream().flatMap(group -> idUserMap.keySet().stream().map(userId -> UserGroup.builder().groupId(group.getId()).userId(userId).build()))
.collect(Collectors.groupingBy(UserGroup::getGroupId, Collectors.mapping(UserGroup::getUserId, Collectors.toList())));
// 神奇的魔法发生了, 分组id和用户ids组成的map,竟然变成了订单编号和用户实体集合组成的map
final Map<Long, List<User>> groupIdUserMap = MapUtil.map(groupIdUserIdsMap, (groupId, userIds) -> userIds.stream().map(idUserMap::get).collect(Collectors.toList()));
// 然后你就可以拿着这个map,去封装groups,使其能够在订单数据带出客户信息啦
groups.forEach(group -> Opt.ofNullable(group.getId()).map(groupIdUserMap::get).ifPresent(group::setUsers));
// 下面是测试报告
groups.forEach(group -> {
final List<User> users = group.getUsers();
assertEquals("刑部尚书手工耿", users.get(0).getName());
assertEquals("木瓜大盗大漠叔", users.get(1).getName());
assertEquals("竹鼠发烧找华农", users.get(2).getName());
assertEquals("朴实无华朱一旦", users.get(3).getName());
});
// 对null友好
MapUtil.map(MapUtil.of(0, 0), (k, v) -> null).forEach((k, v) -> assertNull(v));
} |
@Override
public void report() {
try {
tryReport();
} catch (ConcurrentModificationException | NoSuchElementException ignored) {
// at tryReport() we don't synchronize while iterating over the various maps which might
// cause a
// ConcurrentModificationException or NoSuchElementException to be thrown,
// if concurrently a metric is being added or removed.
}
} | @Test
void testOnlyCounterRegistered() {
reporter.notifyOfAddedMetric(new SimpleCounter(), "metric", metricGroup);
reporter.report();
assertThat(testLoggerResource.getMessages())
.noneMatch(logOutput -> logOutput.contains("-- Meter"))
.noneMatch(logOutput -> logOutput.contains("-- Gauge"))
.noneMatch(logOutput -> logOutput.contains("-- Histogram"))
.anyMatch(logOutput -> logOutput.contains("-- Counter"));
} |
public RegistryBuilder port(Integer port) {
this.port = port;
return getThis();
} | @Test
void port() {
RegistryBuilder builder = new RegistryBuilder();
builder.port(8080);
Assertions.assertEquals(8080, builder.build().getPort());
} |
@Override
public Neighbor<double[], E>[] search(double[] q, int k) {
if (model == null) return super.search(q, k);
return search(q, k, 0.95, 100);
} | @Test
public void testRange() {
System.out.println("range");
int[] recall = new int[testx.length];
for (int i = 0; i < testx.length; i++) {
ArrayList<Neighbor<double[], double[]>> n1 = new ArrayList<>();
ArrayList<Neighbor<double[], double[]>> n2 = new ArrayList<>();
lsh.search(testx[i], 8.0, n1, 0.95, 50);
naive.search(testx[i], 8.0, n2);
for (Neighbor m2 : n2) {
for (Neighbor m1 : n1) {
if (m1.index == m2.index) {
recall[i]++;
break;
}
}
}
}
System.out.format("q1 of recall is %d%n", MathEx.q1(recall));
System.out.format("median of recall is %d%n", MathEx.median(recall));
System.out.format("q3 of recall is %d%n", MathEx.q3(recall));
} |
public static String getKeySchemaName(final String name) {
final String camelName = CaseFormat.UPPER_UNDERSCORE
.converterTo(CaseFormat.UPPER_CAMEL)
.convert(name);
return AvroProperties.AVRO_SCHEMA_NAMESPACE + "." + camelName + "Key";
} | @Test
public void shouldConvertNames() {
assertThat(AvroFormat.getKeySchemaName("foo"), is("io.confluent.ksql.avro_schemas.FooKey"));
assertThat(AvroFormat.getKeySchemaName("Foo"), is("io.confluent.ksql.avro_schemas.FooKey"));
assertThat(AvroFormat.getKeySchemaName("FOO"), is("io.confluent.ksql.avro_schemas.FooKey"));
assertThat(AvroFormat.getKeySchemaName("FOO_BAR"), is("io.confluent.ksql.avro_schemas.FooBarKey"));
assertThat(AvroFormat.getKeySchemaName("Foo_Bar"), is("io.confluent.ksql.avro_schemas.FooBarKey"));
assertThat(AvroFormat.getKeySchemaName("foo_bar"), is("io.confluent.ksql.avro_schemas.FooBarKey"));
assertThat(AvroFormat.getKeySchemaName("fOoBaR"), is("io.confluent.ksql.avro_schemas.FoobarKey"));
assertThat(AvroFormat.getKeySchemaName("_fOoBaR_"), is("io.confluent.ksql.avro_schemas.FoobarKey"));
} |
Object[] findValues(int ordinal) {
return getAllValues(ordinal, type, 0);
} | @Test
public void testSetIntegerReference() throws Exception {
SetType setType = new SetType();
setType.intValues = new HashSet<>(Arrays.asList(1, 2, 3));
objectMapper.add(setType);
StateEngineRoundTripper.roundTripSnapshot(writeStateEngine, readStateEngine);
FieldPath fieldPath;
Object[] values;
Set<Integer> valuesAsSet;
//with partial auto expand
fieldPath = new FieldPath(readStateEngine, "SetType", "intValues.element");
values = fieldPath.findValues(0);
Assert.assertEquals(3, values.length);
valuesAsSet = new HashSet<>();
for (Object v : values) valuesAsSet.add((int) v);
Assert.assertTrue(valuesAsSet.contains(1));
Assert.assertTrue(valuesAsSet.contains(2));
Assert.assertTrue(valuesAsSet.contains(3));
//without auto expand
fieldPath = new FieldPath(readStateEngine, "SetType", "intValues.element.value");
values = fieldPath.findValues(0);
Assert.assertEquals(3, values.length);
valuesAsSet = new HashSet<>();
for (Object v : values) valuesAsSet.add((int) v);
Assert.assertTrue(valuesAsSet.contains(1));
Assert.assertTrue(valuesAsSet.contains(2));
Assert.assertTrue(valuesAsSet.contains(3));
} |
public BlobOperationResponse deleteContainer(final Exchange exchange) {
final BlobRequestConditions blobRequestConditions = configurationProxy.getBlobRequestConditions(exchange);
final Duration timeout = configurationProxy.getTimeout(exchange);
final BlobExchangeHeaders blobExchangeHeaders
= new BlobExchangeHeaders().httpHeaders(client.deleteContainer(blobRequestConditions, timeout));
return BlobOperationResponse.createWithEmptyBody(blobExchangeHeaders.toMap());
} | @Test
void testDeleteContainer() {
when(client.deleteContainer(any(), any())).thenReturn(deleteContainerMock());
final BlobContainerOperations blobContainerOperations = new BlobContainerOperations(configuration, client);
final BlobOperationResponse response = blobContainerOperations.deleteContainer(null);
assertNotNull(response);
assertNotNull(response.getHeaders().get(BlobConstants.RAW_HTTP_HEADERS));
assertTrue((boolean) response.getBody());
} |
public void parseStepParameter(
Map<String, Map<String, Object>> allStepOutputData,
Map<String, Parameter> workflowParams,
Map<String, Parameter> stepParams,
Parameter param,
String stepId) {
parseStepParameter(
allStepOutputData, workflowParams, stepParams, param, stepId, new HashSet<>());
} | @Test
public void testParseLiteralStepParameterWithStepId() {
StringParameter bar = StringParameter.builder().name("bar").value("test ${step1__foo}").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.singletonMap("foo", StringParameter.builder().value("123").build()),
bar,
"step1");
assertEquals("test 123", bar.getEvaluatedResult());
bar = StringParameter.builder().name("bar").value("test ${step1__foo}").build();
paramEvaluator.parseStepParameter(
Collections.emptyMap(),
Collections.emptyMap(),
Collections.singletonMap(
"foo", StringParameter.builder().evaluatedResult("123").evaluatedTime(123L).build()),
bar,
"step1");
assertEquals("test 123", bar.getEvaluatedResult());
} |
private void sendResponse(Response response) {
try {
((GrpcConnection) this.currentConnection).sendResponse(response);
} catch (Exception e) {
LOGGER.error("[{}]Error to send ack response, ackId->{}", this.currentConnection.getConnectionId(),
response.getRequestId());
}
} | @Test
void testBindRequestStreamOnNextParseException()
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class);
GrpcConnection grpcConnection = mock(GrpcConnection.class);
when(stub.requestBiStream(any())).thenAnswer((Answer<StreamObserver<Payload>>) invocationOnMock -> {
((StreamObserver<Payload>) invocationOnMock.getArgument(0)).onNext(Payload.newBuilder().build());
return null;
});
setCurrentConnection(grpcConnection, grpcClient);
invokeBindRequestStream(grpcClient, stub, grpcConnection);
verify(grpcConnection, never()).sendResponse(any(ErrorResponse.class));
} |
private void checkDropMaterializedView(String mvName, OlapTable olapTable)
throws DdlException, MetaNotFoundException {
Preconditions.checkState(olapTable.getState() == OlapTableState.NORMAL, olapTable.getState().name());
if (mvName.equals(olapTable.getName())) {
throw new DdlException("Cannot drop base index by using DROP ROLLUP or DROP MATERIALIZED VIEW.");
}
if (!olapTable.hasMaterializedIndex(mvName)) {
throw new MetaNotFoundException(
"Materialized view [" + mvName + "] does not exist in table [" + olapTable.getName() + "]");
}
long mvIndexId = olapTable.getIndexIdByName(mvName);
int mvSchemaHash = olapTable.getSchemaHashByIndexId(mvIndexId);
Preconditions.checkState(mvSchemaHash != -1);
for (PhysicalPartition partition : olapTable.getPhysicalPartitions()) {
MaterializedIndex materializedIndex = partition.getIndex(mvIndexId);
Preconditions.checkNotNull(materializedIndex);
}
} | @Test
public void testCheckDropMaterializedView(@Injectable OlapTable olapTable, @Injectable Partition partition,
@Injectable MaterializedIndex materializedIndex,
@Injectable Database db) {
String mvName = "mv_1";
new Expectations() {
{
olapTable.getState();
result = OlapTable.OlapTableState.NORMAL;
olapTable.getName();
result = "table1";
olapTable.hasMaterializedIndex(mvName);
result = true;
olapTable.getIndexIdByName(mvName);
result = 1L;
olapTable.getSchemaHashByIndexId(1L);
result = 1;
olapTable.getPhysicalPartitions();
result = Lists.newArrayList(partition);
partition.getIndex(1L);
result = materializedIndex;
}
};
MaterializedViewHandler materializedViewHandler = new MaterializedViewHandler();
try {
Deencapsulation.invoke(materializedViewHandler, "checkDropMaterializedView", mvName, olapTable);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
} |
@Override
public List<TableIdentifier> listTables(Namespace namespace) {
SnowflakeIdentifier scope = NamespaceHelpers.toSnowflakeIdentifier(namespace);
Preconditions.checkArgument(
scope.type() == SnowflakeIdentifier.Type.SCHEMA,
"listTables must be at SCHEMA level; got %s from namespace %s",
scope,
namespace);
List<SnowflakeIdentifier> sfTables = snowflakeClient.listIcebergTables(scope);
return sfTables.stream()
.map(NamespaceHelpers::toIcebergTableIdentifier)
.collect(Collectors.toList());
} | @Test
public void testListTablesWithinDB() {
String dbName = "DB_1";
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> catalog.listTables(Namespace.of(dbName)))
.withMessageContaining("listTables must be at SCHEMA level");
} |
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetPartialGenericBiFunction() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericBiFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getSchemaFromType(genericType);
// Then:
assertThat(returnType, is(LambdaType.of(ImmutableList.of(GenericType.of("T"), ParamTypes.BOOLEAN), GenericType.of("U"))));
} |
Flux<DataEntityList> export(KafkaCluster cluster) {
String clusterOddrn = Oddrn.clusterOddrn(cluster);
Statistics stats = statisticsCache.get(cluster);
return Flux.fromIterable(stats.getTopicDescriptions().keySet())
.filter(topicFilter)
.flatMap(topic -> createTopicDataEntity(cluster, topic, stats))
.onErrorContinue(
(th, topic) -> log.warn("Error exporting data for topic {}, cluster {}", topic, cluster.getName(), th))
.buffer(100)
.map(topicsEntities ->
new DataEntityList()
.dataSourceOddrn(clusterOddrn)
.items(topicsEntities));
} | @Test
void doesNotExportTopicsWhichDontFitFiltrationRule() {
when(schemaRegistryClientMock.getSubjectVersion(anyString(), anyString(), anyBoolean()))
.thenReturn(Mono.error(WebClientResponseException.create(404, "NF", new HttpHeaders(), null, null, null)));
stats = Statistics.empty()
.toBuilder()
.topicDescriptions(
Map.of(
"_hidden", new TopicDescription("_hidden", false, List.of(
new TopicPartitionInfo(0, null, List.of(), List.of())
)),
"visible", new TopicDescription("visible", false, List.of(
new TopicPartitionInfo(0, null, List.of(), List.of())
))
)
)
.build();
StepVerifier.create(topicsExporter.export(cluster))
.assertNext(entityList -> {
assertThat(entityList.getDataSourceOddrn())
.isNotEmpty();
assertThat(entityList.getItems())
.hasSize(1)
.allSatisfy(e -> e.getOddrn().contains("visible"));
})
.verifyComplete();
} |
@Override
public Class<? extends StorageBuilder> builder() {
return MinStorageBuilder.class;
} | @Test
public void testBuilder() throws IllegalAccessException, InstantiationException {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), SMALL_VALUE);
function.calculate();
StorageBuilder<MinFunction> storageBuilder = function.builder().newInstance();
final HashMapConverter.ToStorage toStorage = new HashMapConverter.ToStorage();
storageBuilder.entity2Storage(function, toStorage);
final Map<String, Object> map = toStorage.obtain();
map.put(MinFunction.VALUE, map.get(MinFunction.VALUE));
MinFunction function2 = storageBuilder.storage2Entity(new HashMapConverter.ToEntity(map));
assertThat(function2.getValue()).isEqualTo(function.getValue());
} |
@VisibleForTesting
static int findEndPosition(int startPosition, int endPosition, BiPredicate<Integer, Integer> comparator)
{
checkArgument(startPosition >= 0, "startPosition must be greater or equal than zero: %s", startPosition);
checkArgument(startPosition < endPosition, "startPosition (%s) must be less than endPosition (%s)", startPosition, endPosition);
int left = startPosition;
int right = left + 1;
while (right < endPosition) {
int distance = 1;
for (; distance < endPosition - left; distance *= 2) {
right = left + distance;
if (!comparator.test(startPosition, right)) {
endPosition = right;
break;
}
}
left = left + distance / 2;
right = left + 1;
}
return right;
} | @Test
public void testFindEndPosition()
{
assertFindEndPosition("0", 1);
assertFindEndPosition("11", 2);
assertFindEndPosition("1111111111", 10);
assertFindEndPosition("01", 1);
assertFindEndPosition("011", 1);
assertFindEndPosition("0111", 1);
assertFindEndPosition("0111111111", 1);
assertFindEndPosition("012", 1);
assertFindEndPosition("01234", 1);
assertFindEndPosition("0123456789", 1);
assertFindEndPosition("001", 2);
assertFindEndPosition("0001", 3);
assertFindEndPosition("0000000001", 9);
assertFindEndPosition("000111", 3);
assertFindEndPosition("0001111", 3);
assertFindEndPosition("0000111", 4);
assertFindEndPosition("000000000000001111111111", 14);
} |
public void updateTopicConfig(final TopicConfig topicConfig) {
updateSingleTopicConfigWithoutPersist(topicConfig);
this.persist(topicConfig.getTopicName(), topicConfig);
} | @Test
public void testNormalUpdateUnchangeableKeyOnUpdating() {
String topic = "exist-topic";
supportAttributes(asList(
new EnumAttribute("enum.key", true, newHashSet("enum-1", "enum-2", "enum-3"), "enum-1"),
new BooleanAttribute("bool.key", true, false),
new LongRangeAttribute("long.range.key", false, 10, 20, 15)
));
Map<String, String> attributes = new HashMap<>();
attributes.put("+long.range.key", "14");
TopicConfig topicConfig = new TopicConfig();
topicConfig.setTopicName(topic);
topicConfig.setAttributes(attributes);
topicConfigManager.updateTopicConfig(topicConfig);
attributes.put("+long.range.key", "16");
topicConfig.setAttributes(attributes);
RuntimeException runtimeException = Assert.assertThrows(RuntimeException.class, () -> topicConfigManager.updateTopicConfig(topicConfig));
Assert.assertEquals("attempt to update an unchangeable attribute. key: long.range.key", runtimeException.getMessage());
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
new SchemaBuilder(
mergingStrategies,
sourceSchema,
(FlinkTypeFactory) validator.getTypeFactory(),
dataTypeFactory,
validator,
escapeExpression);
schemaBuilder.appendDerivedColumns(mergingStrategies, derivedColumns);
schemaBuilder.appendDerivedWatermarks(mergingStrategies, derivedWatermarkSpecs);
schemaBuilder.appendDerivedPrimaryKey(derivedPrimaryKey);
return schemaBuilder.build();
} | @Test
void mergeWithIncludeFailsOnDuplicateRegularColumn() {
Schema sourceSchema = Schema.newBuilder().column("one", DataTypes.INT()).build();
List<SqlNode> derivedColumns =
Arrays.asList(
regularColumn("two", DataTypes.INT()),
regularColumn("two", DataTypes.INT()),
regularColumn("four", DataTypes.STRING()));
assertThatThrownBy(
() ->
util.mergeTables(
getDefaultMergingStrategies(),
sourceSchema,
derivedColumns,
Collections.emptyList(),
null))
.isInstanceOf(ValidationException.class)
.hasMessage("A regular Column named 'two' already exists in the table.");
} |
@Description("greedily removes occurrences of a pattern in a string")
@ScalarFunction
@LiteralParameters({"x", "y"})
@SqlType("varchar(x)")
public static Slice replace(@SqlType("varchar(x)") Slice str, @SqlType("varchar(y)") Slice search)
{
return replace(str, search, Slices.EMPTY_SLICE);
} | @Test
public void testReplace()
{
assertFunction("REPLACE('aaa', 'a', 'aa')", createVarcharType(11), "aaaaaa");
assertFunction("REPLACE('abcdefabcdef', 'cd', 'XX')", createVarcharType(38), "abXXefabXXef");
assertFunction("REPLACE('abcdefabcdef', 'cd')", createVarcharType(12), "abefabef");
assertFunction("REPLACE('123123tech', '123')", createVarcharType(10), "tech");
assertFunction("REPLACE('123tech123', '123')", createVarcharType(10), "tech");
assertFunction("REPLACE('222tech', '2', '3')", createVarcharType(15), "333tech");
assertFunction("REPLACE('0000123', '0')", createVarcharType(7), "123");
assertFunction("REPLACE('0000123', '0', ' ')", createVarcharType(15), " 123");
assertFunction("REPLACE('foo', '')", createVarcharType(3), "foo");
assertFunction("REPLACE('foo', '', '')", createVarcharType(3), "foo");
assertFunction("REPLACE('foo', 'foo', '')", createVarcharType(3), "");
assertFunction("REPLACE('abc', '', 'xx')", createVarcharType(11), "xxaxxbxxcxx");
assertFunction("REPLACE('', '', 'xx')", createVarcharType(2), "xx");
assertFunction("REPLACE('', '')", createVarcharType(0), "");
assertFunction("REPLACE('', '', '')", createVarcharType(0), "");
assertFunction("REPLACE('\u4FE1\u5FF5,\u7231,\u5E0C\u671B', ',', '\u2014')", createVarcharType(15), "\u4FE1\u5FF5\u2014\u7231\u2014\u5E0C\u671B");
assertFunction("REPLACE('::\uD801\uDC2D::', ':', '')", createVarcharType(5), "\uD801\uDC2D"); //\uD801\uDC2D is one character
assertFunction("REPLACE('\u00D6sterreich', '\u00D6', 'Oe')", createVarcharType(32), "Oesterreich");
assertFunction("CAST(REPLACE(utf8(from_hex('CE')), '', 'X') AS VARBINARY)", VARBINARY, new SqlVarbinary(new byte[] {'X', (byte) 0xCE, 'X'}));
assertFunction("CAST(REPLACE('abc' || utf8(from_hex('CE')), '', 'X') AS VARBINARY)",
VARBINARY,
new SqlVarbinary(new byte[] {'X', 'a', 'X', 'b', 'X', 'c', 'X', (byte) 0xCE, 'X'}));
assertFunction("CAST(REPLACE(utf8(from_hex('CE')) || 'xyz', '', 'X') AS VARBINARY)",
VARBINARY,
new SqlVarbinary(new byte[] {'X', (byte) 0xCE, 'X', 'x', 'X', 'y', 'X', 'z', 'X'}));
assertFunction("CAST(REPLACE('abc' || utf8(from_hex('CE')) || 'xyz', '', 'X') AS VARBINARY)",
VARBINARY,
new SqlVarbinary(new byte[] {'X', 'a', 'X', 'b', 'X', 'c', 'X', (byte) 0xCE, 'X', 'x', 'X', 'y', 'X', 'z', 'X'}));
String longString = new String(new char[1_000_000]);
assertInvalidFunction(String.format("replace('%s', '', '%s')", longString, longString), "inputs to \"replace\" function are too large: when \"search\" parameter is empty, length of \"string\" times length of \"replace\" must not exceed 2147483647");
} |
public static void adjustImageConfigForTopo(Map<String, Object> conf, Map<String, Object> topoConf, String topoId)
throws InvalidTopologyException {
//don't need sanity check here as we assume it's already done during daemon startup
List<String> allowedImages = getAllowedImages(conf, false);
String topoImage = (String) topoConf.get(Config.TOPOLOGY_OCI_IMAGE);
if (allowedImages.isEmpty()) {
if (topoImage != null) {
LOG.warn("{} is not configured; this indicates OCI container is not supported; "
+ "{} config for topology {} will be removed",
DaemonConfig.STORM_OCI_ALLOWED_IMAGES, Config.TOPOLOGY_OCI_IMAGE, topoId);
topoConf.remove(Config.TOPOLOGY_OCI_IMAGE);
}
} else {
if (topoImage == null) {
//we assume the default image is already validated during daemon startup
String defaultImage = (String) conf.get(DaemonConfig.STORM_OCI_IMAGE);
topoImage = defaultImage;
topoConf.put(Config.TOPOLOGY_OCI_IMAGE, topoImage);
LOG.info("{} is not set for topology {}; set it to the default image {} configured in {}",
Config.TOPOLOGY_OCI_IMAGE, topoId, defaultImage, DaemonConfig.STORM_OCI_IMAGE);
} else {
try {
validateImage(allowedImages, topoImage, Config.TOPOLOGY_OCI_IMAGE);
} catch (IllegalArgumentException e) {
throw new WrappedInvalidTopologyException(e.getMessage());
}
}
}
} | @Test
public void adjustImageConfigForTopoNotInAllowedList() {
String image1 = "storm/rhel7:dev_test";
String image2 = "storm/rhel7:dev_current";
Map<String, Object> conf = new HashMap<>();
List<String> allowedImages = new ArrayList<>();
allowedImages.add(image1);
conf.put(DaemonConfig.STORM_OCI_ALLOWED_IMAGES, allowedImages);
Map<String, Object> topoConf = new HashMap<>();
String topoId = "topo1";
topoConf.put(Config.TOPOLOGY_OCI_IMAGE, image2);
assertThrows(WrappedInvalidTopologyException.class, () ->
OciUtils.adjustImageConfigForTopo(conf, topoConf, topoId));
} |
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) {
invokeCompletedOffsetCommitCallbacks();
if (offsets.isEmpty()) {
// We guarantee that the callbacks for all commitAsync() will be invoked when
// commitSync() completes, even if the user tries to commit empty offsets.
return invokePendingAsyncCommits(timer);
}
long attempts = 0L;
do {
if (coordinatorUnknownAndUnreadySync(timer)) {
return false;
}
RequestFuture<Void> future = sendOffsetCommitRequest(offsets);
client.poll(future, timer);
// We may have had in-flight offset commits when the synchronous commit began. If so, ensure that
// the corresponding callbacks are invoked prior to returning in order to preserve the order that
// the offset commits were applied.
invokeCompletedOffsetCommitCallbacks();
if (future.succeeded()) {
if (interceptors != null)
interceptors.onCommit(offsets);
return true;
}
if (future.failed() && !future.isRetriable())
throw future.exception();
timer.sleep(retryBackoff.backoff(attempts++));
} while (timer.notExpired());
return false;
} | @Test
public void testCommitOffsetSyncWithoutFutureGetsCompleted() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
assertFalse(coordinator.commitOffsetsSync(singletonMap(t1p, new OffsetAndMetadata(100L)), time.timer(0)));
} |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "/export/by-query", produces = MediaType.APPLICATION_OCTET_STREAM)
@Operation(
tags = {"Flows"},
summary = "Export flows as a ZIP archive of yaml sources."
)
public HttpResponse<byte[]> exportByQuery(
@Parameter(description = "A string filter") @Nullable @QueryValue(value = "q") String query,
@Parameter(description = "A namespace filter prefix") @Nullable @QueryValue String namespace,
@Parameter(description = "A labels filter as a list of 'key:value'") @Nullable @QueryValue @Format("MULTI") List<String> labels
) throws IOException {
var flows = flowRepository.findWithSource(query, tenantService.resolveTenant(), namespace, RequestUtils.toMap(labels));
var bytes = zipFlows(flows);
return HttpResponse.ok(bytes).header("Content-Disposition", "attachment; filename=\"flows.zip\"");
} | @Test
void exportByQuery() throws IOException {
byte[] zip = client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/export/by-query?namespace=io.kestra.tests"),
Argument.of(byte[].class));
File file = File.createTempFile("flows", ".zip");
Files.write(file.toPath(), zip);
try (ZipFile zipFile = new ZipFile(file)) {
assertThat(zipFile.stream().count(), is(Helpers.FLOWS_COUNT -1));
}
file.delete();
} |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void returnOnErrorUsingMaybe() throws InterruptedException {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
given(helloWorldService.returnHelloWorld())
.willThrow(new HelloWorldException());
Maybe.fromCallable(helloWorldService::returnHelloWorld)
.compose(RetryTransformer.of(retry))
.test()
.await()
.assertError(HelloWorldException.class)
.assertNotComplete()
.assertSubscribed();
Maybe.fromCallable(helloWorldService::returnHelloWorld)
.compose(RetryTransformer.of(retry))
.test()
.await()
.assertError(HelloWorldException.class)
.assertNotComplete()
.assertSubscribed();
then(helloWorldService).should(times(6)).returnHelloWorld();
Retry.Metrics metrics = retry.getMetrics();
assertThat(metrics.getNumberOfFailedCallsWithRetryAttempt()).isEqualTo(2);
assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isZero();
} |
@GetMapping("")
public ShenyuAdminResult queryApis(final String apiPath, final Integer state,
final String tagId,
@NotNull final Integer currentPage,
@NotNull final Integer pageSize) {
CommonPager<ApiVO> commonPager = apiService.listByPage(new ApiQuery(apiPath, state, tagId, new PageParameter(currentPage, pageSize)));
return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, commonPager);
} | @Test
public void testQueryApis() throws Exception {
final PageParameter pageParameter = new PageParameter();
List<ApiVO> apiVOS = new ArrayList<>();
apiVOS.add(apiVO);
final CommonPager<ApiVO> commonPager = new CommonPager<>();
commonPager.setPage(pageParameter);
commonPager.setDataList(apiVOS);
final ApiQuery apiQuery = new ApiQuery("string", 0, "", pageParameter);
given(this.apiService.listByPage(apiQuery)).willReturn(commonPager);
this.mockMvc.perform(MockMvcRequestBuilders.get("/api")
.param("apiPath", "string")
.param("state", "0")
.param("tagId", "")
.param("currentPage", String.valueOf(pageParameter.getCurrentPage()))
.param("pageSize", String.valueOf(pageParameter.getPageSize())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(ShenyuResultMessage.QUERY_SUCCESS)))
.andExpect(jsonPath("$.data.dataList[0].contextPath", is(apiVO.getContextPath())))
.andReturn();
} |
public Result checkConnectionToPackage(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_CHECK_PACKAGE_CONNECTION, new DefaultPluginInteractionCallback<>() {
@Override
public String requestBody(String resolvedExtensionVersion) {
return messageConverter(resolvedExtensionVersion).requestMessageForCheckConnectionToPackage(packageConfiguration, repositoryConfiguration);
}
@Override
public Result onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) {
return messageConverter(resolvedExtensionVersion).responseMessageForCheckConnectionToPackage(responseBody);
}
});
} | @Test
public void shouldTalkToPluginToCheckPackageConnectionFailure() throws Exception {
String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," +
"\"package-configuration\":{\"key-three\":{\"value\":\"value-three\"},\"key-four\":{\"value\":\"value-four\"}}}";
String expectedResponseBody = "{\"status\":\"failure\",messages=[\"message-one\",\"message-two\"]}";
when(pluginManager.isPluginOfType(PACKAGE_MATERIAL_EXTENSION, PLUGIN_ID)).thenReturn(true);
when(pluginManager.submitTo(eq(PLUGIN_ID), eq(PACKAGE_MATERIAL_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(expectedResponseBody));
Result result = extension.checkConnectionToPackage(PLUGIN_ID, packageConfiguration, repositoryConfiguration);
assertRequest(requestArgumentCaptor.getValue(), PACKAGE_MATERIAL_EXTENSION, "1.0", PackageRepositoryExtension.REQUEST_CHECK_PACKAGE_CONNECTION, expectedRequestBody);
assertFailureResult(result, List.of("message-one", "message-two"));
} |
@Override
@SuppressWarnings("unchecked")
public AccessToken load(String token) {
DBObject query = new BasicDBObject();
query.put(AccessTokenImpl.TOKEN, cipher.encrypt(token));
final List<DBObject> objects = query(AccessTokenImpl.class, query);
if (objects.isEmpty()) {
return null;
}
if (objects.size() > 1) {
LOG.error("Multiple access tokens found, this is a serious bug.");
throw new IllegalStateException("Access tokens collection has no unique index!");
}
return fromDBObject(objects.get(0));
} | @Test
@MongoDBFixtures("accessTokensSingleToken.json")
public void testLoadSingleToken() throws Exception {
final AccessToken accessToken = accessTokenService.load("foobar");
assertNotNull("Matching token should have been returned", accessToken);
assertEquals("foobar", accessToken.getToken());
assertEquals("web", accessToken.getName());
assertEquals("admin", accessToken.getUserName());
assertEquals(DateTime.parse("2015-03-14T15:09:26.540Z"), accessToken.getLastAccess());
} |
@Override
public <T> T clone(T object) {
if (object instanceof String) {
return object;
} else if (object instanceof Collection) {
Object firstElement = findFirstNonNullElement((Collection) object);
if (firstElement != null && !(firstElement instanceof Serializable)) {
JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());
return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);
}
} else if (object instanceof Map) {
Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);
if (firstEntry != null) {
Object key = firstEntry.getKey();
Object value = firstEntry.getValue();
if (!(key instanceof Serializable) || !(value instanceof Serializable)) {
JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());
return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);
}
}
} else if (object instanceof JsonNode) {
return (T) ((JsonNode) object).deepCopy();
}
if (object instanceof Serializable) {
try {
return (T) SerializationHelper.clone((Serializable) object);
} catch (SerializationException e) {
//it is possible that object itself implements java.io.Serializable, but underlying structure does not
//in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization
}
}
return jsonClone(object);
} | @Test
public void should_clone_map_of_non_serializable_value_with_null_value() {
Map<String, NonSerializableObject> original = new LinkedHashMap<>();
original.put("null", null);
original.put("key", new NonSerializableObject("value"));
Object cloned = serializer.clone(original);
assertEquals(original, cloned);
assertNotSame(original, cloned);
} |
void serialize(OutputStream out, TransportSecurityOptions options) {
try {
mapper.writerWithDefaultPrettyPrinter().writeValue(out, toTransportSecurityOptionsEntity(options));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | @Test
void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
.withHostnameValidationDisabled(false)
.build();
File outputFile = File.createTempFile("junit", null, tempDirectory);
try (OutputStream out = Files.newOutputStream(outputFile.toPath())) {
new TransportSecurityOptionsJsonSerializer().serialize(out, options);
}
String expectedOutput = new String(Files.readAllBytes(
Paths.get("src/test/resources/transport-security-options-with-disable-hostname-validation-set-to-false.json")));
String actualOutput = new String(Files.readAllBytes(outputFile.toPath()));
assertJsonEquals(expectedOutput, actualOutput);
} |
@Nonnull
public static <T> Traverser<T> traverseSpliterator(@Nonnull Spliterator<T> spliterator) {
return new SpliteratorTraverser<>(spliterator);
} | @Test(expected = NullPointerException.class)
public void when_traverseSpliteratorWithNull_then_failure() {
Traverser<Integer> trav = traverseSpliterator(Stream.of(1, null).spliterator());
trav.next();
trav.next();
} |
@Override
public String fetchArtifactMessage(ArtifactStore artifactStore, Configuration configuration, Map<String, Object> metadata, String agentWorkingDirectory) {
final Map<String, Object> map = new HashMap<>();
map.put("store_configuration", artifactStore.getConfigurationAsMap(true));
map.put("fetch_artifact_configuration", configuration.getConfigurationAsMap(true));
map.put("artifact_metadata", metadata);
map.put("agent_working_directory", agentWorkingDirectory);
return NULLS_GSON.toJson(map);
} | @Test
public void fetchArtifactMessage_shouldSerializeToJson() {
final ArtifactMessageConverterV2 converter = new ArtifactMessageConverterV2();
final ArtifactStore artifactStore = new ArtifactStore("s3-store", "pluginId", create("Foo", false, "Bar"));
final Map<String, Object> metadata = Map.of("Version", "10.12.0");
final FetchPluggableArtifactTask pluggableArtifactTask = new FetchPluggableArtifactTask(null, null, "artifactId", create("Filename", false, "build/libs/foo.jar"));
final String fetchArtifactMessage = converter.fetchArtifactMessage(artifactStore, pluggableArtifactTask.getConfiguration(), metadata, "/temp");
final String expectedStr = """
{
"artifact_metadata": {
"Version": "10.12.0"
},
"store_configuration": {
"Foo": "Bar"
},
"fetch_artifact_configuration": {
"Filename": "build/libs/foo.jar"
},
"agent_working_directory": "/temp"
}""";
assertThatJson(expectedStr).isEqualTo(fetchArtifactMessage);
} |
public static StrimziPodSet createPodSet(
String name,
String namespace,
Labels labels,
OwnerReference ownerReference,
ResourceTemplate template,
int replicas,
Map<String, String> annotations,
Labels selectorLabels,
Function<Integer, Pod> podCreator
) {
List<Map<String, Object>> pods = new ArrayList<>(replicas);
for (int i = 0; i < replicas; i++) {
Pod pod = podCreator.apply(i);
pods.add(PodSetUtils.podToMap(pod));
}
return new StrimziPodSetBuilder()
.withNewMetadata()
.withName(name)
.withLabels(labels.withAdditionalLabels(TemplateUtils.labels(template)).toMap())
.withNamespace(namespace)
.withAnnotations(Util.mergeLabelsOrAnnotations(annotations, TemplateUtils.annotations(template)))
.withOwnerReferences(ownerReference)
.endMetadata()
.withNewSpec()
.withSelector(new LabelSelectorBuilder().withMatchLabels(selectorLabels.toMap()).build())
.withPods(pods)
.endSpec()
.build();
} | @Test
public void testCreateStrimziPodSetWithTemplate() {
List<Integer> podIds = new ArrayList<>();
StrimziPodSet sps = WorkloadUtils.createPodSet(
NAME,
NAMESPACE,
LABELS,
OWNER_REFERENCE,
new ResourceTemplateBuilder()
.withNewMetadata()
.withLabels(Map.of("label-3", "value-3", "label-4", "value-4"))
.withAnnotations(Map.of("anno-1", "value-1", "anno-2", "value-2"))
.endMetadata()
.build(),
REPLICAS,
Map.of("extra", "annotations"),
Labels.fromMap(Map.of("custom", "selector")),
i -> {
podIds.add(i);
return new PodBuilder()
.withNewMetadata()
.withName(NAME + "-" + i)
.endMetadata()
.build();
}
);
assertThat(sps.getMetadata().getName(), is(NAME));
assertThat(sps.getMetadata().getNamespace(), is(NAMESPACE));
assertThat(sps.getMetadata().getOwnerReferences(), is(List.of(OWNER_REFERENCE)));
assertThat(sps.getMetadata().getLabels(), is(LABELS.withAdditionalLabels(Map.of("label-3", "value-3", "label-4", "value-4")).toMap()));
assertThat(sps.getMetadata().getAnnotations(), is(Map.of("extra", "annotations", "anno-1", "value-1", "anno-2", "value-2")));
assertThat(sps.getSpec().getSelector().getMatchLabels().size(), is(1));
assertThat(sps.getSpec().getSelector().getMatchLabels(), is(Map.of("custom", "selector")));
// Test generating pods from the PodCreator method
assertThat(podIds.size(), is(5));
assertThat(podIds, is(List.of(0, 1, 2, 3, 4)));
assertThat(sps.getSpec().getPods().size(), is(5));
assertThat(sps.getSpec().getPods().stream().map(pod -> PodSetUtils.mapToPod(pod).getMetadata().getName()).toList(), is(List.of("my-workload-0", "my-workload-1", "my-workload-2", "my-workload-3", "my-workload-4")));
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthSendTransaction() throws Exception {
web3j.ethSendTransaction(
new Transaction(
"0xb60e8dd61c5d32be8058bb8eb970870f07233155",
BigInteger.ONE,
Numeric.toBigInt("0x9184e72a000"),
Numeric.toBigInt("0x76c0"),
"0xb60e8dd61c5d32be8058bb8eb970870f07233155",
Numeric.toBigInt("0x9184e72a"),
"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb"
+ "970870f072445675058bb8eb970870f072445675"))
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\",\"nonce\":\"0x1\"}],\"id\":1}");
} |
@Override
public void publish(ScannerReportWriter writer) {
ScannerReport.Component.Builder projectBuilder = prepareProjectBuilder();
ScannerReport.Component.Builder fileBuilder = ScannerReport.Component.newBuilder();
for (DefaultInputFile file : inputComponentStore.allFilesToPublish()) {
projectBuilder.addChildRef(file.scannerId());
fileBuilder.clear();
// non-null fields
fileBuilder.setRef(file.scannerId());
fileBuilder.setType(ComponentType.FILE);
fileBuilder.setIsTest(file.type() == InputFile.Type.TEST);
fileBuilder.setLines(file.lines());
fileBuilder.setStatus(convert(file.status()));
fileBuilder.setMarkedAsUnchanged(file.isMarkedAsUnchanged());
String oldRelativePath = file.oldRelativePath();
if (oldRelativePath != null) {
fileBuilder.setOldRelativeFilePath(oldRelativePath);
}
String lang = getLanguageKey(file);
if (lang != null) {
fileBuilder.setLanguage(lang);
}
fileBuilder.setProjectRelativePath(file.getProjectRelativePath());
writer.writeComponent(fileBuilder.build());
}
writer.writeComponent(projectBuilder.build());
} | @Test
public void publish_project_with_links() throws Exception {
ProjectInfo projectInfo = mock(ProjectInfo.class);
when(projectInfo.getAnalysisDate()).thenReturn(DateUtils.parseDate("2012-12-12"));
ProjectDefinition rootDef = ProjectDefinition.create()
.setKey("foo")
.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "1.0")
.setName("Root project")
.setProperty(CoreProperties.LINKS_HOME_PAGE, "http://home")
.setProperty(CoreProperties.LINKS_CI, "http://ci")
.setDescription("Root description")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder());
DefaultInputProject project = new DefaultInputProject(rootDef, 1);
InputComponentStore store = new InputComponentStore(branchConfiguration, sonarRuntime);
ComponentsPublisher publisher = new ComponentsPublisher(project, store);
publisher.publish(writer);
ScannerReportReader reader = new ScannerReportReader(fileStructure);
Component rootProtobuf = reader.readComponent(1);
assertThat(rootProtobuf.getLinkCount()).isEqualTo(2);
assertThat(rootProtobuf.getLink(0).getType()).isEqualTo(ComponentLinkType.HOME);
assertThat(rootProtobuf.getLink(0).getHref()).isEqualTo("http://home");
assertThat(rootProtobuf.getLink(1).getType()).isEqualTo(ComponentLinkType.CI);
assertThat(rootProtobuf.getLink(1).getHref()).isEqualTo("http://ci");
} |
static void execute(String... args) throws Exception {
if (args.length != 5 && args.length != 6) {
throw new TerseException("USAGE: java " + EndToEndLatency.class.getName()
+ " broker_list topic num_messages producer_acks message_size_bytes [optional] properties_file");
}
String brokers = args[0];
String topic = args[1];
int numMessages = Integer.parseInt(args[2]);
String acks = args[3];
int messageSizeBytes = Integer.parseInt(args[4]);
Optional<String> propertiesFile = (args.length > 5 && !Utils.isBlank(args[5])) ? Optional.of(args[5]) : Optional.empty();
if (!Arrays.asList("1", "all").contains(acks)) {
throw new IllegalArgumentException("Latency testing requires synchronous acknowledgement. Please use 1 or all");
}
try (KafkaConsumer<byte[], byte[]> consumer = createKafkaConsumer(propertiesFile, brokers);
KafkaProducer<byte[], byte[]> producer = createKafkaProducer(propertiesFile, brokers, acks)) {
if (!consumer.listTopics().containsKey(topic)) {
createTopic(propertiesFile, brokers, topic);
}
setupConsumer(topic, consumer);
double totalTime = 0.0;
long[] latencies = new long[numMessages];
Random random = new Random(0);
for (int i = 0; i < numMessages; i++) {
byte[] message = randomBytesOfLen(random, messageSizeBytes);
long begin = System.nanoTime();
//Send message (of random bytes) synchronously then immediately poll for it
producer.send(new ProducerRecord<>(topic, message)).get();
ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(POLL_TIMEOUT_MS));
long elapsed = System.nanoTime() - begin;
validate(consumer, message, records);
//Report progress
if (i % 1000 == 0)
System.out.println(i + "\t" + elapsed / 1000.0 / 1000.0);
totalTime += elapsed;
latencies[i] = elapsed / 1000 / 1000;
}
printResults(numMessages, totalTime, latencies);
consumer.commitSync();
}
} | @Test
public void shouldFailWhenSuppliedUnexpectedArgs() {
String[] args = new String[] {"localhost:9092", "test", "10000", "1", "200", "propsfile.properties", "random"};
assertThrows(TerseException.class, () -> EndToEndLatency.execute(args));
} |
@Override
public void removeService(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);
synchronized (this) {
if (isServiceInUse(uid)) {
final String error = String.format(MSG_SERVICE, uid, ERR_IN_USE);
throw new IllegalStateException(error);
}
Service service = k8sServiceStore.removeService(uid);
if (service != null) {
log.info(String.format(MSG_SERVICE,
service.getMetadata().getName(), MSG_REMOVED));
}
}
} | @Test(expected = IllegalArgumentException.class)
public void testRemoveServiceWithNull() {
target.removeService(null);
} |
public Map<String, Map<String, Object>> getPropertyMetadataAndValuesAsMap() {
Map<String, Map<String, Object>> configMap = new HashMap<>();
for (ConfigurationProperty property : this) {
Map<String, Object> mapValue = new HashMap<>();
mapValue.put("isSecure", property.isSecure());
if (property.isSecure()) {
mapValue.put(VALUE_KEY, property.getEncryptedValue());
} else {
final String value = property.getConfigurationValue() == null ? null : property.getConfigurationValue().getValue();
mapValue.put(VALUE_KEY, value);
}
mapValue.put("displayValue", property.getDisplayValue());
configMap.put(property.getConfigKeyName(), mapValue);
}
return configMap;
} | @Test
void shouldReturnConfigWithMetadataAsMap() throws CryptoException {
ConfigurationProperty configurationProperty1 = ConfigurationPropertyMother.create("property1", false, "value");
ConfigurationProperty configurationProperty2 = ConfigurationPropertyMother.create("property2", false, null);
String password = new GoCipher().encrypt("password");
ConfigurationProperty configurationProperty3 = ConfigurationPropertyMother.create("property3");
configurationProperty3.setEncryptedValue(new EncryptedConfigurationValue(password));
Configuration configuration = new Configuration(configurationProperty1, configurationProperty2, configurationProperty3);
Map<String, Map<String, Object>> metadataAndValuesAsMap = configuration.getPropertyMetadataAndValuesAsMap();
Map<Object, Object> expectedMap = new HashMap<>();
expectedMap.put("property1", buildPropertyMap(false, "value", "value"));
expectedMap.put("property2", buildPropertyMap(false, null, null));
expectedMap.put("property3", buildPropertyMap(true, password, "****"));
assertThat(metadataAndValuesAsMap).isEqualTo(expectedMap);
} |
public static byte[] getValue(byte[] raw) {
try (final Asn1InputStream is = new Asn1InputStream(raw)) {
is.readTag();
return is.read(is.readLength());
}
} | @Test
public void getValueShouldSkipExtendedTagAndLength() {
assertArrayEquals(new byte[] { 0x31 }, Asn1Utils.getValue(new byte[] { 0x7f, 0x01, 1, 0x31}));
} |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void retryOnResultUsingFlowable() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
given(helloWorldService.returnHelloWorld())
.willReturn("retry")
.willReturn("success");
Flowable.fromCallable(helloWorldService::returnHelloWorld)
.compose(RetryTransformer.of(retry))
.test()
.await()
.assertValueCount(1)
.assertValue("success")
.assertComplete();
then(helloWorldService).should(times(2)).returnHelloWorld();
Retry.Metrics metrics = retry.getMetrics();
assertThat(metrics.getNumberOfFailedCallsWithoutRetryAttempt()).isZero();
assertThat(metrics.getNumberOfSuccessfulCallsWithRetryAttempt()).isEqualTo(1);
} |
public <V> V retryCallable(
Callable<V> callable, Set<Class<? extends Exception>> exceptionsToIntercept) {
return RetryHelper.runWithRetries(
callable,
getRetrySettings(),
getExceptionHandlerForExceptions(exceptionsToIntercept),
NanoClock.getDefaultClock());
} | @Test(expected = RetryHelperException.class)
public void testRetryCallable_ThrowsRetryHelperExceptionOnUnspecifiedException() {
Callable<Integer> incrementingFunction =
() -> {
throw new DoNotIgnoreException();
};
retryCallableManager.retryCallable(incrementingFunction, ImmutableSet.of(MyException.class));
} |
@Override
protected void set(String key, String value) {
localProperties.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
} | @Test
public void set_will_throw_NPE_if_key_is_null() {
assertThatThrownBy(() -> underTest.set(null, ""))
.isInstanceOf(NullPointerException.class)
.hasMessage("key can't be null");
} |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definition: return false if any item is false, else true if all items are true, else null
for ( final Object element : list ) {
if (element != null && !(element instanceof Boolean)) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean"));
} else {
if (element != null) {
result &= (Boolean) element;
} else if (!containsNull) {
containsNull = true;
}
}
}
if (containsNull && result) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( result );
}
} | @Test
void invokeListParamReturnNull() {
FunctionTestUtil.assertResultNull(allFunction.invoke(Arrays.asList(Boolean.TRUE, null, Boolean.TRUE)));
} |
@Override
@PublicAPI(usage = ACCESS)
public boolean isAnnotatedWith(Class<? extends Annotation> annotationType) {
return packageInfo.map(it -> it.isAnnotatedWith(annotationType)).orElse(false);
} | @Test
public void test_isAnnotatedWith_type() {
JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
JavaPackage nonAnnotatedPackage = importPackage("packageexamples");
assertThat(annotatedPackage.isAnnotatedWith(PackageLevelAnnotation.class)).isTrue();
assertThat(annotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
assertThat(nonAnnotatedPackage.isAnnotatedWith(Deprecated.class)).isFalse();
} |
public Exception getException() {
if (exception != null) return exception;
try {
final Class<? extends Exception> exceptionClass = ReflectionUtils.toClass(getExceptionType());
if (getExceptionCauseType() != null) {
final Class<? extends Exception> exceptionCauseClass = ReflectionUtils.toClass(getExceptionCauseType());
final Exception exceptionCause = getExceptionCauseMessage() != null ? ReflectionUtils.newInstanceCE(exceptionCauseClass, getExceptionCauseMessage()) : ReflectionUtils.newInstanceCE(exceptionCauseClass);
exceptionCause.setStackTrace(new StackTraceElement[]{});
return getExceptionMessage() != null ? ReflectionUtils.newInstanceCE(exceptionClass, getExceptionMessage(), exceptionCause) : ReflectionUtils.newInstanceCE(exceptionClass, exceptionCause);
} else {
return getExceptionMessage() != null ? ReflectionUtils.newInstanceCE(exceptionClass, getExceptionMessage()) : ReflectionUtils.newInstanceCE(exceptionClass);
}
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Could not reconstruct exception for class " + getExceptionType() + " and message " + getExceptionMessage(), e);
}
} | @Test
void getExceptionWithMessageAndNestedException() {
final FailedState failedState = new FailedState("JobRunr message", new CustomException("custom exception message", new CustomException()));
assertThat(failedState.getException())
.isInstanceOf(CustomException.class)
.hasMessage("custom exception message")
.hasCauseInstanceOf(CustomException.class);
} |
@Override
public Num calculate(BarSeries series, Position position) {
int beginIndex = position.getEntry().getIndex();
int endIndex = series.getEndIndex();
return criterion.calculate(series, createEnterAndHoldTrade(series, beginIndex, endIndex));
} | @Test
public void calculateOnlyWithLossPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(1, series),
Trade.buyAt(2, series), Trade.sellAt(5, series));
// buy and hold of ReturnCriterion
AnalysisCriterion buyAndHoldReturn = getCriterion(new ReturnCriterion());
assertNumEquals(0.7, buyAndHoldReturn.calculate(series, tradingRecord));
// sell and hold of ReturnCriterion
AnalysisCriterion sellAndHoldReturn = getCriterion(TradeType.SELL, new ReturnCriterion());
assertNumEquals(1.3, sellAndHoldReturn.calculate(series, tradingRecord));
// buy and hold of ProfitLossPercentageCriterion
AnalysisCriterion buyAndHoldPnlPercentage = getCriterion(new ProfitLossPercentageCriterion());
assertNumEquals(-30, buyAndHoldPnlPercentage.calculate(series, tradingRecord));
// sell and hold of ProfitLossPercentageCriterion
AnalysisCriterion sellAndHoldPnlPercentage = getCriterion(TradeType.SELL, new ProfitLossPercentageCriterion());
assertNumEquals(30, sellAndHoldPnlPercentage.calculate(series, tradingRecord));
} |
@Override
public OAuth2AccessTokenDO removeAccessToken(String accessToken) {
// 删除访问令牌
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenMapper.selectByAccessToken(accessToken);
if (accessTokenDO == null) {
return null;
}
oauth2AccessTokenMapper.deleteById(accessTokenDO.getId());
oauth2AccessTokenRedisDAO.delete(accessToken);
// 删除刷新令牌
oauth2RefreshTokenMapper.deleteByRefreshToken(accessTokenDO.getRefreshToken());
return accessTokenDO;
} | @Test
public void testRemoveAccessToken_null() {
// 调用,并断言
assertNull(oauth2TokenService.removeAccessToken(randomString()));
} |
public static String version() {
return IcebergBuild.version();
} | @Test
public void testGetVersion() {
String version = IcebergSinkConfig.version();
assertThat(version).isNotNull();
} |
Future<Boolean> canRoll(int podId) {
LOGGER.debugCr(reconciliation, "Determining whether broker {} can be rolled", podId);
return canRollBroker(descriptions, podId);
} | @Test
public void testCanRollThrowsTimeoutExceptionWhenTopicsListThrowsException(VertxTestContext context) {
KSB ksb = new KSB()
.addNewTopic("A", false)
.addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
.addNewPartition(0)
.replicaOn(0, 1, 2)
.leader(0)
.isr(0, 1, 2)
.endPartition()
.endTopic()
.addNewTopic("B", false)
.addToConfig(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, "1")
.addNewPartition(0)
.replicaOn(0, 1, 2)
.leader(1)
.isr(0, 1, 2)
.endPartition()
.endTopic()
.addBroker(3)
.listTopicsResult(new TimeoutException());
KafkaAvailability kafkaAvailability = new KafkaAvailability(new Reconciliation("dummy", "kind", "namespace", "A"), ksb.ac());
Checkpoint a = context.checkpoint(ksb.brokers.size());
for (Integer brokerId : ksb.brokers.keySet()) {
kafkaAvailability.canRoll(brokerId).onComplete(context.failing(e -> context.verify(() -> {
assertThat(e, instanceOf(TimeoutException.class));
a.flag();
})));
}
} |
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be null");
if (dataTable.isEmpty()) {
return emptyMap();
}
DataTable keyColumn = dataTable.columns(0, 1);
DataTable valueColumns = dataTable.columns(1);
String firstHeaderCell = keyColumn.cell(0, 0);
boolean firstHeaderCellIsBlank = firstHeaderCell == null || firstHeaderCell.isEmpty();
List<K> keys = convertEntryKeys(keyType, keyColumn, valueType, firstHeaderCellIsBlank);
if (valueColumns.isEmpty()) {
return createMap(keyType, keys, valueType, nCopies(keys.size(), null));
}
boolean keysImplyTableRowTransformer = keys.size() == dataTable.height() - 1;
List<V> values = convertEntryValues(valueColumns, keyType, valueType, keysImplyTableRowTransformer);
if (keys.size() != values.size()) {
throw keyValueMismatchException(firstHeaderCellIsBlank, keys.size(), keyType, values.size(), valueType);
}
return createMap(keyType, keys, valueType, values);
} | @Test
void to_map_of_entry_to_row__throws_exception__more_values_then_keys() {
DataTable table = parse("",
"| code | 29.993333 | -90.258056 |",
"| KSFO | 37.618889 | -122.375 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KJFK | 40.639722 | -73.778889 |");
registry.defineDataTableType(new DataTableType(AirPortCode.class, AIR_PORT_CODE_TABLE_ENTRY_TRANSFORMER));
registry.defineDataTableType(new DataTableType(Coordinate.class, COORDINATE_TABLE_ROW_TRANSFORMER));
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> converter.toMap(table, AirPortCode.class, Coordinate.class));
assertThat(exception.getMessage(), is(format("" +
"Can't convert DataTable to Map<%s, %s>.\n" +
"There are more values then keys. " +
"Did you use a TableEntryTransformer for the key " +
"while using a TableRow or TableCellTransformer for the value?",
typeName(AirPortCode.class), typeName(Coordinate.class))));
} |
public RelDataType createRelDataTypeFromSchema(Schema schema) {
Builder builder = new Builder(this);
boolean enableNullHandling = schema.isEnableColumnBasedNullHandling();
for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) {
builder.add(entry.getKey(), toRelDataType(entry.getValue(), enableNullHandling));
}
return builder.build();
} | @Test(dataProvider = "relDataTypeConversion")
public void testNullableScalarTypes(FieldSpec.DataType dataType, RelDataType scalarType, boolean columnNullMode) {
TypeFactory typeFactory = new TypeFactory();
Schema testSchema = new Schema.SchemaBuilder()
.addDimensionField("col", dataType, field -> field.setNullable(true))
.setEnableColumnBasedNullHandling(columnNullMode)
.build();
RelDataType relDataTypeFromSchema = typeFactory.createRelDataTypeFromSchema(testSchema);
List<RelDataTypeField> fieldList = relDataTypeFromSchema.getFieldList();
RelDataTypeField field = fieldList.get(0);
boolean colNullable = isColNullable(testSchema);
RelDataType expectedType = typeFactory.createTypeWithNullability(scalarType, colNullable);
Assert.assertEquals(field.getType(), expectedType);
} |
@CanIgnoreReturnValue
public final Ordered containsExactly() {
return containsExactlyEntriesIn(ImmutableMap.of());
} | @Test
public void containsExactlyEmpty_fails() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
expectFailureWhenTestingThat(actual).containsExactly();
assertFailureKeys("expected to be empty", "but was");
} |
@Override
public Progress getProgress() {
// If current tracking range is no longer growable, get progress as a normal range.
if (range.getTo() != Long.MAX_VALUE || range.getTo() == range.getFrom()) {
return super.getProgress();
}
// Convert to BigDecimal in computation to prevent overflow, which may result in lost of
// precision.
BigDecimal estimateRangeEnd = BigDecimal.valueOf(rangeEndEstimator.estimate());
if (lastAttemptedOffset == null) {
return Progress.from(
0,
estimateRangeEnd
.subtract(BigDecimal.valueOf(range.getFrom()), MathContext.DECIMAL128)
.max(BigDecimal.ZERO)
.doubleValue());
}
BigDecimal workRemaining =
estimateRangeEnd
.subtract(BigDecimal.valueOf(lastAttemptedOffset), MathContext.DECIMAL128)
.max(BigDecimal.ZERO);
BigDecimal totalWork =
estimateRangeEnd
.max(BigDecimal.valueOf(lastAttemptedOffset))
.subtract(BigDecimal.valueOf(range.getFrom()), MathContext.DECIMAL128);
return Progress.from(
totalWork.subtract(workRemaining, MathContext.DECIMAL128).doubleValue(),
workRemaining.doubleValue());
} | @Test
public void testProgressAfterFinished() throws Exception {
SimpleEstimator simpleEstimator = new SimpleEstimator();
GrowableOffsetRangeTracker tracker = new GrowableOffsetRangeTracker(10L, simpleEstimator);
assertFalse(tracker.tryClaim(Long.MAX_VALUE));
tracker.checkDone();
simpleEstimator.setEstimateRangeEnd(0L);
Progress currentProgress = tracker.getProgress();
assertEquals(Long.MAX_VALUE - 10L, currentProgress.getWorkCompleted(), 0);
assertEquals(0, currentProgress.getWorkRemaining(), 0.001);
} |
public static String getStackTracker( Throwable e ) {
return getClassicStackTrace( e );
} | @Test
public void testStackTracker() {
assertTrue( Const.getStackTracker( new Exception() ).contains( getClass().getName() + ".testStackTracker("
+ getClass().getSimpleName() + ".java:" ) );
} |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeAlterSystemProperty() {
Assert.assertEquals("ALTER SYSTEM 'ksql.persistent.prefix'='[string]';",
anon.anonymize("ALTER SYSTEM 'ksql.persistent.prefix'='test';"));
} |
public List<CommentSimpleResponse> findAllWithPaging(final Long boardId, final Long memberId, final Long commentId, final int pageSize) {
return jpaQueryFactory.select(constructor(CommentSimpleResponse.class,
comment.id,
comment.content,
member.id,
member.id.eq(memberId),
member.nickname,
comment.createdAt
)).from(comment)
.where(
ltCommentId(commentId),
comment.boardId.eq(boardId)
)
.orderBy(comment.id.desc())
.leftJoin(member).on(comment.writerId.eq(member.id))
.limit(pageSize)
.fetch();
} | @Test
void no_offset_페이징_두번째_조회() {
// given
for (long i = 1L; i <= 20L; i++) {
commentRepository.save(Comment.builder()
.id(i)
.boardId(board.getId())
.content("comment")
.writerId(member.getId())
.build()
);
}
// when
List<CommentSimpleResponse> result = commentQueryRepository.findAllWithPaging(1L, member.getId(), 11L, 10);
// then
assertSoftly(softly -> {
softly.assertThat(result).hasSize(10);
softly.assertThat(result.get(0).id()).isEqualTo(10L);
softly.assertThat(result.get(9).id()).isEqualTo(1L);
});
} |
public String getAndFormatStatsFor(final String topic, final boolean isError) {
return format(
getStatsFor(topic, isError),
isError ? "last-failed" : "last-message");
} | @Test
public void shouldKeepWorkingWhenDuplicateTopicConsumerIsRemoved() {
final MetricCollectors metricCollectors = new MetricCollectors();
final ConsumerCollector collector1 = new ConsumerCollector();
collector1.configure(
ImmutableMap.of(
ConsumerConfig.GROUP_ID_CONFIG, "stream-thread-1",
KsqlConfig.KSQL_INTERNAL_METRIC_COLLECTORS_CONFIG, metricCollectors
)
);
final ConsumerCollector collector2 = new ConsumerCollector();
collector2.configure(
ImmutableMap.of(
ConsumerConfig.GROUP_ID_CONFIG, "stream-thread-2",
KsqlConfig.KSQL_INTERNAL_METRIC_COLLECTORS_CONFIG, metricCollectors
)
);
final Map<TopicPartition, List<ConsumerRecord<Object, Object>>> records = ImmutableMap.of(
new TopicPartition(TEST_TOPIC, 1),
Collections.singletonList(
new ConsumerRecord<>(
TEST_TOPIC,
1,
1,
1L,
TimestampType.CREATE_TIME,
10,
10,
"key",
"1234567890",
new RecordHeaders(),
Optional.empty()
)
)
);
final ConsumerRecords<Object, Object> consumerRecords = new ConsumerRecords<>(records);
collector1.onConsume(consumerRecords);
collector2.onConsume(consumerRecords);
final String firstPassStats = metricCollectors.getAndFormatStatsFor(TEST_TOPIC, false);
assertTrue("Missed stats, got:" + firstPassStats, firstPassStats.contains("total-messages: 2"));
collector2.close();
collector1.onConsume(consumerRecords);
final String statsForTopic2 = metricCollectors.getAndFormatStatsFor(TEST_TOPIC, false);
assertTrue("Missed stats, got:" + statsForTopic2, statsForTopic2.contains("total-messages: 2"));
} |
public static Expression generateFilterExpression(SearchArgument sarg) {
return translate(sarg.getExpression(), sarg.getLeaves());
} | @Test
public void testNotEqualsOperand() {
SearchArgument.Builder builder = SearchArgumentFactory.newBuilder();
SearchArgument arg =
builder.startNot().equals("salary", PredicateLeaf.Type.LONG, 3000L).end().build();
Not expected = (Not) Expressions.not(Expressions.equal("salary", 3000L));
Not actual = (Not) HiveIcebergFilterFactory.generateFilterExpression(arg);
UnboundPredicate childExpressionActual = (UnboundPredicate) actual.child();
UnboundPredicate childExpressionExpected = Expressions.equal("salary", 3000L);
assertThat(expected.op()).isEqualTo(actual.op());
assertThat(expected.child().op()).isEqualTo(actual.child().op());
assertThat(childExpressionExpected.ref().name()).isEqualTo(childExpressionActual.ref().name());
assertThat(childExpressionExpected.literal()).isEqualTo(childExpressionActual.literal());
} |
@Nonnull
public Vertex localParallelism(int localParallelism) {
throwIfLocked();
this.localParallelism = checkLocalParallelism(localParallelism);
return this;
} | @Test
public void when_badLocalParallelism_then_error() {
v = new Vertex("v", NoopP::new);
v.localParallelism(4);
v.localParallelism(-1); // this is good
Assert.assertThrows(IllegalArgumentException.class, () -> v.localParallelism(-5)); // this is not good
} |
public static void main(String[] args) {
LOGGER.info("The knight receives an enchanted sword.");
var enchantedSword = new Sword(new SoulEatingEnchantment());
enchantedSword.wield();
enchantedSword.swing();
enchantedSword.unwield();
LOGGER.info("The valkyrie receives an enchanted hammer.");
var hammer = new Hammer(new FlyingEnchantment());
hammer.wield();
hammer.swing();
hammer.unwield();
} | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
public static VerificationMode times(final int count) {
checkArgument(count >= 0, "Times count must not be less than zero");
return new TimesVerification(count);
} | @Test
public void should_verify_expected_request_and_log_at_same_time_for_https() throws Exception {
final HttpServer server = httpsServer(port(), DEFAULT_CERTIFICATE, hit, log());
server.get(by(uri("/foo"))).response("bar");
running(server, () -> assertThat(helper.get(remoteHttpsUrl("/foo")), is("bar")));
hit.verify(by(uri("/foo")), times(1));
} |
@Override
public void recordMisses(int count) {
missCount.inc(count);
} | @Test
public void miss() {
stats.recordMisses(2);
assertThat(registry.counter(PREFIX + ".misses").getCount()).isEqualTo(2);
} |
public Optional<T> owned() {
return isOwned ? Optional.of(value) : Optional.empty();
} | @Test
void testOwnedReferenceReturnsSomeOwned() {
final String value = "foobar";
final Reference<String> owned = Reference.owned(value);
assertThat(owned.owned()).hasValue(value);
} |
protected Triple<MessageExt, String, Boolean> getMessageFromRemote(String topic, long offset, int queueId, String brokerName) {
return getMessageFromRemoteAsync(topic, offset, queueId, brokerName).join();
} | @Test
public void getMessageFromRemoteTest() {
Assertions.assertThatCode(() -> escapeBridge.getMessageFromRemote(TEST_TOPIC, 1, DEFAULT_QUEUE_ID, BROKER_NAME)).doesNotThrowAnyException();
} |
@Override
public boolean isValid(final String object,
final ConstraintValidatorContext constraintContext) {
if (object == null) {
return true;
}
final int lengthInBytes = object.getBytes(StandardCharsets.UTF_8).length;
return lengthInBytes >= this.min && lengthInBytes <= this.max;
} | @Test
void nullObjectIsValid() {
assertThat(toTest.isValid(null, null)).isTrue();
} |
Flux<Post> allPosts() {
return client.get()
.uri("/posts")
.accept(MediaType.APPLICATION_JSON)
.exchangeToFlux(response -> response.bodyToFlux(Post.class));
} | @SneakyThrows
@Test
public void testGetAllPosts() {
var data = List.of(
new Post(UUID.randomUUID(), "title1", "content1", Status.DRAFT, LocalDateTime.now()),
new Post(UUID.randomUUID(), "title2", "content2", Status.PUBLISHED, LocalDateTime.now())
);
stubFor(get("/posts")
.willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withResponseBody(Body.fromJsonBytes(Json.toByteArray(data)))
)
);
postClient.allPosts()
.as(StepVerifier::create)
.expectNextCount(2)
.verifyComplete();
verify(getRequestedFor(urlEqualTo("/posts"))
.withHeader("Accept", equalTo("application/json")));
} |
public boolean fileIsInAllowedPath(Path path) {
if (allowedPaths.isEmpty()) {
return true;
}
final Path realFilePath = resolveRealPath(path);
if (realFilePath == null) {
return false;
}
for (Path allowedPath : allowedPaths) {
final Path realAllowedPath = resolveRealPath(allowedPath);
if (realAllowedPath != null && realFilePath.startsWith(realAllowedPath)) {
return true;
}
}
return false;
} | @Test
public void permittedPathDoesNotExist() throws IOException {
final Path permittedPath = Paths.get("non-existent-file-path");
final Path filePath = permittedTempDir.newFile(FILE).toPath();
pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.singleton(permittedPath)));
assertFalse(pathChecker.fileIsInAllowedPath(filePath));
} |
private JobMetrics getJobMetrics() throws IOException {
if (cachedMetricResults != null) {
// Metric results have been cached after the job ran.
return cachedMetricResults;
}
JobMetrics result = dataflowClient.getJobMetrics(dataflowPipelineJob.getJobId());
if (dataflowPipelineJob.getState().isTerminal()) {
// Add current query result to the cache.
cachedMetricResults = result;
}
return result;
} | @Test
public void testEmptyMetricUpdates() throws IOException {
Job modelJob = new Job();
modelJob.setCurrentState(State.RUNNING.toString());
DataflowPipelineJob job = mock(DataflowPipelineJob.class);
DataflowPipelineOptions options = mock(DataflowPipelineOptions.class);
when(options.isStreaming()).thenReturn(false);
when(job.getDataflowOptions()).thenReturn(options);
when(job.getState()).thenReturn(State.RUNNING);
when(job.getJobId()).thenReturn(JOB_ID);
JobMetrics jobMetrics = new JobMetrics();
jobMetrics.setMetrics(null /* this is how the APIs represent empty metrics */);
DataflowClient dataflowClient = mock(DataflowClient.class);
when(dataflowClient.getJobMetrics(JOB_ID)).thenReturn(jobMetrics);
DataflowMetrics dataflowMetrics = new DataflowMetrics(job, dataflowClient);
MetricQueryResults result = dataflowMetrics.allMetrics();
assertThat(ImmutableList.copyOf(result.getCounters()), is(empty()));
assertThat(ImmutableList.copyOf(result.getDistributions()), is(empty()));
assertThat(ImmutableList.copyOf(result.getStringSets()), is(empty()));
} |
public EdgeIteratorState copyEdge(int edge, boolean reuseGeometry) {
EdgeIteratorStateImpl edgeState = (EdgeIteratorStateImpl) getEdgeIteratorState(edge, Integer.MIN_VALUE);
EdgeIteratorStateImpl newEdge = (EdgeIteratorStateImpl) edge(edgeState.getBaseNode(), edgeState.getAdjNode())
.setFlags(edgeState.getFlags())
.setDistance(edgeState.getDistance())
.setKeyValues(edgeState.getKeyValues());
if (reuseGeometry) {
// We use the same geo ref for the copied edge. This saves memory because we are not duplicating
// the geometry, and it allows to identify the copies of a given edge.
long edgePointer = edgeState.edgePointer;
long geoRef = store.getGeoRef(edgePointer);
if (geoRef == 0) {
// No geometry for this edge, but we need to be able to identify the copied edges later, so
// we use a dedicated negative value for the geo ref.
geoRef = minGeoRef;
store.setGeoRef(edgePointer, geoRef);
minGeoRef--;
}
store.setGeoRef(newEdge.edgePointer, geoRef);
} else {
newEdge.setWayGeometry(edgeState.fetchWayGeometry(FetchMode.PILLAR_ONLY));
}
return newEdge;
} | @Test
public void copyEdge() {
BaseGraph graph = createGHStorage();
EnumEncodedValue<RoadClass> rcEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class);
EdgeIteratorState edge1 = graph.edge(3, 5).set(rcEnc, RoadClass.LIVING_STREET);
EdgeIteratorState edge2 = graph.edge(3, 5).set(rcEnc, RoadClass.MOTORWAY);
EdgeIteratorState edge3 = graph.copyEdge(edge1.getEdge(), true);
EdgeIteratorState edge4 = graph.copyEdge(edge1.getEdge(), false);
assertEquals(RoadClass.LIVING_STREET, edge1.get(rcEnc));
assertEquals(RoadClass.MOTORWAY, edge2.get(rcEnc));
assertEquals(edge1.get(rcEnc), edge3.get(rcEnc));
assertEquals(edge1.get(rcEnc), edge4.get(rcEnc));
graph.forEdgeAndCopiesOfEdge(graph.createEdgeExplorer(), edge1, e -> e.set(rcEnc, RoadClass.FOOTWAY));
assertEquals(RoadClass.FOOTWAY, edge1.get(rcEnc));
assertEquals(RoadClass.FOOTWAY, edge3.get(rcEnc));
// edge4 was not changed because it was copied with reuseGeometry=false
assertEquals(RoadClass.LIVING_STREET, edge4.get(rcEnc));
} |
public static boolean validatePlugin(PluginLookup.PluginType type, Class<?> pluginClass) {
switch (type) {
case INPUT:
return containsAllMethods(inputMethods, pluginClass.getMethods());
case FILTER:
return containsAllMethods(filterMethods, pluginClass.getMethods());
case CODEC:
return containsAllMethods(codecMethods, pluginClass.getMethods());
case OUTPUT:
return containsAllMethods(outputMethods, pluginClass.getMethods());
default:
throw new IllegalStateException("Unknown plugin type for validation: " + type);
}
} | @Test
public void testValidInputPlugin() {
Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.INPUT, Stdin.class));
Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.INPUT, Generator.class));
} |
@Override
public ProcNodeInterface lookup(String dbIdStr) throws AnalysisException {
long dbId = -1L;
try {
dbId = Long.valueOf(dbIdStr);
} catch (NumberFormatException e) {
throw new AnalysisException("Invalid db id format: " + dbIdStr);
}
if (globalStateMgr.getDb(dbId) == null) {
throw new AnalysisException("Invalid db id: " + dbIdStr);
}
return new IncompleteTabletsProcNode(unhealthyTabletIds.get(dbId),
inconsistentTabletIds.get(dbId),
cloningTabletIds.get(dbId),
errorStateTabletIds.get(dbId));
} | @Test(expected = AnalysisException.class)
public void testLookupInvalid() throws AnalysisException {
new StatisticProcDir(GlobalStateMgr.getCurrentState()).lookup("12345");
} |
public static ScanReport fromJson(String json) {
return JsonUtil.parse(json, ScanReportParser::fromJson);
} | @Test
public void missingFields() {
assertThatThrownBy(() -> ScanReportParser.fromJson("{}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing string: table-name");
assertThatThrownBy(() -> ScanReportParser.fromJson("{\"table-name\":\"roundTripTableName\"}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing long: snapshot-id");
assertThatThrownBy(
() ->
ScanReportParser.fromJson(
"{\"table-name\":\"roundTripTableName\",\"snapshot-id\":23,\"filter\":true}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing int: schema-id");
assertThatThrownBy(
() ->
ScanReportParser.fromJson(
"{\"table-name\":\"roundTripTableName\",\"snapshot-id\":23,\"filter\":true,"
+ "\"schema-id\" : 4,\"projected-field-ids\" : [ 1, 2, 3 ],\"projected-field-names\" : [ \"c1\", \"c2\", \"c3\" ]}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Cannot parse missing field: metrics");
} |
public static List<TypedExpression> coerceCorrectConstructorArguments(
final Class<?> type,
List<TypedExpression> arguments,
List<Integer> emptyCollectionArgumentsIndexes) {
Objects.requireNonNull(type, "Type parameter cannot be null as the method searches constructors from that class!");
Objects.requireNonNull(arguments, "Arguments parameter cannot be null! Use an empty list instance if needed instead.");
Objects.requireNonNull(emptyCollectionArgumentsIndexes, "EmptyListArgumentIndexes parameter cannot be null! Use an empty list instance if needed instead.");
if (emptyCollectionArgumentsIndexes.size() > arguments.size()) {
throw new IllegalArgumentException("There cannot be more empty collection arguments than all arguments! emptyCollectionArgumentsIndexes parameter has more items than arguments parameter. "
+ "(" + emptyCollectionArgumentsIndexes.size() + " > " + arguments.size() + ")");
}
// Rather work only with the argumentsType and when a method is resolved, flip the arguments list based on it.
final List<TypedExpression> coercedArgumentsTypesList = new ArrayList<>(arguments);
Constructor<?> constructor = resolveConstructor(type, coercedArgumentsTypesList);
if (constructor != null) {
return coercedArgumentsTypesList;
} else {
// This needs to go through all possible combinations.
final int indexesListSize = emptyCollectionArgumentsIndexes.size();
for (int numberOfProcessedIndexes = 0; numberOfProcessedIndexes < indexesListSize; numberOfProcessedIndexes++) {
for (int indexOfEmptyListIndex = numberOfProcessedIndexes; indexOfEmptyListIndex < indexesListSize; indexOfEmptyListIndex++) {
switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(indexOfEmptyListIndex));
constructor = resolveConstructor(type, coercedArgumentsTypesList);
if (constructor != null) {
return coercedArgumentsTypesList;
}
switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(indexOfEmptyListIndex));
}
switchCollectionClassInArgumentsByIndex(coercedArgumentsTypesList, emptyCollectionArgumentsIndexes.get(numberOfProcessedIndexes));
}
// No constructor found, return the original arguments.
return arguments;
}
} | @Test
public void coerceCorrectConstructorArgumentsEmptyCollectionIndexesBiggerThanArguments() {
Assertions.assertThatThrownBy(
() -> MethodResolutionUtils.coerceCorrectConstructorArguments(
Person.class,
Collections.emptyList(),
List.of(1, 2, 4)))
.isInstanceOf(IllegalArgumentException.class);
} |
private PaginatedList<ViewDTO> searchPaginated(SearchUser searchUser,
SearchQuery query,
Predicate<ViewDTO> filter,
SortOrder order,
String sortField,
Bson grandTotalQuery,
int page,
int perPage) {
final PaginatedList<ViewDTO> viewsList = findPaginatedWithQueryFilterAndSortWithGrandTotal(searchUser, query, filter,
Sorts.orderBy(order.toBsonSort(sortField), order.toBsonSort(ViewDTO.SECONDARY_SORT)),
grandTotalQuery, page, perPage);
return viewsList.withList(viewsList.delegate().stream()
.map(this::requirementsForView)
.toList());
} | @Test
public void searchPaginated() {
final ImmutableMap<String, SearchQueryField> searchFieldMapping = ImmutableMap.<String, SearchQueryField>builder()
.put("id", SearchQueryField.create(ViewDTO.FIELD_ID))
.put("title", SearchQueryField.create(ViewDTO.FIELD_TITLE))
.put("summary", SearchQueryField.create(ViewDTO.FIELD_DESCRIPTION))
.build();
dbService.save(ViewDTO.builder().title("View A").searchId("abc123").state(Collections.emptyMap()).owner("franz").build());
dbService.save(ViewDTO.builder().title("View B").searchId("abc123").state(Collections.emptyMap()).owner("franz").build());
dbService.save(ViewDTO.builder().title("View C").searchId("abc123").state(Collections.emptyMap()).owner("franz").build());
dbService.save(ViewDTO.builder().title("View D").searchId("abc123").state(Collections.emptyMap()).owner("franz").build());
dbService.save(ViewDTO.builder().title("View E").searchId("abc123").state(Collections.emptyMap()).owner("franz").build());
final SearchQueryParser queryParser = new SearchQueryParser(ViewDTO.FIELD_TITLE, searchFieldMapping);
final PaginatedList<ViewDTO> result1 = dbService.searchPaginated(
searchUser,
queryParser.parse("A B D"),
view -> true, SortOrder.DESCENDING,
"title",
1,
5
);
assertThat(result1)
.hasSize(3)
.extracting("title")
.containsExactly("View D", "View B", "View A");
assertThat(result1.grandTotal()).hasValue(5L);
final PaginatedList<ViewDTO> result2 = dbService.searchPaginated(
searchUser,
queryParser.parse("A B D"),
view -> view.title().contains("B") || view.title().contains("D"), SortOrder.DESCENDING,
"title",
1,
5
);
assertThat(result2)
.hasSize(2)
.extracting("title")
.containsExactly("View D", "View B");
assertThat(result2.grandTotal()).hasValue(5L);
} |
@Override
public T next() {
return buffer.poll();
} | @Test
public void testEmptyCollectorReturnsNull() {
BufferingCollector<Integer> collector = new BufferingCollector<>();
Assert.assertNull("Empty collector did not return null", collector.next());
} |
public String get(MetaDataKey key) {
return metadata.get(key.getName());
} | @Test
public void testAutoBuild() throws Exception {
try (MockedStatic<AmazonInfoUtils> mockUtils = mockStatic(AmazonInfoUtils.class)) {
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt())
).thenReturn(null);
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(any(AmazonInfo.MetaDataKey.class), any(URL.class), anyInt(), anyInt())
).thenReturn(null);
URL macsUrl = AmazonInfo.MetaDataKey.macs.getURL(null, null);
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.macs), eq(macsUrl), anyInt(), anyInt())
).thenReturn("0d:c2:9a:3c:18:2b\n4c:31:99:7e:26:d6");
URL firstMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "0d:c2:9a:3c:18:2b");
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(firstMacPublicIPv4sUrl), anyInt(), anyInt())
).thenReturn(null);
URL secondMacPublicIPv4sUrl = AmazonInfo.MetaDataKey.publicIpv4s.getURL(null, "4c:31:99:7e:26:d6");
mockUtils.when(
() -> AmazonInfoUtils.readEc2MetadataUrl(eq(AmazonInfo.MetaDataKey.publicIpv4s), eq(secondMacPublicIPv4sUrl), anyInt(), anyInt())
).thenReturn("10.0.0.1");
AmazonInfoConfig config = mock(AmazonInfoConfig.class);
when(config.getNamespace()).thenReturn("test_namespace");
when(config.getConnectTimeout()).thenReturn(10);
when(config.getNumRetries()).thenReturn(1);
when(config.getReadTimeout()).thenReturn(10);
when(config.shouldLogAmazonMetadataErrors()).thenReturn(false);
when(config.shouldValidateInstanceId()).thenReturn(false);
when(config.shouldFailFastOnFirstLoad()).thenReturn(false);
AmazonInfo info = AmazonInfo.Builder.newBuilder().withAmazonInfoConfig(config).autoBuild("test_namespace");
assertEquals("10.0.0.1", info.get(AmazonInfo.MetaDataKey.publicIpv4s));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.