focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) { checkNotNull(rekeyedProjects, "rekeyedProjects can't be null"); if (rekeyedProjects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProj...
@Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_calls_all_listeners_even_if_one_throws_an_Exception(Set<RekeyedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new RuntimeException("Faking listener2 throwing an exception")) ...
public static byte[] generateCallStubV(Class<?> clazz, Method method) { final AggBatchCallGenerator generator = new AggBatchCallGenerator(clazz, method); generator.declareCallStubClazz(); generator.genBatchUpdateSingle(); generator.finish(); return generator.getByteCode(); }
@Test public void testAggCallSingleStub() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { Class<?> clazz = IntSumfunc.class; final String genClassName = CallStubGenerator.CLAZZ_NAME.replace("/", "."); Method m = clazz.getM...
@Override public NodeLabelsInfo getClusterNodeLabels(HttpServletRequest hsr) throws IOException { try { long startTime = clock.getTime(); Collection<SubClusterInfo> subClustersActive = federationFacade.getActiveSubClusters(); final HttpServletRequest hsrCopy = clone(hsr); Class[] arg...
@Test public void testGetClusterNodeLabels() throws Exception { NodeLabelsInfo nodeLabelsInfo = interceptor.getClusterNodeLabels(null); Assert.assertNotNull(nodeLabelsInfo); Assert.assertEquals(2, nodeLabelsInfo.getNodeLabelsName().size()); List<String> nodeLabelsName = nodeLabelsInfo.getNodeLabelsNa...
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertEmptyObjectMessageToAmqpMessageUnknownEncodingGetsDataSection() throws Exception { ActiveMQObjectMessage outbound = createObjectMessage(); outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_UNKNOWN); outbound.onSend(); outbound.storeContent(); ...
@Override public String getName() { return ANALYZER_NAME; }
@Test public void testAnalyzePackageJson() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "ruby/vulnerable/gems/specifications/rest-client-1.7.2.gemspec")); analyzer.analyze(result, null); final String vendorString = resul...
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testFetchedRecordsAfterSeek() { buildFetcher(OffsetResetStrategy.NONE, new ByteArrayDeserializer(), new ByteArrayDeserializer(), 2, IsolationLevel.READ_UNCOMMITTED); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); assertTrue(sendFetches...
public static Model readPom(File file) throws AnalysisException { Model model = null; final PomParser parser = new PomParser(); try { model = parser.parse(file); } catch (PomParseException ex) { if (ex.getCause() instanceof SAXParseException) { try...
@Test public void testReadPom_should_trim_version() throws AnalysisException { File input = BaseTest.getResourceAsFile(this, "pom/pom-with-new-line.xml"); String expectedOutputVersion = "2.2.0"; Model output = PomUtils.readPom(input); assertEquals(expectedOutputVersion, output.getV...
public static Timer getTimer() { setup(); return sharedTimer; }
@Test public void timer() { java.util.Timer a = SharedExecutors.getTimer(); assertNotNull("Timer must not be null", a); java.util.Timer b = SharedExecutors.getTimer(); assertSame("factories should be same", a, b); }
public <U> Opt<U> mapOrElse(Function<? super T, ? extends U> mapper, VoidFunc0 emptyAction) { if (isPresent()) { return ofNullable(mapper.apply(value)); } else { emptyAction.callWithRuntimeException(); return empty(); } }
@Test public void mapOrElseTest() { // 如果值存在就转换为大写,否则打印一句字符串,支持链式调用、转换为其他类型 String hutool = Opt.ofBlankAble("hutool").mapOrElse(String::toUpperCase, () -> Console.log("yes")).mapOrElse(String::intern, () -> Console.log("Value is not present~")).get(); assertEquals("HUTOOL", hutool); }
@Override public void onMsg(TbContext ctx, TbMsg msg) { var tbMsg = ackIfNeeded(ctx, msg); withCallback(publishMessageAsync(ctx, tbMsg), m -> tellSuccess(ctx, m), t -> tellFailure(ctx, processException(tbMsg, t), t)); }
@Test void givenForceAckIsTrueAndMsgResultContainsBodyAndAttributesAndNumber_whenOnMsg_thenEnqueueForTellNext() { ReflectionTestUtils.setField(node, "forceAck", true); String messageBodyMd5 = "msgBodyMd5-55fb8ba2-2b71-4673-a82a-969756764761"; String messageAttributesMd5 = "msgAttrMd5-e3ba3ee...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testAdminNodeInfo() throws Exception { web3j.adminNodeInfo().send(); verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"admin_nodeInfo\",\"params\":[],\"id\":1}"); }
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Bandwidth) { return this.compareTo((Bandwidth) obj) == 0; } return false; }
@Test public void testEquals() { Bandwidth expected = Bandwidth.kbps(one); assertFalse(small.equals(big)); assertTrue(small.equals(expected)); assertTrue(small.equals(small)); assertFalse(small.equals(1000)); }
@Override public CounterSet getOutputCounters() { return counters; }
@Test @SuppressWarnings("unchecked") public void testGetOutputCounters() throws Exception { List<Operation> operations = Arrays.asList( new Operation[] { createOperation("o1", 1), createOperation("o2", 2), createOperation("o3", 3) }); ExecutionStateTracker stat...
@Override public String getName() { return "Zip"; }
@Test public void testGetName() { ZIPCompressionProvider provider = (ZIPCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME ); assertNotNull( provider ); assertEquals( PROVIDER_NAME, provider.getName() ); }
public boolean record(final Throwable observation) { final long timestampMs; DistinctObservation distinctObservation; timestampMs = clock.time(); synchronized (this) { distinctObservation = find(distinctObservations, observation); if (null == distinc...
@Test void shouldRecordTwoDistinctObservationsOnCause() { final long timestampOne = 7; final long timestampTwo = 10; final int offset = 0; when(clock.time()).thenReturn(timestampOne).thenReturn(timestampTwo); for (int i = 0; i < 2; i++) { assertTrue(...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer, final Merger<? super K, V> sessionMerger) { return aggregate(initializer, sessionMerger, Materialized.with(null, null)); }
@Test public void sessionWindowMixAggregatorsTest() { final KTable<Windowed<String>, String> customers = windowedCogroupedStream.aggregate( MockInitializer.STRING_INIT, sessionMerger, Materialized.with(Serdes.String(), Serdes.String())); customers.toStream().to(OUTPUT); try ...
protected String[] getRunCommand(String command, String groupId, String userName, Path pidFile, Configuration config) { return getRunCommand(command, groupId, userName, pidFile, config, null); }
@Test (timeout = 5000) public void testRunCommandNoPriority() throws Exception { Configuration conf = new Configuration(); String[] command = containerExecutor.getRunCommand("echo", "group1", "user", null, conf); assertTrue("first command should be the run command for the platform", comman...
@Override public void register(String path, ServiceRecord record) throws IOException { op(path, record, addRecordCommand); }
@Test public void testMultiARecord() throws Exception { ServiceRecord record = getMarshal().fromBytes("somepath", CONTAINER_RECORD.getBytes()); ServiceRecord record2 = getMarshal().fromBytes("somepath", CONTAINER_RECORD2.getBytes()); getRegistryDNS().register( "/registry/users/root...
void getGroupNames(SearchResult groupResult, Collection<String> groups, Collection<String> groupDNs, boolean doGetDNs) throws NamingException { Attribute groupName = groupResult.getAttributes().get(groupNameAttr); if (groupName == null) { throw new NamingException...
@Test public void testGetGroupsWithHierarchy() throws NamingException { // The search functionality of the mock context is reused, so we will // return the user NamingEnumeration first, and then the group // The parent search is run once for each level, and is a different search // The parent group is...
@Nullable ContainerPrices calculate(@Nullable Item[] items) { if (items == null) { return null; } long ge = 0; long alch = 0; for (final Item item : items) { final int qty = item.getQuantity(); final int id = item.getId(); if (id <= 0 || qty == 0) { continue; } alch += (long...
@Test public void testCalculate() { Item coins = new Item(ItemID.COINS_995, Integer.MAX_VALUE); Item whip = new Item(ItemID.ABYSSAL_WHIP, 1_000_000_000); Item[] items = ImmutableList.of( coins, whip ).toArray(new Item[0]); ItemComposition whipComp = mock(ItemComposition.class); when(whipComp.getH...
@Override public void close() { // Push queries can be closed by both terminate commands and the client ending the request, so // we ensure that there's no race and that close is called just once. if (!this.isRunning.compareAndSet(true, false)) { return; } // To avoid deadlock, close the que...
@Test public void shouldCloseQueueBeforeTopologyToAvoidDeadLock() { // Given: query.start(); // When: query.close(); // Then: final InOrder inOrder = inOrder(rowQueue, kafkaStreams); inOrder.verify(rowQueue).close(); inOrder.verify(kafkaStreams).close(any(java.time.Duration.class)); ...
public Object extract(Object target, String attributeName, Object metadata) { return extract(target, attributeName, metadata, true); }
@Test public void when_extractWithNullTarget_then_nullValue() { // WHEN Object power = createExtractors(null).extract(null, "gimmePower", null); // THEN assertNull(power); }
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { long start = System.currentTimeMillis(); Result result = invoker.invoke(invocation); long end = System.currentTimeMillis(); if (TRACERS.size() > 0) { String key = invoker.getIn...
@Test void testInvoke() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 2); Invoker<DemoService> mockInvoker = mock(Invoker.cl...
@Override public Optional<EfestoOutputPMML> evaluateInput(EfestoInputPMML toEvaluate, EfestoRuntimeContext context) { return executeEfestoInputPMML(toEvaluate, context); }
@Test void evaluateCorrectInput() { modelLocalUriId = getModelLocalUriIdFromPmmlIdFactory(FILE_NAME, MODEL_NAME); EfestoInputPMML inputPMML = new EfestoInputPMML(modelLocalUriId, getPMMLContext(FILE_NAME, MODEL_NAME, memo...
public static void maybeMeasureLatency(final Runnable actionToMeasure, final Time time, final Sensor sensor) { if (sensor.shouldRecord() && sensor.hasMetrics()) { final long startNs = time.nanoseconds(); ...
@Test public void shouldNotMeasureLatencyDueToRecordingLevel() { final Sensor sensor = mock(Sensor.class); when(sensor.shouldRecord()).thenReturn(false); final Time time = mock(Time.class); StreamsMetricsImpl.maybeMeasureLatency(() -> { }, time, sensor); }
@Override public long computeLocalQuota(long confUsage, long myUsage, long[] allUsages) throws PulsarAdminException { // ToDo: work out the initial conditions: we may allow a small number of "first few iterations" to go // unchecked as we get some history of usage, or follow some other "TBD" method....
@Test public void testRQCalcGlobUsedEqualsToConfigTest() throws PulsarAdminException { final long config = 100; final long localUsed = 20; final long[] allUsage = { 100 }; final long newQuota = this.rqCalc.computeLocalQuota(config, localUsed, allUsage); Assert.assertEquals(ne...
@Override public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp, final String srcUser) { ConfigInfoStateWrapper configInfo4BetaState = this.findConfigInfo4BetaState(configInfo.getDataId(), configInfo.getGroup(...
@Test void testInsertOrUpdateBetaOfUpdate() { String dataId = "betaDataId113"; String group = "group"; String tenant = "tenant"; //mock exist beta ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper(); mockedConfigInfoStateWrapper.setDataI...
public Properties getProperties() { return properties; }
@Test public void testUriWithCustomHeaders() throws SQLException, UnsupportedEncodingException { String customHeaders = "testHeaderKey:testHeaderValue"; String encodedCustomHeaders = URLEncoder.encode(customHeaders, StandardCharsets.UTF_8.toString()); PrestoDriverUri paramete...
@SuppressWarnings({"unchecked", "UnstableApiUsage"}) @Override public <T extends Statement> ConfiguredStatement<T> inject( final ConfiguredStatement<T> statement) { if (!(statement.getStatement() instanceof DropStatement)) { return statement; } final DropStatement dropStatement = (DropState...
@Test public void shouldDoNothingIfNoDeleteTopic() { // When: final ConfiguredStatement<DropStream> injected = deleteInjector.inject(DROP_WITHOUT_DELETE_TOPIC); // Then: assertThat(injected, is(sameInstance(DROP_WITHOUT_DELETE_TOPIC))); verifyNoMoreInteractions(topicClient, registryClient); }
public String getShare() { return share; }
@Test void shareForValidURIShouldBeExtracted2() { var remoteConf = context.getEndpoint("azure-files://account/share/", FilesEndpoint.class).getConfiguration(); assertEquals("share", remoteConf.getShare()); }
public static PDImageXObject createFromFileByContent(File file, PDDocument doc) throws IOException { FileType fileType = null; try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { fileType = FileTypeDetector.detectFileType(bufferedI...
@Test void testCreateFromFileByContent() throws IOException, URISyntaxException { testCompareCreateByContentWithCreatedByCCITTFactory("ccittg4.tif"); testCompareCreatedByContentWithCreatedByJPEGFactory("jpeg.jpg"); testCompareCreatedByContentWithCreatedByJPEGFactory("jpegcmyk.jpg"); ...
@Override public HttpResponse get() throws InterruptedException, ExecutionException { try { final Object result = process(0, null); if (result instanceof Throwable) { throw new ExecutionException((Throwable) result); } return (HttpResponse) res...
@Test(expected = ExecutionException.class) public void errGetThrowable() throws ExecutionException, InterruptedException, TimeoutException { get(new Exception("wrong"), false); }
public static URI parse(String featureIdentifier) { requireNonNull(featureIdentifier, "featureIdentifier may not be null"); if (featureIdentifier.isEmpty()) { throw new IllegalArgumentException("featureIdentifier may not be empty"); } // Legacy from the Cucumber Eclipse plug...
@Test void can_parse_classpath_directory_form() { URI uri = FeaturePath.parse("classpath:/path/to"); assertAll( () -> assertThat(uri.getScheme(), is("classpath")), () -> assertThat(uri.getSchemeSpecificPart(), is("/path/to"))); }
@Override public void getChildren(final String path, final boolean watch, final AsyncCallback.ChildrenCallback cb, final Object ctx) { if (!SymlinkUtil.containsSymlink(path)) { _zk.getChildren(path, watch, cb, ctx); } else { SymlinkChildrenCallback compositeCallback = new SymlinkChil...
@Test public void testSymlinkWithChildrenWatch() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.ChildrenCallback childrenCallback = new AsyncCallback.ChildrenCallback() { @Override ...
@Override public String format(final Schema schema) { final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema); return options.contains(Option.AS_COLUMN_LIST) ? stripTopLevelStruct(converted) : converted; }
@Test public void shouldFormatOptionalArray() { // Given: final Schema schema = SchemaBuilder .array(Schema.OPTIONAL_FLOAT64_SCHEMA) .optional() .build(); // Then: assertThat(DEFAULT.format(schema), is("ARRAY<DOUBLE>")); assertThat(STRICT.format(schema), is...
public Tenant addTenant(TenantName tenantName) { try (Lock lock = tenantLocks.lock(tenantName)) { writeTenantPath(tenantName); return createTenant(tenantName, clock.instant()); } }
@Test public void testAddTenant() throws Exception { Set<TenantName> allTenants = tenantRepository.getAllTenantNames(); assertTrue(allTenants.contains(tenant1)); assertTrue(allTenants.contains(tenant2)); tenantRepository.addTenant(tenant3); assertZooKeeperTenantPathExists(ten...
@Override public Optional<GeoLocationInformation> doGetGeoIpData(InetAddress address) { try (Timer.Context ignored = getTimer()) { final CityResponse response = getCityResponse(address); final Location location = response.getLocation(); final Country country = response.g...
@Test void testDoGetGeoIpData() throws IOException, GeoIp2Exception { Country country = createCountry(); City city = createCity(); Location location = createLocation(); CityResponse cityResponse = createCityResponse(country, city, location); when(resolver.getCityResponse(an...
public long maxSetBit() { ThreadSafeBitSetSegments segments = this.segments.get(); int segmentIdx = segments.numSegments() - 1; for(;segmentIdx >= 0; segmentIdx--) { AtomicLongArray segment = segments.getSegment(segmentIdx); for(int longIdx=segment.length() - 1; longIdx...
@Test public void testMaxSetBit() { ThreadSafeBitSet set1 = new ThreadSafeBitSet(); set1.set(100); Assert.assertEquals(100, set1.maxSetBit()); set1.set(100000); Assert.assertEquals(100000, set1.maxSetBit()); set1.set(1000000); Assert.assertEquals(1000000, s...
@Override public InterpreterResult interpret(String st, InterpreterContext context) { return helper.interpret(session, st, context); }
@Test void should_interpret_multiple_statements_with_single_line_logged_batch() { // Given String statements = "CREATE TABLE IF NOT EXISTS zeppelin.albums(\n" + " title text PRIMARY KEY,\n" + " artist text,\n" + " year int\n" + ");\n" + "BEGIN BATCH" + ...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testBagIsEmptyTrue() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); SettableFuture<Iterable<String>> future = SettableFuture.create(); when(mockReader.bagFuture(key(NAMESPACE, ...
@Override public void notify(BitList<Invoker<T>> invokers) { BitList<Invoker<T>> invokerList = invokers == null ? BitList.emptyList() : invokers; this.invokerList = invokerList.clone(); registerAppRule(invokerList); computeSubset(this.meshRuleCache.getAppToVDGroup()); }
@Test void testNotify() { StandardMeshRuleRouter<Object> meshRuleRouter = new StandardMeshRuleRouter<>(url); meshRuleRouter.notify(null); assertEquals(0, meshRuleRouter.getRemoteAppName().size()); BitList<Invoker<Object>> invokers = new BitList<>(Arrays.asList(create...
@Override public synchronized Request poll(Task task) { try (Jedis jedis = pool.getResource()) { String url = jedis.lpop(getQueueKey(task)); if (url == null) { return null; } String key = ITEM_PREFIX + task.getUUID(); String field = Diges...
@Ignore("environment depended") @Test public void test() { Task task = new Task() { @Override public String getUUID() { return "1"; } @Override public Site getSite() { return null; } }; ...
@Override @Deprecated public <VR> KStream<K, VR> transformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, ? extends VR> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransformerSup...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullStoreNamesOnTransformValuesWithValueTransformerSupplierWithNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.transformValues( valueTransf...
@Override public final void getSize(@NonNull SizeReadyCallback cb) { sizeDeterminer.getSize(cb); }
@Test public void testMatchParentWidthAndHeight() { LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); view.setLayoutParams(params); target.getSize(cb); verify(cb, never()).onSizeReady(anyInt(), anyInt()); activity.visible(); vi...
@Override public void commit() { if (context == null || context.isEmpty()) { return; } LOGGER.info("Commit started"); if (context.containsKey(UnitActions.INSERT.getActionValue())) { commitInsert(); } if (context.containsKey(UnitActions.MODIFY.getActionValue())) { commitModif...
@Test void shouldNotInsertToDbIfNoRegisteredStudentsToBeCommitted() { context.put(UnitActions.MODIFY.getActionValue(), List.of(weapon1)); context.put(UnitActions.DELETE.getActionValue(), List.of(weapon1)); armsDealer.commit(); verify(weaponDatabase, never()).insert(weapon1); }
@Deprecated // TODO: Remove when stanza builder is ready. public Body addBody(String language, String body) { language = Stanza.determineLanguage(this, language); removeBody(language); Body messageBody = new Body(language, body); addExtension(messageBody); return messag...
@Test(expected = NullPointerException.class) public void setNullMessageBodyTest() { StanzaBuilder.buildMessage() .addBody(null, null) .build(); }
@Override public void doLimitForModifyRequest(ModifyRequest modifyRequest) throws SQLException { if (null == modifyRequest || !enabledLimit) { return; } doLimit(modifyRequest.getSql()); }
@Test void testDoLimitForModifyRequestForDdl() throws SQLException { ModifyRequest createTable = new ModifyRequest("create table test(id int,name varchar(255))"); ModifyRequest createIndex = new ModifyRequest("create index test_index on test(id)"); ModifyRequest alterTable = new ModifyReques...
@Override public ResultSet getBestRowIdentifier(final String catalog, final String schema, final String table, final int scope, final boolean nullable) { return null; }
@Test void assertGetBestRowIdentifier() { assertNull(metaData.getBestRowIdentifier("", "", "", 0, false)); }
String formatStepText( String keyword, String stepText, Format textFormat, Format argFormat, List<Argument> arguments ) { int beginIndex = 0; StringBuilder result = new StringBuilder(textFormat.text(keyword)); for (Argument argument : arguments) { // can be null if th...
@Test void should_mark_subsequent_arguments_in_steps() { Formats formats = ansi(); StepTypeRegistry registry = new StepTypeRegistry(Locale.ENGLISH); StepExpressionFactory stepExpressionFactory = new StepExpressionFactory(registry, bus); StepDefinition stepDefinition = new StubStepDe...
public String getContent() { return content; }
@Test public void testCreateUDFWithContent() { String createFunctionSql = "CREATE FUNCTION echo(int) \n" + "RETURNS int \n" + "properties (\n" + " \"symbol\" = \"echo\",\n" + " \"type\" = \"Python\"\n" + ") AS $$ \n" ...
public static Set<Long> getLongSet(String property, JsonNode node) { Preconditions.checkArgument(node.has(property), "Cannot parse missing set: %s", property); return ImmutableSet.<Long>builder().addAll(new JsonLongArrayIterator(property, node)).build(); }
@Test public void getLongSet() throws JsonProcessingException { assertThatThrownBy(() -> JsonUtil.getLongSet("items", JsonUtil.mapper().readTree("{}"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot parse missing set: items"); assertThatThrownBy( () -> JsonUtil...
@Override public Acl getPermission(final Path file) throws BackgroundException { try { if(file.getType().contains(Path.Type.upload)) { // Incomplete multipart upload has no ACL set return Acl.EMPTY; } final Path bucket = containerService.ge...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet...
@Subscribe public void onVarbitChanged(VarbitChanged event) { if (event.getVarbitId() == Varbits.IN_RAID) { removeVarTimer(OVERLOAD_RAID); removeGameTimer(PRAYER_ENHANCE); } if (event.getVarbitId() == Varbits.VENGEANCE_COOLDOWN && config.showVengeance()) { if (event.getValue() == 1) { creat...
@Test public void testImbuedHeartStart() { when(timersAndBuffsConfig.showImbuedHeart()).thenReturn(true); VarbitChanged varbitChanged = new VarbitChanged(); varbitChanged.setVarbitId(Varbits.IMBUED_HEART_COOLDOWN); varbitChanged.setValue(70); timersAndBuffsPlugin.onVarbitChanged(varbitChanged); Argument...
public static Map<String, Object> getPropertiesWithPrefixForMap(Environment environment, String prefix) { return handleSpringBinder(environment, prefix, Map.class); }
@Test @SuppressWarnings("unchecked") void testGetPropertiesWithPrefixForMap() { Map<String, Object> actual = PropertiesUtil.getPropertiesWithPrefixForMap(environment, "nacos.prefix"); assertEquals(3, actual.size()); for (Map.Entry<String, Object> entry : actual.entrySet()) { ...
@Override public void startIt() { if (semaphore.tryAcquire()) { try { executorService.execute(this::doDatabaseMigration); } catch (RuntimeException e) { semaphore.release(); throw e; } } else { LOGGER.trace("{}: lock is already taken or process is already runnin...
@Test public void startit_calls_MigrationEngine_execute() { underTest.startIt(); inOrder.verify(migrationEngine).execute(any()); inOrder.verify(platform).doStart(); inOrder.verifyNoMoreInteractions(); }
public void record(long latencyNano, Consumer<AbstractHistogram> overflownConsumer) { recordSafeValue(narrow(latencyNano), overflownConsumer); }
@Test public void testOverflowRecording() { LatencyMetric metric = new LatencyMetric(); for (int j = 0; j < 3; j++) { GaussianResponseTimeDistribution distribution = new GaussianResponseTimeDistribution(0, j * 100, 10, TimeUnit.MILLISECONDS); AtomicReference<AbstractHistogram> hist...
public static synchronized void provideImpl(GooglePlayServicesUtilImpl impl) { googlePlayServicesUtilImpl = Preconditions.checkNotNull(impl); }
@Test public void provideImplementation_nullValueNotAllowed() { thrown.expect(NullPointerException.class); ShadowGooglePlayServicesUtil.provideImpl(null); }
@SuppressWarnings("unchecked") public T getValue() { final T value = (T) FROM_STRING.get(getConverterClass()).apply(JiveGlobals.getProperty(key), this); if (value == null || (Collection.class.isAssignableFrom(value.getClass()) && ((Collection) value).isEmpty())) { return defaultValue; ...
@Test public void willNotReturnAnotherClass() { final SystemProperty<Class> classProperty = SystemProperty.Builder.ofType(Class.class) .setKey("another-subclass-property") .setDefaultValue(DefaultAuthProvider.class) .setBaseClass(AuthProvider.class) .setDynam...
protected PaginatedList<DTO> findPaginatedWithQueryAndSort(Bson query, Bson sort, int page, int perPage) { try (final DBCursor<DTO> cursor = db.find(query) .sort(sort) .limit(perPage) .skip(perPage * Math.max(0, page - 1))) { final long grandTotal = db...
@Test public void findPaginatedWithQueryAndSort() { dbService.save(newDto("hello1")); dbService.save(newDto("hello2")); dbService.save(newDto("hello3")); dbService.save(newDto("hello4")); dbService.save(newDto("hello5")); final PaginatedList<TestDTO> page1 = dbServic...
@Override public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters, final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) { final long now = System.cur...
@Test public void reportsLongGaugeValues() throws Exception { reporter.report(map("gauge", gauge(1L)), this.map(), this.map(), this.map(), this.map()); final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class); Mockito.verify(influxDb, atLeastOnc...
public static Map<String, PartitionColumnFilter> convertColumnFilter(List<ScalarOperator> predicates) { return convertColumnFilter(predicates, null); }
@Test public void convertColumnFilterExprDateTruncContains() { OlapTable olapTable = buildOlapTable("month"); List<ScalarOperator> listDay = buildOperator("day", BinaryType.EQ); Map<String, PartitionColumnFilter> resultDay = ColumnFilterConverter.convertColumnFilter(listDay, olapTable); ...
@Override public List<Node> sniff(List<Node> nodes) { if (attribute == null || value == null) { return nodes; } return nodes.stream() .filter(node -> nodeMatchesFilter(node, attribute, value)) .collect(Collectors.toList()); }
@Test void doesNotFilterNodesIfNoFilterIsSet() throws Exception { final List<Node> nodes = mockNodes(); final NodesSniffer nodesSniffer = new FilteredElasticsearchNodesSniffer(null, null); assertThat(nodesSniffer.sniff(nodes)).isEqualTo(nodes); }
@Override public String normalise(String text) { if (Objects.isNull(text) || text.isEmpty()) { throw new IllegalArgumentException("Text cannot be null or empty"); } return text.trim() .toLowerCase() .replaceAll("\\p{Punct}", "") .replaceAll("\\s+", " "); }
@Description("Normalise, when text is mixed case, then return lowercased text") @Test void normalise_WhenTextIsMixedCase_ThenReturnLowercasedText() { // When var result = textNormaliser.normalise("HeLLo WoRLD"); // Then assertThat(result).isEqualTo("hello world"); }
public static List<ActiveMQDestination> convertToActiveMQDestination(Object value) { if (value == null) { return null; } // text must be enclosed with [] String text = value.toString(); if (text.startsWith("[") && text.endsWith("]")) { text = text.substr...
@Test public void testConvertToActiveMQDestination() { List<ActiveMQDestination> result = StringToListOfActiveMQDestinationConverter.convertToActiveMQDestination(""); assertNull(result); result = StringToListOfActiveMQDestinationConverter.convertToActiveMQDestination("[]"); assertN...
@Override public void discardState() throws Exception { final FileSystem fs = getFileSystem(); IOException actualException = null; boolean success = true; try { success = fs.delete(filePath, false); } catch (IOException e) { actualException = e; ...
@Test void testDisposeDoesNotDeleteParentDirectory() throws Exception { final Path p = resolve("path", "with", "parent"); final List<Path> pathsToDelete = new ArrayList<>(); initializeFileSystem( MockedLocalFileSystem.newBuilder() .setDeleteFunction( ...
public ConnectionDetails getConnectionDetails( IMetaStore metaStore, String key, String name ) { ConnectionProvider<? extends ConnectionDetails> connectionProvider = getConnectionProvider( key ); if ( connectionProvider != null ) { Class<? extends ConnectionDetails> clazz = connectionProvider.getClassType...
@Test public void testGetConnectionDetailsNull() { Assert.assertNull( connectionManager.getConnectionDetails( DOES_NOT_EXIST ) ); }
public RunResponse start( @NotNull String workflowId, @NotNull String version, @NotNull RunRequest runRequest) { WorkflowDefinition definition = workflowDao.getWorkflowDefinition(workflowId, version); validateRequest(version, definition, runRequest); RunProperties runProperties = RunProperti...
@Test public void testStartWithInvalidTriggers() { Stream.of(new SignalInitiator(), new TimeInitiator()) .forEach( initiator -> { RunRequest request = RunRequest.builder() .initiator(initiator) .currentPolicy(RunPolicy...
@Override protected String getNodeExplainString(String prefix, TExplainLevel detailLevel) { StringBuilder output = new StringBuilder(); output.append(prefix).append("TABLE: ").append(deltaLakeTable.getName()).append("\n"); if (null != sortColumn) { output.append(prefix).append(...
@Test public void testNodeExplain(@Mocked GlobalStateMgr globalStateMgr, @Mocked CatalogConnector connector, @Mocked DeltaLakeTable table) { String catalogName = "delta0"; CloudConfiguration cloudConfiguration = CloudConfigurationFactory. buildCloudConfigu...
public List<N> getNodesByResourceName(final String resourceName) { Preconditions.checkArgument( resourceName != null && !resourceName.isEmpty()); List<N> retNodes = new ArrayList<>(); if (ResourceRequest.ANY.equals(resourceName)) { retNodes.addAll(getAllNodes()); } else if (nodeNameToNodeM...
@Test public void testGetNodesForResourceName() throws Exception { addEight4x4Nodes(); assertEquals("Incorrect number of nodes matching ANY", 8, nodeTracker.getNodesByResourceName(ResourceRequest.ANY).size()); assertEquals("Incorrect number of nodes matching rack", 4, nodeTracker.getNodes...
public static <I> Builder<I> foreach(Iterable<I> items) { return new Builder<>(requireNonNull(items, "items")); }
@Test public void testFailSlowExceptions() throws Throwable { intercept(IOException.class, () -> builder() .run(failingTask)); failingTask.assertInvoked("continued through operations", ITEM_COUNT); items.forEach(Item::assertCommittedOrFailed); }
public static InetAddress fixScopeIdAndGetInetAddress(final InetAddress inetAddress) throws SocketException { if (!(inetAddress instanceof Inet6Address inet6Address)) { return inetAddress; } if (!inetAddress.isLinkLocalAddress() && !inetAddress.isSiteLocalAddress()) { re...
@Test public void testFixScopeIdAndGetInetAddress_whenLinkLocalAddress_withNoInterfaceBind() throws SocketException, UnknownHostException { Inet6Address inet6Address = createInet6AddressWithScope(SOME_LINK_LOCAL_ADDRESS, 0); assertThat(inet6Address.isLinkLocalAddress()).isTrue(); InetAddres...
public static <E> E findStaticFieldValue(Class clazz, String fieldName) { try { Field field = clazz.getField(fieldName); return (E) field.get(null); } catch (Exception ignore) { return null; } }
@Test public void test_whenFieldNotExist() { Object value = findStaticFieldValue(ClassWithStaticField.class, "nonexisting"); assertNull(value); }
@Override public Local create(final Path file) { return this.create(String.format("%s-%s", new AlphanumericRandomStringService().random(), file.getName())); }
@Test public void testTemporaryPath() { final Path file = new Path("/f1/f2/t.txt", EnumSet.of(Path.Type.file)); file.attributes().setDuplicate(true); file.attributes().setVersionId("1"); final Local local = new FlatTemporaryFileService().create(file); assertTrue(local.getPare...
@Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, MIN_PARAMETER_COUNT, MAX_PARAMETER_COUNT); values = parameters.toArray(new CompoundVariable[parameters.size()]); }
@Test void testDateConvertError() throws Exception { params.add(new CompoundVariable("2017-01-02")); params.add(new CompoundVariable("yyyy-MM-dd")); assertThrows( InvalidVariableException.class, () -> dateConvert.setParameters(params)); }
@GET @Path("{id}/stats") @Timed @ApiOperation(value = "Get index set statistics") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), @ApiResponse(code = 404, message = "Index set not found"), }) public IndexSetStats indexSetStatistics(@ApiParam(na...
@Test public void indexSetStatistics() { final IndexSet indexSet = mock(IndexSet.class); final IndexSetStats indexSetStats = IndexSetStats.create(5L, 23L, 42L); when(indexSetRegistry.get("id")).thenReturn(Optional.of(indexSet)); when(indexSetStatsCreator.getForIndexSet(indexSet)).th...
public static MatchesKV matchesKV(String regex, int keyGroup, int valueGroup) { return matchesKV(Pattern.compile(regex), keyGroup, valueGroup); }
@Test @Category(NeedsRunner.class) public void testKVMatchesNone() { PCollection<KV<String, String>> output = p.apply(Create.of("x y z")).apply(Regex.matchesKV("a (b) (c)", 1, 2)); PAssert.that(output).empty(); p.run(); }
public void appendDocument(PDDocument destination, PDDocument source) throws IOException { if (source.getDocument().isClosed()) { throw new IOException("Error: source PDF is closed."); } if (destination.getDocument().isClosed()) { throw new IOException...
@Test void testMissingParentTreeNextKey() throws IOException { PDFMergerUtility pdfMergerUtility = new PDFMergerUtility(); PDDocument src = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4418-000314.pdf")); PDDocument dst = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4418-000314.pdf"));...
public String toString() { verifyState(State.FINALIZED); return builder.toString(); }
@Test void testStructure() { HttpWriter writer = new HttpWriter(); String header = defaultHeader.replace(defaultTitle, "Untitled page"); assertEquals(header + defaultFooter, writer.toString()); }
public InputFileFilter[] getInputFileFilters() { return inputFileFilters; }
@Test public void should_return_filters_from_initialization() { InputFileFilterRepository underTest = new InputFileFilterRepository(f -> true); assertThat(underTest.getInputFileFilters()).isNotNull(); assertThat(underTest.getInputFileFilters()).hasSize(1); }
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final SelectionParameters other = (SelectionParamet...
@Test public void testAllEqual() { List<String> qualifyingNames = Arrays.asList( "language", "german" ); TypeMirror resultType = new TestTypeMirror( "resultType" ); List<TypeMirror> qualifiers = new ArrayList<>(); qualifiers.add( new TestTypeMirror( "org.mapstruct.test.SomeType" ) );...
@Override protected void setProperties(Map<String, String> properties) throws DdlException { Preconditions.checkState(properties != null); for (String key : properties.keySet()) { if (!DRIVER_URL.equals(key) && !URI.equals(key) && !USER.equals(key) && !PASSWORD.equals(key) ...
@Test(expected = DdlException.class) public void testWithoutDriverClass() throws Exception { Map<String, String> configs = getMockConfigs(); configs.remove(JDBCResource.DRIVER_CLASS); JDBCResource resource = new JDBCResource("jdbc_resource_test"); resource.setProperties(configs); ...
@Udf public <T> String join( @UdfParameter(description = "the array to join using the default delimiter '" + DEFAULT_DELIMITER + "'") final List<T> array ) { return join(array, DEFAULT_DELIMITER); }
@Test public void shouldReturnCorrectStringForFlatArraysWithPrimitiveTypes() { assertThat(arrayJoinUDF.join(Arrays.asList(true, null, false),""), is("truenullfalse") ); assertThat(arrayJoinUDF.join(Arrays.asList(true, null, false)), is("true,null,false") ); assertThat(arrayJoinUDF...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_screenSize_large() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("large", config); assertThat(config.screenLayout).isEqualTo(SCREENSIZE_LARGE); }
@Override public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException { String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX); if (null == prefix) { prefix = ""; } this.confTokenSecretKeySettingName = prefix + CONF_TOK...
@Test(expectedExceptions = IOException.class) public void testInitializeWhenSecretKeyFilePathIsInvalid() throws IOException { Properties properties = new Properties(); properties.setProperty(AuthenticationProviderToken.CONF_TOKEN_SECRET_KEY, "file://" + "invalid_secret_key_file"); ...
@Override public byte[] echo(byte[] message) { return read(null, ByteArrayCodec.INSTANCE, ECHO, message); }
@Test public void testEcho() { assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes()); }
@Override public String getQualifier() { if (isRoot()) { return Qualifiers.VIEW; } return Qualifiers.SUBVIEW; }
@Test void getQualifier_whenRoot_shouldReturnVW() { PortfolioDto dto = new PortfolioDto(); assertThat(dto.getQualifier()).isEqualTo(Qualifiers.VIEW); }
List<Condition> run(boolean useKRaft) { List<Condition> warnings = new ArrayList<>(); checkKafkaReplicationConfig(warnings); checkKafkaBrokersStorage(warnings); if (useKRaft) { // Additional checks done for KRaft clusters checkKRaftControllerStorage(warnings);...
@Test public void testMetadataVersionIsOlderThanKafkaVersion() { Kafka kafka = new KafkaBuilder(KAFKA) .editSpec() .editKafka() .withVersion(KafkaVersionTestUtils.LATEST_KAFKA_VERSION) .withMetadataVersion(KafkaVersionTestUt...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateTypeForUDF() { // Given: givenUdfWithNameAndReturnType("FLOOR", SqlTypes.DOUBLE); final Expression expression = new FunctionCall(FunctionName.of("FLOOR"), ImmutableList.of(COL3)); // When: final SqlType exprType = expressionTypeManager.getExpressionSqlType(...
@Override public <T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException { if (!asyncResult.isCompleted()) { asyncResult.await(); } return asyncResult.getValue(); }
@Test void testEndProcess() { assertTimeout(ofMillis(5000), () -> { // Instantiate a new executor and start a new 'null' task ... final var executor = new ThreadAsyncExecutor(); final var result = new Object(); when(task.call()).thenAnswer(i -> { Thread.sleep(1500); return...
public RemoteSourceStatsRule(FragmentStatsProvider fragmentStatsProvider, StatsNormalizer normalizer) { super(normalizer); this.fragmentStatsProvider = requireNonNull(fragmentStatsProvider, "metadata is null"); }
@Test public void testRemoteSourceStatsRule() { QueryId queryId = new QueryId("testqueryid"); Session session = testSessionBuilder() .setQueryId(queryId) .build(); LocalQueryRunner localQueryRunner = new LocalQueryRunner(session); StatsCalculatorTe...
@Override public PrimitiveTypeEncoding<UTF8Buffer> getEncoding(UTF8Buffer value) { return value.getLength() <= 255 ? smallBufferEncoding : largeBufferEncoding; }
@Test public void testGetEncodingForLargeUTF8Buffer() { PrimitiveTypeEncoding<UTF8Buffer> encoding = utf8BufferEncoding.getEncoding(largeBuffer); assertTrue(encoding instanceof UTF8BufferType.LargeUTF8BufferEncoding); assertEquals(1, encoding.getConstructorSize()); assertEquals(larg...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() != 2 && data.size() != 4) { onInvalidDataReceived(device, data); return; } final int sessionRunTime = data.getIntValue(Data.FORMAT_UINT16_LE, 0); ...
@Test public void onContinuousGlucoseMonitorSessionRunTimeReceived_noCrc() { final DataReceivedCallback callback = new CGMSessionRunTimeDataCallback() { @Override public void onContinuousGlucoseMonitorSessionRunTimeReceived(@NonNull final BluetoothDevice device, final int sessionRunTime, final boolean secured)...
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT." + " Single quotes in the timestamp format can be escaped with ''," + " for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time...
@Test public void shouldConvertStringToTimestamp() throws ParseException { // When: final Object result = udf.stringToTimestamp("2021-12-01 12:10:11.123", "yyyy-MM-dd HH:mm:ss.SSS"); // Then: final long expectedResult = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") .parse("2021-12-0...
public static <T> ParamWindowedValueCoder<T> getParamWindowedValueCoder(Coder<T> valueCoder) { return ParamWindowedValueCoder.of(valueCoder); }
@Test public void testParamWindowedValueCoderIsSerializableWithWellKnownCoderType() { CoderProperties.coderSerializable( WindowedValue.getParamWindowedValueCoder(GlobalWindow.Coder.INSTANCE)); }
@Override public void deleteCategory(Long id) { // 校验分类是否存在 validateProductCategoryExists(id); // 校验是否还有子分类 if (productCategoryMapper.selectCountByParentId(id) > 0) { throw exception(CATEGORY_EXISTS_CHILDREN); } // 校验分类是否绑定了 SPU Long spuCount = pro...
@Test public void testDeleteCategory_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> productCategoryService.deleteCategory(id), CATEGORY_NOT_EXISTS); }
public static String extractAppIdFromRoleName(String roleName) { Iterator<String> parts = STRING_SPLITTER.split(roleName).iterator(); if (parts.hasNext()) { String roleType = parts.next(); if (RoleType.isValidRoleType(roleType) && parts.hasNext()) { return parts.next(); } } ...
@Test public void testExtractAppIdFromRoleName() throws Exception { assertEquals("someApp", RoleUtils.extractAppIdFromRoleName("Master+someApp")); assertEquals("someApp", RoleUtils.extractAppIdFromRoleName("ModifyNamespace+someApp+xx")); assertEquals("app1", RoleUtils.extractAppIdFromRoleName("ReleaseName...
public static ManagedTransform write(String sink) { return new AutoValue_Managed_ManagedTransform.Builder() .setIdentifier( Preconditions.checkNotNull( WRITE_TRANSFORMS.get(sink.toLowerCase()), "An unsupported sink was specified: '%s'. Please specify one of the fo...
@Test public void testManagedTestProviderWithConfigFile() throws Exception { String yamlConfigPath = Paths.get(getClass().getClassLoader().getResource("test_config.yaml").toURI()) .toFile() .getAbsolutePath(); Managed.ManagedTransform writeOp = Managed.write(Managed.IC...
public static boolean isEmpty(Collection<?> col) { return !isNotEmpty(col); }
@Test public void testIsEmptyWithArrays() { String[] emptyArray = {}; String[] filledArray = {"Foo", "Bar"}; Assertions.assertTrue(CollectionUtils.isEmpty(emptyArray)); Assertions.assertFalse(CollectionUtils.isEmpty(filledArray)); }
public static <T> LengthPrefixCoder<T> of(Coder<T> valueCoder) { checkNotNull(valueCoder, "Coder not expected to be null"); return new LengthPrefixCoder<>(valueCoder); }
@Test public void testMultiCoderCycle() throws Exception { LengthPrefixCoder<Long> lengthPrefixedValueCoder = LengthPrefixCoder.of(BigEndianLongCoder.of()); LengthPrefixCoder<byte[]> lengthPrefixedBytesCoder = LengthPrefixCoder.of(ByteArrayCoder.of()); // [0x08, 0, 0, 0, 0, 0, 0, 0, 0x16] by...
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
@Test public void iterableContainsAtLeastWithMany() { assertThat(asList(1, 2, 3)).containsAtLeast(1, 2); }