focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static InetSocketAddress parse(
final String value, final String uriParamName, final boolean isReResolution, final NameResolver nameResolver)
{
if (Strings.isEmpty(value))
{
throw new NullPointerException("input string must not be null or empty");
}
final String ... | @Test
void shouldRejectOnEmptyIpV6Port()
{
assertThrows(IllegalArgumentException.class, () -> SocketAddressParser.parse(
"[::1]:", ENDPOINT_PARAM_NAME, false, DEFAULT_RESOLVER));
} |
public RemoteStorageManager storageManager() {
return remoteLogStorageManager;
} | @Test
void testGetClassLoaderAwareRemoteStorageManager() throws Exception {
ClassLoaderAwareRemoteStorageManager rsmManager = mock(ClassLoaderAwareRemoteStorageManager.class);
try (RemoteLogManager remoteLogManager =
new RemoteLogManager(config.remoteLogManagerConfig(), brokerId, logDir,... |
@Implementation
protected HttpResponse execute(
HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext)
throws HttpException, IOException {
if (FakeHttp.getFakeHttpLayer().isInterceptingHttpRequests()) {
return FakeHttp.getFakeHttpLayer()
.emulateRequest(httpHost, httpRequ... | @Test
public void shouldSupportSocketTimeoutWithExceptions() throws Exception {
FakeHttp.setDefaultHttpResponse(
new TestHttpResponse() {
@Override
public HttpParams getParams() {
HttpParams httpParams = super.getParams();
HttpConnectionParams.setSoTimeout(httpP... |
public static String computeQueryHash(String query)
{
requireNonNull(query, "query is null");
if (query.isEmpty()) {
return "";
}
byte[] queryBytes = query.getBytes(UTF_8);
long queryHash = new XxHash64().update(queryBytes).hash();
return toHexString(que... | @Test
public void testComputeQueryHashLongQuery()
{
String longQuery = "SELECT x" + repeat(",x", 500_000) + " FROM (VALUES 1,2,3,4,5) t(x)";
assertEquals(computeQueryHash(longQuery), "26691c4d35d09c7b");
} |
@Override
public Response toResponse(final IllegalStateException exception) {
final String message = exception.getMessage();
if (LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR().equals(message)) {
/*
* If a POST request contains a Content-Type that is not application/x-... | @Test
void delegatesToParentClass() {
@SuppressWarnings("serial")
final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {
});
assertThat(reponse.getStatusInfo()).isEqualTo(INTERNAL_SERVER_ERROR);
} |
public static String generateServerId() {
return UUID.randomUUID().toString();
} | @Test
public void testGenerateServerId() {
String id = Tools.generateServerId();
/*
* Make sure it has dashes in it. We need that to build a short ID later.
* Short version: Everything falls apart if this is not an UUID-style ID.
*/
assertTrue(id.contains("-"));
... |
@Override
public Table getTable(String dbName, String tblName) {
JDBCTableName jdbcTable = new JDBCTableName(null, dbName, tblName);
return tableInstanceCache.get(jdbcTable,
k -> {
try (Connection connection = getConnection()) {
ResultSet c... | @Test
public void testColumnTypes() {
JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource);
Table table = jdbcMetadata.getTable("test", "tbl1");
List<Column> columns = table.getColumns();
Assert.assertEquals(columns.size(), columnResult.getRowCount());
... |
public Duration computeReadTimeout(HttpRequestMessage request, int attemptNum) {
IClientConfig clientConfig = getRequestClientConfig(request);
Long originTimeout = getOriginReadTimeout();
Long requestTimeout = getRequestReadTimeout(clientConfig);
long computedTimeout;
if (origin... | @Test
void computeReadTimeout_bolth_requestLower() {
requestConfig.set(CommonClientConfigKey.ReadTimeout, 100);
originConfig.set(CommonClientConfigKey.ReadTimeout, 1000);
Duration timeout = originTimeoutManager.computeReadTimeout(request, 1);
assertEquals(100, timeout.toMillis());
... |
public static DoFnInstanceManager cloningPool(DoFnInfo<?, ?> info, PipelineOptions options) {
return new ConcurrentQueueInstanceManager(info, options);
} | @Test
public void testCloningPoolReusesAfterComplete() throws Exception {
DoFnInfo<?, ?> info =
DoFnInfo.forFn(
initialFn,
WindowingStrategy.globalDefault(),
null /* side input views */,
null /* input coder */,
new TupleTag<>(PropertyNames.OUTPUT... |
@Override
public void onDiscoveredSplits(Collection<IcebergSourceSplit> splits) {
addSplits(splits);
} | @Test
public void testMultipleFilesInASplit() throws Exception {
SplitAssigner assigner = splitAssigner();
assigner.onDiscoveredSplits(
SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 4, 2));
assertGetNext(assigner, GetSplitResult.Status.AVAILABLE);
assertSnapshot(assigner,... |
@Override
public ValidationResult responseMessageForPluginSettingsValidation(String responseBody) {
return jsonResultMessageHandler.toValidationResult(responseBody);
} | @Test
public void shouldBuildValidationResultFromCheckSCMConfigurationValidResponse() throws Exception {
String responseBody = "[{\"key\":\"key-one\",\"message\":\"incorrect value\"},{\"message\":\"general error\"}]";
ValidationResult validationResult = messageHandler.responseMessageForPluginSetting... |
public void start() {
commandTopicBackup.initialize();
commandConsumer.assign(Collections.singleton(commandTopicPartition));
} | @Test
public void shouldAssignCorrectPartitionToConsumer() {
// When:
commandTopic.start();
// Then:
verify(commandConsumer)
.assign(eq(Collections.singleton(new TopicPartition(COMMAND_TOPIC_NAME, 0))));
} |
public void dropMapping(String mappingName) {
StringBuilder sb = new StringBuilder()
.append("DROP MAPPING IF EXISTS ");
DIALECT.quoteIdentifier(sb, mappingName);
sqlService.execute(sb.toString()).close();
} | @Test
public void when_dropMapping_then_quoteMappingName() {
mappingHelper.dropMapping("myMapping");
verify(sqlService).execute("DROP MAPPING IF EXISTS \"myMapping\"");
} |
public String toBaseMessageIdString(Object messageId) {
if (messageId == null) {
return null;
} else if (messageId instanceof String) {
String stringId = (String) messageId;
// If the given string has a type encoding prefix,
// we need to escape it as an ... | @Test
public void testToBaseMessageIdStringWithStringBeginningWithEncodingPrefixForString() {
String stringMessageId = AMQPMessageIdHelper.AMQP_STRING_PREFIX + "myStringId";
String expected = AMQPMessageIdHelper.AMQP_STRING_PREFIX + stringMessageId;
String baseMessageIdString = messageIdHel... |
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for eac... | @Test(expected=AclException.class)
public void testReplaceAclEntriesDuplicateEntries() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
... |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttpEntityCallable<StorageObject>(file) {
@Override
... | @Test
public void testWritePublicReadCannedPublicAcl() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
... |
public void verifyStatus() {
if (sequential) {
boolean unopenedIterator = responseIterator == null && !responses.isEmpty();
if (unopenedIterator || responseIterator.hasNext()) {
throw new VerificationAssertionError("More executions were expected");
}
}
} | @Test
void hitMock() {
List<Contributor> contributors = github.contributors("netflix", "feign");
assertThat(contributors).hasSize(30);
mockClient.verifyStatus();
} |
public static String[] getPathComponents(String path) throws InvalidPathException {
path = cleanPath(path);
if (isRoot(path)) {
return new String[]{""};
}
return path.split(AlluxioURI.SEPARATOR);
} | @Test
public void getPathComponentsException() throws InvalidPathException {
mException.expect(InvalidPathException.class);
PathUtils.getPathComponents("");
} |
@VisibleForTesting
AuthRequest buildAuthRequest(Integer socialType, Integer userType) {
// 1. 先查找默认的配置项,从 application-*.yaml 中读取
AuthRequest request = authRequestFactory.get(SocialTypeEnum.valueOfType(socialType).getSource());
Assert.notNull(request, String.format("社交平台(%d) 不存在", socialType)... | @Test
public void testBuildAuthRequest_clientDisable() {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(SocialTypeEnum.class).getType();
// mock 获得对应的 AuthRequest 实现
AuthRequest authRequest = mock(AuthDefaultRequest.class);
... |
public static <EventT> Write<EventT> write() {
return new AutoValue_JmsIO_Write.Builder<EventT>().build();
} | @Test
public void testWriteMessageWithError() throws Exception {
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < 100; i++) {
data.add("Message " + i);
}
WriteJmsResult<String> output =
pipeline
.apply(Create.of(data))
.apply(
JmsIO... |
public void validate(DataConnectionConfig dataConnectionConfig) {
int numberOfSetItems = getNumberOfSetItems(dataConnectionConfig, CLIENT_XML_PATH, CLIENT_YML_PATH, CLIENT_XML,
CLIENT_YML);
if (numberOfSetItems != 1) {
throw new HazelcastException("HazelcastDataConnection wit... | @Test
public void testValidateNone() {
DataConnectionConfig dataConnectionConfig = new DataConnectionConfig();
HazelcastDataConnectionConfigValidator validator = new HazelcastDataConnectionConfigValidator();
assertThatThrownBy(() -> validator.validate(dataConnectionConfig))
... |
@Override
public void execute(ComputationStep.Context context) {
VisitorsCrawler visitorsCrawler = new VisitorsCrawler(visitors, LOGGER.isDebugEnabled());
visitorsCrawler.visit(treeRootHolder.getRoot());
logVisitorExecutionDurations(visitors, visitorsCrawler);
} | @Test
public void execute_with_type_aware_visitor() {
ExecuteVisitorsStep underStep = new ExecuteVisitorsStep(treeRootHolder, singletonList(new TestTypeAwareVisitor()));
measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(1));
measureRepository.addRawMeasure(FILE_2_REF, NCLO... |
@Override
public void submit(Intent intent) {
checkPermission(INTENT_WRITE);
checkNotNull(intent, INTENT_NULL);
IntentData data = IntentData.submit(intent);
store.addPending(data);
} | @Ignore("skipping until we fix update ordering problem")
@Test
public void errorIntentInstallFromFlows() {
final Long id = MockIntent.nextId();
flowRuleService.setFuture(false);
MockIntent intent = new MockIntent(id);
listener.setLatch(1, Type.FAILED);
listener.setLatch(1... |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test
public void endpointsByNamespace() throws JsonProcessingException {
// given
stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsList(
pod("hazelcast-0", NAMESPACE, "node-name-1", "192.168.0.25", 5701),
pod("hazelcast-0", NAMESPACE, "node-name-1", "... |
public void createConnection() {
try {
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.initializeVariablesFrom( null );
getDatabaseDialog().setDatabaseMeta( databaseMeta );
String dbName = getDatabaseDialog().open();
if ( dbName != null ) {
dbName = dbName.trim();... | @Test
public void createConnection_NameExists() throws Exception {
final String dbName = "name";
when( databaseDialog.open() ).thenReturn( dbName );
when( databaseMeta.getDatabaseName() ).thenReturn( dbName );
when( repository.getDatabaseID( dbName ) ).thenReturn( new StringObjectId( "existing" ) );
... |
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
final DescriptiveUrl that = (DescriptiveUrl) o;
return Objects.equals(url, that.url);
} | @Test
public void testEquals() {
assertEquals(new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.provider, "a"), new DescriptiveUrl(URI.create("http://host.domain"), DescriptiveUrl.Type.provider, "b"));
assertNotEquals(new DescriptiveUrl(URI.create("http://host.domainb"), Descr... |
@Override
public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) {
String propertyTypeName = getTypeName(node);
JType type;
if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) {
type =... | @Test
public void applyGeneratesIntegerUsingJavaTypeInteger() {
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectNode objectNode = new ObjectMapper().createObjectNode();
objectNode.put("type", "integer");
objectNode.put("existingJavaType", "ja... |
@Override
public NativeEntity<LookupTableDto> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() {
final Entity entity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.LOOKUP_TABLE_V1)
.data(objectMapper.convertValue(LookupTableEntity.create(
ValueReference.of(DefaultEntityScope.NAME... |
@Override
public boolean encode(
@NonNull Resource<GifDrawable> resource, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = resource.get();
Transformation<Bitmap> transformation = drawable.getFrameTransformation();
boolean isTransformed = !(transformation instanceof UnitTransfor... | @Test
public void testReturnsFalseIfFinishingFails() {
when(gifEncoder.start(any(OutputStream.class))).thenReturn(true);
when(gifEncoder.finish()).thenReturn(false);
assertFalse(encoder.encode(resource, file, options));
} |
@Override
public int hashCode()
{
if (frames.isEmpty()) {
return 0;
}
int result = 1;
for (ZFrame frame : frames) {
result = 31 * result + (frame == null ? 0 : frame.hashCode());
}
return result;
} | @Test
public void testHashcode()
{
ZMsg msg = new ZMsg();
assertThat(msg.hashCode(), is(0));
msg.add("123");
ZMsg other = ZMsg.newStringMsg("123");
assertThat(msg.hashCode(), is(other.hashCode()));
other = new ZMsg().append("2");
assertThat(msg.hashCo... |
public static void validateValue(Schema schema, Object value) {
validateValue(null, schema, value);
} | @Test
public void testValidateValueMismatchMapSomeValues() {
Map<Integer, Object> data = new HashMap<>();
data.put(1, "abc");
data.put(2, "wrong".getBytes());
assertThrows(DataException.class,
() -> ConnectSchema.validateValue(MAP_INT_STRING_SCHEMA, data));
} |
@Override
public void doRun() {
final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge);
searchDbService.getExpiredSearches(findReferencedSearchIds(),
mustBeOlderThan).forEach(searchDbService::delete);
} | @Test
public void testForNonexpiredSearches() {
when(viewService.streamAll()).thenReturn(Stream.empty());
final Search search1 = Search.builder()
.createdAt(DateTime.now(DateTimeZone.UTC).minus(Duration.standardDays(1)))
.build();
final Search search2 = Sear... |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testDisallowMergeModifyInternalModeNonSystem() {
// Don't allow for non system context
AssertHelper.assertThrows(
"Should not allow updating internal mode",
MaestroValidationException.class,
"Cannot modify system mode for parameter [tomerge]",
new Runnable() {... |
@Override
public int size() {
return 0;
} | @Test
public void testIntSpliteratorSplitTryAdvance() {
Set<Integer> results = new HashSet<>();
Spliterator.OfInt spliterator = es.intSpliterator();
Spliterator.OfInt split = spliterator.trySplit();
assertNull(split);
IntConsumer consumer = results::add;
while (spliterator.try... |
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
MainSettingsActivity mainSettingsActivity = (MainSettingsActivity) getActivity();
if (mainSettingsActivity == null) return super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_user_word) {
createEmptyItemForAdd()... | @Test
public void testAddNewWordFromMenuNotAtEmptyState() {
// adding a few words to the dictionary
UserDictionary userDictionary = new UserDictionary(getApplicationContext(), "en");
userDictionary.loadDictionary();
userDictionary.addWord("hello", 1);
userDictionary.addWord("you", 2);
userDict... |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithDirectorySelector() {
DiscoverySelector resource = selectDirectory("src/test/resources/io/cucumber/junit/platform/engine");
EngineDiscoveryRequest discoveryRequest = new SelectorRequest(resource);
resolver.resolveSelectors(discoveryRequest, testDescriptor);
... |
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
// 入栈
DataPermission dataPermission = this.findAnnotation(methodInvocation);
if (dataPermission != null) {
DataPermissionContextHolder.add(dataPermission);
}
try {
// ... | @Test // 无 @DataPermission 注解
public void testInvoke_none() throws Throwable {
// 参数
mockMethodInvocation(TestNone.class);
// 调用
Object result = interceptor.invoke(methodInvocation);
// 断言
assertEquals("none", result);
assertEquals(1, interceptor.getDataPermi... |
public static HoodieIndex.IndexType getIndexType(Configuration conf) {
return HoodieIndex.IndexType.valueOf(conf.getString(FlinkOptions.INDEX_TYPE).toUpperCase());
} | @Test
void testGetIndexType() {
Configuration conf = getConf();
// set uppercase index
conf.setString(FlinkOptions.INDEX_TYPE, "BLOOM");
assertEquals(HoodieIndex.IndexType.BLOOM, OptionsResolver.getIndexType(conf));
// set lowercase index
conf.setString(FlinkOptions.INDEX_TYPE, "bloom");
a... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
if(containerService.isContainer(file)) {
container... | @Test
public void testDeleteVersionedPlaceholder() throws Exception {
final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final String name = new AlphanumericRandomStringService().random();
final S3AccessControlListFea... |
public Optional<RestartPlan> buildRestartPlan(RestartRequest request) {
String connectorName = request.connectorName();
ConnectorStatus connectorStatus = statusBackingStore.get(connectorName);
if (connectorStatus == null) {
return Optional.empty();
}
// If requested,... | @Test
public void testBuildRestartPlanForUnknownConnector() {
String connectorName = "UnknownConnector";
RestartRequest restartRequest = new RestartRequest(connectorName, false, true);
AbstractHerder herder = testHerder();
when(statusStore.get(connectorName)).thenReturn(null);
... |
public static void executeWithRetries(
final Function function,
final RetryBehaviour retryBehaviour
) throws Exception {
executeWithRetries(() -> {
function.call();
return null;
}, retryBehaviour);
} | @Test
public void shouldReturnValue() throws Exception {
// Given:
final String expectedValue = "should return this";
// When:
final String result = ExecutorUtil.executeWithRetries(() -> expectedValue, ON_RETRYABLE);
// Then:
assertThat(result, is(expectedValue));
} |
@Override
public Collection<Long> generateKeys(final AlgorithmSQLContext context, final int keyGenerateCount) {
Collection<Long> result = new LinkedList<>();
for (int index = 0; index < keyGenerateCount; index++) {
result.add(generateKey());
}
return result;
} | @Test
void assertSetMaxVibrationOffsetFailureWhenNegative() {
assertThrows(AlgorithmInitializationException.class,
() -> TypedSPILoader.getService(KeyGenerateAlgorithm.class, "SNOWFLAKE", PropertiesBuilder.build(new Property("max-vibration-offset", "-1")))
.generateKe... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("Search State");
try {
setAttribute(protobuf, "State", getStateAsEnum().name());
completeNodeAttributes(protobuf);
} catch (Exc... | @Test
public void node_attributes() {
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(attribute(section, "CPU Usage (%)")).isNotNull();
assertThat(attribute(section, "Disk Available")).isNotNull();
assertThat(attribute(section, "Store Size")).isNotNull();
assertThat(attribu... |
protected void preHandle(HttpServletRequest request, Object handler, SpanCustomizer customizer) {
if (WebMvcRuntime.get().isHandlerMethod(handler)) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
customizer.tag(CONTROLLER_CLASS, handlerMethod.getBeanType().getSimpleName());
customizer.t... | @Test void preHandle_HandlerMethod_addsClassAndMethodTags() throws Exception {
parser.preHandle(
request,
new HandlerMethod(controller, TestController.class.getMethod("items", String.class)),
customizer
);
verify(customizer).tag("mvc.controller.class", "TestController");
verify(custom... |
@Override
public Mono<Void> writeWith(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
return chain.execute(exchange).doOnError(throwable -> cleanup(exchange)).then(Mono.defer(() -> {
Connection connection = exchange.getAttribute(Constants.CLIENT_RESPONSE_CONN_ATTR);
... | @Test
public void testWriteWith() {
ServerWebExchange exchangeNoClient = MockServerWebExchange.from(MockServerHttpRequest.get("/test")
.build());
StepVerifier.create(nettyClientMessageWriter.writeWith(exchangeNoClient, chain)).expectSubscription().verifyComplete();
ServerWeb... |
@Override
public <K, V> Map<K, V> toMap(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be null");
if (dataTable.isEmpty()) {... | @Test
void to_map__duplicate_keys__throws_exception() {
DataTable table = parse("",
"| | lat | lon |",
"| KMSY | 29.993333 | -90.258056 |",
"| KSEA | 47.448889 | -122.309444 |",
"| KSFO | 37.618889 | -122.375 |",
"| KSEA | 47... |
@Override
public void registerInstance(Service service, Instance instance, String clientId) throws NacosException {
NamingUtils.checkInstanceIsLegal(instance);
Service singleton = ServiceManager.getInstance().getSingleton(service);
if (!singleton.isEphemeral()) {
throw new N... | @Test
void testRegisterWhenClientPersistent() throws NacosException {
assertThrows(NacosRuntimeException.class, () -> {
Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false);
when(clientManager.getClient(anyString())).thenReturn(persistentClient);
//... |
@Override
public Optional<String> canUpgradeTo(final DataSource other) {
final List<String> issues = PROPERTIES.stream()
.filter(prop -> !prop.isCompatible(this, other))
.map(prop -> getCompatMessage(other, prop))
.collect(Collectors.toList());
checkSchemas(getSchema(), other.getSchem... | @Test
public void shouldEnforceSameType() {
// Given:
final KsqlStream<String> streamA = new KsqlStream<>(
"sql",
SourceName.of("A"),
SOME_SCHEMA,
Optional.empty(),
true,
topic,
false
);
final KsqlTable<String> streamB = new KsqlTable<>(
... |
public String driver() {
return get(DRIVER, null);
} | @Test
public void testSetDriver() {
SW_BDC.driver(DRIVER_NEW);
assertEquals("Incorrect driver", DRIVER_NEW, SW_BDC.driver());
} |
public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException {
if (!EnvUtil.getStandaloneMode()) {
String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE);
LookupType type = chooseLookup(lookupType);
LOOK_UP = find(type);
curr... | @Test
void createLookUpFileConfigMemberLookup() throws Exception {
EnvUtil.setIsStandalone(false);
mockEnvironment.setProperty(LOOKUP_MODE_TYPE, "file");
memberLookup = LookupFactory.createLookUp(memberManager);
assertEquals(FileConfigMemberLookup.class, memberLookup.getClass());
... |
public final void enter() {
if (inQueue) throw new IllegalStateException("Unbalanced enter/exit");
long timeoutNanos = timeoutNanos();
boolean hasDeadline = hasDeadline();
if (timeoutNanos == 0 && !hasDeadline) {
return; // No timeout and no deadline? Don't bother with the queue.
}
inQueue... | @Test public void doubleEnter() throws Exception {
a.enter();
try {
a.enter();
fail();
} catch (IllegalStateException expected) {
}
} |
@Nullable
@Override
public Set<String> getRemoteRegionAppWhitelist(@Nullable String regionName) {
if (null == regionName) {
regionName = "global";
} else {
regionName = regionName.trim().toLowerCase();
}
DynamicStringProperty appWhiteListProp =
... | @Test
public void testGetGlobalAppWhiteList() throws Exception {
String whitelistApp = "myapp";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegion.global.appWhiteList", whitelistApp);
DefaultEurekaServerConfig config = new DefaultEurekaServerConfig();
Set<Strin... |
@Override
public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException {
NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}", namespaceId,
serviceName, instance);
if (instance.isEphemeral()) {
... | @Test
void testDeregisterService() throws Exception {
//given
NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class);
HttpRestResult<Object> a = new HttpRestResult<Object>();
a.setData("127.0.0.1:8848");
a.setCode(200);
when(nacosRestTemplate.exchangeForm... |
public String getQuery() throws Exception {
return getQuery(weatherConfiguration.getLocation());
} | @Test
public void testMultiIdQuery() throws Exception {
WeatherConfiguration weatherConfiguration = new WeatherConfiguration();
weatherConfiguration.setIds("524901,703448");
weatherConfiguration.setMode(WeatherMode.JSON);
weatherConfiguration.setLanguage(WeatherLanguage.nl);
... |
@VisibleForTesting
Schema convertSchema(org.apache.avro.Schema schema) {
return Schema.of(getFields(schema));
} | @Test
void convertSchema_maps() {
Schema input = SchemaBuilder.record("testRecord")
.fields()
.name("intMap")
.type()
.map()
.values()
.intType().noDefault()
.name("recordMap")
.type()
.nullable()
.map()
.values(SchemaBuilder.... |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(
Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS)))
... | @Test
public void no_measures_for_FILE_component_without_code() {
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, null, 1)).build());
underTest.execute(new TestComputationStepContext());
assertThat(measureRepository.isEmpty()).i... |
public int add(byte[] value) {
int offsetBufferIndex = _numValues >>> OFFSET_BUFFER_SHIFT_OFFSET;
int offsetIndex = _numValues & OFFSET_BUFFER_MASK;
PinotDataBuffer offsetBuffer;
// If this is the first entry in the offset buffer, allocate a new buffer and store the end offset of the previous
// va... | @Test
public void testAdd()
throws Exception {
try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) {
for (int i = 0; i < NUM_VALUES; i++) {
Assert.assertEquals(offHeapMutableBytesStore.add(_values[i]), i);
}
}
} |
public MailConfiguration getConfiguration() {
if (configuration == null) {
configuration = new MailConfiguration(getCamelContext());
}
return configuration;
} | @Test
public void testMailEndpointsAreConfiguredProperlyWhenUsingImap() {
MailEndpoint endpoint = checkEndpoint("imap://james@myhost:143/subject");
MailConfiguration config = endpoint.getConfiguration();
assertEquals("imap", config.getProtocol(), "getProtocol()");
assertEquals("myhos... |
@GwtIncompatible("java.util.regex.Pattern")
public void doesNotContainMatch(@Nullable Pattern regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that does not contain a match for", regex);
return;
}
Matcher matcher = regex.matcher(actual);
if (matcher... | @Test
@GwtIncompatible("Pattern")
public void stringDoesNotContainMatchPattern() {
assertThat("zzaaazz").doesNotContainMatch(Pattern.compile(".b."));
expectFailureWhenTestingThat("zzabazz").doesNotContainMatch(Pattern.compile(".b."));
assertFailureValue("expected not to contain a match for", ".b.");
... |
@Override
public double getMean() {
if (values.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < values.length; i++) {
sum += values[i] * normWeights[i];
}
return sum;
} | @Test
public void doesNotProduceNaNValues() {
WeightedSnapshot weightedSnapshot = new WeightedSnapshot(
weightedArray(new long[]{1, 2, 3}, new double[]{0, 0, 0}));
assertThat(weightedSnapshot.getMean()).isEqualTo(0);
} |
@Override
public void addTrackedResources(Key intentKey,
Collection<NetworkResource> resources) {
for (NetworkResource resource : resources) {
if (resource instanceof Link) {
intentsByLink.put(linkKey((Link) resource), intentKey);
}... | @Test
public void testEventHostAvailableMatch() throws Exception {
final Device host = device("host1");
final DeviceEvent deviceEvent =
new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, host);
reasons.add(deviceEvent);
final Key key = Key.of(0x333L, APP_ID);
Co... |
public static String generateInventoryTaskId(final InventoryDumperContext dumperContext) {
return String.format("%s.%s#%s", dumperContext.getCommonContext().getDataSourceName(), dumperContext.getActualTableName(), dumperContext.getShardingItem());
} | @Test
void assertGenerateInventoryTaskId() {
InventoryDumperContext dumperContext = new InventoryDumperContext(new DumperCommonContext("foo_ds", null, null, null));
dumperContext.setActualTableName("foo_actual_tbl");
dumperContext.setShardingItem(1);
assertThat(PipelineTaskUtils.gene... |
@Deprecated
public static <T> Task<T> callable(final String name, final Callable<? extends T> callable) {
return Task.callable(name, () -> callable.call());
} | @SuppressWarnings("deprecation")
@Test
public void testThrowableCallableNoError() throws InterruptedException {
final Integer magic = 0x5f3759df;
final ThrowableCallable<Integer> callable = new ThrowableCallable<Integer>() {
@Override
public Integer call() throws Throwable {
return magic... |
@Udf(description = "Returns the hyperbolic tangent of an INT value")
public Double tanh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic tangent of."
) final Integer value
) {
return tanh(value == null ? null : val... | @Test
public void shouldHandleLessThanNegative2Pi() {
assertThat(udf.tanh(-9.1), closeTo(-0.9999999750614947, 0.000000000000001));
assertThat(udf.tanh(-6.3), closeTo(-0.9999932559922726, 0.000000000000001));
assertThat(udf.tanh(-7), closeTo(-0.9999983369439447, 0.000000000000001));
assertThat(udf.tanh... |
@Override
public IdentityContext build(Request request) {
Optional<AuthPluginService> authPluginService = AuthPluginManager.getInstance()
.findAuthServiceSpiImpl(authConfigs.getNacosAuthSystemType());
IdentityContext result = new IdentityContext();
getRemoteIp(request, result... | @Test
void testBuild() {
IdentityContext actual = identityContextBuilder.build(request);
assertEquals(IDENTITY_TEST_VALUE, actual.getParameter(IDENTITY_TEST_KEY));
assertEquals("1.1.1.1", actual.getParameter(Constants.Identity.REMOTE_IP));
} |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
JooqConfiguration conf = configuration != null ? configuration.copy() : new JooqConfiguration();
JooqEndpoint endpoint = new JooqEndpoint(uri, this, conf);
setPropert... | @Test
public void testNonDefaultConfig() {
JooqComponent component = (JooqComponent) context().getComponent("jooq");
assertThrows(PropertyBindingException.class,
() -> component.createEndpoint(
"jooq://org.apache.camel.component.jooq.db.tables.records.BookStor... |
public ZMsg dump(Appendable out)
{
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.printf("--------------------------------------\n");
for (ZFrame frame : frames) {
pw.printf("[%03d] %s\n", frame.size(), fra... | @Test
public void testDump()
{
ZMsg msg = new ZMsg().append(new byte[0]).append(new byte[] { (byte) 0xAA });
msg.dump();
StringBuilder out = new StringBuilder();
msg.dump(out);
System.out.println(msg);
assertThat(out.toString(), endsWith("[000] \n[001] AA\n"));... |
@Override
public List<Catalogue> sort(List<Catalogue> catalogueTree, SortTypeEnum sortTypeEnum) {
log.debug(
"sort catalogue tree based on creation time. catalogueTree: {}, sortTypeEnum: {}",
catalogueTree,
sortTypeEnum);
return recursionSortCatalogues... | @Test
public void sortEmptyTest2() {
List<Catalogue> catalogueTree = null;
SortTypeEnum sortTypeEnum = SortTypeEnum.ASC;
List<Catalogue> resultList = catalogueTreeSortCreateTimeStrategyTest.sort(catalogueTree, sortTypeEnum);
assertEquals(Lists.newArrayList(), resultList);
} |
public List<ErasureCodingPolicy> loadPolicy(String policyFilePath) {
try {
File policyFile = getPolicyFile(policyFilePath);
if (!policyFile.exists()) {
LOG.warn("Not found any EC policy file");
return Collections.emptyList();
}
return loadECPolicies(policyFile);
} catch (... | @Test
public void testBadECPolicy() throws Exception {
PrintWriter out = new PrintWriter(new FileWriter(POLICY_FILE));
out.println("<?xml version=\"1.0\"?>");
out.println("<configuration>");
out.println("<layoutversion>1</layoutversion>");
out.println("<schemas>");
out.println(" <schema id=\"... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListInvisibleCharacter() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("us-east-1");
final Path placeholder = new GoogleStorageTouchFeature(session).touch(
... |
public static void addInvocationRateToSensor(final Sensor sensor,
final String group,
final Map<String, String> tags,
final String operation,
... | @Test
public void shouldAddInvocationRateToSensor() {
final Sensor sensor = mock(Sensor.class);
final MetricName expectedMetricName = new MetricName(METRIC_NAME1 + "-rate", group, DESCRIPTION1, tags);
when(sensor.add(eq(expectedMetricName), any(Rate.class))).thenReturn(true);
Stream... |
public static String translate(String src, String from, String to) {
if (isEmpty(src)) {
return src;
}
StringBuilder sb = null;
int ix;
char c;
for (int i = 0, len = src.length(); i < len; i++) {
c = src.charAt(i);
ix = from.indexOf(c);... | @Test
void testTranslate() throws Exception {
String s = "16314";
assertEquals(StringUtils.translate(s, "123456", "abcdef"), "afcad");
assertEquals(StringUtils.translate(s, "123456", "abcd"), "acad");
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 2) {
onInvalidDataReceived(device, data);
return;
}
// Read the Op Code
final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0);
// Estima... | @Test
public void onContinuousGlucoseCommunicationIntervalReceived_notSecured() {
final Data data = new Data(new byte[] { 3, 11 });
callback.onDataReceived(null, data);
assertEquals("Interval", 11, interval);
assertFalse(secured);
} |
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof ShowFunctionStatusStatement) {
return Optional.of(new ShowFunctionStatusExecutor((ShowFu... | @Test
void assertCreateWithSelectStatementForTransactionIsolation() {
initProxyContext(Collections.emptyMap());
MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class);
when(selectStatement.getFrom()).thenReturn(Optional.empty());
ProjectionsSegment projectionsSegment... |
public static FromEndOfWindow pastEndOfWindow() {
return new FromEndOfWindow();
} | @Test
public void testOnMergeAlreadyFinished() throws Exception {
tester =
TriggerStateMachineTester.forTrigger(
AfterEachStateMachine.inOrder(
AfterWatermarkStateMachine.pastEndOfWindow(),
RepeatedlyStateMachine.forever(AfterPaneStateMachine.elementCountAtLeast... |
@CanIgnoreReturnValue
@SuppressWarnings("deprecation") // TODO(b/134064106): design an alternative to no-arg check()
public final Ordered containsExactly() {
return check().about(iterableEntries()).that(checkNotNull(actual).entries()).containsExactly();
} | @Test
public void containsExactlyVararg() {
ImmutableListMultimap<Integer, String> listMultimap =
ImmutableListMultimap.of(1, "one", 3, "six", 3, "two");
assertThat(listMultimap).containsExactly(1, "one", 3, "six", 3, "two");
} |
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
return inject(statement, new TopicProperties.Builder());
} | @Test
public void shouldIdentifyAndUseCorrectSource() {
// Given:
givenStatement("CREATE STREAM x WITH (kafka_topic='topic') AS SELECT * FROM SOURCE;");
// When:
injector.inject(statement, builder);
// Then:
verify(builder).withSource(argThat(supplierThatGets(sourceDescription)), any(Supplie... |
public synchronized static HealthCheckRegistry setDefault(String name) {
final HealthCheckRegistry registry = getOrCreate(name);
return setDefault(name, registry);
} | @Test
public void unableToSetDefaultRegistryTwice() {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Default health check registry is already set.");
SharedHealthCheckRegistries.setDefault("default");
SharedHealthCheckRegistries.setDefault("d... |
public Marshaller createMarshaller(Class<?> clazz) throws JAXBException {
Marshaller marshaller = getContext(clazz).createMarshaller();
setMarshallerProperties(marshaller);
if (marshallerEventHandler != null) {
marshaller.setEventHandler(marshallerEventHandler);
}
marshaller.setSchema(marshall... | @Test
void buildsMarshallerWithDefaultEventHandler() throws Exception {
JAXBContextFactory factory =
new JAXBContextFactory.Builder().build();
Marshaller marshaller = factory.createMarshaller(Object.class);
assertThat(marshaller.getEventHandler()).isNotNull();
} |
public static void createFile(String filePath) {
Path storagePath = Paths.get(filePath);
Path parent = storagePath.getParent();
try {
if (parent != null) {
Files.createDirectories(parent);
}
Files.createFile(storagePath);
} catch (UnsupportedOperationException e) {
throw ... | @Test
public void createFile() throws IOException {
File tempFile = new File(mTestFolder.getRoot(), "tmp");
FileUtils.createFile(tempFile.getAbsolutePath());
assertTrue(FileUtils.exists(tempFile.getAbsolutePath()));
assertTrue(tempFile.delete());
} |
public void setAttribute(String key, String value) {
ensureLocalMember();
if (instance != null && instance.node.clusterService.isJoined()) {
throw new UnsupportedOperationException("Attributes can not be changed after instance has started");
}
isNotNull(key, "key");
... | @Test(expected = UnsupportedOperationException.class)
public void testSetAttribute_onRemoteMember() {
MemberImpl member = new MemberImpl(address, MemberVersion.of("3.8.0"), false);
member.setAttribute("remoteMemberSet", "wontWork");
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testImplNewInstance() throws Exception {
DynConstructors.Ctor<MyClass> ctor =
DynConstructors.builder().impl(MyClass.class).buildChecked();
assertThat(ctor.newInstance()).isInstanceOf(MyClass.class);
} |
@Override
public String getName() {
return delegate().getName();
} | @Test
public void getNameDelegates() {
String name = "My_forwardingptransform-name;for!thisTest";
when(delegate.getName()).thenReturn(name);
assertThat(forwarding.getName(), equalTo(name));
} |
@Override
public Num calculate(BarSeries series, Position position) {
Num numberOfWinningPositions = numberOfWinningPositionsCriterion.calculate(series, position);
if (numberOfWinningPositions.isZero()) {
return series.zero();
}
Num grossProfit = grossProfitCriterion.calc... | @Test
public void calculateOnlyWithProfitPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series),
Trade.buyAt(3, series), Trade.sellAt(5, seri... |
public static String trimStart( final String source, char c ) {
if ( source == null ) {
return null;
}
int length = source.length();
int index = 0;
while ( index < length && source.charAt( index ) == c ) {
index++;
}
return source.substring( index );
} | @Test
public void testTrimStart_None() {
assertEquals( "file/path/", StringUtil.trimStart( "file/path/", '/' ) );
} |
@Override
public Split.Output run(RunContext runContext) throws Exception {
URI from = new URI(runContext.render(this.from));
return Split.Output.builder()
.uris(StorageService.split(runContext, this, from))
.build();
} | @Test
void partition() throws Exception {
RunContext runContext = runContextFactory.of();
URI put = storageUpload(1000);
Split result = Split.builder()
.from(put.toString())
.partitions(8)
.build();
Split.Output run = result.run(runContext);
... |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey... | @Test
public void testMeasurableCounter() {
Sensor sensor = metrics.sensor("test");
sensor.add(metricName, new WindowedCount());
sensor.record();
sensor.record();
time.sleep(60 * 1000L);
// Collect metrics.
collector.collect(testEmitter);
List<Singl... |
public static <E> E get(final Iterator<E> iterator, int index) throws IndexOutOfBoundsException {
if(null == iterator){
return null;
}
Assert.isTrue(index >= 0, "[index] must be >= 0");
while (iterator.hasNext()) {
index--;
if (-1 == index) {
return iterator.next();
}
iterator.next();
}
r... | @Test
public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
final String str = IterUtil.get(set.iterator(), 2);
assertEquals("C", str);
} |
private Map<String, String> appendConfig() {
Map<String, String> map = new HashMap<>(16);
map.put(INTERFACE_KEY, interfaceName);
map.put(SIDE_KEY, CONSUMER_SIDE);
ReferenceConfigBase.appendRuntimeParameters(map);
if (!ProtocolUtils.isGeneric(generic)) {
String revi... | @Test
void testAppendConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
applicationConfig.setVersion("v1");
applicationConfig.setOwner("owner1");
applicationConfig.setOrganization("bu1");
applicationCo... |
public static <R> Mono<R> entryWith(String resourceName, Mono<R> actual) {
return entryWith(resourceName, EntryType.OUT, actual);
} | @Test
public void testReactorEntryWithBizException() {
String resourceName = createResourceName("testReactorEntryWithBizException");
StepVerifier.create(ReactorSphU.entryWith(resourceName, Mono.error(new IllegalStateException())))
.expectError(IllegalStateException.class)
.ve... |
public static <T extends Throwable> void checkContainsKey(final Map<?, ?> map, final Object key, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (!map.containsKey(key)) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckContainsKeyToNotThrowException() {
assertDoesNotThrow(() -> ShardingSpherePreconditions.checkContainsKey(Collections.singletonMap("foo", "value"), "foo", SQLException::new));
} |
public ModuleBuilder version(String version) {
this.version = version;
return getThis();
} | @Test
void version() {
ModuleBuilder builder = ModuleBuilder.newBuilder();
builder.version("version");
Assertions.assertEquals("version", builder.build().getVersion());
} |
public Instant toInstant() {
return instant;
} | @Test
public void testNanoPrecision() {
final String input = "2021-04-02T00:28:17.987654321Z";
final Timestamp t1 = new Timestamp(input);
assertEquals(987654321, t1.toInstant().getNano());
} |
@Override
public ByteBuf writeShort(int value) {
ensureWritable0(2);
_setShort(writerIndex, value);
writerIndex += 2;
return this;
} | @Test
public void testWriteShortAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeShort(1);
}
});
} |
@Override
public String getMessage() {
return null == message ? LocaleFactory.localizedString("Unknown") : message;
} | @Test
public void testGetMessage() {
final BackgroundException e = new BackgroundException(new LoginCanceledException());
e.setMessage("m");
assertEquals("m", e.getMessage());
} |
List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... | @Test(expected = KubernetesClientException.class)
public void endpointsFailFastWhenNoPublicAccess() throws JsonProcessingException {
// given
cleanUpClient();
kubernetesClient = newKubernetesClient(ExposeExternallyMode.ENABLED, false, null, null);
stub(String.format("/api/v1/namespa... |
@Override
public String getRawSourceHash(Component file) {
checkComponentArgument(file);
if (rawSourceHashesByKey.containsKey(file.getKey())) {
return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey()));
} else {
String newSourceHash = computeRawSourceHash(file);
rawS... | @Test
void getRawSourceHash_let_exception_go_through() {
IllegalArgumentException thrown = new IllegalArgumentException("this IAE will cause the hash computation to fail");
when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenThrow(thrown);
assertThatThrownBy(() -> mockedUnderTest.getRawSource... |
@Override
public String convertToDatabaseColumn(Map<String, String> attribute) {
return GSON.toJson(attribute);
} | @Test
void convertToDatabaseColumn_empty() {
assertEquals("{}", this.converter.convertToDatabaseColumn(new HashMap<>(4)));
} |
public Result fetchArtifacts(String[] uris) {
checkArgument(uris != null && uris.length > 0, "At least one URI is required.");
ArtifactUtils.createMissingParents(baseDir);
List<File> artifacts =
Arrays.stream(uris)
.map(FunctionUtils.uncheckedFunction(thi... | @Test
void testMixedArtifactFetch() throws Exception {
File sourceFile = TestingUtils.getClassFile(getClass());
String uriStr = "file://" + sourceFile.toURI().getPath();
File sourceFile2 = getFlinkClientsJar();
String uriStr2 = "file://" + sourceFile2.toURI().getPath();
Arti... |
public void start(List<AlarmCallback> allCallbacks) {
LocalDateTime now = LocalDateTime.now();
lastExecuteTime = now;
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
try {
final List<AlarmMessage> alarmMessageList = new ArrayList<>(30);
... | @Test
public void testTriggerTimePoint() throws InterruptedException {
String test = System.getProperty("AlarmCoreTest");
if (test == null) {
return;
}
Rules emptyRules = new Rules();
emptyRules.setRules(new ArrayList<>(0));
AlarmCore core = new AlarmCore... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.