focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Optional<Object> invoke(Function<InvokerContext, Object> invokeFunc, Function<Throwable, Object> exFunc, String serviceName) { return invoke(invokeFunc, exFunc, serviceName, getRetry(null)); }
@Test public void testInvoke() { mockInstances(); // Normal call testNormalInvoke(buildRetryConfig("normal")); // Exception calls testErrorInvoke(buildRetryConfig("error")); }
public static Setting get(String name) { return SETTING_MAP.computeIfAbsent(name, (filePath)->{ final String extName = FileNameUtil.extName(filePath); if (StrUtil.isEmpty(extName)) { filePath = filePath + "." + Setting.EXT_NAME; } return new Setting(filePath, true); }); }
@Test public void getTest() { String driver = SettingUtil.get("test").get("demo", "driver"); assertEquals("com.mysql.jdbc.Driver", driver); }
public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) { if (str1 == null || str2 == null) { return str1 == str2; } else if (str1 == str2) { return true; } else if (str1.length() != str2.length()) { return false; } els...
@Test public void testEqualsIgnoreCase() { Assert.assertFalse(StringUtil.equalsIgnoreCase("", "BCCC")); Assert.assertFalse(StringUtil.equalsIgnoreCase(null, "")); Assert.assertTrue(StringUtil.equalsIgnoreCase("", "")); Assert.assertTrue(StringUtil.equalsIgnoreCase("BcCc", "BCCC")); Assert.assertTr...
@Override public EncryptRuleConfiguration buildToBeDroppedRuleConfiguration(final DropEncryptRuleStatement sqlStatement) { Collection<EncryptTableRuleConfiguration> toBeDroppedTables = new LinkedList<>(); Map<String, AlgorithmConfiguration> toBeDroppedEncryptors = new HashMap<>(); for (Strin...
@Test void assertUpdateCurrentRuleConfiguration() { EncryptRuleConfiguration ruleConfig = createCurrentRuleConfiguration(); EncryptRule rule = mock(EncryptRule.class); when(rule.getConfiguration()).thenReturn(ruleConfig); executor.setRule(rule); EncryptRuleConfiguration toBeD...
@Override public void createService(String serviceName) throws NacosException { createService(serviceName, Constants.DEFAULT_GROUP); }
@Test void testCreateService3() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; float protectThreshold = 0.1f; //when nacosNamingMaintainService.createService(serviceName, groupName, protectThreshold); //then ...
public static void copyConfigurationToJob(Properties props, Map<String, String> jobProps) throws HiveException, IOException { checkRequiredPropertiesAreDefined(props); resolveMetadata(props); for (Entry<Object, Object> entry : props.entrySet()) { String key = String.valueOf(entry.getKey()); ...
@Ignore @Test(expected = IllegalArgumentException.class) public void testWithJdbcUrlMissing() throws Exception { Properties props = new Properties(); props.put(JdbcStorageConfig.DATABASE_TYPE.getPropertyName(), DatabaseType.MYSQL.toString()); props.put(JdbcStorageConfig.QUERY.getPropertyName(), "SELECT co...
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("meta", new ParquetMetadataCommand(console)); jc.addCommand("pages", ...
@Test public void mainTest() throws Exception { ToolRunner.run(new Configuration(), new Main(LoggerFactory.getLogger(MainTest.class)), new String[] {}); Assert.assertTrue("we simply verify there are no errors here", true); }
@Override public boolean remove(long key1, long key2) { return super.remove0(key1, key2); }
@Test public void testSize() { final long key1 = randomKey(); final long key2 = randomKey(); insert(key1, key2); assertEquals(1, hsa.size()); assertTrue(hsa.remove(key1, key2)); assertEquals(0, hsa.size()); }
@Override public Optional<ShardingConditionValue> generate(final BinaryOperationExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { String operator = predicate.getOperator().toUpperCase(); if (!isSupportedOperator(operator)) { ...
@SuppressWarnings("unchecked") @Test void assertGenerateConditionValueWithNowExpression() { BinaryOperationExpression rightValue = new BinaryOperationExpression(0, 0, mock(ColumnSegment.class), new LiteralExpressionSegment(0, 0, "now()"), "=", null); Optional<ShardingConditionValue> shardingCond...
static String getLocationFrom( HttpPost method ) { Header locationHeader = method.getFirstHeader( "Location" ); return locationHeader.getValue(); }
@Test public void getLocationFrom() { HttpPost postMethod = mock( HttpPost.class ); Header locationHeader = new BasicHeader( LOCATION_HEADER, TEST_URL ); doReturn( locationHeader ).when( postMethod ).getFirstHeader( LOCATION_HEADER ); assertEquals( TEST_URL, WebService.getLocationFrom( postMethod ) )...
@Override public <UK, UV> MapState<UK, UV> getMapState(MapStateDescriptor<UK, UV> stateProperties) { KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties); stateProperties.initializeSerializerUnlessSet(this::createSerializer); return keyedStateStore.getMa...
@Test void testMapStateInstantiation() throws Exception { final ExecutionConfig config = new ExecutionConfig(); config.getSerializerConfig().registerKryoType(Path.class); final AtomicReference<Object> descriptorCapture = new AtomicReference<>(); StreamingRuntimeContext context = c...
public static Optional<? extends Schema> getSchema(io.swagger.v3.oas.annotations.media.Content annotationContent, Components components, JsonView jsonViewAnnotation) { return getSchema(annotationContent, components, jsonViewAnnotation, false); }
@Test(dataProvider = "expectedSchemaFromTypeAndFormat") public void getSchema(String methodName, Map<String, Object> expected) throws NoSuchMethodException { final Method method = getClass().getDeclaredMethod(methodName); Content annotationContent = method.getAnnotation(ApiResponse.class).content()[...
@VisibleForTesting public DU(File path, long interval, long jitter, long initialUsed) throws IOException { super(path, interval, jitter, initialUsed); this.duShell = new DUShell(); }
@Test public void testDU() throws IOException, InterruptedException { final int writtenSize = 32*1024; // writing 32K // Allow for extra 4K on-disk slack for local file systems // that may store additional file metadata (eg ext attrs). final int slack = 4*1024; File file = new File(DU_DIR, "data...
@PUT @Path("enable/{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response enableConfig(@PathParam("name") String configName) { log.trace(String.format(MESSAGE_CONFIG, UPDATE)); TelemetryConfig config = configService.getConfig( ...
@Test public void testEnableConfig() { expect(mockConfigAdminService.getConfig(anyString())) .andReturn(telemetryConfig).once(); mockConfigAdminService.updateTelemetryConfig(telemetryConfig); replay(mockConfigAdminService); final WebTarget wt = target(); Resp...
public Double getProcessCpuLoad() { return getMXBeanValueAsDouble("ProcessCpuLoad"); }
@Test void ifOperatingSystemMXBeanReturnsNaNForProcessCpuLoadOnLaterCalls_CachedValueIsReturned() throws JMException { when(mBeanServer.getAttribute(objectName, "ProcessCpuLoad")).thenReturn(0.7, Double.NaN, 0.5); assertThat(jobServerStats.getProcessCpuLoad()).isEqualTo(0.7); assertThat(job...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldFailValidationForTerminateUnknownQuery() { // Given: configuredStatement = configuredStatement("TERMINATE X", terminateQuery); when(terminateQuery.getQueryId()).thenReturn(Optional.of(QUERY_ID)); when(executionContext.getPersistentQuery(QUERY_ID)).thenReturn(Optional.empty()); ...
public ConfigTransformerResult transform(Map<String, String> configs) { Map<String, Map<String, Set<String>>> keysByProvider = new HashMap<>(); Map<String, Map<String, Map<String, String>>> lookupsByProvider = new HashMap<>(); // Collect the variables from the given configs that need transforma...
@Test public void testNoReplacement() { ConfigTransformerResult result = configTransformer.transform(Collections.singletonMap(MY_KEY, "${test:testPath:missingKey}")); Map<String, String> data = result.data(); assertEquals("${test:testPath:missingKey}", data.get(MY_KEY)); }
@Override public int configInfoBetaCount() { ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_BETA); String sql = configInfoBetaMapper.count(null); Integer result = jt.queryForObject(sql, Int...
@Test void testConfigInfoBetaCount() { when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(101); int returnCount = externalConfigInfoBetaPersistService.configInfoBetaCount(); assertEquals(101, returnCount); }
@Override public WindowStoreIterator<V> backwardFetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { Objects.requireNonNull(key, "key can't be null"); final L...
@Test public void shouldThrowInvalidStateStoreExceptionIfBackwardFetchThrows() { underlyingWindowStore.setOpen(false); final CompositeReadOnlyWindowStore<Object, Object> store = new CompositeReadOnlyWindowStore<>( new WrappingStoreProvider(singletonList(stubProviderOne), ...
@Description("bitwise XOR in 2's complement arithmetic") @ScalarFunction @SqlType(StandardTypes.BIGINT) public static long bitwiseXor(@SqlType(StandardTypes.BIGINT) long left, @SqlType(StandardTypes.BIGINT) long right) { return left ^ right; }
@Test public void testBitwiseXor() { assertFunction("bitwise_xor(0, -1)", BIGINT, -1L); assertFunction("bitwise_xor(3, 8)", BIGINT, 3L ^ 8L); assertFunction("bitwise_xor(-4, 12)", BIGINT, -4L ^ 12L); assertFunction("bitwise_xor(60, 21)", BIGINT, 60L ^ 21L); }
@Override public void open() throws InterpreterException { try { SparkConf conf = new SparkConf(); for (Map.Entry<Object, Object> entry : getProperties().entrySet()) { if (!StringUtils.isBlank(entry.getValue().toString())) { conf.set(entry.getKey().toString(), entry.getValue().toStri...
@Test void testDisableReplOutputForParagraph() throws InterpreterException { Properties properties = new Properties(); properties.setProperty("spark.master", "local"); properties.setProperty("spark.app.name", "test"); properties.setProperty("zeppelin.spark.maxResult", "100"); properties.setPropert...
@Override public List<DataSourceConfigDO> getDataSourceConfigList() { List<DataSourceConfigDO> result = dataSourceConfigMapper.selectList(); // 补充 master 数据源 result.add(0, buildMasterDataSourceConfig()); return result; }
@Test public void testGetDataSourceConfigList() { // mock 数据 DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class); dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据 // 准备参数 // 调用 List<DataSourceConfigDO> dataSourceConfigLi...
public OkHttpClientBuilder setConnectTimeoutMs(long l) { if (l < 0) { throw new IllegalArgumentException("Connect timeout must be positive. Got " + l); } this.connectTimeoutMs = l; return this; }
@Test public void build_throws_IAE_if_connect_timeout_is_negative() { assertThatThrownBy(() -> underTest.setConnectTimeoutMs(-10)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Connect timeout must be positive. Got -10"); }
@Override public String pluginNamed() { return PluginEnum.MODIFY_RESPONSE.getName(); }
@Test public void pluginNamedTest() { assertEquals(modifyResponsePluginDataHandler.pluginNamed(), PluginEnum.MODIFY_RESPONSE.getName()); }
@Deprecated static void updateBlockHandlerFor(Class<?> clazz, String name, Method method) { if (clazz == null || StringUtil.isBlank(name)) { throw new IllegalArgumentException("Bad argument"); } BLOCK_HANDLER_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); }
@Test(expected = IllegalArgumentException.class) public void testUpdateBlockHandlerBadArgument() { ResourceMetadataRegistry.updateBlockHandlerFor(null, "sxs", new Class[0], String.class.getMethods()[0]); }
@Override public void upgrade() { if (hasBeenRunSuccessfully()) { LOG.debug("Migration already completed."); return; } final Set<String> dashboardIdToViewId = new HashSet<>(); final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add; ...
@Test @MongoDBFixtures("dashboard_with_superfluous_widget_attributes.json") public void migratesADashboardWithSuperfluousWidgetAttributes() { this.migration.upgrade(); final MigrationCompleted migrationCompleted = captureMigrationCompleted(); assertThat(migrationCompleted.migratedDashbo...
@Override public KTable<K, VOut> aggregate(final Initializer<VOut> initializer, final Materialized<K, VOut, KeyValueStore<Bytes, byte[]>> materialized) { return aggregate(initializer, NamedInternal.empty(), materialized); }
@Test public void shouldNotHaveNullMaterializedOnAggregateWithNames() { assertThrows(NullPointerException.class, () -> cogroupedStream.aggregate(STRING_INITIALIZER, Named.as("name"), null)); }
public abstract Optional<Long> maxPartitionRefreshTs();
@Test public void testMaxPartitionRefreshTs() { Map<String, PartitionInfo> fakePartitionInfo = new HashMap<>(); Partition p1 = new Partition("p1", 100); Partition p2 = new Partition("p2", 200); fakePartitionInfo.put("p1", p1); fakePartitionInfo.put("p2", p2); new Moc...
private JobDetails() { this(null, null, null, null); // used for deserialization }
@Test void testJobDetails() { JobDetails jobDetails = jobDetails() .withClassName(TestService.class) .withMethodName("doWork") .withJobParameter(5) .build(); assertThat(jobDetails) .hasClass(TestService.class) ...
public static CodecFactory fromHadoopString(String hadoopCodecClass) { CodecFactory o = null; try { String avroCodec = HADOOP_AVRO_NAME_MAP.get(hadoopCodecClass); if (avroCodec != null) { o = CodecFactory.fromString(avroCodec); } } catch (Exception e) { throw new AvroRuntime...
@Test void hadoopCodecFactoryBZip2() { CodecFactory hadoopSnappyCodec = HadoopCodecFactory.fromHadoopString("org.apache.hadoop.io.compress.BZip2Codec"); CodecFactory avroSnappyCodec = CodecFactory.fromString("bzip2"); assertEquals(hadoopSnappyCodec.getClass(), avroSnappyCodec.getClass()); }
public static Object parse(String element) throws PathSegment.PathSegmentSyntaxException { Queue<Token> tokens = tokenizeElement(element); Object result = parseElement(tokens); if (!tokens.isEmpty()) { throw new PathSegment.PathSegmentSyntaxException("tokens left over after parsing; first exces...
@Test(dataProvider = "undecodables") public void testUndecodable(String undecoable, String expectedErrorMessage) { try { URIElementParser.parse(undecoable); Assert.fail(); } catch (PathSegment.PathSegmentSyntaxException e) { Assert.assertEquals(e.getMessage(), expectedErrorMess...
public static List<PortDescription> parseJuniperPorts(HierarchicalConfiguration cfg) { //This methods ignores some internal ports List<PortDescription> portDescriptions = new ArrayList<>(); List<HierarchicalConfiguration> subtrees = cfg.configurationsAt(IF_INFO); for (Hi...
@Test public void testInterfacesParsedFromJunos18() { HierarchicalConfiguration reply = XmlConfigParser.loadXml( getClass().getResourceAsStream("/Junos_get-interface-information_response_18.4.xml")); final Collection<PortDescription> expected = new ArrayList<>(); expected.ad...
public static Pair<CloudObjectIncrCheckpoint, Option<Dataset<Row>>> filterAndGenerateCheckpointBasedOnSourceLimit(Dataset<Row> sourceData, long sourceLimit, QueryInfo queryInfo, ...
@Test void testSingleObjectExceedingSourceLimit() { List<Triple<String, Long, String>> filePathSizeAndCommitTime = new ArrayList<>(); // Add file paths and sizes to the list filePathSizeAndCommitTime.add(Triple.of("path/to/file1.json", 100L, "commit1")); filePathSizeAndCommitTime.add(Triple.of("path/t...
@VisibleForTesting void collectPackages() throws UploaderException { parseLists(); String[] list = StringUtils.split(input, File.pathSeparatorChar); for (String item : list) { LOG.info("Original source " + item); String expanded = expandEnvironmentVariables(item, System.getenv()); LOG.in...
@Test void testCollectPackages() throws IOException, UploaderException { File parent = new File(testDir); try { parent.deleteOnExit(); assertTrue(parent.mkdirs(), "Directory creation failed"); File dirA = new File(parent, "A"); assertTrue(dirA.mkdirs()); File dirB = new File(pare...
@Override public String convertTo(Duration value) { // Durations will always be converted to ISO8601 formatted Strings // There is no meaningful way to convert them back to a simple jadconfig 'number+unit' format. return value.toString(); }
@Test public void convertTo() { assertThat(converter.convertTo(Duration.ofMillis(10))).isEqualTo("PT0.01S"); assertThat(converter.convertTo(Duration.ofSeconds(10))).isEqualTo("PT10S"); assertThat(converter.convertTo(Duration.ofSeconds(70))).isEqualTo("PT1M10S"); }
public B export(Boolean export) { this.export = export; return getThis(); }
@Test void export() { ServiceBuilder builder = new ServiceBuilder(); builder.export(true); Assertions.assertTrue(builder.build().getExport()); builder.export(false); Assertions.assertFalse(builder.build().getExport()); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleSubscriptionData that = (SimpleSubscriptionData) o; return Objects.equals(topic, that.topic) && Obj...
@Test public void testSetNotEqual() { String topic = "test-topic"; String expressionType = "TAG"; String expression1 = "test-expression-1"; String expression2 = "test-expression-2"; Set<SimpleSubscriptionData> set1 = Sets.newHashSet(new SimpleSubscriptionData(topic, expressio...
static Optional<Model> fromXml(DeployState ds, Element parent, String name, Set<String> requiredTags) { return XmlHelper.getOptionalChild(parent, name).map(e -> fromXml(ds, e, requiredTags)); }
@Test void invalid_url(){ var xml = """ <component id="bert-embedder" type="bert-embedder"> <transformer-model url="models/e5-base-v2.onnx" /> <tokenizer-vocab path="models/vocab.txt"/> </component> """; var state =...
public static <K, V, S extends StateStore> Materialized<K, V, S> as(final DslStoreSuppliers storeSuppliers) { Objects.requireNonNull(storeSuppliers, "store type can't be null"); return new Materialized<>(storeSuppliers); }
@Test public void shouldThrowNullPointerIfStoreTypeIsNull() { final NullPointerException e = assertThrows(NullPointerException.class, () -> Materialized.as((Materialized.StoreType) null)); assertEquals(e.getMessage(), "store type can't be null"); }
@Override public Optional<ConstraintMetaData> revise(final String tableName, final ConstraintMetaData originalMetaData, final ShardingRule rule) { for (DataNode each : shardingTable.getActualDataNodes()) { String referencedTableName = originalMetaData.getReferencedTableName(); Option...
@Test void assertReviseWhenTableDoesNotMatch() { assertFalse(reviser.revise("table_name_1", new ConstraintMetaData("test_table_name_2", "referenced_table_name"), shardingRule).isPresent()); }
public static VerificationMode times(final int count) { checkArgument(count >= 0, "Times count must not be less than zero"); return new TimesVerification(count); }
@Test public void should_verify_expected_request() throws Exception { final HttpServer server = httpServer(port(), hit); server.get(by(uri("/foo"))).response("bar"); running(server, () -> assertThat(helper.get(remoteUrl("/foo")), is("bar"))); hit.verify(by(uri("/foo")), times(1)); ...
@Override public List<CodegenTableDO> getCodegenTableList(Long dataSourceConfigId) { return codegenTableMapper.selectListByDataSourceConfigId(dataSourceConfigId); }
@Test public void testGetCodegenTableList() { // mock 数据 CodegenTableDO table01 = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table01); CodegenTableDO table02 = randomPojo(CodegenTableDO.class, ...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testBarrows() { ChatMessage chatMessageEvent = new ChatMessage(null, GAMEMESSAGE, "", "Your Barrows chest count is: <col=ff0000>277</col>.", null, 0); chatCommandsPlugin.onChatMessage(chatMessageEvent); verify(configManager).setRSProfileConfiguration("killcount", "barrows chests", 277); }
static int writeHeaderBuffer(final MapWriterConfiguration configuration, final TileBasedDataProcessor dataProcessor, final ByteBuffer containerHeaderBuffer) { LOGGER.fine("writing header"); LOGGER.fine("Bounding box for file: " + dataProcessor.getBoundingBox().toString()...
@Test public void testWriteHeaderBuffer() { ByteBuffer headerBuffer = ByteBuffer.allocate(MapFileWriter.HEADER_BUFFER_SIZE); int headerLength = MapFileWriter.writeHeaderBuffer(this.configuration, this.dataProcessor, headerBuffer); // expected header length // 20 + 4 + 4 + 8 + 8 + 16...
public static boolean compareRawTaggedFields(List<RawTaggedField> first, List<RawTaggedField> second) { if (first == null) { return second == null || second.isEmpty(); } else if (second == null) { return first.isEmpty(); } ...
@Test public void testCompareRawTaggedFields() { assertTrue(MessageUtil.compareRawTaggedFields(null, null)); assertTrue(MessageUtil.compareRawTaggedFields(null, Collections.emptyList())); assertTrue(MessageUtil.compareRawTaggedFields(Collections.emptyList(), null)); assertFalse(Messa...
@Override public void updateUserLogin(Long id, String loginIp) { userMapper.updateById(new AdminUserDO().setId(id).setLoginIp(loginIp).setLoginDate(LocalDateTime.now())); }
@Test public void testUpdateUserLogin() { // mock 数据 AdminUserDO user = randomAdminUserDO(o -> o.setLoginDate(null)); userMapper.insert(user); // 准备参数 Long id = user.getId(); String loginIp = randomString(); // 调用 userService.updateUserLogin(id, login...
@Override public void inc() { counter.inc(1D); }
@Test void assertCreate() throws ReflectiveOperationException { PrometheusMetricsCounterCollector collector = new PrometheusMetricsCounterCollector(new MetricConfiguration("foo_counter", MetricCollectorType.COUNTER, "foo_help", Collections.emptyList(), Collections.emptyMap())); colle...
@Override public ParsedLine parse(final String line, final int cursor, final ParseContext context) { final String trimmed = line.trim(); final int adjCursor = adjustCursor(line, trimmed, cursor); return delegate.parse(trimmed, adjCursor, context); }
@Test public void shouldTrimWhiteSpaceAndReturnLine() { expect(delegate.parse("line \t containing \t space", 0, UNSPECIFIED)) .andReturn(parsedLine); replay(delegate); final ParsedLine line = parser.parse(" \t line \t containing \t space \t ", 0, UNSPECIFIED); assertThat(line, is(parsedLine)...
public SnapshotDto setProjectVersion(@Nullable String projectVersion) { checkLength(MAX_VERSION_LENGTH, projectVersion, "projectVersion"); this.projectVersion = projectVersion; return this; }
@Test void fail_if_projectVersion_is_longer_then_100_characters() { SnapshotDto snapshotDto = new SnapshotDto(); snapshotDto.setProjectVersion(null); snapshotDto.setProjectVersion("1.0"); snapshotDto.setProjectVersion(repeat("a", 100)); assertThatThrownBy(() -> snapshotDto.setProjectVersion(repea...
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, ...
@Test public void testNewJoiningMemberTriggersNewTargetAssignment() { String groupId = "fooup"; // Use a static member id as it makes the test easier. String memberId1 = Uuid.randomUuid().toString(); String memberId2 = Uuid.randomUuid().toString(); String memberId3 = Uuid.ran...
@Override public String[] requiredModules() { return new String[] { CoreModule.NAME, ConfigurationModule.NAME }; }
@Test public void requiredModules() { String[] modules = moduleProvider.requiredModules(); assertArrayEquals(new String[] { CoreModule.NAME, ConfigurationModule.NAME }, modules); }
public static GeneratorResult run(String resolverPath, String defaultPackage, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, ...
@Test(dataProvider = "restliVersionsDataProvider") public void testDeterministicMethodOrder(RestliVersion version) throws Exception { final String pegasusDir = moduleDir + FS + RESOURCES_DIR + FS + "pegasus"; final String outPath = outdir.getPath(); RestRequestBuilderGenerator.run(pegasusDir, ...
@Cacheable(value = CACHE_LATEST_EXTENSION_VERSION, keyGenerator = GENERATOR_LATEST_EXTENSION_VERSION) public ExtensionVersion getLatest(List<ExtensionVersion> versions, boolean groupedByTargetPlatform) { return getLatest(versions, groupedByTargetPlatform, false); }
@Test public void testGetLatestNoPreRelease() { var release = new ExtensionVersion(); release.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL); release.setPreRelease(false); release.setVersion("1.0.0"); var minor = new ExtensionVersion(); minor.setTargetPlatform(Targ...
public static void setMetadata( Context context, NotificationCompat.Builder notification, int type) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { switch (type) { case TYPE_NORMAL: createNormalChannel(context); break; case TYPE_FTP: createFtpChannel...
@Test @Config(sdk = {KITKAT}) // max sdk is N public void testNormalNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID) .setContentTitle(context.getString(R.string.waiting_title)) .setContentText(context.getString(R.str...
String getSignature(URL url, Invocation invocation, String secretKey, String time) { String requestString = String.format( Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), RpcUtils.getMethodName(invocation), secretKey, ...
@Test void testGetSignatureNoParameter() { URL url = mock(URL.class); Invocation invocation = mock(Invocation.class); String secretKey = "123456"; AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel()); String signature = helper.getSignatu...
@Override public List<Long> getTenantIdList() { List<TenantDO> tenants = tenantMapper.selectList(); return CollectionUtils.convertList(tenants, TenantDO::getId); }
@Test public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 List<Long> result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); ...
public Organization getOrganizationByName(String name) { Optional<Organization> conf = organizationRepository.findByName(name); if (!conf.isPresent()) { throw new NotFoundException("Could not find organization with name: " + name); } return conf.get(); }
@Test public void organizationNotFound() { Optional<Organization> organizationOptional = Optional.empty(); when(repositoryMock.findByName(anyString())).thenReturn(organizationOptional); assertThrows(NotFoundException.class, () -> { organizationServiceMock.getOrganizationByName("...
public int compute(final RectL pInputRect, final PointL pInputPoint, final double pInputRadius, final PointL pOutputIntersection1, final PointL pOutputIntersection2) { mRect = pInputRect; mPoint = pInputPoint; if (pInputRect.contains(mPoint.x, mPoint.y)) { ret...
@Test public void testCompute() { final SpeechBalloonHelper helper = new SpeechBalloonHelper(); final long radius = 10; final RectL inputRect = new RectL(); final PointL inputPoint = new PointL(); final PointL intersection1 = new PointL(); final PointL intersection2 =...
static List<Integer> deltaEncode(List<Integer> list) { if (list == null) { return null; } ArrayList<Integer> result = new ArrayList<>(); if (list.isEmpty()) { return result; } Iterator<Integer> it = list.iterator(); // add the first way n...
@Test public void testDeltaEncode() { List<Integer> deltaEncoded = DeltaEncoder.deltaEncode(this.mockCoordinates); Assert.assertEquals(Integer.valueOf(52000000), deltaEncoded.get(0)); Assert.assertEquals(Integer.valueOf(13000000), deltaEncoded.get(1)); Assert.assertEquals(Integer.val...
@Override public void execute(Exchange exchange) throws SmppException { CancelSm cancelSm = createCancelSm(exchange); if (log.isDebugEnabled()) { log.debug("Canceling a short message for exchange id '{}' and message id '{}'", exchange.getExchangeId(), cancelSm.getMes...
@Test public void execute() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "CancelSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppC...
private ConfigModelContext(ApplicationType applicationType, DeployState deployState, VespaModel vespaModel, ConfigModelRepoAdder configModelRepoAdder, TreeConfigProducer<AnyConfigProducer> parent,...
@Test void testConfigModelContext() { MockRoot root = new MockRoot(); String id = "foobar"; ApplicationPackage pkg = new MockApplicationPackage.Builder() .withServices("<services version=\"1.0\"><admin version=\"2.0\" /></services>") .build(); DeploySt...
@Override @SuppressWarnings({"unchecked", "rawtypes"}) protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { String body = exchange.getAttribute(Constants.PARAM_TRANSFORM); ShenyuContext shenyuContext =...
@Test public void testTarsPluginWithEmptyBody() { 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()); ...
public SearchOptions setPage(int page, int pageSize) { checkArgument(page >= 1, "Page must be greater or equal to 1 (got " + page + ")"); setLimit(pageSize); int lastResultIndex = page * pageSize; checkArgument(lastResultIndex <= MAX_RETURNABLE_RESULTS, "Can return only the first %s results. %sth result...
@Test public void fail_if_page_is_not_strictly_positive() { assertThatThrownBy(() -> new SearchOptions().setPage(0, 10)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Page must be greater or equal to 1 (got 0)"); }
public static FieldScope fromSetFields(Message message) { return fromSetFields( message, AnyUtils.defaultTypeRegistry(), AnyUtils.defaultExtensionRegistry()); }
@Test public void testFromSetFields_iterables_errorForDifferentMessageTypes() { // Don't run this test twice. if (!testIsRunOnce()) { return; } try { FieldScopes.fromSetFields( TestMessage2.newBuilder().setOInt(2).build(), TestMessage3.newBuilder().setOInt(2).build());...
@Override public Map<K, V> loadAll(Collection<K> keys) { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void loadAll() { cacheStore.loadAll(asList("1", "2")); }
public static Sensor closeTaskSensor(final String threadId, final StreamsMetricsImpl streamsMetrics) { return invocationRateAndCountSensor( threadId, CLOSE_TASK, CLOSE_TASK_RATE_DESCRIPTION, CLOSE_TASK_TOTAL_DESCRIPTION, ...
@Test public void shouldGetCloseTaskSensor() { final String operation = "task-closed"; final String totalDescription = "The total number of closed tasks"; final String rateDescription = "The average per-second number of closed tasks"; when(streamsMetrics.threadLevelSensor(THREAD_ID, ...
public static void main(String[] args) { var root = new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()), NullNode.getInstance() ), new NodeImpl("12", NullNode.getInstance(), new NodeImpl("122...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public static Comparator<StructLike> forType(Types.StructType struct) { return new StructLikeComparator(struct); }
@Test public void testFixed() { assertComparesCorrectly( Comparators.forType(Types.FixedType.ofLength(3)), ByteBuffer.wrap(new byte[] {1, 1, 3}), ByteBuffer.wrap(new byte[] {1, 2, 1})); }
public static void main(String[] args) throws Exception { // Create data source and create the customers, products and purchases tables final var dataSource = createDataSource(); deleteSchema(dataSource); createSchema(dataSource); // create customer var customerDao = new CustomerDaoImpl(dataSo...
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[] {})); }
public static String getCanonicalName(Class cls) { Objects.requireNonNull(cls, "cls"); return cls.getCanonicalName(); }
@Test public void getCanonicalNameTest() { final String canonicalName = ClassUtil.getCanonicalName(TestClass.class); Assert.isTrue(Objects.equals("cn.hippo4j.config.toolkit.ClassUtilTest.TestClass", canonicalName)); }
public abstract void run(T configuration, Environment environment) throws Exception;
@Test void exitWithFatalErrorWhenCommandFails() throws Exception { final File configFile = File.createTempFile("dropwizard-invalid-config", ".yml"); try { final FakeApplication application = new FakeApplication(); application.run("server", configFile.getAbsolutePath()); ...
public final void isNotNaN() { if (actual == null) { failWithActual(simpleFact("expected a double other than NaN")); } else { isNotEqualTo(NaN); } }
@Test public void isNotNaNIsNaN() { expectFailureWhenTestingThat(Double.NaN).isNotNaN(); }
@Nonnull public static <T> Traverser<T> traverseIterable(@Nonnull Iterable<? extends T> iterable) { return traverseIterator(iterable.iterator()); }
@Test public void when_traverseIterable_then_seeAllItems() { validateTraversal(traverseIterable(asList(1, 2))); }
public boolean isSetByUser(PropertyKey key) { if (mUserProps.containsKey(key)) { Optional<Object> val = mUserProps.get(key); // Sources larger than Source.CLUSTER_DEFAULT are considered to be set by the user return val.isPresent() && (getSource(key).compareTo(Source.CLUSTER_DEFAULT) > 0); } ...
@Test public void isSetByUser() { assertFalse(mProperties.isSetByUser(mKeyWithValue)); assertFalse(mProperties.isSetByUser(mKeyWithoutValue)); mProperties.put(mKeyWithValue, "value", Source.CLUSTER_DEFAULT); mProperties.put(mKeyWithoutValue, "value", Source.CLUSTER_DEFAULT); assertFalse(mPropertie...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { try { return new SchemaAndValue(Schema.OPTIONAL_BOOLEAN_SCHEMA, deserializer.deserialize(topic, value)); } catch (SerializationException e) { throw new DataException("Failed to deseria...
@Test public void testToConnectNullValue() { assertEquals(Schema.OPTIONAL_BOOLEAN_SCHEMA, converter.toConnectData(TOPIC, null).schema()); assertNull(converter.toConnectData(TOPIC, null).value()); }
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) { in.markReaderIndex(); MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c...
@Test void assertDecodeTableMapEvent() { ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); // the hex data is from binlog data, The first event used in Row Based Replication byteBuf.writeBytes(StringUtil.decodeHexDump("00cb38a962130100000041000000be7d000000007b000000000001000464735f310009...
public ModelLocalUriId asModelLocalUriId() { return this.getClass().equals(ModelLocalUriId.class) ? this : new ModelLocalUriId(this.asLocalUri()); }
@Test void asModelLocalUriIdWithModelLocalUriId() { String path = "/example/some-id/instances/some-instance-id"; LocalUri parsed = LocalUri.parse(path); ModelLocalUriId retrieved = new ModelLocalUriId(parsed); ModelLocalUriId modelLocalUriId = retrieved.asModelLocalUriId(); a...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentImportExecutor, TokensAndUrlAuthData authData, MusicContainerResource data) throws Exception { if (data == null) { // Nothing to do re...
@Test public void testImportPlaylistTracks() throws Exception { List<MusicPlaylistItem> musicPlaylistItems = createTestPlaylistItems(randomString()); setUpImportPlaylistTracksBatchResponse(musicPlaylistItems.stream().collect( Collectors.toMap(item -> item.getTrack().getIsrcCode(), it...
@Deprecated @InlineMe(replacement = "JsonParser.parseString(json)", imports = "com.google.gson.JsonParser") public JsonElement parse(String json) throws JsonSyntaxException { return parseString(json); }
@Test public void testReadWriteTwoObjects() throws Exception { Gson gson = new Gson(); CharArrayWriter writer = new CharArrayWriter(); BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one"); writer.write(gson.toJson(expectedOne).toCharArray()); BagOfPrimitives expectedTwo = new BagOf...
public static void main(String[] args) { // Getting the bar series BarSeries series = CsvTradesLoader.loadBitstampSeries(); // Building the trading strategy Strategy strategy = buildStrategy(series); // Running the strategy BarSeriesManager seriesManager = new BarSerie...
@Test public void test() { GlobalExtremaStrategy.main(null); }
static Hashtable<String, String> generateJmxTable(Map<String, String> variables) { Hashtable<String, String> ht = new Hashtable<>(variables.size()); for (Map.Entry<String, String> variable : variables.entrySet()) { ht.put( replaceInvalidChars(variable.getKey()), ...
@Test void testGenerateTable() { Map<String, String> vars = new HashMap<>(); vars.put("key0", "value0"); vars.put("key1", "value1"); vars.put("\"key2,=;:?'", "\"value2 (test),=;:?'"); Hashtable<String, String> jmxTable = JMXReporter.generateJmxTable(vars); assertTha...
@Override public String getDocumentationLink(@Nullable String suffix) { return documentationBaseUrl + Optional.ofNullable(suffix).orElse(""); }
@Test public void getDocumentationLink_suffixNotProvided_withPropertyOverride() { String propertyValue = "https://new-url.sonarqube.org/"; when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue)); documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVer...
public String summarize(final ExecutionStep<?> step) { return summarize(step, "").summary; }
@Test public void shouldSummarizeSource() { // When: final String summary = planSummaryBuilder.summarize(sourceStep); // Then: assertThat(summary, is( " > [ SOURCE ] | Schema: ROWKEY STRING KEY, L0 INTEGER | Logger: QID.src\n" )); }
public static SimpleAclRuleResource fromKafkaResourcePattern(ResourcePattern kafkaResourcePattern) { String resourceName; SimpleAclRuleResourceType resourceType; AclResourcePatternType resourcePattern = null; switch (kafkaResourcePattern.resourceType()) { case TOPIC: ...
@Test public void testFromKafkaResourcePatternWithClusterResource() { // Regular cluster ResourcePattern kafkaClusterResourcePattern = new ResourcePattern(ResourceType.CLUSTER, "kafka-cluster", PatternType.LITERAL); SimpleAclRuleResource expectedClusterResourceRules = new SimpleAclRuleResou...
public boolean isPasswordReminderNeeded() { return isPasswordReminderNeeded(new Date().getTime()); }
@Test public void testIsPasswordReminderNeeded() { long currTime = new Date().getTime(); Context context = ApplicationProvider.getApplicationContext(); Preferences prefs = new Preferences(context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)...
public static StatementExecutorResponse execute( final ConfiguredStatement<ListProperties> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final KsqlConfigResolver resolver = new KsqlConfigResolver()...
@Test public void shouldListUnresolvedStreamsTopicProperties() { // When: final PropertiesList properties = (PropertiesList) CustomExecutors.LIST_PROPERTIES.execute( engine.configure("LIST PROPERTIES;") .withConfig(new KsqlConfig(ImmutableMap.of( "ksql.streams.topic.min.ins...
private static int getErrorCode(final int kernelCode, final int errorCode) { Preconditions.checkArgument(kernelCode >= 0 && kernelCode < 10, "The value range of kernel code should be [0, 10)."); Preconditions.checkArgument(errorCode >= 0 && errorCode < 1000, "The value range of error code should be [0, ...
@Test void assertToSQLException() { SQLException actual = new KernelSQLException(XOpenSQLState.GENERAL_ERROR, 1, 1, "reason") { }.toSQLException(); assertThat(actual.getSQLState(), is(XOpenSQLState.GENERAL_ERROR.getValue())); assertThat(actual.getErrorCode(), is(11001)); asse...
@VisibleForTesting @SuppressWarnings("deprecation") public static boolean isOnlyDictionaryEncodingPages(ColumnChunkMetaData columnMetaData) { // Files written with newer versions of Parquet libraries (e.g. parquet-mr 1.9.0) will have EncodingStats available // Otherwise, fallback to v1 logic...
@Test @SuppressWarnings("deprecation") public void testDictionaryEncodingV1() { Set<Encoding> required = ImmutableSet.of(BIT_PACKED); Set<Encoding> optional = ImmutableSet.of(BIT_PACKED, RLE); Set<Encoding> repeated = ImmutableSet.of(RLE); Set<Encoding> notDictionary = Immut...
public void tryLock() { try { if (!lock.tryLock()) { failAlreadyInProgress(null); } } catch (OverlappingFileLockException e) { failAlreadyInProgress(e); } }
@Test public void tryLockConcurrently() { lock.tryLock(); assertThatThrownBy(() -> lock.tryLock()) .isInstanceOf(IllegalStateException.class) .hasMessage("Another SonarQube analysis is already in progress for this project"); }
@Override public void clearMine() { Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap(); UUID clientUUID = hzMember.getUuid(); if (LOG.isTraceEnabled()) { LOG.trace("Reading {} and clearing for {}", new HashMap<>(sqHealthState), clientUUID); } sqHealthState.remove(clientUUID...
@Test public void clearMine_clears_entry_into_map_sq_health_state_under_current_client_uuid() { Map<UUID, TimestampedNodeHealth> map = mock(Map.class); doReturn(map).when(hazelcastMember).getReplicatedMap(MAP_SQ_HEALTH_STATE); UUID uuid = UUID.randomUUID(); when(hazelcastMember.getUuid()).thenReturn(u...
@Override public Result invoke(Invocation invocation) throws RpcException { Result result; String value = getUrl().getMethodParameter( RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()) .trim(); if (ConfigUtils.isEmpty(value)) { ...
@Test void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() ...
@Override public Option<HoodieBaseFile> getBaseFileOn(String partitionPath, String instantTime, String fileId) { return execute(partitionPath, instantTime, fileId, preferredView::getBaseFileOn, (path, instant, id) -> getSecondaryView().getBaseFileOn(path, instant, id)); }
@Test public void testGetBaseFileOn() { Option<HoodieBaseFile> actual; Option<HoodieBaseFile> expected = Option.of(new HoodieBaseFile("test.file")); String partitionPath = "/table2"; String instantTime = "2020-01-01"; String fileID = "file.123"; when(primary.getBaseFileOn(partitionPath, insta...
public Map<String, Object> getClusterMetrics(Map<String, Object> previousMetrics) { Request clusterStatRequest = new Request("GET", "_stats"); try { Response response = client.getLowLevelClient().performRequest(clusterStatRequest); JsonNode responseNode = objectMapper.readValue(r...
@Test public void getClusterMetrics() { final Map<String, Object> previousMetrics = Map.of("search_ops", 5); Map<String, Object> clusterMetrics = collector.getClusterMetrics(previousMetrics); assertThat(clusterMetrics.get("doc_count")).isEqualTo(6206956); assertThat(clusterMetrics.ge...
public AtomicLong clientCaCertificateExpiration(String clusterName, String namespace) { return getGaugeLong(new CertificateMetricKey(kind, namespace, clusterName, CertificateMetricKey.Type.CLIENT_CA), METRICS_CERTIFICATE_EXPIRATION_MS, "Time in milliseconds when the certificate expires", ...
@Test @DisplayName("Should return correct expiration time for client CA certificate") void shouldReturnCorrectExpirationTimeForClientCaCertificate() { AtomicLong expirationTime = metricsHolder.clientCaCertificateExpiration("TestCluster", "TestNamespace"); assertEquals(1000L, expirationTime.get(...
static boolean isValidIfPresent(@Nullable String email) { return isEmpty(email) || isValidEmail(email); }
@Test public void various_examples_of_invalid_emails() { assertThat(isValidIfPresent("infosonarsource.com")).isFalse(); assertThat(isValidIfPresent("info@.sonarsource.com")).isFalse(); assertThat(isValidIfPresent("info\"@.sonarsource.com")).isFalse(); }
public AggregateAnalysisResult analyze( final ImmutableAnalysis analysis, final List<SelectExpression> finalProjection ) { if (!analysis.getGroupBy().isPresent()) { throw new IllegalArgumentException("Not an aggregate query"); } final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ...
@Test public void shouldNotCaptureNonAggregateFunction() { // given: givenSelectExpression(FUNCTION_CALL); givenHavingExpression(FUNCTION_CALL); // When: final AggregateAnalysisResult result = analyzer.analyze(analysis, selects); // Then: assertThat(result.getAggregateFunctions(), contai...
@Override public synchronized void unexport() { if (!exported) { return; } if (unexported) { return; } if (!exporters.isEmpty()) { for (List<Exporter<?>> es : exporters.values()) { for (Exporter<?> exporter : es) { ...
@Test void testUnexport() throws Exception { System.setProperty(SHUTDOWN_WAIT_KEY, "0"); try { service.export(); service.unexport(); // Thread.sleep(1000); Mockito.verify(exporter, Mockito.atLeastOnce()).unexport(); } finally { ...
@Override public void executeSystemTask(WorkflowSystemTask systemTask, String taskId, int callbackTime) { try { Task task = executionDAOFacade.getTaskById(taskId); if (task == null) { LOG.error("TaskId: {} could not be found while executing SystemTask", taskId); return; } L...
@Test public void testExecuteSystemTaskWithoutUpdatingPollingCount() { String workflowId = "workflow-id"; String taskId = "task-id-1"; Task maestroTask = new Task(); maestroTask.setTaskType(Constants.MAESTRO_TASK_NAME); maestroTask.setReferenceTaskName("maestroTask"); maestroTask.setWorkflowI...
public Invocable getInvocable() { return invocable; }
@Test void testAccessors() { final Set<? extends ConstraintViolation<?>> violations = Collections.emptySet(); @SuppressWarnings("unchecked") final Inflector<Request, ?> inf = mock(Inflector.class); final Invocable inv = Invocable.create(inf); final JerseyViolationException t...
public static Read read() { return Read.create(); }
@Test public void testReadValidationFailsMissingTable() { BigtableIO.Read read = BigtableIO.read().withBigtableOptions(BIGTABLE_OPTIONS); thrown.expect(IllegalArgumentException.class); read.expand(null); }