focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<HttpCookie> decodeCookies(List<String> cookieStrs)
{
List<HttpCookie> cookies = new ArrayList<>();
if (cookieStrs == null)
{
return cookies;
}
for (String cookieStr : cookieStrs)
{
if (cookieStr == null)
{
continue;
}
StringTokenizer to... | @Test
public void testInvalidCookieFromClient()
{
cookieA.setComment("nothing important");
List<String> encodeStrs = Collections.singletonList("$Domain=.linkedin.com; $Port=80; $Path=/; $Version=0;");
List<HttpCookie> cookieList = CookieUtil.decodeCookies(encodeStrs);
Assert.assertEquals(0, cookie... |
@Override
public void validatePostList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得岗位信息
List<PostDO> posts = postMapper.selectBatchIds(ids);
Map<Long, PostDO> postMap = convertMap(posts, PostDO::getId);
// 校验
ids.forEach(id ... | @Test
public void testValidatePostList_success() {
// mock 数据
PostDO postDO = randomPostDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
postMapper.insert(postDO);
// 准备参数
List<Long> ids = singletonList(postDO.getId());
// 调用,无需断言
postService.validatePost... |
public static <FnT extends DoFn<?, ?>> DoFnSignature signatureForDoFn(FnT fn) {
return getSignature(fn.getClass());
} | @Test
public void testGenericStatefulDoFn() throws Exception {
class DoFnForTestGenericStatefulDoFn<T> extends DoFn<KV<String, T>, Long> {
// Note that in order to have a coder for T it will require initialization in the constructor,
// but that isn't important for this test
@StateId("foo")
... |
@Override
public Map<V, GeoPosition> pos(V... members) {
return get(posAsync(members));
} | @Test
public void testPos() {
RGeo<String> geo = redisson.getGeo("test");
geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"), new GeoEntry(15.087269, 37.502669, "Catania"));
Map<String, GeoPosition> expected = new LinkedHashMap<>();
expected.put("Palermo", new GeoPosition... |
public static byte[] short2bytes(short num) {
byte[] result = new byte[2];
result[0] = (byte) (num >>> 8); //取次低8位放到0下标
result[1] = (byte) (num); //取最低8位放到1下标
return result;
} | @Test
public void short2bytes() {
short i = 0;
byte[] bs = CodecUtils.short2bytes(i);
Assert.assertArrayEquals(bs, new byte[] { 0, 0 });
i = 1000;
bs = CodecUtils.short2bytes(i);
Assert.assertArrayEquals(bs, new byte[] { 3, -24 });
short s = 258; // =1*256+2... |
public static <T> AsSingleton<T> asSingleton() {
return new AsSingleton<>();
} | @Test
@Category(ValidatesRunner.class)
public void testSingletonSideInput() {
final PCollectionView<Integer> view =
pipeline.apply("Create47", Create.of(47)).apply(View.asSingleton());
PCollection<Integer> output =
pipeline
.apply("Create123", Create.of(1, 2, 3))
.a... |
public static String toOSStyleKey(String key) {
key = key.toUpperCase().replaceAll(DOT_REGEX, UNDERLINE_SEPARATOR);
if (!key.startsWith("DUBBO_")) {
key = "DUBBO_" + key;
}
return key;
} | @Test
void testToOSStyleKey() {
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo_tag1"));
assertEquals("DUBBO_TAG1", StringUtils.toOSStyleKey("dubbo.tag1"));
assertEquals("DUBBO_TAG1_TAG11", StringUtils.toOSStyleKey("dubbo.tag1.tag11"));
assertEquals("DUBBO_TAG1", StringUti... |
@Override
public boolean processArgument(final ShenyuRequest shenyuRequest, final Annotation annotation, final Object arg) {
String name = ANNOTATION.cast(annotation).value();
RequestTemplate requestTemplate = shenyuRequest.getRequestTemplate();
checkState(emptyToNull(name) != null, "Request... | @Test
public void processArgumentEmptyTest() {
final RequestHeader header = spy(RequestHeader.class);
when(header.value()).thenReturn("");
assertThrows(IllegalStateException.class, () -> processor.processArgument(request, header, "value1"));
} |
@Override
public void check( List<CheckResultInterface> remarks, TransMeta transMeta,
StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output,
RowMetaInterface info, VariableSpace space, Repository repository,
IMetaStore metaStore ) {
... | @Test
public void testCheckOptionsFail() {
List<CheckResultInterface> remarks = new ArrayList<>();
MQTTProducerMeta meta = new MQTTProducerMeta();
meta.mqttServer = "theserver:1883";
meta.clientId = "client100";
meta.topic = "newtopic";
meta.qos = "2";
meta.messageField = "Messages";
m... |
public static double[] toDoubleArray(String name, Object value) {
try {
if (value instanceof BigDecimal[]) {
return Arrays.stream((BigDecimal[]) value).mapToDouble(BigDecimal::doubleValue).toArray();
} else if (value instanceof double[]) {
return (double[]) value;
} else if (value ... | @Test
public void testDecimalArrayToDoubleArray() {
Object val =
new BigDecimal[] {new BigDecimal("1.2"), new BigDecimal("3.4"), new BigDecimal("5.6")};
double[] actual = ParamHelper.toDoubleArray("foo", val);
assertEquals(1.2, actual[0], 0.00000000);
assertEquals(3.4, actual[1], 0.00000000);
... |
@Override
public int getOrder() {
return PluginEnum.RATE_LIMITER.getCode();
} | @Test
public void getOrderTest() {
assertEquals(PluginEnum.RATE_LIMITER.getCode(), rateLimiterPlugin.getOrder());
} |
public static <T> byte[] write(Writer<T> writer, T value) {
byte[] result = new byte[writer.sizeInBytes(value)];
WriteBuffer b = WriteBuffer.wrap(result);
try {
writer.write(value, b);
} catch (RuntimeException e) {
int lengthWritten = result.length;
for (int i = 0; i < result.length; ... | @Test void doesntStackOverflowOnToBufferWriterBug_Overflow() {
// pretend there was a bug calculating size, ex it calculated incorrectly as to small
class FooWriter implements WriteBuffer.Writer {
@Override public int sizeInBytes(Object value) {
return 2;
}
@Override public void write... |
@Override
public NacosUser authenticate(String username, String rawPassword) throws AccessException {
if (StringUtils.isBlank(username) || StringUtils.isBlank(rawPassword)) {
throw new AccessException("user not found!");
}
NacosUserDetails nacosUserDetails = (NacosUserDetails) us... | @Test
void testAuthenticate5() {
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authenticate("");
});
} |
public static Object[] getMethodArguments(SofaRequest request) {
return request.getMethodArgs();
} | @Test
public void testGetMethodArguments() {
SofaRequest request = new SofaRequest();
request.setMethodArgs(new Object[]{"Sentinel", 2020});
Object[] arguments = SofaRpcUtils.getMethodArguments(request);
assertEquals(arguments.length, 2);
assertEquals("Sentinel", arguments[0]... |
public static synchronized Map<Pair<String, String>, String> getChanged() {
return CpeEcosystemCache.changed;
} | @Test
public void testGetChanged() {
Pair<String, String> key = new Pair<>("apache", "zookeeper");
Map<Pair<String, String>, String> map = new HashMap<>();
map.put(key, "java");
CpeEcosystemCache.setCache(map);
Map<Pair<String, String>, String> result = CpeEcosystemCache.get... |
@VisibleForTesting
static FlinkSecurityManager fromConfiguration(Configuration configuration) {
final ClusterOptions.UserSystemExitMode userSystemExitMode =
configuration.get(ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT);
boolean haltOnSystemExit = configuration.get(ClusterOptions.HALT... | @Test
void testHaltConfiguration() {
// Halt as forceful shutdown replacing graceful system exit
Configuration configuration = new Configuration();
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, true);
FlinkSecurityManager flinkSecurityManager =
FlinkSecurityMa... |
@Override
public void swap(int i, int j) {
final int segmentNumberI = i / this.indexEntriesPerSegment;
final int segmentOffsetI = (i % this.indexEntriesPerSegment) * this.indexEntrySize;
final int segmentNumberJ = j / this.indexEntriesPerSegment;
final int segmentOffsetJ = (j % this... | @Test
void testSwap() throws Exception {
final int numSegments = MEMORY_SIZE / MEMORY_PAGE_SIZE;
final List<MemorySegment> memory =
this.memoryManager.allocatePages(new DummyInvokable(), numSegments);
NormalizedKeySorter<Tuple2<Integer, String>> sorter = newSortBuffer(memory... |
public void tryLock() {
try {
if (!lock.tryLock()) {
failAlreadyInProgress(null);
}
} catch (OverlappingFileLockException e) {
failAlreadyInProgress(e);
}
} | @Test
public void tryLock() {
Path lockFilePath = worDir.toPath().resolve(DirectoryLock.LOCK_FILE_NAME);
lock.tryLock();
assertThat(Files.exists(lockFilePath)).isTrue();
assertThat(Files.isRegularFile(lockFilePath)).isTrue();
lock.stop();
assertThat(Files.exists(lockFilePath)).isTrue();
} |
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
String urlPath = "apps/" + appName + '/' + id;
Response response = null;
try {
WebTarget webResource = jerseyClient.target(serviceUrl)
... | @Test
public void testHeartbeatReplicationWithNoResponseBody() throws Exception {
serverMockClient.when(
request()
.withMethod("PUT")
.withHeader(header(PeerEurekaNode.HEADER_REPLICATION, "true"))
.withPath("/eureka/v2/a... |
@Override
public Path find() throws BackgroundException {
final String directory;
try {
directory = session.getClient().printWorkingDirectory();
if(null == directory) {
throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyStri... | @Test
public void testDefaultPath() throws Exception {
assertEquals("/", new FTPWorkdirService(session).find().getAbsolute());
} |
@Override
public PageData<Asset> findAssetsByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, PageLink pageLink) {
return DaoUtil.toPageData(assetRepository
.findByTenantIdAndCustomerIdAndType(
tenantId,
customerId,
... | @Test
public void testFindAssetsByTenantIdAndCustomerIdAndType() {
String type = "TYPE_2";
String testLabel = "test_label";
assets.add(saveAsset(Uuids.timeBased(), tenantId2, customerId2, "TEST_ASSET", type, testLabel));
List<Asset> foundedAssetsByType = assetDao
.fi... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseLongAsInt64() {
Long value = Long.MAX_VALUE;
SchemaAndValue schemaAndValue = Values.parseString(
String.valueOf(value)
);
assertEquals(Schema.INT64_SCHEMA, schemaAndValue.schema());
assertInstanceOf(Long.class, schemaAndValue.value());... |
public static int fromLogical(Schema schema, java.util.Date value) {
if (!(LOGICAL_NAME.equals(schema.name())))
throw new DataException("Requested conversion of Date object but the schema does not match.");
Calendar calendar = Calendar.getInstance(UTC);
calendar.setTime(value);
... | @Test
public void testFromLogical() {
assertEquals(0, Date.fromLogical(Date.SCHEMA, EPOCH.getTime()));
assertEquals(10000, Date.fromLogical(Date.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_DAYS.getTime()));
} |
@Override
public Set<Subnet> subnets() {
return osNetworkStore.subnets();
} | @Test
public void testGetSubnets() {
createBasicNetworks();
assertEquals("Number of subnet did not match", 1, target.subnets().size());
} |
@Override
String getProperty(String key) {
String checkedKey = checkPropertyName(key);
if (checkedKey == null) {
final String upperCaseKey = key.toUpperCase();
if (!upperCaseKey.equals(key)) {
checkedKey = checkPropertyName(upperCaseKey);
}
... | @Test
void testGetEnvForUpperCaseKeyWithHyphenAndDot() {
assertEquals("value4", systemEnvPropertySource.getProperty("TEST_CASE.4"));
} |
static MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) {
LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName);
MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName);
if (result == null) {
... | @Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", MetricRegistry.class)).thenReturn(metricRegistry);
MetricRegistry result = MetricsComponent.getOrCreateMetricRegistry(camelRegistry, "name");
assertThat(result, is(metricReg... |
@Description("Returns the bounding rectangular polygon of a Geometry")
@ScalarFunction("ST_Envelope")
@SqlType(GEOMETRY_TYPE_NAME)
public static Slice stEnvelope(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
Envelope envelope = deserializeEnvelope(input);
if (envelope.isEmpty()) {
... | @Test
public void testSTEnvelope()
{
assertFunction("ST_AsText(ST_Envelope(ST_GeometryFromText('MULTIPOINT (1 2, 2 4, 3 6, 4 8)')))", VARCHAR, "POLYGON ((1 2, 1 8, 4 8, 4 2, 1 2))");
assertFunction("ST_AsText(ST_Envelope(ST_GeometryFromText('LINESTRING EMPTY')))", VARCHAR, "POLYGON EMPTY");
... |
public final void registerGlobal(final Serializer serializer) {
registerGlobal(serializer, false);
} | @Test(expected = IllegalStateException.class)
public void testGlobalRegister_doubleRegistration() {
abstractSerializationService.registerGlobal(new StringBufferSerializer(true));
abstractSerializationService.registerGlobal(new StringBufferSerializer(true));
} |
@Override
public void shutdown() throws NacosException {
NAMING_LOGGER.warn("[NamingHttpClientManager] Start destroying NacosRestTemplate");
try {
HttpClientBeanHolder.shutdownNacosSyncRest(HTTP_CLIENT_FACTORY.getClass().getName());
} catch (Exception ex) {
NAMING_LOG... | @Test
void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException {
//given
NamingHttpClientManager instance = NamingHttpClientManager.getInstance();
HttpClientRequest mockHttpClientRequest = Mockito.mock(HttpClientRequest.class);
Fie... |
@Override
public void handle(SchedulerEvent event) {
switch (event.getType()) {
case NODE_ADDED:
if (!(event instanceof NodeAddedSchedulerEvent)) {
throw new RuntimeException("Unexpected event type: " + event);
}
NodeAddedSchedulerEvent nodeAddedEvent = (NodeAddedSchedulerEvent) even... | @Test(timeout = 60000)
public void testNodeRemovalDuringAllocate() throws Exception {
MockNM nm1 = new MockNM("h1:1234", 4096, rm.getResourceTrackerService());
MockNM nm2 = new MockNM("h2:1234", 4096, rm.getResourceTrackerService());
nm1.registerNode();
nm2.registerNode();
nm1.nodeHeartbeat(oppCo... |
@Override
public Map<K, V> getAll(Set<K> keys) {
return cache.getAll(keys);
} | @Test
public void testGetAll() {
cache.put(23, "value-23");
cache.put(42, "value-42");
Map<Integer, String> expectedResult = new HashMap<>();
expectedResult.put(23, "value-23");
expectedResult.put(42, "value-42");
Map<Integer, String> result = adapter.getAll(expecte... |
@Override
public TreeNode<T> next() throws NoSuchElementException {
if (pathStack.isEmpty()) {
throw new NoSuchElementException();
}
var next = pathStack.pop();
pushPathToNextSmallest(next.getRight());
return next;
} | @Test
void nextOverEntirePopulatedTree() {
var iter = new BstIterator<>(nonEmptyRoot);
assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1.");
assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3.");
assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third ... |
public static String queryToFetchAllFieldsOf(final AbstractDescribedSObjectBase object) {
if (object == null) {
return null;
}
final SObjectDescription description = object.description();
final List<SObjectField> fields = description.getFields();
return fields.strea... | @Test
public void shouldGenerateQueryForAllFields() {
assertThat(QueryHelper.queryToFetchAllFieldsOf(new Account()))
.isEqualTo("SELECT Id, IsDeleted, MasterRecordId, Name, Type, ParentId, BillingStreet, BillingCity, "
+ "BillingState, BillingPostalCode, BillingCou... |
<K, V> ShareInFlightBatch<K, V> fetchRecords(final Deserializers<K, V> deserializers,
final int maxRecords,
final boolean checkCrcs) {
// Creating an empty ShareInFlightBatch
ShareInFlightBatch<K, V> inFlig... | @Test
public void testAcquireOddRecords() {
long firstMessageId = 5;
int startingOffset = 0;
int numRecords = 10; // Records for 0-9
// Acquiring all odd Records
List<ShareFetchResponseData.AcquiredRecords> acquiredRecords = new ArrayList<>();
for (long i = 1;... |
@Override
public boolean isIn(String ipAddress) {
if (ipAddress == null || addressList == null) {
return false;
}
return addressList.includes(ipAddress);
} | @Test
public void testWithEmptyList() throws IOException {
String[] ips = {};
createFileWithEntries ("ips.txt", ips);
IPList ipl = new FileBasedIPList("ips.txt");
assertFalse("110.113.221.222 is in the list",
ipl.isIn("110.113.221.222"));
} |
@Override
public Mono<GetUnversionedProfileResponse> getUnversionedProfile(final GetUnversionedProfileRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIden... | @Test
void getUnversionedProfileTargetAccountNotFound() {
when(accountsManager.getByServiceIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.empty()));
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdent... |
@Override
@SuppressWarnings("unchecked")
public <K, V> List<Map<K, V>> toMaps(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 n... | @Test
void to_maps_cant_convert_table_with_duplicate_keys() {
DataTable table = parse("",
"| 1 | 1 | 1 |",
"| 4 | 5 | 6 |",
"| 7 | 8 | 9 |");
CucumberDataTableException exception = assertThrows(
CucumberDataTableException.class,
() -> conv... |
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition td = new TypeDefinition(type.toString());
return td;
} | @Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, vField, builder);
buildAndAssertTypeDefinition(processingEnv, zField, builder);
buildAndAssertTypeDefinition(processingEnv, cField, builder);
buildAndAssertTypeDefinition(processingEnv, sField, builder);
bui... |
public static boolean isPubKeyCompressed(byte[] encoded) {
if (encoded.length == 33 && (encoded[0] == 0x02 || encoded[0] == 0x03))
return true;
else if (encoded.length == 65 && encoded[0] == 0x04)
return false;
else
throw new IllegalArgumentException(ByteUtils... | @Test(expected = IllegalArgumentException.class)
public void isPubKeyCompressed_illegalSign() {
ECKey.isPubKeyCompressed(ByteUtils.parseHex("0438746c59d46d5408bf8b1d0af5740fe1a6e1703fcb56b2953f0b965c740d256f"));
} |
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) {
this.fieldLengths = fieldLengths;
return this;
} | @Test
public void shouldConfigureLineSeparator() {
UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat()
.setFieldLengths(new int[] { 1, 2, 3 })
.setLineSeparator("ls");
assertEquals("ls", dataFormat.getLineSeparator());
assertEquals("ls", data... |
@Override
@SuppressFBWarnings(value = "EI_EXPOSE_REP")
public KsqlConfig getKsqlConfig() {
return ksqlConfig;
} | @Test
public void shouldIgnoreRecordsWithUnparseableKey() {
// Given:
addPollResult(
"badkey".getBytes(StandardCharsets.UTF_8),
"whocares".getBytes(StandardCharsets.UTF_8));
addPollResult(KafkaConfigStore.CONFIG_MSG_KEY, serializer.serialize("", savedProperties));
expectRead(consumerBe... |
public PathSpecSet copyAndRemovePrefix(PathSpec prefix)
{
if (isAllInclusive() || isEmpty())
{
// allInclusive or empty projections stay the same
return this;
}
// if we contain the exact prefix or any sub prefix, it should be an all inclusive set
PathSpec partialPrefix = prefix;
... | @Test(dataProvider = "copyAndRemovePrefixProvider")
public void testCopyAndRemovePrefix(PathSpecSet input, PathSpec prefix, PathSpecSet expected) {
Assert.assertEquals(input.copyAndRemovePrefix(prefix), expected);
} |
@Operation(summary = "batchMoveByCodes", description = "MOVE_PROCESS_DEFINITION_NOTES")
@Parameters({
@Parameter(name = "codes", description = "PROCESS_DEFINITION_CODES", required = true, schema = @Schema(implementation = String.class, example = "3,4")),
@Parameter(name = "targetProjectCode"... | @Test
public void testBatchMoveProcessDefinition() {
long projectCode = 1L;
long targetProjectCode = 2L;
String id = "1";
Map<String, Object> result = new HashMap<>();
putMsg(result, Status.SUCCESS);
Mockito.when(processDefinitionService.batchMoveProcessDefinition(u... |
public void logFrameIn(
final DirectBuffer buffer, final int offset, final int frameLength, final InetSocketAddress dstAddress)
{
final int length = frameLength + socketAddressLength(dstAddress);
final int captureLength = captureLength(length);
final int encodedLength = encodedLength... | @Test
void logFrameIn()
{
final int recordOffset = align(100, ALIGNMENT);
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset);
final int length = 10_000;
final int captureLength = MAX_CAPTURE_LENGTH;
final int srcOffset = 4;
buffer.setMemory(srcOffset... |
public static SlotManagerConfiguration fromConfiguration(
Configuration configuration, WorkerResourceSpec defaultWorkerResourceSpec)
throws ConfigurationException {
final Time rpcTimeout =
Time.fromDuration(configuration.get(RpcOptions.ASK_TIMEOUT_DURATION));
fi... | @Test
void testComputeMinMaxSlotNumIsInvalid() {
final Configuration configuration = new Configuration();
final int minSlotNum = 10;
final int maxSlotNum = 11;
final int numSlots = 3;
configuration.set(ResourceManagerOptions.MIN_SLOT_NUM, minSlotNum);
configuration.se... |
@Override
protected String getFolderSuffix() {
return FOLDER_SUFFIX;
} | @Test
public void testGetFolderSuffix() {
Assert.assertEquals("/", mCOSUnderFileSystem.getFolderSuffix());
} |
public static RunRequest createInternalWorkflowRunRequest(
WorkflowSummary workflowSummary,
StepRuntimeSummary runtimeSummary,
List<Tag> tags,
Map<String, ParamDefinition> runParams,
String dedupKey) {
UpstreamInitiator initiator =
UpstreamInitiator.withType(Initiator.Type.val... | @Test
public void testErrorForTooDeepWorkflow() {
WorkflowSummary summary = new WorkflowSummary();
summary.setWorkflowId("test-workflow");
summary.setWorkflowInstanceId(123);
summary.setWorkflowRunId(2);
SubworkflowInitiator initiator = new SubworkflowInitiator();
UpstreamInitiator.Info info =... |
public ProviderBuilder ioThreads(Integer ioThreads) {
this.iothreads = ioThreads;
return getThis();
} | @Test
void ioThreads() {
ProviderBuilder builder = ProviderBuilder.newBuilder();
builder.ioThreads(25);
Assertions.assertEquals(25, builder.build().getIothreads());
} |
public int replicaId() {
return data.replicaId();
} | @Test
public void testForConsumerRequiresVersion3() {
OffsetsForLeaderEpochRequest.Builder builder = OffsetsForLeaderEpochRequest.Builder.forConsumer(new OffsetForLeaderTopicCollection());
for (short version = 0; version < 3; version++) {
final short v = version;
assertThrows... |
@Override
@SuppressWarnings("nullness")
public List<Map<String, Object>> readTable(String tableName) {
LOG.info("Reading all rows from {}.{}", databaseName, tableName);
List<Map<String, Object>> result = runSQLQuery(String.format("SELECT * FROM %s", tableName));
LOG.info("Successfully loaded rows from {... | @Test
public void testReadTableShouldThrowErrorWhenDriverFailsToEstablishConnection()
throws SQLException {
when(container.getHost()).thenReturn(HOST);
when(container.getMappedPort(JDBC_PORT)).thenReturn(MAPPED_PORT);
doThrow(SQLException.class).when(driver).getConnection(any(), any(), any());
... |
public static SegmentAssignmentStrategy getSegmentAssignmentStrategy(HelixManager helixManager,
TableConfig tableConfig, String assignmentType, InstancePartitions instancePartitions) {
String assignmentStrategy = null;
TableType currentTableType = tableConfig.getTableType();
// TODO: Handle segment a... | @Test
public void testBalancedNumSegmentAssignmentStrategyforOfflineTables() {
TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).build();
InstancePartitions instancePartitions = new InstancePartitions(INSTANCE_PARTITIONS_NAME);
instancePartitions.setInstance... |
public static <T> Bounded<T> from(BoundedSource<T> source) {
return new Bounded<>(null, source);
} | @Test
public void succeedsWhenCustomBoundedSourceIsSerializable() {
Read.from(new SerializableBoundedSource());
} |
@VisibleForTesting
HiveClientPool clientPool() {
return clientPoolCache.get(key, k -> new HiveClientPool(clientPoolSize, conf));
} | @Test
public void testHmsCatalog() {
Map<String, String> properties =
ImmutableMap.of(
String.valueOf(EVICTION_INTERVAL),
String.valueOf(Integer.MAX_VALUE),
ICEBERG_CATALOG_TYPE,
ICEBERG_CATALOG_TYPE_HIVE);
Configuration conf1 = new Configuration();
... |
HashPMap<K, V> underlying() {
return underlying;
} | @Test
public void testUnderlying() {
assertSame(SINGLETON_MAP, new PCollectionsImmutableMap<>(SINGLETON_MAP).underlying());
} |
@Override
public void setApplicationState(OrchestratorContext context, ApplicationInstanceId applicationId,
ClusterControllerNodeState wantedState) throws ApplicationStateChangeDeniedException {
try {
ClusterControllerClientTimeouts timeouts = context.getClust... | @Test
public void verifySetApplicationState() {
wire.expect((url, body) -> {
assertEquals("http://host1:19050/cluster/v2/cc?timeout=299.6",
url.asURI().toString());
assertEquals("{\"state\":{\"user\":{\"reason\":\"Orchestra... |
public void clearStatus(String service) {
healthService.clearStatus(service);
} | @Test
void clearStatus() {
String service = "serv1";
manager.setStatus(service, ServingStatus.SERVING);
ServingStatus stored = manager.getHealthService()
.check(HealthCheckRequest.newBuilder().setService(service).build())
.getStatus();
Assertions.asser... |
public int getUnknown_002c() {
return unknown_002c;
} | @Test
public void testGetUnknown_002() {
assertEquals(TestParameters.VP_ITSP_UNKNOWN_002C, chmItspHeader.getUnknown_002c());
} |
public void setMenuItemEnabledState( List<UIRepositoryObject> selectedRepoObjects ) {
try {
boolean result = false;
if ( selectedRepoObjects.size() == 1 && selectedRepoObjects.get( 0 ) instanceof UIRepositoryDirectory ) {
lockFileMenuItem.setDisabled( true );
deleteFileMenuItem.setDisabl... | @Test
public void testBlockLock() throws Exception {
RepositoryLockController repositoryLockController = new RepositoryLockController();
List<UIRepositoryObject> selectedRepoObjects = new ArrayList<>();
UIEETransformation lockObject = Mockito.mock( UIEETransformation.class );
selectedRepoObjects.add( ... |
@VisibleForTesting
List<String> getHighlights()
{
final String configNpcs = config.getNpcToHighlight();
if (configNpcs.isEmpty())
{
return Collections.emptyList();
}
return Text.fromCSV(configNpcs);
} | @Test
public void getHighlights()
{
when(npcIndicatorsConfig.getNpcToHighlight()).thenReturn("goblin, , zulrah , *wyvern, ,");
final List<String> highlightedNpcs = npcIndicatorsPlugin.getHighlights();
assertEquals("Length of parsed NPCs is incorrect", 3, highlightedNpcs.size());
final Iterator<String> iter... |
@SuppressWarnings("unchecked")
@Override
public void configure(final Map<String, ?> configs, final boolean isKey) {
//check to see if the window size config is set and the window size is already set from the constructor
final Long configWindowSize;
if (configs.get(StreamsConfig.WINDOW_SI... | @Test
public void shouldThrowErrorIfWindowedInnerClassDeserialiserIsNotSet() {
props.put(StreamsConfig.WINDOW_SIZE_MS_CONFIG, "500");
final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>();
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(p... |
@Override
public void doLimitForModifyRequest(ModifyRequest modifyRequest) throws SQLException {
if (null == modifyRequest || !enabledLimit) {
return;
}
doLimit(modifyRequest.getSql());
} | @Test
void testDoLimitForModifyRequestForDml() throws SQLException {
ModifyRequest insert = new ModifyRequest("insert into test(id,name) values(1,'test')");
ModifyRequest update = new ModifyRequest("update test set name='test' where id=1");
ModifyRequest delete = new ModifyRequest("delete fr... |
public static void main(String[] args) {
// get service
var userService = new UserService();
// use create service to add users
for (var user : generateSampleUsers()) {
var id = userService.createUser(user);
LOGGER.info("Add user" + user + "at" + id + ".");
}
// use list service to g... | @Test
void shouldExecuteMetaMappingWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
private static void shutdown() {
if (!ALREADY_SHUTDOWN.compareAndSet(false, true)) {
return;
}
LOGGER.warn("[HttpClientBeanHolder] Start destroying common HttpClient");
try {
shutdown(DefaultHttpClientFactory.class.getName());
} catch (Exception e... | @Test
void shutdown() throws Exception {
HttpClientBeanHolder.getNacosRestTemplate((Logger) null);
HttpClientBeanHolder.getNacosAsyncRestTemplate((Logger) null);
assertEquals(1, restMap.size());
assertEquals(1, restAsyncMap.size());
HttpClientBeanHolder.shutdown(DefaultHttpCl... |
@Operation(summary = "Request a new mijn digid session based on an app session")
@PostMapping(value = "/request_session", consumes = "application/json")
public ResponseEntity<?> requestSession(@RequestBody @Valid MijnDigidSessionRequest request){
if(request == null || request.getAppSessionId() == null) ... | @Test
void validateValidRequest() {
MijnDigidSessionRequest request = new MijnDigidSessionRequest();
String appSessionId = "id";
request.setAppSessionId(appSessionId);
MijnDigidSession session = new MijnDigidSession(1L);
when(mijnDigiDSessionService.createSession(appSessionId... |
public Map<String, String> getSessionVariables() {
return sessionVariables;
} | @Test
public void testGetSessionVariables() {
UserProperty userProperty = new UserProperty();
Map<String, String> sessionVariables = userProperty.getSessionVariables();
Assert.assertEquals(0, sessionVariables.size());
} |
String name(String name) {
return sanitize(name, NAME_RESERVED);
} | @Test
public void replacesNonASCIICharacters() throws Exception {
assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen");
} |
public void validatePassword(final String password) {
if (!this.password.equals(password)) {
throw new PasswordNotMatchedException();
}
} | @Test
void 패스워드가_다른_경우에_예외를_발생한다() {
// given
Member member = 일반_유저_생성();
String givenPassword = "wrongPassword";
// when & then
assertThatThrownBy(() -> member.validatePassword(givenPassword))
.isInstanceOf(PasswordNotMatchedException.class);
} |
public IThrowableRenderer<ILoggingEvent> getThrowableRenderer() {
return throwableRenderer;
} | @Test
public void testAppendThrowable() throws Exception {
StringBuilder buf = new StringBuilder();
DummyThrowableProxy tp = new DummyThrowableProxy();
tp.setClassName("test1");
tp.setMessage("msg1");
StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1);
StackTraceElement s... |
@VisibleForTesting
static void validateFips(final KsqlConfig config, final KsqlRestConfig restConfig) {
if (config.getBoolean(ConfluentConfigs.ENABLE_FIPS_CONFIG)) {
final FipsValidator fipsValidator = ConfluentConfigs.buildFipsValidator();
// validate cipher suites and TLS version
validateCiph... | @Test
public void shouldFailOnInvalidSSLEndpointIdentificationAlgorithm() {
// Given:
final KsqlConfig config = configWith(ImmutableMap.of(
ConfluentConfigs.ENABLE_FIPS_CONFIG, true,
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_SSL.name
));
final KsqlRestConfig r... |
public static void delete(final File rootFile) throws IOException {
if (rootFile == null)
return;
Files.walkFileTree(rootFile.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException {
... | @SuppressWarnings("unchecked")
@Test
public void testRecursiveDeleteWithDeletedFile() throws IOException {
// Test recursive deletes, where the FileWalk is supplied with a deleted file path.
File rootDir = TestUtils.tempDirectory();
File subDir = TestUtils.tempDirectory(rootDir.toPath(),... |
Capabilities getCapabilitiesFromResponseBody(String responseBody) {
final CapabilitiesDTO capabilitiesDTO = FORCED_EXPOSE_GSON.fromJson(responseBody, CapabilitiesDTO.class);
return capabilitiesConverterV5.fromDTO(capabilitiesDTO);
} | @Test
public void shouldGetCapabilitiesFromResponseBody() {
String responseBody = "{" +
" \"supports_plugin_status_report\":\"true\"," +
" \"supports_cluster_status_report\":\"true\"," +
" \"supports_agent_status_report\":\"true\"" +
"... |
@Override
@Nullable
public IdentifiedDataSerializable create(int typeId) {
if (typeId >= 0 && typeId < len) {
Supplier<IdentifiedDataSerializable> factory = constructors[typeId];
return factory != null ? factory.get() : null;
}
return null;
} | @Test
public void testCreateWithoutVersion() {
Supplier<IdentifiedDataSerializable>[] constructorFunctions = new Supplier[1];
Supplier<IdentifiedDataSerializable> function = mock(Supplier.class);
constructorFunctions[0] = function;
ArrayDataSerializableFactory factory = new ArrayDat... |
public static Configuration adjustForLocalExecution(Configuration config) {
UNUSED_CONFIG_OPTIONS.forEach(
option -> warnAndRemoveOptionHasNoEffectIfSet(config, option));
setConfigOptionToPassedMaxIfNotSet(
config, TaskManagerOptions.CPU_CORES, LOCAL_EXECUTION_CPU_CORES)... | @Test
void testUnusedOptionsAreIgnoredForLocalExecution() {
Configuration configuration = new Configuration();
configuration.set(TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(2024));
configuration.set(TaskManagerOptions.TOTAL_FLINK_MEMORY, MemorySize.ofMebiBytes(2024));
... |
@Override
public void loadData(Priority priority, DataCallback<? super T> callback) {
this.callback = callback;
serializer.startRequest(priority, url, this);
} | @Test
public void testRequestComplete_with200NotCancelledMatchingLength_callsCallbackWithValidData()
throws Exception {
String data = "data";
ByteBuffer expected = ByteBuffer.wrap(data.getBytes());
ArgumentCaptor<ByteBuffer> captor = ArgumentCaptor.forClass(ByteBuffer.class);
fetcher.loadData(P... |
@Override
public void notifyTerminated() {
doAction(Executable::notifyTerminated);
} | @Test
public void shouldNotifyAllToShutdown() throws Exception {
// When:
multiExecutable.notifyTerminated();
// Then:
// Then:
final InOrder inOrder = Mockito.inOrder(executable1, executable2);
inOrder.verify(executable1).notifyTerminated();
inOrder.verify(executable2).notifyTerminated()... |
@Override
public void askAccessPermissions(@NonNull final DecryptionContext context) {
this.context = context;
if (!DeviceAvailability.isPermissionsGranted(reactContext)) {
final CryptoFailedException failure = new CryptoFailedException(
"Could not start fingerprint Authentication. No permissio... | @Test(expected= NullPointerException.class)
@Config(sdk = Build.VERSION_CODES.M)
public void testBiometryAuthenticationErrorNoActivity() {
// GIVEN
final KeyguardManager keyguardManager = mock(KeyguardManager.class);
when(keyguardManager.isKeyguardSecure()).thenReturn(true);
final ReactApplicationC... |
public static GoodTuring of(int[] r, int[] Nr) {
final double CONFID_FACTOR = 1.96;
if (r.length != Nr.length) {
throw new IllegalArgumentException("The sizes of r and Nr are not same.");
}
int len = r.length;
double[] p = new double[len];
double[] logR = ne... | @Test
public void test() {
System.out.println("GoodTuring");
int[] r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12};
int[] Nr = {120, 40, 24, 13, 15, 5, 11, 2, 2, 1, 3};
double p0 = 0.2047782;
double[] p = {
0.0009267, 0.0024393, 0.0040945, 0.0058063, 0.0075464,
... |
static boolean shouldStoreMessage(final Message message) {
// XEP-0334: Implement the <no-store/> hint to override offline storage
if (message.getChildElement("no-store", "urn:xmpp:hints") != null) {
return false;
}
// OF-2083: Prevent storing offline message that is already... | @Test
public void shouldStoreNonEmptyChatMessages() {
// XEP-0160: "chat" message types SHOULD be stored offline unless they only contain chat state notifications
Message message = new Message();
message.setType(Message.Type.chat);
message.setBody(" ");
assertTrue(OfflineMess... |
public static void notNullOrEmpty(String string) {
notNullOrEmpty(string, String.format("string [%s] is null or empty", string));
} | @Test
public void testNotNull1NotEmpty3() {
assertThrows(IllegalArgumentException.class, () -> Precondition.notNullOrEmpty(" "));
} |
@Override
public Map<String, String> contextLabels() {
return Collections.unmodifiableMap(contextLabels);
} | @Test
public void testKafkaMetricsContextLabelsAreImmutable() {
context = new KafkaMetricsContext(namespace, labels);
assertThrows(UnsupportedOperationException.class, () -> context.contextLabels().clear());
} |
@Override
public boolean confirm(String key) {
repo.lock(key);
try {
return repo.replace(key, false, true);
} finally {
repo.unlock(key);
}
} | @Test
public void testConfirm() throws Exception {
// ADD first key and confirm
assertTrue(repo.add(key01));
assertTrue(repo.confirm(key01));
// try to confirm a key that isn't there
assertFalse(repo.confirm(key02));
} |
@Override
public ServerWebExchange convert(final JwtRuleHandle jwtRuleHandle, final ServerWebExchange exchange, final Map<String, Object> jwtBody) {
final DefaultJwtRuleHandle defaultJwtRuleHandle = (DefaultJwtRuleHandle) jwtRuleHandle;
if (CollectionUtils.isEmpty(defaultJwtRuleHandle.getConverter()... | @Test
public void testConvert() {
String handleJson = "{\"converter\":[{\"jwtVal\":\"sub\",\"headerVal\":\"id\"}]}";
DefaultJwtRuleHandle defaultJwtRuleHandle = defaultJwtConvertStrategy.parseHandleJson(handleJson);
ServerWebExchange newExchange = defaultJwtConvertStrategy
.c... |
public URLConnection openConnection(URL url) throws IOException {
try {
return openConnection(url, false);
} catch (AuthenticationException e) {
// Unreachable
LOG.error("Open connection {} failed", url, e);
return null;
}
} | @Test
public void testConnConfiguratior() throws IOException {
final URL u = new URL("http://localhost");
final List<HttpURLConnection> conns = Lists.newArrayList();
URLConnectionFactory fc = new URLConnectionFactory(new ConnectionConfigurator() {
@Override
public HttpURLConnection configure(H... |
public static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName) {
if (values == null) {
// pass
return;
}
for (String value : values) {
Preconditions.checkNotNull(
value, "Property '" + propertyName + "' cannot contain null en... | @Test
public void testCheckNullOrNonNullNonEmptyEntries_mapWithValuesPass() {
Validator.checkNullOrNonNullNonEmptyEntries(
ImmutableMap.of("key1", "val1", "key2", "val2"), "test");
// pass
} |
@Override
public double distanceBtw(Point p1, Point p2) {
numCalls++;
confirmRequiredDataIsPresent(p1);
confirmRequiredDataIsPresent(p2);
Duration timeDelta = Duration.between(p1.time(), p2.time()); //can be positive of negative
timeDelta = timeDelta.abs();
Double... | @Test
public void testDistanceComputation_latitude() {
PointDistanceMetric metric1 = new PointDistanceMetric(1.0, 1.0);
PointDistanceMetric metric2 = new PointDistanceMetric(1.0, 2.0);
Point p1 = new PointBuilder()
.latLong(0.0, 0.0)
.altitude(Distance.ofFeet(0.0))
... |
public boolean initAndAddIssue(Issue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
if (noSonar(inputComponent, issue)) {
return false;
}
ActiveRule activeRule = activeRules.find(issue.ruleKey());
if (activeRule == null) {
... | @Test
public void filter_issue() {
DefaultIssue issue = new DefaultIssue(project)
.at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message(""))
.forRule(JAVA_RULE_KEY);
when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(false);
boolean ad... |
@Override
public int size() {
return values.length;
} | @Test
public void hasASize() {
assertThat(snapshot.size())
.isEqualTo(5);
} |
@VisibleForTesting
Optional<Method> getGetSchedulerResourceTypesMethod() {
return getSchedulerResourceTypesMethod;
} | @Test
void testGetSchedulerResourceTypesMethodReflectiveHadoop26() {
final RegisterApplicationMasterResponseReflector
registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(LOG);
assertThat(registerApplicationMasterRespon... |
@Override
public boolean format() throws Exception {
// Clear underreplicated ledgers
store.deleteRecursive(PulsarLedgerUnderreplicationManager.getBasePath(ledgersRootPath)
+ BookKeeperConstants.DEFAULT_ZK_LEDGERS_ROOT_PATH)
.get(BLOCKING_CALL_TIMEOUT, M... | @Test(dataProvider = "impl")
public void testFormatNonExistingCluster(String provider, Supplier<String> urlSupplier) throws Exception {
methodSetup(urlSupplier);
assertClusterNotExists();
assertTrue(registrationManager.format());
assertClusterExists();
} |
public static String formatTime(long timestamp) {
return dateFmt.format(Instant.ofEpochMilli(timestamp));
} | @Test
public void testFormatTime() {
Assert.assertEquals("2019-06-15 12:13:14.000",
EagleEyeCoreUtils.formatTime(1560600794000L - TimeZone.getDefault().getRawOffset()));
} |
public static GeneratorResult run(String resolverPath,
String defaultPackage,
final boolean generateImported,
final boolean generateDataTemplates,
RestliVersion version,
... | @Test
public void testLowercasePathForGeneratedFileDoesNotEffectTargetDirectory() throws IOException
{
if (!isFileSystemCaseSensitive) {
// If system is case insensitive, then this test is a NOP.
return;
}
// Given: Path with upper case letters as part of the target directory's path.
... |
public static Point<AriaCsvHit> parsePointFromAriaCsv(String rawCsvText) {
AriaCsvHit ariaHit = AriaCsvHit.from(rawCsvText);
Position pos = new Position(ariaHit.time(), ariaHit.latLong(), ariaHit.altitude());
return new Point<>(pos, null, ariaHit.linkId(), ariaHit);
} | @Test
public void exampleParsing_failCorrectlyWhenOutOfBounds() {
String rawCsv = ",,2018-03-24T14:41:09.371Z,vehicleIdNumber,42.9525,-83.7056,2700";
Point<AriaCsvHit> pt = AriaCsvHits.parsePointFromAriaCsv(rawCsv);
assertThat("The entire rawCsv text is accessible from the parsed point", ... |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testWithMultipleTargetValueResults() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.callback(new Callable<Result[]>() {
@Override
public Result[] call() throws Exception {
retur... |
@Override
public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) {
log.debug(
"sort catalogue tree based on first letter. catalogueTree: {}, sortTypeEnum: {}",
catalogueTree,
sortTypeEnum);
Collator collator = Collator.ge... | @Test
public void sortEmptyTest2() {
List<Catalogue> catalogueTree = null;
SortTypeEnum sortTypeEnum = SortTypeEnum.ASC;
List<Catalogue> resultList = catalogueTreeSortFirstLetterStrategyTest.sort(catalogueTree, sortTypeEnum);
assertEquals(Lists.newArrayList(), resultList);
} |
@Override
public void profileSetOnce(JSONObject properties) {
} | @Test
public void profileSetOnce() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
... |
@Override
public HttpResponse send(HttpRequest httpRequest) throws IOException {
return send(httpRequest, null);
} | @Test
public void send_whenHeadRequest_returnsHttpResponseWithoutBody() throws IOException {
String responseBody = "test response";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
.setHeader(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString())
... |
@Override public Destination getDestination( JmsDelegate meta ) {
checkNotNull( meta.destinationName, getString( JmsConstants.PKG, "JmsWebsphereMQ.DestinationNameRequired" ) );
try {
String destName = meta.destinationName;
return isQueue( meta )
? new MQQueue( destName )
: new MQTopi... | @Test
public void noDestinationNameSetCausesError() {
jmsDelegate.destinationType = QUEUE.name();
jmsDelegate.destinationName = null;
try {
jmsProvider.getDestination( jmsDelegate );
fail();
} catch ( Exception e ) {
assertTrue( e.getMessage().contains( "Destination name must be set... |
public long cardinality() {
switch (bitmapType) {
case EMPTY:
return 0;
case SINGLE_VALUE:
return 1;
case BITMAP_VALUE:
return bitmap.getLongCardinality();
case SET_VALUE:
return set.size();
}... | @Test
public void testCardinality() {
BitmapValue bitmapValue = new BitmapValue();
assertEquals(0, bitmapValue.cardinality());
bitmapValue.add(0);
bitmapValue.add(0);
bitmapValue.add(-1);
bitmapValue.add(-1);
bitmapValue.add(Integer.MAX_VALUE);
bitma... |
public static Write write() {
return new AutoValue_SnsIO_Write.Builder().build();
} | @Test
public void testRetries() throws Throwable {
thrown.expect(IOException.class);
thrown.expectMessage("Error writing to SNS");
thrown.expectMessage("No more attempts allowed");
final PublishRequest request1 = createSampleMessage("my message that will not be published");
final TupleTag<Publish... |
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{device_id}")
@ChangesLinkedDevices
public void removeDevice(@Mutable @Auth AuthenticatedDevice auth, @PathParam("device_id") byte deviceId) {
if (auth.getAuthenticatedDevice().getId() != Device.PRIMARY_ID &&
auth.getAuthenticatedDevice().getId()... | @Test
void removeDevice() {
// this is a static mock, so it might have previous invocations
clearInvocations(AuthHelper.VALID_ACCOUNT);
final byte deviceId = 2;
when(accountsManager.removeDevice(AuthHelper.VALID_ACCOUNT, deviceId))
.thenReturn(CompletableFuture.completedFuture(AuthHelper.VA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.