focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Num calculate(BarSeries series, Position position) { if (position == null || position.getEntry() == null || position.getExit() == null) { return series.zero(); } Returns returns = new Returns(series, position, Returns.ReturnType.LOG); return calculateES(r...
@Test public void calculateWithNoBarsShouldReturn0() { series = new MockBarSeries(numFunction, 100d, 95d, 100d, 80d, 85d, 70d); AnalysisCriterion varCriterion = getCriterion(); assertNumEquals(numOf(0), varCriterion.calculate(series, new BaseTradingRecord())); }
public static CompletableFuture<Map<String, String>> labelFailure( final Throwable cause, final Context context, final Executor mainThreadExecutor, final Collection<FailureEnricher> failureEnrichers) { // list of CompletableFutures to enrich failure with labels fr...
@Test public void testLabelFailureWithValidAndThrowingEnricher() { // A failing enricher shouldn't affect remaining enrichers with valid labels final Throwable cause = new RuntimeException("test exception"); final FailureEnricher validEnricher = new TestEnricher("enricherKey"); final...
@Nonnull public static <K, V> Sink<ChangeRecord> map( @Nonnull String mapName, @Nonnull FunctionEx<? super ChangeRecord, ? extends K> keyFn, @Nonnull FunctionEx<? super ChangeRecord, ? extends V> valueFn ) { String name = "mapCdcSink(" + mapName + ')'; return ...
@Test public void deleteFromLocalMap_ViaValueProjection() { p.readFrom(items(SYNC1, INSERT2)) .writeTo(localSync()); execute().join(); p = Pipeline.create(); p.readFrom(items(UPDATE1)) .writeTo(CdcSinks.map(MAP, r -> (Integer) ...
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer) { return read(buffer, consumer, 0); }
@Test void readShouldNotReadIfRemainingSpaceIsLessThanOneErrorPrefix() { final UnsafeBuffer buffer = new UnsafeBuffer(new byte[64]); final long lastTimestamp = 543495734L; final long firstTimestamp = lastTimestamp - 1000; final int count = 123; final int totalLength = 45;...
public void markStale() { stale = true; }
@Test void stale() { final Account account = AccountsHelper.generateTestAccount("+14151234567", UUID.randomUUID(), UUID.randomUUID(), Collections.emptyList(), new byte[0]); assertDoesNotThrow(account::getNumber); account.markStale(); assertThrows(AssertionError.class, account::getNumber); ...
@Override protected TableSchema transformTableSchema() { tryOpen(); List<String> inputColumnsMapping = new ArrayList<>(); SeaTunnelRowType outRowType = sqlEngine.typeMapping(inputColumnsMapping); List<String> outputColumns = Arrays.asList(outRowType.getFieldNames()); TableSc...
@Test public void testNotLoseSourceTypeAndOptions() { SQLTransform sqlTransform = new SQLTransform(READONLY_CONFIG, getCatalogTable()); TableSchema tableSchema = sqlTransform.transformTableSchema(); tableSchema .getColumns() .forEach( c...
public static Map<String, Object> getAnnotationValues(Annotation annotation) throws NoSuchFieldException { InvocationHandler h = Proxy.getInvocationHandler(annotation); return getFieldValue(h, "memberValues"); }
@Test @EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11}) // `ReflectionUtil.modifyStaticFinalField` does not supported java17 and above versions public void testGetAnnotationValues() throws NoSuchMethodException, NoSuchFieldException { Assertions.assertEquals(new LinkedHashMap<>(), ReflectionUtil .get...
public void isEqualTo(@Nullable Object expected) { standardIsEqualTo(expected); }
@Test public void isEqualToStringWithNullVsNull() { expectFailure.whenTesting().that("null").isEqualTo(null); assertFailureKeys("expected", "an instance of", "but was", "an instance of"); assertFailureValue("expected", "null"); assertFailureValueIndexed("an instance of", 0, "(null reference)"); as...
public static boolean backgroundRemoval(String inputPath, String outputPath, int tolerance) { return BackgroundRemoval.backgroundRemoval(inputPath, outputPath, tolerance); }
@Test @Disabled public void backgroundRemovalTest() { // 图片 背景 换成 透明的 ImgUtil.backgroundRemoval( "d:/test/617180969474805871.jpg", "d:/test/2.jpg", 10); // 图片 背景 换成 红色的 ImgUtil.backgroundRemoval(new File( "d:/test/617180969474805871.jpg"), new File("d:/test/3.jpg"), new Color(200, 0, 0), ...
public synchronized void register(String id, MapInterceptor interceptor) { assert !(Thread.currentThread() instanceof PartitionOperationThread); if (id2InterceptorMap.containsKey(id)) { return; } Map<String, MapInterceptor> tmpMap = new HashMap<>(id2InterceptorMap); ...
@Test public void testRegister() { registry.register(interceptor.id, interceptor); assertInterceptorRegistryContainsInterceptor(); }
@SuppressWarnings("squid:S1181") // Yes we really do want to catch Throwable @Override public V apply(U input) { int retryAttempts = 0; while (true) { try { return baseFunction.apply(input); } catch (Throwable t) { if (!exceptionClass.i...
@Test public void testSuccessAfterOneRetry() { new RetryingFunction<>(this::succeedAfterOneFailure, RetryableException.class, 1, 10).apply(null); }
public static double cor(int[] x, int[] y) { if (x.length != y.length) { throw new IllegalArgumentException("Arrays have different length."); } if (x.length < 3) { throw new IllegalArgumentException("array length has to be at least 3."); } double Sxy = c...
@Test public void testCor_doubleArr_doubleArr() { System.out.println("cor"); double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515}; double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300}; assertEquals(0.4686847, MathEx.cor(x, y), 1E-7); }
static String resolveCluster(AwsConfig awsConfig, AwsMetadataApi metadataApi, Environment environment) { if (!isNullOrEmptyAfterTrim(awsConfig.getCluster())) { return awsConfig.getCluster(); } if (environment.isRunningOnEcs()) { String cluster = metadataApi.clusterEcs(); ...
@Test public void resolveClusterAwsEcsMetadata() { // given String cluster = "service-name"; AwsConfig config = AwsConfig.builder().build(); AwsMetadataApi metadataApi = mock(AwsMetadataApi.class); given(metadataApi.clusterEcs()).willReturn(cluster); Environment envir...
public byte[] readAll() throws IOException { if (pos == 0 && count == buf.length) { pos = count; return buf; } byte[] ret = new byte[count - pos]; super.read(ret); return ret; }
@Test public void testReadAllAfterReadPartial() throws IOException { assertNotEquals(-1, exposedStream.read()); byte[] ret = exposedStream.readAll(); assertArrayEquals("ello World!".getBytes(StandardCharsets.UTF_8), ret); }
public String getServerStatus() { try { NamingService namingService = nacosServiceManager.getNamingService(); return namingService.getServerStatus(); } catch (NacosException e) { LOGGER.log(Level.SEVERE, "get nacos server status failed", e); } return S...
@Test public void testGetServerStatus() throws NacosException { mockNamingService(); Assert.assertNull(nacosClient.getServerStatus()); }
public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; }
@Test public void testRetryableError() throws IOException { MockLowLevelHttpResponse[] mockResponses = createMockResponseWithStatusCode( 503, // Retryable 429, // We also retry on 429 Too Many Requests. 200); when(mockLowLevelRequest.execute()) .thenReturn(m...
@Override public void warn(String msg) { logger.warn(msg); }
@Test public void testWarnWithException() { Log mockLog = mock(Log.class); InternalLogger logger = new CommonsLogger(mockLog, "foo"); logger.warn("a", e); verify(mockLog).warn("a", e); }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
@Test public void setEnabled() { properties.setEnabled(false); assertThat(properties.isEnabled()).isEqualTo(false); }
public static int scan(final UnsafeBuffer termBuffer, final int termOffset, final int limitOffset) { int offset = termOffset; while (offset < limitOffset) { final int frameLength = frameLengthVolatile(termBuffer, offset); if (frameLength <= 0) { ...
@Test void shouldReadBlockOfTwoMessages() { final int offset = 0; final int limit = termBuffer.capacity(); final int messageLength = 50; final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT); when(termBuffer.getIntVolatile(lengthOffset(offset)))....
public void isNotNull() { standardIsNotEqualTo(null); }
@Test public void isNotNullBadEqualsImplementation() { assertThat(new ThrowsOnEqualsNull()).isNotNull(); }
public static boolean isRetryOrDlqTopic(String topic) { if (StringUtils.isBlank(topic)) { return false; } return topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) || topic.startsWith(MixAll.DLQ_GROUP_TOPIC_PREFIX); }
@Test public void testIsRetryOrDlqTopicWithNonRetryOrDlqTopic() { String topic = "NormalTopic"; boolean result = BrokerMetricsManager.isRetryOrDlqTopic(topic); assertThat(result).isFalse(); }
public static boolean hasModifier(Class<?> clazz, ModifierType... modifierTypes) { if (null == clazz || ArrayUtil.isEmpty(modifierTypes)) { return false; } return 0 != (clazz.getModifiers() & modifiersToInt(modifierTypes)); }
@Test public void hasModifierTest() throws NoSuchMethodException { Method method = ModifierUtilTest.class.getDeclaredMethod("ddd"); assertTrue(ModifierUtil.hasModifier(method, ModifierUtil.ModifierType.PRIVATE)); assertTrue(ModifierUtil.hasModifier(method, ModifierUtil.ModifierType.PRIVATE, ModifierUtil....
public static Builder newBuilder(List<ReservedPort> reservedPorts) { return new Builder(reservedPorts); }
@Test public void zookeeper() throws Exception { mCluster = MultiProcessCluster.newBuilder(PortCoordination.MULTI_PROCESS_ZOOKEEPER) .setClusterName("zookeeper") .setNumMasters(3) .setNumWorkers(2) .addProperty(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS) .build(); ...
@Override public List<KubernetesPod> getPodsWithLabels(Map<String, String> labels) { final List<Pod> podList = this.internalClient .pods() .withLabels(labels) .list( new ListOptionsBuilder...
@Test void testGetPodsWithLabels() { final String podName = "pod-with-labels"; final Pod pod = new PodBuilder() .editOrNewMetadata() .withName(podName) .withLabels(TESTING_LABELS) .endMeta...
public static List<String> computeLangFromLocale(Locale locale) { final List<String> resourceNames = new ArrayList<>(5); if (StringUtils.isBlank(locale.getLanguage())) { throw new IllegalArgumentException( "Locale \"" + locale + "\" " + "cannot be used as...
@Test void computeLangFromLocale() { List<String> languages = LanguageUtils.computeLangFromLocale(Locale.CHINA); assertThat(languages).isEqualTo(List.of("default", "zh", "zh_CN")); languages = LanguageUtils.computeLangFromLocale(Locale.CHINESE); assertThat(languages).isEqualTo(List....
public Quantity<U> add(Quantity<U> second) { if(unit == second.unit) return new Quantity<U>(value + second.value, unit); else { final double sum = value + second.in(unit).value; return new Quantity<U>(sum, unit); } }
@Test public void addQuantitiesGivenAsPrimitives() throws Exception { Quantity<Metrics> first = new Quantity<Metrics>(100, Metrics.cm); assertThat(first.add(2, Metrics.m)).isEqualTo(new Quantity<Metrics>(300, Metrics.cm)); }
@Override public String format(Object value) { return value == null ? EMPTY : nonNullFormat(value); }
@Test public void nonNullInput() { assertEquals("what?", MOCK_OUTPUT, frm.format(1)); }
static MinMax findMinMax(MinMax minMax, List<Statement> statements, EncodedValueLookup lookup) { List<List<Statement>> groups = CustomModelParser.splitIntoGroup(statements); for (List<Statement> group : groups) findMinMaxForGroup(minMax, group, lookup); return minMax; }
@Test public void testBlock() { List<Statement> statements = Arrays.asList( If("road_class == TERTIARY", List.of(If("max_speed > 100", LIMIT, "100"), Else(LIMIT, "30"))), ElseIf("road_class == SECONDARY", LIMIT, "25"), ...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = first.getValue(index).isEqual(second.getValue(index)); traceIsSatisfied(index, satisfied); return satisfied; }
@Test public void isSatisfied() { assertTrue(rule.isSatisfied(0)); assertFalse(rule.isSatisfied(1)); assertFalse(rule.isSatisfied(2)); assertFalse(rule.isSatisfied(3)); }
public static boolean isNotEmpty(String value) { return !isEmpty(value); }
@Test void testIsNotEmpty() throws Exception { assertThat(ConfigUtils.isNotEmpty("abc"), is(true)); }
public static void register(Observer observer) { register(SubjectType.SPRING_CONTENT_REFRESHED.name(), observer); }
@Test public void testDefaultRegister() { AbstractSubjectCenter.register(subjectNotifyListener); List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.SPRING_CONTENT_REFRESHED.name()); Assert.assertNotNull(list); Assert.assertEquals(1, list.size()); Assert...
@Override public SchemaVersion versionFromBytes(byte[] version) { // The schema storage converts the schema from bytes to long // so it handles both cases 1) version is 64 bytes long pre 2.4.0; // 2) version is 8 bytes long post 2.4.0 // // NOTE: if you are planning to change...
@Test public void testVersionFromBytes() { long version = System.currentTimeMillis(); ByteBuffer bbPre240 = ByteBuffer.allocate(Long.SIZE); bbPre240.putLong(version); byte[] versionBytesPre240 = bbPre240.array(); ByteBuffer bbPost240 = ByteBuffer.allocate(Long.BYTES); ...
@Nullable public Buffer requestBuffer() { return bufferManager.requestBuffer(); }
@Test void testRequestBuffer() throws Exception { BufferPool bufferPool = new TestBufferPool(); SingleInputGate inputGate = createSingleInputGate(bufferPool); RemoteInputChannel remoteChannel1 = createRemoteInputChannel(inputGate, 0, 2); RemoteInputChannel remoteChannel2 = createRem...
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldTimeoutSubscription() { driverProxy.addSubscription(CHANNEL_4000, STREAM_ID_1); driverConductor.doWork(); final ArgumentCaptor<ReceiveChannelEndpoint> captor = ArgumentCaptor.forClass(ReceiveChannelEndpoint.class); verify(receiverProxy).registerReceiveChannelEn...
public void setValue(PDSignature value) throws IOException { getCOSObject().setItem(COSName.V, value); applyChange(); }
@Test void setValueForAbstractedSignatureField() { PDSignatureField sigField = new PDSignatureField(acroForm); sigField.setPartialName("SignatureField"); assertThrows(UnsupportedOperationException.class, () -> { sigField.setValue("Can't set value using String"); }); ...
@VisibleForTesting @Override public boolean allocateSlot( int index, JobID jobId, AllocationID allocationId, Duration slotTimeout) { return allocateSlot(index, jobId, allocationId, defaultSlotResourceProfile, slotTimeout); }
@Test void testAllocatedSlotTimeout() throws Exception { final CompletableFuture<AllocationID> timeoutFuture = new CompletableFuture<>(); final TestingSlotActions testingSlotActions = new TestingSlotActionsBuilder() .setTimeoutSlotConsumer( ...
public static void assignFieldParams(Object bean, Map<String, Param> params) throws TikaConfigException { Class<?> beanClass = bean.getClass(); if (!PARAM_INFO.containsKey(beanClass)) { synchronized (TikaConfig.class) { if (!PARAM_INFO.containsKey(beanClass)) { ...
@Test public void testMisMatchType() { class MyParser extends Configurable { @Field(required = true) int config; } Map<String, Param> params = new HashMap<>(); try { params.put("config", new Param<>("config", 1)); MyParser bean = new...
@Override public int read(ByteBuffer dst) throws IOException { checkNotNull(dst); checkOpen(); checkReadable(); int read = 0; // will definitely either be assigned or an exception will be thrown synchronized (this) { boolean completed = false; try { if (!beginBlocking()) { ...
@Test public void testReadNegative() throws IOException { FileChannel channel = channel(regularFile(0), READ, WRITE); try { channel.read(buffer("111"), -1); fail(); } catch (IllegalArgumentException expected) { } ByteBuffer[] bufs = {buffer("111"), buffer("111")}; try { cha...
@Override public Optional<NativeEntity<DataAdapterDto>> findExisting(Entity entity, Map<String, ValueReference> parameters) { if (entity instanceof EntityV1) { return findExisting((EntityV1) entity, parameters); } else { throw new IllegalArgumentException("Unsupported entity ...
@Test @MongoDBFixtures("LookupDataAdapterFacadeTest.json") public void findExisting() { final Entity entity = EntityV1.builder() .id(ModelId.of("1")) .type(ModelTypes.LOOKUP_ADAPTER_V1) .data(objectMapper.convertValue(LookupDataAdapterEntity.create( ...
@Override public String evaluate(EvaluationContext evaluationContext, String... args) { if (args != null && args.length == 1) { int maxLength = DEFAULT_LENGTH; try { maxLength = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { // Ignore, we'll ...
@Test void testCustomSizeEvaluation() { // Compute evaluation. RandomStringELFunction function = new RandomStringELFunction(); String result = function.evaluate(null, "64"); assertEquals(64, result.length()); }
public void watch(final String key, final Consumer<Object> consumer) { watchUpstreamListener.put(key, consumer); }
@Test public void testWatch() { this.applicationConfigCache.watch(selector.getName(), Assertions::assertNotNull); }
@Override protected void customAnalyze( XMLOutputMeta meta, IMetaverseNode node ) throws MetaverseAnalyzerException { super.customAnalyze( meta, node ); node.setProperty( "parentnode", meta.getMainElement() ); node.setProperty( "rownode", meta.getRepeatElement() ); }
@Test public void testCustomAnalyze() throws Exception { when( meta.getMainElement() ).thenReturn( "main" ); when( meta.getRepeatElement() ).thenReturn( "repeat" ); analyzer.customAnalyze( meta, node ); verify( node ).setProperty( "parentnode", "main" ); verify( node ).setProperty( "rownode", "re...
@Override public Result apply(ApplyNode applyNode, Captures captures, Context context) { if (applyNode.getSubqueryAssignments().size() != 1) { return Result.empty(); } RowExpression expression = getOnlyElement(applyNode.getSubqueryAssignments().getExpressions()); if ...
@Test public void testFiresForInPredicate() { tester().assertThat(new TransformUncorrelatedInPredicateSubqueryToSemiJoin()) .on(p -> p.apply( assignment( p.variable("x"), inSubquery(p.variable("y"), p...
@SuppressWarnings("unchecked") public <T> T convert(DocString docString, Type targetType) { if (DocString.class.equals(targetType)) { return (T) docString; } List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType); if (d...
@Test void throws_when_uses_doc_string_type_but_downcast_conversion() { registry.defineDocStringType(jsonNodeForJson); DocString docString = DocString.create("{\"hello\":\"world\"}", "json"); CucumberDocStringException exception = assertThrows( CucumberDocStringException.class, ...
private static void handleSetTabletEnablePersistentIndex(long backendId, Map<Long, TTablet> backendTablets) { List<Pair<Long, Boolean>> tabletToEnablePersistentIndex = Lists.newArrayList(); TabletInvertedIndex invertedIndex = GlobalStateMgr.getCurrentState().getTabletInvertedIndex(); for (TTabl...
@Test public void testHandleSetTabletEnablePersistentIndex() { Database db = GlobalStateMgr.getCurrentState().getDb("test"); long dbId = db.getId(); long backendId = 10001L; List<Long> tabletIds = GlobalStateMgr.getCurrentState().getTabletInvertedIndex().getTabletIdsByBackendId(10001...
public Integer doCall() throws Exception { // Operator id must be set if (ObjectHelper.isEmpty(operatorId)) { printer().println("Operator id must be set"); return -1; } List<String> integrationSources = Stream.concat(Arrays.stream(Optional.ofNulla...
@Test public void shouldRunIntegration() throws Exception { IntegrationRun command = createCommand(); command.filePaths = new String[] { "classpath:route.yaml" }; command.doCall(); Assertions.assertEquals("Integration route created", printer.getOutput()); Integration create...
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { boolean satisfied = false; // No trading history or no position opened, no loss if (tradingRecord != null) { Position currentPosition = tradingRecord.getCurrentPosition(); if (currentPositi...
@Test public void isSatisfiedForBuyForBarCount() { BaseTradingRecord tradingRecord = new BaseTradingRecord(TradeType.BUY); ClosePriceIndicator closePrice = new ClosePriceIndicator( new MockBarSeries(numFunction, 100, 110, 120, 130, 120, 117.00, 117.00, 130, 116.99)); // 10% ...
@Override public void shutdown() throws NacosException { NAMING_LOGGER.info("Shutdown naming grpc client proxy for uuid->{}", uuid); redoService.shutdown(); shutDownAndRemove(uuid); NotifyCenter.deregisterSubscriber(this); }
@Test void testShutdown() throws Exception { client.shutdown(); assertNull(RpcClientFactory.getClient(uuid)); //verify(this.rpcClient, times(1)).shutdown(); }
public static Builder builder() { return new Builder(); }
@Test public void testBuilderDoesNotBuildInvalidRequests() { assertThatThrownBy( () -> RenameTableRequest.builder() .withSource(null) .withDestination(TAX_PAID_RENAMED) .build()) .isInstanceOf(NullPointerException.clas...
void validateSnapshotsUpdate( TableMetadata metadata, List<Snapshot> addedSnapshots, List<Snapshot> deletedSnapshots) { if (metadata.currentSnapshot() == null) { // no need to verify attempt to delete current snapshot if it doesn't exist // deletedSnapshots is necessarily empty when original snaps...
@Test void testValidateSnapshotsUpdateWithNoSnapshotMetadata() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); // No exception since added as well deleted snapshots are allowed to support replication // use case which performs table commit with added and deleted snapsh...
@Override public AttributeResource getAttrValue(ResName resName) { AttributeResource attributeResource = items.get(resName); // This hack allows us to look up attributes from downstream dependencies, see comment in // org.robolectric.shadows.ShadowThemeTest.obtainTypedArrayFromDependencyLibrary() // ...
@Test public void getAttrValue_willNotFindFrameworkResourcesWithSameName() { StyleData styleData = new StyleData( "android", "Theme_Material", "Theme", asList(new AttributeResource(androidSearchViewStyle, "android_value", "android"))); assertThat(styleD...
@POST @Consumes({ MediaTypeRestconf.APPLICATION_YANG_DATA_JSON, MediaType.APPLICATION_JSON }) @Produces(MediaTypeRestconf.APPLICATION_YANG_DATA_JSON) @Path("data/{identifier : .+}") public Response handlePostRequest(@PathParam("identifier") String uriString, InputSt...
@Test public void testHandlePostRequest() { ObjectMapper mapper = new ObjectMapper(); ObjectNode ietfSystemSubNode = mapper.createObjectNode(); ietfSystemSubNode.put("contact", "Open Networking Foundation"); ietfSystemSubNode.put("hostname", "host1"); ietfSystemSubNode.put("l...
public static boolean deleteQuietly(@Nullable File file) { if (file == null) { return false; } try { if (file.isDirectory()) { deleteDirectory(file); if (file.exists()) { LOG.warn("Unable to delete directory '{}'", file); } } else { Files.delete(...
@Test public void deleteDirectory_deletes_directory_and_content() throws IOException { Path target = temporaryFolder.newFolder().toPath(); Path childFile1 = Files.createFile(target.resolve("file1.txt")); Path childDir1 = Files.createDirectory(target.resolve("subDir1")); Path childFile2 = Files.createF...
@Override public synchronized void close() { super.close(); notifyAll(); }
@Test public void testMetadataAwaitAfterClose() throws InterruptedException { long time = 0; metadata.updateWithCurrentRequestVersion(responseWithCurrentTopics(), false, time); assertTrue(metadata.timeToNextUpdate(time) > 0, "No update needed."); metadata.requestUpdate(true); ...
public static boolean seemDuplicates(FeedItem item1, FeedItem item2) { if (sameAndNotEmpty(item1.getItemIdentifier(), item2.getItemIdentifier())) { return true; } FeedMedia media1 = item1.getMedia(); FeedMedia media2 = item2.getMedia(); if (media1 == null || media2 ==...
@Test public void testOtherAttributes() { assertTrue(FeedItemDuplicateGuesser.seemDuplicates( item("id1", "Title", "example.com/episode1", 10, 5 * MINUTES, "audio/*"), item("id2", "Title", "example.com/episode2", 10, 5 * MINUTES, "audio/*"))); assertTrue(FeedItemDupli...
boolean matchesNonValueField(final Optional<SourceName> source, final ColumnName column) { if (!source.isPresent()) { return sourceSchemas.values().stream() .anyMatch(schema -> SystemColumns.isPseudoColumn(column) || schema.isKeyColumn(column)); } final SourceName sourceName =...
@Test public void shouldNotMatchOtherFields() { assertThat(sourceSchemas.matchesNonValueField(Optional.of(ALIAS_2), V2), is(false)); }
public static CrypticClue forText(String text) { for (CrypticClue clue : CLUES) { if (text.equalsIgnoreCase(clue.text) || text.equalsIgnoreCase(clue.questionText)) { return clue; } } return null; }
@Test public void forTextEmptyString() { assertNull(CrypticClue.forText("")); }
@Override public Set<KubevirtSecurityGroup> securityGroups() { return sgStore.securityGroups(); }
@Test public void testGetSecurityGroups() { createBasicSecurityGroups(); assertEquals("Number of security group did not match", 2, target.securityGroups().size()); }
public Path setDistance(double distance) { this.distance = distance; return this; }
@Test public void testFindInstruction() { BaseGraph g = new BaseGraph.Builder(carManager).create(); NodeAccess na = g.getNodeAccess(); na.setNode(0, 0.0, 0.0); na.setNode(1, 5.0, 0.0); na.setNode(2, 5.0, 0.5); na.setNode(3, 10.0, 0.5); na.setNode(4, 7.5, 0.25)...
static byte[] generateRandomPayload(Integer recordSize, List<byte[]> payloadByteList, byte[] payload, SplittableRandom random, boolean payloadMonotonic, long recordValue) { if (!payloadByteList.isEmpty()) { payload = payloadByteList.get(random.nextInt(payloadByteList.size())); } ...
@Test public void testGenerateRandomPayloadByPayloadFile() { Integer recordSize = null; String inputString = "Hello Kafka"; byte[] byteArray = inputString.getBytes(StandardCharsets.UTF_8); List<byte[]> payloadByteList = new ArrayList<>(); payloadByteList.add(byteArray); ...
@Override public Object clone() { try { ValueString retval = (ValueString) super.clone(); return retval; } catch ( CloneNotSupportedException e ) { return null; } }
@Test public void testClone() { ValueString vs = new ValueString( "Boden" ); ValueString vs1 = (ValueString) vs.clone(); assertFalse( vs.equals( vs1 ) ); // not the same object, equals not implement assertTrue( vs != vs1 ); // not the same object assertEquals( vs.getString(), vs1.getString() ); ...
@Override public IcebergEnumeratorState snapshotState(long checkpointId) { return new IcebergEnumeratorState( enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot()); }
@Test public void testThrottlingDiscovery() throws Exception { // create 10 splits List<IcebergSourceSplit> splits = SplitHelpers.createSplitsFromTransientHadoopTable(temporaryFolder, 10, 1); TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext = new TestingSplitEnumeratorC...
public List<String> build() { switch (dialect.getId()) { case PostgreSql.ID: StringBuilder sql = new StringBuilder().append(ALTER_TABLE).append(tableName).append(" "); dropColumns(sql, "DROP COLUMN ", columns); return Collections.singletonList(sql.toString()); case MsSql.ID: ...
@Test public void drop_columns_on_mssql() { assertThat(new DropColumnsBuilder(new MsSql(), "issues", "date_in_ms", "name").build()) .containsOnly("ALTER TABLE issues DROP COLUMN date_in_ms, name"); }
@Override protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) { if (!blueUrl.lastPartIs(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_TAB, "changes")) { // Not interested in it return null; } BluePipeline pipeline = getPipeline(blueUrl); if (...
@Test public void prefetchUrlIsRight() throws IOException, ExecutionException, InterruptedException { FreeStyleProject project = j.createFreeStyleProject("project"); Run run = j.waitForCompletion(project.scheduleBuild2(0).waitForStart()); FreeStylePipeline freeStylePipeline = (FreeStylePipe...
@Override public long stopDebug() { return doStopWithoutMessage(LoggerLevel.DEBUG); }
@Test public void fail_if_stop_without_start() { try { underTest.stopDebug("foo"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Profiler must be started before being stopped"); } }
public static String getRemoteIp(HttpServletRequest request) { String xForwardedFor = request.getHeader(X_FORWARDED_FOR); if (!StringUtils.isBlank(xForwardedFor)) { return xForwardedFor.split(X_FORWARDED_FOR_SPLIT_SYMBOL)[0].trim(); } String nginxHeader = request.getHeader(X_...
@Test void testGetRemoteIp() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1"); assertEquals("127.0.0.1", WebUtils.getRemoteIp(request)); Mockito.when(request.getHeader(eq(X_REAL_IP))...
@Override public void setStoragePolicy(Path src, String policyName) throws IOException { super.setStoragePolicy(fullPath(src), policyName); }
@Test(timeout = 30000) public void testSetStoragePolicy() throws Exception { Path storagePolicyPath = new Path("/storagePolicy"); Path chRootedStoragePolicyPath = new Path("/a/b/storagePolicy"); Configuration conf = new Configuration(); conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem...
@Udf public <T> String join( @UdfParameter(description = "the array to join using the default delimiter '" + DEFAULT_DELIMITER + "'") final List<T> array ) { return join(array, DEFAULT_DELIMITER); }
@Test public void shouldReturnEmptyStringForEmptyArrays() { assertThat(arrayJoinUDF.join(Collections.emptyList()).isEmpty(),is(true)); assertThat(arrayJoinUDF.join(Collections.emptyList(),CUSTOM_DELIMITER).isEmpty(),is(true)); }
public static long ordinalOf(double value) { if (value == Double.POSITIVE_INFINITY) { return 0xFFFFFFFFFFFFFFFFL; } if (value == Double.NEGATIVE_INFINITY || Double.isNaN(value)) { return 0; } long bits = Double.doubleToLongBits(value); // need negatives to come before positives i...
@Test public void testZeroes() { assertEquals(FPOrdering.ordinalOf(0D), 0x8000000000000000L); assertEquals(FPOrdering.ordinalOf(0F), 0x80000000L); assertEquals(FPOrdering.ordinalOf(-0D), 0x8000000000000000L); assertEquals(FPOrdering.ordinalOf(-0F), 0x80000000L); assertTrue(Long.compareUnsigned(FPO...
public String getSource() { return source; }
@Test public void testExchangeDone() throws Exception { // START SNIPPET: e2 // register the NotificationListener ObjectName on = getCamelObjectName(TYPE_EVENT_NOTIFIER, "JmxEventNotifier"); MyNotificationListener listener = new MyNotificationListener(); context.getManagement...
@Override public void accept(final MeterEntity entity, final BucketedValues value) { if (dataset.size() > 0) { if (!value.isCompatible(dataset)) { throw new IllegalArgumentException( "Incompatible BucketedValues [" + value + "] for current HistogramFunction[" ...
@Test public void testFunctionWithInfinite() { HistogramFunctionInst inst = new HistogramFunctionInst(); inst.accept( MeterEntity.newService("service-test", Layer.GENERAL), new BucketedValues( INFINITE_BUCKETS, new long[] { 0, 4...
public static String serialize(Object obj) throws JsonProcessingException { return MAPPER.writeValueAsString(obj); }
@Test void serializeMeterWithoutHost() throws JsonProcessingException { DSeries series = new DSeries(); series.add(new DMeter(new TestMeter(0, 1), METRIC, null, tags, () -> MOCKED_SYSTEM_MILLIS)); assertSerialization( DatadogHttpClient.serialize(series), new ...
@Override public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final S3Object object = this.getDetails(file, status); final DelayedHttpEntityCallable<StorageObject> command = new DelayedHttp...
@Test public void testWriteCustomTimestamp() throws Exception { final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.fil...
public ContentInfo verify(ContentInfo signedMessage, Date date) { final SignedData signedData = SignedData.getInstance(signedMessage.getContent()); final X509Certificate cert = certificate(signedData); certificateVerifier.verify(cert, date); final X500Name name = X500Name.getInstance(ce...
@Test public void verifyValidPcaRvigCms() throws Exception { final ContentInfo signedMessage = ContentInfo.getInstance(fixture("pca-rvig")); final ContentInfo message = new CmsVerifier(new CertificateVerifier.None()).verify(signedMessage); assertEquals(LdsSecurityObject.OID, message.getConte...
public List<Modification> parse(String svnLogOutput, String path, SAXBuilder builder) { try { Document document = builder.build(new StringReader(svnLogOutput)); return parseDOMTree(document, path); } catch (Exception e) { throw bomb("Unable to parse svn log output: " ...
@Test public void shouldGetAllModifiedFilesUnderRootPath() { SvnLogXmlParser parser = new SvnLogXmlParser(); List<Modification> materialRevisions = parser.parse(MULTIPLE_FILES, "", new SAXBuilder()); Modification mod = materialRevisions.get(0); List<ModifiedFile> files = mod.getModi...
static boolean isTableUsingInstancePoolAndReplicaGroup(@Nonnull TableConfig tableConfig) { boolean status = true; Map<String, InstanceAssignmentConfig> instanceAssignmentConfigMap = tableConfig.getInstanceAssignmentConfigMap(); if (instanceAssignmentConfigMap != null) { for (InstanceAssignmentConfig i...
@Test public void testValidIGnRGOfflineTable() { InstanceAssignmentConfig config = new InstanceAssignmentConfig(new InstanceTagPoolConfig("DefaultTenant", true, 0, null), null, new InstanceReplicaGroupPartitionConfig(true, 0, 0, 0, 0, 0, false, null), null, false); TableConfig tableConfig...
@Override public ShardingRule build(final ShardingRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType, final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceCont...
@SuppressWarnings("unchecked") @Test void assertBuild() { assertThat(builder.build(ruleConfig, "sharding_db", new MySQLDatabaseType(), mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), Collections.emptyList(), mock(ComputeNodeInstanceContext.class)), instanceOf(ShardingRule.class)); ...
static void validateJobParameters(List<String> jobParameters) { // Check that parameter is not null if (Objects.isNull(jobParameters)) { throw new JetException("jobParameters can not be null"); } }
@Test public void testValidateJobParameters() { assertThatThrownBy(() -> JarOnClientValidator.validateJobParameters(null)) .isInstanceOf(JetException.class) .hasMessageContaining("jobParameters can not be null"); }
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { try { new EueAttributesFinderFeature(session, fileid).find(file); return true; } catch(NotfoundException e) { return false; } }
@Test public void testFindDirectory() throws Exception { final EueResourceIdProvider fileid = new EueResourceIdProvider(session); final Path folder = new EueDirectoryFeature(session, fileid).mkdir( new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringSer...
@Override public String toString() { return "ID: " + this.id + "\tSequence: " + (this.sequenceNumber + 1) + // +1 for readability: 1/2 not 0/2 "/" + this.sequenceCount + "\tArrival: " + this.arrival + "\tData size: " + this.payload.readableByte...
@Test public void testToString() throws Exception { assertNotNull(buildChunk().toString()); }
public Optional<Boolean> getHelp() { return Optional.ofNullable(mHelp); }
@Test public void testGetHelp() { mJCommander.parse("--help"); assertEquals(Optional.of(true), mOptions.getHelp()); }
@Operation(summary = "create", description = "CREATE_WORKFLOWS_NOTES") @PostMapping(consumes = {"application/json"}) @ResponseStatus(HttpStatus.CREATED) @ApiException(CREATE_PROCESS_DEFINITION_ERROR) public Result<ProcessDefinition> createWorkflow(@Parameter(hidden = true) @RequestAttribute(value = Cons...
@Test public void testCreateWorkflow() { WorkflowCreateRequest workflowCreateRequest = new WorkflowCreateRequest(); workflowCreateRequest.setName(name); workflowCreateRequest.setReleaseState(releaseState); workflowCreateRequest.setProjectCode(projectCode); workflowCreateReque...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void literalWithTwoAccolades() throws ScanException { Tokenizer tokenizer = new Tokenizer("%x{y} %a{b} c"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "%x"); Node t = witness.next = new Node(Node.Type.LITE...
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test public void isEqualTo_WithoutToleranceParameter_Success() { assertThat(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY, 0.0, -0.0)) .isEqualTo(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY, 0.0, -0.0)); }
@Override public void updateIndices(SegmentDirectory.Writer segmentWriter) throws Exception { Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter); if (columnOperationsMap.isEmpty()) { return; } for (Map.Entry<String, List<Operation>> entry : columnOperation...
@Test public void testEnableForwardIndexForDictionaryDisabledColumns() throws Exception { Set<String> forwardIndexDisabledColumns = new HashSet<>(SV_FORWARD_INDEX_DISABLED_COLUMNS); forwardIndexDisabledColumns.addAll(MV_FORWARD_INDEX_DISABLED_COLUMNS); forwardIndexDisabledColumns.addAll(MV_FORWARD_I...
@Override public void close() throws IOException { if (mClosed.getAndSet(true)) { LOG.warn("OBSOutputStream is already closed"); return; } mLocalOutputStream.close(); try { BufferedInputStream in = new BufferedInputStream( new FileInputStream(mFile)); ObjectMetadata o...
@Test @PrepareForTest(OBSOutputStream.class) public void testConstructor() throws Exception { PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(mFile); String errorMessage = "protocol doesn't support output"; PowerMockito.whenNew(FileOutputStream.class).withArguments(mFile) ...
public static <K, V> Read<K, V> read() { return new AutoValue_KafkaIO_Read.Builder<K, V>() .setTopics(new ArrayList<>()) .setTopicPartitions(new ArrayList<>()) .setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN) .setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES) ...
@Test public void testUnboundedSourceWithPattern() { int numElements = 1000; List<String> topics = ImmutableList.of( "best", "gest", "hest", "jest", "lest", "nest", "pest", "rest", "test", "vest", "west", "zest"); String bootStrapServer = "none"; KafkaIO.Read<byte[], ...
private BatchOperationResult suspendAll(RestApi.RequestContext context) { String parentHostnameString = context.pathParameters().getStringOrThrow("hostname"); List<String> hostnamesAsStrings = context.queryParameters().getStringList("hostname"); HostName parentHostname = new HostName(parentHost...
@Test void throws_409_on_suspendAll_timeout() throws BatchHostStateChangeDeniedException, BatchHostNameNotFoundException, BatchInternalErrorException { Orchestrator orchestrator = mock(Orchestrator.class); doThrow(new UncheckedTimeoutException("Timeout Message")).when(orchestrator).suspendAll(any(),...
@Udf public Long trunc(@UdfParameter final Long val) { return val; }
@Test public void shouldTruncateDoubleWithDecimalPlacesNegative() { assertThat(udf.trunc(-1.0d, 0), is(-1.0d)); assertThat(udf.trunc(-1.1d, 0), is(-1.0d)); assertThat(udf.trunc(-1.5d, 0), is(-1.0d)); assertThat(udf.trunc(-1.75d, 0), is(-1.0d)); assertThat(udf.trunc(-100.1d, 0), is(-100.0d)); a...
public static FieldType fieldTypeForJavaType(TypeDescriptor typeDescriptor) { // TODO: Convert for registered logical types. if (typeDescriptor.isArray() || typeDescriptor.isSubtypeOf(TypeDescriptor.of(Collection.class))) { return getArrayFieldType(typeDescriptor); } else if (typeDescriptor.is...
@Test public void testArrayTypeToFieldType() { assertEquals( FieldType.array(FieldType.STRING), FieldTypeDescriptors.fieldTypeForJavaType( TypeDescriptors.lists(TypeDescriptors.strings()))); assertEquals( FieldType.array(FieldType.array(FieldType.STRING)), FieldType...
public void succeededGetResourceProfileRetrieved(long duration) { totalSucceededGetResourceProfileRetrieved.add(duration); getResourceProfileLatency.add(duration); }
@Test public void testSucceededGetResourceProfileRetrieved() { long totalGoodBefore = metrics.getNumSucceededGetResourceProfileRetrieved(); goodSubCluster.getResourceProfileRetrieved(150); Assert.assertEquals(totalGoodBefore + 1, metrics.getNumSucceededGetResourceProfileRetrieved()); Assert.as...
@Override public boolean hasNext() { return innerIterator.hasNext(); }
@Test public void shouldForwardHasNext() { when(mockedKeyValueIterator.hasNext()).thenReturn(true).thenReturn(false); assertTrue(keyValueIteratorFacade.hasNext()); assertFalse(keyValueIteratorFacade.hasNext()); }
public boolean toBoolean(String name) { return toBoolean(name, false); }
@Test public void testToBoolean_String() { System.out.println("toBoolean"); boolean expResult; boolean result; Properties props = new Properties(); props.put("value1", "true"); props.put("value2", "false"); props.put("empty", ""); props.put("str", "ab...
@Override public void loadGlue(Glue glue, List<URI> gluePaths) { gluePaths.stream() .filter(gluePath -> CLASSPATH_SCHEME.equals(gluePath.getScheme())) .map(ClasspathSupport::packageName) .map(classFinder::scanForClassesInPackage) .flatMap(Colle...
@Test void finds_injector_source_impls_once_by_classpath_url() { GuiceBackend backend = new GuiceBackend(factory, classLoader); backend.loadGlue(glue, asList(URI.create("classpath:io/cucumber/guice/integration"), URI.create("classpath:io/cucumber/guice/integration"))); verify(fac...
public double currentErrorRate() { return collectorMap.values().stream() .mapToDouble(MetricCollector::errorRate) .sum(); }
@Test public void shouldAggregateDeserializationErrors() { final MetricCollectors metricCollectors = new MetricCollectors(); final StreamsErrorCollector streamsErrorCollector = StreamsErrorCollector.create( "test-application", metricCollectors ); for (int i = 0; i < 2000; i++) { ...
public static <T> DequeCoder<T> of(Coder<T> elemCoder) { return new DequeCoder<>(elemCoder); }
@Test public void testCoderIsSerializableWithWellKnownCoderType() throws Exception { CoderProperties.coderSerializable(DequeCoder.of(GlobalWindow.Coder.INSTANCE)); }
@Override public Integer convertStringToValue(final String value) { return Integer.valueOf(value); }
@Test void testConvertStringToValue() { assertThat(parallelismQueryParameter.convertValueToString(42)).isEqualTo("42"); }
@Override public boolean shouldWait() { RingbufferContainer ringbuffer = getRingBufferContainerOrNull(); if (resultSet == null) { resultSet = new ReadResultSetImpl<>(minSize, maxSize, getNodeEngine().getSerializationService(), filter); sequence = startSequence; } ...
@Test public void whenOnTailAndBufferEmpty() { ReadManyOperation op = getReadManyOperation(ringbuffer.tailSequence(), 1, 1, null); // since there is an item, we don't need to wait boolean shouldWait = op.shouldWait(); assertTrue(shouldWait); ReadResultSetImpl response = get...
@Override public InstancePort instancePort(MacAddress macAddress) { checkNotNull(macAddress, ERR_NULL_MAC_ADDRESS); return instancePortStore.instancePorts().stream() .filter(port -> port.macAddress().equals(macAddress)) .findFirst().orElse(null); }
@Test public void testGetInstancePortById() { createBasicInstancePorts(); assertNotNull("Instance port did not match", target.instancePort(PORT_ID_1)); assertNotNull("Instance port did not match", target.instancePort(PORT_ID_2)); assertNull("Instance port did not match", target.insta...
public static LoginManager acquireLoginManager(JaasContext jaasContext, String saslMechanism, Class<? extends Login> defaultLoginClass, Map<String, ?> configs) throws LoginException { Class<? extends Login> log...
@Test public void testShouldReThrowExceptionOnErrorLoginAttempt() throws Exception { Map<String, Object> config = new HashMap<>(); config.put(SaslConfigs.SASL_JAAS_CONFIG, dynamicPlainContext); config.put(SaslConfigs.SASL_LOGIN_CLASS, Login.class); config.put(SaslConfigs.SASL_LOGIN_C...