focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void customize(WebServerFactory server) { // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. setLocationForStaticAssets(server); }
@Test void shouldCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs"))...
public long periodBarriersCrossed(long start, long end) { if (start > end) throw new IllegalArgumentException("Start cannot come before end"); long startFloored = getStartOfCurrentPeriodWithGMTOffsetCorrection(start, getTimeZone()); long endFloored = getStartOfCurrentPeriodWithGMTOf...
@Test public void testPeriodBarriersCrossedWhenGoingIntoDaylightSaving() { RollingCalendar rc = new RollingCalendar(dailyPattern, TimeZone.getTimeZone("CET"), Locale.US); // Sun Mar 26 00:02:03 CET 2017, GMT offset = -1h long start = 1490482923333L; // Mon Mar 27 00:02:03 CEST 2017, ...
@Override public OpticalConnectivityId setupPath(Path path, Bandwidth bandwidth, Duration latency) { checkNotNull(path); log.debug("setupPath({}, {}, {})", path, bandwidth, latency); // map of cross connect points (optical port -> packet port) Map<ConnectPoint, ConnectPoint> crossCo...
@Test public void testSetupPath() { Bandwidth bandwidth = Bandwidth.bps(100); Duration latency = Duration.ofMillis(10); List<Link> links = Stream.of(LINK1, LINK2, LINK3, LINK4, LINK5, LINK6) .collect(Collectors.toList()); Path path = new DefaultPath(PROVIDER_ID, links...
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks, final Map<TaskId, Set<TopicPartition>> standbyTasks) { log.info("Handle new assignment with:\n" + "\tNew active tasks: {}\n" + "\tNew standby tasks: {}\n" +...
@Test public void shouldConvertStandbyTaskToActiveTask() { final StandbyTask standbyTask = mock(StandbyTask.class); when(standbyTask.id()).thenReturn(taskId00); when(standbyTask.isActive()).thenReturn(false); when(standbyTask.prepareCommit()).thenReturn(Collections.emptyMap()); ...
@Override public boolean enablePlugin(String pluginId) { throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute enablePlugin!"); }
@Test public void enablePlugin() { pluginManager.loadPlugins(); assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.enablePlugin(OTHER_PLUGIN_ID)); assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.enablePlugin(THIS_PLUGIN_ID)); }
@Deprecated public static boolean isExpired(Date startDate, DateField dateField, int timeLength, Date endDate) { final Date offsetDate = offset(startDate, dateField, timeLength); return offsetDate.after(endDate); }
@Test public void isExpiredTest() { final DateTime startDate = DateUtil.parse("2019-12-01 17:02:30"); final DateTime endDate = DateUtil.parse("2019-12-02 17:02:30"); final int length = 3; //noinspection deprecation final boolean expired = DateUtil.isExpired(startDate, DateField.DAY_OF_YEAR, length, endDate);...
public String getContent(String path) { String htmlPath = HTML_PATHS.contains(path) ? path : INDEX_HTML_PATH; checkState(servletContext != null, "init has not been called"); // Optimization to not have to call platform.currentStatus on each call if (Objects.equals(status, UP)) { return indexHtmlBy...
@Test public void content_is_updated_when_status_has_changed() { doInit(); when(platform.status()).thenReturn(STARTING); assertThat(underTest.getContent("/foo")) .contains(STARTING.name()); when(platform.status()).thenReturn(UP); assertThat(underTest.getContent("/foo")) .contains(UP.n...
@Override protected boolean hasLeadership(String componentId, UUID leaderSessionId) { synchronized (lock) { if (leaderElectionDriver != null) { if (leaderContenderRegistry.containsKey(componentId)) { return leaderElectionDriver.hasLeadership() ...
@Test void testHasLeadershipWithLeadershipLostAndRevokeEventProcessed() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { final UUID expectedSessionID = UUID.randomUUID(); ...
public static BigInteger decodeMPI(byte[] mpi, boolean hasLength) { byte[] buf; if (hasLength) { int length = (int) readUint32BE(mpi, 0); buf = new byte[length]; System.arraycopy(mpi, 4, buf, 0, length); } else buf = mpi; if (buf.length == ...
@Test public void testDecodeMPI() { assertEquals(BigInteger.ZERO, ByteUtils.decodeMPI(new byte[]{}, false)); }
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullValueJoinerWithKeyOnLeftJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin(testStream, (ValueJoinerWithKey<? super String, ? super String, ? super...
@JsonIgnore public boolean canHaveProfile() { return !this.indexTemplateType().map(TEMPLATE_TYPES_FOR_INDEX_SETS_WITH_IMMUTABLE_FIELD_TYPES::contains).orElse(false); }
@Test public void testEventIndexWithProfileSetIsIllegal() { assertFalse(testIndexSetConfig(EVENT_TEMPLATE_TYPE, null, "profile").canHaveProfile()); }
public static KiePMMLDroolsAST getKiePMMLDroolsAST(final List<Field<?>> fields, final TreeModel model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, ...
@Test void getKiePMMLDroolsGolfingAST() { final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap = getFieldTypeMap(golfingPmml.getDataDictionary(), golfingPmml.getTransformationDictionary(), golfingModel.getLocalTransformations()); List<KiePMMLDroolsType> types = Collections.emptyList(); ...
@Override protected Pair<CompletableFuture, ExecutorService> startService() { LOG.info("Starting async archive service..."); return Pair.of(CompletableFuture.supplyAsync(() -> { writeClient.archive(); return true; }, executor), executor); }
@Test void startServiceShouldInvokeCallArchiveMethod() throws ExecutionException, InterruptedException { AsyncArchiveService service = new AsyncArchiveService(writeClient); assertEquals(true, service.startService().getLeft().get()); verify(writeClient).archive(); }
public static <K, V> PerKey<K, V> perKey() { return new AutoValue_ApproximateCountDistinct_PerKey.Builder<K, V>() .setPrecision(HllCount.DEFAULT_PRECISION) .build(); }
@Test @Category(NeedsRunner.class) public void testStandardTypesPerKeyForStrings() { List<KV<Integer, String>> strings = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int k : INTS1) { strings.add(KV.of(i, String.valueOf(k))); } } PCollection<KV<Integer, Long>> result = ...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseChromeOnWindowsServer2012R2Test() { final String uaStr = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("Chrome", ua.getBrowser().toString()); assertEquals("63....
public static void checkDrivingLicenceMrz(String mrz) { if (mrz.charAt(0) != 'D') { throw new VerificationException("MRZ should start with D"); } if (mrz.charAt(1) != '1') { throw new VerificationException("Only BAP configuration is supported (1)"); } if (...
@Test public void checkDrivingLicenceMrzCheckDigitWrong() { assertThrows(VerificationException.class, () -> { MrzUtils.checkDrivingLicenceMrz("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"); }); }
public boolean setSeverity(DefaultIssue issue, String severity, IssueChangeContext context) { checkState(!issue.manualSeverity(), "Severity can't be changed"); if (!Objects.equals(severity, issue.severity())) { issue.setFieldChange(context, SEVERITY, issue.severity(), severity); issue.setSeverity(se...
@Test void not_change_severity() { issue.setSeverity("MINOR"); boolean updated = underTest.setSeverity(issue, "MINOR", context); assertThat(updated).isFalse(); assertThat(issue.mustSendNotifications()).isFalse(); assertThat(issue.currentChange()).isNull(); }
@Override public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { User user = null; try { user = this.identityService.createUserQuery() .userId(userId) .singleResult(); } catch (FlowableException ...
@Test public void testSerializingUserDetailsShouldWorkCorrectly() throws IOException, ClassNotFoundException { UserDetails kermit = userDetailsService.loadUserByUsername("kermit"); byte[] serialized; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream outp...
public boolean isLaunchIntentOfNotification(Intent intent) { return intent.getBooleanExtra(LAUNCH_FLAG_KEY_NAME, false); }
@Test public void isLaunchIntentOfNotification_noFlagInBundle_returnFalse() throws Exception { Intent intent = mock(Intent.class); final AppLaunchHelper uut = getUUT(); boolean result = uut.isLaunchIntentOfNotification(intent); assertFalse(result); }
@Override public Set<OpenstackVtap> getVtapsByDeviceId(DeviceId deviceId) { return store.getVtapsByDeviceId(deviceId); }
@Test public void testGetDeviceIdsFromVtap() { assertTrue(ERR_NOT_FOUND, target.getVtapsByDeviceId(DEVICE_ID_3).contains(VTAP_2)); assertTrue(ERR_NOT_FOUND, target.getVtapsByDeviceId(DEVICE_ID_4).contains(VTAP_2)); }
@Override public void cancel() { context.goToCanceling( getExecutionGraph(), getExecutionGraphHandler(), getOperatorCoordinatorHandler(), getFailures()); }
@Test void testTransitionToCancelingOnCancel() throws Exception { try (MockFailingContext ctx = new MockFailingContext()) { StateTrackingMockExecutionGraph meg = new StateTrackingMockExecutionGraph(); Failing failing = createFailingState(ctx, meg); ctx.setExpectCanceling(...
@Override public DirectoryTimestamp getDirectoryTimestamp() { return DirectoryTimestamp.explicit; }
@Test public void testFeatures() { assertEquals(Protocol.Case.sensitive, new IRODSProtocol().getCaseSensitivity()); assertEquals(Protocol.DirectoryTimestamp.explicit, new IRODSProtocol().getDirectoryTimestamp()); }
@JsonProperty public String getSource() { return message.getSource(); }
@Test public void testGetSource() throws Exception { assertEquals(message.getSource(), messageSummary.getSource()); }
@Override public List<KsqlPartitionLocation> locate( final List<KsqlKey> keys, final RoutingOptions routingOptions, final RoutingFilterFactory routingFilterFactory, final boolean isRangeScan ) { if (isRangeScan && keys.isEmpty()) { throw new IllegalStateException("Query is range sc...
@Test public void shouldReturnStandBysWhenActiveDown() { // Given: getActiveAndStandbyMetadata(); when(livenessFilter.filter(eq(ACTIVE_HOST))) .thenReturn(Host.exclude(ACTIVE_HOST, "liveness")); // When: final List<KsqlPartitionLocation> result = locator.locate(ImmutableList.of(KEY), rout...
@Override public void addSourceMap(String key, String value) { sourcesMap.put(key, value); }
@Test void addSourceMap() { Map<String, String> retrieved = kiePMMLModelWithSources.getSourcesMap(); assertThat(retrieved).isEmpty(); kiePMMLModelWithSources.addSourceMap("KEY", "VALUE"); retrieved = kiePMMLModelWithSources.getSourcesMap(); assertThat(retrieved).containsKey("...
protected boolean isClusterVersionUnknownOrLessOrEqual(Version version) { Version clusterVersion = getNodeEngine().getClusterService().getClusterVersion(); return clusterVersion.isUnknownOrLessOrEqual(version); }
@Test public void testClusterVersion_isUnknownLessOrEqual_currentVersion() { assertTrue(object.isClusterVersionUnknownOrLessOrEqual(CURRENT_CLUSTER_VERSION)); }
@Override public Object evaluateLiteralExpression(String rawExpression, String className, List<String> genericClasses) { if (isStructuredInput(className)) { return convertResult(rawExpression, className, genericClasses); } else { return internalLiteralEvaluation(rawExpression...
@Test public void evaluateLiteralExpression() { assertThat(expressionEvaluator.evaluateLiteralExpression(null, String.class.getCanonicalName(), null)).isNull(); assertThat(expressionEvaluator.evaluateLiteralExpression(null, List.class.getCanonicalName(), null)).isNull(); assertThat(expressio...
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception { return newGetter(object, parent, modifier, method.getReturnType(), method::invoke, (t, et) -> new MethodGetter(parent, method, modifier, t, et)); }
@Test public void newMethodGetter_whenExtractingFromNull_Array_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType() throws Exception { OuterObject object = new OuterObject("name", InnerObject.nullInner("inner")); Getter parentGetter = GetterFactory.newMethodGetter(object, null, inn...
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); ...
@Test public void testSuggestedPathBandwidthConstrainedIntentFailure() { final double bpsTotal = 10.0; final ResourceService resourceService = MockResourceService.makeCustomBandwidthResourceService(bpsTotal); final List<Constraint> constraints = Collections.s...
@Override public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) { // 默认使用积分为 0 result.setUsePoint(0); // 1.1 校验是否使用积分 if (!BooleanUtil.isTrue(param.getPointStatus())) { result.setUsePoint(0); return; } // 1.2 校...
@Test public void testCalculate_UserPointNotEnough() { // 准备参数 TradePriceCalculateReqBO param = new TradePriceCalculateReqBO() .setUserId(233L).setPointStatus(true) // 是否使用积分 .setItems(asList( new TradePriceCalculateReqBO.Item().setSkuId(10L).s...
public static void forRunningTasks(String tableNameWithType, String taskType, ClusterInfoAccessor clusterInfoAccessor, Consumer<Map<String, String>> taskConfigConsumer) { Map<String, TaskState> taskStates = clusterInfoAccessor.getTaskStates(taskType); for (Map.Entry<String, TaskState> entry : taskStates.e...
@Test public void testForRunningTasks() { String tableName = "mytable_OFFLINE"; String taskType = "myTaskType"; ClusterInfoAccessor mockClusterInfoAccessor = createMockClusterInfoAccessor(); Map<String, TaskState> taskStatesMap = new HashMap<>(); String taskID = System.currentTimeMillis() + "_0";...
public static void writeBinaryCodedLengthBytes(byte[] data, ByteArrayOutputStream out) throws IOException { // 1. write length byte/bytes if (data.length < 252) { out.write((byte) data.length); } else if (data.length < (1 << 16L)) { out.write((byte) 252); writ...
@Test public void testWriteBinaryCodedLengthBytes4() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteHelper.writeBinaryCodedLengthBytes(new byte[16777216], out); byte[] expected = new byte[16777221]; expected[0] = -2; expected[4] = 1; Assert.assertArrayEquals(expected, (...
public boolean shouldCareAbout(Object entity) { if (entity != null) return getParameterizedClass().isAssignableFrom(entity.getClass()); return false; }
@Test public void shouldNotCareAboutEntityOfADifferentTypeFromTheOneTheListenerIsParameterizedWith() { EntityConfigChangedListener entityConfigChangedListenerForA = new EntityConfigChangedListener<A>() { @Override public void onEntityConfigChange(A entity) { } };...
@Override public void close() { }
@Test public void shouldSucceed_gapDetectedLocal_retry() throws ExecutionException, InterruptedException { // Given: final AtomicReference<Set<KsqlNode>> nodes = new AtomicReference<>( ImmutableSet.of(ksqlNodeLocal, ksqlNodeRemote)); final PushRouting routing = new PushRouting(sqr -> nodes.g...
@Override public float getProgress() { readLock.lock(); try { TaskAttempt bestAttempt = selectBestAttempt(); if (bestAttempt == null) { return 0f; } return bestAttempt.getProgress(); } finally { readLock.unlock(); } }
@Test public void testTaskProgress() { LOG.info("--- START: testTaskProgress ---"); mockTask = createMockTask(TaskType.MAP); // launch task TaskId taskId = getNewTaskID(); scheduleTaskAttempt(taskId); float progress = 0f; assert(mockTask.getProgress() == progress); la...
public static boolean isTemporaryFileName(String path) { return TEMPORARY_FILE_NAME.matcher(path).matches(); }
@Test public void isTemporaryFileName() { assertTrue(PathUtils.isTemporaryFileName(PathUtils.temporaryFileName(0, "/"))); assertTrue( PathUtils.isTemporaryFileName(PathUtils.temporaryFileName(0xFFFFFFFFFFFFFFFFL, "/"))); assertTrue(PathUtils.isTemporaryFileName("foo.alluxio.0x0123456789ABCDEF.tmp"...
@Override public int compare(String indexName1, String indexName2) { int separatorPosition = indexName1.lastIndexOf(separator); int index1Number; final String indexPrefix1 = separatorPosition != -1 ? indexName1.substring(0, separatorPosition) : indexName1; try { index1Num...
@Test void indexPrefixIsMoreImportantThanNumberWhileSorting() { assertTrue(comparator.compare("abc_5", "bcd_3") < 0); assertTrue(comparator.compare("abc", "bcd_3") < 0); assertTrue(comparator.compare("zzz_1", "aaa") > 0); assertTrue(comparator.compare("zzz", "aaa") > 0); }
public static Set<String> getRpcParams() { return Collections.unmodifiableSet(CONFIG_NAMES); }
@Test void testGetRpcParams() { Field[] declaredFields = RpcConstants.class.getDeclaredFields(); int i = 0; for (Field declaredField : declaredFields) { declaredField.setAccessible(true); if (declaredField.getType().equals(String.class) && null != declaredField.getAnn...
@SuppressWarnings("unchecked") @Override public void punctuate(final ProcessorNode<?, ?, ?, ?> node, final long timestamp, final PunctuationType type, final Punctuator punctuator) { if (processorContext.currentNode() != null) ...
@Test public void punctuateShouldThrowFailedProcessingExceptionWhenProcessingExceptionHandlerThrowsAnException() { when(stateManager.taskId()).thenReturn(taskId); when(stateManager.taskType()).thenReturn(TaskType.ACTIVE); task = createStatelessTask(createConfig( AT_LEAST_ONCE, ...
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer) { return read(buffer, consumer, 0); }
@Test void shouldReadSummarisedObservation() { final ErrorConsumer consumer = mock(ErrorConsumer.class); final long timestampOne = 7; final long timestampTwo = 10; final RuntimeException error = new RuntimeException("Test Error"); final StringWriter stringWriter = new S...
public void clear() { length = 0; textLength = -1; }
@Test public void testClear() throws Exception { // Test lengths on an empty text object Text text = new Text(); assertEquals( "Actual string on an empty text object must be an empty string", "", text.toString()); assertEquals("Underlying byte array length must be zero", ...
public WriteFileP( @Nonnull String directoryName, @Nonnull FunctionEx<? super T, ? extends String> toStringFn, @Nonnull String charset, @Nullable String dateFormatter, long maxFileSize, boolean exactlyOnce, @Nonnull LongSupplier clock ...
@Test public void when_slowSource_then_fileFlushedAfterEachItem() { // Given int numItems = 10; DAG dag = new DAG(); Vertex source = dag.newVertex("source", () -> new SlowSourceP(semaphore, numItems)) .localParallelism(1); Vertex sink = dag.newVert...
@Override public void route(ProcessContext context) throws FrameworkException { try { ProcessType processType = matchProcessType(context); if (processType == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Process type not found, context= {}", ...
@Test public void testRouteOfFrameworkException() { ProcessContextImpl context = new ProcessContextImpl(); DefaultRouterHandler defaultRouterHandler = new DefaultRouterHandler(); Assertions.assertThrows(FrameworkException.class, () -> defaultRouterHandler.route(context)); }
static void readFullyHeapBuffer(InputStream f, ByteBuffer buf) throws IOException { readFully(f, buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); buf.position(buf.limit()); }
@Test public void testHeapReadFullyLargeBuffer() throws Exception { final ByteBuffer readBuffer = ByteBuffer.allocate(20); final MockInputStream stream = new MockInputStream(); TestUtils.assertThrows("Should throw EOFException", EOFException.class, () -> { DelegatingSeekableInputStream.readFullyHe...
public ActorSystem getActorSystem() { return actorSystem; }
@Test void testRpcServiceShutDownWithFailingRpcEndpoints() throws Exception { final PekkoRpcService pekkoRpcService = startRpcService(); final int numberActors = 5; final RpcServiceShutdownTestHelper rpcServiceShutdownTestHelper = startStopNCountingAsynchronousOnStopEndpoin...
@Override public GcsPath getFileName() { int nameCount = getNameCount(); if (nameCount < 2) { throw new UnsupportedOperationException( "Can't get filename from root path in the bucket: " + this); } return getName(nameCount - 1); }
@Test public void testGetFileName() { assertEquals("foo", GcsPath.fromUri("gs://bucket/bar/foo").getFileName().toString()); assertEquals("foo", GcsPath.fromUri("gs://bucket/foo").getFileName().toString()); thrown.expect(UnsupportedOperationException.class); GcsPath.fromUri("gs://bucket/").getFileName(...
@Override public void handlerPlugin(final PluginData pluginData) { Map<String, String> configMap = GsonUtils.getInstance().toObjectMap(pluginData.getConfig(), String.class); final String endpoint = Optional.ofNullable(configMap.get("endpoint")).orElse(""); final String clientSecrect = Option...
@Test public void handlerPlugin() { final PluginData pluginData = new PluginData("pluginId", "pluginName", "{\"organization-name\":\"test\",\"application-name\":\"app-test\",\"endpoint\":\"http://localhost:8000\",\"client_secrect\":\"a4209d412a33a842b7a9c05a3446e623cbb7262d\",\"client_id\":\"6e3a84154e73d1f...
protected boolean isShadedJar(Dependency dependency, Dependency nextDependency) { if (dependency == null || dependency.getFileName() == null || nextDependency == null || nextDependency.getFileName() == null || dependency.getSoftwareIdentifiers().isEmpty() || nextD...
@Test public void testIsShaded() throws MalformedPackageURLException { DependencyBundlingAnalyzer instance = new DependencyBundlingAnalyzer(); Dependency left = null; Dependency right = null; boolean expResult = false; boolean result = instance.isShadedJar(left, right); ...
@Override public boolean remove(Object objectToRemove) { return remove(objectToRemove, objectToRemove.hashCode()); }
@Test(expected = NullPointerException.class) public void testRemoveWithHashNull() { final OAHashSet<Integer> set = new OAHashSet<>(8); set.remove(null, 1); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthUninstallFilter() throws Exception { web3j.ethUninstallFilter(Numeric.toBigInt("0xb")).send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"eth_uninstallFilter\"," + "\"params\":[\"0xb\"],\"id\":1}"); }
public static String[] list(File dir) throws IOException { if (!canRead(dir)) { throw new AccessDeniedException(dir.toString(), null, FSExceptionMessages.PERMISSION_DENIED); } String[] fileNames = dir.list(); if(fileNames == null) { throw new IOException("Invalid directory or I/O e...
@Test (timeout = 30000) public void testListAPI() throws IOException { //Test existing files case String[] files = FileUtil.list(partitioned); Assert.assertEquals("Unexpected number of pre-existing files", 2, files.length); //Test existing directory with no files case File newDir = new File(tmp...
public void removeEntry(String id) { UrlWhitelist modified = removeEntry(getWhitelist(), id); saveWhitelist(modified); }
@Test public void removeEntry() { final WhitelistEntry entry = LiteralWhitelistEntry.create("a", "a", "a"); final UrlWhitelist whitelist = UrlWhitelist.createEnabled(Collections.singletonList(entry)); assertThat(urlWhitelistService.removeEntry(whitelist, null)).isEqualTo(whitelist); ...
public Resource getIncrementAllocation() { Long memory = null; Integer vCores = null; Map<String, Long> others = new HashMap<>(); ResourceInformation[] resourceTypes = ResourceUtils.getResourceTypesArray(); for (int i=0; i < resourceTypes.length; ++i) { String name = resourceTypes[i].getName()...
@Test public void testCpuIncrementConfiguredViaMultipleProperties() { TestAppender testAppender = new TestAppender(); Logger logger = LogManager.getRootLogger(); logger.addAppender(testAppender); try { Configuration conf = new Configuration(); conf.set("yarn.scheduler.increment-allocation-...
@SuppressWarnings("unchecked") public static <T> AgentServiceLoader<T> getServiceLoader(final Class<T> service) { return (AgentServiceLoader<T>) LOADERS.computeIfAbsent(service, AgentServiceLoader::new); }
@Test void assertGetServiceLoaderWithNullValue() { assertThrows(NullPointerException.class, () -> AgentServiceLoader.getServiceLoader(null)); }
public final List<E> findAll(E key) { if (key == null || size() == 0) { return Collections.emptyList(); } ArrayList<E> results = new ArrayList<>(); int slot = slot(elements, key); for (int seen = 0; seen < elements.length; seen++) { Element element = eleme...
@Test public void testInsertDelete() { ImplicitLinkedHashMultiCollection<TestElement> multiSet = new ImplicitLinkedHashMultiCollection<>(100); TestElement e1 = new TestElement(1); TestElement e2 = new TestElement(1); TestElement e3 = new TestElement(2); multiSet.mustAdd(e1); ...
public SchemaCommand(Logger console) { super(console); }
@Test public void testSchemaCommand() throws IOException { File file = parquetFile(); SchemaCommand command = new SchemaCommand(createLogger()); command.targets = Arrays.asList(file.getAbsolutePath()); command.setConf(new Configuration()); Assert.assertEquals(0, command.run()); }
public void applyClientConfiguration(String account, DataLakeFileSystemClientBuilder builder) { String sasToken = adlsSasTokens.get(account); if (sasToken != null && !sasToken.isEmpty()) { builder.sasToken(sasToken); } else if (namedKeyCreds != null) { builder.credential( new StorageSh...
@Test public void testWithConnectionString() { AzureProperties props = new AzureProperties(ImmutableMap.of("adls.connection-string.account1", "http://endpoint")); DataLakeFileSystemClientBuilder clientBuilder = mock(DataLakeFileSystemClientBuilder.class); props.applyClientConfiguration("account1"...
public long getMax() { return maxDate; }
@Test public void max_is_zero_if_no_dates() { assertThat(collector.getMax()).isZero(); }
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchDiscardedAfterPausedPartitionResumedAndSeekedToNewOffset() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertEquals(1, sendFetches()); subscriptions.pause(tp0); client.prepareResponse(fullFetchResponse(tidp...
public static Read read() { return new AutoValue_AmqpIO_Read.Builder().setMaxNumRecords(Long.MAX_VALUE).build(); }
@Test public void testRead() throws Exception { PCollection<Message> output = pipeline.apply( AmqpIO.read() .withMaxNumRecords(100) .withAddresses(Collections.singletonList(broker.getQueueUri("testRead")))); PAssert.thatSingleton(output.apply(Count.globally(...
public String run() throws IOException { Process process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); try { // read the output...
@Test public void execCommand() throws Exception { String testString = "alluxio"; // Execute echo for testing command execution. String[] cmd = new String[]{"bash", "-c", "echo " + testString}; String result = new ShellCommand(cmd).run(); assertEquals(testString + "\n", result); }
protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,...
@Test public void testPkcs8Pbes2() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pbes2_enc_pkcs8.key") .getFile()), "12345678", false); assertNotNull(key); }
@Override public String loadPlugin(Path pluginPath) { throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute loadPlugin!"); }
@Test public void loadPlugin() { assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.loadPlugin(thisPlugin.path())); }
public static <T> RBFNetwork<T> fit(T[] x, double[] y, RBF<T>[] rbf) { return fit(x, y, rbf, false); }
@Test public void testLongley() throws Exception { System.out.println("longley"); MathEx.setSeed(19650218); // to get repeatable results. double[][] x = MathEx.clone(Longley.x); MathEx.standardize(x); RegressionMetrics metrics = LOOCV.regression(x, Longley.y, ...
@Override public void logoutFailure(HttpRequest request, String errorMessage) { checkRequest(request); requireNonNull(errorMessage, "error message can't be null"); if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug("logout failure [error|{}][IP|{}|{}]", emptyIfNull(errorMessage), ...
@Test public void logout_creates_DEBUG_log_with_error() { underTest.logoutFailure(mockRequest(), "bad token"); verifyLog("logout failure [error|bad token][IP||]", Set.of("login", "logout success")); }
public String getOriginDisplayName() { return getOrigin() != null ? getOrigin().displayName() : new FileConfigOrigin().displayName(); }
@Test public void shouldReturnConfigRepoOriginDisplayNameWhenOriginIsNotSet() { PipelineConfig pipelineConfig = new PipelineConfig(); assertThat(pipelineConfig.getOriginDisplayName(), is("cruise-config.xml")); }
@Override public String getMetaServerAddress(Env targetEnv) { return addresses.get(targetEnv); }
@Test public void testGetMetaServerAddress() { String address = databasePortalMetaServerProvider.getMetaServerAddress(Env.DEV); assertEquals("http://server.com:8080", address); String newMetaServerAddress = "http://another-server.com:8080"; metaServiceMap.put("dev", newMetaServerAddress); databa...
@Override public Message request(final Message msg, final long timeout) throws RequestTimeoutException, MQClientException, RemotingException, MQBrokerException, InterruptedException { msg.setTopic(withNamespace(msg.getTopic())); return this.defaultMQProducerImpl.request(msg, timeout); }
@Test(expected = RequestTimeoutException.class) public void testRequestMessage_RequestTimeoutException() throws RemotingException, RequestTimeoutException, MQClientException, InterruptedException, MQBrokerException { when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(cr...
public static void delete(File fileOrDir) throws IOException { if (fileOrDir == null) { return; } if (fileOrDir.isDirectory()) { cleanDirectory(fileOrDir); } else { if (fileOrDir.exists()) { boolean isDeleteOk = fileOrDir.delete(); ...
@Test public void testDelete() throws IOException { File deleteFile = new File(tempDir.toFile(), "delete.txt"); deleteFile.createNewFile(); Assert.assertTrue(deleteFile.exists()); IoUtil.delete(deleteFile); Assert.assertFalse(deleteFile.exists()); File deleteDir = new...
public static Db use() { return use(DSFactory.get()); }
@Test public void findByTest() throws SQLException { List<Entity> find = Db.use().findBy("user", Condition.parse("age", "> 18"), Condition.parse("age", "< 100") ); for (Entity entity : find) { StaticLog.debug("{}", entity); } assertEquals("unitTestUser", find.get(0).get("name")); }
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("position") BigDecimal position, @ParameterName("newItem") Object newItem) { if (list == null) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", CANNO...
@Test void invokeReplaceByPositionWithNotNull() { List list = getList(); List expected = new ArrayList<>(list); expected.set(1, "test"); FunctionTestUtil.assertResult(listReplaceFunction.invoke(list, BigDecimal.valueOf(2), "test"), expected); }
public RecurringJobBuilder withZoneId(ZoneId zoneId) { this.zoneId = zoneId; return this; }
@Test void testWithZoneId() { RecurringJob recurringJob = aRecurringJob() .withZoneId(ZoneId.of("Europe/Brussels")) .withCron(every5Seconds) .withDetails(() -> testService.doWork()) .build(jobDetailsGenerator); assertThat(recurringJob)...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<Path>(); // At least one entry successfully parsed boolean success = false; // Call hook for those im...
@Test(expected = FTPInvalidListException.class) public void testListNoRead() throws Exception { final Path directory = new Path("/sandbox/noread", EnumSet.of(Path.Type.directory)); final String[] lines = new String[]{ "213-Status follows:", "d-w--w---- 2 1003 1003 ...
public static <K, V> AsMultimap<K, V> asMultimap() { return new AsMultimap<>(false); }
@Test @Category({ValidatesRunner.class}) public void testMultimapSideInputWithNonDeterministicKeyCoder() { final PCollectionView<Map<String, Iterable<Integer>>> view = pipeline .apply( "CreateSideInput", Create.of(KV.of("a", 1), KV.of("a", 1), KV.of("a", 2), ...
@Override KeyGroupsStateHandle closeAndGetHandle() throws IOException { StreamStateHandle streamStateHandle = super.closeAndGetHandleAfterLeasesReleased(); return streamStateHandle != null ? new KeyGroupsStateHandle(keyGroupRangeOffsets, streamStateHandle) : null; ...
@Test void testEmptyKeyedStream() throws Exception { final KeyGroupRange keyRange = new KeyGroupRange(0, 2); KeyedStateCheckpointOutputStream stream = createStream(keyRange); TestMemoryCheckpointOutputStream innerStream = (TestMemoryCheckpointOutputStream) stream.getDelegate(...
@Override public void deleteGroup(Long id) { // 校验存在 validateGroupExists(id); // 校验分组下是否有用户 validateGroupHasUser(id); // 删除 memberGroupMapper.deleteById(id); }
@Test public void testDeleteGroup_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> groupService.deleteGroup(id), GROUP_NOT_EXISTS); }
public void createMapping( String mappingName, String tableName, List<SqlColumnMetadata> mappingColumns, String dataConnectionRef, String idColumn ) { sqlService.execute( createMappingQuery(mappingName, tableName, mappingColumns, d...
@Test @SuppressWarnings("OperatorWrap") public void when_createMappingWithTwoColumns_then_quoteParameters() { mappingHelper.createMapping( "myMapping", "myTable", asList( new SqlColumnMetadata("id", SqlColumnType.INTEGER, true), ...
public static String convertMsToClockTime(long millis) { Preconditions.checkArgument(millis >= 0, "Negative values %s are not supported to convert to clock time.", millis); long days = millis / Constants.DAY_MS; long hours = (millis % Constants.DAY_MS) / Constants.HOUR_MS; long mins = (millis %...
@Test public void convertMsToClockTime() { assertEquals("0 day(s), 0 hour(s), 0 minute(s), and 0 second(s)", CommonUtils.convertMsToClockTime(10)); assertEquals("0 day(s), 0 hour(s), 0 minute(s), and 1 second(s)", CommonUtils.convertMsToClockTime(TimeUnit.SECONDS.toMillis(1))); assertEqual...
public QueryConsumeQueueResponseBody queryConsumeQueue(final String brokerAddr, final String topic, final int queueId, final long index, final int count, final String consumerGroup, final long timeoutMillis) throws InterruptedException, RemotingTimeoutException, RemotingSendRequestExcept...
@Test public void assertQueryConsumeQueue() throws RemotingException, InterruptedException, MQClientException { mockInvokeSync(); QueryConsumeQueueResponseBody responseBody = new QueryConsumeQueueResponseBody(); responseBody.setQueueData(Collections.singletonList(new ConsumeQueueData())); ...
@Override public ExportResult<MediaContainerResource> export( UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) throws UploadErrorException, FailedToListAlbumsException, InvalidTokenException, PermissionDeniedException, IOException, FailedToListMediaItemsExcepti...
@Test public void testExportAlbums_failureInterruptsTransfer() throws Exception { String albumIdToFail1 = "albumid3"; String albumIdToFail2 = "albumid5"; ImmutableList<PhotoModel> photos = ImmutableList.of(); ImmutableList<PhotoAlbum> albums = ImmutableList.of( setUpSinglePhotoAlbum("albumid1...
@Override public int remainingCapacity() { int sum = 0; for (BlockingQueue<E> q : this.queues) { sum += q.remainingCapacity(); } return sum; }
@Test public void testTotalCapacityOfSubQueues() { Configuration conf = new Configuration(); FairCallQueue<Schedulable> fairCallQueue; fairCallQueue = new FairCallQueue<Schedulable>(1, 1000, "ns", conf); assertThat(fairCallQueue.remainingCapacity()).isEqualTo(1000); fairCallQueue = new FairCallQue...
@Override public <T> List<SearchResult<T>> search(SearchRequest request, Class<T> typeFilter) { SearchSession<T> session = new SearchSession<>(request, Collections.singleton(typeFilter)); if (request.inParallel()) { ForkJoinPool commonPool = ForkJoinPool.commonPool(); getPro...
@Test public void testFuzzyLabel() { GraphGenerator generator = GraphGenerator.build().generateTinyGraph(); Node node = generator.getGraph().getNode(GraphGenerator.FIRST_NODE); node.setLabel("foobar"); List<Element> r1 = toList(controller.search(buildRequest("foo", generator), Elem...
@Override public void configure(final Map<String, ?> config) { configure( config, new Options(), org.rocksdb.LRUCache::new, org.rocksdb.WriteBufferManager::new ); }
@Test public void shouldFailIfConfiguredTwiceFromDifferentInstances() { // Given: rocksDBConfig.configure(CONFIG_PROPS); // Expect: // When: final Exception e = assertThrows( IllegalStateException.class, () -> secondRocksDBConfig.configure(CONFIG_PROPS) ); // Then: as...
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PRO...
@Test void assertGetBinaryProtocolValueWithMySQLTypeSet() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.SET), instanceOf(MySQLStringLenencBinaryProtocolValue.class)); }
@Override public boolean isQualified(final SQLStatementContext sqlStatementContext, final ReadwriteSplittingDataSourceGroupRule rule, final HintValueContext hintValueContext) { return isPrimaryRoute(sqlStatementContext, hintValueContext); }
@Test void assertHintRouteWriteOnly() { when(sqlStatementContext.getSqlStatement()).thenReturn(mock(SelectStatement.class)); when(hintValueContext.isWriteRouteOnly()).thenReturn(false); assertFalse(new QualifiedReadwriteSplittingPrimaryDataSourceRouter().isQualified(sqlStatementContext, null...
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet()); }
@Test public void cleaningTraceIsIdempotent() { Throwable throwable = createThrowableWithStackTrace("com.example.Foo", "org.junit.FilterMe"); StackTraceCleaner.cleanStackTrace(throwable); StackTraceCleaner.cleanStackTrace(throwable); assertThat(throwable.getStackTrace()).isEqualTo(createStackTrace("...
@Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); ...
@Test public void testGetFieldDefinition() { assertEquals( "FOO TIMESTAMP", nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) ); assertEquals( "TIMESTAMP", nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, false, false ) ); ...
@Override public void destroy() { for (MappedFile mf : this.mappedFiles) { mf.destroy(1000 * 3); } this.mappedFiles.clear(); this.setFlushedWhere(0); Set<String> storePathSet = getPaths(); storePathSet.addAll(getReadonlyPaths()); for (String path...
@Test public void testGetLastMappedFile() { final byte[] fixedMsg = new byte[1024]; MessageStoreConfig config = new MessageStoreConfig(); config.setStorePathCommitLog("target/unit_test_store/a/" + MixAll.MULTI_PATH_SPLITTER + "target/unit_test_store/b/" + MixAll.MULTI_PATH_S...
@Inject public ConfigSentinelClient() { supervisor = new Supervisor(new Transport("sentinel-client")).setDropEmptyBuffers(true); }
@Test public void testConfigSentinelClient() { ConfigSentinelDummy configsentinel = new ConfigSentinelDummy(); List<VespaService> services = new ArrayList<>(); VespaService docproc = new VespaService("docprocservice", "docproc/cluster.x.indexing/0"); VespaService searchnode4 = new Ve...
protected Map<String, Integer> getNumPartitions(final Set<String> topics, final Set<String> tempUnknownTopics) { log.debug("Trying to check if topics {} have been created with expected number of partitions.", topics); final Map<String, List<TopicParti...
@Test public void shouldReturnCorrectPartitionCounts() { mockAdminClient.addTopic( false, topic1, Collections.singletonList(new TopicPartitionInfo(0, broker1, singleReplica, Collections.emptyList())), null); assertEquals(Collections.singletonMap(topic1...
File globalStateDir() { final File dir = new File(stateDir, "global"); if (hasPersistentStores) { if (!dir.exists() && !dir.mkdir()) { throw new ProcessorStateException( String.format("global state directory [%s] doesn't exist and couldn't be created", dir...
@Test public void shouldNotCreateGlobalStateDirectory() throws IOException { initializeStateDirectory(false, false); final File globalStateDir = directory.globalStateDir(); assertFalse(globalStateDir.exists()); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tuple3<?, ?, ?> tuple3 = (Tuple3<?, ?, ?>) o; return Objects.equals(f0, tuple3.f0) && Objects.equals(f1, tuple3.f1) && Objects....
@Test public void testEquals() { assertEquals(Tuple3.of(1, "a", 1.1), Tuple3.of(1, "a", 1.1)); assertEquals(Tuple3.of(1, "a", 1.1).hashCode(), Tuple3.of(1, "a", 1.1).hashCode()); }
public int accumulateMul(int... nums) { LOGGER.info("Source module {}", VERSION); var sum = 1; for (final var num : nums) { sum *= num; } return sum; }
@Test void testAccumulateMul() { assertEquals(0, source.accumulateMul(-1, 0, 1)); }
public MaterializedConfiguration getConfiguration() { MaterializedConfiguration conf = new SimpleMaterializedConfiguration(); FlumeConfiguration fconfig = getFlumeConfiguration(); AgentConfiguration agentConf = fconfig.getConfigurationFor(getAgentName()); if (agentConf != null) { ...
@Test public void testDispoableChannel() throws Exception { String agentName = "agent1"; Map<String, String> properties = getPropertiesForChannel(agentName, DisposableChannel.class.getName()); MemoryConfigurationProvider provider = new MemoryConfigurationProvi...
@Override public <VR> KTable<K, VR> mapValues(final ValueMapper<? super V, ? extends VR> mapper) { Objects.requireNonNull(mapper, "mapper can't be null"); return doMapValues(withKey(mapper), NamedInternal.empty(), null); }
@Test public void shouldNotAllowNullMapperOnMapValueWithKey() { assertThrows(NullPointerException.class, () -> table.mapValues((ValueMapperWithKey) null)); }
public static DateTimeFormatter timeFormatterWithOptionalMilliseconds() { // This is the .SSS part DateTimeParser ms = new DateTimeFormatterBuilder() .appendLiteral(".") .appendFractionOfSecond(1, 3) .toParser(); return new DateTimeFormatterBuilde...
@Test public void testTimeFormatterWithOptionalMilliseconds() { /* * We can actually consider this working if it does not throw parser exceptions. * Check the toString() representation to make sure though. (using startsWith() * to avoid problems on test systems in other time zones...
@Operation(summary = "Get single organization") @GetMapping(value = "name/{name}", produces = "application/json") @ResponseBody public Organization getByName(@PathVariable("name") String name) { return organizationService.getOrganizationByName(name); }
@Test public void organizationNameNotFound() { when(organizationServiceMock.getOrganizationByName(anyString())).thenThrow(NotFoundException.class); assertThrows(NotFoundException.class, () -> { controllerMock.getByName("test"); }); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { return new DeepBoxesListService().list(directory, listener); } if(containerService.isDeepbox(directory)) { // in DeepBox ...
@Test // In this test setting, we get a NodeId from Box REST API and have canListFilesRoot==true for the documents folder. // When listing the files for this nodId or when we try to get its NodeInfo, we get 403. // Still, subfolders of documents are accessible (by listing the boxes files, but without pass...
public static IOException wrapException(final String path, final String methodName, final IOException exception) { if (exception instanceof InterruptedIOException || exception instanceof PathIOException) { return exception; } else { String msg = String .format("Failed with %...
@Test public void testWrapException() throws Exception { // Test for IOException with valid (String) constructor LambdaTestUtils.intercept(EOFException.class, "Failed with java.io.EOFException while processing file/directory " + ":[/tmp/abc.txt] in method:[testWrapException]", () -> { ...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { String s = new String(rawMessage.getPayload(), StandardCharsets.UTF_8); LOG.trace("Received raw message: {}", s); String timezoneID = configuration.getString(CK_TIMEZONE); // previously existing PA input...
@Test public void testAllSyslogFormats() { PaloAltoCodec codec = new PaloAltoCodec(Configuration.EMPTY_CONFIGURATION, messageFactory); Message message = codec.decode(new RawMessage(SYSLOG_THREAT_MESSAGE.getBytes(StandardCharsets.UTF_8))); assertEquals("THREAT", message.getField("type")); ...