focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public List<Ce.Task> formatQueue(DbSession dbSession, List<CeQueueDto> dtos) { DtoCache cache = DtoCache.forQueueDtos(dbClient, dbSession, dtos); return dtos.stream().map(input -> formatQueue(input, cache)).toList(); }
@Test public void formatQueue_compute_execute_time_if_in_progress() { long startedAt = 1_450_000_001_000L; long now = 1_450_000_003_000L; CeQueueDto dto = new CeQueueDto(); dto.setUuid("UUID"); dto.setTaskType("TYPE"); dto.setStatus(CeQueueDto.Status.PENDING); dto.setCreatedAt(1_450_000_00...
public static FormBody buildFormBody(final Map<String, ?> form) { FormBody.Builder paramBuilder = new FormBody.Builder(StandardCharsets.UTF_8); for (Map.Entry<String, ?> entry : form.entrySet()) { paramBuilder.add(entry.getKey(), String.valueOf(entry.getValue())); } return pa...
@Test public void buildFormBodyTest() { FormBody formBody = HttpUtils.buildFormBody(formMap); Assert.assertNotNull(formBody); }
static void readFullyHeapBuffer(InputStream f, ByteBuffer buf) throws IOException { readFully(f, buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); buf.position(buf.limit()); }
@Test public void testHeapReadFullyLimit() throws Exception { final ByteBuffer readBuffer = ByteBuffer.allocate(10); readBuffer.limit(7); MockInputStream stream = new MockInputStream(2, 3, 3); DelegatingSeekableInputStream.readFullyHeapBuffer(stream, readBuffer); Assert.assertEquals(7, readBuffe...
public static <K> KStreamHolder<K> build( final KStreamHolder<K> left, final KTableHolder<K> right, final StreamTableJoin<K> join, final RuntimeBuildContext buildContext, final JoinedFactory joinedFactory ) { final Formats leftFormats = join.getInternalFormats(); final QueryConte...
@Test public void shouldReturnCorrectLegacySchema() { // Given: join = new StreamTableJoin<>( new ExecutionStepPropertiesV1(CTX), JoinType.INNER, ColumnName.of(LEGACY_KEY_COL), LEFT_FMT, left, right ); // When: final KStreamHolder<Struct> result = j...
public static SqlArgument of(final SqlType type) { return new SqlArgument(type, null, null); }
@Test public void shouldThrowWhenLambdaPresentWhenGettingType() { final SqlArgument argument = SqlArgument.of(null, (SqlLambdaResolved .of(ImmutableList.of(SqlTypes.STRING), SqlTypes.INTEGER))); final Exception e = assertThrows( RuntimeException.class, argument::getSqlTypeOrThrow ...
@Override public String toString() { return "ChildEip{" + "id='" + id + '\'' + ", eipAttributes=" + eipAttributeMap + '}'; }
@Test public void testToString() { String toString = getInstance().toString(); assertNotNull(toString); assertTrue(toString.contains("ChildEip")); }
@Override public List<PluginWrapper> getPlugins() { return Arrays.asList(getPlugin(currentPluginId)); }
@Test public void getPlugins() { pluginManager.loadPlugins(); assertEquals(2, pluginManager.getPlugins().size()); assertEquals(1, wrappedPluginManager.getPlugins().size()); }
@Override public CompletableFuture<Acknowledge> disposeSavepoint(String savepointPath) { final SavepointDisposalRequest savepointDisposalRequest = new SavepointDisposalRequest(savepointPath); final CompletableFuture<TriggerResponse> savepointDisposalTriggerFuture = s...
@Test void testDisposeSavepoint() throws Exception { final String savepointPath = "foobar"; final String exceptionMessage = "Test exception."; final FlinkException testException = new FlinkException(exceptionMessage); final TestSavepointDisposalHandlers testSavepointDisposalHandlers...
@Override public boolean addIfGreater(double score, V object) { return get(addIfGreaterAsync(score, object)); }
@Test public void testAddIfGreater() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); set.add(123, "1980"); assertThat(set.addIfGreater(120, "1980")).isFalse(); assertThat(set.getScore("1980")).isEqualTo(123); assertThat(set.addIfGreater(125, "1980")).i...
@Udf public String concat(@UdfParameter( description = "The varchar fields to concatenate") final String... inputs) { if (inputs == null) { return null; } return Arrays.stream(inputs) .filter(Objects::nonNull) .collect(Collectors.joining()); }
@Test public void shouldReturnEmptyForSingleNullInput() { assertThat(udf.concat((String) null), is("")); assertThat(udf.concat((ByteBuffer) null), is(ByteBuffer.wrap(new byte[] {}))); }
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { if ((defaultManagedBean == null && customManagedBean == null) || objectName == null) return null; // skip proxy classes if (defaultManagedBean != null && P...
@Test(expected = IllegalArgumentException.class) public void testAttributePOJONamingNoGetter() throws JMException { mbeanInfoAssembler.getMBeanInfo(new BadAttributeNameNoGetterSetter(), null, "someName"); }
@Override public Result apply(ApplyNode applyNode, Captures captures, Context context) { if (applyNode.getMayParticipateInAntiJoin()) { return Result.empty(); } Assignments subqueryAssignments = applyNode.getSubqueryAssignments(); if (subqueryAssignments.size() != 1)...
@Test public void testFeatureDisabled() { tester().assertThat(new TransformUncorrelatedInPredicateSubqueryToDistinctInnerJoin()) .setSystemProperty(IN_PREDICATES_AS_INNER_JOINS_ENABLED, "false") .on(p -> p.apply( assignment( ...
public Map<String, String> confirm(RdaConfirmRequest params) { AppSession appSession = appSessionService.getSession(params.getAppSessionId()); AppAuthenticator appAuthenticator = appAuthenticatorService.findByUserAppId(appSession.getUserAppId()); if(!checkSecret(params, appSession) || !checkAcc...
@Test void checkVerifiedWidchecker(){ appSession.setRdaAction("upgrade_rda_widchecker"); when(appSessionService.getSession(any())).thenReturn(appSession); when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator); when(switchService.digidAppSwitchEnabled()).t...
public static CustomWeighting.Parameters createWeightingParameters(CustomModel customModel, EncodedValueLookup lookup) { String key = customModel.toString(); Class<?> clazz = customModel.isInternal() ? INTERNAL_CACHE.get(key) : null; if (CACHE_SIZE > 0 && clazz == null) clazz = CACHE...
@Test void testBackwardFunction() { CustomModel customModel = new CustomModel(); customModel.addToPriority(If("backward_car_access != car_access", MULTIPLY, "0.5")); customModel.addToSpeed(If("true", LIMIT, "100")); CustomWeighting.EdgeToDoubleMapping priorityMapping = CustomModelPar...
public static SmtpCommand valueOf(CharSequence commandName) { ObjectUtil.checkNotNull(commandName, "commandName"); SmtpCommand command = COMMANDS.get(commandName.toString()); return command != null ? command : new SmtpCommand(AsciiString.of(commandName)); }
@Test public void equalsIgnoreCase() { assertEquals(SmtpCommand.MAIL, SmtpCommand.valueOf("mail")); assertEquals(SmtpCommand.valueOf("test"), SmtpCommand.valueOf("TEST")); }
public List<String> toMnemonic(byte[] entropy) { checkArgument(entropy.length % 4 == 0, () -> "entropy length not multiple of 32 bits"); checkArgument(entropy.length > 0, () -> "entropy is empty"); // We take initial entropy of ENT bits and compute its //...
@Test(expected = RuntimeException.class) public void testBadEntropyLength() throws Exception { byte[] entropy = ByteUtils.parseHex("7f7f7f7f7f7f7f7f7f7f7f7f7f7f"); mc.toMnemonic(entropy); }
public static <T> Map<Integer, List<T>> distributeObjects(int count, List<T> objects) { Map<Integer, List<T>> processorToObjects = IntStream.range(0, objects.size()) .mapToObj(i -> entry(i, objects.get(i))) .collect(groupingBy(e -> e.getKey() % count, mapping(Map.Entry::getValue,...
@Test public void test_distributeObjects() { // count == 1 assertArrayEquals( new int[][]{ new int[]{}}, distributeObjects(1, new int[]{})); assertArrayEquals( new int[][]{ new int[]{2}}, ...
@Override public void trackChannelEvent(String eventName) { }
@Test public void testTrackChannelEvent() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } ...
static String headerLine(CSVFormat csvFormat) { return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader()); }
@Test public void givenNoCommentMarker_doesntSkipLine() { CSVFormat csvFormat = csvFormat(); PCollection<String> input = pipeline.apply( Create.of(headerLine(csvFormat), "#comment", "a,1,1.1", "b,2,2.2", "c,3,3.3")); CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(csvFor...
public void close() { this.client.close(); }
@Test public void closeTest() { try (MockedStatic<Client> clientMockedStatic = mockStatic(Client.class)) { this.mockEtcd(clientMockedStatic); final EtcdClient etcdClient = new EtcdClient("url", 60L, 3000L); etcdClient.close(); } catch (Exception e) { t...
@Override public PipelineDef parse(Path pipelineDefPath, Configuration globalPipelineConfig) throws Exception { return parse(mapper.readTree(pipelineDefPath.toFile()), globalPipelineConfig); }
@Test void testInvalidTimeZone() throws Exception { URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml"); YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser(); assertThatThrownBy( () -> ...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testInverseUdpMissingColumn() throws Exception { InInt32UDP nullRejecting = new InInt32UDP(ImmutableSet.of(42)); InInt32UDP nullAccepting = new InInt32UDP(Sets.newHashSet((Integer) null)); IntColumn fake = intColumn("missing_column"); assertTrue( "Should drop block for null ...
static String generateIdFromName(String name) { return String.format("%s-%s", AUTO_GENERATED_ID_PREFIX, Objects.hash(name)); }
@Test void generateIdFromName() { String name = "name"; String wrongName = "wrong-name"; String retrieved = TupleIdentifier.generateIdFromName(name); assertThat(retrieved).isEqualTo(TupleIdentifier.generateIdFromName(name)) .isNotEqualTo(TupleIdentifier.generateIdFrom...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void sendChatAction() { assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.typing.name())).isOk()); assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.typing)).isOk()); assertTrue(bot.execute(new SendChatAction(chatId, ChatAction.upload_photo)).isOk()); ...
public Mode.Bits toModeBits() { Mode.Bits bits = Mode.Bits.NONE; if (contains(AclAction.READ)) { bits = bits.or(Mode.Bits.READ); } if (contains(AclAction.WRITE)) { bits = bits.or(Mode.Bits.WRITE); } if (contains(AclAction.EXECUTE)) { bits = bits.or(Mode.Bits.EXECUTE); } ...
@Test public void toModeBits() { AclActions actions = new AclActions(); assertEquals(Mode.Bits.NONE, actions.toModeBits()); actions = new AclActions(); actions.add(AclAction.READ); assertEquals(Mode.Bits.READ, actions.toModeBits()); actions = new AclActions(); actions.add(AclAction.WRITE...
public static Optional<String> getTableName(final String tableMetaDataPath) { Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)/schemas/([\\w\\-]+)/tables" + "/([\\w\\-]+)$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(tableMetaDataPath); return m...
@Test void assertGetTableNameTableNameNotFoundScenario() { assertThat(ShardingSphereDataNode.getTableName("/statistics/databases/db_name/schemas/db_schema"), is(Optional.empty())); }
public static List<HollowSchema> parseCollectionOfSchemas(Reader reader) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer(reader); configureTokenizer(tokenizer); List<HollowSchema> schemaList = new ArrayList<HollowSchema>(); HollowSchema schema = parseSchema(tokenize...
@Test public void testParseCollectionOfSchemas_reader() throws Exception { InputStream input = null; try { input = getClass().getResourceAsStream("/schema1.txt"); List<HollowSchema> schemas = HollowSchemaParser.parseCollectionOfSchemas(new BufferedReader(n...
@Transactional public AccessKey create(String appId, AccessKey entity) { long count = accessKeyRepository.countByAppId(appId); if (count >= ACCESSKEY_COUNT_LIMIT) { throw new BadRequestException("AccessKeys count limit exceeded"); } entity.setId(0L); entity.setAppId(appId); entity.setDa...
@Test(expected = BadRequestException.class) public void testCreateWithException() { String appId = "someAppId"; String secret = "someSecret"; int maxCount = 5; for (int i = 0; i <= maxCount; i++) { AccessKey entity = assembleAccessKey(appId, secret); accessKeyService.create(appId, entity)...
public void reset() { lock.lock(); try { cancellationException = null; clearElementsLocked(); } finally { lock.unlock(); } }
@Test(timeout = 10_000) public void runTestForMultipleConsumersAndProducers() throws Exception { CancellableQueue<String> queue = new CancellableQueue<>(100); runTestForMultipleConsumersAndProducers(queue); queue.reset(); runTestForMultipleConsumersAndProducers(queue); }
@Override public Optional<AuthenticatedDevice> authenticate(BasicCredentials basicCredentials) { boolean succeeded = false; String failureReason = null; try { final UUID accountUuid; final byte deviceId; { final Pair<String, Byte> identifierAndDeviceId = getIdentifierAndDeviceId...
@Test void testAuthenticateIncorrectPassword() { final UUID uuid = UUID.randomUUID(); final byte deviceId = 1; final String password = "12345"; final Account account = mock(Account.class); final Device device = mock(Device.class); final SaltedTokenHash credentials = mock(SaltedTokenHash.class...
public static PathData[] expandAsGlob(String pattern, Configuration conf) throws IOException { Path globPath = new Path(pattern); FileSystem fs = globPath.getFileSystem(conf); FileStatus[] stats = fs.globStatus(globPath); PathData[] items = null; if (stats == null) { // remove any q...
@Test public void testGlobThrowsExceptionForUnreadableDir() throws Exception { Path obscuredDir = new Path("foo"); Path subDir = new Path(obscuredDir, "bar"); //so foo is non-empty fs.mkdirs(subDir); fs.setPermission(obscuredDir, new FsPermission((short)0)); //no access try { PathData.expand...
public static String substVars(String val, PropertyContainer pc1) { return substVars(val, pc1, null); }
@Test(timeout = 1000) public void detectCircularReferences2() { context.putProperty("A", "${B}"); context.putProperty("B", "${C}"); context.putProperty("C", "${A}"); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Circular variable reference detected whi...
public B proxy(String proxy) { this.proxy = proxy; return getThis(); }
@Test void proxy() { InterfaceBuilder builder = new InterfaceBuilder(); builder.proxy("mockproxyfactory"); Assertions.assertEquals("mockproxyfactory", builder.build().getProxy()); }
public static Long parseLedgerId(String name) { if (name == null || name.isEmpty()) { return null; } if (name.endsWith("-index")) { name = name.substring(0, name.length() - "-index".length()); } int pos = name.indexOf("-ledger-"); if (pos < 0) { ...
@Test public void parseLedgerIdTest() throws Exception { UUID id = UUID.randomUUID(); long ledgerId = 123124; String key = DataBlockUtils.dataBlockOffloadKey(ledgerId, id); String keyIndex = DataBlockUtils.indexBlockOffloadKey(ledgerId, id); assertEquals(ledgerId, DataBlockUti...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void kickChatMember() { BaseResponse response = bot.execute(new KickChatMember(channelName, chatId).untilDate(123).revokeMessages(true)); assertFalse(response.isOk()); assertEquals(400, response.errorCode()); assertEquals("Bad Request: can't remove chat owner", response....
@NonNull @Override public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException { return Stapler.lookupConverter(target) .convert( target, context.getSecretSourceResolver() ...
@Test public void _int() throws Exception { Configurator c = registry.lookupOrFail(int.class); final Object value = c.configure(new Scalar("123"), context); assertEquals(123, (int) value); }
public static void createTopics( Logger log, String bootstrapServers, Map<String, String> commonClientConf, Map<String, String> adminClientConf, Map<String, NewTopic> topics, boolean failOnExisting) throws Throwable { // this method wraps the call to createTopics() that takes admin clien...
@Test public void testCreateTopicsFailsIfAtLeastOneTopicExists() { adminClient.addTopic( false, TEST_TOPIC, Collections.singletonList(new TopicPartitionInfo(0, broker1, singleReplica, Collections.emptyList())), null); Map<String, NewTopic> newTopics =...
public Optional<ScimGroupDto> findByGroupUuid(DbSession dbSession, String groupUuid) { return Optional.ofNullable(mapper(dbSession).findByGroupUuid(groupUuid)); }
@Test void findByGroupUuid_whenScimUuidNotFound_shouldReturnEmptyOptional() { assertThat(scimGroupDao.findByGroupUuid(db.getSession(), "unknownId")).isEmpty(); }
@Nullable public Iterable<String> searchDomains() { return searchDomains; }
@Test void searchDomains() { assertThat(builder.build().searchDomains()).isNull(); List<String> searchDomains = Collections.singletonList("searchDomains"); builder.searchDomains(searchDomains); assertThat(builder.build().searchDomains()).isEqualTo(searchDomains); }
public static URI parse(String gluePath) { requireNonNull(gluePath, "gluePath may not be null"); if (gluePath.isEmpty()) { return rootPackageUri(); } // Legacy from the Cucumber Eclipse plugin // Older versions of Cucumber allowed it. if (CLASSPATH_SCHEME_PRE...
@Test void glue_path_must_have_valid_identifier_parts() { Executable testMethod = () -> GluePath.parse("01-examples"); IllegalArgumentException actualThrown = assertThrows(IllegalArgumentException.class, testMethod); assertThat("Unexpected exception message", actualThrown.getMessage(), is(eq...
@Override public boolean shouldHandle(Request request) { // we don't check the method here because we want to return 405 if it is anything but POST return MUX_URI_PATH.equals(request.getURI().getPath()); }
@Test(dataProvider = "multiplexerConfigurations") public void testIsNotMultiplexedRequest(MultiplexerRunMode multiplexerRunMode) throws Exception { MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexerRunMode); RestRequest request = new RestRequestBuilder(new URI("/somethingElse"))...
public void registerRunningQuery(final String appId) { queriesGuaranteedToBeRunningAtSomePoint.add(appId); }
@Test public void shouldReturnTrueForQueriesGuaranteedToBeRunningAtSomePoint() { // Given: ALL_APP_IDS.forEach(id -> service.registerRunningQuery(id)); // When: List<Boolean> results = ALL_APP_IDS.stream() .map(service::wasQueryGuaranteedToBeRunningAtSomePoint) ...
public int generate(Class<? extends CustomResource> crdClass, Writer out) throws IOException { ObjectNode node = nf.objectNode(); Crd crd = crdClass.getAnnotation(Crd.class); if (crd == null) { err(crdClass + " is not annotated with @Crd"); } else { node.put("apiV...
@Test void simpleTest() throws IOException { StringWriter w = new StringWriter(); CrdGenerator crdGenerator = new CrdGenerator(KubeVersion.V1_16_PLUS, ApiVersion.V1, CrdGenerator.YAML_MAPPER, emptyMap(), crdGeneratorReporter, emptyList(), null, null, new CrdGenerator....
@Deprecated protected ExecutorService getReportCacheExecutor() { return reportCacheExecutor; }
@Test void testStoreProviderUsual() throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService"; String version = "1.0.0"; String group = null; String application = "vic"; ThreadPoolExecutor reportCacheExecutor = (ThreadPo...
@VisibleForTesting URI getDefaultHttpUri() { return getDefaultHttpUri("/"); }
@Test public void testHttpBindAddressIPv6Wildcard() throws RepositoryException, ValidationException { jadConfig.setRepository(new InMemoryRepository(ImmutableMap.of("http_bind_address", "[::]:9000"))).addConfigurationBean(configuration).process(); assertThat(configuration.getDefaultHttpUri()) ...
public static String toString(Throwable e) { UnsafeStringWriter w = new UnsafeStringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName()); if (e.getMessage() != null) { p.print(": " + e.getMessage()); } p.println(); try { ...
@Test void testExceptionToString() throws Exception { assertThat( StringUtils.toString(new RuntimeException("abc")), containsString("java.lang.RuntimeException: abc")); }
@Override public List<ActionParameter> getParameters() { return List.of( ActionParameter.from("message", "The message to output to the user, special characters should be escaped.") ); }
@Test void testGetParameters() { List<ActionParameter> parameters = outputMessageAction.getParameters(); assertEquals(1, parameters.size()); ActionParameter parameter = parameters.get(0); assertEquals("message", parameter.getName()); assertTrue(parameter.getDescription().cont...
public static List<Path> pluginUrls(Path topPath) throws IOException { boolean containsClassFiles = false; Set<Path> archives = new TreeSet<>(); LinkedList<DirectoryEntry> dfs = new LinkedList<>(); Set<Path> visited = new HashSet<>(); if (isArchive(topPath)) { return...
@Test public void testPluginUrlsWithRelativeSymlinkBackwards() throws Exception { createBasicDirectoryLayout(); Path anotherPath = rootDir.resolve("moreplugins"); Files.createDirectories(anotherPath); anotherPath = anotherPath.toRealPath(); Files.createDirectories(anotherPat...
public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) { final String output = new String(toHexCharArray(input, offset, length)); return withPrefix ? new StringBuilder(HEX_PREFIX).append(output).toString() : output; }
@Test public void testToHexString() { assertEquals(Numeric.toHexString(new byte[] {}), ("0x")); assertEquals(Numeric.toHexString(new byte[] {0x1}), ("0x01")); assertEquals(Numeric.toHexString(HEX_RANGE_ARRAY), (HEX_RANGE_STRING)); byte[] input = {(byte) 0x12, (byte) 0x34, (byte) 0x56...
@LiteralParameters("x") @ScalarOperator(GREATER_THAN) @SqlType(StandardTypes.BOOLEAN) public static boolean greaterThan(@SqlType("char(x)") Slice left, @SqlType("char(x)") Slice right) { return compareChars(left, right) > 0; }
@Test public void testGreaterThan() { assertFunction("cast('bar' as char(5)) > cast('foo' as char(3))", BOOLEAN, false); assertFunction("cast('foo' as char(5)) > cast('bar' as char(3))", BOOLEAN, true); assertFunction("cast('bar' as char(3)) > cast('foo' as char(5))", BOOLEAN, false); ...
public String getArgs() { return args; }
@Test @DirtiesContext public void testCreateEndpointWithArgs3() throws Exception { String args = "RAW(arg1+arg2 arg3)"; // Just avoid URI encoding by using the RAW() ExecEndpoint e = createExecEndpoint("exec:test?args=" + args); assertEquals("arg1+arg2 arg3", e.getArgs()); }
@GetMapping("/id/{id}") public ShenyuAdminResult queryById(@PathVariable("id") @Valid @Existed(provider = TagMapper.class, message = "tag is not existed") final String id) { TagVO tagVO = tagService.findById(id); ...
@Test public void testqueryById() throws Exception { given(tagService.findById("123")).willReturn(buildTagVO()); this.mockMvc.perform(MockMvcRequestBuilders.get("/tag/id/{id}", "123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.message", is(ShenyuResultMessage...
@Override public void onCreate( final ServiceContext serviceContext, final MetaStore metaStore, final QueryMetadata queryMetadata) { if (perQuery.containsKey(queryMetadata.getQueryId())) { return; } perQuery.put( queryMetadata.getQueryId(), new PerQueryListener( ...
@Test public void shouldInitiallyHaveInitialState() { // When: listener.onCreate(serviceContext, metaStore, query); // Then: assertThat(currentGaugeValue(METRIC_NAME_1), is("-")); assertThat(currentGaugeValue(METRIC_NAME_2), is("NO_ERROR")); assertThat(currentGaugeNumValue(NUM_METRIC_NAME_1),...
@Override public JibContainerBuilder createJibContainerBuilder( JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode) { try { FileCollection projectDependencies = project.files( project.getConfigurations().getByName(configurationName).getResolvedConf...
@Test public void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() throws IOException, InvalidImageReferenceException { setUpWarProject(temporaryFolder.getRoot().toPath()); assertThat( gradleProjectProperties.createJibContainerBuilder( JavaContainerBuilder.from("igno...
@Override public int size() { return size; }
@Test public void sizeIsInitiallyZero() { assertEquals(0, set.size()); }
@Nonnull public <T> T getInstance(@Nonnull Class<T> type) { return getInstance(new Key<>(type)); }
@Test public void whenNoImplOrServiceOrDefaultSpecified_shouldThrow() throws Exception { try { injector.getInstance(Umm.class); fail(); } catch (InjectionException e) { // ok } }
private static List<Long> getAllComputeNodeIds() throws DdlException { SystemInfoService infoService = GlobalStateMgr.getCurrentState().getNodeMgr().getClusterInfo(); List<Long> allComputeNodeIds = Lists.newArrayList(); if (RunMode.isSharedDataMode()) { // check warehouse ...
@Test public void testGetTabletDistributionForSharedDataMode() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { new MockUp<RunMode>() { @Mock public RunMode getCurrentRunMode() { return RunMode.SHARED_DATA; ...
public static BytesInput empty() { return EMPTY_BYTES_INPUT; }
@Test public void testEmpty() throws IOException { byte[] data = new byte[0]; Supplier<BytesInput> factory = () -> BytesInput.empty(); validate(data, factory); }
@Override public DataflowPipelineJob run(Pipeline pipeline) { // Multi-language pipelines and pipelines that include upgrades should automatically be upgraded // to Runner v2. if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) { List<String> experiments = fi...
@Test public void testTemplateRunnerLoggedErrorForFile() throws Exception { DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setJobName("TestJobName"); options.setRunner(DataflowRunner.class); options.setTemplateLocation("//bad/path"); options.set...
@Override public boolean isEnvironmentEmpty() { for (EnvironmentConfig part : this) { if (!part.isEnvironmentEmpty()) return false; } return true; }
@Test void shouldReturnTrueIsChildConfigContainsNoPipelineAgentsAndVariables() { assertTrue(singleEnvironmentConfig.isEnvironmentEmpty()); }
public static CurlOption parse(String cmdLine) { List<String> args = ShellWords.parse(cmdLine); URI url = null; HttpMethod method = HttpMethod.PUT; List<Entry<String, String>> headers = new ArrayList<>(); Proxy proxy = NO_PROXY; while (!args.isEmpty()) { Str...
@Test public void must_provide_valid_proxy_domain() { String uri = "https://example.com -x https://:3129"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> CurlOption.parse(uri)); assertThat(exception.getMessage(), is("'https://:3129' did not have a val...
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_single_object__single_cell__using_default_transformer() { DataTable table = parse("| BLACK_BISHOP |"); registry.setDefaultDataTableEntryTransformer(TABLE_ENTRY_BY_TYPE_CONVERTER_SHOULD_NOT_BE_USED); registry.setDefaultDataTableCellTransformer(JACKSON_TABLE_CELL_BY_TYPE_...
@Override public int getOrder() { return PluginEnum.CRYPTOR_RESPONSE.getCode(); }
@Test public void getOrderTest() { final int result = cryptorResponsePlugin.getOrder(); assertEquals(PluginEnum.CRYPTOR_RESPONSE.getCode(), result); }
public static FindKV findKV(String regex, int keyGroup, int valueGroup) { return findKV(Pattern.compile(regex), keyGroup, valueGroup); }
@Test @Category(NeedsRunner.class) public void testKVMatchesName() { PCollection<KV<String, String>> output = p.apply(Create.of("a b c")) .apply(Regex.findKV("a (?<keyname>b) (?<valuename>c)", "keyname", "valuename")); PAssert.that(output).containsInAnyOrder(KV.of("b", "c")); p.run...
@Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { this.config = TbNodeUtils.convert(configuration, TbJsonPathNodeConfiguration.class); this.jsonPathValue = config.getJsonPath(); if (!TbJsonPathNodeConfiguration.DEFAULT_JSON_PATH.equals(this...
@Test void givenDefaultConfig_whenInit_thenFail() { config.setJsonPath(""); nodeConfiguration = new TbNodeConfiguration(JacksonUtil.valueToTree(config)); assertThatThrownBy(() -> node.init(ctx, nodeConfiguration)).isInstanceOf(IllegalArgumentException.class); }
public String render(Object o) { StringBuilder result = new StringBuilder(template.length()); render(o, result); return result.toString(); }
@Test public void valuesSubstitutedIntoTemplate() { Template template = new Template("Hello {{value}} "); assertEquals("Hello World ", template.render(foo)); }
@Override public boolean needsTaskCommit(TaskAttemptContext context) { // We need to commit if this is the last phase of a MapReduce process return TaskType.REDUCE.equals(context.getTaskAttemptID().getTaskID().getTaskType()) || context.getJobConf().getNumReduceTasks() == 0; }
@Test public void testNeedsTaskCommit() { HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter(); JobConf mapOnlyJobConf = new JobConf(); mapOnlyJobConf.setNumMapTasks(10); mapOnlyJobConf.setNumReduceTasks(0); // Map only job should commit map tasks Assert.assertTrue(committ...
@Override @MethodNotAvailable public CompletionStage<V> putAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testPutAsyncWithExpiryPolicy() { ExpiryPolicy expiryPolicy = new HazelcastExpiryPolicy(1, 1, 1, TimeUnit.MILLISECONDS); adapter.putAsync(42, "value", expiryPolicy); }
@Override public ValueSet canonicalize(boolean removeSafeConstants) { if (removeSafeConstants) { // Since we cannot create a set with multiple entries but same "constant", we just use number of entries return new EquatableValueSet( type, wh...
@Test public void testCanonicalize() throws Exception { assertSameSet(EquatableValueSet.all(type(BIGINT)), EquatableValueSet.all(type(BIGINT)), false); assertSameSet( EquatableValueSet.of(type(BIGINT), 0L, 1L, 3L), EquatableValueSet.of(type(BIGINT), 0L...
public void encryptColumns( String inputFile, String outputFile, List<String> paths, FileEncryptionProperties fileEncryptionProperties) throws IOException { Path inPath = new Path(inputFile); Path outPath = new Path(outputFile); RewriteOptions options = new RewriteOptions.Builder(conf, inPath, o...
@Test public void testEncryptAllColumns() throws IOException { String[] encryptColumns = {"DocId", "Name", "Gender", "Links.Forward", "Links.Backward"}; testSetup("GZIP"); columnEncryptor.encryptColumns( inputFile.getFileName(), outputFile, Arrays.asList(encryptColumns), En...
@UdafFactory(description = "Compute sample standard deviation of column with type Long.", aggregateSchema = "STRUCT<SUM bigint, COUNT bigint, M2 double>") public static TableUdaf<Long, Struct, Double> stdDevLong() { return getStdDevImplementation( 0L, STRUCT_LONG, (agg, newValue) -> ...
@Test public void shouldMergeLongs() { final TableUdaf<Long, Struct, Double> udaf = stdDevLong(); Struct left = udaf.initialize(); final Long[] leftValues = new Long[] {1L, 2L, 3L, 4L, 5L}; for (final Long thisValue : leftValues) { left = udaf.aggregate(thisValue, left); } Struct right...
public static Complex of(double real) { return new Complex(real, 0.0); }
@Test public void testArray() { System.out.println("Complex.Array"); Complex.Array array = Complex.Array.of(a, b); System.out.println("a = " + a); System.out.println("b = " + b); assertEquals(a.re, array.get(0).re, 1E-15); assertEquals(a.im, array.get(0).im, 1E-15); ...
public List<RowMetaInterface> getRecommendedIndexes() { List<RowMetaInterface> indexes = new ArrayList<RowMetaInterface>(); // First index : ID_BATCH if any is used. if ( isBatchIdUsed() ) { indexes.add( addFieldsToIndex( getKeyField() ) ); } // The next index includes : ERRORS, STATUS, TRANS...
@Test public void getRecommendedIndexes() { List<RowMetaInterface> indexes = transLogTable.getRecommendedIndexes(); String[] expected = new String[]{ "TRANSNAME", "LOGDATE" }; assertTrue( "No indicies present", indexes.size() > 0 ); boolean found = false; for ( RowMetaInterface rowMeta : indexes )...
public boolean compatibleVersion(String acceptableVersionRange, String actualVersion) { V pluginVersion = parseVersion(actualVersion); // Treat a single version "1.4" as a left bound, equivalent to "[1.4,)" if (acceptableVersionRange.matches(VERSION_REGEX)) { return ge(pluginVersion, parseVersion(acc...
@Test public void testRange_leftOpen_exact() { Assert.assertFalse(checker.compatibleVersion("(2.3,4.3]", "2.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "2.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,)", "2.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,]", "2...
@Override public void executeUpdate(final UnregisterStorageUnitStatement sqlStatement, final ContextManager contextManager) { if (!sqlStatement.isIfExists()) { checkExisted(sqlStatement.getStorageUnitNames()); } checkInUsed(sqlStatement); try { contextManager....
@Test void assertExecuteUpdateWithStorageUnitInUsedWithoutIgnoredTables() { when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(new DistSQLHandlerFixtureRule()))); assertThrows(InUsedStorageUnitException.class, () -> executor.executeUpdate(new UnregisterStorageUnitStat...
@Override public Option<HoodieBaseFile> getLatestBaseFile(String partitionPath, String fileId) { return execute(partitionPath, fileId, preferredView::getLatestBaseFile, (path, id) -> getSecondaryView().getLatestBaseFile(path, id)); }
@Test public void testGetLatestBaseFile() { Option<HoodieBaseFile> actual; Option<HoodieBaseFile> expected = Option.of(new HoodieBaseFile("test.file")); String partitionPath = "/table2"; String fileID = "file.123"; when(primary.getLatestBaseFile(partitionPath, fileID)).thenReturn(expected); a...
@Override public boolean remove(Object o) { return map.remove(o) != null; }
@Test public void testRemoveFailure() { ExtendedSet<TestValue> set = new ExtendedSet<TestValue>(Maps.newConcurrentMap()); TestValue val = new TestValue("foo", 1); assertFalse(set.remove(val)); }
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> result = getTargetInvokersByRules(invokers, targetSe...
@Test public void testGetTargetInvokerByTagRulesWithPolicySceneTwo() { // initialize the routing rule RuleInitializationUtils.initAZTagMatchTriggerThresholdPolicyRule(); // Scenario 1: The downstream provider has instances that meet the requirements List<Object> invokers = new ArrayL...
@Override public void validateAction( RepositoryOperation... operations ) throws KettleException { for ( RepositoryOperation operation : operations ) { switch ( operation ) { case EXECUTE_TRANSFORMATION: case EXECUTE_JOB: checkOperationAllowed( EXECUTE_CONTENT_ACTION ); ...
@Test public void noExceptionThrown_WhenOperationIsAllowed_CreateOperation() throws Exception { setOperationPermissions( IAbsSecurityProvider.SCHEDULE_CONTENT_ACTION, true ); provider.validateAction( RepositoryOperation.SCHEDULE_TRANSFORMATION ); }
public static <T> Bounded<T> from(BoundedSource<T> source) { return new Bounded<>(null, source); }
@Test public void testDisplayData() { SerializableBoundedSource boundedSource = new SerializableBoundedSource() { @Override public void populateDisplayData(DisplayData.Builder builder) { builder.add(DisplayData.item("foo", "bar")); } }; SerializableUnb...
public OpenTelemetry getOpenTelemetry() { return openTelemetrySdkReference.get(); }
@Test public void testServiceIsDisabledByDefault() throws Exception { @Cleanup var metricReader = InMemoryMetricReader.create(); @Cleanup var ots = OpenTelemetryService.builder() .builderCustomizer(getBuilderCustomizer(metricReader, Map.of())) .cluste...
@Override public UserCredentials findByUserId(TenantId tenantId, UUID userId) { return DaoUtil.getData(userCredentialsRepository.findByUserId(userId)); }
@Test public void testFindByUserId() { UserCredentials foundedUserCredentials = userCredentialsDao.findByUserId(SYSTEM_TENANT_ID, neededUserCredentials.getUserId().getId()); assertNotNull(foundedUserCredentials); assertEquals(neededUserCredentials, foundedUserCredentials); }
@Override public Iterator<QueryableEntry> iterator() { return new It(); }
@Test public void contains_matchingPredicate_inOtherResult() { Set<QueryableEntry> entries = generateEntries(100000); Set<QueryableEntry> otherIndexResult = new HashSet<>(); otherIndexResult.add(entries.iterator().next()); List<Set<QueryableEntry>> otherIndexedResults = new ArrayList...
public List<DataRecord> merge(final List<DataRecord> dataRecords) { Map<DataRecord.Key, DataRecord> result = new HashMap<>(); dataRecords.forEach(each -> { if (PipelineSQLOperationType.INSERT == each.getType()) { mergeInsert(each, result); } else if (PipelineSQLOp...
@Test void assertUpdatePrimaryKeyBeforeUpdatePrimaryKey() { DataRecord beforeDataRecord = mockUpdateDataRecord(1, 2, 10, 50); DataRecord afterDataRecord = mockUpdateDataRecord(2, 3, 10, 50); Collection<DataRecord> actual = groupEngine.merge(Arrays.asList(beforeDataRecord, afterDataRecord)); ...
@Audit @Operation(summary = "login", description = "User Login") @PostMapping(value = "/login") public ResponseEntity<LoginVO> login(@RequestBody LoginReq loginReq) { if (!StringUtils.hasText(loginReq.getUsername()) || !StringUtils.hasText(loginReq.getPassword())) { throw new ApiExceptio...
@Test void loginThrowsExceptionForMissingUsernameAndPassword() { LoginReq loginReq = new LoginReq(); loginReq.setUsername(""); loginReq.setPassword(""); ApiException exception = assertThrows(ApiException.class, () -> loginController.login(loginReq)); assertEquals(ApiExcepti...
public static WhereSegment bind(final WhereSegment segment, final SQLStatementBinderContext binderContext, final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) { return new WhereSegment(segmen...
@Test void assertBind() { SQLStatementBinderContext sqlStatementBinderContext = mock(SQLStatementBinderContext.class); WhereSegment expectedWhereSegment = new WhereSegment(1, 2, mock(ExpressionSegment.class)); Map<String, TableSegmentBinderContext> tableBinderContexts = new HashMap<>(); ...
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testLoadBalancerSheddingConditionHitCountThreshold() { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = setupContext(); int max = 3; ctx.brokerConfiguration() .setLoadBalan...
@Override public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException { throw new UnsupportedOperationException("Do not support subscribe service by UDP, please use gRPC replaced."); }
@Test void testSubscribe() throws Exception { assertThrows(UnsupportedOperationException.class, () -> { String groupName = "group1"; String serviceName = "serviceName"; String clusters = "clusters"; //when clientProxy.subscribe(service...
@Override public void process() { JMeterContext context = getThreadContext(); Sampler sam = context.getCurrentSampler(); SampleResult res = context.getPreviousResult(); HTTPSamplerBase sampler; HTTPSampleResult result; if (!(sam instanceof HTTPSamplerBase) || !(res in...
@Test public void testNullResult() throws Exception { jmctx.setCurrentSampler(makeContext("http://www.apache.org/subdir/previous.html")); jmctx.setPreviousResult(null); parser.process(); // should do nothing }
public boolean isValidatedPath(final String path) { return pathPattern.matcher(path).find(); }
@Test void assertIsNotValidatedPath() { assertFalse(nodePath.isValidatedPath("/metadata/foo_db/rules/bar/tables/foo_table")); }
public CustomToggle turnOff(String ability) { baseMapping.put(ability, OFF); return this; }
@Test public void canTurnOffAbilities() { toggle = new CustomToggle().turnOff(DefaultAbilities.CLAIM); customBot = new DefaultBot(null, EMPTY, db, toggle); customBot.onRegister(); assertFalse(customBot.getAbilities().containsKey(DefaultAbilities.CLAIM)); }
public static String findAddress(List<NodeAddress> addresses, NodeAddressType preferredAddressType) { if (addresses == null) { return null; } Map<String, String> addressMap = addresses.stream() .collect(Collectors.toMap(NodeAddress::getType, NodeAddress::getAddres...
@Test public void testFindAddressesNull() { List<NodeAddress> addresses = null; String address = NodeUtils.findAddress(addresses, null); assertThat(address, is(CoreMatchers.nullValue())); }
public void writeInt1(final int value) { byteBuf.writeByte(value); }
@Test void assertWriteInt1() { new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeInt1(1); verify(byteBuf).writeByte(1); }
P current() { return current; }
@Test void shouldResultNullWhenCurrentCalledWithoutNext() { assertNull(publicationGroup.current()); }
@Override public Set<Path> getPaths(ElementId src, ElementId dst, LinkWeigher weigher) { checkNotNull(src, ELEMENT_ID_NULL); checkNotNull(dst, ELEMENT_ID_NULL); LinkWeigher internalWeigher = weigher != null ? weigher : DEFAULT_WEIGHER; // Get the source and destination edge locatio...
@Test public void testSelfPaths() { HostId host = hid("12:34:56:78:90:ab/1"); Set<Path> paths = service.getPaths(host, host, new TestWeigher()); assertThat(paths, hasSize(1)); Path path = paths.iterator().next(); assertThat(path, not(nullValue())); assertThat(path.lin...
@Override public String getName() { return _name; }
@Test public void testShaTransformFunction() { ExpressionContext expression = RequestContextUtils.getExpression(String.format("sha(%s)", BYTES_SV_COLUMN)); TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap); assertTrue(transformFunction instanceof ScalarTransfor...
public V put(final int key, final V value) { final Entry<V>[] table = this.table; final int index = HashUtil.indexFor(key, table.length, mask); for (Entry<V> e = table[index]; e != null; e = e.hashNext) { if (e.key == key) { moveToTop(e); return e.set...
@Test public void forEachProcedure() { final IntLinkedHashMap<String> tested = new IntLinkedHashMap<>(); for (int i = 0; i < 100000; ++i) { tested.put(i, Integer.toString(i)); } final int[] ii = {0}; tested.forEachKey(object -> { ii[0]++; r...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void shouldNotHaveNullNamedTwoOptionOnAggregate() { assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(MockInitializer.STRING_INIT, (Named) null)); }
@Override public void loadGlue(Glue glue, List<URI> gluePaths) { GlueAdaptor glueAdaptor = new GlueAdaptor(lookup, glue); gluePaths.stream() .filter(gluePath -> CLASSPATH_SCHEME.equals(gluePath.getScheme())) .map(ClasspathSupport::packageName) .map(cl...
@Test void detects_subclassed_glue_and_throws_exception() { Executable testMethod = () -> backend.loadGlue(glue, asList(URI.create("classpath:io/cucumber/java/steps"), URI.create("classpath:io/cucumber/java/incorrectlysubclassedsteps"))); InvalidMethodException expectedThrown = assertThr...
@Override public ExecuteContext doAfter(ExecuteContext context) { if (isHasMethodLoadSpringFactories()) { // 仅当在高版本采用LoadSpringFactories的方式注入, 高版本存在缓存会更加高效, 仅需注入一次 if (IS_INJECTED.compareAndSet(false, true)) { injectConfigurations(context.getResult()); } ...
@Test public void doAfterLowVersion() throws NoSuchMethodException, IllegalAccessException { // lowVersionTesting final SpringFactoriesInterceptor lowVersionInterceptor = new SpringFactoriesInterceptor(); hasMethodLoadSpringFactoriesFiled.set(lowVersionInterceptor, Boolean.FALSE); Ex...