From d95978f7b59298e3a91c86087f362471c72d9508 Mon Sep 17 00:00:00 2001 From: Joanne Wang Date: Tue, 6 Feb 2024 10:50:14 -0800 Subject: [PATCH] Update dependency com.pinterest:kitlint to 0.47.1 and fix CVE-2023-6378 for common-utils (#585) Signed-off-by: Joanne Wang --- build.gradle | 11 ++- .../action/AcknowledgeAlertResponse.kt | 1 - .../action/AcknowledgeChainedAlertRequest.kt | 4 +- .../alerting/action/AlertingActions.kt | 2 + .../alerting/action/DeleteWorkflowRequest.kt | 1 + .../alerting/action/GetMonitorRequest.kt | 4 +- .../alerting/action/GetMonitorResponse.kt | 8 +- .../action/GetWorkflowAlertsRequest.kt | 2 +- .../action/GetWorkflowAlertsResponse.kt | 1 + .../alerting/action/GetWorkflowResponse.kt | 7 +- .../alerting/action/IndexWorkflowRequest.kt | 22 +++-- .../BucketSelectorExtAggregator.kt | 5 +- .../BucketSelectorExtFilter.kt | 1 + .../commons/alerting/alerts/AlertError.kt | 1 - .../alerting/model/AggregationResultBucket.kt | 6 +- .../commons/alerting/model/Alert.kt | 20 +++-- .../alerting/model/BucketLevelTrigger.kt | 3 +- .../alerting/model/ChainedMonitorFindings.kt | 5 +- .../alerting/model/ClusterMetricsInput.kt | 30 ++++--- .../commons/alerting/model/CompositeInput.kt | 5 +- .../commons/alerting/model/DataSources.kt | 2 +- .../commons/alerting/model/Delegate.kt | 6 +- .../alerting/model/DocLevelMonitorInput.kt | 9 +- .../commons/alerting/model/DocLevelQuery.kt | 6 +- .../alerting/model/DocumentLevelTrigger.kt | 6 +- .../commons/alerting/model/Finding.kt | 2 +- .../commons/alerting/model/FindingDocument.kt | 3 +- .../commons/alerting/model/Monitor.kt | 21 +++-- .../commons/alerting/model/NoOpTrigger.kt | 8 +- .../alerting/model/QueryLevelTrigger.kt | 10 ++- .../commons/alerting/model/Schedule.kt | 11 ++- .../commons/alerting/model/SearchInput.kt | 3 +- .../commons/alerting/model/Sequence.kt | 2 +- .../commons/alerting/model/Workflow.kt | 8 +- .../commons/alerting/model/action/Action.kt | 5 +- .../notifications/model/ChannelMessage.kt | 1 - .../opensearch/commons/alerting/AlertTests.kt | 9 +- .../alerting/AlertingPluginInterfaceTests.kt | 7 +- .../commons/alerting/TestHelpers.kt | 27 ++++-- .../action/AcknowledgeAlertResponseTests.kt | 1 - .../action/DeleteMonitorRequestTests.kt | 1 - .../action/DeleteWorkflowRequestTests.kt | 1 - .../action/DeleteWorkflowResponseTests.kt | 1 - .../alerting/action/GetAlertsRequestTests.kt | 4 +- .../action/GetFindingsRequestTests.kt | 1 - .../action/GetFindingsResponseTests.kt | 1 - .../alerting/action/GetMonitorRequestTests.kt | 3 - .../action/GetWorkflowAlertsRequestTests.kt | 2 - .../action/GetWorkflowResponseTests.kt | 14 ++- .../action/IndexMonitorRequestTests.kt | 26 ++++-- .../action/IndexWorkflowRequestTests.kt | 90 +++++++++++++++---- .../action/PublishFindingsRequestTests.kt | 1 - .../commons/alerting/model/FindingTests.kt | 2 +- .../commons/alerting/model/ScheduleTest.kt | 12 ++- .../commons/alerting/model/XContentTests.kt | 6 +- .../NotificationsPluginInterfaceTests.kt | 6 +- .../CreateNotificationConfigRequestTests.kt | 3 + .../action/SendNotificationResponseTests.kt | 2 - .../UpdateNotificationConfigRequestTests.kt | 2 + .../model/NotificationConfigTests.kt | 1 - .../notifications/model/SmtpAccountTests.kt | 3 +- .../model/config/ConfigPropertiesTests.kt | 2 + 62 files changed, 323 insertions(+), 147 deletions(-) diff --git a/build.gradle b/build.gradle index 85acafcc..4b0df736 100644 --- a/build.gradle +++ b/build.gradle @@ -66,7 +66,12 @@ apply plugin: 'opensearch.repositories' apply from: 'build-tools/opensearchplugin-coverage.gradle' configurations { - ktlint + ktlint { + resolutionStrategy { + force "ch.qos.logback:logback-classic:1.3.14" + force "ch.qos.logback:logback-core:1.3.14" + } + } } dependencies { @@ -86,7 +91,7 @@ dependencies { testImplementation "commons-validator:commons-validator:1.7" testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' - ktlint "com.pinterest:ktlint:0.44.0" + ktlint "com.pinterest:ktlint:0.47.1" } test { @@ -226,4 +231,4 @@ task updateVersion { // Include the required files that needs to be updated with new Version ant.replaceregexp(file:'build.gradle', match: '"opensearch.version", "\\d.*"', replace: '"opensearch.version", "' + newVersion.tokenize('-')[0] + '-SNAPSHOT"', flags:'g', byline:true) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt index 53fc2f21..38d81778 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponse.kt @@ -45,7 +45,6 @@ class AcknowledgeAlertResponse : BaseResponse { @Throws(IOException::class) override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { - builder.startObject().startArray("success") acknowledged.forEach { builder.value(it.id) } builder.endArray().startArray("failed") diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt index 2c482f26..81d1fef6 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AcknowledgeChainedAlertRequest.kt @@ -19,7 +19,7 @@ class AcknowledgeChainedAlertRequest : ActionRequest { constructor( workflowId: String, - alertIds: List, + alertIds: List ) : super() { this.workflowId = workflowId this.alertIds = alertIds @@ -28,7 +28,7 @@ class AcknowledgeChainedAlertRequest : ActionRequest { @Throws(IOException::class) constructor(sin: StreamInput) : this( sin.readString(), // workflowId - Collections.unmodifiableList(sin.readStringList()), // alertIds + Collections.unmodifiableList(sin.readStringList()) // alertIds ) override fun validate(): ActionRequestValidationException? { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/AlertingActions.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/AlertingActions.kt index f4e68d73..f2ada6a5 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/AlertingActions.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/AlertingActions.kt @@ -29,6 +29,7 @@ object AlertingActions { @JvmField val INDEX_WORKFLOW_ACTION_TYPE = ActionType(INDEX_WORKFLOW_ACTION_NAME, ::IndexWorkflowResponse) + @JvmField val GET_ALERTS_ACTION_TYPE = ActionType(GET_ALERTS_ACTION_NAME, ::GetAlertsResponse) @@ -48,6 +49,7 @@ object AlertingActions { @JvmField val DELETE_WORKFLOW_ACTION_TYPE = ActionType(DELETE_WORKFLOW_ACTION_NAME, ::DeleteWorkflowResponse) + @JvmField val GET_FINDINGS_ACTION_TYPE = ActionType(GET_FINDINGS_ACTION_NAME, ::GetFindingsResponse) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt index 10189e89..a3907e83 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequest.kt @@ -9,6 +9,7 @@ import java.io.IOException class DeleteWorkflowRequest : ActionRequest { val workflowId: String + /** * Flag that indicates whether the delegate monitors should be deleted or not. * If the flag is set to true, Delegate monitors will be deleted only in the case when they are part of the specified workflow and no other. diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt index 6c1df281..80676a04 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequest.kt @@ -38,7 +38,9 @@ class GetMonitorRequest : ActionRequest { sin.readEnum(RestRequest.Method::class.java), // method if (sin.readBoolean()) { FetchSourceContext(sin) // srcContext - } else null + } else { + null + } ) override fun validate(): ActionRequestValidationException? { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt index 49903853..7984ed07 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetMonitorResponse.kt @@ -32,7 +32,7 @@ class GetMonitorResponse : BaseResponse { seqNo: Long, primaryTerm: Long, monitor: Monitor?, - associatedCompositeMonitors: List?, + associatedCompositeMonitors: List? ) : super() { this.id = id this.version = version @@ -50,8 +50,10 @@ class GetMonitorResponse : BaseResponse { primaryTerm = sin.readLong(), // primaryTerm monitor = if (sin.readBoolean()) { Monitor.readFrom(sin) // monitor - } else null, - associatedCompositeMonitors = sin.readList((AssociatedWorkflow)::readFrom), + } else { + null + }, + associatedCompositeMonitors = sin.readList((AssociatedWorkflow)::readFrom) ) @Throws(IOException::class) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt index bfa80044..9d08fa96 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequest.kt @@ -27,7 +27,7 @@ class GetWorkflowAlertsRequest : ActionRequest { monitorIds: List? = null, workflowIds: List? = null, alertIds: List? = null, - getAssociatedAlerts: Boolean, + getAssociatedAlerts: Boolean ) : super() { this.table = table this.severityLevel = severityLevel diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt index 4856d747..5104f344 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsResponse.kt @@ -12,6 +12,7 @@ import java.util.Collections class GetWorkflowAlertsResponse : BaseResponse { val alerts: List val associatedAlerts: List + // totalAlerts is not the same as the size of alerts because there can be 30 alerts from the request, but // the request only asked for 5 alerts, so totalAlerts will be 30, but alerts will only contain 5 alerts val totalAlerts: Int? diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt index 67bad9d0..ca6db115 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponse.kt @@ -51,7 +51,9 @@ class GetWorkflowResponse : BaseResponse { sin.readEnum(RestStatus::class.java), // RestStatus if (sin.readBoolean()) { Workflow.readFrom(sin) // monitor - } else null + } else { + null + } ) @Throws(IOException::class) @@ -76,8 +78,9 @@ class GetWorkflowResponse : BaseResponse { .field(_VERSION, version) .field(_SEQ_NO, seqNo) .field(_PRIMARY_TERM, primaryTerm) - if (workflow != null) + if (workflow != null) { builder.field("workflow", workflow) + } return builder.endObject() } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt index 6fe9c47b..1033e651 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequest.kt @@ -57,19 +57,22 @@ class IndexWorkflowRequest : ActionRequest { if (workflow.inputs.isEmpty()) { validationException = ValidateActions.addValidationError( - "Input list can not be empty.", validationException + "Input list can not be empty.", + validationException ) return validationException } if (workflow.inputs.size > 1) { validationException = ValidateActions.addValidationError( - "Input list can contain only one element.", validationException + "Input list can contain only one element.", + validationException ) return validationException } if (workflow.inputs[0] !is CompositeInput) { validationException = ValidateActions.addValidationError( - "When creating a workflow input must be CompositeInput", validationException + "When creating a workflow input must be CompositeInput", + validationException ) } val compositeInput = workflow.inputs[0] as CompositeInput @@ -77,7 +80,8 @@ class IndexWorkflowRequest : ActionRequest { if (monitorIds.isNullOrEmpty()) { validationException = ValidateActions.addValidationError( - "Delegates list can not be empty.", validationException + "Delegates list can not be empty.", + validationException ) // Break the flow because next checks are dependant on non-null monitorIds return validationException @@ -85,27 +89,29 @@ class IndexWorkflowRequest : ActionRequest { if (monitorIds.size > MAX_DELEGATE_SIZE) { validationException = ValidateActions.addValidationError( - "Delegates list can not be larger then $MAX_DELEGATE_SIZE.", validationException + "Delegates list can not be larger then $MAX_DELEGATE_SIZE.", + validationException ) } if (monitorIds.toSet().size != monitorIds.size) { validationException = ValidateActions.addValidationError( - "Duplicate delegates not allowed", validationException + "Duplicate delegates not allowed", + validationException ) } val delegates = compositeInput.sequence.delegates val orderSet = delegates.stream().filter { it.order > 0 }.map { it.order }.collect(Collectors.toSet()) if (orderSet.size != delegates.size) { validationException = ValidateActions.addValidationError( - "Sequence ordering of delegate monitor shouldn't contain duplicate order values", validationException + "Sequence ordering of delegate monitor shouldn't contain duplicate order values", + validationException ) } val monitorIdOrderMap: Map = delegates.associate { it.monitorId to it.order } delegates.forEach { if (it.chainedMonitorFindings != null) { - if (it.chainedMonitorFindings.monitorId != null) { if (monitorIdOrderMap.containsKey(it.chainedMonitorFindings.monitorId) == false) { validationException = ValidateActions.addValidationError( diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt index 9003102e..ef305239 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtAggregator.kt @@ -108,7 +108,10 @@ class BucketSelectorExtAggregator : SiblingPipelineAggregator { } return BucketSelectorIndices( - name(), parentBucketPath, selectedBucketsIndex, originalAgg.metadata + name(), + parentBucketPath, + selectedBucketsIndex, + originalAgg.metadata ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt index 55dac69d..3d9466eb 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/aggregation/bucketselectorext/BucketSelectorExtFilter.kt @@ -14,6 +14,7 @@ import java.io.IOException class BucketSelectorExtFilter : BaseModel { // used for composite aggregations val filtersMap: HashMap? + // used for filtering string term aggregation val filters: IncludeExclude? diff --git a/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt b/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt index 5c8aa4d3..28ef4a55 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/alerts/AlertError.kt @@ -36,7 +36,6 @@ data class AlertError(val timestamp: Instant, var message: String) : Writeable, @JvmStatic @Throws(IOException::class) fun parse(xcp: XContentParser): AlertError { - lateinit var timestamp: Instant lateinit var message: String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt index caee50f8..2d36a51c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/AggregationResultBucket.kt @@ -59,8 +59,10 @@ data class AggregationResultBucket( throw ParsingException( xcp.tokenLocation, String.format( - Locale.ROOT, "Failed to parse object: expecting token with name [%s] but found [%s]", - CONFIG_NAME, xcp.currentName() + Locale.ROOT, + "Failed to parse object: expecting token with name [%s] but found [%s]", + CONFIG_NAME, + xcp.currentName() ) ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt index 38726aed..e435c866 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Alert.kt @@ -43,12 +43,14 @@ data class Alert( val aggregationResultBucket: AggregationResultBucket? = null, val executionId: String? = null, val associatedAlertIds: List, - val clusters: List? = null, + val clusters: List? = null ) : Writeable, ToXContent { init { - if (errorMessage != null) require(state == State.DELETED || state == State.ERROR || state == State.AUDIT) { - "Attempt to create an alert with an error in state: $state" + if (errorMessage != null) { + require(state == State.DELETED || state == State.ERROR || state == State.AUDIT) { + "Attempt to create an alert with an error in state: $state" + } } } @@ -308,7 +310,9 @@ data class Alert( monitorVersion = sin.readLong(), monitorUser = if (sin.readBoolean()) { User(sin) - } else null, + } else { + null + }, triggerId = sin.readString(), triggerName = sin.readString(), findingIds = sin.readStringList(), @@ -402,7 +406,6 @@ data class Alert( @JvmOverloads @Throws(IOException::class) fun parse(xcp: XContentParser, id: String = NO_ID, version: Long = NO_VERSION): Alert { - lateinit var monitorId: String var workflowId = "" var workflowName = "" @@ -440,8 +443,11 @@ data class Alert( MONITOR_NAME_FIELD -> monitorName = xcp.text() MONITOR_VERSION_FIELD -> monitorVersion = xcp.longValue() MONITOR_USER_FIELD -> - monitorUser = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null - else User.parse(xcp) + monitorUser = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { + User.parse(xcp) + } TRIGGER_ID_FIELD -> triggerId = xcp.text() FINDING_IDS -> { ensureExpectedToken(XContentParser.Token.START_ARRAY, xcp.currentToken(), xcp) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt index fdba5e3a..669d37b1 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/BucketLevelTrigger.kt @@ -88,7 +88,8 @@ data class BucketLevelTrigger( const val PARENT_BUCKET_PATH = "parentBucketPath" val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, ParseField(BUCKET_LEVEL_TRIGGER_FIELD), + Trigger::class.java, + ParseField(BUCKET_LEVEL_TRIGGER_FIELD), CheckedFunction { parseInner(it) } ) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt index 92192eec..a1b6435a 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ChainedMonitorFindings.kt @@ -17,7 +17,7 @@ import java.util.Collections // TODO - Remove the class and move the monitorId to Delegate (as a chainedMonitorId property) if this class won't be updated by adding new properties data class ChainedMonitorFindings( val monitorId: String? = null, - val monitorIds: List = emptyList(), // if monitorId field is non-null it would be given precendence for BWC + val monitorIds: List = emptyList() // if monitorId field is non-null it would be given precendence for BWC ) : BaseModel { init { @@ -75,8 +75,9 @@ data class ChainedMonitorFindings( when (fieldName) { MONITOR_ID_FIELD -> { - if (!xcp.currentToken().equals(XContentParser.Token.VALUE_NULL)) + if (!xcp.currentToken().equals(XContentParser.Token.VALUE_NULL)) { monitorId = xcp.text() + } } MONITOR_IDS_FIELD -> { diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt index d6ebe804..8c8b2429 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/ClusterMetricsInput.kt @@ -45,10 +45,11 @@ data class ClusterMetricsInput( "Invalid URI constructed from the path and path_params inputs, or the url input." } - if (url.isNotEmpty() && validateFieldsNotEmpty()) + if (url.isNotEmpty() && validateFieldsNotEmpty()) { require(constructedUri == constructUrlFromInputs()) { "The provided URL and URI fields form different URLs." } + } require(constructedUri.host.lowercase() == SUPPORTED_HOST) { "Only host '$SUPPORTED_HOST' is supported." @@ -109,7 +110,8 @@ data class ClusterMetricsInput( /** * This parse function uses [XContentParser] to parse JSON input and store corresponding fields to create a [ClusterMetricsInput] object */ - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parseInner(xcp: XContentParser): ClusterMetricsInput { var path = "" var pathParams = "" @@ -175,17 +177,20 @@ data class ClusterMetricsInput( if (pathParams.isNotEmpty()) { pathParams = pathParams.trim('/') ILLEGAL_PATH_PARAMETER_CHARACTERS.forEach { character -> - if (pathParams.contains(character)) + if (pathParams.contains(character)) { throw IllegalArgumentException( "The provided path parameters contain invalid characters or spaces. Please omit: " + ILLEGAL_PATH_PARAMETER_CHARACTERS.joinToString(" ") ) + } } } - if (apiType.requiresPathParams && pathParams.isEmpty()) + if (apiType.requiresPathParams && pathParams.isEmpty()) { throw IllegalArgumentException("The API requires path parameters.") - if (!apiType.supportsPathParams && pathParams.isNotEmpty()) + } + if (!apiType.supportsPathParams && pathParams.isNotEmpty()) { throw IllegalArgumentException("The API does not use path parameters.") + } return pathParams } @@ -201,11 +206,13 @@ data class ClusterMetricsInput( ClusterMetricType.values() .filter { option -> option != ClusterMetricType.BLANK } .forEach { option -> - if (uriPath.startsWith(option.prependPath) || uriPath.startsWith(option.defaultPath)) + if (uriPath.startsWith(option.prependPath) || uriPath.startsWith(option.defaultPath)) { apiType = option + } } - if (apiType.isBlank()) + if (apiType.isBlank()) { throw IllegalArgumentException("The API could not be determined from the provided URI.") + } return apiType } @@ -238,12 +245,15 @@ data class ClusterMetricsInput( * If [path] and [pathParams] are empty, populates them with values from [url]. */ private fun parseEmptyFields() { - if (pathParams.isEmpty()) + if (pathParams.isEmpty()) { pathParams = this.parsePathParams() - if (path.isEmpty()) + } + if (path.isEmpty()) { path = if (pathParams.isEmpty()) clusterMetricType.defaultPath else clusterMetricType.prependPath - if (url.isEmpty()) + } + if (url.isEmpty()) { url = constructedUri.toString() + } } /** diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt index 7487232b..0f1e3e12 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/CompositeInput.kt @@ -12,7 +12,7 @@ import org.opensearch.core.xcontent.XContentParserUtils import java.io.IOException data class CompositeInput( - val sequence: Sequence, + val sequence: Sequence ) : WorkflowInput { @Throws(IOException::class) constructor(sin: StreamInput) : this( @@ -53,7 +53,8 @@ data class CompositeInput( val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( WorkflowInput::class.java, - ParseField(COMPOSITE_INPUT_FIELD), CheckedFunction { CompositeInput.parse(it) } + ParseField(COMPOSITE_INPUT_FIELD), + CheckedFunction { CompositeInput.parse(it) } ) @JvmStatic diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt index b6beb6a1..b922a706 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DataSources.kt @@ -88,7 +88,7 @@ data class DataSources( ALERTS_HISTORY_INDEX_FIELD to alertsHistoryIndex, ALERTS_HISTORY_INDEX_PATTERN_FIELD to alertsHistoryIndexPattern, QUERY_INDEX_MAPPINGS_BY_TYPE to queryIndexMappingsByType, - FINDINGS_ENABLED_FIELD to findingsEnabled, + FINDINGS_ENABLED_FIELD to findingsEnabled ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt index 7b36ed88..e32ae78d 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Delegate.kt @@ -42,13 +42,15 @@ data class Delegate( monitorId = sin.readString(), chainedMonitorFindings = if (sin.readBoolean()) { ChainedMonitorFindings(sin) - } else null, + } else { + null + } ) fun asTemplateArg(): Map { return mapOf( ORDER_FIELD to order, - MONITOR_ID_FIELD to monitorId, + MONITOR_ID_FIELD to monitorId ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt index 44eeb65d..4ed95cdb 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelMonitorInput.kt @@ -64,10 +64,12 @@ data class DocLevelMonitorInput( val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( Input::class.java, - ParseField(DOC_LEVEL_INPUT_FIELD), CheckedFunction { parse(it) } + ParseField(DOC_LEVEL_INPUT_FIELD), + CheckedFunction { parse(it) } ) - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parse(xcp: XContentParser): DocLevelMonitorInput { var description: String = NO_DESCRIPTION val indices: MutableList = mutableListOf() @@ -106,7 +108,8 @@ data class DocLevelMonitorInput( return DocLevelMonitorInput(description = description, indices = indices, queries = docLevelQueries) } - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun readFrom(sin: StreamInput): DocLevelMonitorInput { return DocLevelMonitorInput(sin) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt index 9574b602..ba3e4e4c 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocLevelQuery.kt @@ -75,7 +75,8 @@ data class DocLevelQuery( const val NO_ID = "" val INVALID_CHARACTERS: List = listOf(" ", "[", "]", "{", "}", "(", ")") - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parse(xcp: XContentParser): DocLevelQuery { var id: String = UUID.randomUUID().toString() lateinit var query: String @@ -130,7 +131,8 @@ data class DocLevelQuery( ) } - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun readFrom(sin: StreamInput): DocLevelQuery { return DocLevelQuery(sin) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt index c06374cf..df584234 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/DocumentLevelTrigger.kt @@ -80,11 +80,13 @@ data class DocumentLevelTrigger( const val QUERY_IDS_FIELD = "query_ids" val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, ParseField(DOCUMENT_LEVEL_TRIGGER_FIELD), + Trigger::class.java, + ParseField(DOCUMENT_LEVEL_TRIGGER_FIELD), CheckedFunction { parseInner(it) } ) - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parseInner(xcp: XContentParser): DocumentLevelTrigger { var id = UUIDs.base64UUID() // assign a default triggerId if one is not specified lateinit var name: String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt index 673fad96..93915358 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Finding.kt @@ -27,7 +27,7 @@ class Finding( * Keeps the track of the workflow-monitor exact execution. * Used for filtering the data when chaining monitors in a workflow. */ - val executionId: String? = null, + val executionId: String? = null ) : Writeable, ToXContent { constructor( diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt index 9e6d4b83..202693fd 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/FindingDocument.kt @@ -52,7 +52,8 @@ class FindingDocument( const val NO_ID = "" const val NO_INDEX = "" - @JvmStatic @JvmOverloads + @JvmStatic + @JvmOverloads @Throws(IOException::class) fun parse(xcp: XContentParser, id: String = NO_ID, index: String = NO_INDEX): FindingDocument { var found = false diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt index 1af3ac37..b2099d93 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Monitor.kt @@ -97,7 +97,9 @@ data class Monitor( monitorType = sin.readEnum(MonitorType::class.java), user = if (sin.readBoolean()) { User(sin) - } else null, + } else { + null + }, schemaVersion = sin.readInt(), inputs = sin.readList((Input)::readFrom), triggers = sin.readList((Trigger)::readFrom), @@ -184,8 +186,11 @@ data class Monitor( // Outputting type with each Input so that the generic Input.readFrom() can read it out.writeVInt(inputs.size) inputs.forEach { - if (it is SearchInput) out.writeEnum(Input.Type.SEARCH_INPUT) - else out.writeEnum(Input.Type.DOCUMENT_LEVEL_INPUT) + if (it is SearchInput) { + out.writeEnum(Input.Type.SEARCH_INPUT) + } else { + out.writeEnum(Input.Type.DOCUMENT_LEVEL_INPUT) + } it.writeTo(out) } // Outputting type with each Trigger so that the generic Trigger.readFrom() can read it @@ -276,8 +281,9 @@ data class Monitor( ) while (xcp.nextToken() != XContentParser.Token.END_ARRAY) { val input = Input.parse(xcp) - if (input is ClusterMetricsInput) + if (input is ClusterMetricsInput) { supportedClusterMetricsSettings?.validateApiType(input) + } inputs.add(input) } } @@ -294,8 +300,11 @@ data class Monitor( ENABLED_TIME_FIELD -> enabledTime = xcp.instant() LAST_UPDATE_TIME_FIELD -> lastUpdateTime = xcp.instant() UI_METADATA_FIELD -> uiMetadata = xcp.map() - DATA_SOURCES_FIELD -> dataSources = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) DataSources() - else DataSources.parse(xcp) + DATA_SOURCES_FIELD -> dataSources = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + DataSources() + } else { + DataSources.parse(xcp) + } OWNER_FIELD -> owner = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) owner else xcp.text() else -> { xcp.skipChildren() diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt index f0d08cbb..3ffacb6e 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/NoOpTrigger.kt @@ -17,7 +17,7 @@ data class NoOpTrigger( override val id: String = UUIDs.base64UUID(), override val name: String = "NoOp trigger", override val severity: String = "", - override val actions: List = listOf(), + override val actions: List = listOf() ) : Trigger { @Throws(IOException::class) @@ -48,11 +48,13 @@ data class NoOpTrigger( const val ID_FIELD = "id" const val NOOP_TRIGGER_FIELD = "noop_trigger" val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, ParseField(NOOP_TRIGGER_FIELD), + Trigger::class.java, + ParseField(NOOP_TRIGGER_FIELD), CheckedFunction { parseInner(it) } ) - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parseInner(xcp: XContentParser): NoOpTrigger { var id = UUIDs.base64UUID() if (xcp.currentToken() == XContentParser.Token.START_OBJECT) xcp.nextToken() diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt index d16b85db..0be93671 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/QueryLevelTrigger.kt @@ -57,7 +57,9 @@ data class QueryLevelTrigger( /** Returns a representation of the trigger suitable for passing into painless and mustache scripts. */ fun asTemplateArg(): Map { return mapOf( - ID_FIELD to id, NAME_FIELD to name, SEVERITY_FIELD to severity, + ID_FIELD to id, + NAME_FIELD to name, + SEVERITY_FIELD to severity, ACTIONS_FIELD to actions.map { it.asTemplateArg() } ) } @@ -77,7 +79,8 @@ data class QueryLevelTrigger( const val SCRIPT_FIELD = "script" val XCONTENT_REGISTRY = NamedXContentRegistry.Entry( - Trigger::class.java, ParseField(QUERY_LEVEL_TRIGGER_FIELD), + Trigger::class.java, + ParseField(QUERY_LEVEL_TRIGGER_FIELD), CheckedFunction { parseInner(it) } ) @@ -113,7 +116,8 @@ data class QueryLevelTrigger( * It isn't typically conventional but this parse method will account for both START_OBJECT * and FIELD_NAME as the starting token to cover both cases. */ - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parseInner(xcp: XContentParser): QueryLevelTrigger { var id = UUIDs.base64UUID() // assign a default triggerId if one is not specified lateinit var name: String diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt index 1f8d8b7f..d82bc375 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Schedule.kt @@ -33,7 +33,8 @@ sealed class Schedule : BaseModel { val cronParser = CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX)) - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parse(xcp: XContentParser): Schedule { var expression: String? = null var timezone: ZoneId? = null @@ -91,7 +92,8 @@ sealed class Schedule : BaseModel { return requireNotNull(schedule) { "Schedule is null." } } - @JvmStatic @Throws(IllegalArgumentException::class) + @JvmStatic + @Throws(IllegalArgumentException::class) private fun getTimeZone(timeZone: String): ZoneId { try { return ZoneId.of(timeZone) @@ -106,10 +108,11 @@ sealed class Schedule : BaseModel { @Throws(IOException::class) fun readFrom(sin: StreamInput): Schedule { val type = sin.readEnum(Schedule.TYPE::class.java) - if (type == Schedule.TYPE.CRON) + if (type == Schedule.TYPE.CRON) { return CronSchedule(sin) - else + } else { return IntervalSchedule(sin) + } } } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt index 0eb87c15..7579a10d 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/SearchInput.kt @@ -46,7 +46,8 @@ data class SearchInput(val indices: List, val query: SearchSourceBuilder val XCONTENT_REGISTRY = NamedXContentRegistry.Entry(Input::class.java, ParseField("search"), CheckedFunction { parseInner(it) }) - @JvmStatic @Throws(IOException::class) + @JvmStatic + @Throws(IOException::class) fun parseInner(xcp: XContentParser): SearchInput { val indices = mutableListOf() lateinit var searchSourceBuilder: SearchSourceBuilder diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt index 22d4683b..e1f6150d 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Sequence.kt @@ -21,7 +21,7 @@ data class Sequence( fun asTemplateArg(): Map { return mapOf( - DELEGATES_FIELD to delegates, + DELEGATES_FIELD to delegates ) } diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt index 2038edfb..d0e57e63 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/Workflow.kt @@ -37,7 +37,7 @@ data class Workflow( val inputs: List, val owner: String? = DEFAULT_OWNER, val triggers: List, - val auditDelegateMonitorAlerts: Boolean? = true, + val auditDelegateMonitorAlerts: Boolean? = true ) : ScheduledJob { override val type = WORKFLOW_TYPE @@ -67,7 +67,9 @@ data class Workflow( workflowType = sin.readEnum(WorkflowType::class.java), user = if (sin.readBoolean()) { User(sin) - } else null, + } else { + null + }, schemaVersion = sin.readInt(), inputs = sin.readList((WorkflowInput)::readFrom), owner = sin.readOptionalString(), @@ -101,7 +103,7 @@ data class Workflow( private fun createXContentBuilder( builder: XContentBuilder, params: ToXContent.Params, - secure: Boolean, + secure: Boolean ): XContentBuilder { builder.startObject() if (params.paramAsBoolean("with_type", false)) builder.startObject(type) diff --git a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt index 2d02385f..4fa0c514 100644 --- a/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt +++ b/src/main/kotlin/org/opensearch/commons/alerting/model/action/Action.kt @@ -130,8 +130,11 @@ data class Action( NAME_FIELD -> name = xcp.textOrNull() DESTINATION_ID_FIELD -> destinationId = xcp.textOrNull() SUBJECT_TEMPLATE_FIELD -> { - subjectTemplate = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) null else + subjectTemplate = if (xcp.currentToken() == XContentParser.Token.VALUE_NULL) { + null + } else { Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) + } } MESSAGE_TEMPLATE_FIELD -> messageTemplate = Script.parse(xcp, Script.DEFAULT_TEMPLATE_LANG) THROTTLE_FIELD -> { diff --git a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt index 3fb16981..d733a8bc 100644 --- a/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt +++ b/src/main/kotlin/org/opensearch/commons/notifications/model/ChannelMessage.kt @@ -48,7 +48,6 @@ data class ChannelMessage( @JvmStatic @Throws(IOException::class) fun parse(parser: XContentParser): ChannelMessage { - var textDescription: String? = null var htmlDescription: String? = null var attachment: Attachment? = null diff --git a/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt index 8b4db7c4..4a5f2346 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/AlertTests.kt @@ -50,7 +50,7 @@ class AlertTests { assertEquals( templateArgs[Alert.PARENTS_BUCKET_PATH], alert.aggregationResultBucket?.parentBucketPath, - "Template args parentBucketPath does not match", + "Template args parentBucketPath does not match" ) } @@ -66,8 +66,11 @@ class AlertTests { @Test fun `test alert in audit state`() { val auditAlert = Alert( - randomQueryLevelMonitor(), randomQueryLevelTrigger(), Instant.now().truncatedTo(ChronoUnit.MILLIS), - null, actionExecutionResults = listOf(randomActionExecutionResult()) + randomQueryLevelMonitor(), + randomQueryLevelTrigger(), + Instant.now().truncatedTo(ChronoUnit.MILLIS), + null, + actionExecutionResults = listOf(randomActionExecutionResult()) ) Assertions.assertFalse(auditAlert.isAcknowledged(), "Alert should not be in acknowledged state") } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt index 3ce4f6bb..3c0e252c 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/AlertingPluginInterfaceTests.kt @@ -162,7 +162,12 @@ internal class AlertingPluginInterfaceTests { fun getWorkflow() { val request = mock(GetWorkflowRequest::class.java) val response = GetWorkflowResponse( - id = "id", version = 1, seqNo = 1, primaryTerm = 1, status = RestStatus.OK, workflow = randomWorkflow() + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = randomWorkflow() ) val listener: ActionListener = mock(ActionListener::class.java) as ActionListener diff --git a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt index e95c88d8..8596a426 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/TestHelpers.kt @@ -208,7 +208,7 @@ fun randomWorkflowWithDelegates( enabled: Boolean = Random().nextBoolean(), enabledTime: Instant? = if (enabled) Instant.now().truncatedTo(ChronoUnit.MILLIS) else null, lastUpdateTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS), - triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomChainedAlertTrigger() }, + triggers: List = (1..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomChainedAlertTrigger() } ): Workflow { return Workflow( name = name, workflowType = Workflow.WorkflowType.COMPOSITE, enabled = enabled, inputs = input, @@ -286,9 +286,11 @@ fun randomDocumentLevelTrigger( name = name, severity = severity, condition = condition, - actions = if (actions.isEmpty() && destinationId.isNotBlank()) + actions = if (actions.isEmpty() && destinationId.isNotBlank()) { (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } - else actions + } else { + actions + } ) } @@ -307,7 +309,9 @@ fun randomChainedAlertTrigger( condition = condition, actions = if (actions.isEmpty() && destinationId.isNotBlank()) { (0..RandomNumbers.randomIntBetween(Random(), 0, 10)).map { randomAction(destinationId = destinationId) } - } else actions + } else { + actions + } ) } @@ -530,14 +534,18 @@ fun randomAlert(monitor: Monitor = randomQueryLevelMonitor()): Alert { val clusterCount = (-1..5).random() val clusters = if (clusterCount == -1) null else (0..clusterCount).map { "index-$it" } return Alert( - monitor, trigger, Instant.now().truncatedTo(ChronoUnit.MILLIS), null, - actionExecutionResults = actionExecutionResults, clusters = clusters + monitor, + trigger, + Instant.now().truncatedTo(ChronoUnit.MILLIS), + null, + actionExecutionResults = actionExecutionResults, + clusters = clusters ) } fun randomChainedAlert( workflow: Workflow = randomWorkflow(), - trigger: ChainedAlertTrigger = randomChainedAlertTrigger(), + trigger: ChainedAlertTrigger = randomChainedAlertTrigger() ): Alert { return Alert( startTime = Instant.now(), @@ -561,7 +569,10 @@ fun randomAlertWithAggregationResultBucket(monitor: Monitor = randomBucketLevelM val trigger = randomBucketLevelTrigger() val actionExecutionResults = mutableListOf(randomActionExecutionResult(), randomActionExecutionResult()) return Alert( - monitor, trigger, Instant.now().truncatedTo(ChronoUnit.MILLIS), null, + monitor, + trigger, + Instant.now().truncatedTo(ChronoUnit.MILLIS), + null, actionExecutionResults = actionExecutionResults, aggregationResultBucket = AggregationResultBucket( "parent_bucket_path_1", diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponseTests.kt index 5733c550..df9a083b 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/AcknowledgeAlertResponseTests.kt @@ -15,7 +15,6 @@ class AcknowledgeAlertResponseTests { @Test fun `test acknowledge alert response`() { - val acknowledged = mutableListOf( Alert( id = "1234", diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequestTests.kt index 38c89fc5..b307ec6c 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteMonitorRequestTests.kt @@ -11,7 +11,6 @@ class DeleteMonitorRequestTests { @Test fun `test delete monitor request`() { - val req = DeleteMonitorRequest("1234", WriteRequest.RefreshPolicy.IMMEDIATE) assertNotNull(req) assertEquals("1234", req.monitorId) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequestTests.kt index a92ee17e..1fc793c2 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowRequestTests.kt @@ -9,7 +9,6 @@ class DeleteWorkflowRequestTests { @Test fun `test delete workflow request`() { - val req = DeleteWorkflowRequest("1234", true) Assert.assertNotNull(req) Assert.assertEquals("1234", req.workflowId) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponseTests.kt index b3d82b90..2aee0fea 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/DeleteWorkflowResponseTests.kt @@ -9,7 +9,6 @@ class DeleteWorkflowResponseTests { @Test fun `test delete workflow response`() { - val res = DeleteWorkflowResponse(id = "w1", version = 1, nonDeletedMonitors = listOf("m1")) Assert.assertNotNull(res) Assert.assertEquals("w1", res.id) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt index bf301f74..58f61550 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetAlertsRequestTests.kt @@ -13,7 +13,6 @@ internal class GetAlertsRequestTests { @Test fun `test get alerts request`() { - val table = Table("asc", "sortString", null, 1, 0, "") val req = GetAlertsRequest( @@ -24,7 +23,7 @@ internal class GetAlertsRequestTests { alertIndex = null, monitorIds = listOf("1", "2"), alertIds = listOf("alert1", "alert2"), - workflowIds = listOf("w1", "w2"), + workflowIds = listOf("w1", "w2") ) assertNotNull(req) @@ -47,7 +46,6 @@ internal class GetAlertsRequestTests { @Test fun `test get alerts request with filter`() { - val table = Table("asc", "sortString", null, 1, 0, "") val req = GetAlertsRequest(table, "1", "active", null, null) assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt index 253f4708..ddd56d15 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsRequestTests.kt @@ -13,7 +13,6 @@ internal class GetFindingsRequestTests { @Test fun `test get findings request`() { - val table = Table("asc", "sortString", null, 1, 0, "") val req = GetFindingsRequest("2121", table, "1", "finding_index_name", listOf("1", "2")) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt index 1a8b2bdb..0c30b640 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetFindingsResponseTests.kt @@ -15,7 +15,6 @@ internal class GetFindingsResponseTests { @Test fun `test get findings response`() { - // Alerting GetFindingsResponse mock #1 val finding1 = Finding( "1", diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt index c916b993..7670650e 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetMonitorRequestTests.kt @@ -14,7 +14,6 @@ import org.opensearch.test.OpenSearchTestCase class GetMonitorRequestTests : OpenSearchTestCase() { fun `test get monitor request`() { - val req = GetMonitorRequest("1234", 1L, RestRequest.Method.GET, FetchSourceContext.FETCH_SOURCE) assertNotNull(req) @@ -29,7 +28,6 @@ class GetMonitorRequestTests : OpenSearchTestCase() { } fun `test get monitor request without src context`() { - val req = GetMonitorRequest("1234", 1L, RestRequest.Method.GET, null) assertNotNull(req) @@ -44,7 +42,6 @@ class GetMonitorRequestTests : OpenSearchTestCase() { } fun `test head monitor request`() { - val req = GetMonitorRequest("1234", 2L, RestRequest.Method.HEAD, FetchSourceContext.FETCH_SOURCE) assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt index 1cf50eec..425151cd 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowAlertsRequestTests.kt @@ -13,7 +13,6 @@ internal class GetWorkflowAlertsRequestTests { @Test fun `test get alerts request`() { - val table = Table("asc", "sortString", null, 1, 0, "") val req = GetWorkflowAlertsRequest( @@ -48,7 +47,6 @@ internal class GetWorkflowAlertsRequestTests { @Test fun `test get alerts request with custom alerts and associated alerts indices`() { - val table = Table("asc", "sortString", null, 1, 0, "") val req = GetWorkflowAlertsRequest( diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt index 8e78b61f..e21bb430 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/GetWorkflowResponseTests.kt @@ -20,7 +20,12 @@ class GetWorkflowResponseTests { fun testGetWorkflowResponse() { val workflow = randomWorkflow(auditDelegateMonitorAlerts = false) val response = GetWorkflowResponse( - id = "id", version = 1, seqNo = 1, primaryTerm = 1, status = RestStatus.OK, workflow = workflow + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = workflow ) val out = BytesStreamOutput() response.writeTo(out) @@ -50,7 +55,12 @@ class GetWorkflowResponseTests { triggers = listOf() ) val response = GetWorkflowResponse( - id = "id", version = 1, seqNo = 1, primaryTerm = 1, status = RestStatus.OK, workflow = workflow + id = "id", + version = 1, + seqNo = 1, + primaryTerm = 1, + status = RestStatus.OK, + workflow = workflow ) val out = BytesStreamOutput() response.writeTo(out) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt index 20381c9b..6efd68b6 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexMonitorRequestTests.kt @@ -20,9 +20,12 @@ class IndexMonitorRequestTests { @Test fun `test index monitor post request`() { - val req = IndexMonitorRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))) ) Assertions.assertNotNull(req) @@ -41,7 +44,11 @@ class IndexMonitorRequestTests { @Test fun `test index bucket monitor post request`() { val req = IndexMonitorRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomBucketLevelMonitor() ) Assertions.assertNotNull(req) @@ -61,7 +68,11 @@ class IndexMonitorRequestTests { @Test fun `Index bucket monitor serialize and deserialize transport object should be equal`() { val bucketLevelMonitorRequest = IndexMonitorRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomBucketLevelMonitor() ) @@ -80,9 +91,12 @@ class IndexMonitorRequestTests { @Test fun `test index monitor put request`() { - val req = IndexMonitorRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomQueryLevelMonitor().copy(inputs = listOf(SearchInput(emptyList(), SearchSourceBuilder()))) ) Assertions.assertNotNull(req) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt index 58feffb2..600ac506 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/IndexWorkflowRequestTests.kt @@ -29,9 +29,12 @@ class IndexWorkflowRequestTests { @Test fun `test index workflow post request`() { - val req = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomWorkflow(auditDelegateMonitorAlerts = false) ) Assertions.assertNotNull(req) @@ -51,7 +54,11 @@ class IndexWorkflowRequestTests { @Test fun `test index composite workflow post request`() { val req = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomWorkflow() ) Assertions.assertNotNull(req) @@ -71,7 +78,11 @@ class IndexWorkflowRequestTests { @Test fun `Index composite workflow serialize and deserialize transport object should be equal`() { val compositeWorkflowRequest = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.POST, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.POST, randomWorkflow() ) @@ -89,9 +100,12 @@ class IndexWorkflowRequestTests { @Test fun `test index workflow put request`() { - val req = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflow() ) Assertions.assertNotNull(req) @@ -110,7 +124,11 @@ class IndexWorkflowRequestTests { @Test fun `test validate`() { val req = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflow(monitorIds = emptyList()) ) Assertions.assertNotNull(req) @@ -120,7 +138,11 @@ class IndexWorkflowRequestTests { Assert.assertTrue(validate!!.message!!.contains("Delegates list can not be empty.;")) // Duplicate delegate val req1 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflow(monitorIds = listOf("1L", "1L", "2L")) ) validate = req1.validate() @@ -133,7 +155,11 @@ class IndexWorkflowRequestTests { Delegate(2, "monitor-3") ) val req2 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates))) ) @@ -148,7 +174,11 @@ class IndexWorkflowRequestTests { Delegate(3, "monitor-3", ChainedMonitorFindings("monitor-x")) ) val req3 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates))) ) @@ -163,7 +193,11 @@ class IndexWorkflowRequestTests { Delegate(2, "monitor-3", ChainedMonitorFindings("monitor-2")) ) val req4 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates))) ) @@ -177,7 +211,11 @@ class IndexWorkflowRequestTests { monitorsIds.add(UUID.randomUUID().toString()) } val req5 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflow( monitorIds = monitorsIds ) @@ -187,7 +225,11 @@ class IndexWorkflowRequestTests { Assert.assertTrue(validate!!.message!!.contains("Delegates list can not be larger then 25.")) // Input list empty val req6 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = emptyList() ) @@ -204,11 +246,15 @@ class IndexWorkflowRequestTests { delegates = listOf( Delegate(1, "monitor-1"), Delegate(2, "monitor-2"), - Delegate(3, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))), + Delegate(3, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))) ) val req7 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates))) ) @@ -216,7 +262,11 @@ class IndexWorkflowRequestTests { assertNull(req7.validate()) try { IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates)), CompositeInput(Sequence(delegates = delegates))) ) @@ -230,11 +280,15 @@ class IndexWorkflowRequestTests { delegates = listOf( Delegate(1, "monitor-1"), Delegate(3, "monitor-2"), - Delegate(2, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))), + Delegate(2, "monitor-3", ChainedMonitorFindings(null, listOf("monitor-1", "monitor-2"))) ) val req8 = IndexWorkflowRequest( - "1234", 1L, 2L, WriteRequest.RefreshPolicy.IMMEDIATE, RestRequest.Method.PUT, + "1234", + 1L, + 2L, + WriteRequest.RefreshPolicy.IMMEDIATE, + RestRequest.Method.PUT, randomWorkflowWithDelegates( input = listOf(CompositeInput(Sequence(delegates = delegates))) ) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt index d29ef7c6..bbfc7793 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/action/PublishFindingsRequestTests.kt @@ -11,7 +11,6 @@ class PublishFindingsRequestTests { @Test fun `test delete monitor request`() { - val finding = randomFinding() val monitorId = "mid" val req = PublishFindingsRequest(monitorId, finding) diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt index 50615cb2..10579a41 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/FindingTests.kt @@ -24,7 +24,7 @@ internal class FindingTests { assertEquals( templateArgs[Finding.MONITOR_NAME_FIELD], finding.monitorName, - "Template args 'monitorName' field does not match:", + "Template args 'monitorName' field does not match:" ) assertEquals( templateArgs[Finding.QUERIES_FIELD], diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt index 1cd69176..590dda04 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/ScheduleTest.kt @@ -51,7 +51,8 @@ class ScheduleTest : XContentTestBase { val nextTimeToExecute = cronSchedule.getExpectedNextExecutionTime(enabledTimeInstance, null) assertNotNull(nextTimeToExecute, "There should be next execute time") assertEquals( - testInstance.plusSeconds(2L), nextTimeToExecute, + testInstance.plusSeconds(2L), + nextTimeToExecute, "nextTimeToExecute should be 2 seconds after test instance" ) } @@ -69,7 +70,8 @@ class ScheduleTest : XContentTestBase { val nextTimeToExecute = cronSchedule.getExpectedNextExecutionTime(enabledTimeInstance, previousExecutionTimeInstance) assertNotNull(nextTimeToExecute, "There should be next execute time") assertEquals( - previousExecutionTimeInstance.plusSeconds(2L), nextTimeToExecute, + previousExecutionTimeInstance.plusSeconds(2L), + nextTimeToExecute, "nextTimeToExecute should be 2 seconds after test instance" ) } @@ -87,7 +89,8 @@ class ScheduleTest : XContentTestBase { val nextTimeToExecute = intervalSchedule.getExpectedNextExecutionTime(enabledTimeInstance, null) assertNotNull(nextTimeToExecute, "There should be next execute time") assertEquals( - enabledTimeInstance.plusSeconds(120L), nextTimeToExecute, + enabledTimeInstance.plusSeconds(120L), + nextTimeToExecute, "nextTimeToExecute should be 120 seconds seconds after enabled time" ) } @@ -107,7 +110,8 @@ class ScheduleTest : XContentTestBase { val nextTimeToExecute = intervalSchedule.getExpectedNextExecutionTime(enabledTimeInstance, previousExecutionTimeInstance) assertNotNull(nextTimeToExecute, "There should be next execute time") assertEquals( - previousExecutionTimeInstance.plusSeconds(60L), nextTimeToExecute, + previousExecutionTimeInstance.plusSeconds(60L), + nextTimeToExecute, "nextTimeToExecute should be 60 seconds after previous execution time" ) } diff --git a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt index e56d4aab..fc93529a 100644 --- a/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt +++ b/src/test/kotlin/org/opensearch/commons/alerting/model/XContentTests.kt @@ -277,13 +277,15 @@ class XContentTests { val cmf1 = ChainedMonitorFindings(monitorId = "m1") val cmf1String = cmf1.toJsonString() Assertions.assertEquals( - ChainedMonitorFindings.parse(parser(cmf1String)), cmf1, + ChainedMonitorFindings.parse(parser(cmf1String)), + cmf1, "Round tripping chained monitor findings failed" ) val cmf2 = ChainedMonitorFindings(monitorIds = listOf("m1", "m2")) val cmf2String = cmf2.toJsonString() Assertions.assertEquals( - ChainedMonitorFindings.parse(parser(cmf2String)), cmf2, + ChainedMonitorFindings.parse(parser(cmf2String)), + cmf2, "Round tripping chained monitor findings failed" ) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt index ae7d0f3f..dd97cfda 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/NotificationsPluginInterfaceTests.kt @@ -202,7 +202,11 @@ internal class NotificationsPluginInterfaceTests { }.whenever(client).execute(any(ActionType::class.java), any(), any()) NotificationsPluginInterface.sendNotification( - client, notificationInfo, channelMessage, listOf("channelId1", "channelId2"), listener + client, + notificationInfo, + channelMessage, + listOf("channelId1", "channelId2"), + listener ) verify(listener, times(1)).onResponse(eq(response)) } diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt index 117375e7..73c446ac 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/CreateNotificationConfigRequestTests.kt @@ -125,6 +125,7 @@ internal class CreateNotificationConfigRequestTests { assertNull(recreatedObject.validate()) assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) } + @Test fun `Create config serialize and deserialize transport object should be equal microsoft teams`() { val configRequest = CreateNotificationConfigRequest( @@ -214,6 +215,7 @@ internal class CreateNotificationConfigRequestTests { assertNull(recreatedObject.validate()) assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) } + @Test fun `Create config serialize and deserialize using json object should be equal microsoft teams`() { val configRequest = CreateNotificationConfigRequest( @@ -309,6 +311,7 @@ internal class CreateNotificationConfigRequestTests { val recreatedObject = createObjectFromJsonString(jsonString) { CreateNotificationConfigRequest.parse(it) } assertEquals(config, recreatedObject.notificationConfig) } + @Test fun `Create config should deserialize json object using parser microsoft teams`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_microsoft_teams_url#1234567890") diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt index 4d828998..1de3c8fa 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/SendNotificationResponseTests.kt @@ -22,7 +22,6 @@ internal class SendNotificationResponseTests { @Test fun `Create response serialize and deserialize transport object should be equal`() { - val sampleEvent = getSampleEvent() val recreatedObject = recreateObject(sampleEvent) { SendNotificationResponse(it) } @@ -31,7 +30,6 @@ internal class SendNotificationResponseTests { @Test fun `Create response serialize and deserialize using json object should be equal`() { - val sampleEvent = getSampleEvent() val jsonString = getJsonString(sampleEvent) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt index e07d7747..fecd7710 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/action/UpdateNotificationConfigRequestTests.kt @@ -119,6 +119,7 @@ internal class UpdateNotificationConfigRequestTests { assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) assertEquals("config_id", recreatedObject.configId) } + @Test fun `Update config serialize and deserialize transport object should be equal Microsoft Teams`() { val configRequest = UpdateNotificationConfigRequest("config_id", createMicrosoftTeamsContentConfigObject()) @@ -187,6 +188,7 @@ internal class UpdateNotificationConfigRequestTests { assertEquals(configRequest.notificationConfig, recreatedObject.notificationConfig) assertEquals("config_id", recreatedObject.configId) } + @Test fun `Update config serialize and deserialize using json object should be equal microsoft Teams`() { val configRequest = UpdateNotificationConfigRequest("config_id", createMicrosoftTeamsContentConfigObject()) diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt index 31791120..ee17777a 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/NotificationConfigTests.kt @@ -202,7 +202,6 @@ internal class NotificationConfigTests { } @Test - fun `Config should safely ignore unknown config type in json object`() { val sampleSlack = Slack("https://domain.com/sample_slack_url#1234567890") val sampleConfig = NotificationConfig( diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt index ffdf26c7..6617d1f6 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/SmtpAccountTests.kt @@ -71,7 +71,8 @@ internal class SmtpAccountTests { fun `SmtpAccount should safely ignore extra field in json object`() { val sampleSmtpAccount = SmtpAccount( "domain.com", - 1234, MethodType.START_TLS, + 1234, + MethodType.START_TLS, "from@domain.com" ) val jsonString = """ diff --git a/src/test/kotlin/org/opensearch/commons/notifications/model/config/ConfigPropertiesTests.kt b/src/test/kotlin/org/opensearch/commons/notifications/model/config/ConfigPropertiesTests.kt index 881cf9d4..c3d20dee 100644 --- a/src/test/kotlin/org/opensearch/commons/notifications/model/config/ConfigPropertiesTests.kt +++ b/src/test/kotlin/org/opensearch/commons/notifications/model/config/ConfigPropertiesTests.kt @@ -76,6 +76,7 @@ internal class ConfigPropertiesTests { val recreatedObject = createObjectFromJsonString(jsonString) { createConfigData(ConfigType.WEBHOOK, it) } assertEquals(sampleWebhook, recreatedObject) } + @Test fun `Validate config data parse Microsoft Teams`() { val sampleMicrosoftTeams = MicrosoftTeams("https://domain.com/sample_url#1234567890") @@ -83,6 +84,7 @@ internal class ConfigPropertiesTests { val recreatedObject = createObjectFromJsonString(jsonString) { createConfigData(ConfigType.MICROSOFT_TEAMS, it) } assertEquals(sampleMicrosoftTeams, recreatedObject) } + @Test fun `Validate config data parse EmailGroup`() { val sampleEmailGroup = EmailGroup(listOf(EmailRecipient("email1@email.com"), EmailRecipient("email2@email.com")))