focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static L4ModificationInstruction modTcpSrc(TpPort port) {
checkNotNull(port, "Src TCP port cannot be null");
return new ModTransportPortInstruction(L4SubType.TCP_SRC, port);
} | @Test
public void testModTcpSrcMethod() {
final Instruction instruction = Instructions.modTcpSrc(tpPort1);
final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction =
checkAndConvert(instruction, Instruction.Type.L4MODIFICATION,
... |
public Timer add(long interval, TimerHandler handler, Object... args)
{
if (handler == null) {
return null;
}
return new Timer(timer.add(interval, handler, args));
} | @Test
public void testAddFaultyHandler()
{
Timer timer = timers.add(10, null);
assertThat(timer, nullValue());
} |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldProvideContextWhenAnExceptionOccurs() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("#a");
new ParamResolver(new ParamSubstitutionHandlerFactory(params(param("foo", "pavan"), param(... |
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
JsonNode jsonValue;
// This handles a tombstone message
if (value == null) {
return SchemaAndValue.NULL;
}
try {
jsonValue = deserializer.deserialize(topic, value);
}... | @Test
public void decimalToConnect() {
Schema schema = Decimal.schema(2);
BigDecimal reference = new BigDecimal(new BigInteger("156"), 2);
// Payload is base64 encoded byte[]{0, -100}, which is the two's complement encoding of 156.
String msg = "{ \"schema\": { \"type\": \"bytes\", \... |
public void isNoneOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
isNotIn(accumulate(first, second, rest));
} | @Test
public void isNoneOfNull() {
assertThat((String) null).isNoneOf("a", "b", "c");
} |
public Optional<TransactionReceipt> getTransactionReceipt() {
return Optional.ofNullable(transactionReceipt);
} | @Test
public void testTransactionFailedWithRevertReason() throws Exception {
TransactionReceipt transactionReceipt = createFailedTransactionReceipt();
prepareCall(OWNER_REVERT_MSG_HASH);
TransactionException thrown =
assertThrows(
TransactionException... |
public static FieldScope ignoringFieldDescriptors(
FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) {
return FieldScopeImpl.createIgnoringFieldDescriptors(asList(firstFieldDescriptor, rest));
} | @Test
public void testIgnoreFieldsAtDifferentLevels() {
// Ignore all 'o_int' fields, in different ways.
Message message =
parse(
"o_int: 1 r_string: \"foo\" o_sub_test_message: { o_int: 2 "
+ "o_sub_sub_test_message: { o_int: 3 r_string: \"bar\" } }");
// Even though ... |
@Override
public OrganizedImports organizeImports(List<Import> imports) {
OrganizedImports organized = new OrganizedImports();
// Group into static and non-static.
Map<Boolean, List<Import>> partionedByStatic =
imports.stream().collect(Collectors.partitioningBy(Import::isStatic));
for (Boole... | @Test
public void staticFirstOrdering() {
AndroidImportOrganizer organizer = new AndroidImportOrganizer(StaticOrder.STATIC_FIRST);
ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS);
assertThat(organized.asImportBlock())
.isEqualTo(
"import static android.f... |
@Override
public boolean add(PipelineConfig pipelineConfig) {
verifyUniqueName(pipelineConfig);
PipelineConfigs part = this.getFirstEditablePartOrNull();
if (part == null)
throw bomb("No editable configuration sources");
return part.add(pipelineConfig);
} | @Test
public void shouldAddPipelineAtIndex_WhenWouldLandInEditablePart() {
PipelineConfig pipeline0 = PipelineConfigMother.pipelineConfig("pipeline0");
PipelineConfig pipeline1 = PipelineConfigMother.pipelineConfig("pipeline1");
PipelineConfig pipeline3 = PipelineConfigMother.pipelineConfig(... |
@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getChildChannelHandlers(MessageInput input) {
final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>();
final CodecAggregator aggregator = getAggregator();
handlers.put("cha... | @Test
public void getChildChannelHandlersFailsIfTempDirIsNotWritable() throws IOException {
final File tmpDir = temporaryFolder.newFolder();
assumeTrue(tmpDir.setWritable(false));
assumeFalse(tmpDir.canWrite());
System.setProperty("java.io.tmpdir", tmpDir.getAbsolutePath());
... |
@Override
public Map<String, String> generationCodes(Long tableId) {
// 校验是否已经存在
CodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
List<CodegenColumnDO> columns = codegenColumnMapper.se... | @Test
public void testGenerationCodes_tableNotExists() {
assertServiceException(() -> codegenService.generationCodes(randomLongId()),
CODEGEN_TABLE_NOT_EXISTS);
} |
@Override
public Set<String> getConfigNames() {
return SOURCE.keySet();
} | @Test
public void getConfigNames() {
final Set<String> configNames = source.getConfigNames();
Assert.assertFalse(configNames.isEmpty());
} |
public static Properties updateSplitSchema(Properties splitSchema, List<HiveColumnHandle> columns)
{
requireNonNull(splitSchema, "splitSchema is null");
requireNonNull(columns, "columns is null");
// clone split properties for update so as not to affect the original one
Properties up... | @Test(expectedExceptions = NullPointerException.class)
public void shouldThrowNullPointerExceptionWhenSchemaIsNull()
{
updateSplitSchema(null, ImmutableList.of());
} |
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getData();
switch (metric.getType().getValueType()) {
case ... | @Test
public void toMeasure_returns_no_value_if_dto_has_no_value_for_Long_Metric() {
Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LONG_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE);
} |
@Override
public Mono<byte[]> readPublicKey() {
return Mono.just(keyPair)
.map(KeyPair::getPublic)
.map(PublicKey::getEncoded);
} | @Test
void shouldReadPublicKey() throws IOException {
var realPubKeyBytes = Files.readAllBytes(tempDir.resolve("pat_id_rsa.pub"));
StepVerifier.create(service.readPublicKey())
.assertNext(bytes -> assertArrayEquals(realPubKeyBytes, bytes))
.verifyComplete();
} |
public boolean canViewAndEditTemplate(CaseInsensitiveString username, List<Role> roles) {
for (PipelineTemplateConfig templateConfig : this) {
if (canUserEditTemplate(templateConfig, username, roles)) {
return true;
}
}
return false;
} | @Test
public void shouldReturnTrueIfUserCanViewAndEditAtLeastOneTemplate() throws Exception {
CaseInsensitiveString templateAdmin = new CaseInsensitiveString("template-admin");
TemplatesConfig templates = configForUserWhoCanViewATemplate();
templates.add(PipelineTemplateConfigMother.createTe... |
@Override
public synchronized DefaultConnectClient get(
final Optional<String> ksqlAuthHeader,
final List<Entry<String, String>> incomingRequestHeaders,
final Optional<KsqlPrincipal> userPrincipal
) {
if (defaultConnectAuthHeader == null) {
defaultConnectAuthHeader = buildDefaultAuthHead... | @Test
public void shouldBuildWithoutAuthHeader() {
// When:
final DefaultConnectClient connectClient =
connectClientFactory.get(Optional.empty(), Collections.emptyList(), Optional.empty());
// Then:
assertThat(connectClient.getRequestHeaders(), is(EMPTY_HEADERS));
} |
@Override
public Object getDateValue(final ResultSet resultSet, final int columnIndex) throws SQLException {
return resultSet.getDate(columnIndex);
} | @Test
void assertGetDateValue() throws SQLException {
when(resultSet.getDate(1)).thenReturn(new Date(0L));
assertThat(dialectResultSetMapper.getDateValue(resultSet, 1), is(new Date(0L)));
} |
public FilterAggregationBuilder buildTopAggregation(String topAggregationName, TopAggregationDefinition<?> topAggregation,
Consumer<BoolQueryBuilder> extraFilters, Consumer<FilterAggregationBuilder> subAggregations) {
BoolQueryBuilder filter = filterComputer.getTopAggregationFilter(topAggregation)
.orElse... | @Test
public void buildTopAggregation_adds_subAggregation_from_lambda_parameter() {
SimpleFieldTopAggregationDefinition topAggregation = new SimpleFieldTopAggregationDefinition("bar", false);
AggregationBuilder[] subAggs = IntStream.range(0, 1 + new Random().nextInt(12))
.mapToObj(i -> AggregationBuilde... |
boolean isCollection( BeanInjectionInfo.Property property ) {
if ( property == null ) { // not sure if this is necessary
return false;
}
BeanLevelInfo beanLevelInfo = getFinalPath( property );
return ( beanLevelInfo != null ) ? isCollection( beanLevelInfo ) : null;
} | @Test
public void isCollection_BeanLevelInfo() {
BeanInjector bi = new BeanInjector(null );
BeanLevelInfo bli_list = new BeanLevelInfo();
bli_list.dim = BeanLevelInfo.DIMENSION.LIST;
assertTrue( bi.isCollection( bli_list ));
BeanLevelInfo bli_array = new BeanLevelInfo();
bli_array.dim = Bea... |
public void callTrack(JSONObject eventObject) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("eventJSON", eventObject);
if ("$AppStart".equals(eventObject.optString("event"))) {
if (mFunctionListener == null) {
cacheData = jso... | @Test
public void callTrack() {
SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplication);
sensorsDataAPI.addFunctionListener(new SAFunctionListener() {
@Override
public void call(String function, JSONObject args) {
Assert.assertEquals("trackEvent", f... |
public void sendMessage(M message, MessageHeaders headers) {
this.sendMessage(responseTopic, message, headers);
} | @Test
public void testMarshallingVerstrekkingAanAfnemer() throws IOException {
VerstrekkingAanAfnemer verstrekkingAanAfnemer = new VerstrekkingAanAfnemer();
verstrekkingAanAfnemer.setDatumtijdstempelDigilevering(parseTime("2018-02-02T11:59:04.170+01:00"));
verstrekkingAanAfnemer.setDatumtij... |
@GET
@Path("/{connector}/tasks")
@Operation(summary = "List all tasks and their configurations for the specified connector")
public List<TaskInfo> getTaskConfigs(final @PathParam("connector") String connector) throws Throwable {
FutureCallback<List<TaskInfo>> cb = new FutureCallback<>();
her... | @Test
public void testGetConnectorTaskConfigs() throws Throwable {
final ArgumentCaptor<Callback<List<TaskInfo>>> cb = ArgumentCaptor.forClass(Callback.class);
expectAndCallbackResult(cb, TASK_INFOS).when(herder).taskConfigs(eq(CONNECTOR_NAME), cb.capture());
List<TaskInfo> taskInfos = conn... |
public DropTypeCommand create(final DropType statement) {
final String typeName = statement.getTypeName();
final boolean ifExists = statement.getIfExists();
if (!ifExists && !metaStore.resolveType(typeName).isPresent()) {
throw new KsqlException("Type " + typeName + " does not exist.");
}
re... | @Test
public void shouldCreateDropTypeForExistingTypeAndIfExistsSet() {
// Given:
final DropType dropType = new DropType(Optional.empty(), EXISTING_TYPE, true);
// When:
final DropTypeCommand cmd = factory.create(dropType);
// Then:
assertThat(cmd.getTypeName(), equalTo(EXISTING_TYPE));
} |
static Method getGetter(final Class<?> clazz, final String propertyName) {
final String getterName = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
final String iserName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
try {... | @Test(expected = IllegalStateException.class)
public void doNotFindGetterWithArgument() throws Exception {
ReflectionUtils.getGetter(Foo.class, "c");
fail("Should have thrown exception - getC is not a getter");
} |
@Override
public int getOriginalPort() {
try {
return getOriginalPort(getContext(), getHeaders(), getPort());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
} | @Test
void getOriginalPort_respectsProxyProtocol() throws URISyntaxException {
SessionContext context = new SessionContext();
context.set(
CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS,
new InetSocketAddress(InetAddresses.forString("1.1.1.1"), 443));
He... |
protected static Map<String, String> appendParameters(
Map<String, String> parameters, Map<String, String> appendParameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.putAll(appendParameters);
return parameters;
} | @Test
void appendParameter2() {
Map<String, String> source = new HashMap<>();
source.put("default.num", "one1");
source.put("num", "ONE1");
Map<String, String> parameters = new HashMap<>();
parameters.put("default.num", "one");
parameters.put("num", "ONE");
s... |
@Override
public Num calculate(BarSeries series, Position position) {
if (position == null || position.getEntry() == null || position.getExit() == null) {
return series.zero();
}
Returns returns = new Returns(series, position, Returns.ReturnType.LOG);
return calculateES(r... | @Test
public void calculateWithBuyAndHold() {
series = new MockBarSeries(numFunction, 100d, 99d);
Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(1, series));
AnalysisCriterion varCriterion = getCriterion();
assertNumEquals(numOf(Math.log(99d / 100)), varCriteri... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final SqlType type, final SqlTypeWalker.Visitor<S, F> visitor) {
final BiFunction<SqlTypeWalker.Visitor<?, ?>, SqlType, Object> handler = HANDLER
.get(type.baseType());
if (handler == null) {
throw new UnsupportedOperationException("Un... | @Test
public void shouldVisitAll() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitType(final SqlType type) {
return "Expected";
}
};
allTypes().forEach(type -> {
// When:
final String result = SqlTypeWalker.visit(type, visito... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersions")
public void testPostProcessingException(final ProtocolVersion protocolVersion, final String errorResponseHeaderName,
final RestOrStream restOrStream) throws Exception
{
//request for nes... |
public static FieldScope fromSetFields(Message message) {
return fromSetFields(
message, AnyUtils.defaultTypeRegistry(), AnyUtils.defaultExtensionRegistry());
} | @Test
public void testFromSetFields() {
Message scopeMessage =
parse(
"o_int: 1 r_string: \"x\" o_test_message: { o_int: 1 } "
+ "r_test_message: { r_string: \"x\" } r_test_message: { o_int: 1 } "
+ "o_sub_test_message: { o_test_message: { o_int: 1 } }");
/... |
@Override
public Thread newThread(Runnable r) {
String threadName = name + id.getAndIncrement();
Thread thread = new Thread(r, threadName);
thread.setDaemon(true);
return thread;
} | @Test
void test() {
NameThreadFactory threadFactory = new NameThreadFactory("test");
Thread t1 = threadFactory.newThread(() -> {
});
Thread t2 = threadFactory.newThread(() -> {
});
assertEquals("test.0", t1.getName());
assertEquals("... |
public static String getName(Object obj) {
Objects.requireNonNull(obj, "obj");
return obj.getClass().getName();
} | @Test
void testGetName() {
final String name = "java.lang.Integer";
Integer val = 1;
assertEquals(name, ClassUtils.getName(val));
assertEquals(name, ClassUtils.getName(Integer.class));
assertEquals(name, ClassUtils.getCanonicalName(val));
assertEquals(name, C... |
public static List<Group> enumerateFrom(Group root) {
List<Group> leaves = new ArrayList<>();
visitNode(root, leaves);
return leaves;
} | @Test
void rootGroupCountedAsLeafWhenNoChildren() {
Group g = new Group(0, "donkeykong");
List<Group> leaves = LeafGroups.enumerateFrom(g);
assertThat(leaves.size(), is(1));
assertThat(leaves.get(0).getName(), is("donkeykong"));
} |
public int getPartition(K key, V value, int numReduceTasks) {
int h = SEED ^ key.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
h = h ^ (h >>> 7) ^ (h >>> 4);
return (h & Integer.MAX_VALUE) % numReduceTasks;
} | @Test
public void testPatterns() {
int results[] = new int[PARTITIONS];
RehashPartitioner <IntWritable, NullWritable> p = new RehashPartitioner < IntWritable, NullWritable> ();
/* test sequence 4, 8, 12, ... 128 */
for(int i = 0; i < END; i+= STEP) {
results[p.getPartition(new IntWritable(i), nu... |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateCastToString() {
// Given:
final Expression cast1 = new Cast(
new IntegerLiteral(10),
new Type(SqlPrimitiveType.of("STRING"))
);
final Expression cast2 = new Cast(
new LongLiteral(1234L),
new Type(SqlPrimitiveType.of("STRING"))
);
... |
@Override
public List<String> splitAndEvaluate() {
try (ReflectContext context = new ReflectContext(JAVA_CLASSPATH)) {
if (Strings.isNullOrEmpty(inlineExpression)) {
return Collections.emptyList();
}
return flatten(evaluate(context, GroovyUtils.split(handl... | @Test
void assertEvaluateForComplex() {
List<String> expected = createInlineExpressionParser("t_${['new','old']}_order_${1..2}, t_config").splitAndEvaluate();
assertThat(expected.size(), is(5));
assertThat(expected, hasItems("t_new_order_1", "t_new_order_2", "t_old_order_1", "t_old_order_2",... |
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 assertDecodeSmallJsonObjectWithUInt16() {
List<JsonEntry> jsonEntries = new LinkedList<>();
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT16, "key1", 0x00007fff));
jsonEntries.add(new JsonEntry(JsonValueTypes.UINT16, "key2", 0x00008000));
ByteBuf payload = mockJsonObjec... |
@Override
public MapperResult findConfigInfoAggrByPageFetchRows(MapperContext context) {
final Integer startRow = context.getStartRow();
final Integer pageSize = context.getPageSize();
final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
final String group... | @Test
void testFindConfigInfoAggrByPageFetchRows() {
String dataId = "data-id";
String groupId = "group-id";
String tenantId = "tenant-id";
Integer startRow = 0;
Integer pageSize = 5;
MapperContext context = new MapperContext();
context.putWhereParame... |
@Override
public Token redeem(@NonNull String code, String redirectUri, String clientId) {
var redeemed = codeRepo.remove(code).orElse(null);
if (redeemed == null) {
return null;
}
if (!validateCode(redeemed, redirectUri, clientId)) {
return null;
}
var accessTokenTtl = Duration... | @Test
void redeem_idToken() throws JOSEException, ParseException {
var issuer = URI.create("https://idp.example.com");
var k = genKey();
var keyStore = mock(KeyStore.class);
when(keyStore.signingKey()).thenReturn(k);
var codeRepo = mock(CodeRepo.class);
var sut = new TokenIssuerImpl(issuer, ... |
@ScalarOperator(SUBTRACT)
@SqlType(StandardTypes.DOUBLE)
public static double subtract(@SqlType(StandardTypes.DOUBLE) double left, @SqlType(StandardTypes.DOUBLE) double right)
{
return left - right;
} | @Test
public void testSubtract()
{
assertFunction("37.7E0 - 37.7E0", DOUBLE, 37.7 - 37.7);
assertFunction("37.7E0 - 17.1E0", DOUBLE, 37.7 - 17.1);
assertFunction("17.1E0 - 37.7E0", DOUBLE, 17.1 - 37.7);
assertFunction("17.1E0 - 17.1E0", DOUBLE, 17.1 - 17.1);
} |
static void dissectCatalogResize(
final MutableDirectBuffer buffer, final int offset, final StringBuilder builder)
{
int absoluteOffset = offset;
absoluteOffset += dissectLogHeader(CONTEXT, CATALOG_RESIZE, buffer, absoluteOffset, builder);
final int maxEntries = buffer.getInt(absolu... | @Test
void catalogResize()
{
internalEncodeLogHeader(buffer, 0, 6, 100, () -> 5_600_000_000L);
buffer.putInt(LOG_HEADER_LENGTH, 24, LITTLE_ENDIAN);
buffer.putLong(LOG_HEADER_LENGTH + SIZE_OF_INT, 100, LITTLE_ENDIAN);
buffer.putInt(LOG_HEADER_LENGTH + SIZE_OF_INT + SIZE_OF_LONG, 7... |
@Override
public Num calculate(BarSeries series, Position position) {
return getTradeCost(series, position, series.numOf(initialAmount));
} | @Test
public void fixedCost() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord();
Num criterion;
tradingRecord.operate(0);
tradingRecord.operate(1);
criterion = getCriterion(1000... |
public List<Path> getBaseDirs() {
return this.baseDirs;
} | @Test
public void testGetBaseDirs() throws Exception {
assertEquals(1, deletionTask.getBaseDirs().size());
assertEquals(baseDirs, deletionTask.getBaseDirs());
} |
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) {
return decorateTextWithHtml(text, decorationDataHolder, null, null);
} | @Test
public void should_allow_multiple_levels_highlighting() {
String javaDocSample =
"/**" + LF_END_OF_LINE +
" * Creates a FormulaDecorator" + LF_END_OF_LINE +
" *" + LF_END_OF_LINE +
" * @param metric the metric should have an associated formula" + LF_END_OF_LINE +
" * "... |
public String getWorkflowIdentity() {
RestartConfig.RestartNode node = getCurrentNode(restartConfig);
return "[" + node.getWorkflowId() + "][" + node.getInstanceId() + "]";
} | @Test
public void testGetWorkflowIdentity() {
RestartConfig config = RestartConfig.builder().addRestartNode("foo", 1, "bar").build();
RunRequest runRequest =
RunRequest.builder()
.initiator(new ManualInitiator())
.currentPolicy(RunPolicy.RESTART_FROM_INCOMPLETE)
.re... |
@Override
public SmsSendRespDTO sendSms(Long sendLogId, String mobile,
String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
// 构建请求
SendSmsRequest request = new SendSmsRequest();
request.setSmsSdkAppId(getSdkAppId());
... | @Test
public void testDoSendSms_success() throws Throwable {
// 准备参数
Long sendLogId = randomLongId();
String mobile = randomString();
String apiTemplateId = randomString();
List<KeyValue<String, Object>> templateParams = Lists.newArrayList(
new KeyValue<>("1",... |
public State currentState() {
return lastState.get().state;
} | @Test
public void currentState() {
for (State state : State.values()) {
tracker.changeState(state, time.milliseconds());
assertEquals(state, tracker.currentState());
}
} |
public Exporter getCompatibleExporter(TransferExtension extension, DataVertical jobType) {
Exporter<?, ?> exporter = getExporterOrNull(extension, jobType);
if (exporter != null) {
return exporter;
}
switch (jobType) {
case MEDIA:
exporter = getMediaExporter(extension);
break... | @Test
public void shouldConstructMediaExporterFromPhotoAndVideo() {
TransferExtension ext = mock(TransferExtension.class);
when(ext.getExporter(eq(PHOTOS))).thenReturn(mock(Exporter.class));
when(ext.getExporter(eq(VIDEOS))).thenReturn(mock(Exporter.class));
when(ext.getExporter(eq(MEDIA))).thenReturn... |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldThrowOnTerminateAsNotExecutable() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
// When:
final PersistentQueryMetadata query = (PersistentQueryMetadata) KsqlEngineTestUtil
.execute(
serviceContext,
ksqlEngine,
"create table ... |
public ZipWriter add(boolean withSrcDir, FileFilter filter, File... files) throws IORuntimeException {
for (File file : files) {
// 如果只是压缩一个文件,则需要截取该文件的父目录
String srcRootDir;
try {
srcRootDir = file.getCanonicalPath();
if ((false == file.isDirectory()) || withSrcDir) {
// 若是文件,则将父目录完整路径都截取掉;若设置包... | @Test
@Disabled
public void addTest(){
final ZipWriter writer = ZipWriter.of(FileUtil.file("d:/test/test.zip"), CharsetUtil.CHARSET_UTF_8);
writer.add(new FileResource("d:/test/qr_c.png"));
writer.close();
} |
RegistryEndpointProvider<Optional<URL>> initializer() {
return new Initializer();
} | @Test
public void testInitializer_handleResponse_accepted() throws IOException, RegistryException {
Mockito.when(mockResponse.getStatusCode()).thenReturn(202); // Accepted
Mockito.when(mockResponse.getHeader("Location"))
.thenReturn(Collections.singletonList("location"));
GenericUrl requestUrl = n... |
@Override
public void truncate() {
truncateToEntries(0);
} | @Test
public void truncate() throws IOException {
try (OffsetIndex idx = new OffsetIndex(nonExistentTempFile(), 0L, 10 * 8)) {
idx.truncate();
IntStream.range(1, 10).forEach(i -> idx.append(i, i));
// now check the last offset after various truncate points and validate t... |
public JRTConnectionPool updateSources(List<String> addresses) {
ConfigSourceSet newSources = new ConfigSourceSet(addresses);
return updateSources(newSources);
} | @Test
public void updateSources() {
ConfigSourceSet twoSources = new ConfigSourceSet(List.of("host0", "host1"));
JRTConnectionPool sourcePool = new JRTConnectionPool(twoSources);
ConfigSourceSet sourcesBefore = sourcePool.getSourceSet();
// Update to the same set, should be equal
... |
public CeTaskMessageDto setMessage(String message) {
checkArgument(message != null && !message.isEmpty(), "message can't be null nor empty");
this.message = abbreviate(message, MAX_MESSAGE_SIZE);
return this;
} | @Test
void setMessage_fails_with_IAE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.setMessage(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("message can't be null nor empty");
} |
public static PostgreSQLErrorResponsePacket newInstance(final Exception cause) {
Optional<ServerErrorMessage> serverErrorMessage = findServerErrorMessage(cause);
return serverErrorMessage.map(PostgreSQLErrorPacketFactory::createErrorResponsePacket)
.orElseGet(() -> createErrorResponsePac... | @Test
void assertPSQLExceptionWithServerErrorMessageIsNull() throws ReflectiveOperationException {
PostgreSQLErrorResponsePacket actual = PostgreSQLErrorPacketFactory.newInstance(new PSQLException("psqlEx", PSQLState.UNEXPECTED_ERROR, new Exception("test")));
Map<Character, String> fields = (Map<Cha... |
@ShellMethod(key = "show restore", value = "Show details of a restore instant")
public String showRestore(
@ShellOption(value = {"--instant"}, help = "Restore instant") String restoreInstant,
@ShellOption(value = {"--limit"}, help = "Limit #rows to be displayed", defaultValue = "10") Integer limit... | @Test
public void testShowRestore() throws IOException {
// get instant
HoodieActiveTimeline activeTimeline = HoodieCLI.getTableMetaClient().getActiveTimeline();
Stream<HoodieInstant> restores = activeTimeline.getRestoreTimeline().filterCompletedInstants().getInstantsAsStream();
HoodieInstant instant ... |
public boolean checkIfEnabled() {
try {
this.gitCommand = locateDefaultGit();
MutableString stdOut = new MutableString();
this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute();
return stdOut.string != null && stdOut.string.startsWith("git version"... | @Test
public void execution_on_windows_is_disabled_if_git_not_on_path() {
System2 system2 = mock(System2.class);
when(system2.isOsWindows()).thenReturn(true);
when(system2.property("PATH")).thenReturn("C:\\some-path;C:\\some-another-path");
ProcessWrapperFactory mockFactory = mock(ProcessWrapperFacto... |
public static <T> Either<String, T> resolveImportDMN(Import importElement, Collection<T> dmns, Function<T, QName> idExtractor) {
final String importerDMNNamespace = ((Definitions) importElement.getParent()).getNamespace();
final String importerDMNName = ((Definitions) importElement.getParent()).getName(... | @Test
void locateInNSnoModelNameWithAlias() {
final Import i = makeImport("nsA", "m1", null);
final List<QName> available = Arrays.asList(new QName("nsA", "m1"),
new QName("nsA", "m2"),
new QName(... |
@Nonnull
@Override
public Optional<? extends INode> parse(
@Nullable final String str, @Nonnull DetectionLocation detectionLocation) {
if (str == null) {
return Optional.empty();
}
for (IMapper mapper : jcaSpecificAlgorithmMappers) {
Optional<? extend... | @Test
void prng() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL");
JcaAlgorithmMapper jcaAlgorithmMapper = new JcaAlgorithmMapper();
Optional<? extends INode> assetOptional =
jcaAlgorithmMapper... |
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException {
// set URL if set in authnRequest
final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL();
if (authnAcsURL != null) {
... | @Test
void resolveAcsUrlWithAcsUrl() throws SamlValidationException {
AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
authnRequest.setAssertionConsumerServiceURL(URL_ASSERTION_CONSUMER_SERVICE);
AuthenticationRequest authenticationRequest = new AuthenticationR... |
public byte[] getKey() {
return key;
} | @Test
public void shouldGenerateAValidAndSafeDESKey() throws Exception {
DESCipherProvider desCipherProvider = new DESCipherProvider(new SystemEnvironment());
byte[] key = desCipherProvider.getKey();
assertThat(DESKeySpec.isWeak(key, 0), is(false));
} |
@Override
public CompletionStage<Void> setAsync(K key, V value) {
return cache.putAsync(key, value);
} | @Test(expected = MethodNotAvailableException.class)
public void testSetAsyncWithTtl() {
adapter.setAsync(42, "value", 1, TimeUnit.MILLISECONDS);
} |
public static DateTimeFormatter createDateTimeFormatter(String format, Mode mode)
{
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
boolean formatContainsHourOfAMPM = false;
for (Token token : tokenize(format)) {
switch (token.getType()) {
case ... | @Test
public void testCreateDateTimeFormatter()
{
DateTimeFormatter formatter = DateFormatParser.createDateTimeFormatter("yyyy/mm/dd", FORMATTER);
assertEquals(formatter.format(LocalDateTime.of(1988, 4, 8, 0, 0)), "1988/04/08");
} |
public synchronized void setSamples(final long samples) {
if (samples < 0) {
this.samples = 0;
} else {
this.samples = samples;
}
} | @Test
public void testSetSamples() throws Throwable {
MeanStatistic stat = tenFromOne.copy();
stat.setSamples(10);
Assertions.assertThat(stat)
.isEqualTo(tenFromTen);
} |
public T fromInstance(T instance) throws IOException {
return fromJson(toJson(instance));
} | @Test
public void testCloneViaJson() throws Throwable {
KeyVal unmarshalled = serDeser.fromInstance(source);
assertEquals(source, unmarshalled);
} |
protected void insertModelAfter(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertAfter) {
int modelIndex = getModelPosition(modelToInsertAfter);
if (modelIndex == -1) {
throw new IllegalStateException("Model is not added: " + modelToInsertAfter);
}
int targetIndex = modelIndex + 1;
pau... | @Test(expected = IllegalStateException.class)
public void testInsertModelAfterThrowsForInvalidModel() {
testAdapter.insertModelAfter(new TestModel(), new TestModel());
} |
@SuppressWarnings("unchecked")
public QueryMetadataHolder handleStatement(
final ServiceContext serviceContext,
final Map<String, Object> configOverrides,
final Map<String, Object> requestProperties,
final PreparedStatement<?> statement,
final Optional<Boolean> isInternalRequest,
f... | @Test
public void shouldRunPushQuery_error() {
// Given:
when(ksqlEngine.executeTransientQuery(any(), any(), anyBoolean()))
.thenThrow(new RuntimeException("Error executing!"));
// When:
Exception e = assertThrows(RuntimeException.class,
() -> queryExecutor.handleStatement(
... |
public int length()
{
return length;
} | @Test
public static void testLength()
{
for (int i = 1; i <= 10; i++) {
Bitmap bitmap = new Bitmap(i * 8);
assertEquals(bitmap.length(), i * 8);
}
} |
@Override
public final SSLEngine newEngine(ByteBufAllocator alloc) {
SSLEngine engine = ctx.newEngine(alloc);
initEngine(engine);
return engine;
} | @Test
public void testInitEngineOnNewEngine() throws Exception {
SslContext delegating = newDelegatingSslContext();
SSLEngine engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT);
assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols());
engine = delegating.ne... |
public static String buildFromParamsMap(String paramsRule, Multimap<String, String> paramsMap) {
if (paramsMap != null && !paramsMap.isEmpty()) {
Multimap<String, String> criteriaMap = TreeMultimap.create(paramsMap);
// Just appends sorted entries, separating them with ?.
StringBuilder... | @Test
void testBuildFromParamsMap() {
Multimap<String, String> paramsMap = ArrayListMultimap.create();
paramsMap.put("page", "1");
paramsMap.put("limit", "20");
paramsMap.put("limitation", "20");
paramsMap.put("status", "available");
// Only 1 parameter should be taken into accou... |
@VisibleForTesting
ExportResult<PhotosContainerResource> exportOneDrivePhotos(
TokensAndUrlAuthData authData,
Optional<IdOnlyContainerResource> albumData,
Optional<PaginationData> paginationData,
UUID jobId)
throws IOException {
Optional<String> albumId = Optional.empty();
if (al... | @Test
public void exportPhotoWithoutNextPage() throws IOException {
// Setup
when(driveItemsResponse.getNextPageLink()).thenReturn(null);
MicrosoftDriveItem photoItem = setUpSinglePhoto(IMAGE_URI, PHOTO_ID);
when(driveItemsResponse.getDriveItems()).thenReturn(new MicrosoftDriveItem[] {photoItem});
... |
public double findPutMessageEntireTimePX(double px) {
Map<Long, LongAdder> lastBuckets = this.lastBuckets;
long start = System.currentTimeMillis();
double result = 0.0;
long totalRequest = lastBuckets.values().stream().mapToLong(LongAdder::longValue).sum();
long pxIndex = (long) ... | @Test
public void findPutMessageEntireTimePXTest() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
final StoreStatsService storeStatsService = new StoreStatsService();
for (int i = 1; i <= 1000; i++) {
for (int j = 0; j < i; j++) {
storeS... |
@Override
public KeyValueSegment getOrCreateSegmentIfLive(final long segmentId,
final ProcessorContext context,
final long streamTime) {
final KeyValueSegment segment = super.getOrCreateSegmentIfLive(segm... | @Test
public void shouldCleanupSegmentsThatHaveExpired() {
final KeyValueSegment segment1 = segments.getOrCreateSegmentIfLive(0, context, -1L);
final KeyValueSegment segment2 = segments.getOrCreateSegmentIfLive(1, context, -1L);
final KeyValueSegment segment3 = segments.getOrCreateSegmentIfL... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final StoregateApiClient client = session.getClient();
final HttpUriRequest request = new HttpGet(String.format("%s/v4.2/download/file... | @Test(expected = NotfoundException.class)
public void testReadNotFound() throws Exception {
final TransferStatus status = new TransferStatus();
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
... |
@Operation(summary = "Get single session")
@PutMapping(value = "/iapi/saml/ad_sessions/{id}", produces = "application/json")
@ResponseBody
public AdSession update(@PathVariable("id") String id, @RequestBody Map<String, Object> body) throws AdException, AdValidationException {
AdSession adSession = a... | @Test
public void updateSession() throws AdException, AdValidationException {
AdSession adSession2 = new AdSession();
adSession2.setAuthenticationLevel(20);
HashMap<String, Object> body = new HashMap<>();
body.put("authentication_level", 20);
body.put("authentication_status"... |
public static Rectangle getExtent(OGCGeometry ogcGeometry)
{
return getExtent(ogcGeometry, 0.0);
} | @Test
public void testGetExtent()
{
assertGetExtent(
"POINT (-23.4 12.2)",
new Rectangle(-23.4, 12.2, -23.4, 12.2));
assertGetExtent(
"LINESTRING (-75.9375 23.6359, -75.9375 23.6364)",
new Rectangle(-75.9375, 23.6359, -75.9375, 23.6... |
@Override
public void onTaskFinished(TaskAttachment attachment) {
if (attachment instanceof BrokerPendingTaskAttachment) {
onPendingTaskFinished((BrokerPendingTaskAttachment) attachment);
} else if (attachment instanceof BrokerLoadingTaskAttachment) {
onLoadingTaskFinished((B... | @Test
public void testLoadingTaskOnFinishedWithErrorNum(@Injectable BrokerLoadingTaskAttachment attachment1,
@Injectable BrokerLoadingTaskAttachment attachment2,
@Injectable LoadTask loadTask1,
... |
public static void onNewIntent(Object activity, Intent intent) {
if (!isTrackPushEnabled()) return;
try {
if (activity instanceof Activity) {
PushProcess.getInstance().onNotificationClick((Activity) activity, intent);
SALog.i(TAG, "onNewIntent");
}... | @Test
public void onNewIntent() {
SchemeActivity activity = Robolectric.setupActivity(SchemeActivity.class);
PushAutoTrackHelper.onNewIntent(activity, activity.getIntent());
} |
public boolean isRetryAnotherBrokerWhenNotStoreOK() {
return retryAnotherBrokerWhenNotStoreOK;
} | @Test
public void assertIsRetryAnotherBrokerWhenNotStoreOK() {
assertFalse(producer.isRetryAnotherBrokerWhenNotStoreOK());
} |
@Operation(summary = "queryTaskListPaging", description = "QUERY_TASK_INSTANCE_LIST_PAGING_NOTES")
@Parameters({
@Parameter(name = "processInstanceId", description = "PROCESS_INSTANCE_ID", schema = @Schema(implementation = int.class, example = "100")),
@Parameter(name = "processInstanceName"... | @Test
public void testQueryTaskListPaging() {
Result result = new Result();
Integer pageNo = 1;
Integer pageSize = 20;
PageInfo pageInfo = new PageInfo<TaskInstance>(pageNo, pageSize);
result.setData(pageInfo);
result.setCode(Status.SUCCESS.getCode());
result... |
public static BIP38PrivateKey fromBase58(Network network, String base58) throws AddressFormatException {
byte[] versionAndDataBytes = Base58.decodeChecked(base58);
int version = versionAndDataBytes[0] & 0xFF;
byte[] bytes = Arrays.copyOfRange(versionAndDataBytes, 1, versionAndDataBytes.length);
... | @Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBase58_invalidLength() {
String base58 = Base58.encodeChecked(1, new byte[16]);
BIP38PrivateKey.fromBase58((Network) null, base58);
} |
boolean tearDown() {
return future.cancel(true);
} | @Test
@SuppressWarnings("unchecked")
public void tearDownTriggersCancellation() throws Exception {
when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))).
thenReturn(mockFuture);
when(mockFuture.cancel(true)).thenReturn(true);
... |
public static String formatBytes(long bytes) {
if (bytes < 0) {
return String.valueOf(bytes);
}
double asDouble = (double) bytes;
int ordinal = (int) Math.floor(Math.log(asDouble) / Math.log(1024.0));
double scale = Math.pow(1024.0, ordinal);
double scaled = a... | @Test
public void testFormatBytes() {
assertEquals("-1", formatBytes(-1));
assertEquals("1023 B", formatBytes(1023));
assertEquals("1 KB", formatBytes(1024));
assertEquals("1024 KB", formatBytes((1024 * 1024) - 1));
assertEquals("1 MB", formatBytes(1024 * 1024));
asse... |
public void processIssuesByBatch(DbSession dbSession, Set<String> issueKeysSnapshot, Consumer<List<IssueDto>> listConsumer, Predicate<? super IssueDto> filter) {
boolean hasMoreIssues = !issueKeysSnapshot.isEmpty();
long offset = 0;
List<IssueDto> issueDtos = new ArrayList<>();
while (hasMoreIssues) {... | @Test
public void processIssuesByBatch_givenNoIssuesReturnedByDatabase_noIssuesConsumed() {
var pullActionIssuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams);
when(issueDao.selectByBranch(any(), any(), any()))
.thenReturn(List.of());
List<IssueDto> returnedDtos = new ArrayList<>()... |
@Override
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) {
final Pod mountedPod = decoratePod(flinkPod.getPodWithoutMainContainer());
final Container mountedMainContainer =
new ContainerBuilder(flinkPod.getMainContainer())
.addNewVolumeMount()
... | @Test
void testDecoratedFlinkContainer() {
final Container resultMainContainer =
flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod).getMainContainer();
assertThat(resultMainContainer.getVolumeMounts()).hasSize(1);
final VolumeMount volumeMount = resultMainContainer.getVo... |
public static Slice unscaledDecimal()
{
return Slices.allocate(UNSCALED_DECIMAL_128_SLICE_LENGTH);
} | @Test
public void testRescaleOverflows()
{
assertRescaleOverflows(unscaledDecimal(1), 38);
} |
@VisibleForTesting
public Supplier<PageProjection> compileProjection(
SqlFunctionProperties sqlFunctionProperties,
RowExpression projection,
Optional<String> classNameSuffix)
{
return compileProjection(sqlFunctionProperties, emptyMap(), projection, classNameSuffix);
... | @Test
public void testCache()
{
PageFunctionCompiler cacheCompiler = new PageFunctionCompiler(createTestMetadataManager(), 100);
assertSame(
cacheCompiler.compileProjection(SESSION.getSqlFunctionProperties(), ADD_10_EXPRESSION, Optional.empty()),
cacheCompiler.com... |
public static UserInfo map(SecurityContext context) {
Authentication authentication = context.getAuthentication();
if (authentication instanceof JwtAuthenticationToken jwtToken) {
Jwt jwt = jwtToken.getToken();
String[] microcksGroups = new String[] {};
if (jwt.hasClaim(MICROCKS... | @Test
void testMap() {
// UserInfo mapper to test.
KeycloakTokenToUserInfoMapper mapper = new KeycloakTokenToUserInfoMapper();
// Prepare a Security Context.
MicrocksJwtConverter converter = new MicrocksJwtConverter();
Jwt jwt = null;
try {
JWT parsedJwt = JWTParser.par... |
@GetInitialRestriction
public OffsetRange initialRestriction(@Element KafkaSourceDescriptor kafkaSourceDescriptor) {
Map<String, Object> updatedConsumerConfig =
overrideBootstrapServersConfig(consumerConfig, kafkaSourceDescriptor);
TopicPartition partition = kafkaSourceDescriptor.getTopicPartition();
... | @Test
public void testInitialRestrictionWhenHasStartOffset() throws Exception {
long expectedStartOffset = 10L;
consumer.setStartOffsetForTime(15L, Instant.now());
consumer.setCurrentPos(5L);
OffsetRange result =
dofnInstance.initialRestriction(
KafkaSourceDescriptor.of(
... |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithClasspathResourceSelector() {
DiscoverySelector resource = selectClasspathResource("io/cucumber/junit/platform/engine/single.feature");
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(discoveryRequest, testDescri... |
public static <T> RetryOperator<T> of(Retry retry) {
return new RetryOperator<>(retry);
} | @Test
public void retryOnResultUsingMono() {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(10))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
given(helloWorldService... |
public MetricDto setKey(String key) {
this.kee = checkMetricKey(key);
return this;
} | @Test
void fail_if_key_longer_than_64_characters() {
String a65 = repeat("a", 65);
assertThatThrownBy(() -> underTest.setKey(a65))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Metric key length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided.");
} |
@Override
public byte[] serialize() {
int length;
if (this.dataOffset == 0) {
this.dataOffset = 5; // default header length
}
length = this.dataOffset << 2;
byte[] payloadData = null;
if (this.payload != null) {
this.payload.setParent(this);
... | @Test
public void testSerialize() {
TCP tcp = new TCP();
tcp.setSourcePort(0x50);
tcp.setDestinationPort(0x60);
tcp.setSequence(0x10);
tcp.setAcknowledge(0x20);
tcp.setDataOffset((byte) 0x5);
tcp.setFlags((short) 0x2);
tcp.setWindowSize((short) 0x1000)... |
public void create(int nodes, int expectedShortcuts) {
if (nodeCount >= 0)
throw new IllegalStateException("CHStorage can only be created once");
if (nodes < 0)
throw new IllegalStateException("CHStorage must be created with a positive number of nodes");
nodesCH.create((l... | @Test
public void testLargeNodeA() {
int nodeA = Integer.MAX_VALUE;
RAMIntDataAccess access = new RAMIntDataAccess("", "", false, -1);
access.create(1000);
access.setInt(0, nodeA << 1 | 1 & PrepareEncoder.getScFwdDir());
assertTrue(access.getInt(0) < 0);
assertEquals(... |
@Override
public void execute(EventNotificationContext ctx) throws EventNotificationException {
final TeamsEventNotificationConfig config = (TeamsEventNotificationConfig) ctx.notificationConfig();
LOG.debug("TeamsEventNotification backlog size in method execute is [{}]", config.backlogSize());
... | @Test(expected = EventNotificationException.class)
public void executeWithInvalidWebhookUrl() throws EventNotificationException {
givenGoodNotificationService();
givenTeamsClientThrowsPermException();
//when execute is called with a invalid webhook URL, we expect a event notification excepti... |
@Override
public boolean isFinished()
{
return finishing && outputPage == null;
} | @Test(dataProvider = "hashEnabledValues")
public void testProbeSideNulls(boolean hashEnabled)
{
DriverContext driverContext = taskContext.addPipelineContext(0, true, true, false).addDriverContext();
// build
OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanN... |
protected SuppressionRules rules() {
return rules;
} | @Test
public void addAnnotationRule() {
final String key1 = "key1", key2 = "key2";
final String value1 = "value1";
Map<String, String> annotation = new HashMap<>();
annotation.put(key1, value1);
cfg.annotation(annotation);
configEvent(NetworkConfigEvent.Type.CONFIG... |
@WorkerThread
@Override
public Unit call()
throws IOException,
StreamNotFoundException,
ShellNotRunningException,
IllegalArgumentException {
OutputStream outputStream;
File destFile = null;
switch (fileAbstraction.scheme) {
case CONTENT:
Objects.require... | @Test
public void testWriteFileOverwriting()
throws IOException, StreamNotFoundException, ShellNotRunningException {
File file = new File(Environment.getExternalStorageDirectory(), "test.txt");
IoUtils.copy(new StringReader("Dummy test content"), new FileWriter(file), 1024);
Uri uri = Uri.fromFile(f... |
@Nonnull @Override
public ProgressState call() {
progTracker.reset();
stateMachineStep();
return progTracker.toProgressState();
} | @Test
public void when_doneItemOnInput_then_eventuallyDone() {
// When
init(singletonList(DONE_ITEM));
// Then
assertEquals(DONE, sst.call());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.