focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public long getSplitBacklogBytes() { // Safety check in case a progress check is made for the start method is called. if (shardReadersPool == null) { return UnboundedReader.BACKLOG_UNKNOWN; } Instant latestRecordTimestamp = shardReadersPool.getLatestRecordTimestamp(); if (latestR...
@Test public void getSplitBacklogBytesShouldReturnUnknownIfNotStarted() { assertThat(reader.getSplitBacklogBytes()).isEqualTo(UnboundedReader.BACKLOG_UNKNOWN); }
public static String variablesToGetParamValue(final String variables) { return StringUtils.trimToNull(variables); }
@Test void testVariablesToGetParamValue() throws Exception { assertEquals(OBJECT_MAPPER.readTree(EXPECTED_VARIABLES_GET_PARAM_VALUE), OBJECT_MAPPER.readTree(GraphQLRequestParamUtils.variablesToGetParamValue(params.getVariables()))); }
@Override public boolean remove(Object o) { return underlying.remove(o); }
@Test public void testRemove() { BoundedList<String> list = BoundedList.newArrayBacked(3); list.add("a"); list.add("a"); list.add("c"); assertEquals(0, list.indexOf("a")); assertEquals(1, list.lastIndexOf("a")); list.remove("a"); assertEquals(Arrays.as...
public static <T> T deserialize(CustomObject customObject) { return (T) SER_DES[customObject.getType()].deserialize(customObject.getBuffer()); }
@Test public void testHyperLogLogDeserializeThrowsForSizeMismatch() throws Exception { // We serialize a HLL w/ log2m of 12 and then trim 1024 bytes from the end of it and try to deserialize it. An // exception should occur because 2732 bytes are expected after the headers, but instead it will only find...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testWrongOutputReceiverType() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("OutputReceiver should be parameterized by java.lang.String"); DoFnSignatures.getSignature( new DoFn<String, String>() { @ProcessElement public...
public static Comparator<StructLike> forType(Types.StructType struct) { return new StructLikeComparator(struct); }
@Test public void testTimestamp() { assertComparesCorrectly(Comparators.forType(Types.TimestampType.withoutZone()), 111, 222); assertComparesCorrectly(Comparators.forType(Types.TimestampType.withZone()), 111, 222); }
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testErasureCodingPolicy() throws Exception { createHttpFSServer(false, false); final String dir = "/ecPolicy"; Path path1 = new Path(dir); final ErasureCodingPolicy ecPolicy = SystemErasureCodingPolicies .getByID(SystemErasureCodingPolicies...
public boolean isEmpty() { return username() == null && password() == null && privateKey() == null && passPhrase() == null; }
@Test public void isEmpty_givenAllNotNullProperties_returnFalse() { MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE)); settings.setProperty("sonar.svn.username", "bob"); settings.setProperty("sonar.svn.privateKeyPath", "bob"); settings.setProperty("sonar.svn.passphrase....
@VisibleForTesting Set<? extends Watcher> getEntries() { return Sets.newHashSet(entries); }
@Test public void testTriggered() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorF...
public CodegenTableDO buildTable(TableInfo tableInfo) { CodegenTableDO table = CodegenConvert.INSTANCE.convert(tableInfo); initTableDefault(table); return table; }
@Test public void testBuildTable() { // 准备参数 TableInfo tableInfo = mock(TableInfo.class); // mock 方法 when(tableInfo.getName()).thenReturn("system_user"); when(tableInfo.getComment()).thenReturn("用户"); // 调用 CodegenTableDO table = codegenBuilder.buildTable(tab...
public void clear() { filter_.clear(); }
@Ignore @Test public void timeit() { int size = 300 * FilterTest.ELEMENTS; bf = new BloomFilter(size, FilterTest.spec.bucketsPerElement); for (int i = 0; i < 10; i++) { FilterTest.testFalsePositives(bf, new KeyGenerator.RandomStringGenerator(new Random().n...
public void clear() { map.clear(); }
@Test public void testClear() { map.put("foo", () -> "foovalue"); map.put("bar", () -> "foovalue2"); map.put("baz", () -> "foovalue3"); map.clear(); assertEquals(0, map.size()); }
@Override public boolean canHandleReturnType(Class returnType) { return (Flux.class.isAssignableFrom(returnType)) || (Mono.class .isAssignableFrom(returnType)); }
@Test public void testCheckTypes() { assertThat(reactorRetryAspectExt.canHandleReturnType(Mono.class)).isTrue(); assertThat(reactorRetryAspectExt.canHandleReturnType(Flux.class)).isTrue(); }
public IsJson(Matcher<? super ReadContext> jsonMatcher) { this.jsonMatcher = jsonMatcher; }
@Test public void shouldDescribeMismatchOfInvalidJson() { Matcher<Object> matcher = isJson(withPathEvaluatedTo(true)); Description description = new StringDescription(); matcher.describeMismatch("invalid-json", description); assertThat(description.toString(), containsString("\"invali...
Double calculateAverage(List<Double> durationEntries) { double sum = 0.0; for (Double duration : durationEntries) { sum = sum + duration; } if (sum == 0) { return 0.0; } return sum / durationEntries.size(); }
@Test void calculateAverageOfEmptylist() { OutputStream out = new ByteArrayOutputStream(); UsageFormatter usageFormatter = new UsageFormatter(out); Double result = usageFormatter.calculateAverage(Collections.emptyList()); assertThat(result, is(equalTo(0.0))); }
public void logAddress(final DriverEventCode code, final InetSocketAddress address) { final int length = socketAddressLength(address); final int captureLength = captureLength(length); final int encodedLength = encodedLength(captureLength); final ManyToOneRingBuffer ringBuffer = this...
@Test void logAddress() { final int recordOffset = 64; logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset); final DriverEventCode eventCode = NAME_RESOLUTION_NEIGHBOR_REMOVED; final int captureLength = 12; logger.logAddress(eventCode, new InetSocketAddress("...
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) { final Map<Transformation<?>, Set<Transformation<?>>> outputMap = buildOutputMap(transformations); final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>(); fina...
@Test void testChainingNonKeyedOperators() { ExternalPythonProcessOperator<?, ?> processOperator1 = createProcessOperator( "f1", new RowTypeInfo(Types.INT(), Types.INT()), Types.STRING()); ExternalPythonProcessOperator<?, ?> processOperator2 = ...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new ...
@Test public void decodeMessagesHandlesGenericBeatWithCloudTencent() throws Exception { final Message message = codec.decode(messageFromJson("generic-with-cloud-tencent.json")); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("-"); assertThat(message.getSo...
public synchronized Counter findCounter(String group, String name) { if (name.equals("MAP_INPUT_BYTES")) { LOG.warn("Counter name MAP_INPUT_BYTES is deprecated. " + "Use FileInputFormatCounters as group name and " + " BYTES_READ as counter name instead"); return findCounter...
@SuppressWarnings("deprecation") @Test public void testCounterValue() { Counters counters = new Counters(); final int NUMBER_TESTS = 100; final int NUMBER_INC = 10; final Random rand = new Random(); for (int i = 0; i < NUMBER_TESTS; i++) { long initValue = rand.nextInt(); long expect...
public static void deleteIfExists(final File file) { try { Files.deleteIfExists(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
@Test void deleteIfExistsErrorHandlerEmptyDirectory() throws IOException { final ErrorHandler errorHandler = mock(ErrorHandler.class); final Path dir = tempDir.resolve("dir"); Files.createDirectory(dir); IoUtil.deleteIfExists(dir.toFile(), errorHandler); assertFalse(Fil...
@ScalarOperator(GREATER_THAN_OR_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThanOrEqual(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right) { return left || !right; }
@Test public void testGreaterThanOrEqual() { assertFunction("true >= true", BOOLEAN, true); assertFunction("true >= false", BOOLEAN, true); assertFunction("false >= true", BOOLEAN, false); assertFunction("false >= false", BOOLEAN, true); }
@VisibleForTesting WxMaService getWxMaService(Integer userType) { // 第一步,查询 DB 的配置项,获得对应的 WxMaService 对象 SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType( SocialTypeEnum.WECHAT_MINI_APP.getType(), userType); if (client != null && Objects.equals(client....
@Test public void testGetWxMaService_clientEnable() { // 准备参数 Integer userType = randomPojo(UserTypeEnum.class).getValue(); // mock 数据 SocialClientDO client = randomPojo(SocialClientDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()) .setUserType(userType)...
@Override public void open() throws Exception { super.open(); final String operatorID = getRuntimeContext().getOperatorUniqueID(); this.workerPool = ThreadPools.newWorkerPool("iceberg-worker-pool-" + operatorID, workerPoolSize); }
@TestTemplate public void testMaxContinuousEmptyCommits() throws Exception { table.updateProperties().set(MAX_CONTINUOUS_EMPTY_COMMITS, "3").commit(); JobID jobId = new JobID(); long checkpointId = 0; long timestamp = 0; try (OneInputStreamOperatorTestHarness<WriteResult, Void> harness = createSt...
@Override public Class<QGChangeNotification> getNotificationClass() { return QGChangeNotification.class; }
@Test public void getNotificationClass_is_QGChangeNotification() { assertThat(underTest.getNotificationClass()).isEqualTo(QGChangeNotification.class); }
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/...
@Test public void longlivedTransferJwt() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("etransfer.r", "etransfer.w"), "user"); claims.setExpirationTimeMinutesInTheFuture(5256000); String jwt = JwtIssu...
@Override public boolean hasAgent(String uuid) { return agents.stream().anyMatch(agent -> agent.hasUuid(uuid)); }
@Test void shouldReturnFalseIfEnvDoesNotContainTheSpecifiedAgentUuid() { assertThat(this.environmentConfig.hasAgent("uuid")).isFalse(); }
@Override public Set<ApplicationId> getAppIds() { return ImmutableSet.copyOf(registeredIds.asJavaMap().values()); }
@Test(expected = NullPointerException.class) public void testEmpty() { idStore = new DistributedApplicationIdStore(); idStore.getAppIds(); }
public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs);
@Test public void shouldSetCreateTimeByDefaultForWindowedChangelog() { final WindowedChangelogTopicConfig topicConfig = new WindowedChangelogTopicConfig("name", Collections.emptyMap(), 10); final Map<String, String> properties = topicConfig.properties(Collections.emptyMap(), 0); assertEqual...
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 updateAdSessionInvalid() { HashMap<String, Object> body = new HashMap<>(); body.put("authentication_level", 1); body.put("authentication_status", "Pending"); body.put("bsn", "PPPPPPP"); AdValidationException exception = assertThrows(AdValidationException.cl...
@Override public RLock readLock() { return new RedissonReadLock(commandExecutor, getName()); }
@Test public void testReadLockExpirationRenewal() throws InterruptedException { int threadCount = 50; ExecutorService executorService = Executors.newFixedThreadPool(threadCount/5); AtomicInteger exceptions = new AtomicInteger(); for (int i=0; i<threadCount; i++) { execu...
@Override protected String buildUndoSQL() { TableRecords beforeImage = sqlUndoLog.getBeforeImage(); List<Row> beforeImageRows = beforeImage.getRows(); if (CollectionUtils.isEmpty(beforeImageRows)) { throw new ShouldNeverHappenException("Invalid UNDO LOG"); } Row r...
@Test public void buildUndoSQL() { OracleUndoDeleteExecutor executor = upperCase(); String sql = executor.buildUndoSQL(); Assertions.assertNotNull(sql); Assertions.assertTrue(sql.contains("INSERT")); Assertions.assertTrue(sql.contains("ID")); Assertions.assertTrue(sq...
@Override public void getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); }
@Test void getByteArrayBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, new byte[0])); }
static KiePMMLNormContinuous getKiePMMLNormContinuous(final NormContinuous normContinuous) { final List<KiePMMLLinearNorm> linearNorms = normContinuous.hasLinearNorms() ? getKiePMMLLinearNorms(normContinuous.getLinearNorms()) : Collections.emptyList(); final OUTLIER_TREATMENT_METHOD outl...
@Test void getKiePMMLNormContinuous() { final NormContinuous toConvert = getRandomNormContinuous(); final KiePMMLNormContinuous retrieved = KiePMMLNormContinuousInstanceFactory.getKiePMMLNormContinuous(toConvert); commonVerifyKiePMMLNormContinuous(retrieved, toConvert); }
@Override public Map<String, Long> call() throws Exception { Map<String, Long> result = new LinkedHashMap<>(); for (DownloadableItem item : items) { InputStreamWrapper stream = connectionProvider.getInputStreamForItem(jobId, item); long size = stream.getBytes(); if (size <= 0) { size...
@Test public void testSizeIsNotProvided() throws Exception { DownloadableItem item = createItem("1-" + nextInt(100, 9999)); int size = nextInt(1, 1024 * 1024 * 42); // 42MB max byte[] bytes = new byte[size]; Arrays.fill(bytes, (byte) 0); InputStream inputStream = new ByteArrayInputStream(bytes); ...
public static IntArrayList permutation(int size, Random rnd) { IntArrayList result = iota(size); shuffle(result, rnd); return result; }
@Test public void testPermutation() { IntArrayList list = ArrayUtil.permutation(15, new Random()); assertEquals(15, list.buffer.length); assertEquals(15, list.elementsCount); assertEquals(14 / 2.0 * (14 + 1), Arrays.stream(list.buffer).sum()); assertTrue(ArrayUtil.isPermutati...
public Future<Collection<Integer>> resizeAndReconcilePvcs(KafkaStatus kafkaStatus, List<PersistentVolumeClaim> pvcs) { Set<Integer> podIdsToRestart = new HashSet<>(); List<Future<Void>> futures = new ArrayList<>(pvcs.size()); for (PersistentVolumeClaim desiredPvc : pvcs) { Future<V...
@Test public void testVolumesBoundWithoutStorageClass(VertxTestContext context) { List<PersistentVolumeClaim> pvcs = List.of( createPvc("data-pod-0"), createPvc("data-pod-1"), createPvc("data-pod-2") ); ResourceOperatorSupplier supplier = Res...
public static Node build(final List<JoinInfo> joins) { Node root = null; for (final JoinInfo join : joins) { if (root == null) { root = new Leaf(join.getLeftSource()); } if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) { throw new K...
@Test public void shouldIgnoreOuterJoinsWhenComputingEquivalenceSets() { // Given: when(j1.getLeftSource()).thenReturn(a); when(j1.getRightSource()).thenReturn(b); when(j2.getLeftSource()).thenReturn(a); when(j2.getRightSource()).thenReturn(c); when(j1.getType()).thenReturn(JoinType.OUTER); ...
@Nullable static String lastStringHeader(Headers headers, String key) { Header header = headers.lastHeader(key); if (header == null || header.value() == null) return null; return new String(header.value(), UTF_8); }
@Test void lastStringHeader_null() { assertThat(KafkaHeaders.lastStringHeader(record.headers(), "b3")).isNull(); }
@Override public int getInt(final int columnIndex) throws SQLException { return (int) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, int.class), int.class); }
@Test void assertGetIntWithColumnIndex() throws SQLException { when(mergeResultSet.getValue(1, int.class)).thenReturn(1); assertThat(shardingSphereResultSet.getInt(1), is(1)); }
public static String toHexStringNoPrefix(BigInteger value) { return value.toString(16); }
@Test public void testToHexStringNoPrefix() { assertEquals(Numeric.toHexStringNoPrefix(BigInteger.TEN), ("a")); }
@Override public long getStartTs() { return _startTs; }
@Test public void testGetStartTs() { MinionProgressObserver observer = new MinionProgressObserver(3); long ts1 = System.currentTimeMillis(); observer.notifyTaskStart(null); long ts = observer.getStartTs(); long ts2 = System.currentTimeMillis(); assertTrue(ts1 <= ts); assertTrue(ts2 >= ts);...
@Description("encode binary data as hex") @ScalarFunction @SqlType(StandardTypes.VARCHAR) public static Slice toHex(@SqlType(StandardTypes.VARBINARY) Slice slice) { String encoded; if (slice.hasByteArray()) { encoded = BaseEncoding.base16().encode(slice.byteArray(), slice.byt...
@Test public void testToHex() { assertFunction("to_hex(CAST('' AS VARBINARY))", VARCHAR, encodeHex("")); assertFunction("to_hex(CAST('a' AS VARBINARY))", VARCHAR, encodeHex("a")); assertFunction("to_hex(CAST('abc' AS VARBINARY))", VARCHAR, encodeHex("abc")); assertFunction("to_he...
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); ...
@Test public void testInternalConnect_bounded_limit() throws Exception { ReadOnlyTableProvider tableProvider = new ReadOnlyTableProvider( "test", ImmutableMap.of( "test", TestBoundedTable.of( Schema.FieldType.INT32, "id", ...
@Override public OUT nextRecord(OUT record) throws IOException { OUT returnRecord = null; do { returnRecord = super.nextRecord(record); } while (returnRecord == null && !reachedEnd()); return returnRecord; }
@Test void testPojoTypeWithTrailingEmptyFields() throws Exception { final String fileContent = "123,,3.123,,\n456,BBB,3.23,,"; final FileInputSplit split = createTempFile(fileContent); @SuppressWarnings("unchecked") PojoTypeInfo<PrivatePojoItem> typeInfo = (PojoTypeI...
@VisibleForTesting Object[] callHttpService( RowMetaInterface rowMeta, Object[] rowData ) throws KettleException { HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder(); if ( data.realConnectionTimeout > -1 ) { clientBuilder.setConnectionTimeout( data...
@Test public void callHttpServiceWithUTF8Encoding() throws Exception { try ( MockedStatic<HttpClientManager> httpClientManagerMockedStatic = mockStatic( HttpClientManager.class ) ) { httpClientManagerMockedStatic.when( HttpClientManager::getInstance ).thenReturn( manager ); doReturn( "UTF-8" ).when( m...
public final void addTransactionSigner(TransactionSigner signer) { lock.lock(); try { if (signer.isReady()) signers.add(signer); else throw new IllegalStateException("Signer instance is not ready to be added into Wallet: " + signer.getClass()); ...
@Test(expected = IllegalStateException.class) public void shouldNotAddTransactionSignerThatIsNotReady() { wallet.addTransactionSigner(new NopTransactionSigner(false)); }
public void validate(List<String> values, String type, List<String> options) { TypeValidation typeValidation = findByKey(type); for (String value : values) { typeValidation.validate(value, options); } }
@Test public void fail_on_unknown_type() { TypeValidation fakeTypeValidation = mock(TypeValidation.class); when(fakeTypeValidation.key()).thenReturn("Fake"); try { TypeValidations typeValidations = new TypeValidations(newArrayList(fakeTypeValidation)); typeValidations.validate("10", "Unknown"...
void handleStatement(final QueuedCommand queuedCommand) { throwIfNotConfigured(); handleStatementWithTerminatedQueries( queuedCommand.getAndDeserializeCommand(commandDeserializer), queuedCommand.getAndDeserializeCommandId(), queuedCommand.getStatus(), Mode.EXECUTE, queue...
@Test public void restartsRuntimeWhenAlterSystemIsSuccessful() { // Given: final String alterSystemQuery = "ALTER SYSTEM 'TEST'='TEST';"; when(mockParser.parseSingleStatement(alterSystemQuery)) .thenReturn(statementParser.parseSingleStatement(alterSystemQuery)); final Command alterSystemComman...
public static long write(InputStream is, OutputStream os) throws IOException { return write(is, os, BUFFER_SIZE); }
@Test void testWrite2() throws Exception { assertThat((int) IOUtils.write(reader, writer, 16), equalTo(TEXT.length())); }
@Override public DescriptiveUrl toDownloadUrl(final Path file, final Sharee sharee, CreateDownloadShareRequest options, final PasswordCallback callback) throws BackgroundException { try { if(log.isDebugEnabled()) { log.debug(String.format("Create download share for %s", file)); ...
@Test public void testShareFile() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new Tran...
@Override // Camel calls this method if the endpoint isSynchronous(), as the // KafkaEndpoint creates a SynchronousDelegateProducer for it public void process(Exchange exchange) throws Exception { // is the message body a list or something that contains multiple values Message message = exch...
@Test public void processSendsMessageWithTopicHeaderAndNoTopicInEndPoint() throws Exception { endpoint.getConfiguration().setTopic(null); Mockito.when(exchange.getIn()).thenReturn(in); in.setHeader(KafkaConstants.TOPIC, "anotherTopic"); Mockito.when(exchange.getMessage()).thenReturn(...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void intToConnect() { assertEquals(new SchemaAndValue(Schema.INT32_SCHEMA, 12), converter.toConnectData(TOPIC, "{ \"schema\": { \"type\": \"int32\" }, \"payload\": 12 }".getBytes())); }
public void upgrade() { viewService.streamAll().forEach(view -> { final Optional<User> user = view.owner().map(userService::load); if (user.isPresent() && !user.get().isLocalAdmin()) { final GRNType grnType = ViewDTO.Type.DASHBOARD.equals(view.type()) ? GRNTypes.DASHBOARD...
@Test @DisplayName("migrate existing owner") void migrateExistingOwner() { final GRN testuserGRN = GRNTypes.USER.toGRN("testuser"); final GRN dashboard = GRNTypes.DASHBOARD.toGRN("54e3deadbeefdeadbeef0002"); final User testuser = mock(User.class); when(testuser.getName()).thenR...
@Override public String getGroupKeyString(int rowIndex, int groupKeyColumnIndex) { throw new AssertionError("No grouping key for queries without a group by clause"); }
@Test(expectedExceptions = AssertionError.class) public void testGetGroupKeyString() { _aggregationResultSetUnderTest.getGroupKeyString(0, 0); }
@Override public JdbcDialect create() { throw new UnsupportedOperationException( "Can't create JdbcDialect without compatible mode for Hive"); }
@Test public void testWithCompatibleMode() { HiveDialectFactory hiveDialectFactory = new HiveDialectFactory(); JdbcDialect inceptorDialect = hiveDialectFactory.create("inceptor", ""); Assertions.assertTrue(inceptorDialect instanceof InceptorDialect); JdbcDialect hiveDialect = hiveDia...
public boolean checkValid(String connectionId) { return connections.containsKey(connectionId); }
@Test void testCheckValid() { assertTrue(connectionManager.checkValid(connectId)); }
@Override public boolean addAll(Collection<? extends E> c) { checkNotNull(c, "The collection to be added cannot be null."); boolean changed = false; for (Object item : c) { changed = items.add(serializer.encode(item)) || changed; } return changed; }
@Test public void testAddAll() throws Exception { //Test multi-adds with change checking Set<Integer> integersToCheck = Sets.newHashSet(); fillSet(10, integersToCheck); assertFalse("Set should be empty and so integers to check should not be a subset.", set.contain...
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { if(file.getType().contains(Path.Type.upload)) { return new NullInputStream(0L); } final HttpRange range = ...
@Test public void testReadGzipContentEncoding() throws Exception { final ByteArrayOutputStream compressedStream = new ByteArrayOutputStream(); final byte[] rawContent = RandomUtils.nextBytes(1457); final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressedStream); gzip...
@Override public HttpServletRequest readRequest(AwsProxyRequest request, SecurityContext securityContext, Context lambdaContext, ContainerConfig config) throws InvalidRequestEventException { // Expect the HTTP method and context to be populated. If they are not, we are handling an // uns...
@Test void readRequest_emptyHeaders_expectSuccess() { AwsProxyRequest req = new AwsProxyRequestBuilder("/path", "GET").build(); try { HttpServletRequest servletReq = reader.readRequest(req, null, null, ContainerConfig.defaultConfig()); String headerValue = servletReq.getHeade...
private static void parseAliases(JsonNode schema, Schema result) { Set<String> aliases = parseAliases(schema); if (aliases != null) // add aliases for (String alias : aliases) result.addAlias(alias); }
@Test public void parseAliases() throws JsonProcessingException { String s1 = "{ \"aliases\" : [\"a1\", \"b1\"]}"; ObjectMapper mapper = new ObjectMapper(); JsonNode j1 = mapper.readTree(s1); Set<String> aliases = Schema.parseAliases(j1); assertEquals(2, aliases.size()); assertTrue(aliases.co...
public String registerCoder(Coder<?> coder) throws IOException { String existing = coderIds.get(coder); if (existing != null) { return existing; } // Unlike StructuredCoder, custom coders may not have proper implementation of hashCode() and // equals(), this lead to unnecessary duplications. I...
@Test public void registerCoder() throws IOException { Coder<?> coder = KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(SetCoder.of(ByteArrayCoder.of()))); String id = components.registerCoder(coder); assertThat(components.registerCoder(coder), equalTo(id)); assertThat(id, not(isEmptyOrNullS...
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RedisConfigProperties that = (RedisConfigProperties) o; return Objects.equals(database, that....
@Test public void equalsTest() { RedisConfigProperties defaultConfig = new RedisConfigProperties(); assertEquals(defaultConfig, this.redisConfigProperties); defaultConfig.setMaster("master"); defaultConfig.setDatabase(2); defaultConfig.setPassword("password"); default...
public static boolean exceedsPushQueryCapacity( final KsqlExecutionContext executionContext, final KsqlRestConfig ksqlRestConfig ) { return getNumLivePushQueries(executionContext) >= getPushQueryLimit(ksqlRestConfig); }
@Test public void shouldReportPushQueryAtCapacityLimit() { // Given: givenAllLiveQueries(10); givenActivePersistentQueries(4); givenPushQueryLimit(6); // Then: assertThat(QueryCapacityUtil.exceedsPushQueryCapacity(ksqlEngine, ksqlRestConfig), equalTo(true)); }
@Override @CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理 public void updateSmsTemplate(SmsTemplateSaveReqVO updateReqVO) { // 校验存在 validateSmsTemplateExists(updateReqVO.getId()); // 校验短信渠道 SmsChann...
@Test public void testUpdateSmsTemplate_notExists() { // 准备参数 SmsTemplateSaveReqVO reqVO = randomPojo(SmsTemplateSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.updateSmsTemplate(reqVO), SMS_TEMPLATE_NOT_EXISTS); }
public static void checkContextPath(String contextPath) { if (contextPath == null) { return; } Matcher matcher = CONTEXT_PATH_MATCH.matcher(contextPath); if (matcher.find()) { throw new IllegalArgumentException("Illegal url path expression"); } }
@Test void testContextPathIllegal1() { assertThrows(IllegalArgumentException.class, () -> { String contextPath1 = "//nacos/"; ValidatorUtils.checkContextPath(contextPath1); }); }
@Override protected void validateDataImpl(TenantId tenantId, AssetProfile assetProfile) { validateString("Asset profile name", assetProfile.getName()); if (assetProfile.getTenantId() == null) { throw new DataValidationException("Asset profile should be assigned to tenant!"); } el...
@Test void testValidateNameInvocation() { AssetProfile assetProfile = new AssetProfile(); assetProfile.setName("prod"); assetProfile.setTenantId(tenantId); validator.validateDataImpl(tenantId, assetProfile); verify(validator).validateString("Asset profile name", assetProfile...
@Override public PageResult<ProductSpuDO> getSpuPage(ProductSpuPageReqVO pageReqVO) { return productSpuMapper.selectPage(pageReqVO); }
@Test void getSpuPage_alarmStock() { // 准备参数 ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{ o.setCategoryId(generateId()); o.setBrandId(generateId()); o.setDeliveryTemplateId(generateId()); o.setSort(Random...
public static byte[] readBytes(ByteBuffer buffer, int offset, int length) { byte[] dest = new byte[length]; if (buffer.hasArray()) { System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, length); } else { buffer.mark(); buffer.position(offse...
@Test public void testReadBytes() { byte[] myvar = "Any String you want".getBytes(); ByteBuffer buffer = ByteBuffer.allocate(myvar.length); buffer.put(myvar); buffer.rewind(); this.subTest(buffer); // test readonly buffer, different path buffer = ByteBuffer....
@Override public Optional<EfestoOutputPMML> evaluateInput(EfestoInputPMML toEvaluate, EfestoRuntimeContext context) { return executeEfestoInputPMML(toEvaluate, context); }
@Test void evaluateEfestoRuntimeContext() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME); EfestoRuntimeContext runtimeContext = EfestoRuntimeContextUtils.buildWithParentClassLoader(memoryCompilerClassLoader); EfestoInputPMML inputPMML = new Efe...
@Override public void write(int byteValue) throws IOException { byte[] bytes = new byte[] {(byte) byteValue}; write(bytes); }
@Test public void shouldFailOnPartialWrite() throws IOException { if (!closed) { blobStorage.maxWriteCount = 1; byte[] bytes = new byte[2]; random.nextBytes(bytes); assertThrows(IOException.class, () -> fsDataOutputStream.write(bytes)); } }
@Override public void run() { try (DbSession dbSession = dbClient.openSession(false)) { List<AlmSettingDto> githubSettingsDtos = dbClient.almSettingDao().selectByAlm(dbSession, ALM.GITHUB); if (githubSettingsDtos.isEmpty()) { metrics.setGithubStatusToRed(); return; } vali...
@Test public void run_githubValidatorDoesntThrowException_setRedStatusInMetricsOnce() { List<AlmSettingDto> dtos = generateDtos(5, ALM.GITHUB); when(almSettingsDao.selectByAlm(any(), any())).thenReturn(dtos); doThrow(new RuntimeException()).when(githubValidator).validate(any()); underTest.run(); ...
public SortedMap<String, HealthCheck.Result> runHealthChecks() { return runHealthChecks(HealthCheckFilter.ALL); }
@Test public void runsRegisteredHealthChecksWithFilter() { final Map<String, HealthCheck.Result> results = registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); assertThat(results).containsOnly(entry("hc1", r1)); }
public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException { int ch; ParserState state = ParserState.INITIAL; List<String> list = new ArrayList<>(); CharArrayWriter baos = new CharArrayWriter(200); boolean push = false; while (-1 ...
@Test public void testBlankLineQuoted() throws Exception { BufferedReader br = new BufferedReader(new StringReader("\"\"\n")); String[] out = CSVSaveService.csvReadFile(br, ','); checkStrings(new String[]{""}, out); assertEquals(-1, br.read(), "Expected to be at EOF"); }
public ApplicationBuilder monitor(MonitorConfig monitor) { this.monitor = monitor; return getThis(); }
@Test void monitor() { MonitorConfig monitor = new MonitorConfig("monitor-addr"); ApplicationBuilder builder = new ApplicationBuilder(); builder.monitor(monitor); Assertions.assertSame(monitor, builder.build().getMonitor()); Assertions.assertEquals("monitor-addr", builder.bui...
@NotNull @Override public INode enrich(@NotNull INode node) { if (node instanceof AES aes) { return enrich(aes); } return node; }
@Test void ae() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); final AES aes = new AES( 128, new GCM(testDetectionLocation), new...
public final synchronized List<E> getAllAddOns() { Logger.d(mTag, "getAllAddOns has %d add on for %s", mAddOns.size(), getClass().getName()); if (mAddOns.size() == 0) { loadAddOns(); } Logger.d( mTag, "getAllAddOns will return %d add on for %s", mAddOns.size(), getClass().getName()); r...
@Test public void testDoesNotFiltersDebugAddOnOnDebugBuilds() throws Exception { TestableAddOnsFactory factory = new TestableAddOnsFactory(true); List<TestAddOn> list = factory.getAllAddOns(); // right now, we have 3 themes that are marked as dev. Assert.assertEquals(STABLE_THEMES_COUNT + UNSTABLE_THE...
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) { Future<Integer> tlsFuture; if (certSecretSources == null || certSecretSources.isEmpty()) { tlsFuture = Future.succeededFutu...
@Test void getHashForPattern(VertxTestContext context) { String namespace = "ns"; CertSecretSource cert1 = new CertSecretSourceBuilder() .withSecretName("cert-secret") .withPattern("*.crt") .build(); CertSecretSource cert2 = new CertSecretSour...
@Override public String getAuthenticationPassword() { return this.authPassword; }
@Test public void testGetAuthenticationPassword() { assertEquals(authPassword, v3SnmpConfiguration.getAuthenticationPassword()); }
public Notification setFieldValue(String field, @Nullable String value) { fields.put(field, value); return this; }
@Test void equals_whenTypeAndFieldsMatch_shouldReturnTrue() { Notification notification1 = new Notification("type"); Notification notification2 = new Notification("type"); notification1.setFieldValue("key", "value"); notification2.setFieldValue("key", "value"); assertThat(notification1) .h...
private <T> RestResponse<T> get(final String path, final Class<T> type) { return executeRequestSync(HttpMethod.GET, path, null, r -> deserialize(r.getBody(), type), Optional.empty()); }
@Test public void shouldPostQueryRequest_chunkHandler_closeAfterFinish() { ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST, Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT); executor.submit(this::expectPostQueryRequestChunkHandler); assertThatEventu...
public static Criterion matchIPv6Dst(IpPrefix ip) { return new IPCriterion(ip, Type.IPV6_DST); }
@Test public void testMatchIPv6DstMethod() { Criterion matchIPv6Dst = Criteria.matchIPv6Dst(ipv61); IPCriterion ipCriterion = checkAndConvert(matchIPv6Dst, Criterion.Type.IPV6_DST, IPCriterion.class); assertThat(...
public static long tileToPixel(long tileNumber, int tileSize) { return tileNumber * tileSize; }
@Test public void tileToPixelTest() { for (int tileSize : TILE_SIZES) { Assert.assertEquals(0, MercatorProjection.tileToPixel(0, tileSize)); Assert.assertEquals(tileSize, MercatorProjection.tileToPixel(1, tileSize)); Assert.assertEquals(tileSize * 2, MercatorProjection.ti...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof PojoSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } PojoSeria...
@Test void testResolveSchemaCompatibilityWithIncompatibleFieldSerializers() { final PojoSerializerSnapshot<TestPojo> oldSnapshot = buildTestSnapshot( Arrays.asList( ID_FIELD, mockFieldSerializerSnapshot( ...
public EntrySet entrySet() { if (null == entrySet) { entrySet = new EntrySet(); } return entrySet; }
@Test void removeIfOnEntrySetThrowsUnsupportedOperationException() { final Predicate<Map.Entry<Integer, String>> filter = (entry) -> true; final UnsupportedOperationException exception = assertThrowsExactly(UnsupportedOperationException.class, () -> cache.entrySet().removeIf(filter)...
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { ...
@Test public void parseEmpty() { List<String> list = parser.toPrefix(""); assertTrue(list.isEmpty()); }
@Override public List<Container> allocateContainers(ResourceBlacklistRequest blackList, List<ResourceRequest> oppResourceReqs, ApplicationAttemptId applicationAttemptId, OpportunisticContainerContext opportContext, long rmIdentifier, String appSubmitter) throws YarnException { // Update b...
@Test public void testMaxAllocationsPerAMHeartbeatWithNoLimit() throws Exception { ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest.newInstance( new ArrayList<>(), new ArrayList<>()); allocator.setMaxAllocationsPerAMHeartbeat(-1); List<ResourceRequest> reqs = new A...
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PRO...
@Test void assertGetBinaryProtocolValueWithMySQLTypeMediumBlob() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.MEDIUM_BLOB), instanceOf(MySQLByteLenencBinaryProtocolValue.class)); }
public void setTransacted(boolean transacted) { if (transacted) { setAcknowledgementMode(SessionAcknowledgementType.SESSION_TRANSACTED); } this.transacted = transacted; }
@Test public void testSetTransacted() { Endpoint endpoint = context.getEndpoint("sjms:queue:test.SjmsEndpointTest?transacted=true"); assertNotNull(endpoint); assertTrue(endpoint instanceof SjmsEndpoint); SjmsEndpoint qe = (SjmsEndpoint) endpoint; assertTrue(qe.isTransacted())...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { session.getClient().putDirectory(folder.getAbsolute()); return folder; } catch(MantaException e) { throw new MantaExceptionMappingService().map("...
@Test public void testWhitespaceMkdir() throws Exception { final RandomStringService randomStringService = new AlphanumericRandomStringService(); final Path target = new MantaDirectoryFeature(session) .mkdir( new Path( testPathPrefix, ...
public static long toUnsignedLong(short value) { return Short.toUnsignedLong(value); }
@Test public void testShortToUnsignedLong() { getShortTestData().forEach(val -> assertEquals(val.toString(), toUnsignedLongPreviousImplementation(val), BitmapUtils.toUnsignedLong(val))); }
public EndpointResponse get() { return EndpointResponse.ok(new ServerInfo( appVersion.get(), kafkaClusterId.get(), ksqlServiceId.get(), serverStatus.get().toString())); }
@Test public void shouldGetKafkaClusterIdWithTimeout() throws InterruptedException, ExecutionException, TimeoutException{ // When: serverInfoResource.get(); // Then: verify(future).get(30, TimeUnit.SECONDS); }
@Override public ResultSet getSchemas() { return null; }
@Test void assertGetSchemas() { assertNull(metaData.getSchemas()); }
@Override public Mono<Void> writeWith(final ServerWebExchange exchange, final ShenyuPluginChain chain) { return chain.execute(exchange).then(Mono.defer(() -> { Object result = exchange.getAttribute(Constants.RPC_RESULT); if (Objects.isNull(result)) { Object error = Sh...
@Test public void testExecuteWithNoResult() { StepVerifier.create(rpcMessageWriter.writeWith(exchange, chain)).expectSubscription().verifyComplete(); }
@Udf(description = "Returns the portion of str from pos to the end of str") public String substring( @UdfParameter(description = "The source string.") final String str, @UdfParameter(description = "The base-one position to start from.") final Integer pos ) { if (str == null || pos == null) { r...
@Test public void shouldExtractFromEndForNegativePositionsOnBytes() { assertThat(udf.substring(ByteBuffer.wrap(new byte[]{1,2,3,4}), -3), is(ByteBuffer.wrap(new byte[]{2,3,4}))); assertThat(udf.substring(ByteBuffer.wrap(new byte[]{1,2,3,4}), -3, 3), is(ByteBuffer.wrap(new byte[]{2,3,4}))); }
public static OffsetBasedPagination forOffset(int offset, int pageSize) { checkArgument(offset >= 0, "offset must be >= 0"); checkArgument(pageSize >= 1, "page size must be >= 1"); return new OffsetBasedPagination(offset, pageSize); }
@Test void hashcode_whenDifferentOffset_shouldBeNotEquals() { Assertions.assertThat(OffsetBasedPagination.forOffset(10, 20)) .doesNotHaveSameHashCodeAs(OffsetBasedPagination.forOffset(15, 20)); }
@Override public List<Integer> applyTransforms(List<Integer> originalGlyphIds) { List<Integer> intermediateGlyphsFromGsub = originalGlyphIds; for (String feature : FEATURES_IN_ORDER) { if (!gsubData.isFeatureSupported(feature)) { LOG.debug("the fe...
@Test void testApplyTransforms_ou_kar() { // given List<Integer> glyphsAfterGsub = Arrays.asList(108, 91, 114, 94); // when List<Integer> result = gsubWorkerForBengali.applyTransforms(getGlyphIds("মৌল")); // then assertEquals(glyphsAfterGsub, result); }
@Override public void validate(CruiseConfig cruiseConfig) { ServerConfig serverConfig = cruiseConfig.server(); String artifactDir = serverConfig.artifactsDir(); if (isEmpty(artifactDir)) { throw new RuntimeException("Please provide a not empty value for artifactsdir"); }...
@Test public void shouldThrowExceptionWhenUserProvidesPathPointToServerSandBox() { File file = new File(""); CruiseConfig cruiseConfig = new BasicCruiseConfig(); cruiseConfig.setServerConfig(new ServerConfig(file.getAbsolutePath(), null)); ArtifactDirValidator dirValidator = new Art...
protected boolean isPassed() { return !agentHealthHolder.hasLostContact(); }
@Test void shouldReturnTrueIfAgentHasNotLostContact() { AgentHealthHolder mock = mock(AgentHealthHolder.class); when(mock.hasLostContact()).thenReturn(false); IsConnectedToServerV1 handler = new IsConnectedToServerV1(mock); assertThat(handler.isPassed()).isTrue(); }
public static <T> CompletableFuture<T> run(Callable<T> callable) { CompletableFuture<T> result = new CompletableFuture<>(); CompletableFuture.runAsync( () -> { // we need to explicitly catch any exceptions, // otherwise they will be silently discar...
@Test public void testRunException() { assertThrows( ExecutionException.class, () -> { Async.run( () -> { throw new RuntimeException(""); }) ...
public static < EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT extends MutableState<EventTypeT, ResultTypeT>> OrderedEventProcessor<EventTypeT, EventKeyTypeT, ResultTypeT, StateTypeT> create( OrderedProcessingHandler<EventTypeT, EventKeyTypeT, StateTypeT, Resu...
@Test public void testSequenceGapProcessingInBufferedOutput() throws CannotProvideCoderException { int maxResultsPerOutput = 3; long[] sequences = new long[] {2, 3, 7, 8, 9, 10, 1, 4, 5, 6}; List<Event> events = new ArrayList<>(sequences.length); List<KV<String, String>> expectedOutput = new ArrayLi...