focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
static CompletableFuture<Void> updateSubscriptions(Pattern topicsPattern, java.util.function.Consumer<String> topicsHashSetter, GetTopicsResult getTopicsResult, ...
@Test public void testChangedFilteredResponse() { PatternMultiTopicsConsumerImpl.updateSubscriptions( Pattern.compile("tenant/my-ns/name-.*"), mockTopicsHashSetter, new GetTopicsResult(Arrays.asList( "persistent://tenant/my-ns/name-0", ...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { return payload.readStringFixByBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); }
@Test void assertReadWithMeta1() { columnDef.setColumnMeta(1); when(payload.getByteBuf()).thenReturn(byteBuf); when(byteBuf.readUnsignedByte()).thenReturn((short) 0xff); when(payload.readStringFixByBytes(0xff)).thenReturn(new byte[255]); assertThat(new MySQLBlobBinlogProtocol...
@CheckForNull @Override public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) { return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir))) .map(GitScmProvider::extractAbsoluteFilePaths) .orElse(null); }
@Test public void branchChangedFiles_should_not_crash_if_branches_have_no_common_ancestors() throws GitAPIException, IOException { String fileName = "file-in-first-commit.xoo"; String renamedName = "file-renamed.xoo"; git.checkout().setOrphan(true).setName("b1").call(); Path file = worktree.resolve(f...
ConcurrentPublication addPublication(final String channel, final int streamId) { clientLock.lock(); try { ensureActive(); ensureNotReentrant(); final long registrationId = driverProxy.addPublication(channel, streamId); stashedChannelByRegistra...
@Test void addPublicationShouldMapLogFile() { whenReceiveBroadcastOnMessage( ControlProtocolEvents.ON_PUBLICATION_READY, publicationReadyBuffer, (buffer) -> publicationReady.length()); conductor.addPublication(CHANNEL, STREAM_ID_1); verify(logBuffers...
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) { if ( from == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));...
@Test void invokeGroupEqualsDecimal() { FunctionTestUtil.assertResultError(numberFunction.invoke("1 000.1", ".", "."), InvalidParametersEvent.class); }
@VisibleForTesting static SingleSegmentAssignment getNextSingleSegmentAssignment(Map<String, String> currentInstanceStateMap, Map<String, String> targetInstanceStateMap, int minAvailableReplicas, boolean lowDiskMode, Map<String, Integer> numSegmentsToOffloadMap, Map<Pair<Set<String>, Set<String>>, Set<Str...
@Test public void testDowntimeWithLowDiskMode() { // With common instance, first assignment should keep the common instance and remove the not common instance Map<String, String> currentInstanceStateMap = SegmentAssignmentUtils.getInstanceStateMap(Arrays.asList("host1", "host2"), ONLINE); Map<Stri...
public String toCompactListString() { return id + COMMA + locType + COMMA + latOrY + COMMA + longOrX; }
@Test public void toCompactListStringNullList() { String s = toCompactListString((List<LayoutLocation>) null); assertEquals("not empty string", "", s); }
public static int readVarint(ByteBuffer buffer) { int value = readUnsignedVarint(buffer); return (value >>> 1) ^ -(value & 1); }
@Test public void testInvalidVarint() { // varint encoding has one overflow byte ByteBuffer buf = ByteBuffer.wrap(new byte[] {xFF, xFF, xFF, xFF, xFF, x01}); assertThrows(IllegalArgumentException.class, () -> ByteUtils.readVarint(buf)); }
@SuppressWarnings("unchecked") public static int compare(Comparable lhs, Comparable rhs) { assert lhs != null; assert rhs != null; if (lhs.getClass() == rhs.getClass()) { return lhs.compareTo(rhs); } if (lhs instanceof Number && rhs instanceof Number) { ...
@Test(expected = Throwable.class) public void testIncompatibleTypesInCompare() { compare("string", 1); }
public static Class<?> defineClass( String className, Class<?> neighbor, ClassLoader loader, ProtectionDomain domain, byte[] bytecodes) { Preconditions.checkNotNull(loader); Preconditions.checkArgument(Platform.JAVA_VERSION >= 8); if (neighbor != null && Platform.JAVA_VERSION >...
@Test public void testDefineClass() throws ClassNotFoundException { String pkg = DefineClassTest.class.getPackage().getName(); CompileUnit unit = new CompileUnit( pkg, "A", ("package " + pkg + ";\n" + "public class A {...
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); ...
@Test public void testInternalConnect_unbounded_limit() throws Exception { ReadOnlyTableProvider tableProvider = new ReadOnlyTableProvider( "test", ImmutableMap.of( "test", TestUnboundedTable.of( Schema.FieldType.INT32, "order...
@Override void toHtml() throws IOException { writeHtmlHeader(); htmlCoreReport.toHtml(); writeHtmlFooter(); }
@Test public void testCounter() throws IOException { // counter avec 3 requêtes setProperty(Parameter.WARNING_THRESHOLD_MILLIS, "500"); setProperty(Parameter.SEVERE_THRESHOLD_MILLIS, "1500"); setProperty(Parameter.ANALYTICS_ID, "123456789"); counter.addRequest("test1", 0, 0, 0, false, 1000); counter.addReq...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindFewerGenericsWithEarlierVariadic() { // Given: givenFunctions( function(EXPECTED, 0, INT_VARARGS, GenericType.of("A"), INT, INT), function(OTHER, 3, INT, GenericType.of("A"), GenericType.of("B"), INT_VARARGS) ); // When: final KsqlScalarFunction...
@Override public void transform(Message message, DataType fromType, DataType toType) { final Map<String, Object> headers = message.getHeaders(); CloudEvent cloudEvent = CloudEvents.v1_0; headers.putIfAbsent(cloudEvent.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_ID).http(), ...
@Test void shouldSetDefaultCloudEventAttributes() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setBody(new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8))); transformer.transform(exchange.getMessage(), DataType.ANY, DataType.AN...
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); decodeCommandPacket(payload, out); }
@Test void assertDecodeOkPacket() { MySQLCommandPacketDecoder commandPacketDecoder = new MySQLCommandPacketDecoder(); List<Object> actual = new LinkedList<>(); commandPacketDecoder.decode(channelHandlerContext, mockOkPacket(), actual); assertPacketByType(actual, MySQLOKPacket.class);...
@Override public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final EncryptRule rule) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof MySQLExplainStatement || sqlStatement instanceof MySQLShowColu...
@Test void assertMergedResultWithOtherStatement() { sqlStatementContext = mock(SQLStatementContext.class); EncryptDALResultDecorator encryptDALResultDecorator = new EncryptDALResultDecorator(mock(RuleMetaData.class)); assertThat(encryptDALResultDecorator.decorate(mock(QueryResult.class), sql...
public static Builder builder() { return new Builder(); }
@Test public void testEqualsAndHashCode() { RuleData ruleData1 = RuleData.builder().id("id").name("name").pluginName("pluginName") .selectorId("selectorId").matchMode(1).sort(0).enabled(true).loged(true) .handle("handle").conditionDataList(new ArrayList<>()).build(); ...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentExecutor, TokenSecretAuthData authData, VideosContainerResource data) throws Exception { if (data == null) { // Nothing to do return ImportResult.OK; } BackblazeDataTransferC...
@Test public void testEmptyVideos() throws Exception { VideosContainerResource data = mock(VideosContainerResource.class); when(data.getVideos()).thenReturn(new ArrayList<>()); BackblazeVideosImporter sut = new BackblazeVideosImporter(monitor, dataStore, streamProvider, clientFactory); Import...
@Override public double read() { return gaugeSource.read(); }
@Test public void whenNotVisitedWithCachedValueReadsDefault() { DynamicMetricsProvider concreteProvider = (descriptor, context) -> context.collect(descriptor.withPrefix("foo"), "doubleField", INFO, COUNT, 42.42D); metricsRegistry.registerDynamicMetricsProvider(concreteProvider); ...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void deleteChatStickerSet() { BaseResponse response = bot.execute(new DeleteChatStickerSet(groupId)); assertFalse(response.isOk()); assertEquals(400, response.errorCode()); }
public CoercedExpressionResult coerce() { final Class<?> leftClass = left.getRawClass(); final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass); final Class<?> rightClass = right.getRawClass(); final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass); ...
@Test public void testStringToBooleanFalse() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getBooleanValue", Boolean.class); final TypedExpression right = expr("\"false\"", String.class); final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, f...
public static long write(InputStream is, OutputStream os) throws IOException { return write(is, os, BUFFER_SIZE); }
@Test void testWrite4() throws Exception { assertThat((int) IOUtils.write(is, os), equalTo(TEXT.length())); }
public String nextString() throws IOException { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED) { result = nextUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED) { result = nextQuotedValue('\''); } else if (p == PEEKED_DO...
@Test public void testEscapeCharacterQuoteWithoutStrictMode() throws IOException { String json = "\"\\'\""; JsonReader reader = new JsonReader(reader(json)); assertThat(reader.nextString()).isEqualTo("'"); }
public static DeploymentDescriptor merge(List<DeploymentDescriptor> descriptorHierarchy, MergeMode mode) { if (descriptorHierarchy == null || descriptorHierarchy.isEmpty()) { throw new IllegalArgumentException("Descriptor hierarchy list cannot be empty"); } if (descriptorHierarchy.si...
@Test public void testDeploymentDesciptorMergeMergeCollectionsAvoidDuplicatesNamedObject() { DeploymentDescriptor primary = new DeploymentDescriptorImpl("org.jbpm.domain"); primary.getBuilder() .addWorkItemHandler(new NamedObjectModel("mvel", "Log", "new org....
public static void jsonEscape(CharSequence in, WriteBuffer out) { int length = in.length(); if (length == 0) return; int afterReplacement = 0; for (int i = 0; i < length; i++) { char c = in.charAt(i); String replacement; if (c < 0x80) { replacement = REPLACEMENT_CHARS[c]; ...
@Test void testJsonEscape() { WriteBuffer buffer = new WriteBuffer(buf, 0); jsonEscape(new String(new char[] {0, 'a', 1}), buffer); assertThat(buffer).hasToString("\\u0000a\\u0001"); buffer.pos = 0; jsonEscape(new String(new char[] {'"', '\\', '\t', '\b'}), buffer); assertThat(buffer).hasToStri...
public static <InputT, OutputT> MapElements<InputT, OutputT> via( final InferableFunction<InputT, OutputT> fn) { return new MapElements<>(fn, fn.getInputTypeDescriptor(), fn.getOutputTypeDescriptor()); }
@Test @Category(NeedsRunner.class) public void testMapWrappedLambda() throws Exception { PCollection<Integer> output = pipeline .apply(Create.of(1, 2, 3)) .apply(MapElements.via(new SimpleFunction<Integer, Integer>((Integer i) -> i * 2) {})); PAssert.that(output).containsIn...
@Override public boolean isInOneOf(Set<?> allowedPrincipals) { throw notAllowed("isInOneOf"); }
@Test(expected=UnsupportedOperationException.class) public void testInOneOf() { ctx.isInOneOf(null); }
public boolean isOther() { return type == Type.OTHER; }
@Test void testPojo() { JsValue jv = je.eval("new com.intuit.karate.core.SimplePojo()"); assertTrue(jv.isOther()); }
@Override protected String processLink(IExpressionContext context, String link) { if (link == null || !linkInSite(externalUrlSupplier.get(), link)) { return link; } if (StringUtils.isBlank(link)) { link = "/"; } if (isAssetsRequest(link)) { ...
@Test void processTemplateLinkWithNoActive() { ThemeLinkBuilder themeLinkBuilder = new ThemeLinkBuilder(getTheme(false), externalUrlSupplier); String link = "/post"; String processed = themeLinkBuilder.processLink(null, link); assertThat(processed).isEqualTo("/post?previ...
public void clear() { throw e; }
@Test void require_that_clear_throws_exception() { assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").clear()); }
public static CompositeData parseComposite(URI uri) throws URISyntaxException { CompositeData rc = new CompositeData(); rc.scheme = uri.getScheme(); String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); parseComposite(uri, rc, ssp); rc.fragment = uri.ge...
@Test public void testCompositeWithParenthesisInParam() throws Exception { URI uri = new URI("failover://(test)?updateURIsURL=file:/C:/Dir(1)/a.csv"); CompositeData data = URISupport.parseComposite(uri); assertEquals(1, data.getComponents().length); assertEquals(1, data.getParameters...
@Override public void addVisualizedAutoTrackActivity(Class<?> activity) { }
@Test public void addVisualizedAutoTrackActivity() { mSensorsAPI.addVisualizedAutoTrackActivity(EmptyActivity.class); Assert.assertFalse(mSensorsAPI.isVisualizedAutoTrackActivity(EmptyActivity.class)); }
public static <T> T createInstance(String userClassName, Class<T> xface, ClassLoader classLoader) { Class<?> theCls; try { theCls = Class.forName(userClassName, true, classLoader); } catch (ClassNotFoundExc...
@Test public void testCreateTypedInstanceUnassignableClass() { try { createInstance(aImplementation.class.getName(), bInterface.class, classLoader); fail("Should fail to load a class that isn't assignable"); } catch (RuntimeException re) { assertEquals( ...
public ConsumerBuilder threads(Integer threads) { this.threads = threads; return getThis(); }
@Test void threads() { ConsumerBuilder builder = ConsumerBuilder.newBuilder(); builder.threads(100); Assertions.assertEquals(100, builder.build().getThreads()); }
public static String toString(String unicode) { if (StrUtil.isBlank(unicode)) { return unicode; } final int len = unicode.length(); StringBuilder sb = new StringBuilder(len); int i; int pos = 0; while ((i = StrUtil.indexOfIgnoreCase(unicode, "\\u", pos)) != -1) { sb.append(unicode, pos, i);//写入Unic...
@Test public void convertTest3() { String str = "aaa\\u111"; String res = UnicodeUtil.toString(str); assertEquals("aaa\\u111", res); }
FileDialogOperation createFileDialogOperation( SelectionOperation selectionOperation ) { switch ( selectionOperation ) { case FILE: return new FileDialogOperation( FileDialogOperation.SELECT_FILE, FileDialogOperation.ORIGIN_SPOON ); case FOLDER: return new FileDialogOperation( FileDialo...
@Test public void testCreateFileDialogOperation() { // TEST : SELECT file FileDialogOperation fdo1 = testInstance.createFileDialogOperation( SelectionOperation.FILE ); assertNotNull( fdo1 ); assertEquals( FileDialogOperation.SELECT_FILE, fdo1.getCommand() ); assertEquals( FileDialogOperation.ORIGI...
@Override public CompletionStage<Void> write(int segment, MarshallableEntry<? extends K, ? extends V> entry) { return handler.write(segment, entry); }
@Test(groups = "stress") public void testConcurrentWrite() throws InterruptedException { final int THREADS = 8; final AtomicBoolean run = new AtomicBoolean(true); final AtomicInteger written = new AtomicInteger(); final CountDownLatch started = new CountDownLatch(THREADS); final CountDo...
public void assignBroker(NamespaceName nsname, BrokerStatus brkStatus, SortedSet<BrokerStatus> primaryCandidates, SortedSet<BrokerStatus> secondaryCandidates, SortedSet<BrokerStatus> sharedCandidates) { NamespaceIsolationPolicy nsPolicy = this.getPolicyByNamespace(nsname); BrokerAssignment b...
@Test public void testBrokerAssignment() throws Exception { NamespaceIsolationPolicies policies = this.getDefaultTestPolicies(); NamespaceName ns = NamespaceName.get("pulsar/use/testns-1"); SortedSet<BrokerStatus> primaryCandidates = new TreeSet<>(); BrokerStatus primary = BrokerStat...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testNotAllowNullSchema() throws JSONException { JSONSchema<Foo> jsonSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).withAlwaysAllowNull(false).build()); Assert.assertEquals(jsonSchema.getSchemaInfo().getType(), SchemaType.JSON); Schema.Parser pars...
@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_non_serializable_object() { Object original = new NonSerializableObject("value"); Object cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSame(original, cloned); }
@Override public boolean supportsOrderByUnrelated() { return false; }
@Test void assertSupportsOrderByUnrelated() { assertFalse(metaData.supportsOrderByUnrelated()); }
public static Builder newIntegerColumnDefBuilder() { return new Builder(); }
@Test public void builder_build_throws_NPE_if_no_name_was_set() { IntegerColumnDef.Builder builder = newIntegerColumnDefBuilder(); assertThatThrownBy(builder::build) .isInstanceOf(NullPointerException.class) .hasMessage("Column name cannot be null"); }
static Class<?> getCommandClass(String request) { try { return Class.forName("com.iluwatar.front.controller." + request + "Command"); } catch (ClassNotFoundException e) { return UnknownCommand.class; } }
@Test void testGetCommandClassUnknown() { Class<?> commandClass = Dispatcher.getCommandClass("Unknown"); assertNotNull(commandClass); assertEquals(UnknownCommand.class, commandClass); }
public void onChange(Multimap<QProfileName, ActiveRuleChange> changedProfiles, long startDate, long endDate) { if (config.getBoolean(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES).orElse(false)) { return; } BuiltInQPChangeNotificationBuilder builder = new BuiltInQPChangeNotificationBuilder(); change...
@Test public void add_profile_to_notification_for_added_rules() { enableNotificationInGlobalSettings(); Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create(); Languages languages = new Languages(); Tuple expectedTuple = addProfile(profiles, languages, ACTIVATED); BuiltInQ...
@Override protected InputStream dumpSnapshot() { Map<Service, ServiceMetadata> snapshot = metadataManager.getServiceMetadataSnapshot(); return new ByteArrayInputStream(serializer.serialize(snapshot)); }
@Test void testDumpSnapshot() { InputStream inputStream = serviceMetadataSnapshotOperation.dumpSnapshot(); assertNotNull(inputStream); }
Mono<Void> sendNotification(NotificationElement notificationElement) { var descriptor = notificationElement.descriptor(); var subscriber = notificationElement.subscriber(); final var notifierExtName = descriptor.getSpec().getNotifierExtName(); return notificationContextFrom(notificationE...
@Test public void testSendNotification() { var spyNotificationCenter = spy(notificationCenter); var context = mock(NotificationContext.class); doReturn(Mono.just(context)) .when(spyNotificationCenter).notificationContextFrom(any()); when(notificationSender.sendNotificat...
@Override protected String getScheme() { return config.getScheme(); }
@Test public void testGetSchemeWithS3Options() { S3FileSystem s3FileSystem = new S3FileSystem(s3Options()); assertEquals("s3", s3FileSystem.getScheme()); }
@Override public Set<String> initialize() { try { checkpointFileCache.putAll(checkpointFile.read()); } catch (final IOException e) { throw new StreamsException("Failed to read checkpoints for global state globalStores", e); } final Set<String> changelogTopics...
@Test public void shouldReturnInitializedStoreNames() { final Set<String> storeNames = stateManager.initialize(); assertEquals(Utils.mkSet(storeName1, storeName2, storeName3, storeName4, storeName5), storeNames); }
@SuppressWarnings("unchecked") public static <T> NFAFactory<T> compileFactory( final Pattern<T, ?> pattern, boolean timeoutHandling) { if (pattern == null) { // return a factory for empty NFAs return new NFAFactoryImpl<>( 0, Collect...
@Test public void testCheckPatternWindowTimes() { expectedException.expect(MalformedPatternException.class); expectedException.expectMessage( "The window length between the previous and current event cannot be larger than the window length between the first and last event for a Patte...
@ConstantFunction(name = "int_divide", argTypes = {LARGEINT, LARGEINT}, returnType = LARGEINT) public static ConstantOperator intDivideLargeInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createLargeInt(first.getLargeInt().divide(second.getLargeInt())); }
@Test public void intDivideLargeInt() { assertEquals("1", ScalarOperatorFunctions.intDivideLargeInt(O_LI_100, O_LI_100).getLargeInt().toString()); }
public boolean isOpen() { return opened; }
@Test void isOpenTest() throws InterpreterException { InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS, ""); when(interpreter.interpret(any(String.class), any(InterpreterContext.class))) .thenReturn(interpreterResult); LazyOpenInterpreter lazyOpenInterpre...
@Override public <T> Optional<T> valueAs(Class<T> type) { checkNotNull(type); return id.lastComponentAs(type); }
@Test public void testValueAs() { DiscreteResource resource = Resources.discrete(D1).resource(); Optional<DeviceId> volume = resource.valueAs(DeviceId.class); assertThat(volume.get(), is(D1)); }
public static void determineTimestamps(Configuration job, Map<URI, FileStatus> statCache) throws IOException { URI[] tarchives = JobContextImpl.getCacheArchives(job); if (tarchives != null) { FileStatus status = getFileStatus(job, tarchives[0], statCache); StringBuilder archiveFileSizes = ...
@Test public void testDetermineTimestamps() throws IOException { Job job = Job.getInstance(conf); job.addCacheFile(firstCacheFile.toUri()); job.addCacheFile(secondCacheFile.toUri()); Configuration jobConf = job.getConfiguration(); Map<URI, FileStatus> statCache = new HashMap<>(); ClientDi...
private void tick() { scheduledFuture = executor.schedule(this::run, delayMillis, MILLISECONDS); }
@Test(enabled = false) public void testTick() throws Exception { int numberOfTicks = 2; long durationBetweenTicksInSeconds = 2; CountDownLatch latch = new CountDownLatch(3); Runnable runnable = latch::countDown; try (PeriodicTaskExecutor executor = new Perio...
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory( final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration, final Configuration jobConfiguration, final Configuration clusterConfiguration, final boolean is...
@Test void testFailureRateRestartStrategySpecifiedInExecutionConfig() { final Configuration conf = new Configuration(); conf.set(RestartStrategyOptions.RESTART_STRATEGY, FIXED_DELAY.getMainValue()); final RestartBackoffTimeStrategy.Factory factory = RestartBackoffTimeStrateg...
@Override public Object get(PropertyKey key) { return get(key, ConfigurationValueOptions.defaults()); }
@Test public void noWhitespaceTrailingInSiteProperties() throws Exception { Properties siteProps = new Properties(); siteProps.setProperty(PropertyKey.MASTER_HOSTNAME.toString(), " host-1 "); siteProps.setProperty(PropertyKey.WEB_THREADS.toString(), "\t123\t"); File propsFile = mFolder.newFile(Constan...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Config config = (Config) o; return entries.equals(config.entries); }
@Test public void testEquals() { ConfigEntry ce0 = new ConfigEntry("abc", null, ConfigEntry.ConfigSource.DEFAULT_CONFIG, false, false, null, null, null); ConfigEntry ce1 = new ConfigEntry("abc", null, ConfigEntry.ConfigSource.DYNAMIC_BROKER_CONFIG, false, false, null, null, null); assertNotE...
public static boolean isViewIgnored(View view) { try { //基本校验 if (view == null) { return true; } //ViewType 被忽略 List<Class<?>> mIgnoredViewTypeList = SensorsDataAPI.sharedInstance().getIgnoredViewTypeList(); if (mIgnoredVie...
@Test public void isViewIgnored() { SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplication); TextView textView1 = new TextView(mApplication); textView1.setText("child1"); sensorsDataAPI.ignoreView(textView1); Assert.assertTrue(SAViewUtils.isViewIgnored(textView1));...
HasRuleEngineProfile getRuleEngineProfileForEntityOrElseNull(TenantId tenantId, EntityId entityId, TbMsg tbMsg) { if (entityId.getEntityType().equals(EntityType.DEVICE)) { if (TbMsgType.ENTITY_DELETED.equals(tbMsg.getInternalType())) { try { Device deletedDevice =...
@Test public void testGetRuleEngineProfileForUpdatedAndDeletedAsset() { AssetId assetId = new AssetId(UUID.randomUUID()); TenantId tenantId = new TenantId(UUID.randomUUID()); AssetProfileId assetProfileId = new AssetProfileId(UUID.randomUUID()); Asset asset = new Asset(assetId); ...
public abstract ImmutableSet<String> objectClasses();
@Test void objectClasses() { 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.objectClasses()).isE...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf...
@Test public void return_nb_of_processors() { ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThat(attribute(protobuf, "Processors").getLongValue()).isPositive(); }
@Override public void execute(Exchange exchange) throws SmppException { byte[] message = getShortMessage(exchange.getIn()); ReplaceSm replaceSm = createReplaceSmTempate(exchange); replaceSm.setShortMessage(message); if (log.isDebugEnabled()) { log.debug("Sending replace...
@Test public void latin1DataCodingOverridesEightBitAlphabet() throws Exception { final int latin1DataCoding = 0x03; /* ISO-8859-1 (Latin1) */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (b...
@Override public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException { if (needUsingInternalAddr()) { remoteInstance = new RemoteInstance( new Address(config.getInternalComHost(), config.getInternalComPort(), true)); } this.selfAddre...
@Test public void registerSelfRemote() { registerRemote(selfRemoteAddress); }
public static ResourceBundle getBundledResource(String basename) { return ResourceBundle.getBundle(basename, new UTF8Control()); }
@Test public void getBundleByClassname() { title("getBundleByClassname"); res = LionUtils.getBundledResource(LionUtils.class); assertNotNull("missing resource bundle", res); String v1 = res.getString("foo"); String v2 = res.getString("boo"); print("v1 is %s, v2 is %s"...
@Override public void startTrackingPartition( ResourceID producingTaskExecutorId, ResultPartitionDeploymentDescriptor resultPartitionDeploymentDescriptor) { Preconditions.checkNotNull(producingTaskExecutorId); Preconditions.checkNotNull(resultPartitionDeploymentDescriptor); ...
@Test void testGetJobPartitionClusterPartition() { final TestingShuffleMaster shuffleMaster = new TestingShuffleMaster(); final Queue<ReleaseCall> releaseCalls = new ArrayBlockingQueue<>(4); final Queue<PromoteCall> promoteCalls = new ArrayBlockingQueue<>(4); final JobMasterPartitio...
@ConstantFunction(name = "concat_ws", argTypes = {VARCHAR, VARCHAR}, returnType = VARCHAR) public static ConstantOperator concat_ws(ConstantOperator split, ConstantOperator... values) { Preconditions.checkArgument(values.length > 0); if (split.isNull()) { return ConstantOperator.createNu...
@Test public void concat_ws() { ConstantOperator[] arg = {ConstantOperator.createVarchar("1"), ConstantOperator.createVarchar("2"), ConstantOperator.createVarchar("3")}; ConstantOperator result = ScalarOperatorFunctions.concat_ws(ConstantOperator.createVarchar(","), a...
public static NotFoundException roleNotFound(String roleName) { return new NotFoundException( "role not found for roleName:%s, please check apollo portal DB table 'Role'", roleName ); }
@Test void roleNotFound() { NotFoundException exception = NotFoundException.roleNotFound("CreateApplication+SystemRole"); assertEquals(exception.getMessage(), "role not found for roleName:CreateApplication+SystemRole, please check apollo portal DB table 'Role'"); }
public static void main(String[] args) throws Throwable { if (!parseInputArgs(args)) { usage(); System.exit(EXIT_FAILED); } if (sHelp) { usage(); System.exit(EXIT_SUCCEEDED); } try { dumpJournal(); } catch (Exception exc) { System.out.printf("Journal tool fai...
@Test public void relativeLocalJournalInput() throws Throwable { String journalPath = "fileA"; JournalTool.main(new String[]{"-inputDir", journalPath}); String inputUri = Whitebox.getInternalState(JournalTool.class, "sInputDir"); Assert.assertEquals( Paths.get(System.getProperty("user.dir"), j...
public static String getTablesPath(final String databaseName, final String schemaName) { return String.join("/", getSchemaDataPath(databaseName, schemaName), TABLES_NODE); }
@Test void assertGetTablesPath() { assertThat(ShardingSphereDataNode.getTablesPath("db_name", "db_schema"), is("/statistics/databases/db_name/schemas/db_schema/tables")); }
@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 testNonTerminalStatusOnWorkflowFinalizedError() { StepRuntimeState state = new StepRuntimeState(); state.setStatus(StepInstance.Status.RUNNING); when(stepInstanceDao.getAllStepStates(any(), anyLong(), anyLong())) .thenReturn(singletonMap("foo", state)); when(workflow.getStatu...
public Clock clock() { return new Clock() { @Override public long currentTimeMicroseconds() { return System.currentTimeMillis() * 1000; } @Override public String toString() { return "System.currentTimeMillis()"; } }; }
@Test void clock_hasNiceToString_jre7() { Platform platform = new Platform.Jre7(); assertThat(platform.clock()).hasToString("System.currentTimeMillis()"); }
@Override public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException { return new Checksum(HashAlgorithm.md5, this.digest("MD5", this.normalize(in, status), status)); }
@Test public void testComputeEmptyString() throws Exception { assertEquals("d41d8cd98f00b204e9800998ecf8427e", new MD5ChecksumCompute().compute(IOUtils.toInputStream("", Charset.defaultCharset()), new TransferStatus()).hash); assertEquals("d41d8cd98f00b204e9800998ecf8427e", n...
@Override public boolean remove(Object objectToRemove) { return remove(objectToRemove, objectToRemove.hashCode()); }
@Test(expected = NullPointerException.class) public void testRemoveNull() { final OAHashSet<Integer> set = new OAHashSet<>(8); set.remove(null); }
@Override public CloseableIterator<ScannerReport.Measure> readComponentMeasures(int componentRef) { ensureInitialized(); return delegate.readComponentMeasures(componentRef); }
@Test public void verify_readComponentMeasures_returns_measures() { writer.appendComponentMeasure(COMPONENT_REF, MEASURE); try (CloseableIterator<ScannerReport.Measure> measures = underTest.readComponentMeasures(COMPONENT_REF)) { assertThat(measures.next()).isEqualTo(MEASURE); assertThat(measures...
public synchronized <KIn, VIn> Topology addReadOnlyStateStore(final StoreBuilder<?> storeBuilder, final String sourceName, final TimestampExtractor timestampExtractor, ...
@Test public void readOnlyStateStoresShouldNotLog() { final String sourceName = "source"; final String storeName = "store"; final String topicName = "topic"; final String processorName = "processor"; final KeyValueStoreBuilder<?, ?> storeBuilder = mock(KeyValueStoreBuilder.c...
public static void verifyGroupId(final String groupId) { if (StringUtils.isBlank(groupId)) { throw new IllegalArgumentException("Blank groupId"); } if (!GROUP_ID_PATTER.matcher(groupId).matches()) { throw new IllegalArgumentException( "Invalid group id, it...
@Test(expected = IllegalArgumentException.class) public void tetsVerifyGroupId4() { Utils.verifyGroupId("*test"); }
protected org.graylog2.plugin.indexer.searches.timeranges.TimeRange restrictTimeRange(final org.graylog2.plugin.indexer.searches.timeranges.TimeRange timeRange) { final DateTime originalFrom = timeRange.getFrom(); final DateTime to = timeRange.getTo(); final DateTime from; final Searche...
@Test public void restrictTimeRangeReturnsGivenTimeRangeWithinLimit() { when(clusterConfigService.get(SearchesClusterConfig.class)).thenReturn(SearchesClusterConfig.createDefault() .toBuilder() .queryTimeRangeLimit(queryLimitPeriod) .build()); final D...
@Override @MethodNotAvailable public void loadAll(boolean replaceExistingValues) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testLoadAllWithListener() { adapter.loadAll(Collections.emptySet(), true, null); }
@SuppressWarnings("unchecked") @VisibleForTesting Schema<T> initializeSchema() throws ClassNotFoundException { if (StringUtils.isEmpty(this.pulsarSinkConfig.getTypeClassName())) { return (Schema<T>) Schema.BYTES; } Class<?> typeArg = Reflections.loadClass(this.pulsarSinkConf...
@Test public void testExplicitDefaultSerDe() throws PulsarClientException { PulsarSinkConfig pulsarConfig = getPulsarConfigs(); // set type to void pulsarConfig.setTypeClassName(String.class.getName()); pulsarConfig.setSerdeClassName(TopicSchema.DEFAULT_SERDE); PulsarSink pul...
private static Map<String, Object> flatten(Map<String, Object> map) { return map.entrySet().stream().flatMap(JsonUtils::flatten) .collect(LinkedHashMap::new, (m, e) -> m.put("/" + e.getKey(), e.getValue()), LinkedHashMap::putAll); }
@Test public void testFlatten() throws IOException { JsonIndexConfig jsonIndexConfig = new JsonIndexConfig(); { JsonNode jsonNode = JsonUtils.stringToJsonNode("null"); List<Map<String, String>> flattenedRecords = JsonUtils.flatten(jsonNode, jsonIndexConfig); assertTrue(flattenedRecords...
@Delete(uri = "{namespace}/{id}") @ExecuteOn(TaskExecutors.IO) @Operation(tags = {"Flows"}, summary = "Delete a flow") @ApiResponse(responseCode = "204", description = "On success") public HttpResponse<Void> delete( @Parameter(description = "The flow namespace") @PathVariable String namespace, ...
@Test void deleteFlowsByQuery(){ postFlow("flow-a","io.kestra.tests.delete", "a"); postFlow("flow-b","io.kestra.tests.delete", "b"); postFlow("flow-c","io.kestra.tests.delete", "c"); List<IdWithNamespace> ids = List.of( new IdWithNamespace("io.kestra.tests.delete", "flow...
public static Map<String, String> deserialize2Map(String jsonStr) { try { if (StringUtils.hasText(jsonStr)) { Map<String, Object> temp = OM.readValue(jsonStr, Map.class); Map<String, String> result = new HashMap<>(); temp.forEach((key, value) -> { result.put(String.valueOf(key), String.valueOf(val...
@Test public void testDeserializeBlankIntoEmptyMap() { Map<String, String> map = JacksonUtils.deserialize2Map(""); assertThat(map).isNotNull(); assertThat(map).isEmpty(); }
public LineString extractPart(double startDistance, double endDistance) { LineString result = new LineString(); for (int i = 0; i < this.segments.size(); startDistance -= this.segments.get(i).length(), endDistance -= this.segments.get(i).length(), i++) { LineSegment segment = this.segments....
@Test public void extractPartTest() { Point point1 = new Point(0, 0); Point point2 = new Point(1, 0); Point point3 = new Point(1, 1); LineString lineString = new LineString(); lineString.segments.add(new LineSegment(point1, point2)); lineString.segments.add(new LineS...
public boolean submitProcessingErrors(Message message) { return submitProcessingErrorsInternal(message, message.processingErrors()); }
@Test public void submitProcessingErrors_nothingSubmittedAndMessageNotFilteredOut_ifSubmissionDisabledAndDuplicatesAreKept() throws Exception { // given final Message msg = Mockito.mock(Message.class); when(msg.getMessageId()).thenReturn("msg-x"); when(msg.supportsFailureHandling())....
public static Key of(String key, ApplicationId appId) { return new StringKey(key, appId); }
@Test public void longKeyCompare() { Key longKey1 = Key.of(LONG_KEY_1, NetTestTools.APP_ID); Key copyOfLongKey1 = Key.of(LONG_KEY_1, NetTestTools.APP_ID); Key longKey2 = Key.of(LONG_KEY_2, NetTestTools.APP_ID); Key copyOfLongKey2 = Key.of(LONG_KEY_2, NetTestTools.APP_ID); Key...
public static byte[] compress(String urlString) throws MalformedURLException { byte[] compressedBytes = null; if (urlString != null) { // Figure the compressed bytes can't be longer than the original string. byte[] byteBuffer = new byte[urlString.length()]; int byteBu...
@Test public void testCompressWithDotCoTLD() throws MalformedURLException { String testURL = "http://google.co"; byte[] expectedBytes = {0x02, 'g', 'o', 'o', 'g', 'l', 'e', '.', 'c', 'o'}; String hexBytes = bytesToHex(UrlBeaconUrlCompressor.compress(testURL)); assertTrue(Arrays.equal...
@Override public ConfigDef config() { return CONFIG_DEF; }
@Test public void testConfig() { TopicNameMatches<SourceRecord> predicate = new TopicNameMatches<>(); predicate.config().validate(Collections.singletonMap("pattern", "my-prefix-.*")); List<ConfigValue> configs = predicate.config().validate(Collections.singletonMap("pattern", "*")); ...
@Override public String service() { // MethodDescriptor.getServiceName() is not in our floor version: gRPC 1.2 return GrpcParser.service(methodDescriptor.getFullMethodName()); }
@Test void service() { assertThat(request.service()).isEqualTo("helloworld.Greeter"); }
@VisibleForTesting public ProcessContinuation run( RestrictionTracker<OffsetRange, Long> tracker, OutputReceiver<PartitionRecord> receiver, ManualWatermarkEstimator<Instant> watermarkEstimator, InitialPipelineState initialPipelineState) throws Exception { LOG.debug("DNP: Watermark: "...
@Test public void testDoNotUpdateWatermarkLessThan10s() throws Exception { // We update watermark every 2 iterations only if it's been more than 10s since the last update. OffsetRange offsetRange = new OffsetRange(2, Long.MAX_VALUE); when(tracker.currentRestriction()).thenReturn(offsetRange); when(tra...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeNestedMapNoOverwrite() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomergemap': {'type': 'MAP', 'source': 'SYSTEM', 'value': {'tomerge1': {'type': 'STRING','value': 'hello', 'meta': {'source': 'DEFINITION'}}}}}"); ...
@SuppressWarnings("unchecked") public static <T> T[] distinct(T[] array) { if (isEmpty(array)) { return array; } final Set<T> set = new LinkedHashSet<>(array.length, 1); Collections.addAll(set, array); return toArray(set, (Class<T>) getComponentType(array)); }
@Test public void distinctTest() { String[] array = {"aa", "bb", "cc", "dd", "bb", "dd"}; String[] distinct = ArrayUtil.distinct(array); assertArrayEquals(new String[]{"aa", "bb", "cc", "dd"}, distinct); }
public static String generateRandomAlphanumericPassword(int length) { char[][] pairs = {{'a', 'z'}, {'A', 'Z'}, {'0', '9'}}; RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder() .usingRandom(LazySecureRandom.INSTANCE::nextInt) .withinRange(pairs) ...
@Test public void testGenerateRandomAlphanumericPassword20() { assertThat(JOrphanUtils.generateRandomAlphanumericPassword(20), Matchers.matchesPattern("[A-Za-z0-9]{20}")); }
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldReturnedTimeWindowedSerdeForNonSessionWindowed() { // When: final Serde<Windowed<GenericKey>> result = factory .create(format, TIMED_WND, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.empty()); // Then: assertThat(result, is(ins...
public static byte[] checkPassword(String passwdString) { if (Strings.isNullOrEmpty(passwdString)) { return EMPTY_PASSWORD; } byte[] passwd; passwdString = passwdString.toUpperCase(); passwd = passwdString.getBytes(StandardCharsets.UTF_8); if (passwd.length !...
@Test(expected = ErrorReportException.class) public void testCheckPasswdFail2() { Assert.assertNotNull(MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32")); MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC3H"); Assert.fail("No exception throws"); ...
@Override public boolean canDeserialize(String topic, Target type) { return topic.equals(TOPIC); }
@Test void canOnlyDeserializeConsumerOffsetsTopic() { var serde = new ConsumerOffsetsSerde(); assertThat(serde.canDeserialize(ConsumerOffsetsSerde.TOPIC, Serde.Target.KEY)).isTrue(); assertThat(serde.canDeserialize(ConsumerOffsetsSerde.TOPIC, Serde.Target.VALUE)).isTrue(); assertThat(serde.canDeserial...
@Override public TransactionRuleConfiguration build() { return new TransactionRuleConfiguration(TransactionType.LOCAL.name(), null, new Properties()); }
@Test void assertBuild() { TransactionRuleConfiguration actual = new DefaultTransactionRuleConfigurationBuilder().build(); assertThat(actual.getDefaultType(), is(TransactionType.LOCAL.name())); assertNull(actual.getProviderType()); assertThat(actual.getProps(), is(new Properties()));...
public static void validateTableName(TableConfig tableConfig) { String tableName = tableConfig.getTableName(); int dotCount = StringUtils.countMatches(tableName, '.'); if (dotCount > 1) { throw new IllegalStateException("Table name: '" + tableName + "' containing more than one '.' is not allowed"); ...
@Test public void testTableName() { String[] malformedTableName = {"test.test.table", "test table"}; for (int i = 0; i < 2; i++) { String tableName = malformedTableName[i]; TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName(tableName).build(); try { Tabl...
public static void batchSetInstanceIdIfEmpty(List<Instance> instances, String groupedServiceName) { if (null != instances) { for (Instance instance : instances) { setInstanceIdIfEmpty(instance, groupedServiceName); } } }
@Test void testBatchSetInstanceIdIfEmpty() { final List<Instance> instances = new ArrayList<>(); Instance instance1 = new Instance(); instance1.setServiceName("test"); Instance instance2 = new Instance(); instance2.setServiceName("test"); Instance instance3 = new Inst...
@Bean @ConfigurationProperties(prefix = "shenyu.sync.nacos") public NacosConfig nacosConfig() { return new NacosConfig(); }
@Test public void nacosConfigTest() { assertNotNull(nacosConfig); }
public void deleteRole(String role, String userName) { rolePersistService.deleteRole(role, userName); }
@Test void deleteRole() { try { nacosRoleService.deleteRole("role-admin"); } catch (Exception e) { assertNull(e); } }