focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void addHeatMapActivity(Class<?> activity) { }
@Test public void addHeatMapActivity() { mSensorsAPI.addHeatMapActivity(EmptyActivity.class); Assert.assertFalse(mSensorsAPI.isHeatMapActivity(EmptyActivity.class)); }
public String destinationURL(File rootPath, File file) { return destinationURL(rootPath, file, getSrc(), getDest()); }
@Test public void shouldProvideAppendFilePathToDestWhenUsingSingleStarToMatchFile() { ArtifactPlan artifactPlan = new ArtifactPlan(ArtifactPlanType.file, "test/a/b/*.log", "logs"); assertThat(artifactPlan.destinationURL(new File("pipelines/pipelineA"), new File("pipelines/pipelineA/test/...
public void clean(final Date now) { List<String> files = this.findFiles(); List<String> expiredFiles = this.filterFiles(files, this.createExpiredFileFilter(now)); for (String f : expiredFiles) { this.delete(new File(f)); } if (this.totalSizeCap != CoreConstants.UNBOUNDED_TOTAL_SIZE_CAP && thi...
@Test public void removesOnlyExpiredFiles() { remover.clean(EXPIRY); for (File f : expiredFiles) { verify(fileProvider).deleteFile(f); } for (File f : recentFiles) { verify(fileProvider, never()).deleteFile(f); } }
@Override public Iterator<LongStatistic> getLongStatistics() { return new LongStatisticIterator(stats.getData()); }
@Test public void testGetLongStatistics() { Iterator<LongStatistic> iter = storageStatistics.getLongStatistics(); while (iter.hasNext()) { final LongStatistic longStat = iter.next(); assertNotNull(longStat); final long expectedStat = getStatisticsValue(longStat.getName()); LOG.info("{}...
public static int getKeyMetaLen(int level) { Preconditions.checkArgument( level >= 0 && level < KEY_META_LEN_BY_LEVEL_ARRAY.length, "level " + level + " out of range [0, " + KEY_META_LEN_BY_LEVEL_ARRAY.length + ")"); return KEY_META_LEN_BY_LEVEL_ARRAY[level]; }
@Test void testKeySpacePutAndGet() { for (int level = 0; level <= MAX_LEVEL; level++) { int keyLen = ThreadLocalRandom.current().nextInt(100) + 1; KeySpace keySpace = createKeySpace(level, keyLen); int keyMetaLen = SkipListUtils.getKeyMetaLen(level); int total...
public static Iterator<Integer> lineOffsetIterator(String input) { return new LineOffsetIterator(input); }
@Test public void terminalOffset() { Iterator<Integer> it = Newlines.lineOffsetIterator("foo\nbar\n"); it.next(); it.next(); it.next(); try { it.next(); fail(); } catch (NoSuchElementException e) { // expected } it = Newlines.lineOffsetIterator("foo\nbar"); it.ne...
static <T> T copy(T object, DataComplexTable alreadyCopied) throws CloneNotSupportedException { if (object == null) { return null; } else if (isComplex(object)) { DataComplex src = (DataComplex) object; @SuppressWarnings("unchecked") T found = (T) alreadyCopied.get(src); ...
@Test public void testDeepCopy() throws CloneNotSupportedException { DataMap root = new DataMap(); DataMap a = new DataMap(); a.put("key", "a"); DataMap b = a.copy(); b.put("key", "b"); root.put("a", a); root.put("b", b); DataMap copy = root.copy(); assertEquals(root, copy); ...
CachedLayer writeCompressed(Blob compressedLayerBlob) throws IOException { // Creates the layers directory if it doesn't exist. Files.createDirectories(cacheStorageFiles.getLayersDirectory()); // Creates the temporary directory. Files.createDirectories(cacheStorageFiles.getTemporaryDirectory()); tr...
@Test public void testWriteCompressed() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); Blob compressedLayerBlob = compress(uncompressedLayerBlob); CachedLayer cachedLayer = cacheStorageWriter.writeCompressed(compressedLayerBlob); verifyCachedLayer(cachedLayer, ...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterSchedulerOverviewFifo() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("cluster") .path("scheduler-overview").accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(Medi...
public void execute() { Optional<String> login = configuration.get(CoreProperties.LOGIN); Optional<String> password = configuration.get(CoreProperties.PASSWORD); String warningMessage = null; if (password.isPresent()) { warningMessage = PASSWORD_WARN_MESSAGE; } else if (login.isPresent()) { ...
@Test public void execute_whenUsingLogin_shouldAddWarning() { settings.setProperty(CoreProperties.LOGIN, "test"); underTest.execute(); verify(analysisWarnings, times(1)).addUnique(LOGIN_WARN_MESSAGE); Assertions.assertThat(logger.logs(Level.WARN)).contains(LOGIN_WARN_MESSAGE); }
public Map<String, List<TopicPartitionInfo>> getTopicPartitionInfo(final Set<String> topics) { log.debug("Starting to describe topics {} in partition assignor.", topics); long currentWallClockMs = time.milliseconds(); final long deadlineMs = currentWallClockMs + retryTimeoutMs; final S...
@Test public void shouldThrowTimeoutExceptionIfGetPartitionInfoHasTopicDescriptionTimeout() { mockAdminClient.timeoutNextRequest(1); final InternalTopicManager internalTopicManager = new InternalTopicManager(time, mockAdminClient, new StreamsConfig(config)); try { ...
public static boolean getBooleanValue(String key, boolean defaultValue) { return getBooleanValue(null, key, defaultValue); }
@Test public void getBooleanValue() throws Exception { }
@VisibleForTesting void validateMenu(Long parentId, String name, Long id) { MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name); if (menu == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的菜单 if (id == null) { throw exception(MENU_NAME_DUPLI...
@Test public void testValidateMenu_sonMenuNameDuplicate() { // mock 父子菜单 MenuDO sonMenu = createParentAndSonMenu(); // 准备参数 Long parentId = sonMenu.getParentId(); Long otherSonMenuId = randomLongId(); String otherSonMenuName = sonMenu.getName(); //相同名称 // 调用,...
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldReturnedSessionWindowedSerdeForSessionWindowed() { // When: final Serde<Windowed<GenericKey>> result = factory .create(format, SESSION_WND, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.empty()); // Then: assertThat(...
public static <T> T clone(T value) { return ObjectMapperWrapper.INSTANCE.clone(value); }
@Test public void cloneDeserializeStepErrorTest() { MyEntity entity = new MyEntity(); entity.setValue("some value"); entity.setPojos(Arrays.asList( createMyPojo("first value", MyType.A, "1.1", createOtherPojo("USD")), createMyPojo("second value", MyType.B, "1...
@Override public void register(@NonNull ThreadPoolPlugin plugin) { mainLock.runWithWriteLock(() -> { String id = plugin.getId(); Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered"); registeredPlugins.put(id, plugin); forQuic...
@Test public void testRegister() { manager.register(new TestShutdownAwarePlugin()); Assert.assertEquals(1, manager.getAllPlugins().size()); }
@Override public Type classify(final Throwable e) { Type type = Type.UNKNOWN; if (e instanceof KsqlFunctionException || (e instanceof StreamsException && ExceptionUtils.getRootCause(e) instanceof KsqlFunctionException)) { type = Type.USER; } if (type == Type.USER) { LOG.in...
@Test public void shouldClassifyWrappedStreamsExceptionWithoutKsqlFunctionExceptionAsUnknownError() { // Given: final Exception e = new StreamsException(new ArithmeticException()); // When: final Type type = new KsqlFunctionClassifier("").classify(e); // Then: assertThat(type, is(Type.UNKNOW...
KubernetesApiProvider buildKubernetesApiUrlProvider() { try { String endpointSlicesUrlString = String.format("%s/apis/discovery.k8s.io/v1/namespaces/%s/endpointslices", kubernetesMaster, namespace); callGet(endpointSlicesUrlString); LOGGER.finest("Using En...
@Test public void buildKubernetesApiUrlProviderReturnsEndpointProvider() { //language=JSON String endpointSlicesResponse = """ { "kind": "Status", "apiVersion": "v1", "metadata": { \s }, ...
public ClassInfo get(Class<?> clz) { return get(clz.getClassLoader(), clz.getName()); }
@Test void getClazz() { ClassInfo ci = instance.get(String.class); assertNotNull(ci); ClassInfo ci1 = instance.get(String.class); assertEquals(ci1, ci); }
@Override public SarifImportResults importSarif(SarifSchema210 sarif210) { int successFullyImportedIssues = 0; int successFullyImportedRuns = 0; int failedRuns = 0; List<Run> runs = requireNonNull(sarif210.getRuns(), "The runs section of the Sarif report is null"); for (Run run : runs) { Ru...
@Test public void importSarif_shouldDelegateRunMapping_toRunMapper() { SarifSchema210 sarif210 = mock(SarifSchema210.class); Run run1 = mock(Run.class); Run run2 = mock(Run.class); when(sarif210.getRuns()).thenReturn(List.of(run1, run2)); NewExternalIssue issue1run1 = mock(NewExternalIssue.class...
@Override public void debug(String msg) { logger.debug(msg); }
@Test void testDebugWithFormat3() { jobRunrDashboardLogger.debug("Debug with {} {} {}", "format1", "format2", "format3"); verify(slfLogger).debug("Debug with {} {} {}", "format1", "format2", "format3"); }
@Override protected HttpApiSpecificInfo doParse(final ApiBean.ApiDefinition apiDefinition) { String produce = ShenyuClientConstants.MEDIA_TYPE_ALL_VALUE; String consume = ShenyuClientConstants.MEDIA_TYPE_ALL_VALUE; List<ApiHttpMethodEnum> apiHttpMethodEnums = Lists.newArrayList(ApiHttpMet...
@Test public void testDoParse() { final TestApiBeanAnnotatedClassAndMethod bean = new TestApiBeanAnnotatedClassAndMethod(); ApiBean apiBean = new ApiBean(RpcTypeEnum.HTTP.getName(), "bean", bean); apiBean.addApiDefinition(null, null); AbstractApiDocRegistra...
public static void deleteIfExists(final File file) { try { Files.deleteIfExists(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } }
@Test void deleteIfExistsErrorHandlerNonExistingFile() { final ErrorHandler errorHandler = mock(ErrorHandler.class); final Path file = tempDir.resolve("non-existing.txt"); IoUtil.deleteIfExists(file.toFile(), errorHandler); assertFalse(Files.exists(file)); verifyNoInter...
public static HttpHeaders parseFromString(String headersString) { HttpHeaders headers = new HttpHeaders(headersString); if (StringUtils.isNotEmpty(headersString)) { try (BufferedReader reader = new BufferedReader(new StringReader(headersString))) { String line = reader.readL...
@Test void parseFromInvalidStringHeader() { assertThatThrownBy(() -> HttpHeaders.parseFromString("Content-Type")) .isInstanceOf(FlowableIllegalArgumentException.class) .hasMessage("Header line 'Content-Type' is invalid"); }
private EidStatInfoBuilder() { }
@Test public void eidstatinfoBuilder_validParameters_infoCorrect() throws SoapValidationException { EIDSTATINFO result = eidStatInfoBuilder.eidstatinfoBuilder("PPPPPPPPP", "PPPPPPPPPPPP"); assertEquals("PPPPPPPPP", result.getEIDSTATAGEG().getBURGSERVNRA().toString()); assertEquals("PPPPPPPP...
public static <E> E checkInstanceOf(Class<E> type, Object object, String errorMessage) { isNotNull(type, "type"); if (!type.isInstance(object)) { throw new IllegalArgumentException(errorMessage); } return (E) object; }
@Test(expected = IllegalArgumentException.class) public void test_checkInstanceOf_whenSuppliedObjectIsNotInstanceOfExpectedType() { checkInstanceOf(Integer.class, BigInteger.ONE, "argumentName"); }
@Override public Type type() { return Type.ACTION_PROFILE_GROUP_ID; }
@Test public void testMethods() { assertThat(piActionGroupId1, is(notNullValue())); assertThat(piActionGroupId1.type(), is(PiTableAction.Type.ACTION_PROFILE_GROUP_ID)); assertThat(piActionGroupId1.id(), is(10)); }
public int compare(Logger l1, Logger l2) { if (l1.getName().equals(l2.getName())) { return 0; } if (l1.getName().equals(Logger.ROOT_LOGGER_NAME)) { return -1; } if (l2.getName().equals(Logger.ROOT_LOGGER_NAME)) { return 1; } ret...
@Test public void testSmoke() { assertEquals(0, comparator.compare(a, a)); assertEquals(-1, comparator.compare(a, b)); assertEquals(1, comparator.compare(b, a)); assertEquals(-1, comparator.compare(root, a)); // following two tests failed before bug #127 was fixed ass...
public boolean isDisableOptionalRecord() { return disableOptionalRecord; }
@Test void disableOptionalRecord() { assertThat(builder.build().isDisableOptionalRecord()).isFalse(); builder.disableOptionalRecord(true); assertThat(builder.build().isDisableOptionalRecord()).isTrue(); }
@Override public Object convertDataUsingConversionMetaData( Object data ) throws KettleValueException { if ( conversionMetadata == null ) { throw new KettleValueException( "API coding error: please specify the conversion metadata before attempting to convert value " + name ); } // Suppose...
@Test public void testConvertDataUsingConversionMetaData() throws KettleValueException, ParseException { ValueMetaString base = new ValueMetaString(); double DELTA = 1e-15; base.setConversionMetadata( new ValueMetaString( "STRING" ) ); Object defaultStringData = "STRING DATA"; String convertedStr...
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException { if ( dbMetaData == null ) { throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" )...
@Test( expected = KettleDatabaseException.class ) public void testGetLegacyColumnNameDatabaseException() throws Exception { new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), getResultSetMetaDataException(), 1 ); }
public CompletionStage<E> add(CompletionStage<E> future) throws InterruptedException { checkNotNull(future, "future can't be null"); this.thread = Thread.currentThread(); down(); futures.add(future); future.whenCompleteAsync((response, t) -> up(), CALLER_RUNS); return fu...
@Test public void testInterrupt() throws Exception { final Pipelining<String> pipelining = new Pipelining<>(1); pipelining.add(mock(CompletionStage.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining....
@Override public void commitOffset(Offset offset) { if (!committer.isRunning()) { throw new IllegalStateException( "Committer not running when commitOffset called.", committer.failureCause()); } try { committer.commitOffset(offset).get(1, TimeUnit.MINUTES); } catch (Exception e) ...
@Test public void commit() { doReturn(ApiFutures.immediateFuture(null)).when(fakeCommitter).commitOffset(Offset.of(42)); committer.commitOffset(Offset.of(42)); }
@Override public Long clusterCountKeysInSlot(int slot) { RedisClusterNode node = clusterGetNodeForSlot(slot); MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort())); RFuture<Long> f = executorService.readAsync(entry, St...
@Test public void testClusterCountKeysInSlot() { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }
public static Criterion matchMplsLabel(MplsLabel mplsLabel) { return new MplsCriterion(mplsLabel); }
@Test public void testMatchMplsLabelMethod() { Criterion matchMplsLabel = Criteria.matchMplsLabel(mpls1); MplsCriterion mplsCriterion = checkAndConvert(matchMplsLabel, Criterion.Type.MPLS_LABEL, MplsCriterion.class); ...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); final Integer offset = readTimeZone(data, 0); if (offset == null) { onInvalidDataReceived(device, data); return; } if (offset == -128) { onUnknownTimeZoneRece...
@Test public void onTimeZoneReceived_unknown() { final Data data = new Data(new byte[] { -128 }); callback.onDataReceived(null, data); assertTrue(unknownTimeZone); }
@Override public Object evaluate(EvaluationContext ctx) { try { ctx.enterFrame(); List<Object> toReturn = new ArrayList<>(); ctx.setValue("partial", toReturn); populateToReturn(0, ctx, toReturn); LOG.trace("returning {}", toReturn); ret...
@Test void evaluateNestedArray() { Map<String, List<String>> firstIterationContext = new LinkedHashMap<>(); firstIterationContext.put("1, 2", Arrays.asList("1", "2")); firstIterationContext.put("3, 4", Arrays.asList("3", "4")); IterationContextNode x = getIterationContextNode("x", ge...
@Override public NotifyTemplateDO getNotifyTemplate(Long id) { return notifyTemplateMapper.selectById(id); }
@Test public void testGetNotifyTemplate() { // mock 数据 NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); notifyTemplateMapper.insert(dbNotifyTemplate); // 准备参数 Long id = dbNotifyTemplate.getId(); // 调用 NotifyTemplateDO notifyTemplate = n...
static boolean unprotectedSetTimes( FSDirectory fsd, INodesInPath iip, long mtime, long atime, boolean force) throws FileNotFoundException { assert fsd.hasWriteLock(); boolean status = false; INode inode = iip.getLastINode(); if (inode == null) { throw new FileNotFoundException("File/D...
@Test public void testUnprotectedSetTimes() throws Exception { // atime < access time + precision assertFalse("SetTimes should not update access time " + "because it's within the last precision interval", unprotectedSetTimes(100, 0, 1000, -1, false)); // atime = access time + precision ...
public static void checkParam(String dataId, String group, String content) throws NacosException { checkKeyParam(dataId, group); if (StringUtils.isBlank(content)) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, CONTENT_INVALID_MSG); } }
@Test void testCheckParamFail() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { String dataId = "b"; String group = "c"; String content = ""; ParamUtils.checkParam(dataId, group, content); }); ...
public boolean evaluate( RowMetaInterface rowMeta, Object[] r ) { // Start of evaluate boolean retval = false; // If we have 0 items in the list, evaluate the current condition // Otherwise, evaluate all sub-conditions // try { if ( isAtomic() ) { if ( function == FUNC_TRUE ) { ...
@Test public void testZeroLargerThanNull() { String left = "left"; String right = "right"; Long leftValue = 0L; Long rightValue = null; RowMetaInterface rowMeta = new RowMeta(); rowMeta.addValueMeta( new ValueMetaInteger( left ) ); rowMeta.addValueMeta( new ValueMetaInteger( right ) ); ...
@Override public long extractWatermark(IcebergSourceSplit split) { return split.task().files().stream() .map( scanTask -> { Preconditions.checkArgument( scanTask.file().lowerBounds() != null && scanTask.file().lowerBounds().get(eventTimeFie...
@TestTemplate public void testTimeUnit() throws IOException { assumeThat(columnName).isEqualTo("long_column"); ColumnStatsWatermarkExtractor extractor = new ColumnStatsWatermarkExtractor(SCHEMA, columnName, TimeUnit.MICROSECONDS); assertThat(extractor.extractWatermark(split(0))) .isEqualT...
@Override public Result invoke(Invocation invocation) throws RpcException { Result result; String value = getUrl().getMethodParameter( RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()) .trim(); if (ConfigUtils.isEmpty(value)) { ...
@Test void testMockInvokerInvoke_forcemock_defaultreturn() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); Invoker<IHelloS...
@Modified public void modified(ComponentContext context) { if (context == null) { log.info("No component configuration"); return; } else { Dictionary<?, ?> properties = context.getProperties(); int newPollFrequency = getNewPollFrequency(properties, li...
@Test @Ignore("FIXME: fails intermittently; suspecting insufficient time and race condition") public void linksTestForStoredDevice() { provider.modified(CONTEXT); providerService.discoveredLinkDescriptions().put(LINKKEY1, LINK1); providerService.discoveredLinkDescriptions().put(LINKKEY2,...
static Set<Dependency> tryCreateFromField(JavaField field) { return tryCreateDependency(field, "has type", field.getRawType()); }
@Test @UseDataProvider("field_array_types") public void Dependencies_from_field_with_component_type(Field reflectionArrayField) { Class<?> reflectionDeclaringClass = reflectionArrayField.getDeclaringClass(); JavaField field = new ClassFileImporter().importClasses(reflectionDeclaringClass).get(re...
public static <E> List<E> executePaginatedRequest(String request, OAuth20Service scribe, OAuth2AccessToken accessToken, Function<String, List<E>> function) { List<E> result = new ArrayList<>(); readPage(result, scribe, accessToken, addPerPageQueryParameter(request, DEFAULT_PAGE_SIZE), function); return resu...
@Test public void execute_paginated_request_with_query_parameter() throws InterruptedException { mockWebServer.enqueue(new MockResponse() .setHeader("Link", "<" + serverUrl + "/test?param=value&per_page=100&page=2>; rel=\"next\", <" + serverUrl + "/test?param=value&per_page=100&page=2>; rel=\"last\"") ...
byte[] readFromChannel(StreamSourceChannel source) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteBuffer buffer = ByteBuffer.wrap(new byte[1024]); ReadableByteChannel blockingSource = new BlockingReadableByteChannel(source); for (;;) { ...
@Timeout(10) @Test public void readEntireMultiDelayedWithPausePayload() throws Exception { String[] delayedPayloads = new String[] { "", "first ", "", "second", }; StreamSourceChannel source = source(delayedPayloads); ...
@Override public Optional<String> validate(String password) { final String LENGTH_REASONING = "must be length of between " + minimumLength + " and " + MAXIMUM_LENGTH; return Strings.isNullOrEmpty(password) || password.length() < minimumLength ? Optional.of(LENGTH_REASONING) ...
@Test public void testValidateSuccess() { Optional<String> result = lengthValidator.validate("Password123"); Assert.assertFalse(result.isPresent()); }
public boolean includes(String ipAddress) { if (all) { return true; } if (ipAddress == null) { throw new IllegalArgumentException("ipAddress is null."); } try { return includes(addressFactory.getByName(ipAddress)); } catch (UnknownHostException e) { return fals...
@Test public void testHostNamesReverserIpMatch() throws UnknownHostException { // create MachineList with a list of of Hostnames TestAddressFactory addressFactory = new TestAddressFactory(); addressFactory.put("1.2.3.1", "host1"); addressFactory.put("1.2.3.4", "host4"); addressFactory.put("1.2.3.5...
public static String toString(Object obj) { if (null == obj) { return StrUtil.NULL; } if (obj instanceof Map) { return obj.toString(); } return Convert.toStr(obj); }
@Test public void toStringTest() { ArrayList<String> strings = CollUtil.newArrayList("1", "2"); String result = ObjectUtil.toString(strings); assertEquals("[1, 2]", result); }
@Override public void run() { try { // make sure we call afterRun() even on crashes // and operate countdown latches, else we may hang the parallel runner if (steps == null) { beforeRun(); } if (skipped) { return; } ...
@Test void testRepeat() { run( "def res1 = karate.repeat(3, i => i + 1 )", "def res2 = karate.repeat(3, i => ({ a: 1 }))", "def res3 = karate.repeat(3, i => ({ a: i + 1 }))" ); matchVar("res1", "[1, 2, 3]"); matchVar("res2", "[{ a: 1 },...
@Override public void checkAppPermissions(GithubAppConfiguration githubAppConfiguration) { AppToken appToken = appSecurity.createAppToken(githubAppConfiguration.getId(), githubAppConfiguration.getPrivateKey()); Map<String, String> permissions = new HashMap<>(); permissions.put("checks", WRITE_PERMISSION_...
@Test public void checkAppPermissions() throws IOException { AppToken appToken = mockAppToken(); String json = "{" + " \"permissions\": {\n" + " \"checks\": \"write\",\n" + " \"metadata\": \"read\",\n" + " \"pul...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testDuplicateVcoresDefinitionAbsolute() throws Exception { expectInvalidResource("vcores"); parseResourceConfigValue("1024 mb, 2 4 vcores"); }
@Override public ExecuteContext doBefore(ExecuteContext context) { String serviceId = (String) context.getArguments()[0]; final RegisterCenterService service = PluginServiceManager.getPluginService(RegisterCenterService.class); final List<MicroServiceInstance> microServiceInstances = service...
@Test public void doBefore() throws NoSuchMethodException { Mockito.when(registerCenterService.getServerList(serviceName)).thenReturn(instanceList); // A normal scenario where isEmpty is false and isAvailable is true RegisterContext.INSTANCE.setAvailable(true); REGISTER_CONFIG.setEn...
public static Set<AttributeKvEntry> convertToAttributes(JsonElement element) { Set<AttributeKvEntry> result = new HashSet<>(); long ts = System.currentTimeMillis(); result.addAll(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts)).collect(Collectors.toList...
@Test public void testParseAttributesBigDecimalAsLong() { var result = new ArrayList<>(JsonConverter.convertToAttributes(JsonParser.parseString("{\"meterReadingDelta\": 1E1}"))); Assertions.assertEquals(10L, result.get(0).getLongValue().get().longValue()); }
public Task<T> getTask() { return _task; }
@Test public void testGetTaskOfParSeqBasedCompletionStage() throws Exception { // Control: CompletableFuture with completed value CompletionStage<String> completionStageCompletableFuture = CompletableFuture.completedFuture(TESTVALUE2); testWithUnFinishedStage(completionStageCompletableFuture); // tre...
public static SslContextFactory.Server createServerSideSslContextFactory(AbstractConfig config, String prefix) { Map<String, Object> sslConfigValues = config.valuesWithPrefixAllOrNothing(prefix); final SslContextFactory.Server ssl = new SslContextFactory.Server(); configureSslContextFactoryKey...
@Test public void testCreateServerSideSslContextFactoryDefaultValues() { Map<String, String> configMap = new HashMap<>(); configMap.put("ssl.keystore.location", "/path/to/keystore"); configMap.put("ssl.keystore.password", "123456"); configMap.put("ssl.key.password", "123456"); ...
public static <KLeftT, KRightT> KTableHolder<KLeftT> build( final KTableHolder<KLeftT> left, final KTableHolder<KRightT> right, final ForeignKeyTableTableJoin<KLeftT, KRightT> join, final RuntimeBuildContext buildContext ) { final LogicalSchema leftSchema = left.getSchema(); final Logi...
@Test public void shouldReturnCorrectSchema() { // Given: givenInnerJoin(left, JOIN_COLUMN); // When: final KTableHolder<Struct> result = join.build(planBuilder, planInfo); // Then: assertThat( result.getSchema(), is(LogicalSchema.builder() .keyColumns(LEFT_SCHEMA...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentExecutor, TokensAndUrlAuthData authData, MediaContainerResource data) throws Exception { if (data == null) { return ImportResult.OK; } for (PhotoModel photoModel: data.getPhotos())...
@Test public void importPhotosVideosAndAlbums() throws Exception { // set up albums final int albumCount = 1; final List<MediaAlbum> mediaAlbums = createTestAlbums(albumCount).stream() .map(MediaAlbum::photoToMediaAlbum) .collect(Collectors.toList()); setUpCreateAlbumsR...
public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); }
@Test public void testAssertEqualsInteger() throws Exception { with(getResourceAsStream("lotto.json")).assertEquals("lotto.winners[0].winnerId", 23); }
public ColumnSizeCommand(Logger console) { super(console); }
@Test public void testColumnSizeCommand() throws IOException { File file = parquetFile(); ColumnSizeCommand command = new ColumnSizeCommand(createLogger()); command.target = file.getAbsolutePath(); command.setConf(new Configuration()); Assert.assertEquals(0, command.run()); }
public String getFilepath() { return filepath; }
@Test public void testConstructorThrowable() { try { throw new KettleFileNotFoundException( cause ); } catch ( KettleFileNotFoundException e ) { assertEquals( cause, e.getCause() ); assertTrue( e.getMessage().contains( causeExceptionMessage ) ); assertEquals( null, e.getFilepath() ); ...
@Override public void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) { while (isValidHeader(in.readableBytes())) { if (startupPhase) { handleStartupPhase(in, out); return; } int payloadLength = in.getI...
@Test void assertDecodeWithStickyPacket() { List<Object> out = new LinkedList<>(); new OpenGaussPacketCodecEngine().decode(context, byteBuf, out); assertTrue(out.isEmpty()); }
@Override public Set<String> getInputMetrics() { return inputMetricKeys; }
@Test public void input_metrics_is_empty_when_not_set() { MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setOutputMetrics("comment_density_1", "comment_density_2") .build(); assertThat(measureComputer.getInputMetrics()).isEmpty(); }
public static String sanitizeName(String name) { return sanitizeName(name, MASK_FOR_INVALID_CHARS_IN_NAMES); }
@Test public void testSanitizeName() { assertEquals("__23456", sanitizeName("123456")); assertEquals("abcdef", sanitizeName("abcdef")); assertEquals("_1", sanitizeName("_1")); assertEquals("a*bc", sanitizeName("a.bc", "*")); assertEquals("abcdef___", sanitizeName("abcdef_.")); assertEquals("__...
public Host get(final String url) throws HostParserException { final StringReader reader = new StringReader(url); final Protocol parsedProtocol, protocol; if((parsedProtocol = findProtocol(reader, factory)) != null) { protocol = parsedProtocol; } else { pr...
@Test public void parseEmptyHost() throws HostParserException { final Host host = new HostParser(new ProtocolFactory(Collections.singleton(new TestProtocol(Scheme.https) { @Override public String getDefaultHostname() { return "host"; } @Overri...
public String getShortMethodDescriptor(MethodReference methodReference) { StringWriter writer = new StringWriter(); try { getWriter(writer).writeShortMethodDescriptor(methodReference); } catch (IOException e) { throw new AssertionError("Unexpected IOException"); }...
@Test public void testGetShortMethodReference() throws IOException { TestDexFormatter formatter = new TestDexFormatter(); Assert.assertEquals( "short method descriptor", formatter.getShortMethodDescriptor(mock(MethodReference.class))); }
public Object execute(ProceedingJoinPoint proceedingJoinPoint, Method method, String fallbackMethodValue, CheckedSupplier<Object> primaryFunction) throws Throwable { String fallbackMethodName = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), fallbackMethodValue); FallbackMethod fallbackMeth...
@Test public void testPrimaryMethodExecutionWithoutFallback() throws Throwable { Method method = this.getClass().getMethod("getName", String.class); final CheckedSupplier<Object> primaryFunction = () -> getName("Name"); final String fallbackMethodValue = ""; when(proceedingJoinPoint...
public static Optional<ESEventOriginContext> parseESContext(String url) { if (url.startsWith(ES_EVENT) || url.startsWith(ES_MESSAGE)) { final String[] tokens = url.split(":"); if (tokens.length != 6) { return Optional.empty(); } return Optional.of(...
@Test public void parseEventESContext() { assertThat(EventOriginContext.parseESContext("urn:graylog:event:es:index-42:01DF13GB094MT6390TYQB2Q73Q")) .isPresent() .get() .satisfies(context -> { assertThat(context.indexName()).isEqualTo("index...
public static byte[] jsonNodeToBinary(JsonNode node, String about) { try { byte[] value = node.binaryValue(); if (value == null) { throw new IllegalArgumentException(about + ": expected Base64-encoded binary data."); } return value; } catc...
@Test public void testInvalidBinaryNode() { assertThrows( IllegalArgumentException.class, () -> MessageUtil.jsonNodeToBinary(new IntNode(42), "Test int to binary") ); assertThrows( UncheckedIOException.class, () -> MessageUtil.jsonNodeToBinary(...
public static Class<?> getLiteral(String className, String literal) { LiteralAnalyzer analyzer = ANALYZERS.get( className ); Class result = null; if ( analyzer != null ) { analyzer.validate( literal ); result = analyzer.getLiteral(); } return result; }
@Test public void testBooleanLiteralFromJLS() { assertThat( getLiteral( boolean.class.getCanonicalName(), "true" ) ).isNotNull(); assertThat( getLiteral( boolean.class.getCanonicalName(), "false" ) ).isNotNull(); assertThat( getLiteral( boolean.class.getCanonicalName(), "FALSE" ) ).isNull();...
@Override public void loadConfiguration(NacosLoggingProperties loggingProperties) { Log4j2NacosLoggingPropertiesHolder.setProperties(loggingProperties); String location = loggingProperties.getLocation(); loadConfiguration(location); }
@Test void testLoadConfigurationWithWrongLocation() { assertThrows(IllegalStateException.class, () -> { System.setProperty("nacos.logging.config", "http://localhost"); nacosLoggingProperties = new NacosLoggingProperties("classpath:nacos-log4j2.xml", System.getProperties()); ...
@Override public IndexMainType getMainType() { checkState(mainType != null, "Main type has not been defined"); return mainType; }
@Test @UseDataProvider("indexes") public void getMainType_fails_with_ISE_if_createTypeMapping_with_IndexMainType_has_not_been_called(Index index) { NewRegularIndex newIndex = new NewRegularIndex(index, defaultSettingsConfiguration); assertThatThrownBy(() -> newIndex.getMainType()) .isInstanceOf(Ille...
@Override public void removeSubscriber(Subscriber subscriber) { removeSubscriber(subscriber, subscriber.subscribeType()); }
@Test void testRemoveSubscriber() { traceEventPublisher.addSubscriber(subscriber, TraceTestEvent.TraceTestEvent1.class); traceEventPublisher.addSubscriber(smartSubscriber, TraceTestEvent.TraceTestEvent1.class); TraceTestEvent.TraceTestEvent1 traceTestEvent1 = new TraceTestEvent.TraceTestEven...
@Override public void init(DatabaseMetaData metaData) throws SQLException { checkState(!initialized, "onInit() must be called once"); Version version = checkDbVersion(metaData, MIN_SUPPORTED_VERSION); supportsNullNotDistinct = version.compareTo(MIN_NULL_NOT_DISTINCT_VERSION) >= 0; initialized = tru...
@Test void postgresql_9_2_is_not_supported() { assertThatThrownBy(() -> { DatabaseMetaData metadata = newMetadata(9, 2); underTest.init(metadata); }) .isInstanceOf(MessageException.class) .hasMessage("Unsupported postgresql version: 9.2. Minimal supported version is 11.0."); }
public final boolean offer(int queueIndex, E item) { return offer(queues[queueIndex], item); }
@Test public void when_offerToGivenQueue_then_poll() { // when boolean didOffer = conveyor.offer(defaultQ, item1); // then assertTrue(didOffer); assertSame(item1, defaultQ.poll()); }
@EventListener(ApplicationEvent.class) void onApplicationEvent(ApplicationEvent event) { if (AnnotationUtils.findAnnotation(event.getClass(), SharedEvent.class) == null) { return; } // we should copy the plugins list to avoid ConcurrentModificationException var startedPlu...
@Test void shouldNotDispatchEventIfNotSharedEvent() { dispatcher.onApplicationEvent(new FakeEvent(this)); verify(pluginManager, never()).getStartedPlugins(); }
@Override public ByteString data() { return _data; }
@Test public void testWrapping() throws InstantiationException, IllegalAccessException { String input = "12345"; ByteString input1 = ByteString.copyAvroString(input, false); Fixed5 fixed1 = DataTemplateUtil.wrap(input1, Fixed5.class); assertSame(input1, fixed1.data()); ByteString input2 ...
@Override public boolean isValid(K key, UUID ticket) { if (timeouts.containsKey(key)) { Timeout<K> timeout = timeouts.get(key); return timeout.getTicket().equals(ticket); } else { return false; } }
@Test void testIsValidInitiallyReturnsFalse() { final DefaultTimerService<AllocationID> timerService = createAndStartTimerService(); assertThat(timerService.isValid(new AllocationID(), UUID.randomUUID())).isFalse(); }
public ExecuteJobServlet() { }
@Test public void testExecuteJobServletTest() throws ServletException, IOException, KettleException { try ( MockedStatic<Encr> encrMockedStatic = mockStatic( Encr.class ) ) { encrMockedStatic.when( () -> Encr.decryptPasswordOptionallyEncrypted( eq( PASSWORD ) ) ).thenReturn( PASSWORD ); doReturn( ...
@Override public <VR> KTable<K, VR> mapValues(final ValueMapper<? super V, ? extends VR> mapper) { Objects.requireNonNull(mapper, "mapper can't be null"); return doMapValues(withKey(mapper), NamedInternal.empty(), null); }
@Test public void shouldNotAllowNullMapperOnMapValues() { assertThrows(NullPointerException.class, () -> table.mapValues((ValueMapper) null)); }
boolean hasReceivedNewVersionFromZooKeeper() { return currentVersion <= lastZooKeeperVersion; }
@Test void new_version_from_zk_predicate_initially_false() { final StateVersionTracker versionTracker = createWithMockedMetrics(); assertFalse(versionTracker.hasReceivedNewVersionFromZooKeeper()); }
static public boolean notMarkedWithNoAutoStart(Object o) { if (o == null) { return false; } Class<?> clazz = o.getClass(); NoAutoStart a = clazz.getAnnotation(NoAutoStart.class); return a == null; }
@Test public void commonObject() { Object o = new Object(); assertTrue(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); }
static Optional<ExecutorService> lookupExecutorServiceRef( CamelContext camelContext, String name, Object source, String executorServiceRef) { ExecutorServiceManager manager = camelContext.getExecutorServiceManager(); ObjectHelper.notNull(manager, ESM_NAME); ObjectHelper.notNull(exec...
@Test void testLookupExecutorServiceRefWithInvalidRef() { String name = "ThreadPool"; Object source = new Object(); String executorServiceRef = "InvalidRef"; when(camelContext.getExecutorServiceManager()).thenReturn(manager); when(camelContext.getRegistry()).thenReturn(mockRe...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldNotCastStringTooBig() { // When: final Exception e = assertThrows( ArithmeticException.class, () -> cast("10", 2, 1) ); // Then: assertThat(e.getMessage(), containsString("Numeric field overflow")); }
@Override public MapperResult listGroupKeyMd5ByPageFetchRows(MapperContext context) { return new MapperResult(" SELECT t.id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified " + "FROM ( SELECT id FROM config_info ORDER BY id OFFSET " + context.getStartRow() + " ROWS FETCH NE...
@Test void testListGroupKeyMd5ByPageFetchRows() { MapperResult mapperResult = configInfoMapperByDerby.listGroupKeyMd5ByPageFetchRows(context); assertEquals(mapperResult.getSql(), " SELECT t.id,data_id,group_id,tenant_id,app_name,type,md5,gmt_modified FROM ( SELECT id FROM config_info...
@ScalarOperator(BETWEEN) @SqlType(StandardTypes.BOOLEAN) public static boolean between(@SqlType(StandardTypes.TINYINT) long value, @SqlType(StandardTypes.TINYINT) long min, @SqlType(StandardTypes.TINYINT) long max) { return min <= value && value <= max; }
@Test public void testBetween() { assertFunction("TINYINT'37' BETWEEN TINYINT'37' AND TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' BETWEEN TINYINT'37' AND TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'37' BETWEEN TINYINT'17' AND TINYINT'37'", BOOLEAN, true); ...
public void setValue(byte[] value) { this.value = value; }
@Test public void testSetValue() { restValue.setValue(PAYLOAD); assertEquals(PAYLOAD, restValue.getValue()); assertContains(restValue.toString(), "value.length=" + PAYLOAD.length); }
public static String u2or4(int v) { if (v == (char) v) { return u2(v); } else { return u4(v); } }
@Test public void testU2or4() { Assert.assertEquals("0000", Hex.u2or4(0)); Assert.assertEquals("04d2", Hex.u2or4(1234)); Assert.assertEquals("0001e240", Hex.u2or4(123456)); Assert.assertEquals("00bc614e", Hex.u2or4(12345678)); Assert.assertEquals("499602d2", Hex.u2or4(1234567...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testShhNewFilter() throws Exception { web3j.shhNewFilter( new ShhFilter( "0x04f96a5e25610293e42a73908e93ccc8c4d4dc0edcfa9fa872f50cb214e08ebf61a03e245533f97284d442460f2998cd41858798ddfd4d661997d3940272b717b1") ...
public static NetFlowV5Packet parsePacket(ByteBuf bb) { final int readableBytes = bb.readableBytes(); final NetFlowV5Header header = parseHeader(bb.slice(bb.readerIndex(), HEADER_LENGTH)); final int packetLength = HEADER_LENGTH + header.count() * RECORD_LENGTH; if (header.count() <= 0 |...
@Test public void pcap_softflowd_NetFlowV5() throws Exception { final List<NetFlowV5Record> allRecords = new ArrayList<>(); try (InputStream inputStream = Resources.getResource("netflow-data/netflow5.pcap").openStream()) { final Pcap pcap = Pcap.openStream(inputStream); pcap....
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldRewriteJoin() { // Given: final Join join = givenJoin(Optional.empty()); // When: final AstNode rewritten = rewriter.rewrite(join, context); // Then: assertThat( rewritten, equalTo( new Join( location, rewrit...
@Override public AppSettings load() { Properties p = loadPropertiesFile(homeDir); Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey) .collect(Collectors.toSet()); keysOverridableFromEnv.addAll(p.stringPropertyNames()); // 1st...
@Test public void command_line_arguments_are_included_to_settings() throws Exception { File homeDir = temp.newFolder(); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[] {"-Dsonar.foo=bar", "-Dhello=world"}, homeDir, serviceLoaderWrapper); AppSettings settings = underTest.l...
public static int[] computePhysicalIndices( List<TableColumn> logicalColumns, DataType physicalType, Function<String, String> nameRemapping) { Map<TableColumn, Integer> physicalIndexLookup = computePhysicalIndices(logicalColumns.stream(), physicalType, nameRe...
@Test void testNameMappingDoesNotExist() { assertThatThrownBy( () -> TypeMappingUtils.computePhysicalIndices( TableSchema.builder() .field("f0", DataTypes.BIGINT())...
public static MySQLBinaryProtocolValue getBinaryProtocolValue(final BinaryColumnType binaryColumnType) { Preconditions.checkArgument(BINARY_PROTOCOL_VALUES.containsKey(binaryColumnType), "Cannot find MySQL type '%s' in column type when process binary protocol value", binaryColumnType); return BINARY_PRO...
@Test void assertGetBinaryProtocolValueWithMySQLTypeVarString() { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLBinaryColumnType.VAR_STRING), instanceOf(MySQLStringLenencBinaryProtocolValue.class)); }
public int completeName(String buffer, int cursor, List<InterpreterCompletion> candidates, Map<String, String> aliases) { CursorArgument cursorArgument = parseCursorArgument(buffer, cursor); // find schema and table name if they are String schema; String table; String colu...
@Test void testCompleteName_SimpleColumn() { String buffer = "prod_dds.financial_account.acc"; int cursor = 30; List<InterpreterCompletion> candidates = new ArrayList<>(); Map<String, String> aliases = new HashMap<>(); sqlCompleter.completeName(buffer, cursor, candidates, aliases); assertEqual...
public RelDataType createRelDataTypeFromSchema(Schema schema) { Builder builder = new Builder(this); boolean enableNullHandling = schema.isEnableColumnBasedNullHandling(); for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) { builder.add(entry.getKey(), toRelDataType(entry.g...
@Test(dataProvider = "relDataTypeConversion") public void testArrayTypes(FieldSpec.DataType dataType, RelDataType arrayType, boolean columnNullMode) { TypeFactory typeFactory = new TypeFactory(); Schema testSchema = new Schema.SchemaBuilder() .addMultiValueDimension("col", dataType) .setEnable...
@Override public String getKind(final String filename) { if(StringUtils.isBlank(Path.getExtension(filename))) { final String kind = this.kind(filename); if(StringUtils.isBlank(kind)) { return LocaleFactory.localizedString("Unknown"); } return k...
@Test public void testGetKind() { assertNotNull(new LaunchServicesFileDescriptor().getKind("/tmp/t.txt")); }
public static Select select(String fieldName) { return new Select(fieldName); }
@Test void basic_and_andnot_or_offset_limit_param_order_by_and_contains() { String q = Q.select("*") .from("sd1") .where("f1").contains("v1") .and("f2").contains("v2") .or("f3").contains("v3") .andnot("f4").contains("v4") ...
@Override public long read() { return gaugeSource.read(); }
@Test public void whenProbeRegisteredAfterGauge() { LongGauge gauge = metricsRegistry.newLongGauge("foo.longField"); SomeObject someObject = new SomeObject(); metricsRegistry.registerStaticMetrics(someObject, "foo"); assertEquals(someObject.longField, gauge.read()); }