focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean handleResult(int returncode, GoPublisher goPublisher) { if (returncode == HttpURLConnection.HTTP_NOT_FOUND) { deleteQuietly(checksumFile); goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR, "[WARN] The md5checksum property file was not found on the serv...
@Test public void shouldHandleResultIfHttpCodeSaysFileNotFound() { StubGoPublisher goPublisher = new StubGoPublisher(); assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_NOT_FOUND, goPublisher), is(true)); assertThat(goPublisher.getMessage(), containsString(String.format("[W...
public static Set<String> extractUniquePrefixes(final Iterator<String> iterator, final String delimiter) { Set<String> uniquePrefixes = new HashSet<>(); try{ iterator.forEachRemaining(element -> { String prefix = element.substring(0, element.indexOf(delimiter)); ...
@Test public void testExtractUniquePrefixes() { Iterator<String> iterator = List.of("backendA.circuitBreaker.test1", "backendA.circuitBreaker.test2", "backendB.circuitBreaker.test3").iterator(); Set<String> prefixes = StringParseUtil.extractUniquePrefixes(iterator, "."); Assertions.assertT...
@Override public Network network() { return network; }
@Test public void getNetwork() { AddressParser parser = AddressParser.getDefault(); Network mainNet = parser.parseAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL").network(); assertEquals(MAINNET, mainNet); Network testNet = parser.parseAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv").netwo...
public static boolean isPrimitiveNumber(Class clazz) { return clazz.isPrimitive() && !clazz.equals(boolean.class); }
@Test public void testIsPrimitiveNumber() { assertTrue(FluxBuilder.isPrimitiveNumber(int.class)); assertFalse(FluxBuilder.isPrimitiveNumber(boolean.class)); assertFalse(FluxBuilder.isPrimitiveNumber(String.class)); }
public void write(final ConsumerRecord<byte[], byte[]> record) throws IOException { if (!writable) { throw new IOException("Write permission denied."); } final File dirty = dirty(file); final File tmp = tmp(file); // first write to the dirty copy appendRecordToFile(record, dirty, filesyste...
@Test public void shouldWriteRecordWithNewLineCharacterInCommand() throws IOException { // Given final String commandId = buildKey("stream1"); final String command = "{\"statement\":\"CREATE STREAM stream1 (id INT, f\\n1 INT) WITH (kafka_topic='topic1')\"}"; // When replayFile.write(newSt...
@Override public List<Class<? extends Event>> subscribeTypes() { List<Class<? extends Event>> result = new LinkedList<>(); result.add(MetadataEvent.InstanceMetadataEvent.class); result.add(MetadataEvent.ServiceMetadataEvent.class); result.add(ClientEvent.ClientDisconnectEvent.class);...
@Test void testSubscribeTypes() { List<Class<? extends Event>> classes = namingMetadataManager.subscribeTypes(); assertEquals(3, classes.size()); }
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor executor, TokensAndUrlAuthData authData, SocialActivityContainerResource resource) throws Exception { if (resource == null) { // Nothing to import return ImportResult.OK; } monitor.deb...
@Test public void testImportSingleActivity() throws Exception { String postContent = "activityContent"; SocialActivityModel activity = new SocialActivityModel( "activityId", Instant.now(), SocialActivityType.POST, Collections.emptyList(), new...
@Override public long transferTo(long position, long count, WritableByteChannel target) throws IOException { checkNotNull(target); Util.checkNotNegative(position, "position"); Util.checkNotNegative(count, "count"); checkOpen(); checkReadable(); long transferred = 0; // will definitely either ...
@Test public void testTransferTo() throws IOException { RegularFile file = regularFile(10); FileChannel channel = channel(file, READ); ByteBufferChannel writeChannel = new ByteBufferChannel(buffer("1234567890")); assertEquals(10, channel.transferTo(0, 100, writeChannel)); assertEquals(0, channel....
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testHsOverallPb_NoPb() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Floor 5 time: <col=ff0000>3:26</col> (new personal best)<br>Overall time: <col=ff0000>9:17</col>. Personal best: 9:15<br>", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); verify(configManager)...
public String getColonSeparatedKey() { StringBuilder serviceNameBuilder = new StringBuilder(); serviceNameBuilder.append(this.getServiceInterface()); append(serviceNameBuilder, VERSION_KEY, false); append(serviceNameBuilder, GROUP_KEY, false); return serviceNameBuilder.toString()...
@Test void testGetColonSeparatedKey() { URL url1 = URL.valueOf( "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:group", u...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = NullPointerException.class, description = "hard fails with NPE on missing criteria parameter") public void failsOnMissingBatchFinderMethodBatchParamParameter() { @RestLiCollection(name = "batchFinderWithMissingBatchParam") class LocalClass extends CollectionResourceTemplate<Long, E...
@Override public Optional<Track<T>> clean(Track<T> track) { TreeSet<Point<T>> points = new TreeSet<>(track.points()); Optional<Point<T>> firstNonNull = firstPointWithAltitude(points); if (!firstNonNull.isPresent()) { return Optional.empty(); } SortedSet<Point<T...
@Test public void testFillingFinalAltitudes() { Track<NoRawData> testTrack = trackWithNoFinalAltitudes(); Track<NoRawData> cleanedTrack = (new FillMissingAltitudes<NoRawData>()).clean(testTrack).get(); ArrayList<Point<NoRawData>> points = new ArrayList<>(cleanedTrack.points()); asse...
public byte exitStatus() { return exitStatus.exitStatus(); }
@Test void with_passed_scenarios() { Runtime runtime = createRuntime(); bus.send(testCaseFinishedWithStatus(Status.PASSED)); assertThat(runtime.exitStatus(), is(equalTo((byte) 0x0))); }
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { String[] parts = remaining.split(":"); if (parts.length < 3) { throw new IllegalArgumentException( "Google PubSub Lite Endpoint format \"proj...
@Test public void testCreateEndpointMissingFields() { String uri = "google-pubsub-lite:123456789012:europe-west3"; String remaining = "123456789012:europe-west3"; Map<String, Object> parameters = new HashMap<>(); Exception exception = assertThrows(IllegalArgumentException.class, ...
static boolean isRealTask(Task task) { return task.getSeq() >= 0 && StepHelper.retrieveStepStatus(task.getOutputData()) != StepInstance.Status.NOT_CREATED; }
@Test public void testIsRealTask() { when(task.getTaskType()).thenReturn(Constants.MAESTRO_TASK_NAME); when(task.getSeq()).thenReturn(-1); Assert.assertFalse(TaskHelper.isRealTask(task)); when(task.getSeq()).thenReturn(1); when(task.getOutputData()) .thenReturn( Collections.sin...
public TaskInfo cancel() { taskStateMachine.cancel(); return getTaskInfo(); }
@Test public void testCancel() { SqlTask sqlTask = createInitialTask(); TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION, Optional.of(PLAN_FRAGMENT), ImmutableList.of(), createInitialEmptyOutputBuffers(PARTITIONED) .with...
@Override public void setNoMorePages() { PendingRead pendingRead; synchronized (this) { state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); noMorePages.set(true); pendingRead = this.pendingRead; this.pendingRead = null; log.info("Task %s:...
@Test public void testAddAfterNoMorePages() { SpoolingOutputBuffer buffer = createSpoolingOutputBuffer(); for (int i = 0; i < 2; i++) { addPage(buffer, createPage(i)); } compareTotalBuffered(buffer, 2); buffer.setNoMorePages(); // should not be adde...
@Override public void reset() { resetCount++; super.reset(); initEvaluatorMap(); initCollisionMaps(); root.recursiveReset(); resetTurboFilterList(); cancelScheduledTasks(); fireOnReset(); resetListenersExceptResetResistant(); resetStatu...
@Test public void resetTest() { Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); Logger a = lc.getLogger("a"); Logger ab = lc.getLogger("a.b"); ab.setLevel(Level.WARN); root.setLevel(Level.INFO); lc.reset(); assertEquals(Level.DEBUG, root.getEffectiveLev...
public static DistCpOptions parse(String[] args) throws IllegalArgumentException { CommandLineParser parser = new CustomParser(); CommandLine command; try { command = parser.parse(cliOptions, args, true); } catch (ParseException e) { throw new IllegalArgumentException("Unable to pars...
@Test public void testLogPath() { DistCpOptions options = OptionsParser.parse(new String[] { "hdfs://localhost:8020/source/first", "hdfs://localhost:8020/target/"}); Assert.assertNull(options.getLogPath()); options = OptionsParser.parse(new String[] { "-log", "hdfs://local...
public static boolean isFileExtractable(String path) { String type = getExtension(path); return isZip(type) || isTar(type) || isRar(type) || isGzippedTar(type) || is7zip(type) || isBzippedTar(type) || isXzippedTar(type) || isLzippedTar(type) || is...
@Test public void isFileExtractableTest() throws Exception { // extension in code. So, it return true assertTrue(CompressedHelper.isFileExtractable("/test/test.zip")); assertTrue(CompressedHelper.isFileExtractable("/test/test.rar")); assertTrue(CompressedHelper.isFileExtractable("/test/test.tar")); ...
public static Builder builder() { return new Builder(); }
@Test void with_parse_error() { Runtime runtime = Runtime.builder() .withFeatureSupplier(() -> { throw new FeatureParserException("oops"); }) .build(); assertThrows(FeatureParserException.class, runtime::run); }
public Option<Dataset<Row>> loadAsDataset(SparkSession spark, List<CloudObjectMetadata> cloudObjectMetadata, String fileFormat, Option<SchemaProvider> schemaProviderOption, int numPartitions) { if (LOG.isDebugEnabled()) { LOG.debug("Extracted distinct files " + clou...
@Test public void partitionKeyNotPresentInPath() { List<CloudObjectMetadata> input = Collections.singletonList(new CloudObjectMetadata("src/test/resources/data/partitioned/country=US/state=CA/data.json", 1)); TypedProperties properties = new TypedProperties(); properties.put("hoodie.deltastreamer.source.c...
static String formatRequestBody(String scope) throws IOException { try { StringBuilder requestParameters = new StringBuilder(); requestParameters.append("grant_type=client_credentials"); if (scope != null && !scope.trim().isEmpty()) { scope = scope.trim(); ...
@Test public void testFormatRequestBodyWithEscaped() throws IOException { String questionMark = "%3F"; String exclamationMark = "%21"; String expected = String.format("grant_type=client_credentials&scope=earth+is+great%s", exclamationMark); String actual = HttpAccessTokenRetriever.f...
public AuthenticationRequest startAuthenticationProcess(HttpServletRequest httpRequest) throws ComponentInitializationException, MessageDecodingException, SamlValidationException, SharedServiceClientException, DienstencatalogusException, SamlSessionException { BaseHttpServletRequestXMLMessageDecoder decoder = d...
@Test //entrance public void parseInvalidAuthenticationRequestTest() { String samlRequest = readXMLFile(authnRequestEntranceInvalidFile); String decodeSAMLRequest = encodeAuthnRequest(samlRequest); httpServletRequestMock.setParameter("SAMLRequest", decodeSAMLRequest); Exception exce...
public void init() { if (isInitiated.compareAndSet(false, true)) { Assert.notNull(applicationContext, () -> "Application must not be null"); Map<String, ReadinessCheckCallback> beansOfType = applicationContext .getBeansOfType(ReadinessCheckCallback.class); ...
@Test public void applicationContextNull() { assertThatThrownBy(() -> new ReadinessCheckCallbackProcessor().init()).hasMessage("Application must not be null"); }
@Override public void registerStore(final StateStore store, final StateRestoreCallback stateRestoreCallback, final CommitCallback commitCallback) { final String storeName = store.name(); // TODO (KAFKA-12887): we should not trigger user's ...
@Test public void shouldThrowIllegalArgumentExceptionIfStoreNameIsSameAsCheckpointFileName() { final ProcessorStateManager stateManager = getStateManager(Task.TaskType.ACTIVE); assertThrows(IllegalArgumentException.class, () -> stateManager.registerStore(new MockKeyValueStore(CHECKPOINT...
static String getPassword(Configuration conf, String alias) { String password = null; try { char[] passchars = conf.getPassword(alias); if (passchars != null) { password = new String(passchars); } } catch (IOException ioe) { LOG.warn("Setting password to null since IOExce...
@Test public void testGetPassword() throws Exception { File testDir = GenericTestUtils.getTestDir(); Configuration conf = new Configuration(); final Path jksPath = new Path(testDir.toString(), "test.jks"); final String ourUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri(); ...
public static double shuffleCompressionRatio( SparkSession spark, FileFormat outputFileFormat, String outputCodec) { if (outputFileFormat == FileFormat.ORC || outputFileFormat == FileFormat.PARQUET) { return columnarCompression(shuffleCodec(spark), outputCodec); } else if (outputFileFormat == FileFo...
@Test public void testCodecNameNormalization() { configureShuffle("zStD", true); double ratio = shuffleCompressionRatio(PARQUET, "ZstD"); assertThat(ratio).isEqualTo(2.0); }
@VisibleForTesting static Estimate calculateDataSizeForPartitioningKey( HiveColumnHandle column, Type type, List<HivePartition> partitions, Map<String, PartitionStatistics> statistics, double averageRowsPerPartition) { if (!hasDataSize(type)) {...
@Test public void testCalculateDataSizeForPartitioningKey() { assertEquals( calculateDataSizeForPartitioningKey( PARTITION_COLUMN_2, BIGINT, ImmutableList.of(partition("p1=string1/p2=1234")), ...
public void createNewCodeDefinition(DbSession dbSession, String projectUuid, String mainBranchUuid, String defaultBranchName, String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) { boolean isCommunityEdition = editionProvider.get().filter(EditionProvider.Edition.COMMUNITY::equals).isPresent()...
@Test public void createNewCodeDefinition_throw_IAE_if_type_is_not_allowed() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH_UUID, MAIN_BRANCH, SPECIFIC_ANALYSIS.name(), null)) .isInstanceOf(IllegalArgumentException.class) .hasMes...
@Override public final Map<PCollection<?>, ReplacementOutput> mapOutputs( Map<TupleTag<?>, PCollection<?>> outputs, OutputT newOutput) { return ReplacementOutputs.singleton(outputs, newOutput); }
@Test public void testMapOutputsMultipleOriginalOutputsFails() { PCollection<Integer> input = pipeline.apply(Create.of(1, 2, 3)); PCollection<Integer> output = input.apply("Map", MapElements.via(fn)); PCollection<Integer> reappliedOutput = input.apply("ReMap", MapElements.via(fn)); thrown.expect(Illeg...
public static Builder builder() { return new Builder(); }
@Test public void testEqualsAndHashCode() { CommonUpstream commonUpstream = new CommonUpstream(); commonUpstream.setProtocol("protocol"); commonUpstream.setUpstreamHost("host"); commonUpstream.setUpstreamUrl("url"); commonUpstream.setStatus(true); commonUpstream.setTi...
@Override public boolean setReadOnly() { throw new UnsupportedOperationException("Not implemented"); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testSetReadOnly() { fs.getFile("nonsuch.txt").setReadOnly(); }
public static String formatSql(final AstNode root) { final StringBuilder builder = new StringBuilder(); new Formatter(builder).process(root, 0); return StringUtils.stripEnd(builder.toString(), "\n"); }
@Test public void shouldFormatSelectStarCorrectlyWithJoin() { final String statementString = "CREATE STREAM S AS SELECT address.*, itemid.* " + "FROM address INNER JOIN itemid ON address.address = itemid.address->address;"; final Statement statement = parseSingle(statementString); assertThat(SqlFo...
public static String getByFilename(String filename) { String extension = FilenameUtils.getExtension(filename); String mime = null; if (!isNullOrEmpty(extension)) { mime = MAP.get(extension.toLowerCase(Locale.ENGLISH)); } return mime != null ? mime : DEFAULT; }
@Test public void getByFilename_default_mime_type() { assertThat(MediaTypes.getByFilename("")).isEqualTo(MediaTypes.DEFAULT); assertThat(MediaTypes.getByFilename("unknown.extension")).isEqualTo(MediaTypes.DEFAULT); }
@SuppressWarnings("java:S2583") public static boolean verify(@NonNull JWKSet jwks, @NonNull JWSObject jws) { if (jwks == null) { throw new IllegalArgumentException("no JWKS provided to verify JWS"); } if (jwks.getKeys() == null || jwks.getKeys().isEmpty()) { return false; } var head...
@Test void verifyBadSignature() throws ParseException { var jws = toJws(ECKEY, "test").serialize(); jws = tamperSignature(jws); var in = JWSObject.parse(jws); // when & then assertFalse(JwsVerifier.verify(JWKS, in)); }
@Override public String getOtp() throws OtpInfoException { checkSecret(); try { OTP otp = HOTP.generateOTP(getSecret(), getAlgorithm(true), getDigits(), getCounter()); return otp.toString(); } catch (NoSuchAlgorithmException | InvalidKeyException e) { thr...
@Test public void testHotpInfoOtp() throws OtpInfoException { for (int i = 0; i < HOTPTest.VECTORS.length; i++) { HotpInfo info = new HotpInfo(HOTPTest.SECRET, OtpInfo.DEFAULT_ALGORITHM, OtpInfo.DEFAULT_DIGITS, i); assertEquals(info.getOtp(), HOTPTest.VECTORS[i]); } }
@Override public void open() throws Exception { if (useSplittableTimers() && areSplittableTimersConfigured() && getTimeServiceManager().isPresent()) { this.watermarkProcessor = new MailboxWatermarkProcessor( output, ...
@Test void testStateDoesNotInterfere() throws Exception { try (KeyedOneInputStreamOperatorTestHarness<Integer, Tuple2<Integer, String>, String> testHarness = createTestHarness()) { testHarness.open(); testHarness.processElement(new Tuple2<>(0, "SET_STATE:HELLO"), 0);...
@Override public void removeInstance(String namespaceId, String serviceName, Instance instance) { boolean ephemeral = instance.isEphemeral(); String clientId = IpPortBasedClient.getClientId(instance.toInetAddr(), ephemeral); if (!clientManager.contains(clientId)) { Loggers.SRV_LO...
@Test void testRemoveInstance() { when(clientManager.contains(Mockito.anyString())).thenReturn(true); instanceOperatorClient.removeInstance("A", "B", new Instance()); Mockito.verify(clientOperationService).deregisterInstance(Mockito.any(), Mockito.any(), Mockito.anyString()...
public static String underlineToCamel(String param) { return formatCamel(param, UNDERLINE); }
@Test void underlineToCamel() { assertThat(StringFormatUtils.underlineToCamel(null)).isEqualTo(""); assertThat(StringFormatUtils.underlineToCamel(" ")).isEqualTo(""); assertThat(StringFormatUtils.underlineToCamel("abc_def_gh")).isEqualTo("abcDefGh"); }
void addAll(ReplicaMap other) { map.putAll(other.map); }
@Test public void testAddAll() { ReplicaMap temReplicaMap = new ReplicaMap(); Block tmpBlock = new Block(5678, 5678, 5678); temReplicaMap.add(bpid, new FinalizedReplica(tmpBlock, null, null)); map.addAll(temReplicaMap); assertNull(map.get(bpid, 1234)); assertNotNull(map.get(bpid, 5678)); }
public static JobId toJobID(String jid) { return TypeConverter.toYarn(JobID.forName(jid)); }
@Test @Timeout(120000) public void testToJobID() { JobId jid = MRApps.toJobID("job_1_1"); assertEquals(1, jid.getAppId().getClusterTimestamp()); assertEquals(1, jid.getAppId().getId()); assertEquals(1, jid.getId()); // tests against some proto.id and not a job.id field }
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) { List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext() ? createShardingConditionsWithInsertValues(sqlStatementContext, params) ...
@Test void assertCreateShardingConditionsInsertStatementWithGeneratedKeyContextAndTableRule() { GeneratedKeyContext generatedKeyContext = mock(GeneratedKeyContext.class); when(insertStatementContext.getGeneratedKeyContext()).thenReturn(Optional.of(generatedKeyContext)); when(generatedKeyCont...
public static Object convertValue(String className, Object cleanValue, ClassLoader classLoader) { // "null" string is converted to null cleanValue = "null".equals(cleanValue) ? null : cleanValue; if (!isPrimitive(className) && cleanValue == null) { return null; } Cl...
@Test public void convertValueFailPrimitiveNullTest() { assertThatThrownBy(() -> convertValue("int", null, classLoader)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(" is not a String or an instance of"); }
public long scan( final UnsafeBuffer termBuffer, final long rebuildPosition, final long hwmPosition, final long nowNs, final int termLengthMask, final int positionBitsToShift, final int initialTermId) { boolean lossFound = false; int rebuildOff...
@Test void shouldHandleNonZeroInitialTermOffset() { lossDetector = getLossHandlerWithLongRetry(); final long rebuildPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L); final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 5L); insertDataFrame(offset...
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), ...
@Test @Category(NeedsRunner.class) public void testPartitionWithSideInputs() { PCollectionView<Integer> gradesView = pipeline.apply("grades", Create.of(50)).apply(View.asSingleton()); Create.Values<Integer> studentsPercentage = Create.of(5, 45, 90, 29, 55, 65); PCollectionList<Integer> student...
public static List<UpdateRequirement> forUpdateTable( TableMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid table metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Bui...
@Test public void setCurrentSchema() { int schemaId = 3; when(metadata.currentSchemaId()).thenReturn(schemaId); List<UpdateRequirement> requirements = UpdateRequirements.forUpdateTable( metadata, ImmutableList.of( new MetadataUpdate.SetCurrentSchema(schemaId...
@Override public void onNotificationOpened() { }
@Test public void onNotificationOpened_neverClearAllNotifications() throws Exception { createUUT().onNotificationOpened(); verify(mNotificationManager, never()).cancelAll(); }
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testParameterConversionRemoveInternalMode() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'optional': {'type': 'STRING', 'value': 'hello', 'internal_mode': 'OPTIONAL'}}"); Map<String, ParamDefinition> convertedParams = Param...
@Override public Set<DeviceId> getNetconfDevices() { return netconfDeviceMap.keySet(); }
@Test public void testGetNetconfDevices() { Set<DeviceId> devices = new HashSet<>(); devices.add(deviceId1); devices.add(deviceId2); assertTrue("Incorrect devices", ctrl.getNetconfDevices().containsAll(devices)); }
public static String getLogicIndexName(final String actualIndexName, final String actualTableName) { String indexNameSuffix = UNDERLINE + actualTableName; return actualIndexName.endsWith(indexNameSuffix) ? actualIndexName.substring(0, actualIndexName.lastIndexOf(indexNameSuffix)) : actualIndexName; ...
@Test void assertGetLogicIndexNameWithMultiIndexNameSuffix() { assertThat(IndexMetaDataUtils.getLogicIndexName("order_t_order_index_t_order", "t_order"), is("order_t_order_index")); }
@Override public String getName() { return "DroneCI"; }
@Test public void getName() { assertThat(underTest.getName()).isEqualTo("DroneCI"); }
@Override public PipelineChannel newInstance(final int importerBatchSize, final PipelineChannelAckCallback ackCallback) { int queueSize = this.queueSize / importerBatchSize; return new MemoryPipelineChannel(queueSize, ackCallback); }
@Test void assertInitWithNonZeroBlockQueueSize() throws Exception { PipelineChannelCreator creator = TypedSPILoader.getService(PipelineChannelCreator.class, "MEMORY", PropertiesBuilder.build(new Property("block-queue-size", "2000"))); assertThat(Plugins.getMemberAccessor().get(MemoryPipelineChannelC...
static <ID, T> TaskExecutors<ID, T> batchExecutors(final String name, int workerCount, final TaskProcessor<T> processor, final AcceptorExecutor<ID, T> acce...
@Test public void testBatchSuccessfulProcessing() throws Exception { taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor); taskBatchQueue.add(asList(successfulTaskHolder(1), successfulTaskHolder(2))); processor.expectSuccesses(2); }
@Override public <T extends MigrationStep> MigrationStepRegistry add(long migrationNumber, String description, Class<T> stepClass) { validate(migrationNumber); requireNonNull(description, "description can't be null"); checkArgument(!description.isEmpty(), "description can't be empty"); requireNonNull(...
@Test public void add_fails_with_ISE_when_called_twice_with_same_migration_number() { underTest.add(12, "dsd", MigrationStep.class); assertThatThrownBy(() -> underTest.add(12, "dfsdf", MigrationStep.class)) .isInstanceOf(IllegalStateException.class) .hasMessage("A migration is already registered ...
public static Builder builder() { return new Builder(); }
@Test void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = Feign.builder().decoder((response, type) -> { throw new IOException("timeout"); }) .target(TestInterface.class, "http://localhost:" + server.getPort()); try { ...
@Override public void onPluginChanged(final List<PluginData> pluginDataList, final DataEventTypeEnum eventType) { WebsocketData<PluginData> websocketData = new WebsocketData<>(ConfigGroupEnum.PLUGIN.name(), eventType.name(), pluginDataList); WebsocketCollector.send(GsonUtils.getInsta...
@Test public void testOnPluginChanged() { String message = "{\"groupType\":\"PLUGIN\",\"eventType\":\"UPDATE\",\"data\":[{\"id\":\"2\",\"name\":\"waf\"," + "\"config\":\"{\\\\\\\"model\\\\\\\":\\\\\\\"black\\\\\\\"}\",\"role\":\"1\",\"enabled\":true}]}"; MockedStatic.Verification ver...
public final void tag(I input, ScopedSpan span) { if (input == null) throw new NullPointerException("input == null"); if (span == null) throw new NullPointerException("span == null"); if (span.isNoop()) return; tag(span, input, span.context()); }
@Test void tag_customizer_withContext_doesntParseNoop() { tag.tag(input, context, NoopSpanCustomizer.INSTANCE); verifyNoMoreInteractions(parseValue); // parsing is lazy }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComChangeUserPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_CHANGE_USER, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
@Override public boolean isGenerateSQLToken(final SQLStatementContext sqlStatementContext) { return sqlStatementContext instanceof InsertStatementContext && ((InsertStatementContext) sqlStatementContext).containsInsertColumns(); }
@Test void assertIsNotGenerateSQLTokenWithoutInsertColumns() { assertFalse(new EncryptInsertDerivedColumnsTokenGenerator(mock(EncryptRule.class)).isGenerateSQLToken(mock(InsertStatementContext.class, RETURNS_DEEP_STUBS))); }
@Override public URL getResource(String name) { ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resource '{}'", name); for (ClassLoadingStrategy.Source classLoadingSource : loadingStrategy.getSources()) { URL url = null; ...
@Test void parentFirstGetExtensionsIndexExistsInParentAndDependencyAndPlugin() throws URISyntaxException, IOException { URL resource = parentLastPluginClassLoader.getResource(LegacyExtensionFinder.EXTENSIONS_RESOURCE); assertFirstLine("plugin", resource); }
public static Builder builder() { return new Builder(); }
@Test public void testJsonSerializeDeserialize() { // default key created by S3Options.SSECustomerKeyFactory SSECustomerKey emptyKey = SSECustomerKey.builder().build(); assertThat(jsonSerializeDeserialize(emptyKey)).isEqualToComparingFieldByField(emptyKey); SSECustomerKey key = SSECustomerKey.builder...
public static byte[] gzip(String content, String charset) throws UtilException { return gzip(StrUtil.bytes(content, charset)); }
@Test public void gzipTest() { final String data = "我是一个需要压缩的很长很长的字符串"; final byte[] bytes = StrUtil.utf8Bytes(data); final byte[] gzip = ZipUtil.gzip(bytes); //保证gzip长度正常 assertEquals(68, gzip.length); final byte[] unGzip = ZipUtil.unGzip(gzip); //保证正常还原 assertEquals(data, StrUtil.utf8Str(unGzip)); ...
@Override public void registerModified(Weapon weapon) { LOGGER.info("Registering {} for modify in context.", weapon.getName()); register(weapon, UnitActions.MODIFY.getActionValue()); }
@Test void shouldSaveModifiedStudentWithoutWritingToDb() { armsDealer.registerModified(weapon1); armsDealer.registerModified(weapon2); assertEquals(2, context.get(UnitActions.MODIFY.getActionValue()).size()); verifyNoMoreInteractions(weaponDatabase); }
@Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { if (boolean.class == type) { return resultSet.getBoolean(columnIndex); } if (byte.class == type) { return resultSet.getByte(columnIndex); } if (short.cla...
@Test void assertGetValueByTime() throws SQLException { ResultSet resultSet = mock(ResultSet.class); when(resultSet.getTime(1)).thenReturn(new Time(0L)); assertThat(new JDBCStreamQueryResult(resultSet).getValue(1, Time.class), is(new Time(0L))); }
public byte[] data() { if (buf.hasArray()) { byte[] array = buf.array(); int offset = buf.arrayOffset(); if (offset == 0 && array.length == size) { // If the backing array is exactly what we need, return it without copy. return array; ...
@Test public void testDataArrayExtendsFurther() { byte[] data = new byte[]{10, 11, 12}; ByteBuffer buffer = ByteBuffer.wrap(data, 0, 2).slice(); Msg msg = new Msg(buffer); assertThat(msg.data(), is(new byte[]{10, 11})); }
@Override public int getColumnCount() { return _columnNamesArray.size(); }
@Test public void testGetColumnCount() { // Run the test final int result = _resultTableResultSetUnderTest.getColumnCount(); // Verify the results assertEquals(2, result); }
@Override public String mask(final Object plainValue) { String result = null == plainValue ? null : String.valueOf(plainValue); if (Strings.isNullOrEmpty(result)) { return result; } char[] chars = result.toCharArray(); for (int i = 0; i < chars.length; i++) { ...
@Test void assertMask() { GenericTableRandomReplaceAlgorithm maskAlgorithm = (GenericTableRandomReplaceAlgorithm) TypedSPILoader.getService(MaskAlgorithm.class, "GENERIC_TABLE_RANDOM_REPLACE", PropertiesBuilder.build(new Property("uppercase-letter-codes", "A,B,C,D"), ...
public static boolean isIpAddress(String address) { try { getAddressMatcher(address); return true; } catch (InvalidAddressException e) { return false; } }
@Test public void testIsIpAddress() { assertTrue(AddressUtil.isIpAddress("10.10.10.10")); assertTrue(AddressUtil.isIpAddress("111.12-66.123.*")); assertTrue(AddressUtil.isIpAddress("111-255.12-66.123.*")); assertTrue(AddressUtil.isIpAddress("255.255.123.*")); assertTrue(Addre...
@SuppressWarnings("unchecked") @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { if (!(statement.getStatement() instanceof CreateSource) && !(statement.getStatement() instanceof CreateAsSelect)) { return statement; } t...
@Test public void shouldThrowIfCtasValueFormatDoesnotSupportInference() { // Given: givenFormatsAndProps(null, "kafka", ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42))); givenDDLSchemaAndFormats(LOGICAL_SCHEMA, "kafka", "delimited", SerdeFeature.UNWRAP_SINGLES, SerdeFeature.UNWR...
@SuppressWarnings("unchecked") public void replaceAllInt(final IntObjectToObjectFunction<? super V, ? extends V> function) { requireNonNull(function); final int[] keys = this.keys; final Object[] values = this.values; @DoNotSub final int length = values.length; @DoNotSub ...
@Test void replaceAllIntThrowsNullPointerExceptionIfFunctionIsNull() { assertThrowsExactly(NullPointerException.class, () -> cache.replaceAllInt(null)); }
@Override public boolean isFinished() { return finishing && outputPage == null; }
@Test(dataProvider = "hashEnabledValues", expectedExceptions = ExceededMemoryLimitException.class, expectedExceptionsMessageRegExp = "Query exceeded per-node user memory limit of.*") public void testMemoryLimit(boolean hashEnabled) { DriverContext driverContext = createTaskContext(executor, scheduledExe...
@Override public ScheduleResult schedule() { List<RemoteTask> newTasks = IntStream.range(0, partitionToNode.size()) .mapToObj(partition -> taskScheduler.scheduleTask(partitionToNode.get(partition), partition)) .filter(Optional::isPresent) .map(Optional::ge...
@Test public void testMultipleNodes() { FixedCountScheduler nodeScheduler = new FixedCountScheduler( (node, partition) -> Optional.of(taskFactory.createTableScanTask( new TaskId("test", 1, 0, 1, 0), node, ImmutableList.of(), ...
public static UVariableDecl create( CharSequence identifier, UExpression type, @Nullable UExpression initializer) { return new AutoValue_UVariableDecl(StringName.of(identifier), type, initializer); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(UVariableDecl.create("foo", UClassIdent.create("java.lang.String"), null)) .addEqualityGroup( UVariableDecl.create( "foo", UClassIdent.create("java.lang.String"), ULiteral.stringLit("bar"))) .ad...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStart, final Range<Instant> windowEnd, final Optional<Position> position ) { try { final ReadOnlySessionStore<GenericKey, GenericRow> store = sta...
@Test public void shouldFetchWithCorrectParams() { // When: table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS); // Then: verify(cacheBypassFetcher).fetch(sessionStore, A_KEY); }
public String readFile(final String inputFile) throws IOException { Path inputFilePath = Paths.get(inputFile); return Files.readString(Paths.get(inputFilePath.toString())); }
@Test public void testReadFile() throws IOException { String content = "x y z"; Path path = Paths.get(temporaryDirectory.getPath(), FOOBAR); File letters = path.toFile(); Files.write(letters.toPath(), Collections.singletonList(content)); String result = fileUtil.readFile(le...
public static void setAttributeValue(Document document, String containerNodeName, String attributeName, String attributeValue) { asStream(document.getElementsByTagName(containerNodeName)) .map(Node::getAttributes) .map(attributes -> attributes.getNamedItem(attributeName)) ...
@Test public void setAttributeValue() throws Exception { final String newValue = "NEW_VALUE"; Document document = DOMParserUtil.getDocument(XML); DOMParserUtil.setAttributeValue(document, MAIN_NODE, MAIN_ATTRIBUTE_NAME, newValue); Map<Node, String> retrieved = DOMParserUtil.getAttrib...
@Override public String getScheme() { return scheme; }
@Test public void testGetScheme() { // Tests s3 paths. assertEquals("s3", S3ResourceId.fromUri("s3://my_bucket/tmp dir/").getScheme()); // Tests bucket with no ending '/'. assertEquals("s3", S3ResourceId.fromUri("s3://my_bucket").getScheme()); }
public static ByteBuf copyMedium(int value) { ByteBuf buf = buffer(3); buf.writeMedium(value); return buf; }
@Test public void testWrapSingleMedium() { ByteBuf buffer = copyMedium(42); assertEquals(3, buffer.capacity()); assertEquals(42, buffer.readMedium()); assertFalse(buffer.isReadable()); buffer.release(); }
public void sanitizeEnv(Map<String, String> environment, Path pwd, List<Path> appDirs, List<String> userLocalDirs, List<String> containerLogDirs, Map<Path, List<String>> resources, Path nmPrivateClasspathJarDir, Set<String> nmVars) throws IOException { // Based on discussion in YARN-7654, fo...
@Test public void testPrependDistcache() throws Exception { // Test is only relevant on Windows assumeWindows(); ContainerLaunchContext containerLaunchContext = recordFactory.newRecordInstance(ContainerLaunchContext.class); ApplicationId appId = ApplicationId.newInstance(0, 0); Applicat...
public static long currentTimeMillis() { // When an exception occurs in the Ticker mechanism, fall back. if (isFallback) { return System.currentTimeMillis(); } if (!isTickerAlive) { try { startTicker(); } catch (Exception e) { ...
@Test void testCurrentTimeMillis() { assertTrue(0 < TimeUtils.currentTimeMillis()); }
@Override public UnboundedReader<KV<byte[], byte[]>> createReader( PipelineOptions options, @Nullable SyntheticRecordsCheckpoint checkpoint) { if (checkpoint == null) { return new SyntheticUnboundedReader(this, this.startOffset); } else { return new SyntheticUnboundedReader(this, checkpoint...
@Test public void lastElementShouldBeInclusive() throws IOException { int endPosition = 2; checkpoint = new SyntheticRecordsCheckpoint(0); UnboundedSource.UnboundedReader<KV<byte[], byte[]>> reader = source.createReader(pipeline.getOptions(), checkpoint); reader.start(); reader.advance()...
public String getDomainObjectName() { if (stringHasValue(domainObjectName)) { return domainObjectName; } String finalDomainObjectName; if (stringHasValue(runtimeTableName)) { finalDomainObjectName = JavaBeansUtil.getCamelCaseString(runtimeTableName, true); ...
@Test void testNormalCaseWithPrefix() { FullyQualifiedTable fqt = new FullyQualifiedTable(null, "myschema", "sys_mytable", null, null, false, null, null, null, false, null, null); assertThat(fqt.getDomainObjectName()).isEqualTo("SysMytable"); }
public IsJson(Matcher<? super ReadContext> jsonMatcher) { this.jsonMatcher = jsonMatcher; }
@Test public void shouldNotMatchInvalidJson() { assertThat(INVALID_JSON, not(isJson())); assertThat(new Object(), not(isJson())); assertThat(new Object[]{}, not(isJson())); assertThat("hi there", not(isJson())); assertThat(new Integer(42), not(isJson())); assertThat(B...
public DropTypeCommand create(final DropType statement) { final String typeName = statement.getTypeName(); final boolean ifExists = statement.getIfExists(); if (!ifExists && !metaStore.resolveType(typeName).isPresent()) { throw new KsqlException("Type " + typeName + " does not exist."); } re...
@Test public void shouldNotFailCreateTypeIfTypeDoesNotExistAndIfExistsSet () { // Given: final DropType dropType = new DropType(Optional.empty(), NOT_EXISTING_TYPE, true); // When: final DropTypeCommand cmd = factory.create(dropType); // Then: assertThat(cmd.getTypeName(), equalTo(NOT_EXISTI...
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testLowerCase() { run("lower-case.feature"); }
@Override public String rpcType() { return RpcTypeEnum.DUBBO.getName(); }
@Test public void testRpcType() { assertEquals(RpcTypeEnum.DUBBO.getName(), shenyuClientRegisterDubboService.rpcType()); }
public static LockTime of(long rawValue) { if (rawValue < 0) throw new IllegalArgumentException("illegal negative lock time: " + rawValue); return rawValue < LockTime.THRESHOLD ? new HeightLock(rawValue) : new TimeLock(rawValue); }
@Test(expected = IllegalArgumentException.class) @Parameters(method = "invalidValueVectors") public void invalidValues(long value) { LockTime lockTime = LockTime.of(value); }
@ApiOperation(value = "List Deployments", tags = { "Deployment" }, nickname="listDeployments") @ApiImplicitParams({ @ApiImplicitParam(name = "name", dataType = "string", value = "Only return deployments with the given name.", paramType = "query"), @ApiImplicitParam(name = "nameLike", dataTyp...
@Test public void testGetDeployments() throws Exception { try { // Alter time to ensure different deployTimes Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DAY_OF_MONTH, -1); processEngineConfiguration.getClock().setCurrentTime(yesterday...
@SafeVarargs public static <E> Set<E> union(final Supplier<Set<E>> constructor, final Set<E>... set) { final Set<E> result = constructor.get(); for (final Set<E> s : set) { result.addAll(s); } return result; }
@Test public void testUnion() { final Set<String> oneSet = mkSet("a", "b", "c"); final Set<String> anotherSet = mkSet("c", "d", "e"); final Set<String> union = union(TreeSet::new, oneSet, anotherSet); assertEquals(mkSet("a", "b", "c", "d", "e"), union); assertEquals(TreeSet....
public static String sanitizeUri(String uri) { // use xxxxx as replacement as that works well with JMX also String sanitized = uri; if (uri != null) { sanitized = ALL_SECRETS.matcher(sanitized).replaceAll("$1=xxxxxx"); sanitized = USERINFO_PASSWORD.matcher(sanitized).repl...
@Test public void testSanitizeUriWithUserInfo() { String uri = "jt400://GEORGE:HARRISON@LIVERPOOL/QSYS.LIB/BEATLES.LIB/PENNYLANE.DTAQ"; String expected = "jt400://GEORGE:xxxxxx@LIVERPOOL/QSYS.LIB/BEATLES.LIB/PENNYLANE.DTAQ"; assertEquals(expected, URISupport.sanitizeUri(uri)); }
static com.google.cloud.datacatalog.v1beta1.Schema toDataCatalog(Schema schema) { com.google.cloud.datacatalog.v1beta1.Schema.Builder schemaBuilder = com.google.cloud.datacatalog.v1beta1.Schema.newBuilder(); for (Schema.Field field : schema.getFields()) { schemaBuilder.addColumns(fromBeamField(fie...
@Test public void testToDataCatalog() { assertEquals(TEST_DC_SCHEMA, SchemaUtils.toDataCatalog(TEST_SCHEMA)); }
public Set<String> names() { return Collections.unmodifiableSet(configKeys.keySet()); }
@Test public void testNames() { final ConfigDef configDef = new ConfigDef() .define("a", Type.STRING, Importance.LOW, "docs") .define("b", Type.STRING, Importance.LOW, "docs"); Set<String> names = configDef.names(); assertEquals(new HashSet<>(Arrays.asList("a"...
@Override public Path relativePathFromScmRoot(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); return builder.getGitDir().toPath().getParent().relativize(path); }
@Test public void relativePathFromScmRoot_should_return_relative_path_for_file_in_project_subdir() throws IOException { Path relpath = Paths.get("sub/dir/to/somefile.xoo"); Path path = worktree.resolve(relpath); Files.createDirectories(path.getParent()); Files.createFile(path); assertThat(newGitSc...
@Override public List<ConfigKeyInfo> connectorPluginConfig(String pluginName) { Plugins p = plugins(); Class<?> pluginClass; try { pluginClass = p.pluginClass(pluginName); } catch (ClassNotFoundException cnfe) { throw new NotFoundException("Unknown plugin " + ...
@Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testGetConnectorConfigDefWithInvalidPluginType() throws Exception { String connName = "AnotherPlugin"; AbstractHerder herder = testHerder(); when(worker.getPlugins()).thenReturn(plugins); when(plugins.pluginClass(anyS...
@Override public ChannelFuture writeData(final ChannelHandlerContext ctx, final int streamId, ByteBuf data, int padding, final boolean endOfStream, ChannelPromise promise) { promise = promise.unvoid(); final Http2Stream stream; try { stream = requireStream(streamId); ...
@Test public void dataFramesShouldMerge() throws Exception { createStream(STREAM_ID, false); final ByteBuf data = dummyData().retain(); ChannelPromise promise1 = newPromise(); encoder.writeData(ctx, STREAM_ID, data, 0, true, promise1); ChannelPromise promise2 = newPromise();...
@GetMapping("/configs") public Result<List<ConfigInfo>> getConfigList(ConfigInfo configInfo) { if (StringUtils.isEmpty(configInfo.getPluginType())) { return new Result<>(ResultCodeType.MISS_PARAM.getCode(), ResultCodeType.MISS_PARAM.getMessage()); } Optional<PluginType> optionalP...
@Test public void getConfigList() { Result<List<ConfigInfo>> result = configController.getConfigList(configInfo); Assert.assertTrue(result.isSuccess()); Assert.assertNotNull(result.getData()); Assert.assertEquals(1, result.getData().size()); ConfigInfo info = result.getData()...
@Override public String load(ImageTarball imageTarball, Consumer<Long> writtenByteCountListener) throws InterruptedException, IOException { // Runs 'docker load'. Process dockerProcess = docker("load"); try (NotifyingOutputStream stdin = new NotifyingOutputStream(dockerProcess.getOutputStre...
@Test public void testLoad_stdoutFail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient(ignored -> mockProcessBuilder); Mockito.when(mockProcess.waitFor()).thenReturn(1); Mockito.when(mockProcess.getOutputStream()).thenReturn(ByteStreams.nullOutputStream()); Mockito....
public CompletableFuture<UsernameReservation> reserveUsernameHash(final Account account, final List<byte[]> requestedUsernameHashes) { if (account.getUsernameHash().filter( oldHash -> requestedUsernameHashes.stream().anyMatch(hash -> Arrays.equals(oldHash, hash))) .isPresent()) { // if we ...
@Test void testReserveUsernameHash() { final Account account = AccountsHelper.generateTestAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID(), new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); when(accounts.getByAccountIdentifierAsync(account.getUuid())).thenReturn(...
public static DisruptContext minimumDelay(long delay) { if (delay < 0) { throw new IllegalArgumentException("Delay cannot be smaller than 0"); } return new MinimumDelayDisruptContext(delay); }
@Test public void testMinimumDelay() { final long latency = 4200; DisruptContexts.MinimumDelayDisruptContext context = (DisruptContexts.MinimumDelayDisruptContext) DisruptContexts.minimumDelay(latency); Assert.assertEquals(context.mode(), DisruptMode.MINIMUM_DELAY); Assert.assertEquals(conte...