focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@VisibleForTesting static String summarize(byte[] value) { if (value.length * 2 <= MAX_DISPLAY_CHARACTERS) { return BaseEncoding.base16().encode(value); } return BaseEncoding.base16().encode(value, 0, PREFIX_SUFFIX_BYTES) + FILLER + BaseEncodin...
@Test public void testSummarize() { assertEquals(summarize(bytes()), ""); assertEquals(summarize(bytes(1)), "01"); assertEquals(summarize(bytes(255, 254, 253, 252, 251, 250, 249)), "FFFEFDFCFBFAF9"); assertEquals(summarize(bytes(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 249, 250, 251, 252, 2...
public Iterable<CounterUpdate> extractMsecCounters(boolean isFinalUpdate) { return executionStateRegistry.extractUpdates(isFinalUpdate); }
@Test public void extractMsecCounters() { BatchModeExecutionContext executionContext = BatchModeExecutionContext.forTesting(PipelineOptionsFactory.create(), "testStage"); MetricsContainer metricsContainer = Mockito.mock(MetricsContainer.class); ProfileScope profileScope = Mockito.mock(ProfileScop...
@Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement ) { return inject(statement, new TopicProperties.Builder()); }
@Test public void shouldHaveCleanupPolicyDeleteCreateStream() { // Given: givenStatement("CREATE STREAM x (FOO VARCHAR) WITH (kafka_topic='foo', partitions=1);"); // When: final CreateSource createSource = ((CreateSource) injector.inject(statement, builder).getStatement()); // Then: final Cr...
List<Endpoint> endpoints() { try { String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace); return enrichWithPublicAddresses(parsePodsList(callGet(urlString))); } catch (RestClientException e) { return handleKnownException(e); ...
@Test(expected = KubernetesClientException.class) public void endpointsFailFastWhenLbServiceHasNoPublicAddress() throws JsonProcessingException { // given kubernetesClient = newKubernetesClient(ExposeExternallyMode.ENABLED, false, null, null); stub(String.format("/api/v1/namespaces/%s/pods"...
public static BytesSchema of() { return INSTANCE; }
@Test public void testBytesSchemaOf() { testBytesSchema(BytesSchema.of()); }
@Udf public List<Long> generateSeriesLong( @UdfParameter(description = "The beginning of the series") final long start, @UdfParameter(description = "Marks the end of the series (inclusive)") final long end ) { return generateSeriesLong(start, end, end - start > 0 ? 1 : -1); }
@Test public void shouldThrowIfStepWrongSignLong2() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> rangeUdf.generateSeriesLong(9, 0, 1) ); // Then: assertThat(e.getMessage(), containsString( "GENERATE_SERIES step has wrong sign")); }
@Override public RefreshServiceAclsResponse refreshServiceAcls(RefreshServiceAclsRequest request) throws YarnException, IOException { // parameter verification. if (request == null) { routerMetrics.incrRefreshServiceAclsFailedRetrieved(); RouterServerUtil.logAndThrowException("Missing Refre...
@Test public void testSC1RefreshServiceAcls() throws Exception { // case 1, test the existing subCluster (SC-1). String existSubCluster = "SC-1"; RefreshServiceAclsRequest request = RefreshServiceAclsRequest.newInstance(existSubCluster); RefreshServiceAclsResponse response = interceptor.refreshService...
@Override public void shutdown() { if (server.started()) { server.stop(); } vertx.close(); }
@Test public void shouldCloseInners() { // When: checker.shutdown(); // Then: verify(server).stop(); verify(vertx).close(); }
public boolean hasAttribute(String key) { return attributes().containsKey(toKey(key)); }
@Test void hasAttribute() { final LDAPEntry entry = LDAPEntry.builder() .dn("cn=jane,ou=people,dc=example,dc=com") .base64UniqueId(Base64.encode("unique-id")) .addAttribute("zero", "0") .addAttribute("one", null) .build(); ...
@Override public void reset() { gaugeValue.set(GaugeData.empty()); dirty.reset(); }
@Test public void testReset() { GaugeCell gaugeCell = new GaugeCell(MetricName.named("namespace", "name")); gaugeCell.set(2); Assert.assertNotEquals(gaugeCell.getDirty(), new DirtyState()); assertThat(gaugeCell.getCumulative().value(), equalTo(GaugeData.create(2).value())); gaugeCell.reset(); ...
static Boolean orOperator(Boolean aBoolean, Boolean aBoolean2) { logger.trace("orOperator {} {}", aBoolean, aBoolean2); return aBoolean != null ? aBoolean || aBoolean2 : aBoolean2; }
@Test void orOperator() { Boolean aBoolean = null; boolean aBoolean2 = true; assertThat(KiePMMLCompoundPredicate.orOperator(aBoolean, aBoolean2)).isTrue(); aBoolean2 = false; assertThat(KiePMMLCompoundPredicate.orOperator(aBoolean, aBoolean2)).isFalse(); aBoolean = ...
public void validateUserCanReceivePushEventForProjectUuids(String userUuid, Set<String> projectUuids) { UserDto userDto; try (DbSession dbSession = dbClient.openSession(false)) { userDto = dbClient.userDao().selectByUuid(dbSession, userUuid); } if (userDto == null) { throw new ForbiddenExcep...
@Test public void validate_givenUserNotActivated_throwException() { UserDto userDto = new UserDto(); when(userDao.selectByUuid(any(), any())).thenReturn(userDto); when(userSession.isActive()).thenReturn(false); assertThrows(ForbiddenException.class, () -> underTest.validateUserCanReceivePushEve...
public RecordAppendResult append(String topic, int partition, long timestamp, byte[] key, byte[] value, Header[] headers, ...
@Test public void testUniformBuiltInPartitioner() throws Exception { mockRandom = new AtomicInteger(); long totalSize = 1024 * 1024; int batchSize = 1024; // note that this is also a "sticky" limit for the partitioner RecordAccumulator accum = createTestRecordAccumulator(batchSize...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testProcessElementWithOnTimerContextRejected() throws Exception { thrown.expect(IllegalArgumentException.class); // The message should at least mention @ProcessElement and OnTimerContext thrown.expectMessage("@" + DoFn.ProcessElement.class.getSimpleName()); thrown.expectMessage(DoFn....
public MediaType detect(InputStream stream, Metadata metadata) throws IOException { if (stream != null) { try { stream.mark(1); if (stream.read() == -1) { return MediaType.EMPTY; } } finally { stream.rese...
@Test public void testDetectZeroValue() { byte[] data = "".getBytes(UTF_8); detect(data, MediaType.EMPTY); }
static byte[] readPrivateKey(Path path) throws KeyException { final byte[] bytes; try { bytes = Files.readAllBytes(path); } catch (IOException e) { throw new KeyException("Couldn't read private key from file: " + path, e); } final String content = new Str...
@Test public void readPrivateKeyHandlesSecuredPrivateKey() throws Exception { final URL url = Resources.getResource("org/graylog2/shared/security/tls/key-enc-pbe1.p8"); final byte[] privateKey = PemReader.readPrivateKey(Paths.get(url.toURI())); assertThat(privateKey).isNotEmpty(); }
protected static String anonymizeLog(String log) { return log.replaceAll( "(/((home)|(Users))/[^/\n]*)|(\\\\Users\\\\[^\\\\\n]*)", "/ANONYMIZED_HOME_DIR"); // NOI18N }
@Test public void testAnonymizeUnixLog() { String log = "" + " System Locale; Encoding = en_GB (gephi); UTF-8\n" + " Home Directory = /home/mjackson\n" + " Current Directory = /home/mjackson/gephi/modules/application\n" + " U...
public void writeBytesDecreasing(byte[] value) { writeBytes(value, true); }
@Test public void testWriteBytesDecreasing() { byte[] first = {'a', 'b', 'c'}; byte[] second = {'d', 'e', 'f'}; byte[] last = {'x', 'y', 'z'}; OrderedCode orderedCode = new OrderedCode(); orderedCode.writeBytesDecreasing(first); byte[] firstEncoded = orderedCode.getEncodedBytes(); assertAr...
@Override public ExportResult<MediaContainerResource> export(UUID jobId, AD authData, Optional<ExportInformation> exportInfo) throws Exception { ExportResult<PhotosContainerResource> per = exportPhotos(jobId, authData, exportInfo); if (per.getThrowable().isPresent()) { return new ExportResult<>(pe...
@Test public void shouldHandleOnlyVideos() throws Exception { MediaContainerResource mcr = new MediaContainerResource(albums, null, videos); ExportResult<MediaContainerResource> exp = new ExportResult<>(ResultType.END, mcr); Optional<ExportInformation> ei = Optional.of(new ExportInformation(null, mcr)); ...
public HtmlCreator center(String text) { html.append("<center>").append(text).append("</center>"); return this; }
@Test public void testCenter() { htmlCreator.center("Hello"); Assert.assertEquals(true, htmlCreator.html().contains("<center>Hello</center>")); }
public StatementExecutorResponse execute( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext executionContext, final KsqlSecurityContext securityContext ) { final String commandRunnerWarningString = commandRunnerWarning.get(); if (!commandRunnerWarningString...
@Test public void shouldReturnCommandStatus() { // When: final CommandStatusEntity commandStatusEntity = (CommandStatusEntity) distributor.execute( CONFIGURED_STATEMENT, executionContext, securityContext ) .getEntity() .orElseThrow(nu...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testHybridShuffleModeInNonBatchMode() { Configuration configuration = new Configuration(); // set all edge to HYBRID_FULL result partition type. configuration.set( ExecutionOptions.BATCH_SHUFFLE_MODE, BatchShuffleMode.ALL_EXCHANGES_HYBRID_FULL); configurati...
public String ldapLogin(String userId, String userPwd) { Properties searchEnv = getManagerLdapEnv(); LdapContext ctx = null; try { // Connect to the LDAP server and Authenticate with a service user of whom we know the DN and credentials ctx = new InitialLdapContext(search...
@Test public void ldapLogin() throws NoSuchFieldException, IllegalAccessException { changeSslEnable(false); String email = ldapService.ldapLogin(username, correctPassword); Assertions.assertEquals("tesla@ldap.forumsys.com", email); }
@Override public final boolean offer(int ordinal, @Nonnull Object item) { if (ordinal == -1) { return offerInternal(allEdges, item); } else { if (ordinal == bucketCount()) { // ordinal beyond bucketCount will add to snapshot queue, which we don't allow through...
@Test public void when_offer2_then_rateLimited() { do_when_offer_then_rateLimited(e -> outbox.offer(0, e)); }
static String escapeAndJoin(List<String> parts) { return parts.stream() .map(ZetaSqlIdUtils::escapeSpecialChars) .map(ZetaSqlIdUtils::replaceWhitespaces) .map(ZetaSqlIdUtils::backtickIfNeeded) .collect(joining(".")); }
@Test public void testHandlesWhiteSpacesInOnePart() { List<String> id = Arrays.asList("a\nab\tbc\rcd\fd"); assertEquals("`a\\nab\\tbc\\rcd\\fd`", ZetaSqlIdUtils.escapeAndJoin(id)); }
@Override public boolean supportsTransactionIsolationLevel(final int level) { return false; }
@Test void assertSupportsTransactionIsolationLevel() { assertFalse(metaData.supportsTransactionIsolationLevel(0)); }
@Override public IcebergEnumeratorState snapshotState(long checkpointId) { return new IcebergEnumeratorState( enumeratorPosition.get(), assigner.state(), enumerationHistory.snapshot()); }
@Test public void testDiscoverWhenReaderRegistered() throws Exception { TestingSplitEnumeratorContext<IcebergSourceSplit> enumeratorContext = new TestingSplitEnumeratorContext<>(4); ScanContext scanContext = ScanContext.builder() .streaming(true) .startingStrategy(Strea...
public static void assertThatClassIsUtility(Class<?> clazz) { final UtilityClassChecker checker = new UtilityClassChecker(); if (!checker.isProperlyDefinedUtilityClass(clazz)) { final Description toDescription = new StringDescription(); final Description mismatchDescription = new...
@Test public void testOnlyOneConstructor() throws Exception { boolean gotException = false; try { assertThatClassIsUtility(TwoConstructors.class); } catch (AssertionError assertion) { assertThat(assertion.getMessage(), containsString("more than ...
public boolean acquire(final Object o) { if (Objects.isNull(o)) { throw new NullPointerException(); } if (memory.sum() >= memoryLimit) { return false; } acquireLock.lock(); try { final long sum = memory.sum(); final long obj...
@Test public void testAcquireWithTimeWaitNotRelease() throws InterruptedException { MemoryLimiter memoryLimiter = new MemoryLimiter(testObjectSize + 1, instrumentation); memoryLimiter.acquire(testObject); assertFalse(memoryLimiter.acquire(testObject, 1, TimeUnit.SECONDS)); }
@Override public Processor<K, Change<V>, K, Change<V>> get() { return new KTableReduceProcessor(); }
@Test public void shouldAddAndSubtract() { final InternalMockProcessorContext<String, Change<Set<String>>> context = new InternalMockProcessorContext<>(); final Processor<String, Change<Set<String>>, String, Change<Set<String>>> reduceProcessor = new KTableReduce<String, Set<String>>( ...
public static Slice truncateToLengthAndTrimSpaces(Slice slice, Type type) { requireNonNull(type, "type is null"); if (!isCharType(type)) { throw new IllegalArgumentException("type must be the instance of CharType"); } return truncateToLengthAndTrimSpaces(slice, CharType.c...
@Test public void testTruncateToLengthAndTrimSpaces() { assertEquals(utf8Slice("a"), truncateToLengthAndTrimSpaces(utf8Slice("a c"), 1)); assertEquals(utf8Slice("a"), truncateToLengthAndTrimSpaces(utf8Slice("a "), 1)); assertEquals(utf8Slice("a"), truncateToLengthAndTrimSpaces(utf8Slice...
public static String getSQLSelectString(PoiCategoryFilter filter, int count, LatLong orderBy) { StringBuilder sb = new StringBuilder(); sb.append(DbConstants.FIND_IN_BOX_CLAUSE_SELECT); sb.append(DbConstants.JOIN_CATEGORY_CLAUSE); sb.append(DbConstants.JOIN_DATA_CLAUSE); sb.appen...
@Test public void selectTwoFromBalancedHierarchy() throws UnknownPoiCategoryException { PoiCategoryFilter filter = new WhitelistPoiCategoryFilter(); filter.addCategory(this.balancedCm.getPoiCategoryByTitle("l1_1")); filter.addCategory(this.balancedCm.getPoiCategoryByTitle("l1_2")); ...
public void createMapping( String mappingName, String tableName, List<SqlColumnMetadata> mappingColumns, String dataConnectionRef, String idColumn ) { sqlService.execute( createMappingQuery(mappingName, tableName, mappingColumns, d...
@Test @SuppressWarnings("OperatorWrap") public void when_createMapping_then_escapeParameters() { mappingHelper.createMapping( "my\"Mapping", "my\"Table", singletonList(new SqlColumnMetadata("id\"", SqlColumnType.INTEGER, true)), "data\"Conn...
@Nullable public TrackerClient getTrackerClient(Request request, RequestContext requestContext, Ring<URI> ring, Map<URI, TrackerClient> trackerClients) { TrackerClient trackerClient; URI ...
@Test public void testGetTargetHost() { KeyMapper.TargetHostHints.setRequestContextTargetHost(_requestContext, URI_1); TrackerClient trackerClient = _clientSelector.getTrackerClient(_request, _requestContext, DEFAULT_RING, DEFAULT_TRACKER_CLIENT_MAP); assertEquals(trackerClient.getUri(), URI_1); }
@Override public RestResponse<KsqlEntityList> makeKsqlRequest( final URI serverEndPoint, final String sql, final Map<String, ?> requestProperties) { final KsqlTarget target = sharedClient .target(serverEndPoint); return getTarget(target) .postKsqlRequest(sql, requestProperti...
@Test public void shouldGetRightTraget() { // When: client.makeKsqlRequest(SERVER_ENDPOINT, "Sql", ImmutableMap.of()); // Then: verify(sharedClient).target(SERVER_ENDPOINT); }
public String anonymize(final ParseTree tree) { return build(tree); }
@Test public void printStatementsShouldGetAnonymized() { Assert.assertEquals("PRINT topic FROM BEGINNING;", anon.anonymize("PRINT my_topic FROM BEGINNING;")); Assert.assertEquals("PRINT topic INTERVAL '0';", anon.anonymize("PRINT my_topic INTERVAL 2;")); Assert.assertEquals("PRINT topic LI...
@Override public V poll(long timeout, TimeUnit unit) throws InterruptedException { return commandExecutor.getInterrupted(pollAsync(timeout, unit)); }
@Test public void testPollInterrupted() throws InterruptedException { final AtomicBoolean interrupted = new AtomicBoolean(); Thread t = new Thread() { public void run() { try { RBlockingQueue<Integer> queue1 = getQueue(redisson); ...
public static void closeAll(Closeable... closeables) throws IOException { IOException exception = null; for (Closeable closeable : closeables) { try { if (closeable != null) closeable.close(); } catch (IOException e) { if (excep...
@Test public void testCloseAll() { TestCloseable[] closeablesWithoutException = TestCloseable.createCloseables(false, false, false); try { Utils.closeAll(closeablesWithoutException); TestCloseable.checkClosed(closeablesWithoutException); } catch (IOException e) { ...
public void startAsync() { try { udfLoader.load(); ProcessingLogServerUtils.maybeCreateProcessingLogTopic( serviceContext.getTopicClient(), processingLogConfig, ksqlConfig); if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) { log.warn...
@Test public void shouldConfigureRocksDBConfigSetter() { // Given: givenQueryFileParsesTo(PREPARED_CSAS); when(sandBoxTopicInjector.inject(argThat(configured(equalTo(PREPARED_CSAS))))) .thenReturn((ConfiguredStatement) CSAS_CFG_WITH_TOPIC); // When: standaloneExecutor.startAsync(); /...
public static KeyFormat sanitizeKeyFormat( final KeyFormat keyFormat, final List<SqlType> newKeyColumnSqlTypes, final boolean allowKeyFormatChangeToSupportNewKeySchema ) { return sanitizeKeyFormatWrapping( !allowKeyFormatChangeToSupportNewKeySchema ? keyFormat : sanitizeKeyFormat...
@Test public void shouldConvertNoneFormatForSingleKeyWithNonPrimitiveType() { // Given: final KeyFormat format = KeyFormat.nonWindowed( FormatInfo.of(NoneFormat.NAME), SerdeFeatures.of()); // When: final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format, ImmutableLis...
public Schema getSchema() { return context.getSchema(); }
@Test public void testReversedOneOfSchema() { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(ReversedOneOf.getDescriptor()); Schema schema = schemaProvider.getSchema(); assertEquals(REVERSED_ONEOF_SCHEMA, schema); }
@Nullable public static <T> T checkSerializable(@Nullable T object, @Nonnull String objectName) { if (object == null) { return null; } if (object instanceof DataSerializable) { // hz-serialization is implemented, but we cannot actually check it - we don't have a ...
@Test public void whenSerializableObjectToCheckSerializable_thenReturnObject() { Object o = "o"; Object returned = Util.checkSerializable(o, "object"); assertThat(returned).isSameAs(o); }
@Override public List<TransferItem> list(final Session<?> session, final Path directory, final Local local, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory));...
@Test public void testList() throws Exception { Transfer t = new CopyTransfer(new Host(new TestProtocol()), new Host(new TestProtocol()), new HashMap<>(Collections.singletonMap( new Path("/s", EnumSet.of(Path.Type.directory)), new Path("/t", EnumSet.of(Path.Ty...
public static String serialize(Object object) { try { return Base64.getUrlEncoder() .encodeToString(OBJECT_MAPPER.writeValueAsBytes(object)); } catch (JsonProcessingException e) { throw new IllegalArgumentException("The given Json object value: " ...
@Test public void serializeDeserializeOAuth2AuthorizationRequestTest() { HttpCookieOAuth2AuthorizationRequestRepository cookieRequestRepo = new HttpCookieOAuth2AuthorizationRequestRepository(); HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); Map<String, Object> a...
@Override public boolean isValid(@Nullable String value, ConstraintValidatorContext context) { return value == null || !value.isEmpty(); }
@Test void isValid_shouldNotValidateEmptyString() { assertFalse(validator.isValid("", context)); }
public static int scanForGap( final UnsafeBuffer termBuffer, final int termId, final int termOffset, final int limitOffset, final GapHandler handler) { int offset = termOffset; do { final int frameLength = frameLengthVolatile(termBuffer, of...
@Test void shouldReportGapAtBeginningOfBuffer() { final int frameOffset = align(HEADER_LENGTH * 3, FRAME_ALIGNMENT); final int highWaterMark = frameOffset + align(HEADER_LENGTH, FRAME_ALIGNMENT); when(termBuffer.getIntVolatile(frameOffset)).thenReturn(HEADER_LENGTH); assertEqua...
@Override public boolean doesMaxRowSizeIncludeBlobs() { return false; }
@Test void assertDoesMaxRowSizeIncludeBlobs() { assertFalse(metaData.doesMaxRowSizeIncludeBlobs()); }
@PUT @Path("/{connector}/config") @Operation(summary = "Create or reconfigure the specified connector") public Response putConnectorConfig(final @PathParam("connector") String connector, final @Context HttpHeaders headers, final @...
@Test public void testPutConnectorConfig() throws Throwable { final ArgumentCaptor<Callback<Herder.Created<ConnectorInfo>>> cb = ArgumentCaptor.forClass(Callback.class); expectAndCallbackResult(cb, new Herder.Created<>(false, new ConnectorInfo(CONNECTOR_NAME, CONNECTOR_CONFIG, CONNECTOR_TASK_NAMES, ...
public static boolean isCoastedPoint(NopHit centerPoint) { CenterRadarHit crh = (CenterRadarHit) centerPoint.rawMessage(); return isCoastedRadarHit(crh); }
@Test public void testIsCoastedPoint() { NopHit notCoasted = new NopHit(NON_COASTED_RH); NopHit coasted = new NopHit(COASTED_RH); assertFalse(CenterSmoothing.isCoastedPoint(notCoasted)); assertTrue(CenterSmoothing.isCoastedPoint(coasted)); }
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Int_Metric() { MeasureDto measureDto = new MeasureDto().setValue(10d).setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_INT_METRIC); asse...
public static int toIntSize(long size) { assert size >= 0 : "Invalid size value: " + size; return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size; }
@Test public void toIntSize_whenEqualToIntMax() { long size = Integer.MAX_VALUE; assertEquals(Integer.MAX_VALUE, toIntSize(size)); }
public static String decompressZlib(byte[] compressedData) throws IOException { return decompressZlib(compressedData, Long.MAX_VALUE); }
@Test public void testDecompressZlib() throws IOException { final String testString = "Teststring 123"; final byte[] compressed = TestHelper.zlibCompress(testString); assertEquals(testString, Tools.decompressZlib(compressed)); }
@Override public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { refreshClassLoader(classLoader); }
@Test void testSerializable1() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig applicationConfig = new ApplicationConfig("Test"); applicationConfig.setCheckSerializable(false); appl...
@Override public T deserialize(final String topic, final byte[] data) { final List<?> values = inner.deserialize(topic, data); if (values == null) { return null; } SerdeUtils.throwOnColumnCountMismatch(numColumns, values.size(), false, topic); return factory.apply(values); }
@Test public void shouldDeserializeNulls() { // Given: when(innerDeserializer.deserialize(any(), any())).thenReturn(null); // When: final TestListWrapper result = deserializer.deserialize("topic", SERIALIZED); // Then: verify(innerDeserializer).deserialize("topic", SERIALIZED); assertTha...
@Override public boolean addAll(Collection<V> objects) { return get(addAllAsync(objects)); }
@Test public void testAddAll() { RHyperLogLog<Integer> log = redisson.getHyperLogLog("log"); log.addAll(Arrays.asList(1, 2, 3)); Assertions.assertEquals(3L, log.count()); }
public EdgeResult convertForViaWays(LongArrayList fromWays, LongArrayList viaWays, LongArrayList toWays) throws OSMRestrictionException { if (fromWays.isEmpty() || toWays.isEmpty() || viaWays.isEmpty()) throw new IllegalArgumentException("There must be at least one from-, via- and to-way"); ...
@Test void convertForViaWays_loop() { BaseGraph graph = new BaseGraph.Builder(1).create(); // 4 // | // 0-1-2 // |/ // 3 graph.edge(0, 1); graph.edge(1, 2); graph.edge(2, 3); graph.edge(3, 1); graph.edge(1, 4); L...
public static String getRamSign(String encryptText, String encryptKey) { try { String[] encryptData = encryptText.split(","); byte[] data = getProductSigningKey(encryptKey, LocalDateTime.ofEpochSecond(Long.parseLong(encryptData[2]) / 1000, 0, ZoneOffset.UTC).format(DT...
@Test public void testGetRamSign() { String encryptText = "testGroup,127.0.0.1,1702564471650"; String encryptKey = "exampleEncryptKey"; String expectedSign = "6g9nMk6BRLFxl7bf5ZfWaEZvGdho3JBmwvx5rqgSUCE="; String actualSign = RamSignAdapter.getRamSign(encryptText, encryptKey); ...
public <InputT, OutputT, CollectionT extends PCollection<? extends InputT>> DataStream<OutputT> applyBeamPTransform( DataStream<InputT> input, PTransform<CollectionT, PCollection<OutputT>> transform) { return (DataStream) getNonNull( applyBeamPTransformInternal( I...
@Test public void testApplyPreservesOutputTimestamps() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStream<Long> input = env.fromCollection(ImmutableList.of(1L, 2L, 12L)); Da...
@VisibleForTesting @Nullable Integer getUploadBufferSizeBytes() { return uploadBufferSizeBytes; }
@Test public void testUploadBufferSizeDefault() { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil util = pipelineOptions.getGcsUtil(); assertNull(util.getUploadBufferSizeBytes()); }
public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) { Optional<URI> externalUri = Optional.empty(); final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER); if (headers != null && !headers.isEmpty()) { ...
@Test public void buildExternalUriReturnsHeaderValueIfHeaderIsPresent() throws Exception { final MultivaluedMap<String, String> httpHeaders = new MultivaluedHashMap<>(); httpHeaders.putSingle(HttpConfiguration.OVERRIDE_HEADER, "http://header.example.com"); final URI externalUri = URI.create(...
@ScalarOperator(CAST) @SqlType(StandardTypes.SMALLINT) public static long castToSmallint(@SqlType(StandardTypes.TINYINT) long value) { return value; }
@Test public void testCastToSmallint() { assertFunction("cast(TINYINT'37' as smallint)", SMALLINT, (short) 37); assertFunction("cast(TINYINT'17' as smallint)", SMALLINT, (short) 17); }
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = trees.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = b; for (int i...
@Test public void testCalHousingHuber() { test(Loss.huber(0.9), "cal_housing", CalHousing.formula, CalHousing.data, 62090.2639); }
@Override public IndexSpec getIndexSpec(String indexName) { return this.indexSpecs.get(indexName); }
@Test void getIndexSpec() { var specs = new DefaultIndexSpecs(); var nameSpec = primaryKeyIndexSpec(FakeExtension.class); specs.add(nameSpec); assertThat(specs.getIndexSpec(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isEqualTo(nameSpec); }
public <T> T parse(String input, Class<T> cls) { return readFlow(input, cls, type(cls)); }
@Test void listeners() { ConstraintViolationException exception = assertThrows( ConstraintViolationException.class, () -> modelValidator.validate(this.parse("flows/invalids/listener.yaml")) ); assertThat(exception.getConstraintViolations().size(), is(2)); ass...
@GetMapping("/queryRootTag") public ShenyuAdminResult queryRootTag() { return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, tagService.findByParentTagId("0")); }
@Test public void testQueryRootTag() throws Exception { List<TagVO> tagVOS = new ArrayList<>(); given(tagService.findByParentTagId("0")).willReturn(tagVOS); this.mockMvc.perform(MockMvcRequestBuilders.get("/tag/queryRootTag")) .andExpect(status().isOk()) .andE...
@Override public void ensureValid(String name, Object value) { if (value == null || ((List) value).isEmpty()) { throw new ConfigException(name, value, "Empty list"); } }
@Test public void testEmptyList() { assertThrows(ConfigException.class, () -> new NonEmptyListValidator().ensureValid("foo", Collections.emptyList())); }
public DefaultIssue setStatus(String s) { Preconditions.checkArgument(!Strings.isNullOrEmpty(s), "Status must be set"); this.status = s; return this; }
@Test void fail_on_empty_status() { try { issue.setStatus(""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Status must be set"); } }
static byte eightBitCharacter(final String asciiCharacter) { Verify.notNull(asciiCharacter, "asciiCharacter"); final byte[] bytes = asciiCharacter.getBytes(StandardCharsets.US_ASCII); if (bytes.length != 1) { throw new IllegalArgumentException( "String val...
@Test void happyPathEightBitCharacter() { final byte aByte = RustUtil.eightBitCharacter("a"); assertEquals('a', (char)aByte); assertEquals("97", Byte.toString(aByte)); }
public static Socket acceptWithoutTimeout(ServerSocket serverSocket) throws IOException { Preconditions.checkArgument( serverSocket.getSoTimeout() == 0, "serverSocket SO_TIMEOUT option must be 0"); while (true) { try { return serverSocket.accept(); ...
@Test void testAcceptWithoutTimeoutZeroTimeout() throws IOException { // Explicitly sets a timeout of zero final Socket expected = new Socket(); try (final ServerSocket serverSocket = new ServerSocket(0) { @Override public Socket accept...
@Override public Endpoint<Http2LocalFlowController> local() { return localEndpoint; }
@Test public void newStreamBehindExpectedShouldThrow() throws Http2Exception { assertThrows(Http2Exception.class, new Executable() { @Override public void execute() throws Throwable { server.local().createStream(0, true); } }); }
boolean isSqlMonitoringDisabled() { return isMonitoringDisabled() || !sqlCounter.isDisplayed(); }
@Test public void testIsSqlMonitoringDisabled() { Utils.setProperty(Parameter.DISABLED, "false"); jdbcWrapper.getSqlCounter().setDisplayed(true); assertFalse("isSqlMonitoringDisabled1", jdbcWrapper.isSqlMonitoringDisabled()); Utils.setProperty(Parameter.DISABLED, "true"); assertTrue("isSqlMonitoringDisabled2...
@Override public int getRemainingQueueCapacity() { return taskQ.remainingCapacity(); }
@Test public void getRemainingQueueCapacity_whenNoTasksSubmitted() { int queueSize = 123; assertEquals(queueSize, newManagedExecutorService(1, queueSize).getRemainingQueueCapacity()); }
@Override public boolean apply(Collection<Member> members) { if (members.size() < minimumClusterSize) { return false; } int count = 0; long timestamp = Clock.currentTimeMillis(); for (Member member : members) { if (!isAlivePerIcmp(member)) { ...
@Test public void testSplitBrainProtectionAbsent_whenIcmpAlive_andFewerThanSplitBrainProtectionPresent() { splitBrainProtectionFunction = new ProbabilisticSplitBrainProtectionFunction(splitBrainProtectionSize, 10000, 10000, 200, 100, 10); prepareSplitBrainProtectionFunctionForIcmpFDTest(splitBrainPr...
@GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); }
@Test public void getAllPostsWillBeOk() throws Exception { this.rest .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final AttributedList<Path> children = new AttributedList<Path>(); try (RemoteDirectory handle = session.sftp().openDir(directory.getAbsolute())) { for(List<R...
@Test(expected = NotfoundException.class) public void testListFile() throws Exception { final Path home = new SFTPHomeDirectoryService(session).find(); final Path f = new Path(home, "test", EnumSet.of(Path.Type.directory)); final SFTPListService service = new SFTPListService(session); ...
public final void doesNotContain(@Nullable Object element) { if (Iterables.contains(checkNotNull(actual), element)) { failWithActual("expected not to contain", element); } }
@Test public void iterableDoesNotContainFailure() { expectFailureWhenTestingThat(asList(1, 2, 3)).doesNotContain(2); assertFailureKeys("expected not to contain", "but was"); assertFailureValue("expected not to contain", "2"); }
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void loadingErrorFabric() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/crash-report/loading_error_fabric.txt")), CrashReportAnalyzer.Rule.LOADING_CRASHED_FABRIC); assertEquals("test", res...
public Order complete(Boolean complete) { this.complete = complete; return this; }
@Test public void completeTest() { // TODO: test complete }
@Asn1ObjectIdentifier("2.16.528.1.1003.10.9.1") @Asn1Property(order = 71) public PolymorphicInfo getPolymorphicInfo() { return polymorphicInfo; }
@Test public void testEfCardAccess() { final PcaSecurityInfos result = mapper.read(efCardAccess, PcaSecurityInfos.class); assertEquals(1, result.getPolymorphicInfo().getPcaVersion()); assertEquals(0x6c, result.getPolymorphicInfo().getFlags().intValue()); }
public DiscardObject markAsDiscardedOnShutdown(JobStatus jobStatus) { return shouldBeDiscardedOnShutdown(jobStatus) ? markAsDiscarded() : NOOP_DISCARD_OBJECT; }
@Test void testCleanUpOnShutdown() throws Exception { JobStatus[] terminalStates = new JobStatus[] { JobStatus.FINISHED, JobStatus.CANCELED, JobStatus.FAILED, JobStatus.SUSPENDED }; for (JobStatus status : terminalStates) { OperatorSt...
public DefaultHeaders<K, V, T> copy() { DefaultHeaders<K, V, T> copy = new DefaultHeaders<K, V, T>( hashingStrategy, valueConverter, nameValidator, entries.length); copy.addImpl(this); return copy; }
@Test public void testCopy() throws Exception { TestDefaultHeaders headers = newInstance(); headers.addBoolean(of("boolean"), true); headers.addLong(of("long"), Long.MAX_VALUE); headers.addInt(of("int"), Integer.MIN_VALUE); headers.addShort(of("short"), Short.MAX_VALUE); ...
@Override public DataSourceProvenance getProvenance() { return new AggregateDataSourceProvenance(this); }
@Test public void testADSIterationOrder() { MockOutputFactory factory = new MockOutputFactory(); String[] featureNames = new String[] {"X1","X2"}; double[] featureValues = new double[] {1.0, 2.0}; List<Example<MockOutput>> first = new ArrayList<>(); first.add(new ArrayExampl...
@Override public ShardingTableRuleConfiguration swapToObject(final YamlTableRuleConfiguration yamlConfig) { ShardingSpherePreconditions.checkNotNull(yamlConfig.getLogicTable(), () -> new MissingRequiredShardingConfigurationException("Sharding Logic table")); ShardingTableRuleConfiguration result = n...
@Test void assertSwapToObject() { YamlShardingTableRuleConfigurationSwapper swapper = new YamlShardingTableRuleConfigurationSwapper(); ShardingTableRuleConfiguration actual = swapper.swapToObject(createYamlTableRuleConfiguration()); assertThat(actual.getDatabaseShardingStrategy().getSharding...
public void addPackageDescr(Resource resource, PackageDescr packageDescr) { if (!getNamespace().equals(packageDescr.getNamespace())) { throw new RuntimeException("Composing PackageDescr (" + packageDescr.getName() + ") in different namespaces (namespace=" + getNamespace() ...
@Test(expected = RuntimeException.class) public void addPackageDescrDifferentPkgUUID() { String pkgUUID = generateUUID(); PackageDescr first = new PackageDescr(NAMESPACE); first.setPreferredPkgUUID(pkgUUID); assertThat(first.getPreferredPkgUUID().isPresent()).isTrue(); compos...
public ClientTelemetrySender telemetrySender() { return clientTelemetrySender; }
@Test public void testCreateRequestInvalidState() { ClientTelemetryReporter.DefaultClientTelemetrySender telemetrySender = (ClientTelemetryReporter.DefaultClientTelemetrySender) clientTelemetryReporter.telemetrySender(); telemetrySender.updateSubscriptionResult(subscription, time.milliseconds()); ...
public static int hash32(byte[] data) { int len = data.length; if (len <= 24) { return len <= 12 ? (len <= 4 ? hash32Len0to4(data) : hash32Len5to12(data)) : hash32Len13to24(data); } // len > 24 int h = len, g = c1 * len, f = g; int a0 = rotate32(fetch32(data, len - 4) * c1, 17) * c2; int a1 ...
@Test public void hash32Test() { int hv = CityHash.hash32(StrUtil.utf8Bytes("你")); assertEquals(1290029860, hv); hv = CityHash.hash32(StrUtil.utf8Bytes("你好")); assertEquals(1374181357, hv); hv = CityHash.hash32(StrUtil.utf8Bytes("见到你很高兴")); assertEquals(1475516842, hv); hv = CityHash.hash32(StrUtil.utf...
@Override public AppResponse process(Flow flow, ActivateWithCodeRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException { Map<String, Object> result = digidClient.activateAccountWithCode(appSession.getAccountId(), request.getActivationCode()); if (result.get(lowerUnd...
@Test public void responseNotCorrectTest() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException { //given when(digidClientMock.activateAccountWithCode(anyLong(), any())).thenReturn(Map.of( lowerUnderscore(STATUS), "NOK", lowerUnderscore(ERROR), "activation_co...
@Override protected Drive connect(final ProxyFinder proxy, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws HostParserException, ConnectionCanceledException { final HttpClientBuilder configuration = builder.build(proxy, this, prompt); authorizationServi...
@Test public void testConnect() throws Exception { assertTrue(session.isConnected()); session.close(); assertFalse(session.isConnected()); }
public static ByteBuf copyFloat(float value) { ByteBuf buf = buffer(4); buf.writeFloat(value); return buf; }
@Test public void testWrapSingleFloat() { ByteBuf buffer = copyFloat(42); assertEquals(4, buffer.capacity()); assertEquals(42, buffer.readFloat(), 0.01); assertFalse(buffer.isReadable()); buffer.release(); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QueryEntry that = (QueryEntry) o; if (!key.equals(that.key)) { return false; } ...
@Test @SuppressWarnings("EqualsWithItself") public void test_equality_same() { QueryableEntry entry = createEntry(); assertTrue(entry.equals(entry)); }
public List<KiePMMLDroolsType> declareTypes(final List<DerivedField> derivedFields) { return derivedFields.stream().map(this::declareType).collect(Collectors.toList()); }
@Test void declareTypes() { List<DerivedField> derivedFields = IntStream.range(0, 5) .mapToObj(value -> getDerivedField("FieldName-" + value)) .collect(Collectors.toList()); List<KiePMMLDroolsType> retrieved = fieldASTFactory.declareTypes(derivedFields); asser...
@Override protected Map<String, Object> toJsonMap(ILoggingEvent event) { final MapBuilder mapBuilder = new MapBuilder(timestampFormatter, customFieldNames, additionalFields, includes.size()) .addTimestamp("timestamp", isIncluded(EventAttribute.TIMESTAMP), event.getTimeStamp()) .add("...
@Test void testProducesDefaultMap() { Map<String, Object> map = eventJsonLayout.toJsonMap(event); final HashMap<String, Object> expectedFields = new HashMap<>(defaultExpectedFields); assertThat(map).isEqualTo(expectedFields); }
public static boolean prefixEquals(ChannelBuffer bufferA, ChannelBuffer bufferB, int count) { final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); if (aLen < count || bLen < count) { return false; } int aIndex = bufferA.readerIndex(); ...
@Test void testPrefixEquals() { ChannelBuffer bufA = ChannelBuffers.wrappedBuffer("abcedfaf".getBytes()); ChannelBuffer bufB = ChannelBuffers.wrappedBuffer("abcedfaa".getBytes()); Assertions.assertTrue(ChannelBuffers.equals(bufA, bufB)); Assertions.assertTrue(ChannelBuffers.prefixEqu...
@Override public PostgreSQLIdentifierTag getIdentifier() { return PostgreSQLMessagePacketType.ROW_DESCRIPTION; }
@Test void assertGetIdentifier() { PostgreSQLRowDescriptionPacket packet = new PostgreSQLRowDescriptionPacket(Collections.emptyList()); assertThat(packet.getIdentifier(), is(PostgreSQLMessagePacketType.ROW_DESCRIPTION)); }
@Override public Set<K8sNode> completeNodes() { Set<K8sNode> nodes = nodeStore.nodes().stream() .filter(node -> node.state() == COMPLETE) .collect(Collectors.toSet()); return ImmutableSet.copyOf(nodes); }
@Test public void testGetCompleteNodes() { assertEquals(ERR_SIZE, 1, target.completeNodes().size()); assertTrue(ERR_NOT_FOUND, target.completeNodes().contains(MINION_3)); }
public < M extends MessageHeaders<EmptyRequestBody, P, EmptyMessageParameters>, P extends ResponseBody> CompletableFuture<P> sendRequest(String targetAddress, int targetPort, M messageHeaders) throws IOException { return sendRequest( ...
@Test void testConnectionClosedHandling() throws Exception { final Configuration config = new Configuration(); config.set(RestOptions.IDLENESS_TIMEOUT, Duration.ofMillis(5000L)); try (final ServerSocket serverSocket = new ServerSocket(0); final RestClient restClient = ...
@Override public ValidationTaskResult validateImpl(Map<String, String> optionMap) { // Skip this test if NOSASL if (mConf.get(PropertyKey.SECURITY_AUTHENTICATION_TYPE) .equals(AuthType.NOSASL)) { return new ValidationTaskResult(ValidationUtils.State.SKIPPED, getName(), String.f...
@Test public void skipped() { mConf.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL); HdfsProxyUserValidationTask task = new HdfsProxyUserValidationTask("hdfs://namenode:9000/alluxio", mConf); ValidationTaskResult result = task.validateImpl(ImmutableMap.of()); assertEquals(Va...
long importPhotos( Collection<PhotoModel> photos, GPhotosUpload gPhotosUpload) throws Exception { return gPhotosUpload.uploadItemsViaBatching( photos, this::importPhotoBatch); }
@Test public void importTwoPhotosWithFailure() throws Exception { PhotoModel photoModel1 = new PhotoModel( PHOTO_TITLE, IMG_URI, PHOTO_DESCRIPTION, JPEG_MEDIA_TYPE, "oldPhotoID1", OLD_ALBUM_ID, false); PhotoModel photo...
public int validate( final ServiceContext serviceContext, final List<ParsedStatement> statements, final SessionProperties sessionProperties, final String sql ) { requireSandbox(serviceContext); final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext)); ...
@Test public void shouldThrowIfSnapshotSupplierReturnsNonSandbox() { // Given: executionContext = mock(KsqlExecutionContext.class); givenRequestValidator(ImmutableMap.of()); // When: final Exception e = assertThrows( IllegalArgumentException.class, () -> validator.validate(service...
@Override public boolean supports(Job job) { JobDetails jobDetails = job.getJobDetails(); return !jobDetails.hasStaticFieldName() && Modifier.isStatic(getJobMethod(jobDetails).getModifiers()); }
@Test void supportsJobIfJobClassHasPrivateConstructorButStaticJobMethod() { Job job = anEnqueuedJob() .withJobDetails(() -> TestServiceForIoC.doWorkInStaticMethod(UUID.randomUUID())) .build(); assertThat(backgroundStaticJobWithoutIocRunner.supports(job)).isTrue(); ...