focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { switch (method.getName()) { case "equals": return equals(args.length > 0 ? args[0] : null); case "hashCode": return hashCode(); ...
@Test public void testDecorator() throws Throwable { feignDecorator.setAlternativeFunction(fnArgs -> "AlternativeFunction"); testSubject = new DecoratorInvocationHandler(target, dispatch, feignDecorator); final Object result = testSubject.invoke(testService, greetingMethod, new Object[0]); ...
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException { List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>(); for (File jarFile : jarFiles) { findEntryClass(jarFile) .ifPresent( entryClass -...
@Test void testFindOnlyEntryClassMultipleJarsWithSingleManifestEntry() throws IOException { File jarWithNoManifest = createJarFileWithManifest(ImmutableMap.of()); File jarFile = TestJob.getTestJobJar(); JarManifestParser.JarFileWithEntryClass jarFileWithEntryClass = JarManif...
@Override public void cancel() {}
@Test void testCancelIgnored() { MockFinishedContext ctx = new MockFinishedContext(); createFinishedState(ctx).cancel(); assertThat(ctx.getArchivedExecutionGraph().getState()).isEqualTo(testJobStatus); }
@Override public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { int nextValue = nextValue(topic); List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic); if (!availablePartitions.isEmpty()) { ...
@Test public void testRoundRobinWithKeyBytes() { final String topicA = "topicA"; final String topicB = "topicB"; List<PartitionInfo> allPartitions = asList(new PartitionInfo(topicA, 0, NODES[0], NODES, NODES), new PartitionInfo(topicA, 1, NODES[1], NODES, NODES), new Partiti...
static void addClusterToMirrorMaker2ConnectorConfig(Map<String, Object> config, KafkaMirrorMaker2ClusterSpec cluster, String configPrefix) { config.put(configPrefix + "alias", cluster.getAlias()); config.put(configPrefix + AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, cluster.getBootstrapServers()); ...
@Test public void testAddClusterToMirrorMaker2ConnectorConfigWithoutAuthWithClusterConfig() { Map<String, Object> config = new HashMap<>(); KafkaMirrorMaker2ClusterSpec cluster = new KafkaMirrorMaker2ClusterSpecBuilder() .withAlias("sourceClusterAlias") .withBootstrap...
@Override public boolean matchesJdbcUrl(String jdbcConnectionURL) { return StringUtils.startsWithIgnoreCase(jdbcConnectionURL, "jdbc:oracle:"); }
@Test void matchesJdbcURL() { assertThat(underTest.matchesJdbcUrl("jdbc:oracle:thin:@localhost/XE")).isTrue(); assertThat(underTest.matchesJdbcUrl("jdbc:hsql:foo")).isFalse(); }
@Override public void writeTo(View t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStre...
@Test void writeToShouldThrowWhenNoValidRendererFound() { final ViewMessageBodyWriter writer = new ViewMessageBodyWriter(metricRegistry, Collections.emptyList()); when(metricRegistry.timer(anyString())).thenReturn(timer); when(timer.time()).thenReturn(timerContext); assertThatExcep...
File decompress() throws IOException { return decompress(uncheck(() -> java.nio.file.Files.createTempDirectory("decompress")).toFile()); }
@Test public void require_that_valid_tar_application_can_be_unpacked() throws IOException { File outFile = createTarFile(temporaryFolder.getRoot().toPath()); try (CompressedApplicationInputStream unpacked = streamFromTarGz(outFile)) { File outApp = unpacked.decompress(); asse...
public List<BuiltinArtifactConfig> getBuiltInArtifactConfigs() { final List<BuiltinArtifactConfig> artifactConfigs = new ArrayList<>(); for (ArtifactTypeConfig artifactTypeConfig : this) { if (artifactTypeConfig instanceof BuiltinArtifactConfig) { artifactConfigs.add((Builtin...
@Test public void getArtifactConfigs_shouldReturnBuiltinArtifactConfigs() { ArtifactTypeConfigs allConfigs = new ArtifactTypeConfigs(); allConfigs.add(new BuildArtifactConfig("src", "dest")); allConfigs.add(new BuildArtifactConfig("java", null)); allConfigs.add(new PluggableArtifactC...
@Override public boolean noServicesOutsideGroupIsDown() throws HostStateChangeDeniedException { return servicesDownAndNotInGroup().size() + missingServices == 0; }
@Test public void testUnknownServiceStatusOutsideGroup() { ClusterApi clusterApi = makeClusterApiWithUnknownStatus(ServiceStatus.UP, ServiceStatus.UNKNOWN, ServiceStatus.UP); try { clusterApi.noServicesOutsideGroupIsDown(); fail(); } catch (HostStateChangeDeniedExcep...
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final ReadOnlyKeyValueStore<GenericKey, ValueAndTimestamp<GenericRow>> store = stateStore .store(QueryableStoreTypes.timestampedKeyValueSt...
@Test public void shouldReturnValueIfKeyPresent() { // Given: final GenericRow value = GenericRow.genericRow("col0"); final long rowTime = 2343553L; when(tableStore.get(any())).thenReturn(ValueAndTimestamp.make(value, rowTime)); // When: final Iterator<Row> rowIterator = table.get(A_KEY, PART...
@Override public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) { return firstAddress(addresses(inetHost, resolvedAddressTypes)); }
@Test public void shouldntFindWhenAddressTypeDoesntMatch() { HostsFileEntriesProvider.Parser parser = givenHostsParserWith( LOCALHOST_V4_ADDRESSES, Collections.<String, List<InetAddress>>emptyMap() ); DefaultHostsFileEntriesResolver resolver = new DefaultHost...
@Override public Optional<String> buildInsertOnDuplicateClause(final DataRecord dataRecord) { // TODO without unique key, job has been interrupted, which may lead to data duplication if (dataRecord.getUniqueKeyValue().isEmpty()) { return Optional.empty(); } StringBuilder ...
@Test void assertBuildInsertSQLOnDuplicateClause() { String actual = sqlBuilder.buildInsertOnDuplicateClause(mockDataRecord()).orElse(null); assertThat(actual, is("ON CONFLICT (order_id) DO UPDATE SET user_id=EXCLUDED.user_id,status=EXCLUDED.status")); }
@Override public int compareTo(final Host o) { if(protocol.compareTo(o.protocol) < 0) { return -1; } else if(protocol.compareTo(o.protocol) > 0) { return 1; } if(port.compareTo(o.port) < 0) { return -1; } else if(port.compar...
@Test public void testCompare() { assertEquals(0, new Host(new TestProtocol(Scheme.ftp), "a", 33) .compareTo(new Host(new TestProtocol(Scheme.ftp), "a", 33))); assertEquals(-1, new Host(new TestProtocol(Scheme.ftp), "a", 22) .compareTo(new Host(new TestProtocol(Scheme.ftp), "...
@Override public int availablePermits() { return get(availablePermitsAsync()); }
@Test public void testNotExistent() { RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("testSemaphoreForNPE"); Assertions.assertEquals(0, semaphore.availablePermits()); }
public boolean isRunning() { return transactionStatus == TransactionStatus.PREPARE || transactionStatus == TransactionStatus.PREPARED || transactionStatus == TransactionStatus.COMMITTED; }
@Test public void testIsRunning() { Set<TransactionStatus> nonRunningStatus = new HashSet<>(); nonRunningStatus.add(TransactionStatus.UNKNOWN); nonRunningStatus.add(TransactionStatus.VISIBLE); nonRunningStatus.add(TransactionStatus.ABORTED); UUID uuid = UUID.randomUUID(); ...
public int doWork() { final long nowNs = nanoClock.nanoTime(); cachedNanoClock.update(nowNs); dutyCycleTracker.measureAndUpdate(nowNs); int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT); final int bytesReceived = dataTransportPolle...
@Test void shouldOverwriteHeartbeatWithDataFrame() { receiverProxy.registerReceiveChannelEndpoint(receiveChannelEndpoint); receiver.doWork(); receiverProxy.addSubscription(receiveChannelEndpoint, STREAM_ID); receiver.doWork(); fillSetupFrame(setupHeader); receive...
@Override public List<PartitionInfo> getPartitions(Table table, List<String> partitionNames) { if (partitionNames == null || partitionNames.isEmpty()) { return Collections.emptyList(); } OdpsTable odpsTable = (OdpsTable) table; List<Partition> partitions = get(partitionCa...
@Test public void testGetPartitions() { Table table = odpsMetadata.getTable("db", "tbl"); List<String> partitionNames = odpsMetadata.listPartitionNames("db", "tbl", TableVersionRange.empty()); List<PartitionInfo> partitions = odpsMetadata.getPartitions(table, partitionNames); Assert....
@Subscribe @SuppressWarnings("unused") public void handleDataNodeLifeCycleEvent(DataNodeLifecycleEvent event) { switch (event.trigger()) { case REMOVED -> handleNextNode(DataNodeLifecycleTrigger.REMOVE); case STOPPED -> handleNextNode(DataNodeLifecycleTrigger.STOP); } ...
@Test public void removedLifecycleEventRemovesNextNode() { DataNodeDto node1 = buildTestNode("node1", DataNodeStatus.REMOVING); nodeService.registerServer(node1); DataNodeDto node2 = buildTestNode("node2", DataNodeStatus.AVAILABLE); nodeService.registerServer(node2); DataNode...
@Override public List<ApolloAuditLogDetailsDTO> queryTraceDetails(String traceId) { List<ApolloAuditLogDetailsDTO> detailsDTOList = new ArrayList<>(); logService.findByTraceId(traceId).forEach(log -> { detailsDTOList.add(new ApolloAuditLogDetailsDTO(ApolloAuditUtil.logToDTO(log), ApolloAuditUt...
@Test public void testQueryTraceDetails() { final String traceId = "query-trace-id"; final int traceDetailsLength = 3; final int dataInfluenceOfEachLog = 3; { List<ApolloAuditLog> logList = MockBeanFactory.mockAuditLogListByLength(traceDetailsLength); Mockito.when(logService.findByTraceId(...
@Override public MetadataReport getMetadataReport(URL url) { url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY); String key = url.toServiceString(NAMESPACE_KEY); MetadataReport metadataReport = serviceStoreMap.get(key); if (metadataReport != nu...
@Test void testGetOneMetadataReport() { URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url); Metada...
public AdSession updateAdSession(AdSession session, Map<String, Object> body) throws AdValidationException { session.setAuthenticationLevel((Integer) body.get("authentication_level")); session.setAuthenticationStatus((String) body.get("authentication_status")); session.setBsn((String) body.get("...
@Test public void updateAdSession() throws AdValidationException { HashMap<String, Object> body = new HashMap<>(); body.put("authentication_level", 10); body.put("authentication_status", AdAuthenticationStatus.STATUS_SUCCESS.label); body.put("bsn", "PPPPPPPPP"); AdSession re...
public void updateUsedBytes(Map<String, Long> usedBytesOnTiers) { long usedBytes = 0; mUsage.mUsedBytesOnTiers = new HashMap<>(usedBytesOnTiers); for (long t : mUsage.mUsedBytesOnTiers.values()) { usedBytes += t; } mUsage.mUsedBytes = usedBytes; }
@Test public void updateUsedBytes() { assertEquals(Constants.KB * 2L, mInfo.getUsedBytes()); Map<String, Long> usedBytesOnTiers = ImmutableMap.of(Constants.MEDIUM_MEM, Constants.KB * 2L, Constants.MEDIUM_SSD, (long) Constants.KB); mInfo.updateUsedBytes(usedBytesOnTiers); assertEqua...
@Override public String toString() { final String escapedPartitionKeys = partitionKeys.stream() .map(EncodingUtils::escapeIdentifier) .collect(Collectors.joining(", ")); final String distributedBy = distribution == null ? "" : distribu...
@Test void testDistributedBy() { assertThat(getTableDescriptorBuilder().distributedByHash(3, "f0").build().toString()) .contains("DISTRIBUTED BY HASH(`f0`) INTO 3 BUCKETS\n"); assertThat(getTableDescriptorBuilder().distributedByHash("f0").build().toString()) .contains...
public int getJobManagerMemoryMB() { return clusterSpecification.getMasterMemoryMB(); }
@Test void testGetJobManagerMemoryMB() { assertThat(kubernetesJobManagerParameters.getJobManagerMemoryMB()) .isEqualTo(JOB_MANAGER_MEMORY); }
public Favorite addFavorite(Favorite favorite) { UserInfo user = userService.findByUserId(favorite.getUserId()); if (user == null) { throw BadRequestException.userNotExists(favorite.getUserId()); } UserInfo loginUser = userInfoHolder.getUser(); //user can only add himself favorite app if ...
@Test(expected = BadRequestException.class) @Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void testAddFavoriteErrorUser() { String testApp = "testApp"; Favorite favorite = instanceOfFavorite("errorUser", testApp); favoriteService.addFavorite(favorite); ...
public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) { final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode()); final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessorPai...
@Test public void testProcessRequestCommand() throws InterruptedException { final Semaphore semaphore = new Semaphore(0); RemotingCommand request = RemotingCommand.createRequestCommand(1, null); ResponseFuture responseFuture = new ResponseFuture(null, 1, request, 3000, new Invoke...
@Override public String toString() { return String.format( "IcebergStagedScan(table=%s, type=%s, taskSetID=%s, caseSensitive=%s)", table(), expectedSchema().asStruct(), taskSetId, caseSensitive()); }
@Test public void testTaskSetLoading() throws NoSuchTableException, IOException { sql("CREATE TABLE %s (id INT, data STRING) USING iceberg", tableName); List<SimpleRecord> records = ImmutableList.of(new SimpleRecord(1, "a"), new SimpleRecord(2, "b")); Dataset<Row> df = spark.createDataFrame(recor...
public static RowRanges intersection(RowRanges left, RowRanges right) { RowRanges result = new RowRanges(); int rightIndex = 0; for (Range l : left.ranges) { for (int i = rightIndex, n = right.ranges.size(); i < n; ++i) { Range r = right.ranges.get(i); if (l.isBefore(r)) { b...
@Test public void testIntersection() { RowRanges ranges1 = buildRanges( 2, 5, 7, 9, 14, 14, 20, 24); RowRanges ranges2 = buildRanges( 1, 2, 6, 7, 9, 9, 11, 12, 14, 15, 21, 22); RowRanges empty = buildRanges(); assertAllRow...
@Udf(description = "Converts the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into " + "a TIMESTAMP value.") public Timestamp fromUnixTime( @UdfParameter( description = "Milliseconds since" + " January 1, 1970, 00:00:00 GMT.") final Long epochMilli ) { if (epochMi...
@Test public void shouldConvertToTimestamp() { // When: final Object result = udf.fromUnixTime(100L); // Then: assertThat(result, is(new Timestamp(100L))); }
@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 parentLastGetExtensionsIndexExistsInParentAndDependencyAndPlugin() throws URISyntaxException, IOException { URL resource = parentLastPluginClassLoader.getResource(LegacyExtensionFinder.EXTENSIONS_RESOURCE); assertFirstLine("plugin", resource); }
public static MetricsReporter combine(MetricsReporter first, MetricsReporter second) { if (null == first) { return second; } else if (null == second || first == second) { return first; } Set<MetricsReporter> reporters = Sets.newIdentityHashSet(); if (first instanceof CompositeMetricsRe...
@Test public void combineComposites() { MetricsReporter one = report -> {}; MetricsReporter two = report -> {}; MetricsReporter firstComposite = MetricsReporters.combine(one, LoggingMetricsReporter.instance()); MetricsReporter secondComposite = MetricsReporters.combine(two, LoggingMetr...
public synchronized LogAction record(double... values) { return record(DEFAULT_RECORDER_NAME, timer.monotonicNow(), values); }
@Test public void testNamedLoggersWithoutSpecifiedPrimary() { assertTrue(helper.record("foo", 0).shouldLog()); assertTrue(helper.record("bar", 0).shouldLog()); assertFalse(helper.record("foo", LOG_PERIOD / 2).shouldLog()); assertFalse(helper.record("bar", LOG_PERIOD / 2).shouldLog()); assertTrue...
@Override public void close() { try { if (this.response != null) { HttpClientUtils.closeQuietly(response); } } catch (Exception ex) { // ignore } }
@Test void testCloseResponseWithException() { when(response.getEntity()).thenThrow(new RuntimeException("test")); clientHttpResponse.close(); }
public static Map<Integer, ColumnStatistics> createEmptyColumnStatistics(List<OrcType> orcTypes, int nodeIndex, ColumnWriterOptions columnWriterOptions) { requireNonNull(orcTypes, "orcTypes is null"); checkArgument(nodeIndex >= 0, "Invalid nodeIndex value: %s", nodeIndex); ImmutableMap.Buil...
@Test public void testCreateEmptyColumnStatistics() { ColumnWriterOptions columnWriterOptions = ColumnWriterOptions.builder().setCompressionKind(CompressionKind.ZSTD).build(); Type rootType = rowType(// node index 0 TINYINT, // 1 mapType(TINYINT, SMALLINT), // 2-4...
@Override public void upgrade() { final MongoCollection<Document> collection = mongoConnection.getMongoDatabase().getCollection(AccessTokenImpl.COLLECTION_NAME); // We use the absence of the "token_type" field as an indicator to select access tokens that need to be encrypted // If we should...
@Test @MongoDBFixtures("V20200226181600_EncryptAccessTokensMigrationTest.json") public void upgrade() { final Document plainToken1 = collection.find(Filters.eq("_id", new ObjectId("54e3deadbeefdeadbeef0001"))).first(); final Document plainToken2 = collection.find(Filters.eq("_id", new ObjectId("...
public static Read read() { return new AutoValue_HCatalogIO_Read.Builder() .setDatabase(DEFAULT_DATABASE) .setPartitionCols(new ArrayList<>()) .build(); }
@Test public void testReadFailureValidationTable() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("withTable() is required"); HCatalogIO.read() .withConfigProperties(getConfigPropertiesAsMap(service.getHiveConf())) .expand(null); }
public CompletableFuture<Void> complete(URL lra, Exchange exchange) { HttpRequest request = prepareRequest(URI.create(lra.toString() + COORDINATOR_PATH_CLOSE), exchange) .setHeader(CONTENT_TYPE, TEXT_PLAIN_CONTENT) .PUT(HttpRequest.BodyPublishers.ofString("")) .bu...
@DisplayName("Tests whether LRAClient is calling prepareRequest with exchange from complete()") @Test void testCallsPrepareRequestWithExchangeInComplete() throws MalformedURLException { LRASagaService sagaService = new LRASagaService(); applyMockProperties(sagaService); LRAClient client ...
public static List<ACL> parseACLs(String aclString) throws BadAclFormatException { List<ACL> acl = Lists.newArrayList(); if (aclString == null) { return acl; } List<String> aclComps = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults() .split(aclString)...
@Test public void testNullACL() { List<ACL> result = ZKUtil.parseACLs(null); assertTrue(result.isEmpty()); }
public static <K extends WritableComparable, V extends Writable> Writable getEntry(MapFile.Reader[] readers, Partitioner<K, V> partitioner, K key, V value) throws IOException { int readerLength = readers.length; ...
@SuppressWarnings("static-access") @Test public void testPartitionerShouldNotBeCalledWhenOneReducerIsPresent() throws Exception { MapFileOutputFormat outputFormat = new MapFileOutputFormat(); Reader reader = Mockito.mock(Reader.class); Reader[] readers = new Reader[]{reader}; outputFormat.getE...
public void updateTaskConfig(Map<String, String> taskConfig) { try { taskLifecycleLock.lock(); if (!Objects.equals(this.taskConfigReference, taskConfig)) { logger.info("Updating task '" + name + "' configuration"); taskConfigReference = taskConfig; ...
@Test public void should_reconfigure_task() { assertPolledRecordsSize(CONFIGURED_ITEMS_SIZE); connector.setProperty(ITEMS_SIZE, String.valueOf(5)); assertPolledRecordsSize(CONFIGURED_ITEMS_SIZE); taskRunner.updateTaskConfig(dummyTaskConfig()); assertPolledRecordsSize(5); ...
@SuppressWarnings("deprecation") @SneakyThrows(SQLException.class) public static Message convertToProtobufMessage(final Object object) { if (null == object) { return Empty.getDefaultInstance(); } if (object instanceof Integer) { return Int32Value.of((int) object);...
@Test void assertConvertToProtobufMessage() { Message actualMessage = ColumnValueConvertUtils.convertToProtobufMessage(null); assertTrue(actualMessage instanceof Empty); actualMessage = ColumnValueConvertUtils.convertToProtobufMessage(1); assertTrue(actualMessage instanceof Int32Valu...
public static void main(String[] args) { if (args.length < 3) { System.out.println("Error: insufficient arguments"); System.out.println(); System.out.println("usage: java -cp jobrunr-${jobrunr.version}.jar org.jobrunr.storage.sql.common.DatabaseCreator {jdbcUrl} {userName} {p...
@Test void testSqlLiteMigrationsUsingMainMethod() { assertThatCode(() -> DatabaseCreator.main(new String[]{"jdbc:sqlite:" + SQLITE_DB1, "", ""})).doesNotThrowAnyException(); }
public static ParameterizedType parameterize(final Class<?> raw, final Type... typeArguments) { checkParameterizeMethodParameter(raw, typeArguments); return new ParameterizedTypeImpl(raw, raw.getEnclosingClass(), typeArguments); }
@Test void testParameterizeForDiffLength() { assertThrows(IllegalArgumentException.class, () -> { TypeUtils.parameterize(List.class, String.class, Integer.class); }); }
public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected an empty string")); } else if (!actual.isEmpty()) { failWithActual(simpleFact("expected to be empty")); } }
@Test public void stringIsEmptyFailNull() { expectFailureWhenTestingThat(null).isEmpty(); assertFailureKeys("expected an empty string", "but was"); }
public static String getDescription(String descriptionTemplate, Map<String, String> params) { assertParamsMatchWithDescription(descriptionTemplate, params); String description = descriptionTemplate; for (String param : getParams(descriptionTemplate)) { String value = params.get(param...
@Test void testGetDescriptionForTemplate() { String description = "test description with param <key1>, <key2> and <key3>."; Map<String, String> params = new HashMap<>(); params.put("key1", "value1"); params.put("key2", "value2"); params.put("key3", "value3"); Assertio...
public static <T> PTransform<PCollection<T>, PCollection<T>> unionAll( PCollection<T> rightCollection) { checkNotNull(rightCollection, "rightCollection argument is null"); return new SetImpl<>(rightCollection, unionAll()); }
@Test @Category(NeedsRunner.class) public void testUnionAll() { PAssert.that(first.apply("strings", Sets.unionAll(second))) .containsInAnyOrder( "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "d", "d", "d", "d", "e", "e", "f", "f", "g", "g", "h", "h"); PCollect...
@Override public Output run(RunContext runContext) throws Exception { String renderedNamespace = runContext.render(this.namespace); FlowService flowService = ((DefaultRunContext) runContext).getApplicationContext().getBean(FlowService.class); flowService.checkAllowedNamespace(runContext.ten...
@Test void shouldGetKeysGivenMatchingPrefix() throws Exception { // Given String namespace = IdUtils.create(); RunContext runContext = this.runContextFactory.of(Map.of( "flow", Map.of("namespace", namespace), "inputs", Map.of( "prefix", TEST_KEY_PREFIX...
@SuppressWarnings("unchecked") @Override public Throwable deSerialize() { SerializedException cause = getCause(); SerializedExceptionProtoOrBuilder p = viaProto ? proto : builder; Class<?> realClass = null; try { realClass = Class.forName(p.getClassName()); } catch (ClassNotFoundException...
@Test void testDeserialize() throws Exception { Exception ex = new Exception("test exception"); SerializedExceptionPBImpl pb = new SerializedExceptionPBImpl(); try { pb.deSerialize(); fail("deSerialize should throw YarnRuntimeException"); } catch (YarnRuntimeException e) { assertEqu...
@Override public boolean localMember() { return localMember; }
@Test public void testConstructor_withLiteMember_isTrue() { MemberImpl member = new MemberImpl.Builder(address) .version(MemberVersion.of("3.8.0")) .localMember(true) .uuid(newUnsecureUUID()) .liteMember(true) .build(); ...
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void ifExpression() { String inputExpression = "if applicant.age < 18 then \"declined\" else \"accepted\""; BaseNode ifBase = parse( inputExpression ); assertThat( ifBase).isInstanceOf(IfExpressionNode.class); assertThat( ifBase.getText()).isEqualTo(inputExpression); a...
@Udf public <T> List<T> intersect( @UdfParameter(description = "First array of values") final List<T> left, @UdfParameter(description = "Second array of values") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> intersection = Sets.newLinkedHashSet(l...
@Test public void shouldReturnNullForNullInputs() { final List<Long> result = udf.intersect((List<Long>) null, (List<Long>) null); assertThat(result, is(nullValue())); }
public static Mode parse(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException(ExceptionMessage.INVALID_MODE.getMessage(value)); } try { return parseNumeric(value); } catch (NumberFormatException e) { // Treat as symbolic return parseSymbolic(value...
@Test public void numerics() { Mode parsed = ModeParser.parse("777"); assertEquals(Mode.Bits.ALL, parsed.getOwnerBits()); assertEquals(Mode.Bits.ALL, parsed.getGroupBits()); assertEquals(Mode.Bits.ALL, parsed.getOtherBits()); parsed = ModeParser.parse("755"); assertEquals(Mode.Bits.ALL, parse...
public UserGroupDto addMembership(String groupUuid, String userUuid) { try (DbSession dbSession = dbClient.openSession(false)) { UserDto userDto = findUserOrThrow(userUuid, dbSession); GroupDto groupDto = findNonDefaultGroupOrThrow(groupUuid, dbSession); UserGroupDto userGroupDto = new UserGroupDt...
@Test public void addMembership_ifGroupAndUserNotFound_shouldThrow() { assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> groupMembershipService.addMembership(GROUP_A, USER_1)) .withMessage("User 'user_1' not found"); }
public static boolean canProduceEmptyMatches(final Pattern<?, ?> pattern) { NFAFactoryCompiler<?> compiler = new NFAFactoryCompiler<>(checkNotNull(pattern)); compiler.compileFactory(); State<?> startState = compiler.getStates().stream() .filter(State::isSt...
@Test public void testCheckingEmptyMatches() { assertThat(NFACompiler.canProduceEmptyMatches(Pattern.begin("a").optional()), is(true)); assertThat( NFACompiler.canProduceEmptyMatches(Pattern.begin("a").oneOrMore().optional()), is(true)); assertThat( ...
public byte[] signDataWithPrivateKey(byte[] data) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, ...
@Test public void testSignDataWithPrivateKey() throws UnsupportedEncodingException, UnrecoverableKeyException, InvalidKeyException, KeyStoreException, ...
@Override public double d(BitSet x, BitSet y) { if (x.size() != y.size()) { throw new IllegalArgumentException(String.format("BitSets have different length: x[%d], y[%d]", x.size(), y.size())); } int dist = 0; for (int i = 0; i < x.size(); i++) { if (x.get(i)...
@Test public void testDistance() { System.out.println("distance"); int x = 0x5D; int y = 0x49; assertEquals(2, HammingDistance.d(x, y)); }
public SelectorData obtainSelectorData(final String pluginName, final String path) { final Map<String, SelectorData> lruMap = SELECTOR_DATA_MAP.get(pluginName); return Optional.ofNullable(lruMap).orElse(Maps.newHashMap()).get(path); }
@Test public void testObtainSelectorData() throws NoSuchFieldException, IllegalAccessException { SelectorData firstSelectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).sort(1).build(); ConcurrentHashMap<String, WindowTinyLFUMap<String, SelectorData>> selectorMap = getFieldByName...
public String prettyHexDump() { final ByteBuf buffer = Unpooled.buffer(20); try { buffer.writeShort(version()); buffer.writeShort(count()); buffer.writeInt(Math.toIntExact(sysUptime())); buffer.writeInt(Math.toIntExact(unixSecs())); buffer.writ...
@Test public void prettyHexDump() { final NetFlowV9Header header = NetFlowV9Header.create(5, 23, 42L, 1000L, 1L, 1L); assertThat(header.prettyHexDump()).isNotEmpty(); }
@Override public Collection<String> getJdbcUrlPrefixes() { return Collections.singletonList("jdbc:p6spy:mysql:"); }
@Test void assertGetJdbcUrlPrefixes() { assertThat(TypedSPILoader.getService(DatabaseType.class, "P6spyMySQL").getJdbcUrlPrefixes(), is(Collections.singletonList("jdbc:p6spy:mysql:"))); }
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator288() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); assertTrue("hostname with path should validate", validator.isValid(...
protected static VplsOperation getOptimizedVplsOperation(Deque<VplsOperation> operations) { if (operations.isEmpty()) { return null; } // no need to optimize if the queue contains only one operation if (operations.size() == 1) { return operations.getFirst(); ...
@Test public void testOptimizeOperationsUToU() { Deque<VplsOperation> operations = new ArrayDeque<>(); VplsData vplsData = VplsData.of(VPLS1); vplsData.addInterfaces(ImmutableSet.of(V100H1)); VplsOperation vplsOperation = VplsOperation.of(vplsData, ...
public static byte[] zip(List<ZipItem> source) { byte[] result = null; try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream( byteOut)) { for (ZipItem item : source) { zipOut.putNextEntry(new ZipEntry(it...
@Test void testZip() { List<ZipUtils.ZipItem> zipItemList = new ArrayList<>(); zipItemList.add(new ZipUtils.ZipItem("test", "content")); byte[] zip = ZipUtils.zip(zipItemList); assertTrue(zip != null && zip.length > 0); }
public static long fix(FileSystem fs, Path dir, Class<? extends Writable> keyClass, Class<? extends Writable> valueClass, boolean dryrun, Configuration conf) throws Exception { String dr = (dryrun ? "[DRY RUN ] " : ""); Path data = new P...
@Test public void testFix() { final String INDEX_LESS_MAP_FILE = "testFix.mapfile"; int PAIR_SIZE = 20; MapFile.Writer writer = null; try { FileSystem fs = FileSystem.getLocal(conf); Path dir = new Path(TEST_DIR, INDEX_LESS_MAP_FILE); writer = createWriter(INDEX_LESS_MAP_FILE, IntWri...
public static String from(Query query) { if (query instanceof SqmInterpretationsKey.InterpretationsKeySource && query instanceof QueryImplementor && query instanceof QuerySqmImpl) { QueryInterpretationCache.Key cacheKey = SqmInterpretationsKey.createInterpretationsKey((SqmInt...
@Test public void testJPQL() { doInJPA(entityManager -> { Query jpql = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + ...
static Schema toGenericAvroSchema( String schemaName, List<TableFieldSchema> fieldSchemas, @Nullable String namespace) { String nextNamespace = namespace == null ? null : String.format("%s.%s", namespace, schemaName); List<Field> avroFields = new ArrayList<>(); for (TableFieldSchema bigQueryField : ...
@Test public void testConvertBigQuerySchemaToAvroSchema() { TableSchema tableSchema = new TableSchema(); tableSchema.setFields(fields); Schema avroSchema = BigQueryAvroUtils.toGenericAvroSchema("testSchema", tableSchema.getFields()); assertThat(avroSchema.getField("number").schema(), equalTo(...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { int time = payload.getByteBuf().readUnsignedMedium(); if (0x800000 == time) { return MySQLTimeValueUtils.ZERO_OF_TIME; } MySQLFractionalSeconds fractionalSeconds =...
@Test void assertReadWithFraction3() { columnDef.setColumnMeta(3); when(payload.getByteBuf()).thenReturn(byteBuf); when(byteBuf.readUnsignedShort()).thenReturn(9000); when(byteBuf.readUnsignedMedium()).thenReturn(0x800000 | (0x10 << 12) | (0x08 << 6) | 0x04); assertThat(new M...
@Override public void close() { if (initialized) { destroyFn.accept(ctx); } }
@Test public void when_streamingSourceClosesBuffer_then_fails() { StreamSource<Integer> source = SourceBuilder .stream("src", ctx -> null) .<Integer>fillBufferFn((src, buffer) -> buffer.close()) .distributed(1) // we use this to avoid forceTotalParallelismOne ...
public Optional<PushEventDto> raiseEventOnIssue(String projectUuid, DefaultIssue currentIssue) { var currentIssueComponentUuid = currentIssue.componentUuid(); if (currentIssueComponentUuid == null) { return Optional.empty(); } var component = treeRootHolder.getComponentByUuid(currentIssueComponen...
@Test public void raiseEventOnIssue_whenNewHotspot_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setStatus(Issue.STATUS_TO_REVIEW) .setNew(true) .setRuleDescriptionContextKey(randomAlphabetic(6)); assertThat(underTest...
public Map<String, Parameter> generateMergedWorkflowParams( WorkflowInstance instance, RunRequest request) { Workflow workflow = instance.getRuntimeWorkflow(); Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>(); Map<String, ParamDefinition> defaultWorkflowParams = defaultParamMa...
@Test public void testCalculateUserDefinedSelParams() { paramsManager = new ParamsManager(defaultsManager); Step step = Mockito.mock(Step.class); when(step.getType()).thenReturn(StepType.TITUS); RunProperties runProperties = new RunProperties(); runProperties.setOwner(User.builder().name("demo").b...
public List<VespaService> getMonitoringServices(String service) { if (service.equalsIgnoreCase(ALL_SERVICES)) return services; List<VespaService> myServices = new ArrayList<>(); for (VespaService s : services) { log.log(FINE, () -> "getMonitoringServices. service=" + ser...
@Test public void all_services_can_be_retrieved_by_using_special_name() { List<VespaService> dummyServices = List.of( new DummyService(0, "dummy/id/0")); VespaServices services = new VespaServices(dummyServices); assertEquals(1, services.getMonitoringServices(ALL_SERVICES).s...
@Override public void publishLong(MetricDescriptor descriptor, long value) { publishNumber(descriptor, value, LONG); }
@Test public void when_singleMetricWithModule() throws Exception { MetricDescriptor descriptor = newDescriptor() .withMetric("c") .withTag("tag1", "a") .withTag("module", MODULE_NAME); jmxPublisher.publishLong(descriptor, 1L); helper.assertMBea...
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) { List<String> diagramLines = filterOutComments(rawDiagramLines); Set<PlantUmlComponent> components = parseComponents(diagramLines); PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components); List<Parse...
@Test public void does_not_include_dependency_descriptions() { PlantUmlDiagram diagram = createDiagram(TestDiagram.in(temporaryFolder) .component("component").withStereoTypes("..somePackage..") .component("otherComponent").withStereoTypes("..somePackage2..") ....
@Override public NotificationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) { PluggableInstanceSettings pluggableInstanceSettings = getPluginSettingsAndView(descriptor, extension); return new NotificationPluginInfo(descriptor, pluggableInstanceSettings); }
@Test public void shouldBuildPluginInfo() { GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build(); NotificationPluginInfo pluginInfo = new NotificationPluginInfoBuilder(extension).pluginInfoFor(descriptor); List<PluginConfiguration> pluginConfigurations = List....
public static ScenarioBeanWrapper<?> navigateToObject(Object rootObject, List<String> steps) { return navigateToObject(rootObject, steps, true); }
@Test public void navigateToObjectNoStepCreationTest() { Dispute dispute = new Dispute(); List<String> pathToProperty = List.of("creator", "firstName"); String message = "Impossible to reach field firstName because a step is not instantiated"; assertThatThrownBy(() -> ScenarioBeanUt...
public boolean hasScheme() { return mUri.getScheme() != null; }
@Test public void hasScheme() { assertFalse(new AlluxioURI("/").hasScheme()); assertTrue(new AlluxioURI("file:/").hasScheme()); assertTrue(new AlluxioURI("file://localhost/").hasScheme()); assertTrue(new AlluxioURI("file://localhost:8080/").hasScheme()); assertFalse(new AlluxioURI("//localhost:808...
@Override public byte[] serialize() { final byte[] data = new byte[LENGTH + PADDING_LENGTH]; final ByteBuffer bb = ByteBuffer.wrap(data); bb.put(PADDING); return data; }
@Test public void serialize() { assertArrayEquals(data, TERMINATOR_TLV.serialize()); }
@Operation(summary = "Create the signature") @PostMapping(value = { Constants.URL_OLD_RDW_SIGNATURE, Constants.URL_RDW_SIGNATURE }, consumes = "application/json", produces = "application/json") public SignatureResponse getDigitalSignatureRestService(@Valid @RequestBody SignatureRequest request, ...
@Test public void getDigitalSignatureRestServiceTest() { SignatureResponse expectedResponse = new SignatureResponse(); when(rdwServiceMock.getDigitalSignatureRestService(any(SignatureRequest.class), anyString())).thenReturn(expectedResponse); SignatureResponse actualResponse = rdwController...
@SuppressWarnings("argument") static Status runSqlLine( String[] args, @Nullable InputStream inputStream, @Nullable OutputStream outputStream, @Nullable OutputStream errorStream) throws IOException { String[] modifiedArgs = checkConnectionArgs(args); SqlLine sqlLine = new SqlLine...
@Test public void testSqlLine_select() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String[] args = buildArgs("SELECT 3, 'hello', DATE '2018-05-28';"); BeamSqlLine.runSqlLine(args, null, byteArrayOutputStream, null); List<List<String>> lines = toLines...
@Override public void write(int b) throws IOException { if (buffer.length <= bufferIdx) { flushInternalBuffer(); } buffer[bufferIdx] = (byte) b; ++bufferIdx; }
@Test void testFailingSecondaryWriteArrayOffsFail() throws Exception { DuplicatingCheckpointOutputStream duplicatingStream = createDuplicatingStreamWithFailingSecondary(); testFailingSecondaryStream( duplicatingStream, () -> duplicatingStream.write(new byte[512], 20, ...
public B serialization(String serialization) { this.serialization = serialization; return getThis(); }
@Test void serialization() { ServiceBuilder builder = new ServiceBuilder(); builder.serialization("serialization"); Assertions.assertEquals("serialization", builder.build().getSerialization()); }
@Override public SpanCustomizer annotate(String value) { return tracer.currentSpanCustomizer().annotate(value); }
@Test void annotate_when_no_current_span() { spanCustomizer.annotate("foo"); }
NewExternalIssue mapResult(String driverName, @Nullable Result.Level ruleSeverity, @Nullable Result.Level ruleSeverityForNewTaxonomy, Result result) { NewExternalIssue newExternalIssue = sensorContext.newExternalIssue(); newExternalIssue.type(DEFAULT_TYPE); newExternalIssue.engineId(driverName); newExte...
@Test public void mapResult_whenStacksLocationExists_createsCodeFlowFileLocation_no_text_messages() { Location stackFrameLocationWithoutMessage = new Location().withMessage(new Message().withId("1")); result.withStacks(Set.of(new Stack().withFrames(List.of(new StackFrame().withLocation(stackFrameLocationWitho...
public String getContextPath() { return contextPath; }
@Test public void context_path_is_configured() { settings.setProperty(CONTEXT_PROPERTY, "/my_path"); assertThat(underTest().getContextPath()).isEqualTo("/my_path"); }
public static boolean reserved(Uuid uuid) { return uuid.getMostSignificantBits() == 0 && uuid.getLeastSignificantBits() < 100; }
@Test void testLostIsReserved() { assertTrue(DirectoryId.reserved(DirectoryId.LOST)); }
@Override public FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress) throws IOException { return super.create(fullPath(f), permission, overwrite, bufferSize, ...
@Test public void testURIEmptyPath() throws IOException { Configuration conf = new Configuration(); conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class); URI chrootUri = URI.create("mockfs://foo"); new ChRootedFileSystem(chrootUri, conf); }
public static MetricName name(Class<?> klass, String... names) { return name(klass.getName(), names); }
@Test public void elidesEmptyStringsFromNames() throws Exception { assertThat(name("one", "", "three")) .isEqualTo(MetricName.build("one.three")); }
public static String toCamelCase(CharSequence name) { return toCamelCase(name, CharUtil.UNDERLINE); }
@Test public void toCamelCaseTest() { Dict.create() .set("Table_Test_Of_day","tableTestOfDay") .set("TableTestOfDay","TableTestOfDay") .set("abc_1d","abc1d") .forEach((key, value) -> assertEquals(value, NamingCase.toCamelCase(key))); }
@Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { if (executor.isShutdown()) { return; } BlockingQueue<Runnable> workQueue = executor.getQueue(); Runnable firstWork = workQueue.poll(); boolean newTaskAdd = workQueue.offer(r); ...
@Test public void testRejectedExecutionWhenATaskIsInTheQueueTheExecutorShouldExecute() { when(threadPoolExecutor.isShutdown()).thenReturn(false); when(threadPoolExecutor.getQueue()).thenReturn(workQueue); when(workQueue.poll()).thenReturn(runnableInTheQueue); when(workQueue.offer(run...
@Override public void notifyAfterCompleted() { }
@Test public void notifyAfterCompleted() { provider.notifyAfterCompleted(); }
@Override synchronized Set<TopicPartition> partitions() { return wrapped.partitions(); }
@Test public void testPartitions() { final Set<TopicPartition> partitions = Collections.singleton(new TopicPartition("topic", 0)); when(wrapped.partitions()).thenReturn(partitions); final Set<TopicPartition> result = synchronizedPartitionGroup.partitions(); assertEquals(partitions,...
public String render(Object o) { StringBuilder result = new StringBuilder(template.length()); render(o, result); return result.toString(); }
@Test public void canSubstituteValuesFromLists() { Template template = new Template("Hello {{#getValues}}{{toString}},{{/getValues}} "); assertEquals("Hello 1,2,3, ", template.render(foo)); }
IdBatchAndWaitTime newIdBaseLocal(int batchSize) { return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize); }
@Test public void when_maximumAllowedFuturePlusOne_then_1msWaitTime() { int batchSize = (int) (IDS_PER_SECOND * DEFAULT_ALLOWED_FUTURE_MILLIS) + IDS_PER_SECOND; IdBatchAndWaitTime result = gen.newIdBaseLocal(1516028439000L, 1234, batchSize); assertEquals(1, result.waitTimeMillis); }
@Override public Result invoke(Invocation invocation) throws RpcException { // When broadcasting, it should be called remotely. if (isBroadcast()) { if (logger.isDebugEnabled()) { logger.debug("Performing broadcast call for method: " + RpcUtils.getMethodName(invocation) ...
@Test void testScopeNull_RemoteInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); ...
public BootstrapMetadata copyWithOnlyVersion() { ApiMessageAndVersion versionRecord = null; for (ApiMessageAndVersion record : records) { if (recordToMetadataVersion(record.message()).isPresent()) { versionRecord = record; } } if (versionRecord == ...
@Test public void testCopyWithOnlyVersion() { assertEquals(new BootstrapMetadata(SAMPLE_RECORDS1.subList(2, 3), IBP_3_3_IV2, "baz"), BootstrapMetadata.fromRecords(SAMPLE_RECORDS1, "baz").copyWithOnlyVersion()); }
public void notifyKvStateUnregistered( JobVertexID jobVertexId, KeyGroupRange keyGroupRange, String registrationName) { KvStateLocation location = lookupTable.get(registrationName); if (location != null) { // Duplicate name if vertex IDs don't match if (!location.ge...
@Test void testUnregisterBeforeRegister() throws Exception { ExecutionJobVertex vertex = createJobVertex(4); Map<JobVertexID, ExecutionJobVertex> vertexMap = createVertexMap(vertex); KvStateLocationRegistry registry = new KvStateLocationRegistry(new JobID(), vertexMap); assertThatTh...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final ReadOnlyWindowStore<GenericKey, ValueAndTime...
@Test public void shouldReturnValuesForClosedStartBounds() { // Given: final Range<Instant> start = Range.closed( NOW, NOW.plusSeconds(10) ); when(fetchIterator.hasNext()) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(fetchIterator.next()) ...
public static Integer parseRestBindPortFromWebInterfaceUrl(String webInterfaceUrl) { if (webInterfaceUrl != null) { final int lastColon = webInterfaceUrl.lastIndexOf(':'); if (lastColon == -1) { return -1; } else { try { re...
@Test void testParseRestBindPortFromWebInterfaceUrlWithValidPort() { assertThat(ResourceManagerUtils.parseRestBindPortFromWebInterfaceUrl("localhost:8080")) .isEqualTo(8080); }
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsNoneOf_primitiveDoubleArray_success() { assertThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsNoneOf(array(99.99, 999.999)); }
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final Map<String, Object> event; try { event = objectMapper.readValue(payload, TypeReferences.MAP_STRING_OBJECT); } catch (IOException e) { ...
@Test public void decodeMessagesHandlesGenericBeatWithDocker() throws Exception { final Message message = codec.decode(messageFromJson("generic-with-docker.json")); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("null"); assertThat(message.getSource()).is...