focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@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_COMMENTS) .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES) .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); final JsonNode node; try { node = mapper.readTree(jsonSchema); } catch (IOException e) { throw new IllegalArgumentException("Invalid JSON schema.", e); } return (TypeInformation<T>) convertType("<root>", node, node); }
@Test void testReferenceSchema() throws Exception { final URL url = getClass().getClassLoader().getResource("reference-schema.json"); Objects.requireNonNull(url); final String schema = FileUtils.readFileUtf8(new File(url.getFile())); final TypeInformation<?> result = JsonRowSchemaConverter.convert(schema); final TypeInformation<?> expected = Types.ROW_NAMED( new String[] {"billing_address", "shipping_address", "optional_address"}, Types.ROW_NAMED( new String[] {"street_address", "city", "state"}, Types.STRING, Types.STRING, Types.STRING), Types.ROW_NAMED( new String[] {"street_address", "city", "state"}, Types.STRING, Types.STRING, Types.STRING), Types.ROW_NAMED( new String[] {"street_address", "city", "state"}, Types.STRING, Types.STRING, Types.STRING)); assertThat(result).isEqualTo(expected); }
public static CheckpointStorage load( @Nullable CheckpointStorage fromApplication, StateBackend configuredStateBackend, Configuration jobConfig, Configuration clusterConfig, ClassLoader classLoader, @Nullable Logger logger) throws IllegalConfigurationException, DynamicCodeLoadingException { Preconditions.checkNotNull(jobConfig, "jobConfig"); Preconditions.checkNotNull(clusterConfig, "clusterConfig"); Preconditions.checkNotNull(classLoader, "classLoader"); Preconditions.checkNotNull(configuredStateBackend, "statebackend"); // Job level config can override the cluster level config. Configuration mergedConfig = new Configuration(clusterConfig); mergedConfig.addAll(jobConfig); // Legacy state backends always take precedence for backwards compatibility. StateBackend rootStateBackend = (configuredStateBackend instanceof DelegatingStateBackend) ? ((DelegatingStateBackend) configuredStateBackend) .getDelegatedStateBackend() : configuredStateBackend; if (rootStateBackend instanceof CheckpointStorage) { if (logger != null) { logger.info( "Using legacy state backend {} as Job checkpoint storage", rootStateBackend); if (fromApplication != null) { logger.warn( "Checkpoint storage passed via StreamExecutionEnvironment is ignored because legacy state backend '{}' is used. {}", rootStateBackend.getClass().getName(), LEGACY_PRECEDENCE_LOG_MESSAGE); } if (mergedConfig.get(CheckpointingOptions.CHECKPOINT_STORAGE) != null) { logger.warn( "Config option '{}' is ignored because legacy state backend '{}' is used. {}", CheckpointingOptions.CHECKPOINT_STORAGE.key(), rootStateBackend.getClass().getName(), LEGACY_PRECEDENCE_LOG_MESSAGE); } } return (CheckpointStorage) rootStateBackend; } // In the FLINK-2.0, the checkpoint storage from application will not be supported // anymore. if (fromApplication != null) { if (fromApplication instanceof ConfigurableCheckpointStorage) { if (logger != null) { logger.info( "Using job/cluster config to configure application-defined checkpoint storage: {}", fromApplication); if (mergedConfig.get(CheckpointingOptions.CHECKPOINT_STORAGE) != null) { logger.warn( "Config option '{}' is ignored because the checkpoint storage passed via StreamExecutionEnvironment takes precedence.", CheckpointingOptions.CHECKPOINT_STORAGE.key()); } } return ((ConfigurableCheckpointStorage) fromApplication) // Use cluster config for backwards compatibility. .configure(clusterConfig, classLoader); } if (logger != null) { logger.info("Using application defined checkpoint storage: {}", fromApplication); } return fromApplication; } return fromConfig(mergedConfig, classLoader, logger) .orElseGet(() -> createDefaultCheckpointStorage(mergedConfig, classLoader, logger)); }
@Test void testLoadFileSystemCheckpointStorageMixed() throws Exception { final Path appCheckpointDir = new Path(TempDirUtils.newFolder(tmp).toURI()); final String checkpointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString(); final String savepointDir = new Path(TempDirUtils.newFolder(tmp).toURI()).toString(); final Path expectedSavepointsPath = new Path(savepointDir); final int threshold = 1000000; final int writeBufferSize = 4000000; final FileSystemCheckpointStorage storage = new FileSystemCheckpointStorage(appCheckpointDir, threshold, writeBufferSize); final Configuration config = new Configuration(); config.set( CheckpointingOptions.CHECKPOINT_STORAGE, "jobmanager"); // this should not be picked up config.set( CheckpointingOptions.CHECKPOINTS_DIRECTORY, checkpointDir); // this should not be picked up config.set(CheckpointingOptions.SAVEPOINT_DIRECTORY, savepointDir); config.set( CheckpointingOptions.FS_SMALL_FILE_THRESHOLD, MemorySize.parse("20")); // this should not be picked up config.set( CheckpointingOptions.FS_WRITE_BUFFER_SIZE, 3000000); // this should not be picked up final CheckpointStorage loadedStorage1 = CheckpointStorageLoader.load( storage, new ModernStateBackend(), new Configuration(), config, cl, LOG); assertThat(loadedStorage1).isInstanceOf(FileSystemCheckpointStorage.class); final FileSystemCheckpointStorage fs1 = (FileSystemCheckpointStorage) loadedStorage1; assertThat(fs1.getCheckpointPath()).is(matching(normalizedPath(appCheckpointDir))); assertThat(fs1.getSavepointPath()).is(matching(normalizedPath(expectedSavepointsPath))); assertThat(fs1.getMinFileSizeThreshold()).isEqualTo(threshold); assertThat(fs1.getWriteBufferSize()).isEqualTo(writeBufferSize); }
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) { CsvIOParseHelpers.validateCsvFormat(csvFormat); CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema); RowCoder coder = RowCoder.of(schema); CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.builder(); builder.setCsvFormat(csvFormat).setSchema(schema).setCoder(coder).setFromRowFn(row -> row); return CsvIOParse.<Row>builder().setConfigBuilder(builder).build(); }
@Test public void givenMismatchedCsvFormatAndSchema_throws() { Pipeline pipeline = Pipeline.create(); CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader("a_string", "an_integer", "a_double") .withAllowDuplicateHeaderNames(true); Schema schema = Schema.builder().addStringField("a_string").addDoubleField("a_double").build(); assertThrows(IllegalArgumentException.class, () -> CsvIO.parseRows(schema, csvFormat)); pipeline.run(); }
@Override public void scheduleCommand(Command command) { scheduleCommand(command, DEFAULT_SCHEDULING_TIMEOUT); }
@Test public void testScheduleCommand() throws Exception { final WaitHelper.ResultHolder resultHolder = new WaitHelper.ResultHolder(); command.setCommandExecutionListener(new CommandExecutionListener() { @Override public void commandExecuted(Object result) { assertNotNull("Command result not null", result); assertTrue("Command result true", result instanceof Boolean && ((Boolean) result)); resultHolder.result = true; } }); scheduler.scheduleCommand(command); assertTrue("Event listener not called", WaitHelper.waitForResult(resultHolder)); }
public Seckill getSeckill(long seckillId) { String key = "seckill:" + seckillId; Seckill seckill = (Seckill) redisTemplate.opsForValue().get(key); if (seckill != null) { return seckill; } else { seckill = seckillMapper.selectById(seckillId); if (seckill == null) { throw new RuntimeException("秒杀活动不存在!"); } putSeckill(seckill); return seckill; } }
@Test void getSeckillError() { long seckillId = 1001L; when(redisTemplate.opsForValue()).thenReturn(mock(ValueOperations.class)); assertThrows(RuntimeException.class, () -> redisService.getSeckill(seckillId)); }
@Override public String create(final Local file) { return null; }
@Test public void testCreate() { assertNull(new DisabledFilesystemBookmarkResolver().create(new NullLocal("/t"))); }
public CommonContext conclude() { if (0 != IS_CONCLUDED_UPDATER.getAndSet(this, 1)) { throw new ConcurrentConcludeException(); } concludeAeronDirectory(); cncFile = new File(aeronDirectory, CncFileDescriptor.CNC_FILE); return this; }
@Test void shouldNotAllowConcludeMoreThanOnce() { final CommonContext ctx = new CommonContext(); ctx.conclude(); assertThrows(ConcurrentConcludeException.class, ctx::conclude); }
public List<AnalyzedInstruction> getAnalyzedInstructions() { return analyzedInstructions.getValues(); }
@Test public void testInstanceOfNarrowingEqz_dalvik() throws IOException { MethodImplementationBuilder builder = new MethodImplementationBuilder(2); builder.addInstruction(new BuilderInstruction22c(Opcode.INSTANCE_OF, 0, 1, new ImmutableTypeReference("Lmain;"))); builder.addInstruction(new BuilderInstruction21t(Opcode.IF_EQZ, 0, builder.getLabel("not_instance_of"))); builder.addInstruction(new BuilderInstruction10x(Opcode.RETURN_VOID)); builder.addLabel("not_instance_of"); builder.addInstruction(new BuilderInstruction10x(Opcode.RETURN_VOID)); MethodImplementation methodImplementation = builder.getMethodImplementation(); Method method = new ImmutableMethod("Lmain;", "narrowing", Collections.singletonList(new ImmutableMethodParameter("Ljava/lang/Object;", null, null)), "V", AccessFlags.PUBLIC.getValue(), null, null, methodImplementation); ClassDef classDef = new ImmutableClassDef("Lmain;", AccessFlags.PUBLIC.getValue(), "Ljava/lang/Object;", null, null, null, null, Collections.singletonList(method)); DexFile dexFile = new ImmutableDexFile(Opcodes.forApi(19), Collections.singletonList(classDef)); ClassPath classPath = new ClassPath(new DexClassProvider(dexFile)); MethodAnalyzer methodAnalyzer = new MethodAnalyzer(classPath, method, null, false); List<AnalyzedInstruction> analyzedInstructions = methodAnalyzer.getAnalyzedInstructions(); Assert.assertEquals("Ljava/lang/Object;", analyzedInstructions.get(2).getPreInstructionRegisterType(1).type.getType()); Assert.assertEquals("Ljava/lang/Object;", analyzedInstructions.get(3).getPreInstructionRegisterType(1).type.getType()); }
public boolean didTimeout(long duration, TimeUnit unit) { if (completed) { return false; } return timeSinceLastLine(unit) > duration; }
@Test public void shouldKnowIfPumperExpired() throws Exception { PipedOutputStream output = new PipedOutputStream(); try (output) { InputStream inputStream = new PipedInputStream(output); TestingClock clock = new TestingClock(); StreamPumper pumper = new StreamPumper(inputStream, new TestConsumer(), "", StandardCharsets.UTF_8, clock); new Thread(pumper).start(); output.write("line1\n".getBytes()); output.flush(); long timeoutDuration = 2L; assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(false)); clock.addSeconds(5); assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(true)); } }
@Override public void addTask(Object key, AbstractDelayTask newTask) { lock.lock(); try { AbstractDelayTask existTask = tasks.get(key); if (null != existTask) { newTask.merge(existTask); } tasks.put(key, newTask); } finally { lock.unlock(); } }
@Test void testRetryTaskAfterFail() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(false, true); nacosDelayTaskExecuteEngine.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(300); verify(taskProcessor, new Times(2)).process(abstractTask); }
public static Driver load(String className) throws DriverLoadException { final ClassLoader loader = DriverLoader.class.getClassLoader(); return load(className, loader); }
@Test(expected = DriverLoadException.class) public void testLoad_String_String_badClassName() throws Exception { String className = "com.mybad.jdbc.Driver"; //we know this is in target/test-classes //File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile(); File testClassPath = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar").getParentFile(); File driver = new File(testClassPath, "../../src/test/resources/mysql-connector-java-5.1.27-bin.jar"); assertTrue("MySQL Driver JAR file not found in src/test/resources?", driver.isFile()); DriverLoader.load(className, driver.getAbsolutePath()); }
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) { Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">"); if(object == null) return null; if(object instanceof Object[]) { return (T)Array.get(object, 0); } else { return (T)object; } }
@Test public void testSingleWithProperties() { G g = SingletonServiceFactory.getBean(G.class); Assert.assertEquals("Sky Walker", g.getName()); Assert.assertEquals(23, g.getAge()); }
@Override public void visit(final Entry target) { final String actionName = target.getName(); if (!actionName.isEmpty() && new EntryAccessor().getAction(target) == null) { AFreeplaneAction action = freeplaneActions.getAction(actionName); if(action == null) { for (final Class<? extends AFreeplaneAction> actionClass : Arrays.asList(SetBooleanPropertyAction.class, SetBooleanMapPropertyAction.class, SetBooleanMapViewPropertyAction.class, SetStringPropertyAction.class)){ final String actionPrefix = actionClass.getSimpleName() + "."; if (actionName.startsWith(actionPrefix)) { String propertyName = actionName.substring(actionPrefix.length()); action = createAction(actionClass, propertyName); if(action != null) { freeplaneActions.addAction(action); } break; } } } new EntryAccessor().setAction(target, action); } }
@Test public void attachesExistingFreeplaneAction() { FreeplaneActions freeplaneActions = mock(FreeplaneActions.class); Entry entry = new Entry(); entry.setName("action"); final AFreeplaneAction someAction = Mockito.mock(AFreeplaneAction.class); when(freeplaneActions.getAction("action")).thenReturn(someAction); final ActionFinder actionFinder = new ActionFinder(freeplaneActions); actionFinder.visit(entry); assertThat(new EntryAccessor().getAction(entry), CoreMatchers.equalTo(someAction)); }
@Override public Character getCharAndRemove(K name) { return null; }
@Test public void testGetCharAndRemove() { assertNull(HEADERS.getCharAndRemove("name1")); }
static Node selectNodeByRequesterAndStrategy(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node) { // The limit app should not be empty. String limitApp = rule.getLimitApp(); int strategy = rule.getStrategy(); String origin = context.getOrigin(); if (limitApp.equals(origin) && filterOrigin(origin)) { if (strategy == RuleConstant.STRATEGY_DIRECT) { // Matches limit origin, return origin statistic node. return context.getOriginNode(); } return selectReferenceNode(rule, context, node); } else if (RuleConstant.LIMIT_APP_DEFAULT.equals(limitApp)) { if (strategy == RuleConstant.STRATEGY_DIRECT) { // Return the cluster node. return node.getClusterNode(); } return selectReferenceNode(rule, context, node); } else if (RuleConstant.LIMIT_APP_OTHER.equals(limitApp) && FlowRuleManager.isOtherOrigin(origin, rule.getResource())) { if (strategy == RuleConstant.STRATEGY_DIRECT) { return context.getOriginNode(); } return selectReferenceNode(rule, context, node); } return null; }
@Test public void testCustomOriginFlowSelectNode() { String origin = "appA"; String limitAppB = "appB"; DefaultNode node = mock(DefaultNode.class); DefaultNode originNode = mock(DefaultNode.class); ClusterNode cn = mock(ClusterNode.class); when(node.getClusterNode()).thenReturn(cn); Context context = mock(Context.class); when(context.getOrigin()).thenReturn(origin); when(context.getOriginNode()).thenReturn(originNode); FlowRule rule = new FlowRule("testCustomOriginFlowSelectNode").setCount(1); rule.setLimitApp(origin); // Origin matches, return the origin node. assertEquals(originNode, FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node)); rule.setLimitApp(limitAppB); // Origin mismatch, no node found. assertNull(FlowRuleChecker.selectNodeByRequesterAndStrategy(rule, context, node)); }
@Override public void selectWorker(long workerId) throws NonRecoverableException { if (getWorkerById(workerId) == null) { reportWorkerNotFoundException(workerId); } selectWorkerUnchecked(workerId); }
@Test public void testSelectWorker() throws UserException { HostBlacklist blockList = SimpleScheduler.getHostBlacklist(); SystemInfoService sysInfo = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo(); List<Long> availList = prepareNodeAliveAndBlock(sysInfo, blockList); WorkerProvider provider = newWorkerProvider(); // intend to iterate the id out of the actual range. for (long id = -1; id < id2AllNodes.size() + 5; id++) { if (availList.contains(id)) { provider.selectWorker(id); testUsingWorkerHelper(provider, id); } else { long finalId = id; Assert.assertThrows(NonRecoverableException.class, () -> provider.selectWorker(finalId)); } } }
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) { if (partitions == null || partitions.isEmpty()) { return Collections.emptyMap(); } Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> OffsetSpec.latest())); ListOffsetsResult resultFuture = admin.listOffsets(offsetSpecMap, new ListOffsetsOptions(IsolationLevel.READ_UNCOMMITTED)); // Get the individual result for each topic partition so we have better error messages Map<TopicPartition, Long> result = new HashMap<>(); for (TopicPartition partition : partitions) { try { ListOffsetsResultInfo info = resultFuture.partitionResult(partition).get(); result.put(partition, info.offset()); } catch (ExecutionException e) { Throwable cause = e.getCause(); String topic = partition.topic(); if (cause instanceof AuthorizationException) { String msg = String.format("Not authorized to get the end offsets for topic '%s' on brokers at %s", topic, bootstrapServers); throw new ConnectException(msg, cause); } else if (cause instanceof UnsupportedVersionException) { // Should theoretically never happen, because this method is the same as what the consumer uses and therefore // should exist in the broker since before the admin client was added String msg = String.format("API to get the get the end offsets for topic '%s' is unsupported on brokers at %s", topic, bootstrapServers); throw new UnsupportedVersionException(msg, cause); } else if (cause instanceof TimeoutException) { String msg = String.format("Timed out while waiting to get end offsets for topic '%s' on brokers at %s", topic, bootstrapServers); throw new TimeoutException(msg, cause); } else if (cause instanceof LeaderNotAvailableException) { String msg = String.format("Unable to get end offsets during leader election for topic '%s' on brokers at %s", topic, bootstrapServers); throw new LeaderNotAvailableException(msg, cause); } else if (cause instanceof org.apache.kafka.common.errors.RetriableException) { throw (org.apache.kafka.common.errors.RetriableException) cause; } else { String msg = String.format("Error while getting end offsets for topic '%s' on brokers at %s", topic, bootstrapServers); throw new ConnectException(msg, cause); } } catch (InterruptedException e) { Thread.interrupted(); String msg = String.format("Interrupted while attempting to read end offsets for topic '%s' on brokers at %s", partition.topic(), bootstrapServers); throw new RetriableException(msg, e); } } return result; }
@Test public void endOffsetsShouldReturnOffsetsForOnePartition() { String topicName = "myTopic"; TopicPartition tp1 = new TopicPartition(topicName, 0); Set<TopicPartition> tps = Collections.singleton(tp1); long offset = 1000L; Cluster cluster = createCluster(1, topicName, 1); try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(new MockTime(), cluster)) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(prepareMetadataResponse(cluster, Errors.NONE)); env.kafkaClient().prepareResponse(listOffsetsResult(tp1, offset)); TopicAdmin admin = new TopicAdmin(env.adminClient()); Map<TopicPartition, Long> offsets = admin.endOffsets(tps); assertEquals(1, offsets.size()); assertEquals(Long.valueOf(offset), offsets.get(tp1)); } }
@Override public <VO, VR> KStream<K, VR> outerJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return outerJoin(otherStream, toValueJoinerWithKey(joiner), windows); }
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullValueJoinerWithKeyOnOuterJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.outerJoin(testStream, (ValueJoinerWithKey<? super String, ? super String, ? super String, ?>) null, JoinWindows.of(ofMillis(10)))); assertThat(exception.getMessage(), equalTo("joiner can't be null")); }
public Optional<String> getHostName(String nodeId) { return hostNameCache.getUnchecked(nodeId); }
@Test public void getHostNameUsesCache() { when(cluster.nodeIdToHostName("node_id")).thenReturn(Optional.of("node-hostname")); nodeInfoCache.getHostName("node_id"); nodeInfoCache.getHostName("node_id"); verify(cluster, times(1)).nodeIdToHostName("node_id"); }
public static void isTrue(boolean expression, String message) { if (!expression) { throw new IllegalArgumentException(message); } }
@Test(expected = IllegalArgumentException.class) public void assertIsTrue() { Assert.isTrue(false, "test message"); }
ControllerResult<Map<String, ApiError>> updateFeatures( Map<String, Short> updates, Map<String, FeatureUpdate.UpgradeType> upgradeTypes, boolean validateOnly ) { TreeMap<String, ApiError> results = new TreeMap<>(); List<ApiMessageAndVersion> records = BoundedList.newArrayBacked(MAX_RECORDS_PER_USER_OP); for (Entry<String, Short> entry : updates.entrySet()) { results.put(entry.getKey(), updateFeature(entry.getKey(), entry.getValue(), upgradeTypes.getOrDefault(entry.getKey(), FeatureUpdate.UpgradeType.UPGRADE), records)); } if (validateOnly) { return ControllerResult.of(Collections.emptyList(), results); } else { return ControllerResult.atomicOf(records, results); } }
@Test public void testUpdateFeatures() { SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext()); FeatureControlManager manager = new FeatureControlManager.Builder(). setQuorumFeatures(features("foo", 1, 2)). setSnapshotRegistry(snapshotRegistry). setMetadataVersion(MetadataVersion.IBP_3_3_IV0). build(); snapshotRegistry.idempotentCreateSnapshot(-1); assertEquals(new FinalizedControllerFeatures(Collections.singletonMap("metadata.version", (short) 4), -1), manager.finalizedFeatures(-1)); assertEquals(ControllerResult.atomicOf(emptyList(), Collections. singletonMap("foo", new ApiError(Errors.INVALID_UPDATE_VERSION, "Invalid update version 3 for feature foo. Local controller 0 only supports versions 1-2"))), manager.updateFeatures(updateMap("foo", 3), Collections.singletonMap("foo", FeatureUpdate.UpgradeType.SAFE_DOWNGRADE), false)); ControllerResult<Map<String, ApiError>> result = manager.updateFeatures( updateMap("foo", 2, "bar", 1), Collections.emptyMap(), false); Map<String, ApiError> expectedMap = new HashMap<>(); expectedMap.put("foo", ApiError.NONE); expectedMap.put("bar", new ApiError(Errors.INVALID_UPDATE_VERSION, "Invalid update version 1 for feature bar. Local controller 0 does not support this feature.")); assertEquals(expectedMap, result.response()); List<ApiMessageAndVersion> expectedMessages = new ArrayList<>(); expectedMessages.add(new ApiMessageAndVersion(new FeatureLevelRecord(). setName("foo").setFeatureLevel((short) 2), (short) 0)); assertEquals(expectedMessages, result.records()); }
static java.sql.Date parseSqlDate(final String value) { try { // JDK format in Date.valueOf is compatible with DATE_FORMAT return java.sql.Date.valueOf(value); } catch (IllegalArgumentException e) { return throwRuntimeParseException(value, new ParseException(value, 0), SQL_DATE_FORMAT); } }
@Test public void testSqlDate() { long now = System.currentTimeMillis(); java.sql.Date date1 = new java.sql.Date(now); java.sql.Date date2 = DateHelper.parseSqlDate(date1.toString()); assertSqlDatesEqual(date1, date2); }
@Override public boolean test(Pickle pickle) { URI picklePath = pickle.getUri(); if (!lineFilters.containsKey(picklePath)) { return true; } for (Integer line : lineFilters.get(picklePath)) { if (Objects.equals(line, pickle.getLocation().getLine()) || Objects.equals(line, pickle.getScenarioLocation().getLine()) || pickle.getExamplesLocation().map(Location::getLine).map(line::equals).orElse(false) || pickle.getRuleLocation().map(Location::getLine).map(line::equals).orElse(false) || pickle.getFeatureLocation().map(Location::getLine).map(line::equals).orElse(false)) { return true; } } return false; }
@Test void matches_rule() { LinePredicate predicate = new LinePredicate(singletonMap( featurePath, singletonList(2))); assertTrue(predicate.test(firstPickle)); assertTrue(predicate.test(secondPickle)); assertTrue(predicate.test(thirdPickle)); assertTrue(predicate.test(fourthPickle)); }
@Override public void removeFlowRules(FlowRule... flowRules) { FlowRuleOperations.Builder builder = FlowRuleOperations.builder(); for (FlowRule flowRule : flowRules) { builder.remove(flowRule); } apply(builder.build()); }
@Test public void removeFlowRules() { FlowRule f1 = addFlowRule(1); FlowRule f2 = addFlowRule(2); FlowRule f3 = addFlowRule(3); assertEquals("3 rules should exist", 3, flowCount(vnetFlowRuleService1)); FlowEntry fe1 = new DefaultFlowEntry(f1); FlowEntry fe2 = new DefaultFlowEntry(f2); FlowEntry fe3 = new DefaultFlowEntry(f3); providerService1.pushFlowMetrics(VDID1, ImmutableList.of(fe1, fe2, fe3)); validateEvents(listener1, RULE_ADD_REQUESTED, RULE_ADD_REQUESTED, RULE_ADD_REQUESTED, RULE_ADDED, RULE_ADDED, RULE_ADDED); vnetFlowRuleService1.removeFlowRules(f1, f2); //removing from north, so no events generated validateEvents(listener1, RULE_REMOVE_REQUESTED, RULE_REMOVE_REQUESTED); assertEquals("3 rule should exist", 3, flowCount(vnetFlowRuleService1)); assertTrue("Entries should be pending remove.", validateState(ImmutableMap.of( f1, FlowEntry.FlowEntryState.PENDING_REMOVE, f2, FlowEntry.FlowEntryState.PENDING_REMOVE, f3, FlowEntry.FlowEntryState.ADDED))); vnetFlowRuleService1.removeFlowRules(f1); assertEquals("3 rule should still exist", 3, flowCount(vnetFlowRuleService1)); }
@Override public MaskRuleConfiguration findRuleConfiguration(final ShardingSphereDatabase database) { return database.getRuleMetaData().findSingleRule(MaskRule.class) .map(optional -> getConfiguration(optional.getConfiguration())).orElseGet(() -> new MaskRuleConfiguration(new LinkedList<>(), new LinkedHashMap<>())); }
@Test void assertFindRuleConfigurationWhenTableDoesNotExist() { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getRuleMetaData().findSingleRule(MaskRule.class)).thenReturn(Optional.of(new MaskRule(new MaskRuleConfiguration(Collections.emptyList(), Collections.emptyMap())))); assertTrue(new MaskTableChangedProcessor().findRuleConfiguration(database).getTables().isEmpty()); }
@Override public void ignoreAutoTrackActivities(List<Class<?>> activitiesList) { }
@Test public void ignoreAutoTrackActivities() { List<Class<?>> activities = new ArrayList<>(); activities.add(EmptyActivity.class); activities.add(ListActivity.class); mSensorsAPI.ignoreAutoTrackActivities(activities); Assert.assertTrue(mSensorsAPI.isActivityAutoTrackAppClickIgnored(EmptyActivity.class)); }
public String name() { return name; }
@Test public void testConstruction() { assertThat(bridgeName1.name(), is(NAME1)); }
public static boolean isHttp(String url) { return StrUtil.startWithIgnoreCase(url, "http:"); }
@Test public void isHttpTest(){ assertTrue(HttpUtil.isHttp("Http://aaa.bbb")); assertTrue(HttpUtil.isHttp("HTTP://aaa.bbb")); assertFalse(HttpUtil.isHttp("FTP://aaa.bbb")); }
@Udf public <T> List<String> mapKeys(final Map<String, T> input) { if (input == null) { return null; } return Lists.newArrayList(input.keySet()); }
@Test public void shouldReturnNullForNullInput() { List<String> result = udf.mapKeys((Map<String, Long>) null); assertThat(result, is(nullValue())); }
public ProducerConnection getProducerConnectionList(final String addr, final String producerGroup, final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException { GetProducerConnectionListRequestHeader requestHeader = new GetProducerConnectionListRequestHeader(); requestHeader.setProducerGroup(producerGroup); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_PRODUCER_CONNECTION_LIST, requestHeader); RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis); switch (response.getCode()) { case ResponseCode.SUCCESS: { return ProducerConnection.decode(response.getBody(), ProducerConnection.class); } default: break; } throw new MQBrokerException(response.getCode(), response.getRemark(), addr); }
@Test public void assertGetProducerConnectionList() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); ProducerConnection responseBody = new ProducerConnection(); responseBody.getConnectionSet().add(new Connection()); setResponseBody(responseBody); ProducerConnection actual = mqClientAPI.getProducerConnectionList(defaultBrokerAddr, "", defaultTimeout); assertNotNull(actual); assertEquals(1, actual.getConnectionSet().size()); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TaskPreference that = (TaskPreference) o; if (!taskConfig.equals(that.taskConfig)) return false; if (!taskView.equals(that.taskView)) return false; return true; }
@Test public void shouldTestEquals() throws Exception { Task task1 = mock(Task.class); TaskConfig config1 = new TaskConfig(); TaskView taskView1 = mock(TaskView.class); when(task1.config()).thenReturn(config1); when(task1.view()).thenReturn(taskView1); TaskPreference taskPreference1 = new TaskPreference(task1); Task task2 = mock(Task.class); TaskConfig config2 = new TaskConfig(); TaskView taskView2 = mock(TaskView.class); when(task2.config()).thenReturn(config2); when(task2.view()).thenReturn(taskView2); TaskPreference taskPreference2 = new TaskPreference(task2); TaskPreference taskPreference3 = new TaskPreference(task1); Task task3 = mock(Task.class); when(task3.config()).thenReturn(config1); when(task3.view()).thenReturn(taskView1); TaskPreference taskPreference4 = new TaskPreference(task3); Task task5 = mock(Task.class); TaskView taskView5 = mock(TaskView.class); when(task5.config()).thenReturn(config1); when(task5.view()).thenReturn(taskView5); TaskPreference taskPreference5 = new TaskPreference(task5); assertThat(taskPreference1.equals(taskPreference2), is(false)); assertThat(taskPreference1.equals(taskPreference3), is(true)); assertThat(taskPreference1.equals(taskPreference4), is(true)); assertThat(taskPreference1.equals(taskPreference5), is(false)); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; } String message = chatMessage.getMessage(); Matcher matcher = KILLCOUNT_PATTERN.matcher(message); if (matcher.find()) { final String boss = matcher.group("boss"); final int kc = Integer.parseInt(matcher.group("kc")); final String pre = matcher.group("pre"); final String post = matcher.group("post"); if (Strings.isNullOrEmpty(pre) && Strings.isNullOrEmpty(post)) { unsetKc(boss); return; } String renamedBoss = KILLCOUNT_RENAMES .getOrDefault(boss, boss) // The config service doesn't support keys with colons in them .replace(":", ""); if (boss != renamedBoss) { // Unset old TOB kc unsetKc(boss); unsetPb(boss); unsetKc(boss.replace(":", ".")); unsetPb(boss.replace(":", ".")); // Unset old story mode unsetKc("Theatre of Blood Story Mode"); unsetPb("Theatre of Blood Story Mode"); } setKc(renamedBoss, kc); // We either already have the pb, or need to remember the boss for the upcoming pb if (lastPb > -1) { log.debug("Got out-of-order personal best for {}: {}", renamedBoss, lastPb); if (renamedBoss.contains("Theatre of Blood")) { // TOB team size isn't sent in the kill message, but can be computed from varbits int tobTeamSize = tobTeamSize(); lastTeamSize = tobTeamSize == 1 ? "Solo" : (tobTeamSize + " players"); } else if (renamedBoss.contains("Tombs of Amascut")) { // TOA team size isn't sent in the kill message, but can be computed from varbits int toaTeamSize = toaTeamSize(); lastTeamSize = toaTeamSize == 1 ? "Solo" : (toaTeamSize + " players"); } final double pb = getPb(renamedBoss); // If a raid with a team size, only update the pb if it is lower than the existing pb // so that the pb is the overall lowest of any team size if (lastTeamSize == null || pb == 0 || lastPb < pb) { log.debug("Setting overall pb (old: {})", pb); setPb(renamedBoss, lastPb); } if (lastTeamSize != null) { log.debug("Setting team size pb: {}", lastTeamSize); setPb(renamedBoss + " " + lastTeamSize, lastPb); } lastPb = -1; lastTeamSize = null; } else { lastBossKill = renamedBoss; lastBossTime = client.getTickCount(); } return; } matcher = DUEL_ARENA_WINS_PATTERN.matcher(message); if (matcher.find()) { final int oldWins = getKc("Duel Arena Wins"); final int wins = matcher.group(2).equals("one") ? 1 : Integer.parseInt(matcher.group(2).replace(",", "")); final String result = matcher.group(1); int winningStreak = getKc("Duel Arena Win Streak"); int losingStreak = getKc("Duel Arena Lose Streak"); if (result.equals("won") && wins > oldWins) { losingStreak = 0; winningStreak += 1; } else if (result.equals("were defeated")) { losingStreak += 1; winningStreak = 0; } else { log.warn("unrecognized duel streak chat message: {}", message); } setKc("Duel Arena Wins", wins); setKc("Duel Arena Win Streak", winningStreak); setKc("Duel Arena Lose Streak", losingStreak); } matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message); if (matcher.find()) { int losses = matcher.group(1).equals("one") ? 1 : Integer.parseInt(matcher.group(1).replace(",", "")); setKc("Duel Arena Losses", losses); } matcher = KILL_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = NEW_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_PB_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = RAIDS_DURATION_PATTERN.matcher(message); if (matcher.find()) { matchPb(matcher); } matcher = HS_PB_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group("floor")); String floortime = matcher.group("floortime"); String floorpb = matcher.group("floorpb"); String otime = matcher.group("otime"); String opb = matcher.group("opb"); String pb = MoreObjects.firstNonNull(floorpb, floortime); setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb)); if (otime != null) { pb = MoreObjects.firstNonNull(opb, otime); setPb("Hallowed Sepulchre", timeStringToSeconds(pb)); } } matcher = HS_KC_FLOOR_PATTERN.matcher(message); if (matcher.find()) { int floor = Integer.parseInt(matcher.group(1)); int kc = Integer.parseInt(matcher.group(2).replaceAll(",", "")); setKc("Hallowed Sepulchre Floor " + floor, kc); } matcher = HS_KC_GHC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hallowed Sepulchre", kc); } matcher = HUNTER_RUMOUR_KC_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1).replaceAll(",", "")); setKc("Hunter Rumours", kc); } if (lastBossKill != null && lastBossTime != client.getTickCount()) { lastBossKill = null; lastBossTime = -1; } matcher = COLLECTION_LOG_ITEM_PATTERN.matcher(message); if (matcher.find()) { String item = matcher.group(1); int petId = findPet(item); if (petId != -1) { final List<Integer> petList = new ArrayList<>(getPetList()); if (!petList.contains(petId)) { log.debug("New pet added: {}/{}", item, petId); petList.add(petId); setPetList(petList); } } } matcher = GUARDIANS_OF_THE_RIFT_PATTERN.matcher(message); if (matcher.find()) { int kc = Integer.parseInt(matcher.group(1)); setKc("Guardians of the Rift", kc); } }
@Test public void testHerbiboar() { ChatMessage chatMessageEvent = new ChatMessage(null, GAMEMESSAGE, "", "Your herbiboar harvest count is: <col=ff0000>4091</col>.", null, 0); chatCommandsPlugin.onChatMessage(chatMessageEvent); verify(configManager).setRSProfileConfiguration("killcount", "herbiboar", 4091); }
@GetMapping("/auth/delete") public Mono<String> clean(@RequestParam("appKey") final String appKey) { if (CollectionUtils.isEmpty(subscribers)) { return Mono.just(Constants.SUCCESS); } LOG.info("delete apache shenyu local AppAuth data"); AppAuthData appAuthData = AppAuthData.builder().appKey(appKey).build(); subscribers.forEach(authDataSubscriber -> authDataSubscriber.unSubscribe(appAuthData)); return Mono.just(Constants.SUCCESS); }
@Test public void testClean() throws Exception { String appKey = "D9FD95F496C9495DB5604778A13C3D08"; final MockHttpServletResponse response = this.mockMvc.perform(MockMvcRequestBuilders.get("/shenyu/auth/delete") .contentType(MediaType.APPLICATION_JSON) .queryParam("appKey", appKey)) .andReturn().getResponse(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); AppAuthData appAuthData = new AppAuthData(); appAuthData.setAppKey(appKey); subscribers.forEach(subscriber -> verify(subscriber).unSubscribe(appAuthData)); final MockHttpServletResponse responseError = this.mockMvcSubscribersNull.perform(MockMvcRequestBuilders.get("/shenyu/auth/delete") .contentType(MediaType.APPLICATION_JSON) .queryParam("appKey", appKey)) .andReturn().getResponse(); assertThat(responseError.getStatus()).isEqualTo(HttpStatus.OK.value()); }
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } int frameOffset = buffer.readerIndex(); int flagsOffset = frameOffset + SPDY_HEADER_FLAGS_OFFSET; int lengthOffset = frameOffset + SPDY_HEADER_LENGTH_OFFSET; buffer.skipBytes(SPDY_HEADER_SIZE); boolean control = (buffer.getByte(frameOffset) & 0x80) != 0; int version; int type; if (control) { // Decode control frame common header version = getUnsignedShort(buffer, frameOffset) & 0x7FFF; type = getUnsignedShort(buffer, frameOffset + SPDY_HEADER_TYPE_OFFSET); streamId = 0; // Default to session Stream-ID } else { // Decode data frame common header version = spdyVersion; // Default to expected version type = SPDY_DATA_FRAME; streamId = getUnsignedInt(buffer, frameOffset); } flags = buffer.getByte(flagsOffset); length = getUnsignedMedium(buffer, lengthOffset); // Check version first then validity if (version != spdyVersion) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SPDY Version"); } else if (!isValidFrameHeader(streamId, type, flags, length)) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid Frame Error"); } else { state = getNextState(type, length); } break; case READ_DATA_FRAME: if (length == 0) { state = State.READ_COMMON_HEADER; delegate.readDataFrame(streamId, hasFlag(flags, SPDY_DATA_FLAG_FIN), Unpooled.buffer(0)); break; } // Generate data frames that do not exceed maxChunkSize int dataLength = Math.min(maxChunkSize, length); // Wait until entire frame is readable if (buffer.readableBytes() < dataLength) { return; } ByteBuf data = buffer.alloc().buffer(dataLength); data.writeBytes(buffer, dataLength); length -= dataLength; if (length == 0) { state = State.READ_COMMON_HEADER; } last = length == 0 && hasFlag(flags, SPDY_DATA_FLAG_FIN); delegate.readDataFrame(streamId, last, data); break; case READ_SYN_STREAM_FRAME: if (buffer.readableBytes() < 10) { return; } int offset = buffer.readerIndex(); streamId = getUnsignedInt(buffer, offset); int associatedToStreamId = getUnsignedInt(buffer, offset + 4); byte priority = (byte) (buffer.getByte(offset + 8) >> 5 & 0x07); last = hasFlag(flags, SPDY_FLAG_FIN); boolean unidirectional = hasFlag(flags, SPDY_FLAG_UNIDIRECTIONAL); buffer.skipBytes(10); length -= 10; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SYN_STREAM Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readSynStreamFrame(streamId, associatedToStreamId, priority, last, unidirectional); } break; case READ_SYN_REPLY_FRAME: if (buffer.readableBytes() < 4) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); last = hasFlag(flags, SPDY_FLAG_FIN); buffer.skipBytes(4); length -= 4; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SYN_REPLY Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readSynReplyFrame(streamId, last); } break; case READ_RST_STREAM_FRAME: if (buffer.readableBytes() < 8) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); statusCode = getSignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); if (streamId == 0 || statusCode == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid RST_STREAM Frame"); } else { state = State.READ_COMMON_HEADER; delegate.readRstStreamFrame(streamId, statusCode); } break; case READ_SETTINGS_FRAME: if (buffer.readableBytes() < 4) { return; } boolean clear = hasFlag(flags, SPDY_SETTINGS_CLEAR); numSettings = getUnsignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); length -= 4; // Validate frame length against number of entries. Each ID/Value entry is 8 bytes. if ((length & 0x07) != 0 || length >> 3 != numSettings) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid SETTINGS Frame"); } else { state = State.READ_SETTING; delegate.readSettingsFrame(clear); } break; case READ_SETTING: if (numSettings == 0) { state = State.READ_COMMON_HEADER; delegate.readSettingsEnd(); break; } if (buffer.readableBytes() < 8) { return; } byte settingsFlags = buffer.getByte(buffer.readerIndex()); int id = getUnsignedMedium(buffer, buffer.readerIndex() + 1); int value = getSignedInt(buffer, buffer.readerIndex() + 4); boolean persistValue = hasFlag(settingsFlags, SPDY_SETTINGS_PERSIST_VALUE); boolean persisted = hasFlag(settingsFlags, SPDY_SETTINGS_PERSISTED); buffer.skipBytes(8); --numSettings; delegate.readSetting(id, value, persistValue, persisted); break; case READ_PING_FRAME: if (buffer.readableBytes() < 4) { return; } int pingId = getSignedInt(buffer, buffer.readerIndex()); buffer.skipBytes(4); state = State.READ_COMMON_HEADER; delegate.readPingFrame(pingId); break; case READ_GOAWAY_FRAME: if (buffer.readableBytes() < 8) { return; } int lastGoodStreamId = getUnsignedInt(buffer, buffer.readerIndex()); statusCode = getSignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); state = State.READ_COMMON_HEADER; delegate.readGoAwayFrame(lastGoodStreamId, statusCode); break; case READ_HEADERS_FRAME: if (buffer.readableBytes() < 4) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); last = hasFlag(flags, SPDY_FLAG_FIN); buffer.skipBytes(4); length -= 4; if (streamId == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid HEADERS Frame"); } else { state = State.READ_HEADER_BLOCK; delegate.readHeadersFrame(streamId, last); } break; case READ_WINDOW_UPDATE_FRAME: if (buffer.readableBytes() < 8) { return; } streamId = getUnsignedInt(buffer, buffer.readerIndex()); int deltaWindowSize = getUnsignedInt(buffer, buffer.readerIndex() + 4); buffer.skipBytes(8); if (deltaWindowSize == 0) { state = State.FRAME_ERROR; delegate.readFrameError("Invalid WINDOW_UPDATE Frame"); } else { state = State.READ_COMMON_HEADER; delegate.readWindowUpdateFrame(streamId, deltaWindowSize); } break; case READ_HEADER_BLOCK: if (length == 0) { state = State.READ_COMMON_HEADER; delegate.readHeaderBlockEnd(); break; } if (!buffer.isReadable()) { return; } int compressedBytes = Math.min(buffer.readableBytes(), length); ByteBuf headerBlock = buffer.alloc().buffer(compressedBytes); headerBlock.writeBytes(buffer, compressedBytes); length -= compressedBytes; delegate.readHeaderBlock(headerBlock); break; case DISCARD_FRAME: int numBytes = Math.min(buffer.readableBytes(), length); buffer.skipBytes(numBytes); length -= numBytes; if (length == 0) { state = State.READ_COMMON_HEADER; break; } return; case FRAME_ERROR: buffer.skipBytes(buffer.readableBytes()); return; default: throw new Error("Shouldn't reach here."); } } }
@Test public void testUnknownSpdyPingFrameFlags() throws Exception { short type = 6; byte flags = (byte) 0xFF; // undefined flags int length = 4; int id = RANDOM.nextInt(); ByteBuf buf = Unpooled.buffer(SPDY_HEADER_SIZE + length); encodeControlFrameHeader(buf, type, flags, length); buf.writeInt(id); decoder.decode(buf); verify(delegate).readPingFrame(id); assertFalse(buf.isReadable()); buf.release(); }
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) ); } if ( rsMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoRSMetaDataException" ) ); } try { return dbMetaData.getDriverMajorVersion() > 3 ? rsMetaData.getColumnLabel( index ) : rsMetaData.getColumnName( index ); } catch ( Exception e ) { throw new KettleDatabaseException( String.format( "%s: %s", BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameException" ), e.getMessage() ), e ); } }
@Test( expected = KettleDatabaseException.class ) public void testGetLegacyColumnNameNullRSMetaDataException() throws Exception { new MySQLDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), null, 1 ); }
@Override public Optional<String> getContentHash() { return Optional.ofNullable(mContentHash); }
@Test public void flush() throws Exception { int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE); byte[] b = new byte[2 * partSize - 1]; mStream.write(b, 0, b.length); Mockito.verify(mMockObsClient) .initiateMultipartUpload(any(InitiateMultipartUploadRequest.class)); Mockito.verify(mMockOutputStream).write(b, 0, partSize); Mockito.verify(mMockOutputStream).write(b, partSize, partSize - 1); Mockito.verify(mMockExecutor).submit(any(Callable.class)); mStream.flush(); Mockito.verify(mMockExecutor, times(2)).submit(any(Callable.class)); Mockito.verify(mMockTag, times(2)).get(); mStream.close(); Mockito.verify(mMockObsClient) .completeMultipartUpload(any(CompleteMultipartUploadRequest.class)); assertTrue(mStream.getContentHash().isPresent()); assertEquals("multiTag", mStream.getContentHash().get()); }
@Override public JobDO getJob(Long id) { return jobMapper.selectById(id); }
@Test public void testGetJob() { // mock 数据 JobDO dbJob = randomPojo(JobDO.class); jobMapper.insert(dbJob); // 调用 JobDO job = jobService.getJob(dbJob.getId()); // 断言 assertPojoEquals(dbJob, job); }
CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File connectorConfigurationFile = Paths.get(filePath).toFile(); try { Map<String, String> connectorConfigs = objectMapper.readValue( connectorConfigurationFile, new TypeReference<Map<String, String>>() { }); if (!connectorConfigs.containsKey(NAME_CONFIG)) { throw new ConnectException("Connector configuration at '" + filePath + "' is missing the mandatory '" + NAME_CONFIG + "' " + "configuration"); } return new CreateConnectorRequest(connectorConfigs.get(NAME_CONFIG), connectorConfigs, null); } catch (StreamReadException | DatabindException e) { log.debug("Could not parse connector configuration file '{}' into a Map with String keys and values", filePath); } try { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CreateConnectorRequest createConnectorRequest = objectMapper.readValue(connectorConfigurationFile, new TypeReference<CreateConnectorRequest>() { }); if (createConnectorRequest.config().containsKey(NAME_CONFIG)) { if (!createConnectorRequest.config().get(NAME_CONFIG).equals(createConnectorRequest.name())) { throw new ConnectException("Connector name configuration in 'config' doesn't match the one specified in 'name' at '" + filePath + "'"); } } else { createConnectorRequest.config().put(NAME_CONFIG, createConnectorRequest.name()); } return createConnectorRequest; } catch (StreamReadException | DatabindException e) { log.debug("Could not parse connector configuration file '{}' into an object of type {}", filePath, CreateConnectorRequest.class.getSimpleName()); } Map<String, String> connectorConfigs = Utils.propsToStringMap(Utils.loadProps(filePath)); if (!connectorConfigs.containsKey(NAME_CONFIG)) { throw new ConnectException("Connector configuration at '" + filePath + "' is missing the mandatory '" + NAME_CONFIG + "' " + "configuration"); } return new CreateConnectorRequest(connectorConfigs.get(NAME_CONFIG), connectorConfigs, null); }
@Test public void testParseJsonFileWithCreateConnectorRequest() throws Exception { CreateConnectorRequest requestToWrite = new CreateConnectorRequest( CONNECTOR_NAME, CONNECTOR_CONFIG, CreateConnectorRequest.InitialState.STOPPED ); try (FileWriter writer = new FileWriter(connectorConfigurationFile)) { writer.write(new ObjectMapper().writeValueAsString(requestToWrite)); } CreateConnectorRequest parsedRequest = connectStandalone.parseConnectorConfigurationFile(connectorConfigurationFile.getAbsolutePath()); assertEquals(requestToWrite, parsedRequest); }
@Override public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) { log.trace("PUSHING msg: {} to:{}", msg, tpi); producerProvider.getRuleEngineMsgProducer().send(tpi, new TbProtoQueueMsg<>(msgId, msg), callback); toRuleEngineMsgs.incrementAndGet(); }
@Test public void testPushMsgToRuleEngineWithTenantIdIsNullUuidAndEntityIsDevice() { TenantId tenantId = TenantId.SYS_TENANT_ID; DeviceId deviceId = new DeviceId(UUID.fromString("aa6d112d-2914-4a22-a9e3-bee33edbdb14")); TbMsg requestMsg = TbMsg.newMsg(TbMsgType.REST_API_REQUEST, deviceId, TbMsgMetaData.EMPTY, TbMsg.EMPTY_JSON_OBJECT); TbQueueCallback callback = mock(TbQueueCallback.class); clusterService.pushMsgToRuleEngine(tenantId, deviceId, requestMsg, false, callback); verifyNoMoreInteractions(partitionService, producerProvider); }
public static Boolean matches(String raw, String encoded) { return new BCryptPasswordEncoder().matches(raw, encoded); }
@Test void matches() { Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO"); assertTrue(result1); Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO"); assertFalse(result2); Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos")); assertTrue(matches); }
public void record(Uuid topicId) { // Topic IDs should not differ, but we defensively check here to fail earlier in the case that the IDs somehow differ. dirtyTopicIdOpt.ifPresent(dirtyTopicId -> { if (!dirtyTopicId.equals(topicId)) { throw new InconsistentTopicIdException("Tried to record topic ID " + topicId + " to file " + "but had already recorded " + dirtyTopicId); } }); dirtyTopicIdOpt = Optional.of(topicId); }
@Test public void testSetRecordWithDifferentTopicId() { PartitionMetadataFile partitionMetadataFile = new PartitionMetadataFile(file, null); Uuid topicId = Uuid.randomUuid(); partitionMetadataFile.record(topicId); Uuid differentTopicId = Uuid.randomUuid(); assertThrows(InconsistentTopicIdException.class, () -> partitionMetadataFile.record(differentTopicId)); }
@Override public String toString() { return "ResourceConfig{" + "url=" + url + ", id='" + id + '\'' + ", resourceType=" + resourceType + '}'; }
@Test public void when_attachNonexistentFileWithFileAndId_then_throwsException() { // Given String id = "exist"; String path = Paths.get("/i/do/not/" + id).toString(); File file = new File(path); // Then expectedException.expect(JetException.class); expectedException.expectMessage("Not an existing, readable file: " + path); // When config.attachFile(file, id); }
static BlockStmt getKiePMMLLocalTransformationsVariableDeclaration(final LocalTransformations localTransformations) { final MethodDeclaration methodDeclaration = LOCAL_TRANSFORMATIONS_TEMPLATE.getMethodsByName(GETKIEPMMLLOCALTRANSFORMATIONS).get(0).clone(); final BlockStmt transformationDictionaryBody = methodDeclaration.getBody().orElseThrow(() -> new KiePMMLException(String.format(MISSING_BODY_TEMPLATE, methodDeclaration))); final VariableDeclarator variableDeclarator = getVariableDeclarator(transformationDictionaryBody, LOCAL_TRANSFORMATIONS) .orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_IN_BODY, LOCAL_TRANSFORMATIONS, transformationDictionaryBody))); final MethodCallExpr initializer = variableDeclarator.getInitializer() .orElseThrow(() -> new KiePMMLException(String.format(MISSING_VARIABLE_INITIALIZER_TEMPLATE, LOCAL_TRANSFORMATIONS, methodDeclaration))) .asMethodCallExpr(); final BlockStmt toReturn = new BlockStmt(); if (localTransformations.hasDerivedFields()) { NodeList<Expression> derivedFields = addDerivedField(toReturn, localTransformations.getDerivedFields()); getChainedMethodCallExprFrom("withDerivedFields", initializer).setArguments(derivedFields); } transformationDictionaryBody.getStatements().forEach(toReturn::addStatement); return toReturn; }
@Test void getKiePMMLTransformationDictionaryVariableDeclaration() throws IOException { LocalTransformations localTransformations = new LocalTransformations(); localTransformations.addDerivedFields(getDerivedFields()); BlockStmt retrieved = KiePMMLLocalTransformationsFactory.getKiePMMLLocalTransformationsVariableDeclaration(localTransformations); String text = getFileContent(TEST_01_SOURCE); Statement expected = JavaParserUtils.parseBlock(text); assertThat(JavaParserUtils.equalsNode(expected, retrieved)).isTrue(); List<Class<?>> imports = Arrays.asList(KiePMMLConstant.class, KiePMMLApply.class, KiePMMLDerivedField.class, KiePMMLLocalTransformations.class, Arrays.class, Collections.class); commonValidateCompilationWithImports(retrieved, imports); }
@Override public boolean add(V value) { lock.lock(); try { checkComparator(); BinarySearchResult<V> res = binarySearch(value); int index = 0; if (res.getIndex() < 0) { index = -(res.getIndex() + 1); } else { index = res.getIndex() + 1; } get(commandExecutor.evalWriteNoRetryAsync(getRawName(), codec, RedisCommands.EVAL_VOID, "local len = redis.call('llen', KEYS[1]);" + "if tonumber(ARGV[1]) < len then " + "local pivot = redis.call('lindex', KEYS[1], ARGV[1]);" + "redis.call('linsert', KEYS[1], 'before', pivot, ARGV[2]);" + "return;" + "end;" + "redis.call('rpush', KEYS[1], ARGV[2]);", Arrays.asList(getRawName()), index, encode(value))); return true; } finally { lock.unlock(); } }
@Test public void testReadAll() { RPriorityQueue<Integer> set = redisson.getPriorityQueue("simple"); set.add(2); set.add(0); set.add(1); set.add(5); assertThat(set.readAll()).containsExactly(0, 1, 2, 5); }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); if ("img".equals(localName) && attributes.getValue("alt") != null) { String nfo = "[image: " + attributes.getValue("alt") + ']'; characters(nfo.toCharArray(), 0, nfo.length()); } if ("a".equals(localName) && attributes.getValue("name") != null) { String nfo = "[bookmark: " + attributes.getValue("name") + ']'; characters(nfo.toCharArray(), 0, nfo.length()); } }
@Test public void imgTagTest() throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); XHTMLContentHandler xhtml = new XHTMLContentHandler(new RichTextContentHandler( new OutputStreamWriter(buffer, UTF_8)), new Metadata()); xhtml.startDocument(); AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", "", "alt", "", "value"); xhtml.startElement("img", attributes); xhtml.endDocument(); assertEquals("\n\n\n\n[image: value]", buffer.toString(UTF_8.name())); }
public static boolean isInvalidStanzaSentPriorToResourceBinding(final Packet stanza, final ClientSession session) { // Openfire sets 'authenticated' only after resource binding. if (session.getStatus() == Session.Status.AUTHENTICATED) { return false; } // Beware, the 'to' address in the stanza will have been overwritten by the final JID intendedRecipient = stanza.getTo(); final JID serverDomain = new JID(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); // If there's no 'to' address, then the stanza is implicitly addressed at the user itself. if (intendedRecipient == null) { return false; } // TODO: after authentication (but prior to resource binding), it should be possible to verify that the // intended recipient's bare JID corresponds with the authorized user. Openfire currently does not have an API // that can be used to obtain the authorized username, prior to resource binding. if (intendedRecipient.equals(serverDomain)) { return false; } return true; }
@Test public void testIsInvalid_addressedAtThirdPartyUser_authenticated() throws Exception { // Setup test fixture. final Packet stanza = new Message(); stanza.setTo(new JID("foobar123", XMPPServer.getInstance().getServerInfo().getXMPPDomain(), "test123")); final LocalClientSession session = mock(LocalClientSession.class, withSettings().strictness(Strictness.LENIENT)); when(session.getStatus()).thenReturn(Session.Status.AUTHENTICATED); // Openfire sets 'AUTHENTICATED' only after resource binding has been done. // Execute system under test. final boolean result = SessionPacketRouter.isInvalidStanzaSentPriorToResourceBinding(stanza, session); // Verify results. assertFalse(result); }
@Udf public String concat(@UdfParameter final String... jsonStrings) { if (jsonStrings == null) { return null; } final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length); boolean allObjects = true; for (final String jsonString : jsonStrings) { if (jsonString == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonString); if (node.isMissingNode()) { return null; } if (allObjects && !node.isObject()) { allObjects = false; } nodes.add(node); } JsonNode result = nodes.get(0); if (allObjects) { for (int i = 1; i < nodes.size(); i++) { result = concatObjects((ObjectNode) result, (ObjectNode) nodes.get(i)); } } else { for (int i = 1; i < nodes.size(); i++) { result = concatArrays(toArrayNode(result), toArrayNode(nodes.get(i))); } } return UdfJsonMapper.writeValueAsJson(result); }
@Test public void shouldWrapObjectInArray() { // When: final String result = udf.concat("[1, 2]", "{\"a\": 1}"); // Then: assertEquals("[1,2,{\"a\":1}]", result); }
public static boolean containsAbfsUrl(final String string) { if (string == null || string.isEmpty()) { return false; } return ABFS_URI_PATTERN.matcher(string).matches(); }
@Test public void testIfUriContainsAbfs() throws Exception { Assert.assertTrue(UriUtils.containsAbfsUrl("abfs.dfs.core.windows.net")); Assert.assertTrue(UriUtils.containsAbfsUrl("abfs.dfs.preprod.core.windows.net")); Assert.assertFalse(UriUtils.containsAbfsUrl("abfs.dfs.cores.windows.net")); Assert.assertFalse(UriUtils.containsAbfsUrl("")); Assert.assertFalse(UriUtils.containsAbfsUrl(null)); Assert.assertFalse(UriUtils.containsAbfsUrl("abfs.dfs.cores.windows.net")); Assert.assertFalse(UriUtils.containsAbfsUrl("xhdfs.blob.core.windows.net")); }
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from(outputNode.getKsqlTopic()), outputNode.getKsqlTopic().getKeyFormat().getWindowInfo(), Optional.of(outputNode.getOrReplace()), Optional.of(false) ); }
@Test public void shouldValidateKeyFormatCanHandleKeySchema() { // Given: givenCommandFactoriesWithMocks(); final CreateStream statement = new CreateStream(SOME_NAME, STREAM_ELEMENTS, false, true, withProperties, false); when(keySerdeFactory.create( FormatInfo.of(KAFKA.name()), PersistenceSchema.from(EXPECTED_SCHEMA.key(), SerdeFeatures.of()), ksqlConfig, serviceContext.getSchemaRegistryClientFactory(), "", NoopProcessingLogContext.INSTANCE, Optional.empty() )).thenThrow(new RuntimeException("Boom!")); // When: final Exception e = assertThrows( Exception.class, () -> createSourceFactory.createStreamCommand(statement, ksqlConfig) ); // Then: assertThat(e.getMessage(), containsString("Boom!")); }
public static String getContentIdentity(String content) { int index = content.indexOf(WORD_SEPARATOR); if (index == -1) { throw new IllegalArgumentException("The content does not contain separator!"); } return content.substring(0, index); }
@Test void testGetContentIdentity() { String content = "abc" + Constants.WORD_SEPARATOR + "edf"; String result = ContentUtils.getContentIdentity(content); assertEquals("abc", result); content = "test"; try { ContentUtils.getContentIdentity(content); fail(); } catch (IllegalArgumentException e) { assertNotNull(e.toString()); } }
public static String resolveMainClass( @Nullable String configuredMainClass, ProjectProperties projectProperties) throws MainClassInferenceException, IOException { if (configuredMainClass != null) { if (isValidJavaClass(configuredMainClass)) { return configuredMainClass; } throw new MainClassInferenceException( HelpfulSuggestions.forMainClassNotFound( "'mainClass' configured in " + projectProperties.getPluginName() + " is not a valid Java class: " + configuredMainClass, projectProperties.getPluginName())); } projectProperties.log( LogEvent.info( "Searching for main class... Add a 'mainClass' configuration to '" + projectProperties.getPluginName() + "' to improve build speed.")); String mainClassFromJarPlugin = projectProperties.getMainClassFromJarPlugin(); if (mainClassFromJarPlugin != null && isValidJavaClass(mainClassFromJarPlugin)) { return mainClassFromJarPlugin; } if (mainClassFromJarPlugin != null) { projectProperties.log( LogEvent.warn( "'mainClass' configured in " + projectProperties.getJarPluginName() + " is not a valid Java class: " + mainClassFromJarPlugin)); } projectProperties.log( LogEvent.info( "Could not find a valid main class from " + projectProperties.getJarPluginName() + "; looking into all class files to infer main class.")); MainClassFinder.Result mainClassFinderResult = MainClassFinder.find(projectProperties.getClassFiles(), projectProperties::log); switch (mainClassFinderResult.getType()) { case MAIN_CLASS_FOUND: return mainClassFinderResult.getFoundMainClass(); case MAIN_CLASS_NOT_FOUND: throw new MainClassInferenceException( HelpfulSuggestions.forMainClassNotFound( "Main class was not found", projectProperties.getPluginName())); case MULTIPLE_MAIN_CLASSES: throw new MainClassInferenceException( HelpfulSuggestions.forMainClassNotFound( "Multiple valid main classes were found: " + String.join(", ", mainClassFinderResult.getFoundMainClasses()), projectProperties.getPluginName())); default: throw new IllegalStateException("Cannot reach here"); } }
@Test public void testResolveMainClass_noneInferredWithoutMainClassFromJar() throws IOException { Mockito.when(mockProjectProperties.getClassFiles()) .thenReturn(ImmutableList.of(Paths.get("ignored"))); try { MainClassResolver.resolveMainClass(null, mockProjectProperties); Assert.fail(); } catch (MainClassInferenceException ex) { MatcherAssert.assertThat( ex.getMessage(), CoreMatchers.containsString("Main class was not found")); String info1 = "Searching for main class... Add a 'mainClass' configuration to 'jib-plugin' to " + "improve build speed."; String info2 = "Could not find a valid main class from jar-plugin; looking into all class files to " + "infer main class."; Mockito.verify(mockProjectProperties).log(LogEvent.info(info1)); Mockito.verify(mockProjectProperties).log(LogEvent.info(info2)); } }
public static KafkaRebalanceState rebalanceState(KafkaRebalanceStatus kafkaRebalanceStatus) { if (kafkaRebalanceStatus != null) { Condition rebalanceStateCondition = rebalanceStateCondition(kafkaRebalanceStatus); String statusString = rebalanceStateCondition != null ? rebalanceStateCondition.getType() : null; if (statusString != null) { return KafkaRebalanceState.valueOf(statusString); } } return null; }
@Test public void testNoConditions() { KafkaRebalanceStatus kafkaRebalanceStatus = new KafkaRebalanceStatusBuilder().build(); KafkaRebalanceState state = KafkaRebalanceUtils.rebalanceState(kafkaRebalanceStatus); assertThat(state, is(nullValue())); }
@VisibleForTesting RoleDO validateRoleForUpdate(Long id) { RoleDO role = roleMapper.selectById(id); if (role == null) { throw exception(ROLE_NOT_EXISTS); } // 内置角色,不允许删除 if (RoleTypeEnum.SYSTEM.getType().equals(role.getType())) { throw exception(ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE); } return role; }
@Test public void testValidateUpdateRole_systemRoleCanNotBeUpdate() { RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.SYSTEM.getType())); roleMapper.insert(roleDO); // 准备参数 Long id = roleDO.getId(); assertServiceException(() -> roleService.validateRoleForUpdate(id), ROLE_CAN_NOT_UPDATE_SYSTEM_TYPE_ROLE); }
@GetMapping("/vscode/gallery/publishers/{namespaceName}/vsextensions/{extensionName}/{version}/vspackage") @CrossOrigin public ModelAndView download( @PathVariable String namespaceName, @PathVariable String extensionName, @PathVariable String version, @RequestParam(defaultValue = TargetPlatform.NAME_UNIVERSAL) String targetPlatform, ModelMap model ) { for (var service : getVSCodeServices()) { try { var downloadUrl = service.download(namespaceName, extensionName, version, targetPlatform); return new ModelAndView("redirect:" + downloadUrl, model); } catch (NotFoundException exc) { // Try the next registry } } return new ModelAndView(null, HttpStatus.NOT_FOUND); }
@Test public void testDownload() throws Exception { mockExtensionVersion(); mockMvc.perform(get("/vscode/gallery/publishers/{namespace}/vsextensions/{extension}/{version}/vspackage", "redhat", "vscode-yaml", "0.5.2")) .andExpect(status().isFound()) .andExpect(header().string("Location", "http://localhost/vscode/asset/redhat/vscode-yaml/0.5.2/Microsoft.VisualStudio.Services.VSIXPackage")); }
public static boolean isNotBlank(String str) { return !isBlank(str); }
@Test public void testIsNotBlank() { Assert.assertFalse(StringUtil.isNotBlank("")); Assert.assertTrue(StringUtil.isNotBlank("\"###")); }
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } return rule.getInverted() ^ (msgVal < ruleVal); }
@Test public void testMissedMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); Message msg = getSampleMessage(); msg.addField("something", "27"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); }
@Override public boolean apply(Collection<Member> members) { if (members.size() < minimumClusterSize) { return false; } int count = 0; long timestamp = Clock.currentTimeMillis(); for (Member member : members) { if (!isAlivePerIcmp(member)) { continue; } if (member.localMember() || failureDetector.isAlive(member, timestamp)) { count++; } } return count >= minimumClusterSize; }
@Test public void testSplitBrainProtectionAbsent_whenHeartbeatsLate() throws Exception { // will do 5 heartbeats with 500msec interval starting from now long now = System.currentTimeMillis(); // initialize clock offset +1 minute --> last heartbeat received was too far in the past long clockOffset = 60000; initClockOffsetTest(clockOffset); createSplitBrainProtectionFunctionProxy(1000, 1000); heartbeat(now, 5, 500); assertFalse(splitBrainProtectionFunction.apply(Arrays.asList(members))); }
public final DisposableServer bindNow() { return bindNow(Duration.ofSeconds(45)); }
@Test void testBindTimeout() { assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> new TestServerTransport(Mono.never()).bindNow(Duration.ofMillis(1))); }
@GET @Produces(MediaType.APPLICATION_JSON) @Operation(summary = "Get prekey count", description = "Gets the number of one-time prekeys uploaded for this device and still available") @ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true) @ApiResponse(responseCode = "401", description = "Account authentication check failed.") public CompletableFuture<PreKeyCount> getStatus(@ReadOnly @Auth final AuthenticatedDevice auth, @QueryParam("identity") @DefaultValue("aci") final IdentityType identityType) { final CompletableFuture<Integer> ecCountFuture = keysManager.getEcCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId()); final CompletableFuture<Integer> pqCountFuture = keysManager.getPqCount(auth.getAccount().getIdentifier(identityType), auth.getAuthenticatedDevice().getId()); return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new); }
@Test void putKeysTestV2EmptySingleUseKeysList() { final ECSignedPreKey signedPreKey = KeysHelper.signedECPreKey(31338, AuthHelper.VALID_IDENTITY_KEY_PAIR); final SetKeysRequest setKeysRequest = new SetKeysRequest(List.of(), signedPreKey, List.of(), null); try (final Response response = resources.getJerseyTest() .target("/v2/keys") .request() .header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)) .put(Entity.entity(setKeysRequest, MediaType.APPLICATION_JSON_TYPE))) { assertThat(response.getStatus()).isEqualTo(204); verify(KEYS, never()).storeEcOneTimePreKeys(any(), anyByte(), any()); verify(KEYS, never()).storeKemOneTimePreKeys(any(), anyByte(), any()); verify(KEYS).storeEcSignedPreKeys(AuthHelper.VALID_UUID, AuthHelper.VALID_DEVICE.getId(), signedPreKey); } }
@Override protected int getJDBCPort() { return DEFAULT_ORACLE_INTERNAL_PORT; }
@Test public void testGetJDBCPortReturnsCorrectValue() { assertThat(testManager.getJDBCPort()).isEqualTo(DEFAULT_ORACLE_INTERNAL_PORT); }
@Override public Response toResponse(Throwable e) { if (log.isDebugEnabled()) { log.debug("Uncaught exception in REST call: ", e); } else if (log.isInfoEnabled()) { log.info("Uncaught exception in REST call: {}", e.getMessage()); } if (e instanceof NotFoundException) { return buildResponse(Response.Status.NOT_FOUND, e); } else if (e instanceof InvalidRequestException) { return buildResponse(Response.Status.BAD_REQUEST, e); } else if (e instanceof InvalidTypeIdException) { return buildResponse(Response.Status.NOT_IMPLEMENTED, e); } else if (e instanceof JsonMappingException) { return buildResponse(Response.Status.BAD_REQUEST, e); } else if (e instanceof ClassNotFoundException) { return buildResponse(Response.Status.NOT_IMPLEMENTED, e); } else if (e instanceof SerializationException) { return buildResponse(Response.Status.BAD_REQUEST, e); } else if (e instanceof RequestConflictException) { return buildResponse(Response.Status.CONFLICT, e); } else { return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, e); } }
@Test public void testToResponseUnknownException() { RestExceptionMapper mapper = new RestExceptionMapper(); Response resp = mapper.toResponse(new Exception("Unknown exception")); assertEquals(resp.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); }
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, List<String> subscribedTopicNames, String assignorName, List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions ) throws ApiException { final long currentTimeMs = time.milliseconds(); final List<CoordinatorRecord> records = new ArrayList<>(); // Get or create the consumer group. boolean createIfNotExists = memberEpoch == 0; final ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, createIfNotExists, records); throwIfConsumerGroupIsFull(group, memberId); // Get or create the member. if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString(); final ConsumerGroupMember member; if (instanceId == null) { member = getOrMaybeSubscribeDynamicConsumerGroupMember( group, memberId, memberEpoch, ownedTopicPartitions, createIfNotExists, false ); } else { member = getOrMaybeSubscribeStaticConsumerGroupMember( group, memberId, memberEpoch, instanceId, ownedTopicPartitions, createIfNotExists, false, records ); } // 1. Create or update the member. If the member is new or has changed, a ConsumerGroupMemberMetadataValue // record is written to the __consumer_offsets partition to persist the change. If the subscriptions have // changed, the subscription metadata is updated and persisted by writing a ConsumerGroupPartitionMetadataValue // record to the __consumer_offsets partition. Finally, the group epoch is bumped if the subscriptions have // changed, and persisted by writing a ConsumerGroupMetadataValue record to the partition. ConsumerGroupMember updatedMember = new ConsumerGroupMember.Builder(member) .maybeUpdateInstanceId(Optional.ofNullable(instanceId)) .maybeUpdateRackId(Optional.ofNullable(rackId)) .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs)) .maybeUpdateServerAssignorName(Optional.ofNullable(assignorName)) .maybeUpdateSubscribedTopicNames(Optional.ofNullable(subscribedTopicNames)) .setClientId(clientId) .setClientHost(clientHost) .setClassicMemberMetadata(null) .build(); boolean bumpGroupEpoch = hasMemberSubscriptionChanged( groupId, member, updatedMember, records ); int groupEpoch = group.groupEpoch(); Map<String, TopicMetadata> subscriptionMetadata = group.subscriptionMetadata(); Map<String, Integer> subscribedTopicNamesMap = group.subscribedTopicNames(); SubscriptionType subscriptionType = group.subscriptionType(); if (bumpGroupEpoch || group.hasMetadataExpired(currentTimeMs)) { // The subscription metadata is updated in two cases: // 1) The member has updated its subscriptions; // 2) The refresh deadline has been reached. subscribedTopicNamesMap = group.computeSubscribedTopicNames(member, updatedMember); subscriptionMetadata = group.computeSubscriptionMetadata( subscribedTopicNamesMap, metadataImage.topics(), metadataImage.cluster() ); int numMembers = group.numMembers(); if (!group.hasMember(updatedMember.memberId()) && !group.hasStaticMember(updatedMember.instanceId())) { numMembers++; } subscriptionType = ModernGroup.subscriptionType( subscribedTopicNamesMap, numMembers ); if (!subscriptionMetadata.equals(group.subscriptionMetadata())) { log.info("[GroupId {}] Computed new subscription metadata: {}.", groupId, subscriptionMetadata); bumpGroupEpoch = true; records.add(newConsumerGroupSubscriptionMetadataRecord(groupId, subscriptionMetadata)); } if (bumpGroupEpoch) { groupEpoch += 1; records.add(newConsumerGroupEpochRecord(groupId, groupEpoch)); log.info("[GroupId {}] Bumped group epoch to {}.", groupId, groupEpoch); metrics.record(CONSUMER_GROUP_REBALANCES_SENSOR_NAME); } group.setMetadataRefreshDeadline(currentTimeMs + consumerGroupMetadataRefreshIntervalMs, groupEpoch); } // 2. Update the target assignment if the group epoch is larger than the target assignment epoch. The delta between // the existing and the new target assignment is persisted to the partition. final int targetAssignmentEpoch; final Assignment targetAssignment; if (groupEpoch > group.assignmentEpoch()) { targetAssignment = updateTargetAssignment( group, groupEpoch, member, updatedMember, subscriptionMetadata, subscriptionType, records ); targetAssignmentEpoch = groupEpoch; } else { targetAssignmentEpoch = group.assignmentEpoch(); targetAssignment = group.targetAssignment(updatedMember.memberId(), updatedMember.instanceId()); } // 3. Reconcile the member's assignment with the target assignment if the member is not // fully reconciled yet. updatedMember = maybeReconcile( groupId, updatedMember, group::currentPartitionEpoch, targetAssignmentEpoch, targetAssignment, ownedTopicPartitions, records ); scheduleConsumerGroupSessionTimeout(groupId, memberId); // Prepare the response. ConsumerGroupHeartbeatResponseData response = new ConsumerGroupHeartbeatResponseData() .setMemberId(updatedMember.memberId()) .setMemberEpoch(updatedMember.memberEpoch()) .setHeartbeatIntervalMs(consumerGroupHeartbeatIntervalMs(groupId)); // The assignment is only provided in the following cases: // 1. The member sent a full request. It does so when joining or rejoining the group with zero // as the member epoch; or on any errors (e.g. timeout). We use all the non-optional fields // (rebalanceTimeoutMs, subscribedTopicNames and ownedTopicPartitions) to detect a full request // as those must be set in a full request. // 2. The member's assignment has been updated. boolean isFullRequest = memberEpoch == 0 || (rebalanceTimeoutMs != -1 && subscribedTopicNames != null && ownedTopicPartitions != null); if (isFullRequest || hasAssignedPartitionsChanged(member, updatedMember)) { response.setAssignment(createConsumerGroupResponseAssignment(updatedMember)); } return new CoordinatorResult<>(records, response); }
@Test public void testConsumerGroupHeartbeatFullResponse() { String groupId = "fooup"; String memberId = Uuid.randomUuid().toString(); Uuid fooTopicId = Uuid.randomUuid(); String fooTopicName = "foo"; // Create a context with an empty consumer group. MockPartitionAssignor assignor = new MockPartitionAssignor("range"); GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroupAssignors(Collections.singletonList(assignor)) .withMetadataImage(new MetadataImageBuilder() .addTopic(fooTopicId, fooTopicName, 2) .addRacks() .build()) .build(); // Prepare new assignment for the group. assignor.prepareGroupAssignment(new GroupAssignment( new HashMap<String, MemberAssignment>() { { put(memberId, new MemberAssignmentImpl(mkAssignment( mkTopicAssignment(fooTopicId, 0, 1) ))); } } )); CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> result; // A full response should be sent back on joining. result = context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId(groupId) .setMemberId(memberId) .setMemberEpoch(0) .setRebalanceTimeoutMs(5000) .setSubscribedTopicNames(Arrays.asList("foo", "bar")) .setServerAssignor("range") .setTopicPartitions(Collections.emptyList())); assertResponseEquals( new ConsumerGroupHeartbeatResponseData() .setMemberId(memberId) .setMemberEpoch(1) .setHeartbeatIntervalMs(5000) .setAssignment(new ConsumerGroupHeartbeatResponseData.Assignment() .setTopicPartitions(Collections.singletonList( new ConsumerGroupHeartbeatResponseData.TopicPartitions() .setTopicId(fooTopicId) .setPartitions(Arrays.asList(0, 1))))), result.response() ); // Otherwise, a partial response should be sent back. result = context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId(groupId) .setMemberId(memberId) .setMemberEpoch(result.response().memberEpoch())); assertResponseEquals( new ConsumerGroupHeartbeatResponseData() .setMemberId(memberId) .setMemberEpoch(1) .setHeartbeatIntervalMs(5000), result.response() ); // A full response should be sent back when the member sends // a full request again. result = context.consumerGroupHeartbeat( new ConsumerGroupHeartbeatRequestData() .setGroupId(groupId) .setMemberId(memberId) .setMemberEpoch(result.response().memberEpoch()) .setRebalanceTimeoutMs(5000) .setSubscribedTopicNames(Arrays.asList("foo", "bar")) .setServerAssignor("range") .setTopicPartitions(Collections.emptyList())); assertResponseEquals( new ConsumerGroupHeartbeatResponseData() .setMemberId(memberId) .setMemberEpoch(1) .setHeartbeatIntervalMs(5000) .setAssignment(new ConsumerGroupHeartbeatResponseData.Assignment() .setTopicPartitions(Collections.singletonList( new ConsumerGroupHeartbeatResponseData.TopicPartitions() .setTopicId(fooTopicId) .setPartitions(Arrays.asList(0, 1))))), result.response() ); }
@Override public FastAppend appendManifest(ManifestFile manifest) { Preconditions.checkArgument( !manifest.hasExistingFiles(), "Cannot append manifest with existing files"); Preconditions.checkArgument( !manifest.hasDeletedFiles(), "Cannot append manifest with deleted files"); Preconditions.checkArgument( manifest.snapshotId() == null || manifest.snapshotId() == -1, "Snapshot id must be assigned during commit"); Preconditions.checkArgument( manifest.sequenceNumber() == -1, "Sequence number must be assigned during commit"); if (canInheritSnapshotId() && manifest.snapshotId() == null) { summaryBuilder.addedManifest(manifest); appendManifests.add(manifest); } else { // the manifest must be rewritten with this update's snapshot ID ManifestFile copiedManifest = copyManifest(manifest); rewrittenAppendManifests.add(copiedManifest); } return this; }
@TestTemplate public void testInvalidAppendManifest() throws IOException { assertThat(listManifestFiles()).isEmpty(); TableMetadata base = readMetadata(); assertThat(base.currentSnapshot()).isNull(); ManifestFile manifestWithExistingFiles = writeManifest("manifest-file-1.avro", manifestEntry(Status.EXISTING, null, FILE_A)); assertThatThrownBy( () -> table.newFastAppend().appendManifest(manifestWithExistingFiles).commit()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot append manifest with existing files"); ManifestFile manifestWithDeletedFiles = writeManifest("manifest-file-2.avro", manifestEntry(Status.DELETED, null, FILE_A)); assertThatThrownBy( () -> table.newFastAppend().appendManifest(manifestWithDeletedFiles).commit()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot append manifest with deleted files"); }
public static List<Criterion> parse(String filter) { return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false) .map(FilterParser::parseCriterion) .toList(); }
@Test public void search_is_case_insensitive() { List<Criterion> criterion = FilterParser.parse("ncloc > 10 AnD coverage <= 80 AND debt = 10 AND issues = 20"); assertThat(criterion).hasSize(4); }
public static List<Field> getDeclaredFieldsIncludingInherited(Class<?> clazz) { List<Field> fields = new ArrayList<Field>(); while (clazz != null) { Field[] sortedFields = clazz.getDeclaredFields(); Arrays.sort(sortedFields, new Comparator<Field>() { public int compare(Field a, Field b) { return a.getName().compareTo(b.getName()); } }); for (Field field : sortedFields) { fields.add(field); } clazz = clazz.getSuperclass(); } return fields; }
@Test public void testGetDeclaredFieldsIncludingInherited() { Parent child = new Parent() { private int childField; @SuppressWarnings("unused") public int getChildField() { return childField; } }; List<Field> fields = ReflectionUtils.getDeclaredFieldsIncludingInherited( child.getClass()); boolean containsParentField = false; boolean containsChildField = false; for (Field field : fields) { if (field.getName().equals("parentField")) { containsParentField = true; } else if (field.getName().equals("childField")) { containsChildField = true; } } List<Method> methods = ReflectionUtils.getDeclaredMethodsIncludingInherited( child.getClass()); boolean containsParentMethod = false; boolean containsChildMethod = false; for (Method method : methods) { if (method.getName().equals("getParentField")) { containsParentMethod = true; } else if (method.getName().equals("getChildField")) { containsChildMethod = true; } } assertTrue("Missing parent field", containsParentField); assertTrue("Missing child field", containsChildField); assertTrue("Missing parent method", containsParentMethod); assertTrue("Missing child method", containsChildMethod); }
public String getExcludeName() { return excludeName; }
@Test public void getExcludeName() throws Exception { Assert.assertEquals(new ExcludeFilter("*").getExcludeName(), "*"); }
private boolean check(char exp) { return desc.charAt(pos) == exp; }
@Test public void testPrimitives() { check("()V", "V"); check("(I)D", "D", "I"); }
public static Optional<SchemaAndId> getLatestSchemaAndId( final SchemaRegistryClient srClient, final String topic, final boolean isKey ) { final String subject = KsqlConstants.getSRSubject(topic, isKey); return getLatestSchemaId(srClient, topic, isKey) .map(id -> { try { return new SchemaAndId(srClient.getSchemaById(id), id); } catch (final Exception e) { throwOnAuthError(e, subject); throw new KsqlException( "Could not get schema for subject " + subject + " and id " + id, e); } }); }
@Test public void shouldReturnParsedSchemaFromSubjectValue() throws Exception { // Given: when(schemaMetadata.getId()).thenReturn(123); when(schemaRegistryClient.getLatestSchemaMetadata("bar-value")) .thenReturn(schemaMetadata); when(schemaRegistryClient.getSchemaById(123)) .thenReturn(AVRO_SCHEMA); // When: final Optional<SchemaAndId> schemaAndId = SchemaRegistryUtil.getLatestSchemaAndId(schemaRegistryClient, "bar", false); // Then: assertThat(schemaAndId.get().getSchema(), equalTo(AVRO_SCHEMA)); }
@Override public void write(DataOutput out) throws IOException { super.write(out); jobId.write(out); WritableUtils.writeEnum(out, type); }
@Test public void testWrite() throws Exception { JobID jobId = new JobID("1234", 1); TaskID taskId = new TaskID(jobId, TaskType.JOB_SETUP, 0); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); taskId.write(out); DataInputByteBuffer in = new DataInputByteBuffer(); byte[] buffer = new byte[4]; in.reset(ByteBuffer.wrap(baos.toByteArray())); assertEquals("The write() method did not write the expected task ID", 0, in.readInt()); assertEquals("The write() method did not write the expected job ID", 1, in.readInt()); assertEquals("The write() method did not write the expected job " + "identifier length", 4, WritableUtils.readVInt(in)); in.readFully(buffer, 0, 4); assertEquals("The write() method did not write the expected job " + "identifier length", "1234", new String(buffer)); assertEquals("The write() method did not write the expected task type", TaskType.JOB_SETUP, WritableUtils.readEnum(in, TaskType.class)); }
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time zone is used when no time zone is explicitly provided." + " The format pattern should be in the format expected" + " by java.time.format.DateTimeFormatter") public String timestampToString( @UdfParameter( description = "Milliseconds since" + " January 1, 1970, 00:00:00 UTC/GMT.") final long epochMilli, @UdfParameter( description = "The format pattern should be in the format expected by" + " java.time.format.DateTimeFormatter.") final String formatPattern) { if (formatPattern == null) { return null; } try { final Timestamp timestamp = new Timestamp(epochMilli); final DateTimeFormatter formatter = formatters.get(formatPattern); return timestamp.toInstant() .atZone(ZoneId.systemDefault()) .format(formatter); } catch (final ExecutionException | RuntimeException e) { throw new KsqlFunctionException("Failed to format timestamp " + epochMilli + " with formatter '" + formatPattern + "': " + e.getMessage(), e); } }
@Test public void shouldBeThreadSafe() { IntStream.range(0, 10_000) .parallel() .forEach(idx -> { shouldConvertTimestampToString(); udf.timestampToString(1538361611123L, "yyyy-MM-dd HH:mm:ss.SSS"); }); }
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testDuplicateVcoresDefinitionPercentage() throws Exception { expectInvalidResourcePercentage("cpu"); parseResourceConfigValue("50% memory, 50% 100%cpu"); }
public void error( Throwable throwable ) { publishProcessor.onError( throwable ); }
@Test public void testError() { // verifies that calling .error() results in an exception being thrown // by the .rows() blocking iterable. final String exceptionMessage = "Exception raised during acceptRows loop"; streamSource = new BlockingQueueStreamSource<String>( streamStep ) { @Override public void open() { execSvc.submit( () -> { for ( int i = 0; i < 10; i++ ) { acceptRows( singletonList( "new row " + i ) ); try { Thread.sleep( 5 ); } catch ( InterruptedException e ) { fail(); } if ( i == 5 ) { error( new RuntimeException( exceptionMessage ) ); break; } } } ); } }; streamSource.open(); Iterator<String> iterator = streamSource.flowable().blockingIterable().iterator(); Future<List<String>> iterLoop = execSvc.submit( () -> { List<String> strings = new ArrayList<>(); do { strings.add( iterator.next() ); } while ( strings.size() < 9 ); return strings; } ); try { iterLoop.get( 50, MILLISECONDS ); fail( "expected exception" ); } catch ( InterruptedException | ExecutionException | TimeoutException e ) { // occasionally fails wingman with npe for mysterious reason, // so guarding with null check if ( e != null && e.getCause() != null ) { assertThat( e.getCause().getMessage(), equalTo( exceptionMessage ) ); } } }
public CaseInsensitiveString getDirectParentName() { String stringPath = path(); if (stringPath == null) { return null; } int index = stringPath.lastIndexOf(DELIMITER); return index == -1 ? path : new CaseInsensitiveString(stringPath.substring(index + 1)); }
@Test public void shouldUnderstandDirectParentName() { PathFromAncestor path = new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child")); assertThat(path.getDirectParentName(), is(new CaseInsensitiveString("child"))); }
public static WalletFile createLight(String password, ECKeyPair ecKeyPair) throws CipherException { return create(password, ecKeyPair, N_LIGHT, P_LIGHT); }
@Test public void testCreateLight() throws Exception { testCreate(Wallet.createLight(SampleKeys.PASSWORD, SampleKeys.KEY_PAIR)); }
public void insertPausedStepInstanceAttempt( Connection conn, String workflowId, long version, long instanceId, long runId, String stepId, long stepAttemptId) throws SQLException { try (PreparedStatement stmt = conn.prepareStatement(CREATE_PAUSED_STEP_INSTANCE_ATTEMPT)) { int idx = 0; stmt.setString(++idx, workflowId); stmt.setLong(++idx, version); stmt.setLong(++idx, instanceId); stmt.setLong(++idx, runId); stmt.setString(++idx, stepId); stmt.setLong(++idx, stepAttemptId); stmt.executeUpdate(); } }
@Test public void testInsertPausedStepInstanceAttempt() throws SQLException { when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd); String workflowId = wfd.getPropertiesSnapshot().getWorkflowId(); maestroStepBreakpointDao.insertPausedStepInstanceAttempt( conn, workflowId, TEST_WORKFLOW_VERSION1, TEST_WORKFLOW_INSTANCE1, TEST_WORKFLOW_RUN1, TEST_STEP_ID1, TEST_STEP_ATTEMPT1); conn.commit(); conn.close(); List<PausedStepAttempt> pausedStepAttempts = maestroStepBreakpointDao.getPausedStepAttempts( workflowId, TEST_WORKFLOW_VERSION1, TEST_WORKFLOW_INSTANCE1, TEST_WORKFLOW_RUN1, TEST_STEP_ID1, TEST_STEP_ATTEMPT1); assertEquals(1, pausedStepAttempts.size()); // Also test remove cycle when(workflowDao.getWorkflowDefinition(anyString(), anyString())).thenReturn(wfd); maestroStepBreakpointDao.addStepBreakpoint( workflowId, Constants.MATCH_ALL_WORKFLOW_VERSIONS, Constants.MATCH_ALL_WORKFLOW_INSTANCES, Constants.MATCH_ALL_RUNS, TEST_STEP_ID1, Constants.MATCH_ALL_STEP_ATTEMPTS, TEST_USER); int cnt = maestroStepBreakpointDao.removeStepBreakpoint( workflowId, Constants.MATCH_ALL_WORKFLOW_VERSIONS, Constants.MATCH_ALL_WORKFLOW_INSTANCES, Constants.MATCH_ALL_RUNS, TEST_STEP_ID1, Constants.MATCH_ALL_STEP_ATTEMPTS, false); assertEquals(0, cnt); maestroStepBreakpointDao.addStepBreakpoint( workflowId, Constants.MATCH_ALL_WORKFLOW_VERSIONS, Constants.MATCH_ALL_WORKFLOW_INSTANCES, Constants.MATCH_ALL_RUNS, TEST_STEP_ID1, Constants.MATCH_ALL_STEP_ATTEMPTS, TEST_USER); cnt = maestroStepBreakpointDao.removeStepBreakpoint( workflowId, Constants.MATCH_ALL_WORKFLOW_VERSIONS, Constants.MATCH_ALL_WORKFLOW_INSTANCES, Constants.MATCH_ALL_RUNS, TEST_STEP_ID1, Constants.MATCH_ALL_STEP_ATTEMPTS, true); assertEquals(1, cnt); pausedStepAttempts = maestroStepBreakpointDao.getPausedStepAttempts( workflowId, TEST_WORKFLOW_VERSION1, TEST_WORKFLOW_INSTANCE1, TEST_WORKFLOW_RUN1, TEST_STEP_ID1, TEST_STEP_ATTEMPT1); assertEquals(0, pausedStepAttempts.size()); }
public Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> newChannelInitializers() { Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> channelInitializers = new HashMap<>(); Set<InetSocketAddress> addresses = new HashSet<>(); for (Map.Entry<String, ProxyExtensionWithClassLoader> extension : extensions.entrySet()) { Map<InetSocketAddress, ChannelInitializer<SocketChannel>> initializers = extension.getValue().newChannelInitializers(); initializers.forEach((address, initializer) -> { if (!addresses.add(address)) { log.error("extension for `{}` attempts to use {} for its listening port." + " But it is already occupied by other extensions.", extension.getKey(), address); throw new RuntimeException("extension for `" + extension.getKey() + "` attempts to use " + address + " for its listening port. But it is" + " already occupied by other messaging extensions"); } endpoints.put(address, extension.getKey()); channelInitializers.put(extension.getKey(), initializers); }); } return channelInitializers; }
@Test(expectedExceptions = RuntimeException.class) public void testNewChannelInitializersOverlapped() { ChannelInitializer<SocketChannel> i1 = mock(ChannelInitializer.class); ChannelInitializer<SocketChannel> i2 = mock(ChannelInitializer.class); Map<InetSocketAddress, ChannelInitializer<SocketChannel>> p1Initializers = new HashMap<>(); p1Initializers.put(new InetSocketAddress("127.0.0.1", 6650), i1); p1Initializers.put(new InetSocketAddress("127.0.0.2", 6651), i2); ChannelInitializer<SocketChannel> i3 = mock(ChannelInitializer.class); ChannelInitializer<SocketChannel> i4 = mock(ChannelInitializer.class); Map<InetSocketAddress, ChannelInitializer<SocketChannel>> p2Initializers = new HashMap<>(); p2Initializers.put(new InetSocketAddress("127.0.0.1", 6650), i3); p2Initializers.put(new InetSocketAddress("127.0.0.4", 6651), i4); when(extension1.newChannelInitializers()).thenReturn(p1Initializers); when(extension2.newChannelInitializers()).thenReturn(p2Initializers); extensions.newChannelInitializers(); }
@Udf public <T extends Comparable<? super T>> T arrayMin(@UdfParameter( description = "Array of values from which to find the minimum") final List<T> input) { if (input == null) { return null; } T candidate = null; for (T thisVal : input) { if (thisVal != null) { if (candidate == null) { candidate = thisVal; } else if (thisVal.compareTo(candidate) < 0) { candidate = thisVal; } } } return candidate; }
@Test public void shouldFindDoubleMin() { final List<Double> input = Arrays.asList(Double.valueOf(1.1), Double.valueOf(3.1), Double.valueOf(-1.1)); assertThat(udf.arrayMin(input), is(Double.valueOf(-1.1))); }
@Override public int getOrder() { return PluginEnum.DIVIDE.getCode(); }
@Test public void getOrderTest() { assertEquals(PluginEnum.DIVIDE.getCode(), dividePlugin.getOrder()); }
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length) { return false; }
@Test void singleSmallGapRX() { final MultiGapLossGenerator generator = new MultiGapLossGenerator(0, 8, 4, 1); assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 0, 8)); assertTrue(generator.shouldDropFrame(null, null, 123, 456, 0, 8, 8)); assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 16, 8)); assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 8, 8)); }
public static Field p(String fieldName) { return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName); }
@Test void basic_group_syntax() { /* example from vespa document: https://docs.vespa.ai/en/grouping.html all( group(a) max(5) each(output(count()) all(max(1) each(output(summary()))) all(group(b) each(output(count()) all(max(1) each(output(summary()))) all(group(c) each(output(count()) all(max(1) each(output(summary())))))))) ); */ String q = Q.p("f1").contains("v1") .group( G.all(G.group("a"), G.maxRtn(5), G.each(G.output(G.count()), G.all(G.maxRtn(1), G.each(G.output(G.summary()))), G.all(G.group("b"), G.each(G.output(G.count()), G.all(G.maxRtn(1), G.each(G.output(G.summary()))), G.all(G.group("c"), G.each(G.output(G.count()), G.all(G.maxRtn(1), G.each(G.output(G.summary()))) )) )) )) ) .build(); assertEquals(q, "yql=select * from sources * where f1 contains \"v1\" | all(group(a) max(5) each(output(count()) all(max(1) each(output(summary()))) all(group(b) each(output(count()) all(max(1) each(output(summary()))) all(group(c) each(output(count()) all(max(1) each(output(summary())))))))))"); }
public String name() { return name; }
@Test void nameCannotBeNull() { Assertions.assertThrows(IllegalArgumentException.class, () -> DefaultBot.getDefaultBuilder().name(null).build()); }
public DropSourceCommand create(final DropStream statement) { return create( statement.getName(), statement.getIfExists(), statement.isDeleteTopic(), DataSourceType.KSTREAM ); }
@Test public void shouldFailDropSourceOnMissingSourceWithNoIfExistsForStream() { // Given: final DropStream dropStream = new DropStream(SOME_NAME, false, true); when(metaStore.getSource(SOME_NAME)).thenReturn(null); // When: final Exception e = assertThrows( KsqlException.class, () -> dropSourceFactory.create(dropStream) ); // Then: assertThat(e.getMessage(), containsString("Stream bob does not exist.")); }
@Override public String quoteIdentifier(String identifier) { if (identifier.contains(".")) { String[] parts = identifier.split("\\."); StringBuilder sb = new StringBuilder(); for (int i = 0; i < parts.length - 1; i++) { sb.append("\"").append(parts[i]).append("\"").append("."); } return sb.append("\"") .append(getFieldIde(parts[parts.length - 1], fieldIde)) .append("\"") .toString(); } return "\"" + getFieldIde(identifier, fieldIde) + "\""; }
@Test public void testIdentifierCaseSensitive() { DmdbDialectFactory factory = new DmdbDialectFactory(); JdbcDialect dialect = factory.create(); Assertions.assertEquals("\"test\"", dialect.quoteIdentifier("test")); Assertions.assertEquals("\"TEST\"", dialect.quoteIdentifier("TEST")); dialect = factory.create(null, FieldIdeEnum.ORIGINAL.getValue()); Assertions.assertEquals("\"test\"", dialect.quoteIdentifier("test")); Assertions.assertEquals("\"TEST\"", dialect.quoteIdentifier("TEST")); dialect = factory.create(null, FieldIdeEnum.LOWERCASE.getValue()); Assertions.assertEquals("\"test\"", dialect.quoteIdentifier("test")); Assertions.assertEquals("\"test\"", dialect.quoteIdentifier("TEST")); dialect = factory.create(null, FieldIdeEnum.UPPERCASE.getValue()); Assertions.assertEquals("\"TEST\"", dialect.quoteIdentifier("test")); Assertions.assertEquals("\"TEST\"", dialect.quoteIdentifier("TEST")); }
@Override public EntityStatementJWS establishIdpTrust(URI issuer) { var trustedFederationStatement = fetchTrustedFederationStatement(issuer); // the federation statement from the master will establish trust in the JWKS and the issuer URL // of the idp, // we still need to fetch the entity configuration directly afterward to get the full // entity statement return fetchTrustedEntityConfiguration(issuer, trustedFederationStatement.body().jwks()); }
@Test void establishTrust_configurationWithBadJwks() throws JOSEException { var client = new FederationMasterClientImpl(FEDERATION_MASTER, federationApiClient, clock); var issuer = URI.create("https://idp-tk.example.com"); var federationFetchUrl = FEDERATION_MASTER.resolve("/fetch"); var fedmasterKeypair = ECKeyGenerator.example(); var fedmasterEntityConfigurationJws = federationFetchFedmasterConfiguration(federationFetchUrl, fedmasterKeypair); var trustedSectoralIdpKeypair = new com.nimbusds.jose.jwk.gen.ECKeyGenerator(Curve.P_256).generate(); var trustedFederationStatement = trustedFederationStatement(issuer, trustedSectoralIdpKeypair, fedmasterKeypair); var untrustedSectoralIdpKeypair = new com.nimbusds.jose.jwk.gen.ECKeyGenerator(Curve.P_256).generate(); var sectoralEntityConfiguration = badSignedSectoralIdpEntityConfiguration( issuer, trustedSectoralIdpKeypair, untrustedSectoralIdpKeypair); when(federationApiClient.fetchEntityConfiguration(FEDERATION_MASTER)) .thenReturn(fedmasterEntityConfigurationJws); when(federationApiClient.fetchFederationStatement( federationFetchUrl, FEDERATION_MASTER.toString(), issuer.toString())) .thenReturn(trustedFederationStatement); when(federationApiClient.fetchEntityConfiguration(issuer)) .thenReturn(sectoralEntityConfiguration); // when var e = assertThrows(FederationException.class, () -> client.establishIdpTrust(issuer)); // then assertEquals("federation statement untrusted: sub=https://idp-tk.example.com", e.getMessage()); }
static Comparator<String> compareBySnapshot(Map<String, SnapshotDto> snapshotByProjectUuid) { return (uuid1, uuid2) -> { SnapshotDto snapshot1 = snapshotByProjectUuid.get(uuid1); SnapshotDto snapshot2 = snapshotByProjectUuid.get(uuid2); if (snapshot1 == null && snapshot2 == null) { return 0; } if (snapshot1 == null) { return 1; } if (snapshot2 == null) { return -1; } return snapshot2.getCreatedAt().compareTo(snapshot1.getCreatedAt()); }; }
@Test public void verify_comparator_transitivity() { Map<String, SnapshotDto> map = new HashMap<>(); map.put("A", new SnapshotDto().setCreatedAt(1L)); map.put("B", new SnapshotDto().setCreatedAt(2L)); map.put("C", new SnapshotDto().setCreatedAt(-1L)); List<String> uuids = new ArrayList<>(map.keySet()); uuids.add("D"); Comparators.verifyTransitivity(AsyncIssueIndexingImpl.compareBySnapshot(map), uuids); }
public List<String> toPrefix(String in) { List<String> tokens = buildTokens(alignINClause(in)); List<String> output = new ArrayList<>(); List<String> stack = new ArrayList<>(); for (String token : tokens) { if (isOperand(token)) { if (token.equals(")")) { while (openParanthesesFound(stack)) { output.add(stack.remove(stack.size() - 1)); } if (!stack.isEmpty()) { // temporarily fix for issue #189 stack.remove(stack.size() - 1); } } else { while (openParanthesesFound(stack) && !hasHigherPrecedence(token, stack.get(stack.size() - 1))) { output.add(stack.remove(stack.size() - 1)); } stack.add(token); } } else { output.add(token); } } while (!stack.isEmpty()) { output.add(stack.remove(stack.size() - 1)); } return output; }
@Test public void testNot() { String query = "a and not(b) OR c not in ( 4, 5, 6 )"; List<String> list = parser.toPrefix(query); assertEquals(Arrays.asList("a", "b", "not", "and", "c", "4,5,6", "in", "not", "OR"), list); }
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics, Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) { List<String> sortParameters = wsRequest.getSort(); if (sortParameters == null || sortParameters.isEmpty()) { return components; } boolean isAscending = wsRequest.getAsc(); Map<String, Ordering<ComponentDto>> orderingsBySortField = ImmutableMap.<String, Ordering<ComponentDto>>builder() .put(NAME_SORT, componentNameOrdering(isAscending)) .put(QUALIFIER_SORT, componentQualifierOrdering(isAscending)) .put(PATH_SORT, componentPathOrdering(isAscending)) .put(METRIC_SORT, metricValueOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric)) .put(METRIC_PERIOD_SORT, metricPeriodOrdering(wsRequest, metrics, measuresByComponentUuidAndMetric)) .build(); String firstSortParameter = sortParameters.get(0); Ordering<ComponentDto> primaryOrdering = orderingsBySortField.get(firstSortParameter); if (sortParameters.size() > 1) { for (int i = 1; i < sortParameters.size(); i++) { String secondarySortParameter = sortParameters.get(i); Ordering<ComponentDto> secondaryOrdering = orderingsBySortField.get(secondarySortParameter); primaryOrdering = primaryOrdering.compound(secondaryOrdering); } } primaryOrdering = primaryOrdering.compound(componentNameOrdering(true)); return primaryOrdering.immutableSortedCopy(components); }
@Test void sort_by_numerical_metric_key_descending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, NUM_METRIC_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure"); }
public static LeaseRenewer getInstance(final String authority, final UserGroupInformation ugi, final DFSClient dfsc) { final LeaseRenewer r = Factory.INSTANCE.get(authority, ugi); r.addClient(dfsc); return r; }
@Test public void testInstanceSharing() throws IOException { // Two lease renewers with the same UGI should return // the same instance LeaseRenewer lr = LeaseRenewer.getInstance( FAKE_AUTHORITY, FAKE_UGI_A, MOCK_DFSCLIENT); LeaseRenewer lr2 = LeaseRenewer.getInstance( FAKE_AUTHORITY, FAKE_UGI_A, MOCK_DFSCLIENT); Assert.assertSame(lr, lr2); // But a different UGI should return a different instance LeaseRenewer lr3 = LeaseRenewer.getInstance( FAKE_AUTHORITY, FAKE_UGI_B, MOCK_DFSCLIENT); Assert.assertNotSame(lr, lr3); // A different authority with same UGI should also be a different // instance. LeaseRenewer lr4 = LeaseRenewer.getInstance( "someOtherAuthority", FAKE_UGI_B, MOCK_DFSCLIENT); Assert.assertNotSame(lr, lr4); Assert.assertNotSame(lr3, lr4); }
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLComQuitPacket(); case COM_INIT_DB: return new MySQLComInitDbPacket(payload); case COM_FIELD_LIST: return new MySQLComFieldListPacket(payload); case COM_QUERY: return new MySQLComQueryPacket(payload); case COM_STMT_PREPARE: return new MySQLComStmtPreparePacket(payload); case COM_STMT_EXECUTE: MySQLServerPreparedStatement serverPreparedStatement = connectionSession.getServerPreparedStatementRegistry().getPreparedStatement(payload.getByteBuf().getIntLE(payload.getByteBuf().readerIndex())); return new MySQLComStmtExecutePacket(payload, serverPreparedStatement.getSqlStatementContext().getSqlStatement().getParameterCount()); case COM_STMT_SEND_LONG_DATA: return new MySQLComStmtSendLongDataPacket(payload); case COM_STMT_RESET: return new MySQLComStmtResetPacket(payload); case COM_STMT_CLOSE: return new MySQLComStmtClosePacket(payload); case COM_SET_OPTION: return new MySQLComSetOptionPacket(payload); case COM_PING: return new MySQLComPingPacket(); case COM_RESET_CONNECTION: return new MySQLComResetConnectionPacket(); default: return new MySQLUnsupportedCommandPacket(commandPacketType); } }
@Test void assertNewInstanceWithComShutDownPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_SHUTDOWN, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
public ProjectList getProjects(String serverUrl, String token) { HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/projects"); return doGet(token, url, body -> buildGson().fromJson(body, ProjectList.class)); }
@Test public void get_projects_failed() { server.enqueue(new MockResponse() .setBody(new Buffer().write(new byte[4096])) .setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY)); String serverUrl = server.url("/").toString(); assertThatThrownBy(() -> underTest.getProjects(serverUrl, "token")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to contact Bitbucket server"); assertThat(String.join(", ", logTester.logs())).contains("Unable to contact Bitbucket server"); }
public static BadRequestException appAlreadyExists(String appId) { return new BadRequestException("app already exists for appId:%s", appId); }
@Test public void testAppAlreadyExists(){ BadRequestException appAlreadyExists = BadRequestException.appAlreadyExists(appId); assertEquals("app already exists for appId:app-1001", appAlreadyExists.getMessage()); }
public static <T> T newInstance(ClassLoader classLoader, String name) { try { return ClassLoaderUtil.newInstance(classLoader, name); } catch (Exception e) { throw sneakyThrow(e); } }
@Test public void when_newInstance_then_returnsInstance() { // When OuterClass instance = ReflectionUtils.newInstance(OuterClass.class.getClassLoader(), OuterClass.class.getName()); // Then assertThat(instance).isNotNull(); }
public void stop() { if (!isRunning()) { return; } super.stop(); // At the end save cookies to the file specified in the order file. if (getCookieStore() != null) { AbstractCookieStore r = getCookieStore(); if (r.getCookiesSaveFile() != null) { r.saveCookies(r.getCookiesSaveFile().getFile().getAbsolutePath()); } getCookieStore().stop(); setCookieStore(null); } }
@Test public void testSocksProxy() throws Exception { // create a fetcher with socks enabled FetchHTTP socksFetcher = newSocksTestFetchHttp(getUserAgentString(), "localhost", 7800); CrawlURI curi = makeCrawlURI("http://localhost:7777/"); socksFetcher().process(curi); runDefaultChecks(curi); socksServer.stop(); }
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowReadwriteSplittingRulesStatement sqlStatement, final ContextManager contextManager) { Collection<LocalDataQueryResultRow> result = new LinkedList<>(); Map<String, Map<String, String>> exportableDataSourceMap = getExportableDataSourceMap(rule); ReadwriteSplittingRuleConfiguration ruleConfig = rule.getConfiguration(); ruleConfig.getDataSourceGroups().forEach(each -> { LocalDataQueryResultRow dataItem = buildDataItem(exportableDataSourceMap, each, getLoadBalancers(ruleConfig)); if (null == sqlStatement.getRuleName() || sqlStatement.getRuleName().equalsIgnoreCase(each.getName())) { result.add(dataItem); } }); return result; }
@Test void assertGetRowDataWithoutLoadBalancer() throws SQLException { engine = setUp(mock(ShowReadwriteSplittingRulesStatement.class), createRuleConfigurationWithoutLoadBalancer()); engine.executeQuery(); Collection<LocalDataQueryResultRow> actual = engine.getRows(); assertThat(actual.size(), is(1)); Iterator<LocalDataQueryResultRow> iterator = actual.iterator(); LocalDataQueryResultRow row = iterator.next(); assertThat(row.getCell(1), is("readwrite_ds")); assertThat(row.getCell(2), is("write_ds")); assertThat(row.getCell(3), is("read_ds_0,read_ds_1")); assertThat(row.getCell(4), is("DYNAMIC")); assertThat(row.getCell(5), is("")); assertThat(row.getCell(6), is("")); }
@Override public void update(Component component, Metric metric, Measure measure) { requireNonNull(component); checkValueTypeConsistency(metric, measure); Optional<Measure> existingMeasure = find(component, metric); if (!existingMeasure.isPresent()) { throw new UnsupportedOperationException( format( "a measure can be updated only if one already exists for a specific Component (key=%s), Metric (key=%s). Use add method", component.getKey(), metric.getKey())); } add(component, metric, measure, OverridePolicy.OVERRIDE); }
@Test public void update_throws_NPE_if_Component_measure_is_null() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null)) .isInstanceOf(NullPointerException.class); }
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider) throws OutsideScopeException { return resolveScopeFromLifecycle(provider, true); }
@Test public void lifecycleDefault_withStart_shouldFailIfEnded() { TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED); try { testSource(resolveScopeFromLifecycle(lifecycle)); throw new AssertionError("Lifecycle resolution should have failed due to it being ended."); } catch (LifecycleEndedException ignored) { } }
@Override public Http clone() throws CloneNotSupportedException { final Http config = new Http(); config.setPath(getPath()); config.setHeaders(getHeaders()); config.setExpectedResponseCode(getExpectedResponseCode()); return config; }
@Test void testClone() throws CloneNotSupportedException { Http cloned = http.clone(); assertEquals(http.hashCode(), cloned.hashCode()); assertEquals(http, cloned); }
@Override public void writeComment(String data) throws XMLStreamException { String filteredData = nonXmlCharFilterer.filter(data); writer.writeComment(filteredData); }
@Test public void testWriteComment() throws XMLStreamException { filteringXmlStreamWriter.writeComment("value"); verify(xmlStreamWriterMock).writeComment("filteredValue"); }
public static String humanReadableByteSize(long size) { String measure = "B"; if (size < 1024) { return size + " " + measure; } double number = size; if (number >= 1024) { number = number / 1024; measure = "KiB"; if (number >= 1024) { number = number / 1024; measure = "MiB"; if (number >= 1024) { number = number / 1024; measure = "GiB"; if (number >= 1024) { number = number / 1024; measure = "TiB"; } } } } DecimalFormat format = new DecimalFormat("#0.00"); return format.format(number) + " " + measure; }
@Test @Issue("JENKINS-16630") public void testHumanReadableFileSize() { Locale defaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.ENGLISH); assertEquals("0 B", Functions.humanReadableByteSize(0)); assertEquals("1023 B", Functions.humanReadableByteSize(1023)); assertEquals("1.00 KiB", Functions.humanReadableByteSize(1024)); assertEquals("1.50 KiB", Functions.humanReadableByteSize(1536)); assertEquals("20.00 KiB", Functions.humanReadableByteSize(20480)); assertEquals("1023.00 KiB", Functions.humanReadableByteSize(1047552)); assertEquals("1.00 MiB", Functions.humanReadableByteSize(1048576)); assertEquals("1.50 GiB", Functions.humanReadableByteSize(1610612700)); assertEquals("1.50 TiB", Functions.humanReadableByteSize(1649267441664L)); } finally { Locale.setDefault(defaultLocale); } }
@Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(task); }
@Test public void submit_runnable_with_result_delegates_to_executorService() { underTest.submit(SOME_RUNNABLE, SOME_STRING); inOrder.verify(executorService).submit(SOME_RUNNABLE, SOME_STRING); inOrder.verifyNoMoreInteractions(); }