focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean exists(String path) throws IOException { return fs.exists(makePath(path)); }
@Test public void testExists() throws IOException { System.out.println("pre-create test path"); fs.mkdirs(new Path("test/registryTestNode")); System.out.println("Check for existing node"); boolean exists = registry.exists("test/registryTestNode"); Assert.assertTrue(exists); System.out.printl...
@Override public List<String> list() { final List<String> list = new ArrayList<>(); try { final javax.net.ssl.X509KeyManager manager = this.getKeystore(); { final String[] aliases = manager.getClientAliases("RSA", null); if(null != aliases) { ...
@Test public void testList() { assertTrue(new DefaultX509KeyManager().init().list().isEmpty()); }
public static PDImageXObject createFromStream(PDDocument document, InputStream stream) throws IOException { return createFromByteArray(document, stream.readAllBytes()); }
@Test void testCreateFromStream() throws IOException { PDDocument document = new PDDocument(); InputStream stream = JPEGFactoryTest.class.getResourceAsStream("jpeg.jpg"); PDImageXObject ximage = JPEGFactory.createFromStream(document, stream); validate(ximage, 8, 344, 287, "jpg", ...
public ServiceInfo getData(Service service) { return serviceDataIndexes.containsKey(service) ? serviceDataIndexes.get(service) : getPushData(service); }
@Test void testGetData() { ServiceInfo serviceInfo = serviceStorage.getData(SERVICE); assertNotNull(serviceInfo); }
@Override public void verify(byte[] data, byte[] signature, MessageDigest digest) { final byte[] decrypted = engine.processBlock(signature, 0, signature.length); final int delta = checkSignature(decrypted, digest); final int offset = decrypted.length - digest.getDigestLength() - delta; ...
@Test public void shouldThrowVerificationExceptionIfSignatureIsInvalid() { final byte[] challenge = CryptoUtils.random(40); final byte[] invalid = challenge.clone(); invalid[0]++; final byte[] signature = sign(0x54, invalid, ISOTrailers.TRAILER_SHA1, "SHA1"); thrown.expect(Ve...
@Override public String rpcType() { return RpcTypeEnum.MOTAN.getName(); }
@Test public void testRpcType() { String rpcType = shenyuClientRegisterMotanService.rpcType(); assertEquals(RpcTypeEnum.MOTAN.getName(), rpcType); }
@Override String getInterfaceName(Invoker invoker, String prefix) { return DubboUtils.getInterfaceName(invoker, prefix); }
@Test public void testDegradeAsync() throws InterruptedException { try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) { setCurrentMillis(mocked, 1740000000000L); Invocation invocation = DubboTestUtil.getDefaultMockInvocationOne(); Invoker invoker = DubboTestUtil....
@Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final Set<Evidence> remove; if (dependency.getVersion() != null) { remove = dependency.getEvidence(EvidenceType.VERSION).stream() .filter(e -> !e.isFromHint() ...
@Test public void testAnalyzeDependencyFileManifest() throws Exception { Dependency dependency = new Dependency(); dependency.addEvidence(EvidenceType.VERSION, "util", "version", "33.3", Confidence.HIGHEST); dependency.addEvidence(EvidenceType.VERSION, "other", "version", "alpha", Confidenc...
@Override public Iterable<K> loadAllKeys() { // If loadAllKeys property is disabled, don't load anything if (!genericMapStoreProperties.loadAllKeys) { return Collections.emptyList(); } awaitSuccessfulInit(); String sql = queries.loadAllKeys(); SqlResult ...
@Test public void givenRowAndIdColumn_whenLoadAllKeysWithSingleColumn_thenReturnKeys() { ObjectSpec spec = objectProvider.createObject(mapName, true); objectProvider.insertItems(spec, 1); Properties properties = new Properties(); properties.setProperty(DATA_CONNECTION_REF_PROPERTY, ...
public int getDelegationTokenFailedRetrieved() { return numGetDelegationTokenFailedRetrieved.value(); }
@Test public void testGetDelegationTokenRetrievedFailed() { long totalBadBefore = metrics.getDelegationTokenFailedRetrieved(); badSubCluster.getDelegationTokenFailed(); Assert.assertEquals(totalBadBefore + 1, metrics.getDelegationTokenFailedRetrieved()); }
public static boolean contains(final Object[] array, final Object objectToFind) { if (array == null) { return false; } return Arrays.asList(array).contains(objectToFind); }
@Test void contains() { assertFalse(ArrayUtils.contains(nullArr, "a")); assertFalse(ArrayUtils.contains(nullArr, null)); assertFalse(ArrayUtils.contains(nothingArr, "b")); Integer[] arr = new Integer[] {1, 2, 3}; assertFalse(ArrayUtils.contains(arr, null)); Integer[] ...
public static void initKalkanProvider() { if (!isAddedKalkan) { synchronized (SecurityProviderInitializer.class) { if (!isAddedKalkan) { logger.info("Trying to add KalkanProvider to Security providers.."); Security.addProvider(new KalkanProvide...
@Test public void initKalkanProvider_AddsKalkanProviderOnce() { SecurityProviderInitializer.initKalkanProvider(); logger.info("Checking if KalkanProvider is added to Security providers.."); assertSecurityProvidersContains(KalkanProvider.class); logger.info("Initialized again to che...
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 testHeapReadFullyPosition() throws Exception { final ByteBuffer readBuffer = ByteBuffer.allocate(10); readBuffer.position(3); readBuffer.mark(); MockInputStream stream = new MockInputStream(2, 3, 3); DelegatingSeekableInputStream.readFullyHeapBuffer(stream, readBuffer); Ass...
public final void containsAnyOf( @Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) { containsAnyIn(accumulate(first, second, rest)); }
@Test public void iterableContainsAnyOfFailsWithSameToStringAndNullInSubject() { expectFailureWhenTestingThat(asList(null, "abc")).containsAnyOf("def", "null"); assertFailureKeys( "expected to contain any of", "but did not", "though it did contain", "full contents"); assertFailureValue("expected t...
@VisibleForTesting static boolean isUriValid(String uri) { Matcher matcher = URI_PATTERN.matcher(uri); return matcher.matches(); }
@Test public void testInvalidUri() { assertThat( HttpCacheServerHandler.isUriValid( "http://localhost:8080/ac_e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) .isFalse(); assertThat( HttpCacheServerHandler.isUriValid( "http://l...
static void applySchemaUpdates(Table table, SchemaUpdate.Consumer updates) { if (updates == null || updates.empty()) { // no updates to apply return; } Tasks.range(1) .retry(IcebergSinkConfig.SCHEMA_UPDATE_RETRIES) .run(notUsed -> commitSchemaUpdates(table, updates)); }
@Test public void testApplyNestedSchemaUpdates() { UpdateSchema updateSchema = mock(UpdateSchema.class); Table table = mock(Table.class); when(table.schema()).thenReturn(NESTED_SCHEMA); when(table.updateSchema()).thenReturn(updateSchema); // the updates to "st.i" should be ignored as it already e...
public Long getUsableSpace() { return usableSpace; }
@Test public void shouldInitializeTheFreeSpaceAtAgentSide() { AgentIdentifier id = new Agent("uuid", "localhost", "176.19.4.1").getAgentIdentifier(); AgentRuntimeInfo agentRuntimeInfo = new AgentRuntimeInfo(id, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"); assertThat(agentR...
public static Optional<IndexSetValidator.Violation> validate(ElasticsearchConfiguration elasticsearchConfiguration, IndexLifetimeConfig retentionConfig) { Period indexLifetimeMin = retentionConfig.indexLifetimeMin(); Period indexLifetimeMa...
@Test void testAllowFlexiblePeriodFlag() { when(elasticConfig.getTimeSizeOptimizingRotationPeriod()).thenReturn(Period.minutes(1)); when(elasticConfig.getTimeSizeOptimizingRetentionFixedLeeway()).thenReturn(Period.minutes(1)); IndexLifetimeConfig config = IndexLifetimeConfig.builder() ...
public WeightedItem<T> addOrVote(T item) { for (int i = 0; i < list.size(); i++) { WeightedItem<T> weightedItem = list.get(i); if (weightedItem.item.equals(item)) { voteFor(weightedItem); return weightedItem; } } return organize...
@Test public void testScenario() { WeightedEvictableList<String> list = new WeightedEvictableList<>(3, 3); list.addOrVote("a"); list.addOrVote("b"); list.addOrVote("c"); // 3 iterations are here, now list will organize itself. Since all items have 1 vote, order does not chan...
@GET @Path("/entity-uid/{uid}/") @Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8) public TimelineEntity getEntity( @Context HttpServletRequest req, @Context HttpServletResponse res, @PathParam("uid") String uId, @QueryParam("confstoretrieve") String confsToRetrieve, @Q...
@Test void testGetEntitiesByRelations() throws Exception { Client client = createClient(); try { URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" + "timeline/clusters/cluster1/apps/app1/entities/app?relatesto=" + "flow:flow1"); ClientResponse resp = getResponse...
@Override public boolean isSubscribed(String serviceName, String groupName, String clusters) throws NacosException { return true; }
@Test void testIsSubscribed() throws NacosException { assertTrue(clientProxy.isSubscribed("serviceName", "group1", "clusters")); }
public NODE remove(int index) { throw e; }
@Test void require_that_remove_index_throws_exception() { assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").remove(0)); }
public static List<Interval> normalize(List<Interval> intervals) { if (intervals.size() <= 1) { return intervals; } List<Interval> valid = intervals.stream().filter(Interval::isValid).collect(Collectors.toList()); if (valid.size() <= 1) { return valid; } // 2 or more interva...
@Test public void normalizeSimple() { List<Interval> i; i = IntervalUtils.normalize(Collections.emptyList()); Assert.assertTrue(i.isEmpty()); i = IntervalUtils.normalize(Arrays.asList(Interval.NEVER, Interval.NEVER, Interval.NEVER)); Assert.assertTrue(i.isEmpty()); i = IntervalUtils.normali...
@Override public <K> Iterable<K> findIds(Class<?> entityClass) { return findIds(entityClass, 10); }
@Test public void testFindIds() { RLiveObjectService s = redisson.getLiveObjectService(); TestIndexed1 t1 = new TestIndexed1(); t1.setId("1"); t1.setKeywords(Collections.singletonList("132323")); TestIndexed1 t2 = new TestIndexed1(); t2.setId("2"); t2.setKeywo...
public static UArrayTypeTree create(UExpression elementType) { return new AutoValue_UArrayTypeTree(elementType); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UArrayTypeTree.create(UPrimitiveTypeTree.INT)) .addEqualityGroup(UArrayTypeTree.create(UClassIdent.create("java.lang.String"))) .addEqualityGroup(UArrayTypeTree.create(UArrayTypeTree.create(UPrimitiveTypeTree.INT))) ...
@Override public SecurityModeState getState(ApplicationId appId) { return states.asJavaMap().getOrDefault(appId, new SecurityInfo(null, null)).getState(); }
@Test public void testGetState() { assertEquals(SECURED, states.get(appId).getState()); }
@Override public AlterUserScramCredentialsResult alterUserScramCredentials(List<UserScramCredentialAlteration> alterations, AlterUserScramCredentialsOptions options) { final long now = time.milliseconds(); final Map<String, KafkaFu...
@Test public void testAlterUserScramCredentials() { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); final String user0Name = "user0"; ScramMechanism user0ScramMechanism0 = ScramMechanism.SCRAM_SHA_256; ...
GuardedScheduler(Scheduler delegate) { this.delegate = requireNonNull(delegate); }
@Test public void guardedScheduler() { var future = Scheduler.guardedScheduler((r, e, d, u) -> Futures.immediateVoidFuture()) .schedule(Runnable::run, () -> {}, 1, TimeUnit.MINUTES); assertThat(future).isSameInstanceAs(Futures.immediateVoidFuture()); }
public Bson parseSingleExpression(final String filterExpression, final List<EntityAttribute> attributes) { final Filter filter = singleFilterParser.parseSingleExpression(filterExpression, attributes); return filter.toBson(); }
@Test void parsesFilterExpressionForStringFieldsCorrectlyEvenIfValueContainsRangeSeparator() { final List<EntityAttribute> entityAttributes = List.of(EntityAttribute.builder() .id("text") .title("Text") .type(SearchQueryField.Type.STRING) .filt...
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception { CruiseConfig configForEdit; CruiseConfig config; LOGGER.debug("[Config Save] Loading config holder"); configForEdit = deserializeConfig(content); if (callback != null) callback.call...
@Test void shouldLoadConfigWithNoEnvironment() throws Exception { String content = configWithEnvironments("", CONFIG_SCHEMA_VERSION); EnvironmentsConfig environmentsConfig = xmlLoader.loadConfigHolder(content).config.getEnvironments(); EnvironmentPipelineMatchers matchers = environmentsConfi...
@Override public void load(String mountTableConfigPath, Configuration conf) throws IOException { this.mountTable = new Path(mountTableConfigPath); String scheme = mountTable.toUri().getScheme(); FsGetter fsGetter = new ViewFileSystemOverloadScheme.ChildFsGetter(scheme); try (FileSystem fs = fsGe...
@Test public void testMountTableFileWithInvalidFormatWithNoDotsInName() throws Exception { Path path = new Path(new URI(targetTestRoot.toString() + "/testMountTableFileWithInvalidFormatWithNoDots/")); fsTarget.mkdirs(path); File invalidMountFileName = new File(new URI(path.toString()...
@Override public <V> MultiLabel generateOutput(V label) { if (label instanceof Collection) { Collection<?> c = (Collection<?>) label; List<Pair<String,Boolean>> dimensions = new ArrayList<>(); for (Object o : c) { dimensions.add(MultiLabel.parseElement(o.t...
@Test public void testGenerateOutput_unparseable() { MultiLabelFactory factory = new MultiLabelFactory(); MultiLabel output = factory.generateOutput(new Unparseable()); assertEquals(1, output.getLabelSet().size()); assertTrue(output.getLabelString().startsWith("org.tribuo.multilabel....
public abstract String dn();
@Test void dn() { final LDAPEntry entry = LDAPEntry.builder() .dn("cn=jane,ou=people,dc=example,dc=com") .base64UniqueId(Base64.encode("unique-id")) .addAttribute("foo", "bar") .build(); assertThat(entry.dn()).isEqualTo("cn=jane,ou=peo...
public static String formatSimple(long amount) { if (amount < 1_0000 && amount > -1_0000) { return String.valueOf(amount); } String res; if (amount < 1_0000_0000 && amount > -1_0000_0000) { res = NumberUtil.div(amount, 1_0000, 2) + "万"; } else if (amount < 1_0000_0000_0000L && amount > -1_0000_0000_0000...
@Test public void formatSimpleTest() { String f1 = NumberChineseFormatter.formatSimple(1_2345); assertEquals("1.23万", f1); f1 = NumberChineseFormatter.formatSimple(-5_5555); assertEquals("-5.56万", f1); f1 = NumberChineseFormatter.formatSimple(1_2345_6789); assertEquals("1.23亿", f1); f1 = NumberChineseFor...
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { ResourceConverter converter = new ResourceConverter(dataFormatTypeClasses); byte[] objectAsBytes = converter.writeDocument(new JSONAPIDocument<>(graph)); stream.write(objectAsBytes); }
@Test public void testJsonApiMarshalWrongType() { Class<?>[] formats = { MyBook.class, MyAuthor.class }; JsonApiDataFormat jsonApiDataFormat = new JsonApiDataFormat(formats); Exchange exchange = new DefaultExchange(context); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ...
@Override public String getId() { return id; }
@Test void recurringJobWithAVeryLongIdUsesMD5HashingForId() { RecurringJob recurringJob = aDefaultRecurringJob().withoutId().withJobDetails(new JobDetails(new SimpleJobRequest())).build(); assertThat(recurringJob.getId()).isEqualTo("045101544c9006c596e6bc7c59506913"); }
public String getHiveMetastoreURIs() { return metastoreURIs; }
@Test public void testFromStmt(@Mocked GlobalStateMgr globalStateMgr) throws UserException { String name = "hudi0"; String type = "hudi"; String metastoreURIs = "thrift://127.0.0.1:9380"; Map<String, String> properties = Maps.newHashMap(); properties.put("type", type); ...
@Override public String getSinkTableName(Table table) { String tableName = table.getName(); Map<String, String> sink = config.getSink(); // Add table name mapping logic String mappingRoute = sink.get(FlinkCDCConfig.TABLE_MAPPING_ROUTES); if (mappingRoute != null) { ...
@Test public void testGetSinkTableNameWithConversionUpperCase() { Map<String, String> sinkConfig = new HashMap<>(); sinkConfig.put("table.prefix", ""); sinkConfig.put("table.suffix", ""); sinkConfig.put("table.lower", "false"); sinkConfig.put("table.upper", "true"); w...
public Host get(final String url) throws HostParserException { final StringReader reader = new StringReader(url); final Protocol parsedProtocol, protocol; if((parsedProtocol = findProtocol(reader, factory)) != null) { protocol = parsedProtocol; } else { pr...
@Test public void parseDefaultHostnameWithUserRelativePath() throws Exception { final Host host = new HostParser(new ProtocolFactory(Collections.singleton(new TestProtocol(Scheme.https) { @Override public String getDefaultHostname() { return "defaultHostname"; ...
@Override public Set<String> getAvailableBrokers() { try { return getAvailableBrokersAsync().get(conf.getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS); } catch (Exception e) { log.warn("Error when trying to get active brokers", e); return loadData.getB...
@Test public void testBrokerStopCacheUpdate() throws Exception { ModularLoadManagerWrapper loadManagerWrapper = (ModularLoadManagerWrapper) pulsar1.getLoadManager().get(); ModularLoadManagerImpl lm = (ModularLoadManagerImpl) loadManagerWrapper.getLoadManager(); assertEquals(lm.getAvailableBr...
public CategoricalInfo(String name) { super(name); }
@Test void testCategoricalInfo() throws Exception { CategoricalInfo info = new CategoricalInfo("cat"); IntStream.range(0, 10).forEach(i -> { IntStream.range(0, i*2).forEach(j -> { info.observe(i); }); }); VariableInfoProto infoProto = info.ser...
@Override public Collection<String> getDistributedTableNames() { return Collections.emptySet(); }
@Test void assertGetDistributedTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getDistributedTableNames()), is(Collections.emptyList())); }
@Override public void writeLong(final long v) throws IOException { ensureAvailable(LONG_SIZE_IN_BYTES); MEM.putLong(buffer, ARRAY_BYTE_BASE_OFFSET + pos, v); pos += LONG_SIZE_IN_BYTES; }
@Test public void testWriteLongForPositionV() throws Exception { long expected = 100; out.writeLong(2, expected); long actual = Bits.readLong(out.buffer, 2, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); assertEquals(expected, actual); }
public static <T extends Throwable> void checkNotEmpty(final String value, final Supplier<T> exceptionSupplierIfUnexpected) throws T { if (Strings.isNullOrEmpty(value)) { throw exceptionSupplierIfUnexpected.get(); } }
@Test void assertCheckNotEmptyWithMapToThrowsException() { assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkNotEmpty(Collections.emptyMap(), SQLException::new)); }
public static boolean isDirectOutOfMemoryError(@Nullable Throwable t) { return isOutOfMemoryErrorWithMessageContaining(t, "Direct buffer memory"); }
@Test void testIsDirectOutOfMemoryErrorCanHandleNullValue() { assertThat(ExceptionUtils.isDirectOutOfMemoryError(null)).isFalse(); }
@Operation(summary = "Redirect with SAML artifact") @GetMapping(value = {"/frontchannel/saml/v4/redirect_with_artifact", "/frontchannel/saml/v4/idp/redirect_with_artifact"}) public RedirectView redirectWithArtifact(@RequestParam(value = "SAMLart") String artifact, HttpServletRequest request) throws SamlSessionE...
@Test void redirectWithArtifactTest() throws SamlSessionException, UnsupportedEncodingException { String redirectUrl = "redirectUrl"; httpServletRequestMock.setRequestedSessionId("sessionId"); when(assertionConsumerServiceUrlServiceMock.generateRedirectUrl(anyString(), any(), anyString(), an...
@Override public int actionUpgradeComponents(String appName, List<String> components) throws IOException, YarnException { int result; Component[] toUpgrade = new Component[components.size()]; try { int idx = 0; for (String compName : components) { Component component = new Compon...
@Test void testComponentsUpgrade() { String appName = "example-app"; try { int result = asc.actionUpgradeComponents(appName, Lists.newArrayList( "comp")); assertEquals(EXIT_SUCCESS, result); } catch (IOException | YarnException e) { fail(); } }
@Override public Optional<ShardingConditionValue> generate(final BinaryOperationExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { String operator = predicate.getOperator().toUpperCase(); if (!isSupportedOperator(operator)) { ...
@Test void assertGenerateNullConditionValueWithLessThanOperator() { BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new LiteralExpressionSegment(0, 0, null), "<", null); Optional<ShardingConditionValue> shardingConditionValue = generator.generate...
public static String getRandomName(int number) { int combinationIdx = number % (LEFT.length * RIGHT.length); int rightIdx = combinationIdx / LEFT.length; int leftIdx = combinationIdx % LEFT.length; String name = String.format(NAME_FORMAT, LEFT[leftIdx], RIGHT[rightIdx]); String p...
@Test public void getRandomNameNotEmpty() { String randomName = MobyNames.getRandomName(0); assertFalse(isNullOrEmptyAfterTrim(randomName)); }
public boolean eval(ContentFile<?> file) { // TODO: detect the case where a column is missing from the file using file's max field id. return new MetricsEvalVisitor().eval(file); }
@Test public void testIntegerGt() { boolean shouldRead = new InclusiveMetricsEvaluator(SCHEMA, greaterThan("id", INT_MAX_VALUE + 6)).eval(FILE); assertThat(shouldRead).as("Should not read: id range above upper bound (85 < 79)").isFalse(); shouldRead = new InclusiveMetricsEvaluator(SCHEMA, greater...
@VisibleForTesting public static Optional<QueryId> getMaxMemoryConsumingQuery(ListMultimap<QueryId, SqlTask> queryIDToSqlTaskMap) { if (queryIDToSqlTaskMap.isEmpty()) { return Optional.empty(); } Comparator<Map.Entry<QueryId, Long>> comparator = Comparator.comparingLong(Map....
@Test public void testMaxMemoryConsumingQuery() throws Exception { QueryId highMemoryQueryId = new QueryId("query1"); SqlTask highMemoryTask = createInitialTask(highMemoryQueryId); updateTaskMemory(highMemoryTask, 200); QueryId lowMemoryQueryId = new QueryId("query2"...
public static long getNumSector(String requestSize, String sectorSize) { Double memSize = Double.parseDouble(requestSize); Double sectorBytes = Double.parseDouble(sectorSize); Double nSectors = memSize / sectorBytes; Double memSizeKB = memSize / 1024; Double memSizeGB = memSize / (1024 * 1024 * 1024...
@Test public void getSectorTest20() { String testRequestSize = "20"; String testSectorSize = "512"; long result = HFSUtils.getNumSector(testRequestSize, testSectorSize); assertEquals(1L, result); }
@Override public int run(String[] args) throws Exception { try { webServiceClient = WebServiceClient.getWebServiceClient().createClient(); return runCommand(args); } finally { if (yarnClient != null) { yarnClient.close(); } if (webServiceClient != null) { webServi...
@Test (timeout = 5000) public void testWithInvalidApplicationId() throws Exception { LogsCLI cli = createCli(); // Specify an invalid applicationId int exitCode = cli.run(new String[] {"-applicationId", "123"}); assertTrue(exitCode == -1); assertTrue(sysErrStream.toString().contains( ...
@Override public boolean check(final Session<?> session, final CancelCallback callback) throws BackgroundException { final Host bookmark = session.getHost(); if(bookmark.getProtocol().isHostnameConfigurable() && StringUtils.isBlank(bookmark.getHostname())) { throw new ConnectionCanceledE...
@Test public void testConnectDnsFailure() throws Exception { final Session session = new NullSession(new Host(new TestProtocol(), "unknownhost.local", new Credentials("user", "p"))) { @Override public boolean isConnected() { return false; } }; ...
@Override public ClusterHealth checkCluster() { checkState(!nodeInformation.isStandalone(), "Clustering is not enabled"); checkState(sharedHealthState != null, "HealthState instance can't be null when clustering is enabled"); Set<NodeHealth> nodeHealths = sharedHealthState.readAll(); Health health = ...
@Test public void checkCluster_passes_set_of_NodeHealth_returns_by_HealthState_to_all_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); ClusterHealthCheck[] mockedClusterHealthChecks = IntStream.range(0, 1 + random.nextInt(3)) .mapToObj(i -> mock(ClusterHealthCheck.class)) ...
public void sendAcks(List<String> messagesToAck) throws IOException { try (SubscriberStub subscriber = pubsubQueueClient.getSubscriber(subscriberStubSettings)) { int numberOfBatches = (int) Math.ceil((double) messagesToAck.size() / DEFAULT_BATCH_SIZE_ACK_API); CompletableFuture.allOf(IntStream.range(0, ...
@Test public void testSendAcks() throws IOException { doNothing().when(mockSubscriber).close(); when(mockPubsubQueueClient.getSubscriber(any())).thenReturn(mockSubscriber); List<String> messageAcks = IntStream.range(0, 20).mapToObj(i -> "msg_" + i).collect(Collectors.toList()); doNothing().when(mockPu...
public static Class<?> getParamClass(final String className) throws ClassNotFoundException { if (PRIMITIVE_TYPE.containsKey(className)) { return PRIMITIVE_TYPE.get(className).getClazz(); } else { return Class.forName(className); } }
@Test public void testGetParamClass() throws Exception { assertEquals(int.class, PrxInfoUtil.getParamClass("int")); assertEquals(long.class, PrxInfoUtil.getParamClass("long")); assertEquals(short.class, PrxInfoUtil.getParamClass("short")); assertEquals(byte.class, PrxInfoUtil.getPara...
@Override @Deprecated public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier, final String... stateStoreNames) { process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames); }
@Test public void shouldNotAllowNullStoreNamesOnProcess() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.process(processorSupplier, (String[]) null)); assertThat(exception.getMessage(), equalTo("stateStoreNames can't be a n...
@Override public int countWords(Note note) { return countChars(note); }
@Test public void getChecklistWords() { String content = CHECKED_SYM + "這是中文測試\n" + UNCHECKED_SYM + "これは日本語のテストです"; Note note = getNote(1L, "这是中文测试", content); note.setChecklist(true); assertEquals(24, new IdeogramsWordCounter().countWords(note)); }
public static MapViewController create(MapView mapView, Model model) { MapViewController mapViewController = new MapViewController(mapView); model.mapViewPosition.addObserver(mapViewController); return mapViewController; }
@Test public void repaintTest() { DummyMapView dummyMapView = new DummyMapView(); Model model = new Model(); MapViewController.create(dummyMapView, model); Assert.assertEquals(0, dummyMapView.repaintCounter); model.mapViewPosition.setZoomLevel((byte) 1); // this does...
public void setHost(String host) { this.host = host; }
@Test void testSetHost() { assertNull(addressContext.getHost()); addressContext.setHost("127.0.0.1"); assertEquals("127.0.0.1", addressContext.getHost()); }
public static void main(String[] args) { final List<Long> numbers = Arrays.asList(1L, 3L, 4L, 7L, 8L); LOGGER.info("Numbers to be squared and get sum --> {}", numbers); final List<SquareNumberRequest> requests = numbers.stream().map(SquareNumberRequest::new).toList(); var consumer = new Consu...
@Test void shouldLaunchApp() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = checkNotNull(threadFactory, "threadFactory"); }
@Test public void test_setThreadFactory_whenNull() { ReactorBuilder builder = newBuilder(); assertThrows(NullPointerException.class, () -> builder.setThreadFactory(null)); }
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldCastNullInt() { // When: final BigDecimal decimal = DecimalUtil.cast((Integer)null, 2, 1); // Then: assertThat(decimal, is(nullValue())); }
public static Expression create(final String value) { /* remove the start and end braces */ final String expression = stripBraces(value); if (expression == null || expression.isEmpty()) { throw new IllegalArgumentException("an expression is required."); } /* Check if the expression is too lo...
@Test void malformedBodyTemplate() { String bodyTemplate = "{" + "a".repeat(65536) + "}"; try { BodyTemplate template = BodyTemplate.create(bodyTemplate); } catch (Throwable e) { assertThatObject(e).isNotInstanceOf(StackOverflowError.class); } }
@Override public RedisClusterNode clusterGetNodeForSlot(int slot) { Iterable<RedisClusterNode> res = clusterGetNodes(); for (RedisClusterNode redisClusterNode : res) { if (redisClusterNode.isMaster() && redisClusterNode.getSlotRange().contains(slot)) { return redisCluster...
@Test public void testClusterGetNodeForSlot() { RedisClusterNode node1 = connection.clusterGetNodeForSlot(1); RedisClusterNode node2 = connection.clusterGetNodeForSlot(16000); assertThat(node1.getId()).isNotEqualTo(node2.getId()); }
@Override public void close() { close(Duration.ofMillis(Long.MAX_VALUE)); }
@Test public void testConstructorWithSerializers() { Properties producerProps = new Properties(); producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9000"); new KafkaProducer<>(producerProps, new ByteArraySerializer(), new ByteArraySerializer()).close(); }
public static Env valueOf(String name) { name = getWellFormName(name); if (exists(name)) { return STRING_ENV_MAP.get(name); } else { throw new IllegalArgumentException(name + " not exist"); } }
@Test(expected = IllegalArgumentException.class) public void valueOf() { String name = "notexist"; assertFalse(Env.exists(name)); assertEquals(Env.valueOf(name), Env.UNKNOWN); assertEquals(Env.valueOf("dev"), Env.DEV); assertEquals(Env.valueOf("UAT"), Env.UAT); }
@GetMapping("/tagId/{tagId}") public ShenyuAdminResult queryApiByTagId(@PathVariable("tagId") @Valid final String tagId) { List<TagRelationDO> tagRelationDOS = Optional.ofNullable(tagRelationService.findByTagId(tagId)).orElse(Lists.newArrayList()); return ShenyuAdminResult.success(ShenyuResultMessag...
@Test public void testQueryApiByTagId() throws Exception { List<TagRelationDO> tagRelationDOS = new ArrayList<>(); tagRelationDOS.add(buildTagRelationDO()); given(tagRelationService.findByTagId(anyString())).willReturn(tagRelationDOS); this.mockMvc.perform(MockMvcRequestBuilders.get(...
public Collection<NodeInfo> load() { NodeStatsResponse response = esClient.nodesStats(); List<NodeInfo> result = new ArrayList<>(); response.getNodeStats().forEach(nodeStat -> result.add(toNodeInfo(nodeStat))); return result; }
@Test public void return_info_from_elasticsearch_api() { Collection<NodeInfo> nodes = underTest.load(); assertThat(nodes).hasSize(1); NodeInfo node = nodes.iterator().next(); assertThat(node.getName()).isNotEmpty(); assertThat(node.getHost()).isNotEmpty(); assertThat(node.getSections()).hasSi...
@GetMapping( path = "/api/{namespace}/{extension}", produces = MediaType.APPLICATION_JSON_VALUE ) @CrossOrigin @Operation(summary = "Provides metadata of the latest version of an extension") @ApiResponses({ @ApiResponse( responseCode = "200", description =...
@Test public void testPostExistingReview() throws Exception { var user = mockUserData(); var extVersion = mockExtension(); var extension = extVersion.getExtension(); Mockito.when(repositories.findExtension("bar", "foo")) .thenReturn(extension); Mockito.when(re...
@Override public ScheduledFuture<@Nullable ?> schedule(Runnable command, long delay, TimeUnit unit) { if (command == null || unit == null) { throw new NullPointerException(); } ScheduledFutureTask<Void> task = new ScheduledFutureTask<>(command, null, triggerTime(delay, unit)); runNowOrSc...
@Test public void testSchedule() throws Exception { List<AtomicInteger> callCounts = new ArrayList<>(); List<ScheduledFutureTask<?>> futures = new ArrayList<>(); FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper(); UnboundedScheduledExecutorService executorService = ...
public void submitIndexingErrors(Collection<IndexingError> indexingErrors) { try { final FailureBatch fb = FailureBatch.indexingFailureBatch( indexingErrors.stream() .filter(ie -> { if (!ie.message().supportsFailureHandl...
@Test public void submitIndexingErrors_allIndexingErrorsTransformedAndSubmittedToFailureQueue() throws Exception { // given final Message msg1 = Mockito.mock(Message.class); when(msg1.getMessageId()).thenReturn("msg-1"); when(msg1.supportsFailureHandling()).thenReturn(true); ...
public MapStoreConfig setImplementation(@Nonnull Object implementation) { this.implementation = checkNotNull(implementation, "Map store cannot be null!"); this.className = null; return this; }
@Test public void setImplementation() { Object mapStoreImpl = new Object(); MapStoreConfig cfg = new MapStoreConfig().setImplementation(mapStoreImpl); assertEquals(mapStoreImpl, cfg.getImplementation()); assertEquals(new MapStoreConfig().setImplementation(mapStoreImpl), cfg); }
@Operation(summary = "Gets the status of ongoing database migrations, if any", description = "Return the detailed status of ongoing database migrations" + " including starting date. If no migration is ongoing or needed it is still possible to call this endpoint and receive appropriate information.") @GetMapping ...
@Test void getStatus_whenDbMigrationsFailed_returnFailed() throws Exception { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_UPGRADE); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(DatabaseMigrationState.Status.FAILED); wh...
@Override @MethodNotAvailable public void clear() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testClear() { adapter.clear(); }
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException { int respCode = conn.getResponseCode(); if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_CREATED || respCode == HttpURLConnection.HTTP_ACCEPTED) { ...
@Test public void testExtractTokenLowerCaseCookieHeader() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<>(); L...
public void toXMLUTF8(Object obj, OutputStream out) throws IOException { Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8); w.write("<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n"); toXML(obj, w); }
@Issue("JENKINS-71139") @Test public void nullsWithEncodingDeclaration() throws Exception { Bar b = new Bar(); b.s = "x\u0000y"; try { new XStream2().toXMLUTF8(b, new ByteArrayOutputStream()); fail("expected to fail fast; not supported to read either"); } ...
public void cancel(Throwable throwable) { cancellationContext.cancel(throwable); }
@Test void cancel() {}
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void setChatTitle() { BaseResponse response = bot.execute(new SetChatTitle(groupId, "Test Bot Group " + System.currentTimeMillis())); assertTrue(response.isOk()); }
public boolean checkIfEnabled() { try { this.gitCommand = locateDefaultGit(); MutableString stdOut = new MutableString(); this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute(); return stdOut.string != null && stdOut.string.startsWith("git version"...
@Test public void git_should_not_be_enabled_if_version_is_less_than_required_minimum() { ProcessWrapperFactory mockFactory = mockGitVersionCommand("git version 1.9.0"); NativeGitBlameCommand blameCommand = new NativeGitBlameCommand(System2.INSTANCE, mockFactory); assertThat(blameCommand.checkIfEnabled())....
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_collection_of_serializable_object() { List<SerializableObject> original = new ArrayList<>(); original.add(new SerializableObject("value")); List<SerializableObject> cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSa...
@Override public Time getTime(final int columnIndex) throws SQLException { return (Time) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, Time.class), Time.class); }
@Test void assertGetTimeAndCalendarWithColumnIndex() throws SQLException { Calendar calendar = Calendar.getInstance(); when(mergeResultSet.getCalendarValue(1, Time.class, calendar)).thenReturn(new Time(0L)); assertThat(shardingSphereResultSet.getTime(1, calendar), is(new Time(0L))); }
@Override public void request(Payload grpcRequest, StreamObserver<Payload> responseObserver) { traceIfNecessary(grpcRequest, true); String type = grpcRequest.getMetadata().getType(); long startTime = System.nanoTime(); //server is on starting. if (!Applicati...
@Test void testConnectionNotRegister() { ApplicationUtils.setStarted(true); Mockito.when(requestHandlerRegistry.getByRequestType(Mockito.anyString())).thenReturn(mockHandler); Mockito.when(connectionManager.checkValid(Mockito.any())).thenReturn(false); RequestMeta metadata =...
@Override public boolean supports(FailureBatch failureBatch) { return failureBatch.containsIndexingFailures(); }
@Test public void supports_indexingFailuresSupported() { assertThat(underTest.supports(FailureBatch.indexingFailureBatch(new ArrayList<>()))).isTrue(); }
public void createBackupLog(UUID callerUuid, UUID txnId) { createBackupLog(callerUuid, txnId, false); }
@Test(expected = TransactionException.class) public void createBackupLog_whenAlreadyExist() { UUID callerUuid = UuidUtil.newUnsecureUUID(); txService.createBackupLog(callerUuid, TXN); txService.createBackupLog(callerUuid, TXN); }
public Collection<File> getUploadedFiles() throws IOException { if (uploadDirectory == null) { return Collections.emptyList(); } FileAdderVisitor visitor = new FileAdderVisitor(); Files.walkFileTree(uploadDirectory, visitor); return Collections.unmodifiableCollectio...
@Test void testEmptyDirectory() throws IOException { Path rootDir = Paths.get("root"); Path tmp = temporaryFolder; Files.createDirectory(tmp.resolve(rootDir)); try (FileUploads fileUploads = new FileUploads(tmp.resolve(rootDir))) { Collection<File> detectedFiles = fileU...
public Collection<File> getUploadedFiles() throws IOException { if (uploadDirectory == null) { return Collections.emptyList(); } FileAdderVisitor visitor = new FileAdderVisitor(); Files.walkFileTree(uploadDirectory, visitor); return Collections.unmodifiableCollectio...
@Test void testDirectoryScan() throws IOException { Path rootDir = Paths.get("root"); Path rootFile = rootDir.resolve("rootFile"); Path subDir = rootDir.resolve("sub"); Path subFile = subDir.resolve("subFile"); Path tmp = temporaryFolder; Files.createDirectory(tmp.re...
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { ...
@Test public void testFilterWithKVOnly() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("k1=v1"); assertEquals(1, result.size()); assertEquals("v1", r...
public static BadRequestException namespaceAlreadyExists(String namespaceName) { return new BadRequestException("namespace already exists for namespaceName:%s", namespaceName); }
@Test public void testNamespaceAlreadyExists() { BadRequestException namespaceAlreadyExists = BadRequestException.namespaceAlreadyExists(namespaceName); assertEquals("namespace already exists for namespaceName:application", namespaceAlreadyExists.getMessage()); }
@Override public int getMaxColumnsInOrderBy() { return 0; }
@Test void assertGetMaxColumnsInOrderBy() { assertThat(metaData.getMaxColumnsInOrderBy(), is(0)); }
public Map<FeatureOption, MergingStrategy> computeMergingStrategies( List<SqlTableLikeOption> mergingOptions) { Map<FeatureOption, MergingStrategy> result = new HashMap<>(defaultMergingStrategies); Optional<SqlTableLikeOption> maybeAllOption = mergingOptions.stream() ...
@Test void defaultMergeStrategies() { Map<FeatureOption, MergingStrategy> mergingStrategies = util.computeMergingStrategies(Collections.emptyList()); assertThat(mergingStrategies.get(FeatureOption.OPTIONS)) .isEqualTo(MergingStrategy.OVERWRITING); assertThat(...
@Override public JSONObject getLastScreenTrackProperties() { return new JSONObject(); }
@Test public void getLastScreenTrackProperties() { Assert.assertEquals(0, mSensorsAPI.getLastScreenTrackProperties().length()); }
public List<LoadJob> getLoadJobsByDb(long dbId, String labelValue, boolean accurateMatch) { List<LoadJob> loadJobList = Lists.newArrayList(); readLock(); try { if (dbId != -1 && !dbIdToLabelToLoadJobs.containsKey(dbId)) { return loadJobList; } ...
@Test public void testGetLoadJobsByDb(@Mocked GlobalStateMgr globalStateMgr) throws MetaNotFoundException { LoadMgr loadMgr = new LoadMgr(new LoadJobScheduler()); LoadJob job1 = new InsertLoadJob("job1", 1L, 1L, System.currentTimeMillis(), "", "", null); Deencapsulation.invoke(loadMgr, "addL...
@Override public void onWorkflowFinalized(Workflow workflow) { WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput()); WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow); String reason = workflow.getReasonForIncompletion(); LOG.inf...
@Test public void testDaoErrorOnWorkflowFinalized() { when(workflow.getStatus()).thenReturn(Workflow.WorkflowStatus.TERMINATED); when(instanceDao.getWorkflowInstanceStatus(eq("test-workflow-id"), anyLong(), anyLong())) .thenReturn(WorkflowInstance.Status.IN_PROGRESS); when(instanceDao.updateWorkfl...
public static Credentials loadCredentials(String password, String source) throws IOException, CipherException { return loadCredentials(password, new File(source)); }
@Test public void testLoadCredentialsFromFile() throws Exception { Credentials credentials = WalletUtils.loadCredentials( PASSWORD, new File( WalletUtilsTest.class .getReso...
public static <K> KTableHolder<K> build( final KTableHolder<K> left, final KTableHolder<K> right, final TableTableJoin<K> join ) { final LogicalSchema leftSchema; final LogicalSchema rightSchema; if (join.getJoinType().equals(RIGHT)) { leftSchema = right.getSchema(); rightSc...
@Test public void shouldDoLeftJoinWithSyntheticKey() { // Given: givenLeftJoin(SYNTH_KEY); // When: join.build(planBuilder, planInfo); // Then: verify(leftKTable).leftJoin( same(rightKTable), eq(new KsqlValueJoiner(LEFT_SCHEMA.value().size(), RIGHT_SCHEMA.value().size(), 1)) ...
@Override public RFuture<Boolean> removeAsync(Object value) { CompletableFuture<Boolean> f = CompletableFuture.supplyAsync(() -> remove(value), getServiceManager().getExecutor()); return new CompletableFutureWrapper<>(f); }
@Test public void testRemoveAsync() throws InterruptedException, ExecutionException { RSortedSet<Integer> set = redisson.getSortedSet("simple"); set.add(1); set.add(3); set.add(7); Assertions.assertTrue(set.removeAsync(1).get()); Assertions.assertFalse(set.contains(1...
public static MapBackedDMNContext of(Map<String, Object> ctx) { return new MapBackedDMNContext(ctx); }
@Test void contextWithEntries() { MapBackedDMNContext ctx1 = MapBackedDMNContext.of(new HashMap<>(DEFAULT_ENTRIES)); testCloneAndAlter(ctx1, DEFAULT_ENTRIES, Collections.emptyMap()); MapBackedDMNContext ctx2 = MapBackedDMNContext.of(new HashMap<>(DEFAULT_ENTRIES)); testPushAndPopSco...
@Override public ClusterHealth checkCluster() { checkState(!nodeInformation.isStandalone(), "Clustering is not enabled"); checkState(sharedHealthState != null, "HealthState instance can't be null when clustering is enabled"); Set<NodeHealth> nodeHealths = sharedHealthState.readAll(); Health health = ...
@Test public void checkCluster_returns_YELLOW_status_if_only_GREEN_and_at_least_one_YELLOW_statuses_returned_by_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); List<Health.Status> statuses = new ArrayList<>(); Stream.concat( IntStream.range(0, 1 + random.nextInt(20))....