focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static boolean isBindingAnnotation(Annotation annotation) { LinkedList<Class<?>> queue = new LinkedList<>(); queue.add(annotation.getClass()); queue.addAll(List.of(annotation.getClass().getInterfaces())); while (!queue.isEmpty()) { Class<?> clazz = queue.removeFirst()...
@Test void check_if_annotation_is_a_binding_annotation() { assertTrue(isBindingAnnotation(Names.named("name"))); assertFalse(isBindingAnnotation(Named.class.getAnnotations()[0])); }
@VisibleForTesting Map<String, List<Operation>> computeOperations(SegmentDirectory.Reader segmentReader) throws Exception { Map<String, List<Operation>> columnOperationsMap = new HashMap<>(); // Does not work for segment versions < V3. if (_segmentDirectory.getSegmentMetadata().getVersion().compare...
@Test public void testComputeOperationDisableForwardIndex() throws Exception { // Setup SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory); SegmentDirectory segmentLocalFSDirectory = new SegmentLocalFSDirectory(_segmentDirectory, existingSegmentMetadata,...
@Override public byte[] serialize() { byte[] actorInfo = Optional.ofNullable(tlv.get(TYPE_ACTOR)).map(LacpTlv::serialize) .orElse(new byte[0]); byte[] partnerInfo = Optional.ofNullable(tlv.get(TYPE_PARTNER)).map(LacpTlv::serialize) .orElse(new byte[0]); byte[]...
@Test public void serialize() { assertArrayEquals(data, LACP.serialize()); }
@SuppressWarnings("unchecked") public static <T> TypeInformation<T> convert(String jsonSchema) { Preconditions.checkNotNull(jsonSchema, "JSON schema"); final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); mapper.getFactory() .enable(JsonParser.Feature.ALLOW_...
@Test void testWrongType() { assertThatThrownBy(() -> JsonRowSchemaConverter.convert("{ type: 'whatever' }")) .isInstanceOf(IllegalArgumentException.class); }
public static CreateSourceAsProperties from(final Map<String, Literal> literals) { try { return new CreateSourceAsProperties(literals, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" ); throw new ...
@Test public void shouldThrowIfValueSchemaNameAndAvroSchemaNameProvided() { // When: final Exception e = assertThrows( KsqlException.class, () -> CreateSourceAsProperties.from( ImmutableMap.<String, Literal>builder() .put(VALUE_SCHEMA_FULL_NAME, new StringLiteral("v...
@Override @SuppressWarnings("unchecked") public <T> T create(Class<T> extensionClass) { String extensionClassName = extensionClass.getName(); ClassLoader extensionClassLoader = extensionClass.getClassLoader(); if (!cache.containsKey(extensionClassLoader)) { cache.put(extensi...
@Test public void createNewEachTime() { ExtensionFactory extensionFactory = new SingletonExtensionFactory(pluginManager, "FailTestExtension.class"); Object extensionOne = extensionFactory.create(TestExtension.class); Object extensionTwo = extensionFactory.create(TestExtension.class); ...
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) { return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature); }
@Test public void testDeclAndUsageOfTimerInSuperclass() throws Exception { DoFnSignature sig = DoFnSignatures.getSignature(new DoFnOverridingAbstractTimerUse().getClass()); assertThat(sig.timerDeclarations().size(), equalTo(1)); assertThat(sig.processElement().extraParameters().size(), equalTo(2)...
int calculateParamTransportSize(Object value) { if (value == null) { return 0; } // Layout for primitives: |type flag(1)|value| // size = original size + type flag (1) if (value instanceof Integer || int.class.isInstance(value)) { return 5; } else ...
@Test public void testCalculateParamTransportSize() { ParamFlowRequestDataWriter writer = new ParamFlowRequestDataWriter(); // POJO (non-primitive type) should not be regarded as a valid parameter. assertEquals(0, writer.calculateParamTransportSize(new SomePojo().setParam1("abc"))); ...
public static ByteBuffer cloneByteBuffer(ByteBuffer buf) { ByteBuffer ret = ByteBuffer.allocate(buf.limit() - buf.position()); if (buf.hasArray()) { ret.put(buf.array(), buf.position(), buf.limit() - buf.position()); } else { // direct buffer ret.put(buf); } ret.flip(); return ...
@Test public void cloneDirectByteBuffer() { final int bufferSize = 10; ByteBuffer bufDirect = ByteBuffer.allocateDirect(bufferSize); for (byte i = 0; i < bufferSize; i++) { bufDirect.put(i); } ByteBuffer bufClone = BufferUtils.cloneByteBuffer(bufDirect); assertEquals(bufDirect, bufClone)...
protected void declareRuleFromAttribute(final Attribute attribute, final String parentPath, final int attributeIndex, final List<KiePMMLDroolsRule> rules, final String statusToSet, ...
@Test void declareRuleFromAttributeWithSimplePredicateLastCharacteristic() { Attribute attribute = getSimplePredicateAttribute(); final String parentPath = "parent_path"; final int attributeIndex = 2; final List<KiePMMLDroolsRule> rules = new ArrayList<>(); final String statu...
public static Optional<String> getViewName(final String path) { Pattern pattern = Pattern.compile(getMetaDataNode() + VIEWS_PATTERN + "/([\\w\\-]+)$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(path); return matcher.find() ? Optional.of(matcher.group(3)) : Optional.empty(); ...
@Test void assertGetViewName() { Optional<String> actual = ViewMetaDataNode.getViewName("/metadata/foo_db/schemas/foo_schema/views/foo_view"); assertTrue(actual.isPresent()); assertThat(actual.get(), is("foo_view")); }
public static HintValueContext extractHint(final String sql) { if (!containsSQLHint(sql)) { return new HintValueContext(); } HintValueContext result = new HintValueContext(); int hintKeyValueBeginIndex = getHintKeyValueBeginIndex(sql); String hintKeyValueText = sql.su...
@Test void assertSQLHintSkipSQLRewrite() { HintValueContext actual = SQLHintUtils.extractHint("/* SHARDINGSPHERE_HINT: SKIP_SQL_REWRITE=true */"); assertTrue(actual.isSkipSQLRewrite()); }
public static int read( final UnsafeBuffer termBuffer, final int termOffset, final FragmentHandler handler, final int fragmentsLimit, final Header header, final ErrorHandler errorHandler, final long currentPosition, final Position subscriberPosition) {...
@Test void shouldReadFirstMessage() { final int msgLength = 1; final int frameLength = HEADER_LENGTH + msgLength; final int alignedFrameLength = align(frameLength, FRAME_ALIGNMENT); final int termOffset = 0; when(termBuffer.getIntVolatile(0)).thenReturn(frameLength); ...
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void kGroupedStreamZeroArgCountWithTopologyConfigShouldPreserveTopologyStructure() { // override the default store into in-memory final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY)); builder.stream("input-topic") .groupByK...
public static URL parseEncodedStr(String encodedURLStr) { Map<String, String> parameters = null; int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F"); // '?' if (pathEndIdx >= 0) { parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3); } else { pat...
@Test void testEncoded() { testCases.forEach(testCase -> { assertThat(URLStrParser.parseEncodedStr(URL.encode(testCase)), equalTo(URL.valueOf(testCase))); }); errorEncodedCases.forEach(errorCase -> { Assertions.assertThrows(RuntimeException.class, () -> URLStrParser....
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void workerAddrUpdateWithIdUnchanged() throws Exception { MultiProbeHashPolicy policy = new MultiProbeHashPolicy(mConf); List<WorkerInfo> workers = new ArrayList<>(); workers.add(new WorkerInfo().setIdentity(WorkerIdentityTestUtils.ofLegacyId(1L)) .setAddress(new WorkerNetAddress().se...
@Override public Collection<ThreadPoolPlugin> getAllPlugins() { return mainLock.applyWithReadLock(() -> { // sort if necessary if (isEnableSort()) { return registeredPlugins.values().stream() .sorted(pluginComparator) .c...
@Test public void testGetAllPlugins() { manager.register(new TestExecuteAwarePlugin()); manager.register(new TestRejectedAwarePlugin()); Assert.assertEquals(2, manager.getAllPlugins().size()); }
@Override public Map<String, Object> processCsvFile(String encodedCsvData, boolean dryRun) throws JsonProcessingException { services = new HashMap<>(); serviceParentChildren = new HashMap<>(); Map<String, Object> result = super.processCsvFile(encodedCsvData, dryRun); if (!services.is...
@Test void processCsvFileFailDigidTrueWithMultipleServiceOrganizationRolesTest() throws IOException { mockconnection(); String csvData = """SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...
public static boolean isCoastedRadarHit(StarsRadarHit starsRh) { String statusFieldValue = starsRh.trackStatus(); return (statusFieldValue == null) ? false : STARS_COASTED_FLAGS.contains(statusFieldValue); }
@Test public void testIsCoastedRadarHit() { StarsRadarHit active = (StarsRadarHit) NopMessageType.parse(ACTIVE_STARS); StarsRadarHit coasted = (StarsRadarHit) NopMessageType.parse(COASTED_STARS); StarsRadarHit dropped = (StarsRadarHit) NopMessageType.parse(DROPPED_STARS); assertFal...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { try { final AttributedList<Path> objects = new AttributedList<>(); Marker marker = new Marker(null, null); final String containerId = fileid....
@Test public void testListFileNameDot() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir( new Path(String.format("test-%s", new AsciiRandomStringService().random()), EnumSet.of(Pa...
@Override protected String buildUndoSQL() { TableRecords afterImage = sqlUndoLog.getAfterImage(); List<Row> afterImageRows = afterImage.getRows(); if (CollectionUtils.isEmpty(afterImageRows)) { throw new ShouldNeverHappenException("Invalid UNDO LOG"); } return gen...
@Test public void buildUndoSQL() { OracleUndoInsertExecutor executor = upperCase(); String sql = executor.buildUndoSQL(); Assertions.assertNotNull(sql); Assertions.assertTrue(sql.contains("DELETE")); Assertions.assertTrue(sql.contains("ID")); Assertions.assertTrue(sql...
static BlockStmt getApplyVariableDeclaration(final String variableName, final Apply apply) { final MethodDeclaration methodDeclaration = APPLY_TEMPLATE.getMethodsByName(GETKIEPMMLAPPLY).get(0).clone(); final BlockStmt applyBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLE...
@Test void getApplyVariableDeclarationWithFieldRefs() throws IOException { String variableName = "variableName"; Apply apply = new Apply(); apply.setFunction(function); String mapMissingTo = "mapMissingTo"; apply.setMapMissingTo(mapMissingTo); String defaultValue = "d...
@Override @Transactional(value="defaultTransactionManager") public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException { if (Strings.isNullOrEmpty(refreshTokenValue)) { // throw an invalid token exception if there's no refresh token val...
@Test public void refreshAccessToken_requestingEmptyScope() { Set<String> emptyScope = newHashSet(); tokenRequest.setScope(emptyScope); OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); assertTh...
public static Map<Node, List<Node>> getNestedChildrenNodesMap(Document document, String mainContainerNodeName, String containerNodeName, String childNodeName) { Map<Node, List<Node>> toReturn = new HashMap<>(); asStream(document.getElementsByTagName(mainContainerNodeName)) .map(mainConta...
@Test public void getNestedChildrenNodesMap() throws Exception { Document document = DOMParserUtil.getDocument(XML); Map<Node, List<Node>> retrieved = DOMParserUtil.getNestedChildrenNodesMap(document, MAIN_NODE, CHILD_NODE, TEST_NODE); assertThat(retrieved).isNotNull(); assertThat(re...
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) { SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt() .orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo())); SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt() ...
@Test public void testAllowNullNestedClasses() { JSONSchema<NestedBar> jsonSchema = JSONSchema.of(SchemaDefinition.<NestedBar>builder().withPojo(NestedBar.class).build()); JSONSchema<NestedBarList> listJsonSchema = JSONSchema.of(SchemaDefinition.<NestedBarList>builder().withPojo(NestedBarList.class)...
@Override public DataSink createDataSink(Context context) { FactoryHelper.createFactoryHelper(this, context) .validateExcept(TABLE_CREATE_PROPERTIES_PREFIX, SINK_PROPERTIES_PREFIX); StarRocksSinkOptions sinkOptions = buildSinkConnectorOptions(context.getFactoryConfig...
@Test void testCreateDataSink() { DataSinkFactory sinkFactory = FactoryDiscoveryUtils.getFactoryByIdentifier("starrocks", DataSinkFactory.class); Assertions.assertThat(sinkFactory).isInstanceOf(StarRocksDataSinkFactory.class); Configuration conf = Configurati...
public static boolean isPrimitive(Object bean) { return isPrimitive(bean.getClass()); }
@Test public void testIsPrimitive() { Assert.assertTrue(ReflectKit.isPrimitive(int.class)); Assert.assertTrue(ReflectKit.isPrimitive(long.class)); Assert.assertTrue(ReflectKit.isPrimitive(boolean.class)); Assert.assertTrue(ReflectKit.isPrimitive(short.class)); Assert.assertTr...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test(expectedExceptions = RuntimeException.class) public void testMissingOpenParen() { PredicateExpressionParser.parse("com.linkedin.data.it.AlwaysFalsePredicate)"); }
public static String groupSessionTimeoutKey(String groupId, String memberId) { return "session-timeout-" + groupId + "-" + memberId; }
@Test public void testConsumerGroupMemberUsingClassicProtocolFencedWhenSessionTimeout() { String groupId = "group-id"; String memberId = Uuid.randomUuid().toString(); int sessionTimeout = 5000; List<ConsumerGroupMemberMetadataValue.ClassicProtocol> protocols = Collections.singletonL...
@Override public void execute(Runnable r) { runQueue.add(r); schedule(r); }
@Test void testSerial() throws InterruptedException { int total = 10000; Map<String, Integer> map = new HashMap<>(); map.put("val", 0); Semaphore semaphore = new Semaphore(1); CountDownLatch startLatch = new CountDownLatch(1); AtomicBoolean failed = new AtomicBoolea...
public FloatArrayAsIterable usingExactEquality() { return new FloatArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject()); }
@Test public void usingExactEquality_contains_otherTypes_doubleNotSupported() { double expected = 2.0; float[] actual = array(1.0f, 2.0f, 3.0f); expectFailureWhenTestingThat(actual).usingExactEquality().contains(expected); assertFailureKeys( "value of", "expected to contain", "...
@Udf(description = "Returns a masked version of the input string. All characters except for the" + " last n will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final Str...
@Test public void shouldReturnNullForNullInput() { final String result = udf.mask(null, 5); assertThat(result, is(nullValue())); }
public synchronized boolean saveNamespace(long timeWindow, long txGap, FSNamesystem source) throws IOException { if (timeWindow > 0 || txGap > 0) { final FSImageStorageInspector inspector = storage.readAndInspectDirs( EnumSet.of(NameNodeFile.IMAGE, NameNodeFile.IMAGE_ROLLBACK), Start...
@Test public void testSaveAndLoadErasureCodingPolicies() throws IOException{ Configuration conf = new Configuration(); final int blockSize = 16 * 1024 * 1024; conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataN...
@PUT @Path("{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response updateSubnet(@PathParam("id") String id, InputStream input) throws IOException { log.trace(String.format(MESSAGE, "UPDATE " + id)); String inputStr = IOUtils.toString(input, RE...
@Test public void testUpdateSubnetWithNonexistId() { expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes(); replay(mockOpenstackHaService); mockOpenstackNetworkAdminService.updateSubnet(anyObject()); expectLastCall().andThrow(new IllegalArgumentException()); re...
@VisibleForTesting public void validateSmsTemplateCodeDuplicate(Long id, String code) { SmsTemplateDO template = smsTemplateMapper.selectByCode(code); if (template == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的字典类型 if (id == null) { throw exception(...
@Test public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String code = randomString(); // mock 数据 smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 assertServiceException(() ...
Command getCommand(String request) { var commandClass = getCommandClass(request); try { return (Command) commandClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new ApplicationException(e); } }
@Test void testGetCommandUnknown() { Command command = dispatcher.getCommand("Unknown"); assertNotNull(command); assertTrue(command instanceof UnknownCommand); }
void startup(@Observes StartupEvent event) { if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) { backgroundJobServerInstance.get().start(); } if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { dashboardWebServerInstance.get().start(); } ...
@Test void jobRunrStarterDoesNotStartDashboardIfNotConfigured() { when(dashboardConfiguration.enabled()).thenReturn(false); jobRunrStarter.startup(new StartupEvent()); verify(dashboardWebServerInstance, never()).get(); }
@SuppressWarnings("unchecked") public static <T> NFAFactory<T> compileFactory( final Pattern<T, ?> pattern, boolean timeoutHandling) { if (pattern == null) { // return a factory for empty NFAs return new NFAFactoryImpl<>( 0, Collect...
@Test public void testWindowTimesCorrectlySet() { Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .followedBy("middle") .within(Time.seconds(10), WithinType.PREVIOUS_AND_CURRENT) .followedBy("then") ...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchIPv6SrcTest() { Criterion criterion = Criteria.matchIPv6Src(ipPrefix6); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
public List<ParsedTerm> filterElementsContainingUsefulInformation(final Map<String, List<ParsedTerm>> parsedTermsGroupedByField) { return parsedTermsGroupedByField.values() .stream() .map(this::filterElementsContainingUsefulInformation) .flatMap(Collection::stream...
@Test void doesNothingOnEmptyInput() { assertThat(toTest.filterElementsContainingUsefulInformation(Map.of())) .isEmpty(); }
public static void copyDirectory(File srcDir, File destDir) throws IOException { FileUtils.copyDirectory(srcDir, destDir); }
@Test void testCopyDirectory() throws IOException { Path srcPath = Paths.get(TMP_PATH, UUID.randomUUID().toString()); DiskUtils.forceMkdir(srcPath.toString()); File nacos = DiskUtils.createTmpFile(srcPath.toString(), "nacos", ".ut"); Path destPath = Paths.get(TMP_PATH, UUID....
@Override public void run() throws InvalidInputException { String tableType = _input.getTableType(); if ((tableType.equalsIgnoreCase(REALTIME) || tableType.equalsIgnoreCase(HYBRID))) { _output.setAggregateMetrics(shouldAggregate(_input)); } }
@Test public void testRunNonAggregate() throws Exception { Set<String> metrics = ImmutableSet.of("a", "b", "c"); InputManager input = createInput(metrics, "select sum(a), sum(b), sum(c) from tableT", "select sum(a), avg(b) from tableT2"); ConfigManager output = new ConfigManager(); Aggre...
public static void clear() { logList.clear(); }
@Test void testClear() { DubboAppender.doStart(); DubboAppender appender = new DubboAppender(); appender.append(event); assumeTrue(1 == DubboAppender.logList.size()); DubboAppender.clear(); assertThat(DubboAppender.logList, hasSize(0)); }
public ScriptBuilder opFalse() { return number(0); // push OP_0/OP_FALSE }
@Test public void testOpFalse() { byte[] expected = new byte[] { OP_FALSE }; byte[] s = new ScriptBuilder().opFalse().build().program(); assertArrayEquals(expected, s); }
public static boolean hasCauseOf(Throwable t, Class<? extends Throwable> causeType) { return Throwables.getCausalChain(t) .stream() .anyMatch(c -> causeType.isAssignableFrom(c.getClass())); }
@Test public void hasCauseOf_returnsTrueIfTheExceptionItselfIsSubtypeOfTheProvidedType() { assertThat(ExceptionUtils.hasCauseOf(new SocketTimeoutException("asdasd"), IOException.class)).isTrue(); assertThat(ExceptionUtils.hasCauseOf(new IOException("asdasd"), IOException.class)).isTrue(); }
@Override public String getTargetRestEndpointURL() { return URL; }
@Test void testURL() { assertThat(instance.getTargetRestEndpointURL()).endsWith("yarn-stop"); }
public LibResponse createBook(BookDto bookDto) { log.info("Book DTO from POST request : {}", bookDto); LibResponse resp = null; AuditDto audit = null; try { Call<LibResponse> callLibResponse = libraryClient.createNewBook(bookDto); Response<LibResponse> libResponse...
@Test @DisplayName("Successful call to create a book") public void postBookRequestTest() throws Exception { String booksResponse = getBooksResponse("/request/postBook.json"); BookDto bookDto = new ObjectMapper().readValue(booksResponse, BookDto.class); LibResponse response = new LibRespo...
public void processRow(GenericRow decodedRow, Result reusedResult) throws Exception { reusedResult.reset(); if (_complexTypeTransformer != null) { // TODO: consolidate complex type transformer into composite type transformer decodedRow = _complexTypeTransformer.transform(decodedRow); } ...
@Test public void testMultipleRow() throws Exception { TableConfig config = createTestTableConfig(); Schema schema = Fixtures.createSchema(); TransformPipeline pipeline = new TransformPipeline(config, schema); GenericRow multipleRow = Fixtures.createMultipleRow(9527); Collection<GenericRow> ...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenBigDecimalWithSurroundingSpaces_throws() { BigDecimal decimal = new BigDecimal("123.456"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" 123.456 ", decimal); Schema schema = Schema.builder().addDecimalField("a_decimal").addStringField("a_string").build(); ...
@Override public void isEqualTo(@Nullable Object expected) { if (sameClassMessagesWithDifferentDescriptors(actual, expected)) { // This can happen with DynamicMessages, and it's very confusing if they both have the // same string. failWithoutActual( simpleFact("Not true that messages c...
@Test public void testDifferentDynamicDescriptors() throws InvalidProtocolBufferException { // Only test once. if (!isProto3()) { return; } DynamicMessage message1 = DynamicMessage.parseFrom( TestMessage2.getDescriptor(), TestMessage2.newBuilder().setOInt(43).bui...
public void setText(String newText) { this.text = newText; this.dateUpdated = new Date(); parseText(); }
@Test void testInvalidProperties() { Note note = createNote(); Paragraph paragraph = new Paragraph(note, null); assertThrows(RuntimeException.class, () -> { paragraph.setText("%test(p1=v1=v2) a"); }, "Invalid paragraph properties format"); }
@Override public List<DiscoveryUpstreamData> parseValue(final String jsonString) { if (StringUtils.isBlank(jsonString)) { return Collections.emptyList(); } GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(DiscoveryUpstreamData.class, this); Gson gson = gson...
@Test void testParseValue() { final String jsonString = "{\"protocol\":\"tcp\",\"url\":\"127.0.0.1:8188\",\"status\":1,\"weight\":1}"; final List<DiscoveryUpstreamData> expectDiscoveryUpstreamData = new ArrayList<>(); DiscoveryUpstreamData discoveryUpstreamData = new DiscoveryUpstreamData();...
@VisibleForTesting public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { throw exception(CONFIG_NOT_EXISTS); } return config; }
@Test public void testValidateConfigExists_success() { // mock 数据 ConfigDO dbConfigDO = randomConfigDO(); configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 // 调用成功 configService.validateConfigExists(dbConfigDO.getId()); }
@Override public boolean remove(Object o) { throw new UnsupportedOperationException("RangeSet is immutable"); }
@Test(expected = UnsupportedOperationException.class) public void remove1() throws Exception { RangeSet rs = new RangeSet(4); rs.remove(Integer.valueOf(1)); }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatDateLiteral() { assertThat(ExpressionFormatter.formatExpression(new DateLiteral(new Date(864000000))), equalTo("1970-01-11")); }
public String apiURL() { return DEFAULT_API_URL; }
@Test public void default_apiUrl() { assertThat(underTest.apiURL()).isEqualTo("https://api.bitbucket.org/"); }
@Override public ObjectNode encode(MappingAddress address, CodecContext context) { EncodeMappingAddressCodecHelper encoder = new EncodeMappingAddressCodecHelper(address, context); return encoder.encode(); }
@Test public void asMappingAddressTest() { MappingAddress address = MappingAddresses.asMappingAddress(AS); ObjectNode result = addressCodec.encode(address, context); assertThat(result, matchesMappingAddress(address)); }
public static String castValue(String value, Type requiredType, String valueType) { String requiredTypeName = requiredType.asString(); if (requiredTypeName.equals(valueType)) return value; return String.format("(%s) %s", requiredTypeName, value); }
@Test void castReturnValue_whenAValueIsNotAssignedByReturnShouldBeCasted() { Type returnType = StaticJavaParser.parseType("String"); Type valueType = StaticJavaParser.parseType("Object"); assertEquals( String.format("(%s) %s", returnType, RETURN_VALUE), castV...
public static <T> boolean contains(T[] array, T item) { for (T o : array) { if (o == null) { if (item == null) { return true; } } else { if (o.equals(item)) { return true; } ...
@Test public void contains_nullValue_returnsFalse() { Object[] array = new Object[1]; array[0] = new Object(); assertFalse(ArrayUtils.contains(array, null)); }
@Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = !ruleToNegate.isSatisfied(index, tradingRecord); traceIsSatisfied(index, satisfied); return satisfied; }
@Test public void isSatisfied() { assertFalse(satisfiedRule.negation().isSatisfied(0)); assertTrue(unsatisfiedRule.negation().isSatisfied(0)); assertFalse(satisfiedRule.negation().isSatisfied(10)); assertTrue(unsatisfiedRule.negation().isSatisfied(10)); }
public Optional<ContentPack> insert(final ContentPack pack) { if (findByIdAndRevision(pack.id(), pack.revision()).isPresent()) { LOG.debug("Content pack already found: id: {} revision: {}. Did not insert!", pack.id(), pack.revision()); return Optional.empty(); } final Wri...
@Test public void insertDuplicate() { final ContentPackV1 contentPack = ContentPackV1.builder() .id(ModelId.of("id")) .revision(1) .name("name") .description("description") .summary("summary") .vendor("vendor") ...
@Override public void onActivityDestroyed(Activity activity) { }
@Test public void onActivityDestroyed() { mActivityLifecycle.onActivityDestroyed(mActivity); }
@Override @SuppressWarnings("rawtypes") public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String,...
@Test public void reportsMetersInMinutes() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getOneMinuteRate()).thenReturn(2.0); when(meter.getFiveMinuteRate()).thenReturn(3.0); when(meter.getFifteenMinuteRate()).then...
public UpstreamCheck getUpstreamCheck() { return upstreamCheck; }
@Test public void testUpstreamCheck() { ShenyuConfig.UpstreamCheck upstreamCheck = config.getUpstreamCheck(); upstreamCheck.setEnabled(false); upstreamCheck.setPoolSize(10); upstreamCheck.setHealthyThreshold(4); upstreamCheck.setTimeout(10); upstreamCheck.setInterval(...
@VisibleForTesting static String extractTableName(MultivaluedMap<String, String> pathParameters, MultivaluedMap<String, String> queryParameters) { String tableName = extractTableName(pathParameters); if (tableName != null) { return tableName; } return extractTableName(queryParameters); }
@Test public void testExtractTableNameWithSchemaNameInPathParams() { MultivaluedMap<String, String> pathParams = new MultivaluedHashMap<>(); MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>(); pathParams.putSingle("schemaName", "C"); queryParams.putSingle("tableName", "D"); qu...
public ExtensionInstaller install(ExtensionContainer container, ExtensionMatcher matcher) { // core components for (Object o : BatchComponents.all()) { doInstall(container, matcher, null, o); } // plugin extensions installExtensionsForPlugins(container, matcher, pluginRepository.getPluginInfo...
@Test public void should_filter_extensions_to_install() { when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList(new PluginInfo("foo"))); when(pluginRepository.getPluginInstance("foo")).thenReturn(newPluginInstance(Foo.class, Bar.class)); ListContainer container = new ListContainer(); Exten...
@PostMapping("/updateDetailPath") @RequiresPermissions("system:authen:editResourceDetails") public ShenyuAdminResult updateDetailPath(@RequestBody @Valid final AuthPathWarpDTO authPathWarpDTO) { return appAuthService.updateDetailPath(authPathWarpDTO); }
@Test public void testUpdateDetailPath() throws Exception { final AuthPathDTO authPathDTO = new AuthPathDTO(); authPathDTO.setAppName("testApp"); authPathDTO.setPath("/test"); authPathDTO.setEnabled(true); List<AuthPathDTO> authPathDTOS = new ArrayList<>(); authPathDT...
@Override public void start() { initializeMonitorThread(); monitorThread.start(); }
@Test void shouldNotAllowMonitorToBeStartedMultipleTimes() { monitor.start(); assertThatThrownBy(() -> monitor.start()).isExactlyInstanceOf(IllegalStateException.class) .hasMessageContaining("Cannot start the monitor multiple times."); }
@Override public UpdateSchema renameColumn(String name, String newName) { Types.NestedField field = findField(name); Preconditions.checkArgument(field != null, "Cannot rename missing column: %s", name); Preconditions.checkArgument(newName != null, "Cannot rename a column to null"); Preconditions.check...
@Test public void testRenameMissingColumn() { assertThatThrownBy( () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); update.renameColumn("col", "fail"); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can...
public boolean updateAccessConfig(PlainAccessConfig plainAccessConfig) { if (plainAccessConfig == null) { log.error("Parameter value plainAccessConfig is null,Please check your parameter"); throw new AclException("Parameter value plainAccessConfig is null, Please check your parameter");...
@Test public void updateAccessConfigTest() { Assert.assertThrows(AclException.class, () -> plainPermissionManager.updateAccessConfig(null)); plainAccessConfig.setAccessKey("admin_test"); // Invalid parameter plainAccessConfig.setSecretKey("123456"); plainAccessConfig.setAdmi...
public URI getServerAddress() { return serverAddresses.get(0); }
@Test public void shouldParseHttpsAddress() throws Exception { // Given: final String serverAddress = "https://singleServer:8088"; final URI serverURI = new URI(serverAddress); // When: try (KsqlRestClient ksqlRestClient = clientWithServerAddresses(serverAddress)) { // Then: assertTha...
@Override public String toString() { return "DelegateAndSkipOnConcurrentExecutionDecorator{" + "isAlreadyRunning=" + isAlreadyRunning + ", runnable=" + runnable + ", executor=" + executor + ", throwable=" + throwable + '}'; ...
@Test public void toString_contains_runnables_info() { ResumableCountingRunnable runnable = new ResumableCountingRunnable(); Executor executor = command -> { }; String stringified = new DelegateAndSkipOnConcurrentExecutionDecorator(runnable, executor).toString(); assertTrue(...
public static void refreshSuperUserGroupsConfiguration() { //load server side configuration; refreshSuperUserGroupsConfiguration(new Configuration()); }
@Test public void testProxyUsersWithCustomPrefix() throws Exception { Configuration conf = new Configuration(false); conf.set("x." + REAL_USER_NAME + ".users", StringUtils.join(",", Arrays.asList(AUTHORIZED_PROXY_USER_NAME))); conf.set("x." + REAL_USER_NAME+ ".hosts", PROXY_IP); ProxyUsers.ref...
@Nullable public static String ipOrNull(@Nullable String ip) { if (ip == null || ip.isEmpty()) return null; if ("::1".equals(ip) || "127.0.0.1".equals(ip)) return ip; // special-case localhost IpFamily format = detectFamily(ip); if (format == IpFamily.IPv4Embedded) { ip = ip.substring(ip.lastIndex...
@Test void ipOrNull_ipv6() { assertThat(IpLiteral.ipOrNull("2001:db8::c001")).isEqualTo("2001:db8::c001"); }
@Override public final void getSize(@NonNull SizeReadyCallback cb) { sizeDeterminer.getSize(cb); }
@Test public void testDoesNotThrowOnPreDrawIfViewTreeObserverIsDead() { target.getSize(cb); int width = 1; int height = 2; LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height); view.setLayoutParams(layoutParams); ViewTreeObserver vto = view.getViewTreeObserver(); view.r...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final P4TableModel other = (P4TableModel) obj; return Objects.equals(this.id, other.id) ...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(P4_TABLE_MODEL_1, SAME_AS_P4_TABLE_MODEL_1) .addEqualityGroup(P4_TABLE_MODEL_2) .addEqualityGroup(P4_TABLE_MODEL_3) .testEquals(); }
public Set<String> listFunctions() { return usedModules.stream() .map(name -> loadedModules.get(name).listFunctions(false)) .flatMap(Collection::stream) .collect(Collectors.toSet()); }
@Test void testListFunctions() { ModuleMock x = new ModuleMock("x"); manager.loadModule(x.getType(), x); assertThat(manager.listFunctions()).contains(ModuleMock.DUMMY_FUNCTION_NAME); // hidden functions not in the default list assertThat(manager.listFunctions()).doesNotCont...
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String token = request.getHeader(HttpHeaders.AUTHORIZA...
@Test public void testAuthFailed() throws Exception { String someInvalidToken = "someInvalidToken"; when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someInvalidToken); when(consumerAuthUtil.getConsumerId(someInvalidToken)).thenReturn(null); authenticationFilter.doFilter(request, respons...
public double asDouble() { checkState(type == Type.FLOAT || type == Type.DOUBLE, "Value is not a float or double"); return Double.parseDouble(value); }
@Test public void asDouble() { ConfigProperty p = defineProperty("foo", DOUBLE, "123.0", "Foo Prop"); validate(p, "foo", DOUBLE, "123.0", "123.0"); assertEquals("incorrect value", 123.0, p.asDouble(), 0.01); }
@Override public String getOriginalHost() { try { if (originalHost == null) { originalHost = getOriginalHost(getHeaders(), getServerName()); } return originalHost; } catch (URISyntaxException e) { throw new IllegalArgumentException(e); ...
@Test void testGetOriginalHost() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "P...
public static int readUnsignedIntLE(InputStream in) throws IOException { return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); }
@Test public void testReadUnsignedIntLEFromInputStream() throws IOException { byte[] array1 = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}; ByteArrayInputStream is1 = new ByteArrayInputStream(array1); assertEquals(0x04030201, ByteUtils.readUnsignedIntLE(is1)); assertEquals(...
@Override public KCell[] getRow( int rownr ) { // xlsx raw row numbers are 1-based index, KSheet is 0-based // Don't check the upper limit as not all rows may have been read! // If it's found that the row does not exist, the exception will be thrown at the end of this method. if ( rownr < 0 ) { ...
@Test public void testNoUsedRangeSpecified() throws Exception { final String sheetId = "1"; final String sheetName = "Sheet 1"; SharedStringsTable sharedStringsTableMock = mockSharedStringsTable( "Report ID", "Report ID", "Approval Status", "Total Report Amount", "Policy", "ReportIdValue_1",...
public static String getDateFormatByRegex( String regex ) { return getDateFormatByRegex( regex, null ); }
@Test public void testGetDateFormatByRegexLocale() { assertNull( DateDetector.getDateFormatByRegex( null, null ) ); assertNull( DateDetector.getDateFormatByRegex( null, LOCALE_en_US ) ); // return eu if we pass en_US regexp without locale assertEquals( SAMPLE_DATE_FORMAT, DateDetector.getDateFormatByR...
@Override public CompletableFuture<Void> globalCleanupAsync(JobID jobId, Executor executor) { checkNotNull(jobId, "Job ID"); return runAsyncWithLockAssertRunning( () -> { LOG.debug("Removing job graph {} from {}.", jobId, jobGraphStateHandleStore); ...
@Test public void testGlobalCleanupWithNonExistName() throws Exception { final CompletableFuture<JobID> removeFuture = new CompletableFuture<>(); final TestingStateHandleStore<JobGraph> stateHandleStore = builder.setRemoveFunction(name -> removeFuture.complete(JobID.fromHexString(nam...
@Override public void invoke(IN value, Context context) throws Exception { bufferLock.lock(); try { // TODO this implementation is not very effective, // optimize this with MemorySegment if needed ByteArrayOutputStream baos = new ByteArrayOutputStream(); ...
@Test void testIncreasingToken() throws Exception { functionWrapper.openFunction(); for (int i = 0; i < 6; i++) { functionWrapper.invoke(i); } String version = initializeVersion(); CollectCoordinationResponse response; response = functionWrapper.sendReque...
private void stop(int numOfServicesStarted, boolean stopOnlyStartedServices) { // stop in reverse order of start Exception firstException = null; List<Service> services = getServices(); for (int i = numOfServicesStarted - 1; i >= 0; i--) { Service service = services.get(i); if (LOG.isDebugEn...
@Test(timeout = 10000) public void testAddInitedChildInInit() throws Throwable { CompositeService parent = new CompositeService("parent"); BreakableService child = new BreakableService(); child.init(new Configuration()); parent.init(new Configuration()); AddSiblingService.addChildToService(parent,...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { String param = exchange.getAttribute(Constants.PARAM_TRANSFORM); ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); ...
@Test public void testSofaPlugin2() { ShenyuContext context = mock(ShenyuContext.class); exchange.getAttributes().put(Constants.CONTEXT, context); exchange.getAttributes().put(Constants.META_DATA, metaData); when(chain.execute(exchange)).thenReturn(Mono.empty()); SelectorData...
public List<JobInfo> getRecentActivities() { return Collections.unmodifiableList(mRecentActivities); }
@Test public void testRecentActivities() { Collection<JobInfo> recentActivities = mSummary.getRecentActivities(); assertEquals("Unexpected length of recent activities", 7, recentActivities.size()); JobInfo[] recentActvitiesArray = new JobInfo[7]; recentActivities.toArray(recentActvitiesArray); ...
public FontMetrics parse() throws IOException { return parseFontMetric(false); }
@Test void testMalformedInteger() throws IOException { AFMParser parser = new AFMParser( new FileInputStream("src/test/resources/afm/MalformedInteger.afm")); try { parser.parse(); fail("The AFMParser should have thrown an IOException because of a m...
public boolean shouldCreateSSLSocketFactory(URL url) { return url.getProtocol().equalsIgnoreCase("https"); }
@Test public void testShouldUseSslClientConfig() throws Exception { JaasOptionsUtils jou = new JaasOptionsUtils(Collections.emptyMap()); assertFalse(jou.shouldCreateSSLSocketFactory(new URL("http://example.com"))); assertTrue(jou.shouldCreateSSLSocketFactory(new URL("https://example.com")));...
public Optional<UserAgent> getUserAgent(final LocalAddress localAddress) { return Optional.ofNullable(remoteChannelsByLocalAddress.get(localAddress)) .map(remoteChannel -> remoteChannel.attr(PARSED_USER_AGENT_ATTRIBUTE_KEY).get()); }
@Test void getUserAgent() throws UnrecognizedUserAgentException { clientConnectionManager.handleConnectionEstablished(localChannel, remoteChannel, Optional.empty()); assertEquals(Optional.empty(), clientConnectionManager.getUserAgent(localChannel.localAddress())); final UserAgent userAgent = Use...
public static <T> T getOnlyElement(Iterable<T> iterable) { if (iterable == null) { throw new IllegalArgumentException("iterable cannot be null."); } Iterator<T> iterator = iterable.iterator(); T first = iterator.next(); if (!iterator.hasNext()) { return fi...
@Test void testGetOnlyElementIllegalArgumentException2() { assertThrows(IllegalArgumentException.class, () -> { CollectionUtils.getOnlyElement(null); }); }
Number evaluateOutlierValue(final Number input) { switch (outlierTreatmentMethod) { case AS_IS: KiePMMLLinearNorm[] limitLinearNorms; if (input.doubleValue() < firstLinearNorm.getOrig()) { limitLinearNorms = linearNorms.subList(0, 2).toArray(new Ki...
@Test void evaluateOutlierValueAsExtremeValues() { KiePMMLNormContinuous kiePMMLNormContinuous = getKiePMMLNormContinuous(null, OUTLIER_TREATMENT_METHOD.AS_EXTREME_VALUES, null); Number input = 23; Number retrieve...
public static int precision(final Schema schema) { requireDecimal(schema); final String precisionString = schema.parameters().get(PRECISION_FIELD); if (precisionString == null) { return PRECISION_DEFAULT; } try { return Integer.parseInt(precisionString); } catch (final NumberFormatE...
@Test public void shouldUseDefaultPrecisionIfNotPresentInSchema() { // When: final int precision = DecimalUtil.precision(decimalSchemaWithoutPrecision(3)); // Then: assertThat(precision, is(64)); }
public CompletableFuture<Void> setPublicKey( final BackupAuthCredentialPresentation presentation, final byte[] signature, final ECPublicKey publicKey) { // Note: this is a special case where we can't validate the presentation signature against the stored public key // because we are currently...
@Test public void mismatchedPublicKey() throws VerificationFailedException { final BackupAuthCredentialPresentation presentation = backupAuthTestUtil.getPresentation( BackupLevel.MESSAGES, backupKey, aci); final ECKeyPair keyPair1 = Curve.generateKeyPair(); final ECKeyPair keyPair2 = Curve.genera...
private MergeSortedPages() {}
@Test public void testSingleStream() throws Exception { List<Type> types = ImmutableList.of(INTEGER, INTEGER); MaterializedResult actual = mergeSortedPages( types, ImmutableList.of(0, 1), ImmutableList.of(ASC_NULLS_FIRST, DESC_NULLS_FIR...
public static void cleanDirectory(File directory) throws IOException { requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL); Path path = directory.toPath(); if (!path.toFile().exists()) { return; } cleanDirectoryImpl(path); }
@Test public void cleanDirectory_follows_symlink_to_target_directory() throws IOException { assumeTrue(SystemUtils.IS_OS_UNIX); Path target = temporaryFolder.newFolder().toPath(); Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target); Path childFi...
public void startProcessing(Job job, Thread thread) { Optional<Job> optionalExistingThatMayBeReplacedJob = jobsCurrentlyInProgress.keySet().stream().filter(j -> j.getId().equals(job.getId())).findFirst(); optionalExistingThatMayBeReplacedJob .map(j -> j.delete("Job has been replaced")) ...
@Test void jobsThatAreProcessedAreBeingUpdatedWithAHeartbeat() { jobSteward = initializeBackgroundJobServerWithJobSteward(); final Job job = anEnqueuedJob().withId().build(); job.startProcessingOn(backgroundJobServer); jobSteward.startProcessing(job, mock(Thread.class)); job...
public static SharedFileDescriptorFactory create(String prefix, String paths[]) throws IOException { String loadingFailureReason = getLoadingFailureReason(); if (loadingFailureReason != null) { throw new IOException(loadingFailureReason); } if (paths.length == 0) { throw new IOExceptio...
@Test(timeout=10000) public void testCleanupRemainders() throws Exception { Assume.assumeTrue(NativeIO.isAvailable()); Assume.assumeTrue(SystemUtils.IS_OS_UNIX); File path = new File(TEST_BASE, "testCleanupRemainders"); path.mkdirs(); String remainder1 = path.getAbsolutePath() + Path.SEPA...
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createNetwork(InputStream input) { log.trace(String.format(MESSAGE, "CREATE")); KubevirtNetworkAdminService service = get(KubevirtNetworkAdminService.class); URI location; try {...
@Test public void testCreateNetworkWithCreateOperation() { mockAdminService.createNetwork(anyObject()); replay(mockAdminService); final WebTarget wt = target(); InputStream jsonStream = KubevirtNetworkWebResourceTest.class .getResourceAsStream("kubevirt-network.json"...