focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testNameIsReplacedOnMatch() throws Exception {
new JmxCollector(
"\n---\nrules:\n- pattern: `^hadoop<service=DataNode, name=DataNodeActivity-ams-hdd001-50010><>replaceBlockOpMinTime:`\n name: foo"
.replace('`', '"'))
... |
@Override
public GenericRow transform(GenericRow record) {
try {
GenericRow originalRow = _fieldsToUnnest.isEmpty() ? null : record.copy(_fieldsToUnnest);
flattenMap(record, new ArrayList<>(record.getFieldToValueMap().keySet()));
for (String field : _fieldsToUnnest) {
unnestCollection(re... | @Test
public void testPrefixesToRename() {
HashMap<String, String> prefixesToRename = new HashMap<>();
prefixesToRename.put("map1.", "");
prefixesToRename.put("map2", "test");
ComplexTypeTransformer transformer = new ComplexTypeTransformer(new ArrayList<>(), ".",
DEFAULT_COLLECTION_TO_JSON_MOD... |
@Override
public AppSettings load() {
Properties p = loadPropertiesFile(homeDir);
Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey)
.collect(Collectors.toSet());
keysOverridableFromEnv.addAll(p.stringPropertyNames());
// 1st... | @Test
public void command_line_arguments_take_precedence_over_env_vars() throws Exception {
when(system.getenv()).thenReturn(ImmutableMap.of("SONAR_CUSTOMPROP", "11"));
when(system.getenv("SONAR_CUSTOMPROP")).thenReturn("11");
File homeDir = temp.newFolder();
File propsFile = new File(homeDir, "conf/s... |
public Offloaders getOrLoadOffloaders(String offloadersPath, String narExtractionDirectory) {
return loadedOffloaders.computeIfAbsent(offloadersPath,
(directory) -> {
try {
return OffloaderUtils.searchForOffloaders(directory, narExtractionDirectory);
... | @Test
public void testLoadsOnlyOnce() throws Exception {
Offloaders expectedOffloaders = new Offloaders();
try (MockedStatic<OffloaderUtils> offloaderUtils = Mockito.mockStatic(OffloaderUtils.class)) {
offloaderUtils.when(() -> OffloaderUtils.searchForOffloaders(eq("./offloaders"), eq("... |
@Override
public <Request extends RequestCommand> boolean deserializeContent(Request request)
throws DeserializationException {
if (request instanceof RpcRequestCommand) {
RpcRequestCommand requestCommand = (RpcRequestCommand) request;
Object header = requestCommand.getReques... | @Test
public void deserializeRequestContent() {
String traceId = "traceId";
String rpcId = "rpcId";
Map<String, String> headerMap = new HashMap<>();
headerMap.put("rpc_trace_context.sofaTraceId", traceId);
headerMap.put("rpc_trace_context.sofaRpcId", rpcId);
RpcReque... |
public static boolean isX64Arch()
{
return isX64Arch(OS_ARCH);
} | @Test
@EnabledOnOs(architectures = { "x64", "x86_64", "amd64" })
void isX64ArchSystemTest()
{
assertTrue(SystemUtil.isX64Arch());
} |
protected void declareRule(final KiePMMLDroolsRule rule) {
logger.trace("declareRule {}", rule);
final RuleDescrBuilder ruleBuilder = builder.newRule().name(rule.getName());
if (rule.getAgendaGroup() != null) {
declareAgendaGroup(ruleBuilder, rule.getAgendaGroup());
}
... | @Test
void declareRule() {
String name = "NAME";
String statusToSet = "STATUS_TO_SET";
String patternType = "TEMPERATURE";
String agendaGroup = "agendaGroup";
String activationGroup = "activationGroup";
List<KiePMMLFieldOperatorValue> orConstraints = Arrays.asList(new... |
@Override
@Cacheable(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, key = "#code",
unless = "#result == null")
public NotifyTemplateDO getNotifyTemplateByCodeFromCache(String code) {
return notifyTemplateMapper.selectByCode(code);
} | @Test
public void testGetNotifyTemplateByCodeFromCache() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);
// 准备参数
String code = dbNotifyTemplate.getCode();
// 调用
NotifyTemplate... |
@Override
public Interface removeInterface(VplsData vplsData, Interface iface) {
requireNonNull(vplsData);
requireNonNull(iface);
VplsData newData = VplsData.of(vplsData);
newData.removeInterface(iface);
updateVplsStatus(newData, VplsData.VplsState.UPDATING);
return i... | @Test
public void testRemoveInterface() {
VplsData vplsData = vplsManager.createVpls(VPLS1, NONE);
vplsManager.addInterface(vplsData, V100H1);
vplsManager.addInterface(vplsData, V100H2);
vplsManager.removeInterface(vplsData, V100H1);
vplsData = vplsStore.getVpls(VPLS1);
... |
public static Properties loadProperties(Set<ClassLoader> classLoaders, String fileName) {
return loadProperties(classLoaders, fileName, false, false);
} | @Test
void testLoadPropertiesOneFile() throws Exception {
Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "properties.load", false);
Properties expected = new Properties();
expected.put("a", "12");
expected.put("b", "34");
expected.put("c", "56");
... |
@Override
public String toString() {
return HeadersUtils.toString(getClass(), iterator(), size());
} | @Test
public void testToString() {
TestDefaultHeaders headers = newInstance();
headers.add(of("name1"), of("value1"));
headers.add(of("name1"), of("value2"));
headers.add(of("name2"), of("value3"));
assertEquals("TestDefaultHeaders[name1: value1, name1: value2, name2: value3]... |
@Override
public Mono<ClientResponse> filter(ClientRequest originRequest, ExchangeFunction next) {
EnhancedPluginContext enhancedPluginContext = new EnhancedPluginContext();
EnhancedRequestContext enhancedRequestContext = EnhancedRequestContext.builder()
.httpHeaders(originRequest.headers())
.httpMethod(o... | @Test
public void testRun() throws URISyntaxException {
doReturn(new URI("http://0.0.0.0/")).when(clientRequest).url();
doReturn(new HttpHeaders()).when(clientRequest).headers();
doReturn(HttpMethod.GET).when(clientRequest).method();
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
doRet... |
public <T> T getStore(final StoreQueryParameters<T> storeQueryParameters) {
final String storeName = storeQueryParameters.storeName();
final QueryableStoreType<T> queryableStoreType = storeQueryParameters.queryableStoreType();
final List<T> globalStore = globalStoreProvider.stores(storeName, que... | @Test
public void shouldThrowExceptionWhenKVStoreWithPartitionDoesntExists() {
final int partition = numStateStorePartitions + 1;
final InvalidStateStoreException thrown = assertThrows(InvalidStateStoreException.class, () ->
storeProvider.getStore(
StoreQueryP... |
@SneakyThrows(ReflectiveOperationException.class)
public static <T extends YamlConfiguration> T unmarshal(final File yamlFile, final Class<T> classType) throws IOException {
try (BufferedReader inputStreamReader = Files.newBufferedReader(Paths.get(yamlFile.toURI()))) {
T result = new Yaml(new Sh... | @Test
void assertUnmarshalProperties() {
Properties actual = YamlEngine.unmarshal("password: pwd", Properties.class);
assertThat(actual.getProperty("password"), is("pwd"));
} |
@Override
public Table getTable(String dbName, String tblName) {
Table table;
try {
table = hmsOps.getTable(dbName, tblName);
} catch (StarRocksConnectorException e) {
LOG.error("Failed to get hive table [{}.{}.{}]", catalogName, dbName, tblName, e);
throw... | @Test
public void testGetTable() {
com.starrocks.catalog.Table table = hiveMetadata.getTable("db1", "tbl1");
HiveTable hiveTable = (HiveTable) table;
Assert.assertEquals("db1", hiveTable.getDbName());
Assert.assertEquals("tbl1", hiveTable.getTableName());
Assert.assertEquals(... |
@SuppressWarnings("unchecked")
public static List<Object> asList(final Object key) {
final Optional<Windowed<Object>> windowed = key instanceof Windowed
? Optional.of((Windowed<Object>) key)
: Optional.empty();
final Object naturalKey = windowed
.map(Windowed::key)
.orElse(key... | @Test
public void shouldConvertNonWindowedKeyToList() {
// Given:
final GenericKey key = GenericKey.genericKey(10);
// When:
final List<?> result = KeyUtil.asList(key);
// Then:
assertThat(result, is(ImmutableList.of(10)));
} |
public static KafkaLogCollectClient getKafkaLogCollectClient() {
return KAFKA_LOG_COLLECT_CLIENT;
} | @Test
public void testGetKafkaLogCollectClient() {
Assertions.assertEquals(LoggingKafkaPluginDataHandler.getKafkaLogCollectClient().getClass(), KafkaLogCollectClient.class);
} |
@Override
public SubscriptionType getSubscriptionType() {
return subscriptionType;
} | @Test
public void testGetSubscriptionType() {
SinkContext ctx = context;
// make sure SinkContext can get SubscriptionType.
Assert.assertEquals(ctx.getSubscriptionType(), SubscriptionType.Shared);
} |
public String getMethod(){
return method;
} | @Test
public void testRepeatedArguments() throws Exception {
String url = "http://localhost/matrix.html";
// A HTTP GET request
String contentEncoding = "UTF-8";
String testGetRequest =
"GET " + url
+ "?update=yes&d=1&d=2&d=&d=&d=&d=&d=&d=1&d=2&d=1&d=&d= "
... |
public static void unzip(Path archive, Path destination) throws IOException {
unzip(archive, destination, false);
} | @Test
public void testUnzip() throws URISyntaxException, IOException {
verifyUnzip(tempFolder.getRoot().toPath());
} |
@Override
public String getType() {
return type;
} | @Test
public void testType() {
Assert.assertEquals(getExpectedType(), handler.getType());
} |
static void checkValidTableId(String idToCheck) {
if (idToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table ID " + idToCheck + " cannot be empty.");
}
if (idToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table ID "
... | @Test
public void testCheckValidTableIdWhenIdIsTooLong() {
assertThrows(
IllegalArgumentException.class,
() -> checkValidTableId("really-really-really-really-long-table-id"));
} |
public void changeFieldType(final CustomFieldMapping customMapping,
final Set<String> indexSetsIds,
final boolean rotateImmediately) {
checkFieldTypeCanBeChanged(customMapping.fieldName());
checkType(customMapping);
checkAllIndicesS... | @Test
void testSavesIndexSetWithNewMappingAndPreviousMappings() {
doReturn(Optional.of(existingIndexSet)).when(indexSetService).get("existing_index_set");
toTest.changeFieldType(newCustomMapping,
Set.of("existing_index_set"),
false);
verify(mongoIndexSetServi... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void test_get_bad_double() {
Settings settings = new MapSettings();
settings.setProperty("foo", "bar");
assertThatThrownBy(() -> settings.getDouble("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'foo' is not a double value");
} |
protected TaskConfig buildTaskConfig(TaskConfig config) {
TaskConfig taskExecConfig = new TaskConfig();
for (Property property : config.list()) {
taskExecConfig.add(getExecProperty(config, property));
}
return taskExecConfig;
} | @Test
public void shouldReturnDefaultValueInExecConfigWhenConfigValueIsEmptyString() {
TaskConfig defaultTaskConfig = new TaskConfig();
String propertyName = "URL";
String defaultValue = "ABC.TXT";
Map<String, Map<String, String>> configMap = new HashMap<>();
HashMap<String,... |
public static UDoWhileLoop create(UStatement body, UExpression condition) {
return new AutoValue_UDoWhileLoop((USimpleStatement) body, condition);
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UDoWhileLoop.create(
UBlock.create(
UExpressionStatement.create(
UAssign.create(
ULocalVarIdent.create("old"),
UMethodInvocation.crea... |
public static PTransformMatcher classEqualTo(Class<? extends PTransform> clazz) {
return new EqualClassPTransformMatcher(clazz);
} | @Test
public void classEqualToMatchesSameClass() {
PTransformMatcher matcher = PTransformMatchers.classEqualTo(ParDo.SingleOutput.class);
AppliedPTransform<?, ?, ?> application =
getAppliedTransform(
ParDo.of(
new DoFn<KV<String, Integer>, Integer>() {
@Pr... |
@Override
public AppResponse process(Flow flow, AppRequest params) {
var result = digidClient.getWidstatus(appSession.getWidRequestId());
switch(result.get("status").toString()){
case "NO_DOCUMENTS":
appSession.setRdaSessionStatus("NO_DOCUMENTS");
appSess... | @Test
void processWidstatusPending(){
when(digidClientMock.getWidstatus(mockedAppSession.getWidRequestId())).thenReturn(invalidDigidClientResponsePending);
AppResponse appResponse = rdaPolling.process(mockedFlow, mockedAbstractAppRequest);
assertEquals("PENDING", ((StatusResponse)appRespon... |
@Override
public ValidationResult validate(Object value) {
ValidationResult result = super.validate(value);
if (result instanceof ValidationResult.ValidationPassed) {
final String sValue = (String) value;
if (sValue != null && sValue.length() > maxLength) {
r... | @Test
public void testValidateNullValue() {
assertThat(new LimitedOptionalStringValidator(1).validate(null))
.isInstanceOf(ValidationResult.ValidationPassed.class);
} |
static boolean isUserDefinedRealTask(Task task) {
return isUserDefinedTask(task) && isRealTask(task);
} | @Test
public void testIsUserDefinedRealTask() {
when(task.getTaskType()).thenReturn(Constants.MAESTRO_TASK_NAME);
when(task.getSeq()).thenReturn(1);
Assert.assertTrue(TaskHelper.isUserDefinedRealTask(task));
when(task.getTaskType()).thenReturn("TEST_TASK");
Assert.assertFalse(TaskHelper.isUserDefi... |
public void decode(ByteBuf buffer) {
boolean last;
int statusCode;
while (true) {
switch(state) {
case READ_COMMON_HEADER:
if (buffer.readableBytes() < SPDY_HEADER_SIZE) {
return;
}
... | @Test
public void testInvalidSpdySynReplyFrameLength() throws Exception {
short type = 2;
byte flags = 0;
int length = 0; // invalid length
ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length);
encodeControlFrameHeader(buf, type, flags, length);
decoder.decode(b... |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void shouldMatchFixedStage() {
NotificationFilter filter = new NotificationFilter("cruise", "dev", StageEvent.Fixed, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise", "dev"), StageEvent.Fixed)).isTrue();
} |
@Override
public void process(String host, String value, ApplicationId applicationId,
ApplicationSubmissionContext submissionContext) {
submissionContext.setNodeLabelExpression(value);
} | @Test
public void testNodeLabelProcessor() {
ContextProcessor nodeLabelProcessor = new NodeLabelProcessor();
ApplicationId app = ApplicationId.newInstance(123456, 111);
ApplicationSubmissionContext applicationSubmissionContext =
mock(ApplicationSubmissionContext.class);
when(applicationSubmiss... |
public void processTimeout() {
// this is only for jobs which transaction is not started.
// if transaction is started, global transaction manager will handle the timeout.
writeLock();
try {
if (state != JobState.PENDING) {
return;
}
i... | @Test
public void testProcessTimeout(@Mocked GlobalStateMgr globalStateMgr, @Mocked EditLog editLog) {
LoadJob loadJob = new BrokerLoadJob();
Deencapsulation.setField(loadJob, "timeoutSecond", 0);
new Expectations() {
{
globalStateMgr.getEditLog();
... |
@SuppressWarnings("deprecation")
File convertToFile(URL url) {
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
return new File(URLDecoder.decode(url.getFile()));
} else {
addInfo("URL [" + url + "] is not of type file");
return null;
}
} | @Test
// See http://jira.qos.ch/browse/LBCORE-119
public void fileToURLAndBack() throws MalformedURLException {
File file = new File("a b.xml");
URL url = file.toURI().toURL();
ConfigurationWatchList cwl = new ConfigurationWatchList();
File back = cwl.convertToFile(url);
assertEquals(file.getNam... |
boolean dropSession(final String clientId, boolean removeSessionState) {
LOG.debug("Disconnecting client: {}", clientId);
if (clientId == null) {
return false;
}
final Session client = pool.get(clientId);
if (client == null) {
LOG.debug("Client {} not fou... | @Test
public void testDropSessionWithNullClientId() {
assertFalse(sut.dropSession(null, ANY_BOOLEAN), "Can't be successful when null clientId is passed");
} |
@Override
public void destroy() {
if (this.sqsClient != null) {
try {
this.sqsClient.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown SQS client during destroy()", e);
}
}
} | @Test
void givenSqsClientIsNull_whenDestroy_thenVerifyNoInteractions() {
ReflectionTestUtils.setField(node, "sqsClient", null);
node.destroy();
then(sqsClientMock).shouldHaveNoInteractions();
} |
@Override
public String getMethod() {
return PATH;
} | @Test
public void testGetChatMenuButtonAsWebApp() {
SetChatMenuButton setChatMenuButton = SetChatMenuButton
.builder()
.chatId("123456")
.menuButton(MenuButtonWebApp
.builder()
.text("Web app text")
... |
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testWriteMessageWithRetryPolicyReachesLimit() throws Exception {
String messageText = "text";
int maxPublicationAttempts = 2;
List<String> data = Collections.singletonList(messageText);
RetryConfiguration retryConfiguration =
RetryConfiguration.create(maxPublicationAttempts, ... |
public void runPickle(Pickle pickle) {
try {
StepTypeRegistry stepTypeRegistry = createTypeRegistryForPickle(pickle);
snippetGenerators = createSnippetGeneratorsForPickle(stepTypeRegistry);
// Java8 step definitions will be added to the glue here
buildBackendWorl... | @Test
void scenario_hooks_not_executed_for_empty_pickles() {
HookDefinition beforeHook = createHook();
HookDefinition afterHook = createHook();
HookDefinition beforeStepHook = createHook();
HookDefinition afterStepHook = createHook();
TestRunnerSupplier runnerSupplier = new ... |
public static NetworkInterface findNetworkInterface() {
List<NetworkInterface> validNetworkInterfaces = emptyList();
try {
validNetworkInterfaces = getValidNetworkInterfaces();
} catch (Throwable e) {
logger.warn(e);
}
NetworkInterface result = null;
... | @Test
void testIgnoreAllInterfaces() {
// store the origin ignored interfaces
String originIgnoredInterfaces = this.getIgnoredInterfaces();
try {
// ignore all interfaces
this.setIgnoredInterfaces(".*");
assertNull(NetUtils.findNetworkInterface());
... |
@Override
public void validate(final Host bookmark, final LoginCallback prompt, final LoginOptions options) throws ConnectionCanceledException, LoginFailureException {
if(log.isDebugEnabled()) {
log.debug(String.format("Validate login credentials for %s", bookmark));
}
final Cred... | @Test
public void testFindPasswordSftp() throws Exception {
final AtomicBoolean keychain = new AtomicBoolean(false);
KeychainLoginService l = new KeychainLoginService(new DisabledPasswordStore() {
@Override
public String findLoginPassword(final Host bookmark) {
... |
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + (this.qualifyingNames != null ? this.qualifyingNames.hashCode() : 0);
hash = 97 * hash + (this.resultType != null ? this.resultType.toString().hashCode() : 0);
return hash;
} | @Test
public void testHashCodeWithNullQualifyingNames() {
TypeMirror resultType = new TestTypeMirror( "someType" );
SelectionParameters params = new SelectionParameters( null, null, resultType, null );
assertThat( params.hashCode() )
.as( "QualifyingNames null hashCode" )
... |
@SuppressWarnings("unchecked")
public static <T extends Message> T newMessageByJavaClassName(final String className, final byte[] bs) {
final MethodHandle handle = PARSE_METHODS_4J.get(className);
if (handle == null) {
throw new MessageClassNotFoundException(className + " not found");
... | @Test
public void testNewMessageByJavaClassName() {
SnapshotMeta meta = SnapshotMeta.newBuilder().setLastIncludedIndex(99).setLastIncludedTerm(1).build();
SnapshotMeta pMeta = ProtobufMsgFactory
.newMessageByJavaClassName(meta.getClass().getName(), meta.toByteArray());
assertNotN... |
@Override
public ValidationResult validate(Object value) {
if (value == null || value instanceof String) {
return new ValidationResult.ValidationPassed();
} else {
return new ValidationResult.ValidationFailed("Value \"" + value + "\" is not a valid string!");
}
} | @Test
public void validateString() {
assertThat(validator.validate("foobar")).isInstanceOf(ValidationResult.ValidationPassed.class);
} |
public static NamespaceName get(String tenant, String namespace) {
validateNamespaceName(tenant, namespace);
return get(tenant + '/' + namespace);
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void namespace_nullTenant2() {
NamespaceName.get(null, "cluster", "namespace");
} |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void overridesArrayPropertiesWithIndices() throws Exception {
System.setProperty("dw.servers[0].port", "7000");
System.setProperty("dw.servers[2].port", "9000");
final Example example = factory.build(configurationSourceProvider, validFile);
assertThat(example.getServers())
... |
static ClockImpl createClock() {
String clockImplClassName = System.getProperty(ClockProperties.HAZELCAST_CLOCK_IMPL);
if (clockImplClassName != null) {
try {
return ClassLoaderUtil.newInstance(null, clockImplClassName);
} catch (Exception e) {
thr... | @Test
public void testCreateClock_withClockOffset() {
setClockOffset(30);
Clock.ClockImpl clock = Clock.createClock();
assertInstanceOf(Clock.SystemOffsetClock.class, clock);
} |
public static boolean startsWithIgnoreCase(String str, String prefix) {
if (str == null || prefix == null || str.length() < prefix.length()) {
return false;
}
// return str.substring(0, prefix.length()).equalsIgnoreCase(prefix);
return str.regionMatches(true, 0, prefix, 0, pr... | @Test
void testStartsWithIgnoreCase() {
assertTrue(startsWithIgnoreCase("dubbo.application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("dubbo.Application.name", "dubbo.application."));
assertTrue(startsWithIgnoreCase("Dubbo.application.name", "dubbo.application."));
} |
public static ExecuteEnv getInstance() {
return INSTANCE;
} | @Test
public void testGetInstance() {
Set<Thread> tds = new HashSet<Thread>();
for (int i = 0; i < THREAD_MAX_NUM; i++) {
Thread td = new Thread(new MyTest(i, oids));
tds.add(td);
td.start();
}
for (Thread td : tds) {
try {
... |
@Override
public ConfigInfoBetaWrapper findConfigInfo4Beta(final String dataId, final String group, final String tenant) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
try {
ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceSer... | @Test
void testFindConfigInfo4Beta() {
String dataId = "dataId456789";
String group = "group4567";
String tenant = "tenant56789o0";
//mock exist beta
ConfigInfoBetaWrapper mockedConfigInfoStateWrapper = new ConfigInfoBetaWrapper();
mockedConfigInfoStateWrapper.setData... |
static @NonNull CloudStringReader of(final @NonNull CommandInput commandInput) {
return new CloudStringReader(commandInput);
} | @Test
void testAllThreeWordsRead() throws CommandSyntaxException {
// Arrange
final CommandInput commandInput = CommandInput.of("hello some worlds");
final StringReader stringReader = CloudStringReader.of(commandInput);
// Act
final String readString1 = stringReader.readStri... |
@Override
public String toString() {
return String.format("ThriftMetaData(thriftClassName: %s, descriptor: %s)", thriftClassName, descriptor);
} | @Test
public void testToStringDoesNotThrow() {
StructType descriptor = new StructType(new ArrayList<ThriftField>(), StructOrUnionType.STRUCT);
ThriftMetaData tmd = new ThriftMetaData("non existent class!!!", descriptor);
assertEquals(
("ThriftMetaData(thriftClassName: non existent class!!!, descr... |
public static void checkMock(Class<?> interfaceClass, AbstractInterfaceConfig config) {
String mock = config.getMock();
if (ConfigUtils.isEmpty(mock)) {
return;
}
String normalizedMock = MockInvoker.normalizeMock(mock);
if (normalizedMock.startsWith(RETURN_PREFIX)) {... | @Test
void checkMock2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
InterfaceConfig interfaceConfig = new InterfaceConfig();
interfaceConfig.setMock(GreetingMock1.class.getName());
ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig);
... |
@Udf(description = "Returns the tangent of an INT value")
public Double tan(
@UdfParameter(
value = "value",
description = "The value in radians to get the tangent of."
) final Integer value
) {
return tan(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.tan(-9.1), closeTo(0.33670052643287396, 0.000000000000001));
assertThat(udf.tan(-6.3), closeTo(-0.016816277694182057, 0.000000000000001));
assertThat(udf.tan(-7), closeTo(-0.8714479827243188, 0.000000000000001));
assertThat(udf.tan(-... |
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, CreateDownloadShareRequest options, final PasswordCallback callback) throws BackgroundException {
try {
if(log.isDebugEnabled()) {
log.debug(String.format("Create download share for %s", file));
... | @Test(expected = InteroperabilityException.class)
public void testToUrlMissingEmailRecipients() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(new AlphanumericRandomStringService().random()... |
@Override
public void setDebugMode(DebugMode debugMode) {
} | @Test
public void setDebugMode() {
mSensorsAPI.setDebugMode(SensorsDataAPI.DebugMode.DEBUG_OFF);
Assert.assertFalse(SALog.isDebug());
} |
public ProtocolBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
} | @Test
void dispatcher() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.dispatcher("mockdispatcher");
Assertions.assertEquals("mockdispatcher", builder.build().getDispatcher());
} |
public long residentMemorySizeEstimate() {
long size = 0;
size += Long.BYTES; // value.context.timestamp
size += Long.BYTES; // value.context.offset
if (topic != null) {
size += topic.toCharArray().length;
}
size += Integer.BYTES; // partition
for (fin... | @Test
public void shouldEstimateTopicLength() {
final ProcessorRecordContext context = new ProcessorRecordContext(
42L,
73L,
0,
"topic",
new RecordHeaders()
);
assertEquals(MIN_SIZE + 5L, context.residentMemorySizeEstimate());
... |
@Override
public CompletableFuture<Void> deregisterApplication(
final ApplicationStatus applicationStatus, final @Nullable String diagnostics) {
synchronized (lock) {
if (!running || leaderResourceManager == null) {
return deregisterWithoutLeaderRm();
}
... | @Test
void deregisterApplication_noLeaderRm() throws Exception {
createAndStartResourceManager();
final CompletableFuture<Void> deregisterApplicationFuture =
resourceManagerService.deregisterApplication(ApplicationStatus.CANCELED, null);
// should not report error
as... |
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
if (null == source) {
return null;
}
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
} | @Test
public void copyPropertiesMapToMapTest() {
// 测试MapToMap
final Map<String, Object> p1 = new HashMap<>();
p1.put("isSlow", true);
p1.put("name", "测试");
p1.put("subName", "sub测试");
final Map<String, Object> map = MapUtil.newHashMap();
BeanUtil.copyProperties(p1, map);
assertTrue((Boolean) map.get(... |
public void setLocalMode(boolean localMode) {
if (localMode) {
addCapability(Capability.LOCALMODE);
} else {
removeCapability(Capability.LOCALMODE);
}
} | @Test
public void testSetLocalMode() throws Exception {
status.setLocalMode(false);
assertFalse(status.hasCapability(ServerStatus.Capability.LOCALMODE));
status.setLocalMode(true);
assertTrue(status.hasCapability(ServerStatus.Capability.LOCALMODE));
} |
@Override
public void run(DiagnosticsLogWriter writer) {
metricCollector.writer = writer;
// we set the time explicitly so that for this particular rendering of the probes, all metrics have exactly
// the same timestamp
metricCollector.timeMillis = System.currentTimeMillis();
... | @Test
public void testExclusion() {
metricsRegistry.registerStaticMetrics(new ExclusionProbeSource(), "test");
plugin.run(logWriter);
assertContains("[unit=count,metric=test.notExcludedLong]=1");
assertNotContains("[unit=count,metric=test.excludedLong]=1");
assertContains("... |
@Override
public InputFile newInputFile(String path) {
return new CachingInputFile(fileContentCache, wrappedIO.newInputFile(path));
} | @Test
public void testNewInputFile() {
writeIcebergMetaTestFile();
String path = "file:/tmp/0001.metadata.json";
// create iceberg cachingFileIO
IcebergCachingFileIO cachingFileIO = new IcebergCachingFileIO();
cachingFileIO.setConf(new Configuration());
Map<String, S... |
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
} | @Test(expected = EncodingException.class)
public void testParseInvalidWeight() {
MediaType.fromString("application/json ; q=high");
} |
boolean isContentExpected() {
return this.equals(DATA);
} | @Test
public void isContentExpected() {
assertTrue(SmtpCommand.valueOf("DATA").isContentExpected());
assertTrue(SmtpCommand.valueOf("data").isContentExpected());
assertFalse(SmtpCommand.HELO.isContentExpected());
assertFalse(SmtpCommand.HELP.isContentExpected());
assertFalse... |
public List<RunResponse> startBatch(
String workflowId, String version, List<RunRequest> requests) {
if (ObjectHelper.isCollectionEmptyOrNull(requests)) {
return Collections.emptyList();
}
Checks.checkTrue(
requests.size() <= Constants.START_BATCH_LIMIT,
"The size of Requests is ... | @Test
public void testStartBatch() {
when(runStrategyDao.startBatchWithRunStrategy(any(), any(), any()))
.thenReturn(new int[] {1, 0});
RunRequest request =
RunRequest.builder()
.initiator(new ManualInitiator())
.requestId(UUID.fromString("41f0281e-41a2-468d-b830-56141b... |
public OffsetRange[] getNextOffsetRanges(Option<String> lastCheckpointStr, long sourceLimit, HoodieIngestionMetrics metrics) {
// Come up with final set of OffsetRanges to read (account for new partitions, limit number of events)
long maxEventsToReadFromKafka = getLongWithAltKeys(props, KafkaSourceConfig.MAX_EV... | @Test
public void testGetNextOffsetRangesFromTimestampCheckpointType() {
HoodieTestDataGenerator dataGenerator = new HoodieTestDataGenerator();
testUtils.createTopic(testTopicName, 1);
testUtils.sendMessages(testTopicName, Helpers.jsonifyRecords(dataGenerator.generateInserts("000", 1000)));
KafkaOffs... |
@Override
public boolean containsActiveConnection(final DataSource dataSource) {
return 0 != getActiveConnections(dataSource);
} | @Test
void assertContainsActiveConnection() throws SQLException {
DataSource dataSource = createHikariDataSource();
try (Connection ignored = dataSource.getConnection()) {
assertTrue(new HikariDataSourcePoolActiveDetector().containsActiveConnection(dataSource));
}
} |
@Override
public void deleteConfig(Long id) {
// 校验配置存在
ConfigDO config = validateConfigExists(id);
// 内置配置,不允许删除
if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) {
throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE);
}
// 删除
configMapp... | @Test
public void testDeleteConfig_canNotDeleteSystemType() {
// mock 数据
ConfigDO dbConfig = randomConfigDO(o -> {
o.setType(ConfigTypeEnum.SYSTEM.getType()); // SYSTEM 不允许删除
});
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbConfig... |
@VisibleForTesting
public void validateDictTypeExists(String type) {
DictTypeDO dictType = dictTypeService.getDictType(type);
if (dictType == null) {
throw exception(DICT_TYPE_NOT_EXISTS);
}
if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) {
... | @Test
public void testValidateDictTypeExists_notEnable() {
// mock 方法,数据类型被禁用
String dictType = randomString();
when(dictTypeService.getDictType(eq(dictType))).thenReturn(
randomPojo(DictTypeDO.class, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 调用, 并... |
public static PTransform<PCollection<?>, PCollection<String>> elements() {
return new Elements();
} | @Test
@Category(NeedsRunner.class)
public void testToStringOf() {
Integer[] ints = {1, 2, 3, 4, 5};
String[] strings = {"1", "2", "3", "4", "5"};
PCollection<Integer> input = p.apply(Create.of(Arrays.asList(ints)));
PCollection<String> output = input.apply(ToString.elements());
PAssert.that(outp... |
@Override
// The set of valid retention strategies must
// - contain only names of supported strategies
// - at least one must stay enabled
public void validate(String parameter, Set<String> values) throws ValidationException {
if (!values.stream()
.filter(s -> !VALID_STRATEGIES... | @Test
void invalidStrategy() {
assertThrows(ValidationException.class, () -> {
classUnderTest.validate(PARAM, Set.of("nonsense"));
});
} |
public static void executeWithRetry(RetryFunction function) throws Exception {
executeWithRetry(maxAttempts, minDelay, function);
} | @Test
public void retryFunctionThatFailsWithMoreAttempts() throws Exception {
exceptionRule.expect(SQLException.class);
exceptionRule.expectMessage("Problem with connection");
executeWithRetry(4, 1_000, IOITHelperTest::failingFunction);
assertEquals(4, listOfExceptionsThrown.size());
} |
public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException {
val messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")");
if (connection.getResponseMessage() != null) {
messageBuilder.append(" ");
messageBuil... | @Test
public void testBuildHttpErrorMessage() throws IOException {
// creating mock htp connection
HttpURLConnection connectionMock = null ;
// expected test data for mock connection
var testResponseBody = "{\"error_description\":\"MSIS9612: The authorization code received in [code]... |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void inputs() {
Flow flow = this.parse("flows/valids/inputs.yaml");
assertThat(flow.getInputs().size(), is(27));
assertThat(flow.getInputs().stream().filter(Input::getRequired).count(), is(9L));
assertThat(flow.getInputs().stream().filter(r -> !r.getRequired()).count(), is(18L... |
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String resourceName, BlockException ex)
throws Exception {
// Return 429 (Too Many Requests) by default.
response.setStatus(429);
PrintWriter out = response.getWriter();
out.print("Blo... | @Test
public void handle_writeBlockPage() throws Exception {
DefaultBlockExceptionHandler h = new DefaultBlockExceptionHandler();
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/a/b/c");
req.setQueryString("a=1&b=2");
MockHttpServletResponse resp = new MockHttpServle... |
public static Optional<KsqlAuthorizationValidator> create(
final KsqlConfig ksqlConfig,
final ServiceContext serviceContext,
final Optional<KsqlAuthorizationProvider> externalAuthorizationProvider
) {
final Optional<KsqlAccessValidator> accessValidator = getAccessValidator(
ksqlConfig,
... | @Test
public void shouldReturnEmptyValidatorIfKafkaBrokerVersionTooLowAndExceptionWrapped()
throws InterruptedException, ExecutionException {
// Given:
givenSingleNode();
givenAuthorizerClass("a-class");
final KafkaFuture<Set<AclOperation>> authorized = mockAuthorizedOperationsFuture();
fina... |
public Ce.Task formatActivity(DbSession dbSession, CeActivityDto dto, @Nullable String scannerContext) {
return formatActivity(dto, DtoCache.forActivityDtos(dbClient, dbSession, singletonList(dto)), scannerContext);
} | @Test
public void formatActivity_filterWarnings_andSetWarningsAndCount() {
TestActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null);
CeTaskMessageDto warning1 = createCeTaskMessageDto(1998, MessageType.GENERIC);
CeTaskMessageDto warning2 = createCeTaskMessageDto(1999,... |
@Override
public Set<ProfileDescription> find(final Visitor visitor) throws BackgroundException {
if(log.isInfoEnabled()) {
log.info(String.format("Fetch profiles from %s", session.getHost()));
}
final ProfileFilter filter = new ProfileFilter();
final AttributedList<Path>... | @Test
public void find() throws Exception {
final ProtocolFactory protocols = new ProtocolFactory(new HashSet<>(Arrays.asList(new TestProtocol() {
@Override
public String getIdentifier() {
return "s3";
}
@Override
public Type getTy... |
@Override
public Connection getConnection(Properties properties, String connectionString, SSLContextSettings sslContextSettings) {
try {
RestClientConfigurationBuilder builder = new RestClientConfigurationBuilder().withProperties(properties);
if (connectionString == null || connectionString.i... | @Test
public void testUrlWithSSL() throws NoSuchAlgorithmException {
RestConnector connector = new RestConnector();
RestConnection connection = (RestConnection) connector.getConnection(new Properties(),"https://localhost", null);
RestClientConfigurationBuilder builder = connection.getBuilder();
... |
protected boolean fastpath() {
return false;
} | @Test(dataProvider = "caches")
@CacheSpec(compute = Compute.SYNC, population = Population.EMPTY,
maximumSize = Maximum.FULL, weigher = CacheWeigher.DISABLED,
expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED,
expiry = CacheExpiry.DISABLED, keys = ReferenceType.STRONG, values = ... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test(description = "Responses with array schema")
public void testTicket2763() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(Ticket2763Resource.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /array:\n" +
... |
protected void updateHost(MacAddress mac, VlanId vlan, Set<HostLocation> locations, Set<IpAddress> ips) {
HostId hid = HostId.hostId(mac, vlan);
HostDescription desc = new DefaultHostDescription(mac, vlan, locations, ips, true);
providerService.hostDetected(hid, desc, true);
} | @Test
public void testUpdateHost() throws Exception {
provider.updateHost(mac, vlan, locations, auxLocations, ips, innerVlan, outerTpid);
assertThat(providerService.hostId, is(hostId));
assertThat(providerService.hostDescription, is(hostDescription));
assertThat(providerService.event... |
@VisibleForTesting()
void checkDiskUsage() {
final Map<Notification.Type, List<String>> notificationTypePerNodeIdentifier = new HashMap<>();
try {
ClusterAllocationDiskSettings settings = cluster.getClusterAllocationDiskSettings();
if (settings.ThresholdEnabled()) {
... | @Test
public void fixAllDiskUsageNotificationsPercentage() throws Exception {
Set<NodeDiskUsageStats> nodeDiskUsageStats = mockNodeDiskUsageStats();
when(cluster.getDiskUsageStats()).thenReturn(nodeDiskUsageStats);
when(cluster.getClusterAllocationDiskSettings()).thenReturn(buildThresholdNot... |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldSelectFirstElementOfOne() {
// When:
final String el = elt.elt(1, "a");
// Then:
assertThat(el, equalTo("a"));
} |
@Override
public File getScannerEngine() {
File scannerDir = new File(fs.getHomeDir(), "lib/scanner");
if (!scannerDir.exists()) {
throw new NotFoundException(format("Scanner directory not found: %s", scannerDir.getAbsolutePath()));
}
return listFiles(scannerDir, VISIBLE, directoryFileFilter())
... | @Test
void getScannerEngine_shouldFail_whenScannerDirNotFound() throws IOException {
deleteIfExists(scannerDir);
assertThatThrownBy(() -> scannerEngineHandler.getScannerEngine())
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Scanner directory not found: %s", scannerDir.toAbsolutePath(... |
@Override
public AppResponse process(Flow flow, AppSessionRequest request) {
if (appSession.getRegistrationId() == null) {
return new NokResponse();
}
Map<String, String> result = digidClient.getExistingAccount(appSession.getRegistrationId(), appSession.getLanguage());
... | @Test
void processOKTest(){
when(digidClientMock.getExistingAccount(1337L, "NL")).thenReturn(Map.of(
lowerUnderscore(STATUS), "OK",
lowerUnderscore(ACCOUNT_ID), "1"
));
AppResponse appResponse = checkExistingAccount.process(flowMock, null);
assertEquals(1, c... |
@Override
public void consume(Update update) {
super.consume(update);
} | @Test
void canProcessChannelPosts() {
Update update = mock(Update.class);
Message message = mock(Message.class);
when(message.getChatId()).thenReturn(1L);
when(update.getChannelPost()).thenReturn(message);
when(update.hasChannelPost()).thenReturn(true);
bot.consume(update);
String expec... |
@Override
public Response request(Request request, long timeouts) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
Payload grpcResponse;
try {
if (timeouts <= 0)... | @Test
void testRequestSuccessAsync() throws NacosException {
Response response = connection.request(new HealthCheckRequest(), 100);
assertTrue(response instanceof HealthCheckResponse);
} |
public MetadataReportBuilder retryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
return getThis();
} | @Test
void retryTimes() {
MetadataReportBuilder builder = new MetadataReportBuilder();
builder.retryTimes(1);
Assertions.assertEquals(1, builder.build().getRetryTimes());
} |
@Nullable
public static Extractor getExtractorInstance(
@NonNull Context context,
@NonNull File file,
@NonNull String outputPath,
@NonNull Extractor.OnUpdate listener,
@NonNull UpdatePosition updatePosition) {
Extractor extractor;
String type = getExtension(file.getPath());
... | @Test
public void getExtractorInstance() {
UpdatePosition updatePosition = ServiceWatcherUtil.UPDATE_POSITION;
File file = new File("/test/test.zip"); // .zip used by ZipExtractor
Extractor result =
CompressedHelper.getExtractorInstance(
context, file, "/test2", emptyUpdateListener, u... |
@Nonnull
public static String removeBracketsFromIpv6Address(@Nonnull final String address)
{
final String result;
if (address.startsWith("[") && address.endsWith("]")) {
result = address.substring(1, address.length()-1);
try {
Ipv6.parse(result);
... | @Test
public void stripBracketsNonIPNoBrackets() throws Exception {
// Setup test fixture.
final String input = "Foo Bar";
// Execute system under test.
final String result = AuthCheckFilter.removeBracketsFromIpv6Address(input);
// Verify result.
assertEquals(input,... |
public static boolean toBoolean(final Literal literal, final String propertyName) {
final String value = literal.getValue().toString();
final boolean isTrue = value.equalsIgnoreCase("true");
final boolean isFalse = value.equalsIgnoreCase("false");
if (!isTrue && !isFalse) {
throw new KsqlException... | @Test
public void shouldThrowConvertingOtherLiteralTypesToBoolean() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> LiteralUtil.toBoolean(new LongLiteral(10), "bob")
);
// Then:
assertThat(e.getMessage(), containsString("Property 'bob' is not a boolean valu... |
public long asHz() {
return frequency;
} | @Test
public void testasHz() {
Frequency frequency = Frequency.ofKHz(1);
assertThat(frequency.asHz(), is(1000L));
} |
@Override
public Num calculate(BarSeries series, Position position) {
Num profitLossRatio = profitLossRatioCriterion.calculate(series, position);
Num numberOfPositions = numberOfPositionsCriterion.calculate(series, position);
Num numberOfWinningPositions = numberOfWinningPositionsCriterion.c... | @Test
public void calculateWithMixedPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 110, 80, 130, 150, 160);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, series));... |
@ScalarOperator(LESS_THAN_OR_EQUAL)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThanOrEqual(@SqlType(StandardTypes.SMALLINT) long left, @SqlType(StandardTypes.SMALLINT) long right)
{
return left <= right;
} | @Test
public void testLessThanOrEqual()
{
assertFunction("SMALLINT'37' <= SMALLINT'37'", BOOLEAN, true);
assertFunction("SMALLINT'37' <= SMALLINT'17'", BOOLEAN, false);
assertFunction("SMALLINT'17' <= SMALLINT'37'", BOOLEAN, true);
assertFunction("SMALLINT'17' <= SMALLINT'17'", B... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longlivedLightPortalController() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("stevehu@gmail.com", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("portal.r", "portal.w"), "user CtlPltAdmin CtlPltRead CtlPltWrite");
claims.setExpirationTimeMinute... |
@VisibleForTesting
public NotifyTemplateDO validateNotifyTemplate(String templateCode) {
// 获得站内信模板。考虑到效率,从缓存中获取
NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode);
// 站内信模板不存在
if (template == null) {
throw exception(NOTICE_NO... | @Test
public void testCheckMailTemplateValid_notExists() {
// 准备参数
String templateCode = randomString();
// mock 方法
// 调用,并断言异常
assertServiceException(() -> notifySendService.validateNotifyTemplate(templateCode),
NOTICE_NOT_FOUND);
} |
@Override
public void awaitTerminated() throws InterruptedException {
doAction(Executable::awaitTerminated);
} | @Test
public void shouldJoinAll() throws Exception {
// When:
multiExecutable.awaitTerminated();
// Then:
final InOrder inOrder = Mockito.inOrder(executable1, executable2);
inOrder.verify(executable1).awaitTerminated();
inOrder.verify(executable2).awaitTerminated();
inOrder.verifyNoMoreIn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.