focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException { lock.lock(); try { checkArgument(!req.completed, () -> "given SendRequest has already been completed"); log.info("Completing send tx with {} outputs totalling {} ...
@Test public void opReturnMaxBytes() throws Exception { receiveATransaction(wallet, myAddress); Transaction tx = new Transaction(); Script script = ScriptBuilder.createOpReturnScript(new byte[80]); tx.addOutput(Coin.ZERO, script); SendRequest request = SendRequest.forTx(tx); ...
@Override public void run() { // top-level command, do nothing }
@Test public void test_submit_server_cli_version_minor_mismatch_ignore() { String serverVersion = "5.0.0"; System.setProperty(HAZELCAST_INTERNAL_OVERRIDE_VERSION, serverVersion); Config cfg = smallInstanceConfig(); cfg.getJetConfig().setResourceUploadEnabled(true); String cl...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertBlob() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("tinyblob") .dataType("tinyblob") .build(); Column column = M...
@Override public ParseResult parsePath(String path) { String original = path; path = path.replace('/', '\\'); if (WORKING_DIR_WITH_DRIVE.matcher(path).matches()) { throw new InvalidPathException( original, "Jimfs does not currently support the Windows syntax for a relative path ...
@Test public void testWindows_relativePathsWithDriveRoot_unsupported() { try { windows().parsePath("C:"); fail(); } catch (InvalidPathException expected) { } try { windows().parsePath("C:foo\\bar"); fail(); } catch (InvalidPathException expected) { } }
public static byte[] readFileBytes(File file) { if (file.exists()) { String result = readFile(file); if (result != null) { return ByteUtils.toBytes(result); } } return null; }
@Test void testReadFileBytes() { assertNotNull(DiskUtils.readFileBytes(testFile)); }
@POST @ApiOperation("Get all views that match given parameter value") @NoAuditEvent("Only returning matching views, not changing any data") public Collection<ViewParameterSummaryDTO> forParameter(@Context SearchUser searchUser) { return qualifyingViewsService.forValue() .stream() ...
@Test public void returnsNoViewsIfNoneArePresent() { final SearchUser searchUser = TestSearchUser.builder().build(); QualifyingViewsService service = mockViewsService(); final QualifyingViewsResource resource = new QualifyingViewsResource(service); final Collection<ViewParameterSum...
public static CertificateMetadata parseMetadata(String certificateValue, boolean isIndividual) throws LibCertificateException { SecurityProviderInitializer.initKalkanProvider(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature(XML_DISALLOW_D...
@Test public void testParseMetadataCorporate() throws LibCertificateException { try (MockedStatic<DateUtils> dateUtilsMock = Mockito.mockStatic(DateUtils.class)) { String certificateValue = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><login><timeTicket>1714814361503</timeTicket>...
public static <T> ProcessorMetaSupplier metaSupplier( @Nonnull String directoryName, @Nonnull FunctionEx<? super T, ? extends String> toStringFn, @Nonnull String charset, @Nullable String datePattern, long maxFileSize, boolean exactlyOnce ) { ...
@Test public void test_rollByFileSize() throws Exception { int numItems = 10; DAG dag = new DAG(); Vertex src = dag.newVertex("src", () -> new SlowSourceP(semaphore, numItems)).localParallelism(1); Vertex map = dag.newVertex("map", mapP((Integer i) -> i + 100)); // maxFileSiz...
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn, final String regexField) { return rows.stream() .map(row -> row.evaluate(columnPairsMap, outputColumn, regexField)) .filter(Optional::isPresent) .findFirst() ...
@Test void evaluateKeyNotFound() { KiePMMLInlineTable kiePMMLInlineTable = new KiePMMLInlineTable("name", Collections.emptyList(), ROWS); Optional<Object> retrieved = kiePMMLInlineTable.evaluate(Collections.singletonMap("NOT-KEY", 0), "KEY-0-0", ...
@Override public HttpResponseOutputStream<File> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final String location = new StoregateWriteFeature(session, fileid).start(file, status); final MultipartOutputStream proxy = new Multipar...
@Test(expected = TransferStatusCanceledException.class) public void testWriteCancel() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new...
@Override public void toJson(Map<String, Object> json, Revision revision) { json.put("folder", getFolder() == null ? "" : getFolder()); json.put("scmType", "Dependency"); json.put("location", pipelineName + "/" + stageName); json.put("action", "Completed"); if (!CaseInsensiti...
@Test void shouldReturnJson() { Map<String, Object> json = new LinkedHashMap<>(); dependencyMaterial.toJson(json, create("pipeline", 10, "1.0.123", "stage", 1)); assertThat(json.get("location")).isEqualTo("pipeline/stage"); assertThat(json.get("scmType")).isEqualTo("Dependency"); ...
public static CsvReader getReader(CsvReadConfig config) { return new CsvReader(config); }
@Test @Disabled public void readLfTest(){ final CsvReader reader = CsvUtil.getReader(); String path = FileUtil.isWindows() ? "d:/test/rw_test.csv" : "~/test/rw_test.csv"; final CsvData read = reader.read(FileUtil.file(path)); for (CsvRow row : read) { Console.log(row); } }
public static void bindEnvironment(ScriptEngine engine, String requestContent, Map<String, Object> requestContext, StateStore stateStore) { // Build a map of header values. bindEnvironment(engine, requestContent, requestContext, stateStore, null); }
@Test void testMicrocksXmlHolder() { String body = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header/> <soapenv:Body> <hel:sayHello xmlns:hel="http://www.example.com/hello"> <name...
public List<String> getOnUpdateColumnsOnlyName() { return allColumns.values().stream().filter(ColumnMeta::isOnUpdate).map(ColumnMeta::getColumnName).collect(Collectors.toList()); }
@Test public void testGetOnUpdateColumnsOnlyName() { List<String> onUpdateColumns = tableMeta.getOnUpdateColumnsOnlyName(); List<String> expected = Arrays.asList("col1"); assertEquals(expected.size(), onUpdateColumns.size()); assertTrue(onUpdateColumns.containsAll(expected)); }
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void withDefaultValue() throws ScanException { String input = "${k67:-b}c"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); Assertions.assertEquals("bc", nodeToStringTransformer.transfo...
@Override public T load(long sequence) { long startNanos = Timer.nanos(); try { return delegate.load(sequence); } finally { loadProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void load() { long sequence = 1L; String value = "someValue"; when(delegate.load(sequence)).thenReturn(value); String result = ringbufferStore.load(sequence); assertEquals(value, result); assertProbeCalledOnce("load"); }
public KVTable getBrokerRuntimeInfo(final String addr, final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_RUNTI...
@Test public void assertGetBrokerRuntimeInfo() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); KVTable responseBody = new KVTable(); responseBody.getTable().put("key", "value"); setResponseBody(responseBody); KVTable actual = mqClientAPI....
@Override public GoViewDataRespVO getDataBySQL(String sql) { // 1. 执行查询 SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql); // 2. 构建返回结果 GoViewDataRespVO respVO = new GoViewDataRespVO(); // 2.1 解析元数据 SqlRowSetMetaData metaData = sqlRowSet.getMetaData(); S...
@Test public void testGetDataBySQL() { // 准备参数 String sql = "SELECT id, name FROM system_users"; // mock 方法 SqlRowSet sqlRowSet = mock(SqlRowSet.class); when(jdbcTemplate.queryForRowSet(eq(sql))).thenReturn(sqlRowSet); // mock 元数据 SqlRowSetMetaData metaData = ...
private void sendResponse(Response response) { try { ((GrpcConnection) this.currentConnection).sendResponse(response); } catch (Exception e) { LOGGER.error("[{}]Error to send ack response, ackId->{}", this.currentConnection.getConnectionId(), response.getReque...
@Test void testBindRequestStreamOnNextNoRequest() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { BiRequestStreamGrpc.BiRequestStreamStub stub = mock(BiRequestStreamGrpc.BiRequestStreamStub.class); GrpcConnection grpcConnection = mo...
@Override public void reportCompletedCheckpoint(CompletedCheckpointStats completed) { statsReadWriteLock.lock(); try { latestCompletedCheckpoint = completed; counts.incrementCompletedCheckpoints(); history.replacePendingCheckpointById(completed); sum...
@Test void testCheckpointStatsListenerOnCompletedCheckpoint() { testCheckpointStatsListener( (checkpointStatsTracker, pendingCheckpointStats) -> checkpointStatsTracker.reportCompletedCheckpoint( pendingCheckpointStats.toCompletedCheckpo...
public static BigDecimal pow(Number number, int n) { return pow(toBigDecimal(number), n); }
@Test public void testPowNegative() { BigDecimal number = new BigDecimal("2.5"); int exponent = -2; BigDecimal expected = new BigDecimal("0.16"); assertEquals(expected, NumberUtil.pow(number, exponent)); }
void generate(MessageSpec message) throws Exception { if (message.struct().versions().contains(Short.MAX_VALUE)) { throw new RuntimeException("Message " + message.name() + " does " + "not specify a maximum version."); } structRegistry.register(message); schema...
@Test public void testNullDefaultsWithDeprecatedVersions() throws Exception { MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"va...
@Override public void setKeyboardTheme(@NonNull KeyboardTheme theme) { super.setKeyboardTheme(theme); mExtensionKeyboardYDismissPoint = getThemedKeyboardDimens().getNormalKeyHeight(); mGestureDrawingHelper = GestureTypingPathDrawHelper.create( this::invalidate, GestureTra...
@Test public void testDisregardIfSameTheme() { final KeyboardThemeFactory keyboardThemeFactory = AnyApplication.getKeyboardThemeFactory(getApplicationContext()); Assert.assertTrue(mThemeWasSet); mThemeWasSet = false; mViewUnderTest.setKeyboardTheme(keyboardThemeFactory.getAllAddOns().get(2)); ...
@Override public void transform(Message message, DataType fromType, DataType toType) { if (message.getHeaders().containsKey(Ddb2Constants.ITEM) || message.getHeaders().containsKey(Ddb2Constants.KEY)) { return; } JsonNode jsonBody = getBodyAsJsonNode(message); ...
@Test void shouldFailForUnsupportedOperation() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setBody(Json.mapper().readTree("{}")); exchange.setProperty("operation", Ddb2Operations.BatchGetItems.name()); Assertions.assertThrows(Unsu...
@Override public String toString() { StringBuilder builder = new StringBuilder("AfterEach.inOrder("); Joiner.on(", ").appendTo(builder, subTriggers); builder.append(")"); return builder.toString(); }
@Test public void testToString() { TriggerStateMachine trigger = AfterEachStateMachine.inOrder( StubTriggerStateMachine.named("t1"), StubTriggerStateMachine.named("t2"), StubTriggerStateMachine.named("t3")); assertEquals("AfterEach.inOrder(t1, t2, t3)", trigger.toS...
@Override public void onConnected(Connection connection) { connected = true; LogUtils.NAMING_LOGGER.info("Grpc connection connect"); }
@Test void testOnConnected() { assertFalse(redoService.isConnected()); redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); assertTrue(redoService.isConnected()); }
@Override public MastershipRole getRole(DeviceId deviceId) { checkPermission(DEVICE_READ); checkNotNull(deviceId, DEVICE_ID_NULL); return mastershipService.getLocalRole(deviceId); }
@Test public void getRole() { connectDevice(DID1, SW1); assertEquals("incorrect role", MastershipRole.MASTER, service.getRole(DID1)); }
public static LinkedHashSet<Class<?>> listBeansRecursiveInclusive(Class<?> beanClass) { return listBeansRecursiveInclusive(beanClass, new LinkedHashSet<>()); }
@Test public void listBeansRecursiveInclusiveTest() { LinkedHashSet<Class<?>> classes = TypeUtils.listBeansRecursiveInclusive(BeanA.class); // System.out.println(classes); assertEquals(classes.size(), 2); }
public static List<String> splitStatementsAcrossBlocks(CharSequence string) { List<String> statements = codeAwareSplitOnChar(string, false, true, ';', '\n', '{', '}'); return statements.stream() .filter(stmt -> !(stmt.isEmpty())) .filter(stmt -> !(stmt.startsWith("//"))) ...
@Test public void splitStatementsAcrossBlocksFor() { String text = "for (int i = 0; i < 1; i++) {\n" + " $fact.value1 = 2;\n" + " drools.update($fact);\n" + "}"; List<String> statements = splitStatementsAcrossBlocks(text); a...
@Override public AlterConsumerGroupOffsetsResult alterConsumerGroupOffsets( String groupId, Map<TopicPartition, OffsetAndMetadata> offsets, AlterConsumerGroupOffsetsOptions options ) { SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, Errors>> future = Alte...
@Test public void testAlterConsumerGroupOffsetsRetriableErrors() throws Exception { // Retriable errors should be retried final TopicPartition tp1 = new TopicPartition("foo", 0); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient(...
@Override public SlotAssignmentResult ensure(long key1, long key2) { assert key1 != unassignedSentinel : "ensure() called with key1 == nullKey1 (" + unassignedSentinel + ')'; return super.ensure0(key1, key2); }
@Test public void testCursor_advance() { hsa.ensure(randomKey(), randomKey()); HashSlotCursor16byteKey cursor = hsa.cursor(); assertTrue(cursor.advance()); assertFalse(cursor.advance()); }
public static PDImageXObject createFromStream(PDDocument document, InputStream stream) throws IOException { return createFromByteArray(document, stream.readAllBytes()); }
@Test void testCreateFromStreamCMYK() throws IOException { PDDocument document = new PDDocument(); InputStream stream = JPEGFactoryTest.class.getResourceAsStream("jpegcmyk.jpg"); PDImageXObject ximage = JPEGFactory.createFromStream(document, stream); validate(ximage, 8, 343, 287,...
public Set<String> allPermissions() { return allPermissions; }
@Test public void testAllPermissions() throws Exception { assertThat(permissions.allPermissions()) .containsOnlyElementsOf(restPermissions.permissions() .stream() .map(Permission::permission) .collect(Collectors.toSet())...
public Map<ExecNode<?>, Integer> calculate() { createTopologyGraph(); // some boundaries node may be connected from the outside of the sub-graph, // which we cannot deduce by the above process, // so we need to check each pair of boundaries and see if they're related dealWithPos...
@Test void testCalculateInputOrder() { // P = InputProperty.DamBehavior.PIPELINED, B = InputProperty.DamBehavior.BLOCKING // P1 = PIPELINED + priority 1 // // 0 -(P1)-> 3 -(B0)-\ // 6 -(B0)-\ // /-(P1)-/ \ // 1 -(P1)-> 4 ...
@Override public RexNode visit(CallExpression call) { boolean isBatchMode = unwrapContext(relBuilder).isBatchMode(); for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) { Optional<RexNode> converted = rule.convert(call, newFunctionContext()); if (conve...
@Test void testIntervalYearMonth() { Period value = Period.of(999, 3, 1); RexNode rex = converter.visit(valueLiteral(value)); assertThat(((RexLiteral) rex).getValueAs(BigDecimal.class)) .isEqualTo(BigDecimal.valueOf(value.toTotalMonths())); // TODO planner ignores the...
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "Parameter with ref") public void testParameterWithRef() { Components components = new Components(); components.addParameters("id", new Parameter() .description("Id Description") .schema(new IntegerSchema()) .in(ParameterIn.QUERY.to...
public static <T> AggregateOperation1<T, Set<T>, Set<T>> toSet() { return toCollection(HashSet::new); }
@Test public void when_toSet() { validateOpWithoutDeduct( toSet(), identity(), 1, 2, singleton(1), new HashSet<>(asList(1, 2)), new HashSet<>(asList(1, 2))); }
public static BitSetCoder of() { return INSTANCE; }
@Test public void testEncodedTypeDescriptor() throws Exception { assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(TypeDescriptor.of(BitSet.class))); }
@Override public long getPendingCount() { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.PENDING); } }
@Test public void count_Pending_from_database() { when(getDbClient().ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.PENDING))).thenReturn(42); assertThat(underTest.getPendingCount()).isEqualTo(42); }
public static boolean hasCollisionChars(String topic) { return topic.contains("_") || topic.contains("."); }
@Test public void testTopicHasCollisionChars() { List<String> falseTopics = Arrays.asList("start", "end", "middle", "many"); List<String> trueTopics = Arrays.asList( ".start", "end.", "mid.dle", ".ma.ny.", "_start", "end_", "mid_dle", "_ma_ny." ); for...
public double vincentyDistance(LatLong other) { return LatLongUtils.vincentyDistance(this, other); }
@Test public void vincentyDistance_southPoleToNorthPole_returnTwiceOfDistanceFromPoleToEquator() { // Calculating the distance between the north pole and the equator LatLong northPole = new LatLong(90d, 0d); // Check if the distance from pole to pole works as well in the vincentyDistance ...
public StreamGraph generate() { streamGraph = new StreamGraph( configuration, executionConfig, checkpointConfig, savepointRestoreSettings); shouldExecuteInBatchMode = shouldExecuteInBatchMode(); configureStreamGraph(streamGraph); alreadyTransforme...
@Test void testSettingSavepointRestoreSettings() { Configuration config = new Configuration(); config.set(StateRecoveryOptions.SAVEPOINT_PATH, "/tmp/savepoint"); final StreamGraph streamGraph = new StreamGraphGenerator( Collections.emptyList()...
@Override @CacheEvict(value = RedisKeyConstants.MAIL_ACCOUNT, key = "#updateReqVO.id") public void updateMailAccount(MailAccountSaveReqVO updateReqVO) { // 校验是否存在 validateMailAccountExists(updateReqVO.getId()); // 更新 MailAccountDO updateObj = BeanUtils.toBean(updateReqVO, MailAc...
@Test public void testUpdateMailAccount_notExists() { // 准备参数 MailAccountSaveReqVO reqVO = randomPojo(MailAccountSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> mailAccountService.updateMailAccount(reqVO), MAIL_ACCOUNT_NOT_EXISTS); }
@Override public V fetch(final K key, final long time) { Objects.requireNonNull(key, "key can't be null"); final List<ReadOnlyWindowStore<K, V>> stores = provider.stores(storeName, windowStoreType); for (final ReadOnlyWindowStore<K, V> windowStore : stores) { try { ...
@Test public void emptyIteratorPeekNextKeyShouldThrowNoSuchElementException() { final StateStoreProvider storeProvider = mock(StateStoreProvider.class); when(storeProvider.stores(anyString(), any())).thenReturn(emptyList()); final CompositeReadOnlyWindowStore<Object, Object> store = new Com...
RuleChange findChangesAndUpdateRule(RulesDefinition.Rule ruleDef, RuleDto ruleDto) { RuleChange ruleChange = new RuleChange(ruleDto); boolean ruleMerged = mergeRule(ruleDef, ruleDto, ruleChange); boolean debtDefinitionsMerged = mergeDebtDefinitions(ruleDef, ruleDto); boolean tagsMerged = mergeTags(ruleD...
@Test public void findChangesAndUpdateRule_whenNoCleanCodeTaxonomyChanged_thenPluginRuleChangeShouldBeNull() { RulesDefinition.Rule ruleDef = getDefaultRuleDef(); when(ruleDef.cleanCodeAttribute()).thenReturn(CleanCodeAttribute.COMPLETE); Map<SoftwareQuality, Severity> newImpacts = Map.of(SoftwareQuality....
public static List<FileNode> listDirByPath(String path) { List<FileNode> dirList = new ArrayList<>(); File logDir = new File(path); if (logDir.isFile()) { throw new BusException(StrUtil.format("Directory path {} is a file.", path)); } File[] files = logDir.listFiles()...
@Ignore @Test public void testListDirByPath() { List<FileNode> dirList = DirUtil.listDirByPath(DirConstant.getRootLogsPath()); Assertions.assertThat(dirList).isNotNull(); }
public Optional<Instant> getTimestamp() { return Optional.ofNullable(timestamp); }
@Test public void testFilePropertiesSpec_timestampSpecIso8601() throws JsonProcessingException { String data = "timestamp: 2020-06-08T14:54:36+00:00"; FilePropertiesSpec parsed = mapper.readValue(data, FilePropertiesSpec.class); assertThat(parsed.getTimestamp().get()).isEqualTo(Instant.parse("2020-06-08T...
static boolean objectIsAcyclic(Object object) { if (object == null) { return true; } Class<?> klass = object.getClass(); if (isPrimitiveClass(klass)) { return true; } else if (isComplexClass(klass)) { DataComplex complex = (DataComplex) object; try { ...
@Test public void testDataListNoCyclesOnAdd() { // test with DataList DataList a = new DataList(); DataList b = new DataList(); DataList c = new DataList(); a.add(b); a.add(c); assertTrue(Data.objectIsAcyclic(a)); DataList d = new DataList(); b.add(d); c.add(d); asse...
public static URI getInfoServer(InetSocketAddress namenodeAddr, Configuration conf, String scheme) throws IOException { String[] suffixes = null; if (namenodeAddr != null) { // if non-default namenode, try reverse look up // the nameServiceID if it is available suffixes = getSuffixIDs(c...
@Test public void testGetInfoServer() throws IOException, URISyntaxException { HdfsConfiguration conf = new HdfsConfiguration(); URI httpsport = DFSUtil.getInfoServer(null, conf, "https"); assertEquals(new URI("https", null, "0.0.0.0", DFS_NAMENODE_HTTPS_PORT_DEFAULT, null, null, null), https...
@Override public Map<String, List<String>> getRequestTag(String path, String methodName, Map<String, List<String>> headers, Map<String, List<String>> parameters) { Set<String> injectTags = configService.getInjectTags(); if (CollectionUtils.isEmpty(injectTags)) { // The staini...
@Test public void testGetRequestTag() { // Test matchTags as null configService.setReturnEmptyWhenGetMatchTags(true); Map<String, List<String>> requestTag = handler.getRequestTag("", "", null, null); Assert.assertEquals(requestTag, Collections.emptyMap()); // Test getLane re...
@Override public boolean wasNull() throws SQLException { return mergeResultSet.wasNull(); }
@Test void assertWasNull() throws SQLException { assertFalse(shardingSphereResultSet.wasNull()); }
@Override public Map<String, InterpreterClient> restore() throws IOException { Map<String, InterpreterClient> clients = new HashMap<>(); File[] recoveryFiles = recoveryDir.listFiles(file -> file.getName().endsWith(".recovery")); for (File recoveryFile : recoveryFiles) { String fileName = recoveryFil...
@Test void testSingleInterpreterProcess() throws InterpreterException, IOException { InterpreterSetting interpreterSetting = interpreterSettingManager.getByName("test"); interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED); Interpreter interpreter1 = interpreterSetting.getDefaultInterprete...
public Path back() { int size = back.size(); if(size > 1) { forward.add(back.get(size - 1)); Path p = back.get(size - 2); //delete the fetched path - otherwise we produce a loop back.remove(size - 1); back.remove(size - 2); return p...
@Test public void testBack() { Navigation n = new Navigation(); assertNull(n.back()); n.add(new Path("a", EnumSet.of(Path.Type.directory))); n.add(new Path("b", EnumSet.of(Path.Type.directory))); assertEquals("a", n.back().getName()); assertEquals("b", n.forward().get...
@Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void testRetainAll() { queue.retainAll(emptyList); }
@Override public void execute() throws CommandExecuteException, ConfigCheckException { if (abstractCommandArgs.isDecrypt()) { log.warn( "When both --decrypt and --encrypt are specified, only --encrypt will take effect"); } String encryptConfigFile = abstractCo...
@Test public void testEncrypt() throws URISyntaxException { TestCommandArgs testCommandArgs = new TestCommandArgs(); Path filePath = getFilePath("/origin.conf"); testCommandArgs.setEncrypt(true); testCommandArgs.setConfigFile(filePath.toString()); ConfEncryptCommand confEncry...
public MessageType convert(Class<? extends TBase<?, ?>> thriftClass) { return convert(toStructType(thriftClass)); }
@Test public void testLogicalTypeConvertion() throws Exception { String expected = "message ParquetSchema {\n" + " required int32 test_i16 (INTEGER(16,true)) = 1;\n" + " required int32 test_i8 (INTEGER(8,true)) = 2;\n" + "}\n"; ThriftSchemaConverter schemaConverter = new ThriftSchemaConverte...
@Override public byte[] fromConnectData(String topic, Schema schema, Object value) { try { return serializer.serialize(topic, value == null ? null : cast(value)); } catch (ClassCastException e) { throw new DataException("Failed to serialize to " + typeName + " (was " + value....
@Test public void testNullToBytes() { assertNull(converter.fromConnectData(TOPIC, schema, null)); }
@Override public Void handleResponse(Response response) throws IOException, UnexpectedBlobDigestException { blobSizeListener.accept(response.getContentLength()); try (OutputStream outputStream = new NotifyingOutputStream(destinationOutputStream, writtenByteCountListener)) { BlobDescriptor recei...
@Test public void testHandleResponse() throws IOException, UnexpectedBlobDigestException { InputStream blobContent = new ByteArrayInputStream("some BLOB content".getBytes(StandardCharsets.UTF_8)); DescriptorDigest testBlobDigest = Digests.computeDigest(blobContent).getDigest(); blobContent.reset()...
@Override public void toPB(EncryptionKeyPB pb, KeyMgr mgr) { super.toPB(pb, mgr); pb.type = EncryptionKeyTypePB.NORMAL_KEY; pb.algorithm = algorithm; if (encryptedKey == null && plainKey != null) { // it's a plain master key pb.plainKey = plainKey; } e...
@Test public void testToPB() { EncryptionKeyPB pb = new EncryptionKeyPB(); KeyMgr mgr = new KeyMgr(); normalKey.toPB(pb, mgr); assertEquals(normalKey.getId(), pb.id.longValue()); assertEquals(normalKey.getCreateTime(), pb.createTime.longValue()); assertEquals(normalK...
@Override public ParSeqBasedCompletionStage<Void> thenAccept(Consumer<? super T> action) { return nextStageByComposingTask(_task.flatMap("thenAccept", (t) -> Task.action(() -> action.accept(t)))); }
@Test public void testThenAccept() throws Exception { Consumer<String> consumer = mock(Consumer.class); finish(createTestStage(TESTVALUE1).thenAccept(consumer)); verify(consumer, times(1)).accept(TESTVALUE1); }
public TransactionRole getTransactionRole() { return transactionRole; }
@Test public void getTransactionRole() { Assertions.assertEquals(nettyPoolKey.getTransactionRole(), RM_ROLE); }
public void validate(CreateReviewAnswerRequest request) { validateNotContainingText(request); Question question = questionRepository.findById(request.questionId()) .orElseThrow(() -> new SubmittedQuestionNotFoundException(request.questionId())); OptionGroup optionGroup = optionGr...
@Test void 저장되지_않은_질문에_대한_응답이면_예외가_발생한다() { // given long notSavedQuestionId = 100L; CreateReviewAnswerRequest request = new CreateReviewAnswerRequest( notSavedQuestionId, List.of(1L), null ); // when, then assertThatCode(() -> createCheckBoxAnswerReq...
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) { if (LOG.isTraceEnabled()) { LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}" + " Used Normalized Resources: {} Total Normalized Resources:...
@Test public void testCalculateMinThrowsIfTotalIsMissingCpu() { NormalizedResources resources = new NormalizedResources(normalize(Collections.singletonMap(Constants.COMMON_CPU_RESOURCE_NAME, 2))); NormalizedResources usedResources = new NormalizedResources(normalize(Collections.singletonMap(Constant...
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) { Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>(); for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) { Map<String, ...
@Test public void testValidateAndParseStringOffsetValue() { Map<Map<String, ?>, Map<String, ?>> partitionOffsets = createPartitionOffsetMap("topic", "10", "100"); Map<TopicPartition, Long> parsedOffsets = SinkUtils.parseSinkConnectorOffsets(partitionOffsets); assertEquals(1, parsedOffsets.si...
@Override public void setQuarantine(final Local file, final String originUrl, final String dataUrl) throws LocalAccessDeniedException { if(StringUtils.isEmpty(originUrl)) { log.warn("No origin url given for quarantine"); return; } if(StringUtils.isEmpty(dataUrl)) { ...
@Test public void testSetQuarantine() throws Exception { final QuarantineService q = new LaunchServicesQuarantineService(); Callable<Local> c = new Callable<Local>() { @Override public Local call() throws Exception { final NullLocal l = new NullLocal(System.ge...
public void process() throws Exception { if (_segmentMetadata.getTotalDocs() == 0) { LOGGER.info("Skip preprocessing empty segment: {}", _segmentMetadata.getName()); return; } // Segment processing has to be done with a local directory. File indexDir = new File(_indexDirURI); // ...
@Test public void testColumnMinMaxValue() throws Exception { constructV1Segment(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); // Remove min/max value from the metadata removeMinMaxValuesFromMetadataFile(_indexDir); IndexLoadingConf...
public static void info(final Logger logger, final String format, final Supplier<Object> supplier) { if (logger.isInfoEnabled()) { logger.info(format, supplier.get()); } }
@Test public void testNeverInfoWithFormat() { when(logger.isInfoEnabled()).thenReturn(false); LogUtils.info(logger, "testInfo: {}", supplier); verify(supplier, never()).get(); }
int commit(final Collection<Task> tasksToCommit) { int committed = 0; final Set<TaskId> ids = tasksToCommit.stream() .map(Task::id) .collect(Collectors.toSet()); maybeLockTasks(ids); // We have to throw the first uncaught exception after locki...
@Test public void shouldLockCommitableTasksOnCorruptionWithProcessingThreads() { final StreamTask activeTask1 = statefulTask(taskId00, taskId00ChangelogPartitions) .inState(State.RUNNING) .withInputPartitions(taskId00Partitions).build(); final StreamTask activeTask2 = statefu...
public SharedPool getSharedPool() { return sharedPool; }
@Test public void testSharedPool() { ShenyuConfig.SharedPool sharedPool = config.getSharedPool(); sharedPool.setCorePoolSize(3); sharedPool.setEnable(true); sharedPool.setMaximumPoolSize(5); sharedPool.setPrefix("test-"); sharedPool.setKeepAliveTime(1000L); sh...
@Override public JMXReporter createMetricReporter(Properties properties) { String portsConfig = properties.getProperty(ARG_PORT); return new JMXReporter(portsConfig); }
@Test void testPortRangeArgument() { Properties properties = new Properties(); properties.setProperty(JMXReporterFactory.ARG_PORT, "9000-9010"); JMXReporter metricReporter = new JMXReporterFactory().createMetricReporter(properties); try { assertThat(metricReporter.getPor...
public String toEnrichedRst() { StringBuilder b = new StringBuilder(); String lastKeyGroupName = ""; for (ConfigKey key : sortedConfigs()) { if (key.internalConfig) { continue; } if (key.group != null) { if (!lastKeyGroupName.e...
@Test public void toEnrichedRst() { final ConfigDef def = new ConfigDef() .define("opt1.of.group1", Type.STRING, "a", ValidString.in("a", "b", "c"), Importance.HIGH, "Doc doc.", "Group One", 0, Width.NONE, "..", Collections.emptyList()) .define("opt2.o...
public static String initCacheDir(String namespace, NacosClientProperties properties) { String jmSnapshotPath = properties.getProperty(JM_SNAPSHOT_PATH_PROPERTY); String namingCacheRegistryDir = ""; if (properties.getProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR) != null)...
@Test void testInitCacheDirWithDefaultRootAndWithoutCache2() { NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty("user.home", "/home/test"); String actual = CacheDirUtil.initCacheDir("test", properties); assertEquals("/home/test/nacos...
public List<String> getLiveBrokers() { List<String> brokerUrls = new ArrayList<>(); try { byte[] brokerResourceNodeData = _zkClient.readData(BROKER_EXTERNAL_VIEW_PATH, true); brokerResourceNodeData = unpackZnodeIfNecessary(brokerResourceNodeData); JsonNode jsonObject = OBJECT_READER.readTree(g...
@Test public void testGetBrokerListByInstanceConfigDefault() { configureData(_instanceConfigPlain, false); final List<String> brokers = _externalViewReaderUnderTest.getLiveBrokers(); assertEquals(brokers, Arrays.asList("first.pug-pinot-broker-headless:8099")); }
public static Float toFloat(Object value, Float defaultValue) { return convertQuietly(Float.class, value, defaultValue); }
@Test public void toFloatTest() { // https://gitee.com/dromara/hutool/issues/I4M0E4 final String hex2 = "CD0CCB43"; final byte[] value = HexUtil.decodeHex(hex2); final float f = Convert.toFloat(value); assertEquals(406.1F, f, 0); }
@Override public synchronized double getFractionConsumed() { if (position == null) { return 0; } else if (done) { return 1.0; } else if (position.compareTo(range.getEndKey()) >= 0) { return 1.0; } return range.estimateFractionForKey(position); }
@Test public void testGetFractionConsumed() { ByteKeyRangeTracker tracker = ByteKeyRangeTracker.of(INITIAL_RANGE); double delta = 0.00001; assertEquals(0.0, tracker.getFractionConsumed(), delta); tracker.tryReturnRecordAt(true, INITIAL_START_KEY); assertEquals(0.0, tracker.getFractionConsumed(),...
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } final double pos = q...
@Test public void bigQuantilesAreTheLastValue() throws Exception { assertThat(snapshot.getValue(1.0)) .isEqualTo(5, offset(0.1)); }
static List<GeneratedResource> getGeneratedResources(EfestoClassesContainer finalOutput) { List<GeneratedResource> toReturn = new ArrayList<>(); for (String key : finalOutput.getCompiledClassesMap().keySet()) { toReturn.add(getGeneratedClassResource(key)); } return toReturn; ...
@Test void getGeneratedResources() { List<GeneratedResource> retrieved = CompilationManagerUtils.getGeneratedResources(finalOutput); commonEvaluateGeneratedIntermediateResources(retrieved); }
@Override public TTableDescriptor toThrift(List<DescriptorTable.ReferencedPartitionInfo> partitions) { TJDBCTable tJDBCTable = new TJDBCTable(); if (!Strings.isNullOrEmpty(resourceName)) { JDBCResource resource = (JDBCResource) (GlobalStateMgr.getCurrentState().getRes...
@Test public void testToThrift(@Mocked GlobalStateMgr globalStateMgr, @Mocked ResourceMgr resourceMgr) throws Exception { new Expectations() { { GlobalStateMgr.getCurrentState(); result = globalStateMgr; globalStateMgr...
EncodedDiscreteResources add(EncodedDiscreteResources other) { checkArgument(this.codec.getClass() == other.codec.getClass()); RangeSet<Integer> newRangeSet = TreeRangeSet.create(this.rangeSet); newRangeSet.addAll(other.rangeSet); return new EncodedDiscreteResources(newRangeSet, this.c...
@Test public void testAdd() { DiscreteResource res1 = Resources.discrete(DID, PN, VID1).resource(); DiscreteResource res2 = Resources.discrete(DID, PN, VID2).resource(); DiscreteResource res3 = Resources.discrete(DID, PN, VID3).resource(); EncodedDiscreteResources sut = EncodedDiscr...
public ActionResult apply(Agent agent, Map<String, String> request) { log.debug("Writing content to file {}", request.get("filename")); String filename = request.get("filename"); if (filename == null || filename.isEmpty()) { return ActionResult.builder() .status(...
@Test void testApplyWithValidInput() { String agentId = "agent1"; String filename = "test.txt"; String fileContent = "This is a test file."; Map<String, String> request = new HashMap<>(); request.put("filename", filename); request.put("body", fileContent); Do...
public Set<EntityDescriptor> resolveEntities(Collection<EntityDescriptor> unresolvedEntities) { final MutableGraph<EntityDescriptor> dependencyGraph = GraphBuilder.directed() .allowsSelfLoops(false) .nodeOrder(ElementOrder.insertion()) .build(); unresolved...
@Test public void resolveEntitiesWithTransitiveDependencies() throws NotFoundException { final StreamMock streamMock = new StreamMock(ImmutableMap.of( "_id", "stream-1234", StreamImpl.FIELD_TITLE, "Stream Title")) { @Override public Set<Output> getOutp...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchResponseMetrics() { buildFetcher(); String topic1 = "foo"; String topic2 = "bar"; TopicPartition tp1 = new TopicPartition(topic1, 0); TopicPartition tp2 = new TopicPartition(topic2, 0); subscriptions.assignFromUser(mkSet(tp1, tp2)); ...
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time zon...
@Test public void shouldRoundTripWithStringToTimestamp() { final String pattern = "yyyy-MM-dd HH:mm:ss.SSS'Freya'"; final StringToTimestamp stringToTimestamp = new StringToTimestamp(); IntStream.range(-10_000, 20_000) .parallel() .forEach(idx -> { final long millis = 153836161112...
@CheckForNull static String checkEventName(@Nullable String name) { if (name == null) { return null; } checkArgument(name.length() <= MAX_NAME_LENGTH, "Event name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", name.length(), MAX_NAME_LENGTH, name); return name...
@Test void fail_if_name_longer_than_400() { assertThatThrownBy(() -> EventValidator.checkEventName(repeat("a", 400 + 1))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Event name length (401) is longer than the maximum authorized (400)."); }
public Object invokeMethod(String methodName) { return invokeMethod(methodName, (Class []) null, (Object []) null); }
@Test void testInvokeMethod_shouldAbleToInvokeMethodWithClass() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Resource r = new Resource(null, new ResourceId("pool1", "name1"), "object"); assertEquals(true, r.invokeMethod("startsWith", new Class...
@Override public GenericRow transform(GenericRow record) { for (Map.Entry<String, FunctionEvaluator> entry : _expressionEvaluators.entrySet()) { String column = entry.getKey(); FunctionEvaluator transformFunctionEvaluator = entry.getValue(); Object existingValue = record.getValue(column); ...
@Test public void testTransformConfigsFromTableConfig() { Schema pinotSchema = new Schema.SchemaBuilder().addSingleValueDimension("userId", FieldSpec.DataType.LONG) .addSingleValueDimension("fullName", FieldSpec.DataType.STRING) .addMultiValueDimension("bids", FieldSpec.DataType.INT) .addS...
@Override public Object[] toArray() { List<Object> res = (List<Object>) get(valueRangeAsync(0, -1)); return res.toArray(); }
@Test public void testToArray() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); set.add(0, "1"); set.add(1, "4"); set.add(2, "2"); set.add(3, "5"); set.add(4, "3"); assertThat(Arrays.asList(set.toArray())).containsExactly("1", "4", "2"...
@Override public void setTimestamp(final Path file, final TransferStatus status) throws BackgroundException { try { final SoftwareVersionData version = session.softwareVersion(); final Matcher matcher = Pattern.compile(SDSSession.VERSION_REGEX).matcher(version.getRestApiVersion()); ...
@Test public void testWriteTimestampFile() 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, Pa...
public String format() { StringBuilder builder = new StringBuilder(); for (RestartActions.Entry entry : actions.getEntries()) { builder.append("In cluster '" + entry.getClusterName() + "' of type '" + entry.getClusterType() + "':\n"); builder.append(" Restart services of type ...
@Test public void formatting_of_multiple_actions() { RestartActions actions = new ConfigChangeActionsBuilder(). restart(CHANGE_MSG, CLUSTER, CLUSTER_TYPE, SERVICE_TYPE, SERVICE_NAME). restart(CHANGE_MSG_2, CLUSTER, CLUSTER_TYPE, SERVICE_TYPE, SERVICE_NAME). re...
public RelDataType createRelDataTypeFromSchema(Schema schema) { Builder builder = new Builder(this); boolean enableNullHandling = schema.isEnableColumnBasedNullHandling(); for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) { builder.add(entry.getKey(), toRelDataType(entry.g...
@Test(dataProvider = "relDataTypeConversion") public void testNotNullableScalarTypes(FieldSpec.DataType dataType, RelDataType scalarType, boolean columnNullMode) { TypeFactory typeFactory = new TypeFactory(); Schema testSchema = new Schema.SchemaBuilder() .addDimensionField("col", dataType, field -> f...
@Override boolean addStorage(DatanodeStorageInfo storage, Block reportedBlock) { Preconditions.checkArgument(BlockIdManager.isStripedBlockID( reportedBlock.getBlockId()), "reportedBlock is not striped"); Preconditions.checkArgument(BlockIdManager.convertToStripedID( reportedBlock.getBlockId())...
@Test public void testAddStorage() { // first add NUM_DATA_BLOCKS + NUM_PARITY_BLOCKS storages, i.e., a complete // group of blocks/storages DatanodeStorageInfo[] storageInfos = DFSTestUtil.createDatanodeStorageInfos( totalBlocks); Block[] blocks = createReportedBlocks(totalBlocks); int i ...
@Override public final void isEqualTo(@Nullable Object other) { @SuppressWarnings("UndefinedEquals") // the contract of this method is to follow Multimap.equals boolean isEqual = Objects.equal(actual, other); if (isEqual) { return; } // Fail but with a more descriptive message: if ((act...
@Test public void setMultimapIsEqualToListMultimap_fails() { ImmutableSetMultimap<String, String> multimapA = ImmutableSetMultimap.<String, String>builder() .putAll("kurt", "kluever", "russell", "cobain") .build(); ImmutableListMultimap<String, String> multimapB = Immut...
@Implementation public static synchronized Context getRemoteContext(Context context) { return googlePlayServicesUtilImpl.getRemoteContext(context); }
@Test public void getRemoteContext_defaultNotNull() { assertNotNull(GooglePlayServicesUtil.getRemoteContext(RuntimeEnvironment.getApplication())); }
@Override public KsMaterializedQueryResult<Row> get( final GenericKey key, final int partition, final Optional<Position> position ) { try { final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key); StateQueryRequest<ValueAndTimestamp<GenericRow>> ...
@Test public void shouldRangeQueryWithCorrectParams_noBounds() { // Given: when(kafkaStreams.query(any())).thenReturn(getIteratorResult()); // When: table.get(PARTITION, null, null); // Then: verify(kafkaStreams).query(queryTypeCaptor.capture()); StateQueryRequest request = queryTypeCapt...
@Override public String get(String name) { checkKey(name); String value = null; String[] keyParts = splitKey(name); String ns = registry.getNamespaceURI(keyParts[0]); if (ns != null) { try { XMPProperty prop = xmpData.getProperty(ns, keyParts[1])...
@Test public void get_notQualifiedKey_throw() { assertThrows(PropertyTypeException.class, () -> { xmpMeta.get("wrongKey"); }); }
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) { Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>(); for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) { Map<String, ...
@Test public void testValidateAndParseEmptyPartitionOffsetMap() { // expect no exception to be thrown Map<TopicPartition, Long> parsedOffsets = SinkUtils.parseSinkConnectorOffsets(new HashMap<>()); assertTrue(parsedOffsets.isEmpty()); }
void writeConfigToDisk() { VespaTlsConfig config = VespaZookeeperTlsContextUtils.tlsContext() .map(ctx -> new VespaTlsConfig(ctx, TransportSecurityUtils.getInsecureMixedMode())) .orElse(Vesp...
@Test(expected = RuntimeException.class) public void require_that_this_id_must_be_present_amongst_servers() { ZookeeperServerConfig.Builder builder = new ZookeeperServerConfig.Builder(); builder.zooKeeperConfigFile(cfgFile.getAbsolutePath()); builder.server(newServer(1, "bar", 234, 432, fals...
@Override public void execute(final List<String> args, final PrintWriter terminal) { CliCmdUtil.ensureArgCountBounds(args, 0, 1, HELP); if (args.isEmpty()) { final String setting = requestPipeliningSupplier.get() ? "ON" : "OFF"; terminal.printf("Current %s configuration: %s%n", NAME, setting); ...
@Test public void shouldRejectUpdateOnInvalidSetting() { // When: requestPipeliningCommand.execute(ImmutableList.of("bad"), terminal); // Then: verify(settingConsumer, never()).accept(anyBoolean()); assertThat(out.toString(), containsString(String.format("Invalid %s setting: bad", Request...
@Override public ResponseHeader execute() throws SQLException { check(sqlStatement); ProxyContext.getInstance().getContextManager().getPersistServiceFacade().getMetaDataManagerPersistService().createDatabase(sqlStatement.getDatabaseName()); return new UpdateResponseHeader(sqlStatement); ...
@Test void assertExecuteCreateExistDatabaseWithIfNotExists() throws SQLException { when(statement.getDatabaseName()).thenReturn("foo_db"); when(statement.isIfNotExists()).thenReturn(true); ContextManager contextManager = mockContextManager(); when(ProxyContext.getInstance().getContex...
@Override public void onWorkflowFinalized(Workflow workflow) { WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput()); WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow); String reason = workflow.getReasonForIncompletion(); LOG.inf...
@Test public void testInconsistentStatsOnWorkflowFinalized() { StepRuntimeState state = new StepRuntimeState(); state.setStatus(StepInstance.Status.FATALLY_FAILED); when(stepInstanceDao.getAllStepStates(any(), anyLong(), anyLong())) .thenReturn(singletonMap("foo", state)); when(workflow.getSta...