focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@VisibleForTesting synchronized void updateStateStore() { String routerId = router.getRouterId(); if (routerId == null) { LOG.error("Cannot heartbeat for router: unknown router id"); return; } if (isStoreAvailable()) { RouterStore routerStore = router.getRouterStateManager(); t...
@Test public void testStateStoreUnavailable() throws IOException { curatorFramework.close(); testingServer.stop(); router.getStateStore().stop(); // The driver is not ready assertFalse(router.getStateStore().isDriverReady()); // Do a heartbeat, and no exception thrown out RouterHeartbeatS...
@SuppressWarnings("deprecation") public boolean setSocketOpt(int option, Object optval) { final ValueReference<Boolean> result = new ValueReference<>(false); switch (option) { case ZMQ.ZMQ_SNDHWM: sendHwm = (Integer) optval; if (sendHwm < 0) { thro...
@Test(expected = IllegalArgumentException.class) public void testHeartbeatTtlOverflow() { options.setSocketOpt(ZMQ.ZMQ_HEARTBEAT_TTL, 655400); }
public static void saveStartType() { try { Storage storage = new Storage(Config.meta_dir + "/image"); String hostType = useFqdn ? HostType.FQDN.toString() : HostType.IP.toString(); storage.writeFeStartFeHostType(hostType); } catch (IOException e) { LOG.err...
@Test public void testSaveStartType() throws FileNotFoundException, IOException { Config.meta_dir = "feOpTestDir2"; String metaPath = Config.meta_dir + "/"; // fqdn File dir = new File(metaPath); deleteDir(dir); mkdir(false, metaPath); FrontendOptions.saveStar...
@Override public GoApiResponse submit(final GoApiRequest request) { if (requestProcessorRegistry.canProcess(request)) { try { GoPluginApiRequestProcessor processor = requestProcessorRegistry.processorFor(request); return processor.process(pluginDescriptor, request...
@Test void shouldHandleExceptionThrownByProcessor() { String api = "api-uri"; GoPluginApiRequestProcessor processor = mock(GoPluginApiRequestProcessor.class); GoApiRequest goApiRequest = mock(GoApiRequest.class); GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class); ...
public static Expression normalize(Expression expression) { if (expression instanceof NotExpression) { NotExpression not = (NotExpression) expression; if (not.getValue() instanceof ComparisonExpression && ((ComparisonExpression) not.getValue()).getOperator() != IS_DISTINCT_FROM) { ...
@Test public void testNormalize() { assertNormalize(new ComparisonExpression(EQUAL, name("a"), new LongLiteral("1"))); assertNormalize(new IsNullPredicate(name("a"))); assertNormalize(new NotExpression(new LikePredicate(name("a"), new StringLiteral("x%"), Optional.empty()))); ass...
public static void deleteQuietly(File file) { Objects.requireNonNull(file, "file"); FileUtils.deleteQuietly(file); }
@Test void deleteQuietly() throws IOException { File tmpFile = DiskUtils.createTmpFile(UUID.randomUUID().toString(), ".ut"); DiskUtils.deleteQuietly(tmpFile); assertFalse(tmpFile.exists()); }
void precheckMaxResultLimitOnLocalPartitions(String mapName) { // check if feature is enabled if (!isPreCheckEnabled) { return; } // limit number of local partitions to check to keep runtime constant PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa...
@Test(expected = QueryResultSizeExceededException.class) public void testLocalPreCheckEnabledWitPartitionOverLimit() { int[] partitionsSizes = {1090}; populatePartitions(partitionsSizes); initMocksWithConfiguration(200000, 1); limiter.precheckMaxResultLimitOnLocalPartitions(ANY_MAP_...
public void setResource(Resource resource) { this.resource = resource; }
@Test void testSetResource() { Resource resource = new Resource("", "", "", "", new Properties()); assertNull(authContext.getResource()); authContext.setResource(resource); assertSame(resource, authContext.getResource()); }
String formatsTimeZone(TimeZone tz) { // package-private for test. int seconds = Math.abs(tz.getOffset(System.currentTimeMillis())) / 1000; int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; return (tz.getRawOffset() < 0 ? "-" : "+") + String.format("%02d:%02d", hou...
@Test public void testTimeZone() { IQEntityTimeHandler iqEntityTimeHandler = new IQEntityTimeHandler(); assertEquals(iqEntityTimeHandler.formatsTimeZone(TimeZone.getTimeZone("GMT-8:00")), "-08:00"); }
public ProviderGroup add(ProviderInfo providerInfo) { if (providerInfo == null) { return this; } ConcurrentHashSet<ProviderInfo> tmp = new ConcurrentHashSet<ProviderInfo>(providerInfos); tmp.add(providerInfo); // 排重 this.providerInfos = new ArrayList<ProviderInfo>(tmp...
@Test public void add() throws Exception { ProviderGroup pg = new ProviderGroup("xxx", null); Assert.assertTrue(pg.size() == 0); pg.add(null); Assert.assertTrue(pg.size() == 0); pg.add(ProviderHelper.toProviderInfo("127.0.0.1:12200")); Assert.assertTrue(pg.size() ==...
public static Executor scopeToJob(JobID jobID, Executor executor) { checkArgument(!(executor instanceof MdcAwareExecutor)); return new MdcAwareExecutor<>(executor, asContextData(jobID)); }
@Test void testScopeScheduledExecutorService() throws Exception { ScheduledExecutorService ses = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); try { assertJobIDLogged( jobID -> MdcUtils.scopeToJob(jobID,...
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag(TagConstants.DB_SYSTEM, "sql"); Object body = exchange.getIn().getBody(); if (body instanceof String) { span.setTag(TagConstants.DB_STATE...
@Test public void testPre() { Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("test"); Mockito.when(exchange.getIn()).thenRet...
@Override public String toString() { String bounds = printExtendsClause() ? " extends " + joinTypeNames(upperBounds) : ""; return getClass().getSimpleName() + '{' + getName() + bounds + '}'; }
@Test public void toString_unbounded() { @SuppressWarnings("unused") class Unbounded<NAME> { } JavaTypeVariable<JavaClass> typeVariable = new ClassFileImporter().importClass(Unbounded.class).getTypeParameters().get(0); assertThat(typeVariable.toString()) .co...
@Override public int getPriority() { return 6; }
@Test public void testGetPriority() { assertEquals(6, roundRobinLoadBalancerProvider.getPriority()); }
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(String topic, long offset, int queueId, String brokerName, boolean deCompressBody) { MessageStore messageStore = brokerController.getMessageStoreByBrokerName(brokerName); if (messageStore != null) { return messageS...
@Test public void getMessageAsyncTest_remoteStore_addressNotFound() throws Exception { when(brokerController.getMessageStoreByBrokerName(any())).thenReturn(null); // just test address not found, since we have complete tests of getMessageFromRemoteAsync() when(topicRouteInfoManager.findBroke...
public static Message toProto(final Map<?, ?> inputData, final Message defaultInstance) { ObjectHelper.notNull(inputData, "inputData"); ObjectHelper.notNull(defaultInstance, "defaultInstance"); final Descriptor descriptor = defaultInstance.getDescriptorForType(); final Builder target = ...
@Test public void testIfThrowsErrorInCaseNestedMessageNotMap() { final Map<String, Object> input = new HashMap<>(); input.put("name", "Martin"); input.put("id", 1234); input.put("address", "wrong address"); final AddressBookProtos.Person defaultInstance = AddressBookProtos....
@Override public List<ResourceReference> getResourceDependencies( TransMeta transMeta, StepMeta stepInfo ) { List<ResourceReference> references = new ArrayList<>( 5 ); String realFilename = transMeta.environmentSubstitute( transformationPath ); ResourceReference reference = new ResourceReference( stepInfo...
@Test public void testGetResourceDependencies() { String stepId = "KafkConsumerInput"; String path = "/home/bgroves/fake.ktr"; StepMeta stepMeta = new StepMeta(); stepMeta.setStepID( stepId ); StuffStreamMeta inputMeta = new StuffStreamMeta(); List<ResourceReference> resourceDependencies = in...
public FEELFnResult<BigDecimal> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } FEELFnResult<BigDecimal> s = sum.invoke( list ); Function<FEELEven...
@Test void invokeNumberFloat() { FunctionTestUtil.assertResult(meanFunction.invoke(Arrays.asList(10.1f)), BigDecimal.valueOf(10.1)); }
public void validate() { final String[] patterns = value().toArray(new String[0]); Automaton automaton = Regex.simpleMatchToAutomaton(patterns); final CharacterRunAutomaton characterRunAutomaton = new CharacterRunAutomaton(automaton); final boolean isHostMatching = characterRunAutomaton....
@Test void testRegexValidationOK() { final RemoteReindexAllowlist allowlist = new RemoteReindexAllowlist(URI.create("http://10.0.1.28:9200"), "10.0.1.*:9200"); allowlist.validate(); }
@Override public DataSink createDataSink(Context context) { FactoryHelper.createFactoryHelper(this, context) .validateExcept(TABLE_CREATE_PROPERTIES_PREFIX, SINK_PROPERTIES_PREFIX); StarRocksSinkOptions sinkOptions = buildSinkConnectorOptions(context.getFactoryConfig...
@Test void testPrefixRequireOption() { DataSinkFactory sinkFactory = FactoryDiscoveryUtils.getFactoryByIdentifier("starrocks", DataSinkFactory.class); Assertions.assertThat(sinkFactory).isInstanceOf(StarRocksDataSinkFactory.class); Configuration conf = Config...
public EnumNode() { }
@Test void testEnumNode() { MyNode n = new MyNode(); assertNull(n.getValue()); assertEquals("(null)", n.toString()); assertTrue(n.doSetValue("ONE")); assertEquals("ONE", n.getValue()); assertEquals("ONE", n.toString()); assertFalse(n.doSetValue("THREE")); ...
@Override public void checkBeforeUpdate(final CreateReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkCreation(database, sqlStatement.getRules(), null == rule ? null : rule.getConfiguration(), sqlStatement.isIfNotExists()); }
@Test void assertCheckSQLStatementWithIfNotExists() { ReadwriteSplittingRuleSegment staticSegment = new ReadwriteSplittingRuleSegment("readwrite_ds_0", "write_ds_0", Arrays.asList("read_ds_2", "read_ds_3"), new AlgorithmSegment(null, new Properties())); ReadwriteSplittingRule rule = ...
static <K, V> CacheConfig<K, V> createCacheConfig(HazelcastClientInstanceImpl client, CacheConfig<K, V> newCacheConfig, boolean urgent) { try { String nameWithPrefix = newCacheConfig.getNameWithPrefix(); int partitionId = client.getCl...
@Test(expected = IllegalArgumentException.class) public void testCreateCacheConfig_rethrowsExceptions() { createCacheConfig(exceptionThrowingClient, newCacheConfig, false); }
public void generateAcknowledgementPayload( MllpSocketBuffer mllpSocketBuffer, byte[] hl7MessageBytes, String acknowledgementCode) throws MllpAcknowledgementGenerationException { generateAcknowledgementPayload(mllpSocketBuffer, hl7MessageBytes, acknowledgementCode, null); }
@Test public void testGenerateAcknowledgementPayloadWithoutEndOfSegment() throws Exception { String junkMessage = "MSH|^~\\&|REQUESTING|ICE|INHOUSE|RTH00|20161206193919||ORM^O01|00001|D|2.3|||||||" + "PID|1||ICE999999^^^ICE^ICE||Testpatient^Testy^^^Mr||19740401|M|||123 Barrel Dr...
public boolean isZero() { return value.compareTo(BigDecimal.ZERO) == 0; }
@Test void testIsZero() { final Resource resource1 = new TestResource(0.0); final Resource resource2 = new TestResource(1.0); assertThat(resource1.isZero()).isTrue(); assertThat(resource2.isZero()).isFalse(); }
public final DisposableServer bindNow() { return bindNow(Duration.ofSeconds(45)); }
@Test void testBindTimeoutLongOverflow() { assertThatExceptionOfType(ArithmeticException.class) .isThrownBy(() -> new TestServerTransport(Mono.never()).bindNow(Duration.ofMillis(Long.MAX_VALUE))); }
String getServiceProviderCertificate() { return configuration.get(SERVICE_PROVIDER_CERTIFICATE).orElseThrow(() -> new IllegalArgumentException("Service provider certificate is missing")); }
@Test public void return_service_provider_certificate() { settings.setProperty("sonar.auth.saml.sp.certificate.secured", "my_certificate"); assertThat(underTest.getServiceProviderCertificate()).isEqualTo("my_certificate"); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } JsonPrimitive other = (JsonPrimitive) obj; if (value == null) { return other.value == null; } if (isIntegral(this) && isI...
@Test public void testEqualsIntegerAndBigInteger() { JsonPrimitive a = new JsonPrimitive(5L); JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); assertWithMessage("%s not equals %s", a, b).that(a.equals(b)).isFalse(); }
@Override public PageResult<NotifyTemplateDO> getNotifyTemplatePage(NotifyTemplatePageReqVO pageReqVO) { return notifyTemplateMapper.selectPage(pageReqVO); }
@Test public void testGetNotifyTemplatePage() { // mock 数据 NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class, o -> { // 等会查询到 o.setName("芋头"); o.setCode("test_01"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCreateTime(b...
public static SqlAggregation from(QueryDataType operandType, boolean distinct) { SqlAggregation aggregation = from(operandType); return distinct ? new DistinctSqlAggregation(aggregation) : aggregation; }
@Test public void test_serialization() { SqlAggregation original = AvgSqlAggregations.from(QueryDataType.DECIMAL, false); original.accumulate(BigDecimal.ONE); InternalSerializationService ss = new DefaultSerializationServiceBuilder().build(); SqlAggregation serialized = ss.toObject(...
public static DataMap convertToDataMap(Map<String, Object> queryParams) { return convertToDataMap(queryParams, Collections.<String, Class<?>>emptyMap(), AllProtocolVersions.RESTLI_PROTOCOL_1_0_0.getProtocolVersion(), RestLiProjectionDataMapSerializer.DEFAULT_SERIALIZER); }
@Test public void testPreSerializedProjectionParams() { Map<String, Object> queryParams = new HashMap<>(); queryParams.put(RestConstants.FIELDS_PARAM, "fields"); queryParams.put(RestConstants.PAGING_FIELDS_PARAM, "paging"); queryParams.put(RestConstants.METADATA_FIELDS_PARAM, "metadata"); DataM...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { return payload.readStringFixByBytes(readLengthFromMeta(columnDef.getColumnMeta(), payload)); }
@Test void assertReadWithUnknownMetaValue() { columnDef.setColumnMeta(5); assertThrows(UnsupportedSQLOperationException.class, () -> new MySQLBlobBinlogProtocolValue().read(columnDef, payload)); }
@Override public Collection<SchemaMetaData> load(final MetaDataLoaderMaterial material) throws SQLException { try (Connection connection = material.getDataSource().getConnection()) { Collection<String> schemaNames = SchemaMetaDataLoader.loadSchemaNames(connection, TypedSPILoader.getService(Datab...
@Test void assertLoadWithoutTables() throws SQLException { DataSource dataSource = mockDataSource(); ResultSet schemaResultSet = mockSchemaMetaDataResultSet(); when(dataSource.getConnection().getMetaData().getSchemas()).thenReturn(schemaResultSet); ResultSet tableResultSet = mockTabl...
@Override public List<Class<? extends Event>> subscribeTypes() { List<Class<? extends Event>> result = new LinkedList<>(); result.add(ClientOperationEvent.ClientRegisterServiceEvent.class); result.add(ClientOperationEvent.ClientDeregisterServiceEvent.class); result.add(ClientOperatio...
@Test void testSubscribeTypes() { List<Class<? extends Event>> classes = clientServiceIndexesManager.subscribeTypes(); assertNotNull(classes); assertEquals(5, classes.size()); }
@Override protected void requestSubpartitions() throws IOException { boolean retriggerRequest = false; boolean notifyDataAvailable = false; // The lock is required to request only once in the presence of retriggered requests. synchronized (requestLock) { checkState(!isR...
@Test void testConcurrentReleaseAndRetriggerPartitionRequest() throws Exception { final SingleInputGate gate = createSingleInputGate(1); ResultPartitionManager partitionManager = mock(ResultPartitionManager.class); when(partitionManager.createSubpartitionView( any(Re...
@Override public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) { Collection<Stri...
@Test void assertDecideWhenAllTablesIsBindingTables() { SelectStatementContext select = createStatementContext(); when(select.isContainsJoinQuery()).thenReturn(true); ShardingRule shardingRule = createShardingRule(); ShardingSphereDatabase database = createDatabase(shardingRule); ...
public ConnectionDetails createConnectionDetails( String scheme ) { try { ConnectionProvider<? extends ConnectionDetails> provider = connectionProviders.get( scheme ); return provider.getClassType().newInstance(); } catch ( Exception e ) { logger.error( "Error in createConnectionDetails {}", s...
@Test public void testCreateConnectionDetails() { addProvider(); assertNotNull( connectionManager.createConnectionDetails( TestConnectionWithBucketsProvider.SCHEME ) ); }
public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(Collections.singletonList(address)); }
@Test public void removeWatchedAddress() { Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, TESTNET); wallet.addWatchedAddress(watchedAddress); wallet.removeWatchedAddress(watchedAddress); assertFalse(wallet.isAddressWatched(watchedAddress)); }
public static <InputT> KeyByBuilder<InputT> of(PCollection<InputT> input) { return named(null).of(input); }
@Test public void testWindow_applyIfNot() { final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings()); final PCollection<KV<String, Long>> reduced = ReduceByKey.of(dataset) .keyBy(s -> s) .valueBy(s -> 1L) .combineBy(Sums.ofLongs()) ...
@Override public int getOrder() { return PluginEnum.LOGGING_CONSOLE.getCode(); }
@Test public void testGetOrder() { assertEquals(loggingConsolePlugin.getOrder(), PluginEnum.LOGGING_CONSOLE.getCode()); }
@Override public MethodDescriptor<?, ?> methodDescriptor() { return methodDescriptor; }
@Test void methodDescriptor() { assertThat(request.methodDescriptor()).isSameAs(methodDescriptor); }
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { expectCaseSensitiveDefaultCollation(connection); if (state == DatabaseCharsetChecker.State.UPGRADE || state == DatabaseCharsetChecker.State.STARTUP) { repairColumns(connection); } }
@Test public void fresh_install_fails_if_default_collation_is_not_CS_AS() throws SQLException { answerDefaultCollation("Latin1_General_CI_AI"); assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL)) .isInstanceOf(MessageException.class) .hasMessage("Dat...
public SendResult putMessageToRemoteBroker(MessageExtBrokerInner messageExt, String brokerNameToSend) { if (this.brokerController.getBrokerConfig().getBrokerName().equals(brokerNameToSend)) { // not remote broker return null; } final boolean isTransHalfMessage = TransactionalMessageU...
@Test public void testPutMessageToRemoteBroker_specificBrokerName_addressNotFound() throws Exception { MessageExtBrokerInner message = new MessageExtBrokerInner(); message.setTopic(TEST_TOPIC); TopicPublishInfo publishInfo = mockTopicPublishInfo(BROKER_NAME); when(topicRouteInfoManag...
@Override public Collection<ParameterRewriter> getParameterRewriters() { Collection<ParameterRewriter> result = new LinkedList<>(); addParameterRewriter(result, new EncryptAssignmentParameterRewriter(encryptRule)); addParameterRewriter(result, new EncryptPredicateParameterRewriter(encryptRul...
@Test void assertGetParameterRewritersWhenPredicateIsNeedRewrite() { EncryptRule encryptRule = mock(EncryptRule.class, RETURNS_DEEP_STUBS); when(encryptRule.findEncryptTable("t_order").isPresent()).thenReturn(true); SelectStatementContext sqlStatementContext = mock(SelectStatementContext.cla...
public PendingTransactionFilter(Web3j web3j, Callback<String> callback) { super(web3j, callback); }
@Test public void testPendingTransactionFilter() throws Exception { EthLog ethLog = objectMapper.readValue( "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":[\"0x31c2342b1e0b8ffda1507fbffddf213c4b3c1e819ff6a84b943faabb0ebf2403\",\"0xccc0d2e07c1febcaca0c3341c4e1268204b06fefa4...
public void forEachInt(final IntConsumer action) { if (sizeOfArrayValues > 0) { final int[] values = this.values; for (final int v : values) { if (MISSING_VALUE != v) { action.accept(v); } ...
@Test void forEachIntIsANoOpIfTheSetIsEmpty() { final IntConsumer consumer = mock(IntConsumer.class); testSet.forEachInt(consumer); verifyNoInteractions(consumer); }
@Activate public void activate(ComponentContext context) { cfgService.registerProperties(getClass()); alarmsExecutor = newScheduledThreadPool(CORE_POOL_SIZE, groupedThreads("onos/pollingalarmprovider", ...
@Test public void activate() throws Exception { assertFalse("Provider should be registered", providerRegistry.getProviders().contains(provider.id())); assertEquals("Device listener should be added", 1, deviceListeners.size()); assertEquals("Incorrect alarm provider service", alarmProviderSer...
@GetMapping("/price") public String getPrice() { return priceService.getPrice(); }
@Test void getPriceTest() { var priceController = new PriceController(new PriceServiceImpl()); var price = priceController.getPrice(); assertEquals("20", price); }
@Override public void define(WebService.NewController controller) { controller .createAction(VALIDATION_INIT_KEY) .setInternal(true) .setPost(false) .setHandler(ServletFilterHandler.INSTANCE) .setDescription("Initiate a SAML request to the identity Provider for configuration validati...
@Test public void verify_definition() { String controllerKey = "foo"; WebService.Context context = new WebService.Context(); WebService.NewController newController = context.createController(controllerKey); underTest.define(newController); newController.done(); WebService.Action validationIni...
@Override public boolean publishConfig(String dataId, String group, String content) throws NacosException { return publishConfig(dataId, group, content, ConfigType.getDefaultType().getType()); }
@Test void testPublishConfig() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; String namespace = ""; String type = ConfigType.getDefaultType().getType(); Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, nul...
public static Tags empty() { return new Tags(Set.of()); }
@Test public void testEmpty() { assertEquals(Tags.empty(), Tags.fromString(null)); assertEquals(Tags.empty(), Tags.fromString("")); assertEquals(Tags.empty(), Tags.fromString(" ")); }
@Override public void execute(String commandName, BufferedReader reader, BufferedWriter writer) throws Py4JException, IOException { String subCommand = safeReadLine(reader); boolean unknownSubCommand = false; String param = reader.readLine(); String returnCommand = null; try { final String[] names; ...
@Test public void testDirMethods() throws Exception { String inputCommand = "m\n" + target + "\ne\n"; assertTrue(gateway.getBindings().containsKey(target)); command.execute("d", new BufferedReader(new StringReader(inputCommand)), writer); Set<String> methods = convertResponse(sWriter.toString()); assertEqua...
@Override public Result analysis( final Result result, final StreamAccessLogsMessage.Identifier identifier, final HTTPAccessLogEntry entry, final Role role ) { switch (role) { case PROXY: return analyzeProxy(result, entry); case SID...
@Test public void testIngress2SidecarMetric() throws IOException { try (InputStreamReader isr = new InputStreamReader(getResourceAsStream("envoy-ingress2sidecar.msg"))) { StreamAccessLogsMessage.Builder requestBuilder = StreamAccessLogsMessage.newBuilder(); JsonFormat.parser().merge(...
@VisibleForTesting static Optional<String> getChildValue(@Nullable Xpp3Dom dom, String... childNodePath) { if (dom == null) { return Optional.empty(); } Xpp3Dom node = dom; for (String child : childNodePath) { node = node.getChild(child); if (node == null) { return Optional....
@Test public void testGetChildValue_nullValue() { Xpp3Dom root = new Xpp3Dom("root"); addXpp3DomChild(root, "foo", null); assertThat(MavenProjectProperties.getChildValue(root)).isEmpty(); assertThat(MavenProjectProperties.getChildValue(root, "foo")).isEmpty(); }
@Override public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { // 校验旧密码密码 validateOldPassword(id, reqVO.getOldPassword()); // 执行更新 AdminUserDO updateObj = new AdminUserDO().setId(id); updateObj.setPassword(encodePassword(reqVO.getNewPassword())); //...
@Test public void testUpdateUserPassword02_success() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); // 准备参数 Long userId = dbUser.getId(); String password = "yudao"; // mock 方法 when(passwordEncoder.encode(anyString()))...
public StatisticRange addAndMaxDistinctValues(StatisticRange other) { double newDistinctValues = max(distinctValues, other.distinctValues); return expandRangeWithNewDistinct(newDistinctValues, other); }
@Test public void testAddAndMaxDistinctValues() { assertEquals(unboundedRange(NaN).addAndMaxDistinctValues(unboundedRange(NaN)), unboundedRange(NaN)); assertEquals(unboundedRange(NaN).addAndMaxDistinctValues(unboundedRange(1)), unboundedRange(NaN)); assertEquals(unboundedRange(1).addAndM...
@Override public void exportData(JsonWriter writer) throws IOException { // version tag at the root writer.name(THIS_VERSION); writer.beginObject(); // clients list writer.name(CLIENTS); writer.beginArray(); writeClients(writer); writer.endArray(); writer.name(GRANTS); writer.beginArray(); wr...
@Test public void testExportGrants() throws IOException, ParseException { Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+00:00", Locale.ENGLISH); Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity....
@Override public Iterator<E> iterator() { return Iterators.transform(items.iterator(), serializer::decode); }
@Test public void testIterator() throws Exception { //Test iterator behavior (no order guarantees are made) Set<Integer> validationSet = Sets.newHashSet(); fillSet(10, this.set); fillSet(10, validationSet); set.iterator().forEachRemaining(item -> assertTrue("Items were mismat...
public static <T> PTransform<PCollection<T>, PCollection<KV<T, Long>>> perElement() { return new PerElement<>(); }
@Test @Category(NeedsRunner.class) @SuppressWarnings("unchecked") public void testCountPerElementBasic() { PCollection<String> input = p.apply(Create.of(WORDS)); PCollection<KV<String, Long>> output = input.apply(Count.perElement()); PAssert.that(output) .containsInAnyOrder( KV.o...
public IndexerDirectoryInformation parse(Path path) { if (!Files.exists(path)) { throw new IndexerInformationParserException("Path " + path + " does not exist."); } if (!Files.isDirectory(path)) { throw new IndexerInformationParserException("Path " + path + " is not a di...
@Test void testEmptyDataDir(@TempDir Path tempDir) { final IndexerDirectoryInformation result = parser.parse(tempDir); Assertions.assertThat(result).isNotNull(); Assertions.assertThat(result.nodes()).isEmpty(); }
public ApplicationBuilder addRegistries(List<? extends RegistryConfig> registries) { if (this.registries == null) { this.registries = new ArrayList<>(); } this.registries.addAll(registries); return getThis(); }
@Test void addRegistries() { RegistryConfig registry = new RegistryConfig(); ApplicationBuilder builder = new ApplicationBuilder(); builder.addRegistries(Collections.singletonList(registry)); Assertions.assertNotNull(builder.build().getRegistry()); Assertions.assertEquals(1, ...
@Override public <VAgg> KTable<K, VAgg> aggregate(final Initializer<VAgg> initializer, final Aggregator<? super K, ? super V, VAgg> adder, final Aggregator<? super K, ? super V, VAgg> subtractor, ...
@Test public void shouldThrowNullPointerOnAggregateWhenAdderIsNull() { assertThrows(NullPointerException.class, () -> groupedTable.aggregate( MockInitializer.STRING_INIT, null, MockAggregator.TOSTRING_REMOVER, Materialized.as("store"))); }
@Override public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { final Credentials credentials = authentication.get(); if(credentials.isAnonymousLogin()) { if(log.isDebugEnabled()) { log.debug(String.format("Connect with no...
@Test public void testConnectDefaultPath() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new S3Protocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/S3 (HTTPS).cy...
public static AggregateFunctionInitArguments createAggregateFunctionInitArgs( final int numInitArgs, final FunctionCall functionCall ) { return createAggregateFunctionInitArgs( numInitArgs, Collections.emptyList(), functionCall, KsqlConfig.empty(...
@Test public void shouldNotThrowIfSecondParamIsColArgAndIsNotALiteral() { // Given: when(functionCall.getArguments()).thenReturn(ImmutableList.of( new UnqualifiedColumnReferenceExp(ColumnName.of("Bob")), new UnqualifiedColumnReferenceExp(ColumnName.of("Col2")), new StringLi...
@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 testConvertCompressedObjectMessageToAmqpMessageWithAmqpValueBody() throws Exception { ActiveMQObjectMessage outbound = createObjectMessage(TEST_OBJECT_VALUE, true); outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_BINARY); outbound.onSend(); outbound...
public ModuleBuilder addRegistry(RegistryConfig registry) { if (this.registries == null) { this.registries = new ArrayList<>(); } this.registries.add(registry); return getThis(); }
@Test void addRegistry() { RegistryConfig registry = new RegistryConfig(); ModuleBuilder builder = ModuleBuilder.newBuilder(); builder.addRegistry(registry); Assertions.assertTrue(builder.build().getRegistries().contains(registry)); Assertions.assertEquals(1, builder.build()....
public static UserGroupInformation getUGIFromSubject(Subject subject) throws IOException { if (subject == null) { throw new KerberosAuthException(SUBJECT_MUST_NOT_BE_NULL); } if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) { throw new KerberosAuthException(SUBJECT_MUST_CONTA...
@Test (timeout = 30000) public void testGetUGIFromSubject() throws Exception { KerberosPrincipal p = new KerberosPrincipal("guest"); Subject subject = new Subject(); subject.getPrincipals().add(p); UserGroupInformation ugi = UserGroupInformation.getUGIFromSubject(subject); assertNotNull(ugi); ...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapViaMultimapRemoveAndGet() { final String tag = "map"; StateTag<MapState<byte[], Integer>> addr = StateTags.map(tag, ByteArrayCoder.of(), VarIntCoder.of()); MapState<byte[], Integer> mapViaMultiMapState = underTestMapViaMultimap.state(NAMESPACE, addr); final byte[] key...
public static String getStringInMillis(final Duration duration) { return duration.toMillis() + TimeUnit.MILLISECONDS.labels.get(0); }
@Test void testGetStringInMillis() { assertThat(TimeUtils.getStringInMillis(Duration.ofMillis(4567L))).isEqualTo("4567ms"); assertThat(TimeUtils.getStringInMillis(Duration.ofSeconds(4567L))).isEqualTo("4567000ms"); assertThat(TimeUtils.getStringInMillis(Duration.of(4567L, ChronoUnit.MICROS))...
TeamsMessage createTeamsMessage(EventNotificationContext ctx, TeamsEventNotificationConfig config) throws PermanentEventNotificationException { String messageTitle = buildDefaultMessage(ctx); String description = buildMessageDescription(ctx); String customMessage = null; String template ...
@Test public void createTeamsMessage() throws EventNotificationException { String expectedText = "**Alert Event Definition Test Title triggered:**\n"; String expectedSubtitle = "_Event Definition Test Description_"; TeamsMessage actual = teamsEventNotification.createTeamsMessage(eventNotific...
@Around("pageableCut()") public Object mapperAround(final ProceedingJoinPoint point) { // CHECKSTYLE:OFF try { Object query = point.getArgs()[0]; PageParameter pageParameter = (PageParameter) ReflectUtils.getFieldValue(query, "pageParameter"); if (Objects.isNull(p...
@Test public void testMapperAround() { MetaDataQuery metaDataQuery = new MetaDataQuery(); PageParameter pageParameter = new PageParameter(); MetaDataQuery[] metaDataQueries = {metaDataQuery}; /** * test null return. */ when(point.getArgs()).thenReturn(metaDa...
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@Test public void shouldNotAllowNullValueJoinerWithKeyOnTableLeftJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin(testTable, (ValueJoinerWithKey<? super String, ? super String, ? super String, ?>) null)); asse...
public Optional<YamlRuleConfiguration> swapToYamlRuleConfiguration(final Collection<RepositoryTuple> repositoryTuples, final Class<? extends YamlRuleConfiguration> toBeSwappedType) { RepositoryTupleEntity tupleEntity = toBeSwappedType.getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) ...
@Test void assertSwapToYamlRuleConfigurationWithInvalidNodeYamlRuleConfiguration() { Optional<YamlRuleConfiguration> actual = new RepositoryTupleSwapperEngine().swapToYamlRuleConfiguration( Collections.singleton(new RepositoryTuple("/invalid", "foo")), NodeYamlRuleConfiguration.class); ...
public static Statement sanitize( final Statement node, final MetaStore metaStore) { return sanitize(node, metaStore, true); }
@Test public void shouldThrowIfRightJoinSourceDoesNotExist() { // Given: final Statement stmt = givenQuery("SELECT * FROM TEST1 JOIN UNKNOWN" + " ON test1.col1 = UNKNOWN.col1;"); // When: final Exception e = assertThrows( KsqlException.class, () -> AstSanitizer.sanitize(stmt, ...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceInfo that = (ServiceInfo) o; if (ports != null ? !ports.equals(that.ports) : that.ports != null) return false; if (properties != null ? ...
@Test public void testEquals() { String commonConfigId = "common-config-id"; String commonHostName = "common-host"; ServiceInfo a = new ServiceInfo("0", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, commonHostName); ServiceInfo b = new ServiceInfo("0", ...
@Override public void reportConsumerRunningInfo(TreeMap<String, ConsumerRunningInfo> criTable) { { boolean result = ConsumerRunningInfo.analyzeSubscription(criTable); if (!result) { logger.info(String.format(LOG_NOTIFY + "reportConsumerRunningInfo...
@Test public void testReportConsumerRunningInfo() { TreeMap<String, ConsumerRunningInfo> criTable = new TreeMap<>(); ConsumerRunningInfo consumerRunningInfo = new ConsumerRunningInfo(); consumerRunningInfo.setSubscriptionSet(new TreeSet<>()); consumerRunningInfo.setStatusTable(new Tr...
<T> List<List<T>> computePaths(Translator<Step, T> translator) { List<List<T>> taskPaths = new ArrayList<>(); while (!startNodes.isEmpty()) { Iterator<GraphNode> iterator = startNodes.iterator(); GraphNode start = iterator.next(); iterator.remove(); List<T> path = getPath(start, translat...
@Test public void testComputePaths() throws Exception { WorkflowCreateRequest request = loadObject( "fixtures/workflows/request/sample-conditional-wf.json", WorkflowCreateRequest.class); WorkflowGraph graph = WorkflowGraph.build( request.getWorkflow(), WorkflowGraph.com...
public static TbMathArgumentValue fromString(String value) { try { return new TbMathArgumentValue(Double.parseDouble(value)); } catch (NumberFormatException ne) { throw new RuntimeException("Can't convert value '" + value + "' to double!"); } }
@Test public void test_fromString_thenOK() { var value = "5.0"; TbMathArgumentValue result = TbMathArgumentValue.fromString(value); Assertions.assertNotNull(result); Assertions.assertEquals(5.0, result.getValue(), 0d); }
public static Type convertType(TypeInfo typeInfo) { switch (typeInfo.getOdpsType()) { case BIGINT: return Type.BIGINT; case INT: return Type.INT; case SMALLINT: return Type.SMALLINT; case TINYINT: ret...
@Test public void testConvertTypeCaseTinyint() { TypeInfo typeInfo = TypeInfoFactory.TINYINT; Type result = EntityConvertUtils.convertType(typeInfo); assertEquals(Type.TINYINT, result); }
@Override public BufferedSink writeUtf8(String string) throws IOException { if (closed) throw new IllegalStateException("closed"); buffer.writeUtf8(string); return emitCompleteSegments(); }
@Test public void bytesNotEmittedToSinkWithoutFlush() throws Exception { Buffer sink = new Buffer(); BufferedSink bufferedSink = new RealBufferedSink(sink); bufferedSink.writeUtf8("abc"); assertEquals(0, sink.size()); }
@Override public void configure(Map<String, ?> props) { final SimpleConfig config = new SimpleConfig(CONFIG_DEF, props); casts = parseFieldTypes(config.getList(SPEC_CONFIG)); wholeValueCastType = casts.get(WHOLE_VALUE_CAST); schemaUpdateCache = new SynchronizedCache<>(new LRUCache<>(...
@Test public void testUnsupportedTargetType() { assertThrows(ConfigException.class, () -> xformKey.configure(Collections.singletonMap(Cast.SPEC_CONFIG, "foo:bytes"))); }
public EvictionConfig getEvictionConfig() { return evictionConfig; }
@Test public void testSetEvictionPolicy() { assertEquals(EvictionPolicy.LRU, new MapConfig().getEvictionConfig() .setEvictionPolicy(EvictionPolicy.LRU) .getEvictionPolicy()); }
@Override public Set<TransferItem> find(final CommandLine input, final TerminalAction action, final Path remote) { if(input.getOptionValues(action.name()).length == 2) { switch(action) { case download: return new DownloadTransferItemFinder().find(input, action...
@Test public void testNoLocalInOptionsUploadFile() throws Exception { final CommandLineParser parser = new PosixParser(); final CommandLine input = parser.parse(TerminalOptionsBuilder.options(), new String[]{"--upload", "rackspace://cdn.cyberduck.ch/remote"}); final Set<TransferItem> found ...
public static void writeText(File target, String text) { target.getParentFile().mkdirs(); GFileUtils.writeFile(text, target); }
@Test public void writesTextOnNonExistentFile() throws IOException { Path tempDirectory = Files.createTempDirectory(getClass().getSimpleName()); File f = tempDirectory.resolve("foo/bar/baz.txt").toFile(); f.delete(); f.getParentFile().delete(); assertFalse(f.exists()); assertFalse(f.getPar...
public static String desensitizeSingleKeyword(final boolean desensitized, final String keyWord, final String source, final KeyWordMatch keyWordMatch, final String desensitizedAlg) { if (StringUtils.hasLength(source) && desensitized && keyWordMatch.matches(keyWord)) { ...
@Test public void desensitizeSingleKeywordTest() { String noDesensitizedData = DataDesensitizeUtils.desensitizeSingleKeyword(false, "name", JSON_TEXT, keyWordMatch, DataDesensitizeEnum.MD5_ENCRYPT.getDataDesensitizeAlg()); Assertions.assertEquals(JSON_TEXT, noDesensitizedData); ...
public static Properties updateSplitSchema(Properties splitSchema, List<HiveColumnHandle> columns) { requireNonNull(splitSchema, "splitSchema is null"); requireNonNull(columns, "columns is null"); // clone split properties for update so as not to affect the original one Properties up...
@Test(expectedExceptions = NullPointerException.class) public void shouldThrowNullPointerExceptionWhenColumnsIsNull() { updateSplitSchema(new Properties(), null); }
static boolean isTLSv13Cipher(String cipher) { // See https://tools.ietf.org/html/rfc8446#appendix-B.4 return TLSV13_CIPHERS.contains(cipher); }
@Test public void testIsTLSv13Cipher() { assertTrue(SslUtils.isTLSv13Cipher("TLS_AES_128_GCM_SHA256")); assertTrue(SslUtils.isTLSv13Cipher("TLS_AES_256_GCM_SHA384")); assertTrue(SslUtils.isTLSv13Cipher("TLS_CHACHA20_POLY1305_SHA256")); assertTrue(SslUtils.isTLSv13Cipher("TLS_AES_128_...
@Override public boolean passes(final String artifactType) { return StringUtils.isNotEmpty(regex) && StringUtils.isNotEmpty(artifactType) && artifactType.matches(regex); }
@Test public void testPasses() { String artifactType = null; ArtifactTypeExcluded instance = new ArtifactTypeExcluded(null); boolean expResult = false; boolean result = instance.passes(artifactType); assertEquals(expResult, result); artifactType = "pom"; inst...
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology) // must be verified. expectUtf8AsDefault(connection); if (state == DatabaseCharse...
@Test public void column_charset_can_be_empty() throws Exception { answerDefaultCharset("utf8"); answerColumns(asList( new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"}, new String[] {TABLE_PROJECTS, COLUMN_NAME, "" /* unset -> uses db collation */})); // no error assertThatCode(() -> under...
public QueryCacheEventData getEventData() { return eventData; }
@Test public void testGetEventData() { assertEquals(queryCacheEventData, singleIMapEvent.getEventData()); }
public ClientSession toClientSession() { return new ClientSession( parseServer(server), user, source, Optional.empty(), parseClientTags(clientTags), clientInfo, catalog, schema, ...
@Test public void testSource() { ClientOptions options = new ClientOptions(); options.source = "test"; ClientSession session = options.toClientSession(); assertEquals(session.getSource(), "test"); }
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the re...
@Test public void testPostNewDeploymentBPMNFile() throws Exception { try { // Upload a valid BPMN-file using multipart-data HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT_COLLECTION)); httpPost.setEntity(Htt...
public static boolean isValidEmail(String email) { return StringUtils.isNotBlank(email) && email.matches(EMAIL_REGEX); }
@Test void validateEmailTest() { var cases = new HashMap<String, Boolean>(); // Valid cases cases.put("simple@example.com", true); cases.put("very.common@example.com", true); cases.put("disposable.style.email.with+symbol@example.com", true); cases.put("other.email-wit...
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName, @Nullable Integer pageNumber, @Nullable Integer pageSize) { String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s", gitlabUrl, proj...
@Test public void search_projects() throws InterruptedException { MockResponse projects = new MockResponse() .setResponseCode(200) .setBody("[\n" + " {\n" + " \"id\": 1,\n" + " \"name\": \"SonarQube example 1\",\n" + " \"name_with_namespace\": \"SonarSource / ...
@Override public void beforeRejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { if (!(executor instanceof ExtensibleThreadPoolExecutor)) { return; } String threadPoolId = ((ExtensibleThreadPoolExecutor) executor).getThreadPoolId(); threadPoolCheckAlarm.asy...
@Test public void testBeforeRejectedExecution() { ExtensibleThreadPoolExecutor executor = new ExtensibleThreadPoolExecutor( "test", new DefaultThreadPoolPluginManager(), 1, 1, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1), Thread::new, new ThreadPo...
public ReadOperation getReadOperation() { if (operations == null || operations.isEmpty()) { throw new IllegalStateException("Map task has no operation."); } Operation readOperation = operations.get(0); if (!(readOperation instanceof ReadOperation)) { throw new IllegalStateException("First o...
@Test public void testNoReadOperation() throws Exception { // Test MapTaskExecutor without ReadOperation. List<Operation> operations = Arrays.<Operation>asList(createOperation("o1", 1), createOperation("o2", 2)); ExecutionStateTracker stateTracker = ExecutionStateTracker.newForTest(); try (Map...
@Override public void upgrade() { if (shouldSkip()) { return; } final ImmutableSet<String> eventIndexPrefixes = ImmutableSet.of( elasticsearchConfig.getDefaultEventsIndexPrefix(), elasticsearchConfig.getDefaultSystemEventsIndexPrefix()); ...
@Test void doesNotRunIfMigrationHasCompletedBefore() { when(clusterConfigService.get(V20200730000000_AddGl2MessageIdFieldAliasForEvents.MigrationCompleted.class)) .thenReturn(V20200730000000_AddGl2MessageIdFieldAliasForEvents.MigrationCompleted.create(ImmutableSet.of())); this.sut.u...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getProducerConfigs(final String clientId) { final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(PRODUCER_PREFIX, ProducerConfig.configNames()); checkIfUnexpectedUserSpecifiedConsumerConfig(clientProvidedProps, NON_CON...
@Test public void shouldSupportNonPrefixedProducerConfigs() { props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 10); props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> configs = streamsConfig.g...
public static MepId valueOf(short id) { if (id < 1 || id > 8191) { throw new IllegalArgumentException( "Invalid value for Mep Id - must be between 1-8191 inclusive. " + "Rejecting " + id); } return new MepId(id); }
@Test public void testLowRange() { try { MepId.valueOf((short) -1); fail("Exception expected for MepId = -1"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Invalid value for Mep Id")); } try { MepId.valueO...
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void typedHandle_InvalidRequestEventException_jsonContentTypeHeader() { AwsProxyResponse resp = exceptionHandler.handle(new InvalidRequestEventException(INVALID_REQUEST_MESSAGE, null)); assertNotNull(resp); assertTrue(resp.getMultiValueHeaders().containsKey(HttpHeaders.CONTENT_TYPE));...