From ca67accd7dbf32c051ff7250f068be955a0879ff Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 22 Aug 2023 08:22:34 +0200 Subject: [PATCH 01/31] #17 - Assertion rename and simplification * Renamed assertion json tag to responseAction. * Refactored related logic and doc. --- README.md | 2 +- .../main/resources/schema/after.schema.json | 10 +-- .../main/resources/schema/before.schema.json | 10 +-- .../main/resources/schema/suite.schema.json | 10 +-- .../absa/testing/scapi/Exceptions.scala | 4 +- .../scapi/json/ReferenceResolver.scala | 24 +++--- .../absa/testing/scapi/json/Requestable.scala | 2 +- .../testing/scapi/json/SuiteFactory.scala | 24 +++--- .../absa/testing/scapi/model/Method.scala | 8 +- .../scapi/model/SuiteTestScenario.scala | 8 +- ...on.scala => AssertionResponseAction.scala} | 38 ++++----- ....scala => ExtractJsonResponseAction.scala} | 54 ++++++------ .../rest/response/LogResponseAction.scala | 82 +++++++++++++++++++ .../scapi/rest/response/Response.scala | 42 +++++----- .../scapi/rest/response/ResponseLog.scala | 82 ------------------- .../rest/response/ResponsePerformer.scala | 6 +- .../scapi/suite/runner/SuiteRunner.scala | 6 +- .../undefinedConstantIssue.suite.json | 2 +- .../gui-controller/deleteQuestion.suite.json | 2 +- .../gui-controller/getUserCurrent.after.json | 2 +- .../gui-controller/getUserCurrent.before.json | 2 +- .../gui-controller/getUserCurrent.suite.json | 2 +- .../gui-controller/postQuestion.suite.json | 2 +- .../gui-controller/putQuestion.suite.json | 2 +- .../testing/scapi/json/SuiteFactoryTest.scala | 18 ++-- .../response/ResponseAssertionsTest.scala | 44 +++++----- .../rest/response/ResponseExtractTest.scala | 64 +++++++-------- .../scapi/rest/response/ResponseLogTest.scala | 26 +++--- .../scapi/rest/response/ResponseTest.scala | 6 +- .../scapi/suite/runner/SuiteRunnerTest.scala | 22 ++--- 30 files changed, 303 insertions(+), 303 deletions(-) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ResponseAssertion.scala => AssertionResponseAction.scala} (69%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ResponseExtractJson.scala => ExtractJsonResponseAction.scala} (66%) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseLog.scala diff --git a/README.md b/README.md index 9942ee6..891fe21 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # ScAPI ### How to run api tests -TBD - work in progress +TODO - work in progress ### How to run unit tests Run unit tests from path `{project-root}` diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index 421bbb7..e174db4 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -42,10 +42,10 @@ "$ref": "#/definitions/Action" } }, - "assertions": { + "responseActions": { "type": "array", "items": { - "$ref": "#/definitions/Assertion" + "$ref": "#/definitions/ResponseAction" } } }, @@ -53,7 +53,7 @@ "name", "headers", "actions", - "assertions" + "responseActions" ], "title": "Method" }, @@ -100,7 +100,7 @@ ], "title": "Action" }, - "Assertion": { + "ResponseAction": { "type": "object", "additionalProperties": false, "properties": { @@ -121,7 +121,7 @@ "name", "param_1" ], - "title": "Assertion" + "title": "ResponseAction" }, "Param": { "type": "object", diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index b54982c..6ee3005 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -42,10 +42,10 @@ "$ref": "#/definitions/Action" } }, - "assertions": { + "responseActions": { "type": "array", "items": { - "$ref": "#/definitions/Assertion" + "$ref": "#/definitions/ResponseAction" } } }, @@ -53,7 +53,7 @@ "name", "headers", "actions", - "assertions" + "responseActions" ], "title": "Method" }, @@ -100,7 +100,7 @@ ], "title": "Action" }, - "Assertion": { + "ResponseAction": { "type": "object", "additionalProperties": false, "properties": { @@ -121,7 +121,7 @@ "name", "param_1" ], - "title": "Assertion" + "title": "ResponseAction" }, "Param": { "type": "object", diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index d2b7536..020d115 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -51,10 +51,10 @@ "$ref": "#/definitions/Action" } }, - "assertions": { + "responseActions": { "type": "array", "items": { - "$ref": "#/definitions/Assertion" + "$ref": "#/definitions/ResponseAction" } } }, @@ -63,7 +63,7 @@ "categories", "headers", "actions", - "assertions" + "responseActions" ], "title": "Test" }, @@ -110,7 +110,7 @@ ], "title": "Action" }, - "Assertion": { + "ResponseAction": { "type": "object", "additionalProperties": false, "properties": { @@ -131,7 +131,7 @@ "name", "param_1" ], - "title": "Assertion" + "title": "ResponseAction" }, "Param": { "type": "object", diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala b/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala index 449f543..78b1227 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala @@ -35,8 +35,8 @@ case class SuiteLoadFailed(detail: String) extends Exception(s"Problems during p case class UndefinedHeaderType(undefinedType: String) extends Exception(s"Undefined Header content type: '$undefinedType'") -case class UndefinedAssertionType(undefinedType: String) - extends Exception(s"Undefined Assertion content type: '$undefinedType'") +case class UndefinedResponseActionType(undefinedType: String) + extends Exception(s"Undefined response action content type: '$undefinedType'") case class ContentValidationFailed(value: String, message: String) extends Exception(s"Content validation failed for value: '$value': $message") diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index fdc54d2..6754a9b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -198,35 +198,35 @@ case class Action private(methodName: String, url: String, body: Option[String] } /** - * Case class that represents Assertion. - * This class is used to hold test assertions. + * Case class that represents ResponseAction. + * This class is used to hold test response action. * It implements the `ReferenceResolver` trait to support resolution of reference constants. * - * @constructor create a new Assertion with a name and value. - * @param name the name of the assertion. - * @param params the map containing the parameters of the assertion. Each key-value pair in the map + * @constructor create a new ResponseAction with a name and value. + * @param name the name of the response action. + * @param params the map containing the parameters of the response action. Each key-value pair in the map * represents a parameter name and its corresponding value. */ -case class Assertion private(group: String, - name: String, - params: Map[String, String]) extends ReferenceResolver { +case class ResponseAction private(group: String, + name: String, + params: Map[String, String]) extends ReferenceResolver { /** * Method to resolve references. * * @param references the map of references that may be used to resolve references in the value. - * @return a new Assertion instance with resolved references. + * @return a new ResponseAction instance with resolved references. */ - def resolveReferences(references: Map[String, String]): Assertion = this.copy( + def resolveReferences(references: Map[String, String]): ResponseAction = this.copy( params = this.params.map { case (k, v) => k -> getResolved(v, references) } ) /** * Method to resolve references using Runtime Cache. This method is used when the resolution of a reference is not possible at compile-time. * - * @return A new Assertion instance with resolved references. + * @return A new ResponseAction instance with resolved references. */ - def resolveByRuntimeCache(): Assertion = this.copy( + def resolveByRuntimeCache(): ResponseAction = this.copy( params = this.params.map { case (k, v) => k -> RuntimeCache.resolve(v) } ) } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala index 468b660..9830ae3 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala @@ -23,5 +23,5 @@ trait Requestable { def actions: Set[Action] - def assertions: Set[Assertion] + def responseActions: Set[ResponseAction] } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index 5a38d5e..1be1dd2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -259,7 +259,7 @@ object SuiteFactory { /** * This method validates the content of a SuiteBundle. - * It checks the suite's headers, body, parameters, and assertions. + * It checks the suite's headers, body, parameters, and response action. * * @param suiteBundle The SuiteBundle to be validated. */ @@ -269,7 +269,7 @@ object SuiteFactory { test.headers.foreach(header => RequestHeaders.validateContent(header)) RequestBody.validateContent(test.actions.head.body) RequestParams.validateContent(test.actions.head.params) - test.assertions.foreach(assertion => Response.validate(assertion)) + test.responseActions.foreach(responseAction => Response.validate(responseAction)) }) } } @@ -281,7 +281,7 @@ object SuiteJsonProtocol extends DefaultJsonProtocol { implicit val headerFormat: RootJsonFormat[Header] = jsonFormat2(Header) implicit val paramFormat: RootJsonFormat[Param] = jsonFormat2(Param) implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) - implicit val assertionFormat: RootJsonFormat[Assertion] = AssertionJsonProtocol.AssertionJsonFormat + implicit val assertionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val suiteTestFormat: RootJsonFormat[SuiteTestScenario] = jsonFormat6(SuiteTestScenario) implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) implicit val suiteFormat: RootJsonFormat[Suite] = jsonFormat2(Suite) @@ -301,7 +301,7 @@ object SuiteBeforeJsonProtocol extends DefaultJsonProtocol { implicit val headerFormat: RootJsonFormat[Header] = jsonFormat2(Header) implicit val paramFormat: RootJsonFormat[Param] = jsonFormat2(Param) implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) - implicit val assertionFormat: RootJsonFormat[Assertion] = AssertionJsonProtocol.AssertionJsonFormat + implicit val responseActionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) implicit val suiteBeforeFormat: RootJsonFormat[SuiteBefore] = jsonFormat2(SuiteBefore) } @@ -313,29 +313,29 @@ object SuiteAfterJsonProtocol extends DefaultJsonProtocol { implicit val headerFormat: RootJsonFormat[Header] = jsonFormat2(Header) implicit val paramFormat: RootJsonFormat[Param] = jsonFormat2(Param) implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) - implicit val assertionFormat: RootJsonFormat[Assertion] = AssertionJsonProtocol.AssertionJsonFormat + implicit val assertionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) implicit val suiteAfterFormat: RootJsonFormat[SuiteAfter] = jsonFormat2(SuiteAfter) } /** - * Object that provides implicit JSON format for Assertion class. + * Object that provides implicit JSON format for ResponseAction class. */ -object AssertionJsonProtocol extends DefaultJsonProtocol { +object ResponseActionJsonProtocol extends DefaultJsonProtocol { - implicit object AssertionJsonFormat extends RootJsonFormat[Assertion] { - def write(a: Assertion): JsObject = JsObject( + implicit object ResponseActionJsonFormat extends RootJsonFormat[ResponseAction] { + def write(a: ResponseAction): JsObject = JsObject( ("group" -> JsString(a.group)) +: ("name" -> JsString(a.name)) +: a.params.view.mapValues(JsString(_)).toSeq: _* ) - def read(value: JsValue): Assertion = { + def read(value: JsValue): ResponseAction = { value.asJsObject.getFields("group", "name") match { case Seq(JsString(group), JsString(name)) => val params = value.asJsObject.fields.view.filterKeys(_.startsWith("param_")).toMap - Assertion(group, name, params.map { case (k, v) => k -> v.convertTo[String] }) - case _ => throw new DeserializationException("Assertion expected") + ResponseAction(group, name, params.map { case (k, v) => k -> v.convertTo[String] }) + case _ => throw DeserializationException("Assertion expected") } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala index 8087c89..224702d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.model -import africa.absa.testing.scapi.json.{Action, Assertion, Header, Requestable} +import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseAction} /** * Case class that represents a single method. @@ -24,12 +24,12 @@ import africa.absa.testing.scapi.json.{Action, Assertion, Header, Requestable} * @param name The name of the method. * @param headers The set of header options for the method. * @param actions The set of action objects for the method. - * @param assertions The set of assertion objects for the method. + * @param responseActions The set of responseAction objects for the method. */ case class Method(name: String, headers: Set[Header], actions: Set[Action], - assertions: Set[Assertion]) extends Requestable { + responseActions: Set[ResponseAction]) extends Requestable { /** * Method to resolve references within the Method instance. * @@ -41,7 +41,7 @@ case class Method(name: String, name, headers.map(c => c.resolveReferences(references)), actions.map(c => c.resolveReferences(references)), - assertions.map(c => c.resolveReferences(references)) + responseActions.map(c => c.resolveReferences(references)) ) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala index 3d4a9d3..b01efa7 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.model -import africa.absa.testing.scapi.json.{Action, Assertion, Header, Requestable} +import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseAction} /** * Case class that represents a suite test scenario. @@ -25,14 +25,14 @@ import africa.absa.testing.scapi.json.{Action, Assertion, Header, Requestable} * @param categories The required test categories of the test scenario. * @param headers The set of header options for the test scenario. * @param actions The set of action objects for the test scenario. - * @param assertions The set of assertion objects for the test scenario. + * @param responseActions The set of responseAction objects for the test scenario. * @param only The control if test should be only be running when set to true. */ case class SuiteTestScenario(name: String, categories: Set[String], headers: Set[Header], actions: Set[Action], - assertions: Set[Assertion], + responseActions: Set[ResponseAction], only: Option[Boolean] = Some(false)) extends Requestable { /** * Method to resolve references within the SuiteTestScenario instance. @@ -46,7 +46,7 @@ case class SuiteTestScenario(name: String, categories, headers.map(c => c.resolveReferences(references)), actions.map(c => c.resolveReferences(references)), - assertions.map(c => c.resolveReferences(references)), + responseActions.map(c => c.resolveReferences(references)), only ) } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseAssertion.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala similarity index 69% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseAssertion.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index b52b198..574bf0a 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseAssertion.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -16,60 +16,60 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedAssertionType -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.validation.ContentValidator /** - * Object that validates and performs various assertions on the response received. + * Object that validates and performs various assertion response actions on the response received. * It extends the functionality of ResponsePerformer. */ -object ResponseAssertion extends ResponsePerformer { +object AssertionResponseAction extends ResponsePerformer { val STATUS_CODE = "status-code" val BODY_CONTAINS = "body-contains" /** - * Validates the content of an assertion object depending on its type. + * Validates the content of an assertion response action object depending on its type. * - * @param assertion The assertion object to be validated. - * @throws UndefinedAssertionType If the assertion type is not recognized. + * @param responseAction The response action object to be validated. + * @throws UndefinedResponseActionType If the response action type is not recognized. */ - def validateContent(assertion: Assertion): Unit = { - assertion.name.toLowerCase match { + def validateContent(responseAction: ResponseAction): Unit = { + responseAction.name.toLowerCase match { case STATUS_CODE => - assertion.params.get("param_1") match { + responseAction.params.get("param_1") match { case param_1 => ContentValidator.validateIntegerString(param_1.get, s"ResponseAssertion.$STATUS_CODE.param_1") case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $STATUS_CODE") } case BODY_CONTAINS => - assertion.params.get("param_1") match { + responseAction.params.get("param_1") match { case param_1 => ContentValidator.validateNonEmptyString(param_1.get, s"ResponseAssertion.$BODY_CONTAINS.param_1") case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $BODY_CONTAINS") } - case _ => throw UndefinedAssertionType(assertion.name) + case _ => throw UndefinedResponseActionType(responseAction.name) } } /** - * Performs assertions on a response depending on the type of assertion provided. + * Performs assertion actions on a response depending on the type of assertion action provided. * * @param response The response to perform the assertions on. - * @param assertion The assertion to perform on the response. + * @param responseAction The assertion response action to perform on the response. * @return Boolean value indicating whether the assertion passed or failed. * @throws IllegalArgumentException If the assertion type is not supported. */ - def performAssertion(response: Response, assertion: Assertion): Boolean = { - assertion.name match { + def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + responseAction.name match { case STATUS_CODE => - val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) + val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) assertStatusCode(response, param_1) case BODY_CONTAINS => - val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) + val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) assertBodyContains(response, param_1) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: assert]: ${assertion.name}") + case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: assert]: ${responseAction.name}") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseExtractJson.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala similarity index 66% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseExtractJson.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala index 84bafc6..40ee111 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseExtractJson.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala @@ -16,53 +16,53 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedAssertionType -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator import spray.json._ /** - * ResponseExtractJson is an object that extends ResponsePerformer. + * ExtractJsonResponseAction is an object that extends ResponsePerformer. * It is designed to extract specific data from a JSON response and perform validations. */ -object ResponseExtractJson extends ResponsePerformer { +object ExtractJsonResponseAction extends ResponsePerformer { val STRING_FROM_LIST = "string-from-list" /** - * This method validates the assertion's content based on the assertion's name. - * It supports the STRING_FROM_LIST type of assertion. + * This method validates the response action's content based on the response action's name. + * It supports the STRING_FROM_LIST type of response action. * - * @param assertion The Assertion instance to be validated. - * @throws UndefinedAssertionType if an unsupported assertion type is encountered. + * @param responseAction The ResponseAction instance to be validated. + * @throws UndefinedResponseActionType if an unsupported assertion type is encountered. */ - def validateContent(assertion: Assertion): Unit = { - assertion.name.toLowerCase match { - case STRING_FROM_LIST => validateStringFromList(assertion) - case _ => throw UndefinedAssertionType(assertion.name) + def validateContent(responseAction: ResponseAction): Unit = { + responseAction.name.toLowerCase match { + case STRING_FROM_LIST => validateStringFromList(responseAction) + case _ => throw UndefinedResponseActionType(responseAction.name) } } /** - * This method performs assertions on a given response based on the assertion's name. - * It supports the STRING_FROM_LIST type of assertion. + * This method performs response actions on a given response based on the response action's name. + * It supports the STRING_FROM_LIST type of response action. * - * @param response The Response instance to perform assertions on. - * @param assertion The Assertion instance containing the assertion details. - * @throws IllegalArgumentException if an unsupported assertion group is encountered. + * @param response The Response instance to perform response action on. + * @param responseAction The ResponseAction instance containing the response action details. + * @throws IllegalArgumentException if an unsupported response action name is encountered. */ - def performAssertion(response: Response, assertion: Assertion): Boolean = { - assertion.name match { + def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + responseAction.name match { case STRING_FROM_LIST => - val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - val param_2 = assertion.params.get("param_2").map(_.toInt).getOrElse(throw new IllegalArgumentException("param_2 is missing")) - val param_3 = assertion.params.getOrElse("param_3", throw new IllegalArgumentException("param_3 is missing")) - val param_4 = assertion.params.getOrElse("param_4", throw new IllegalArgumentException("param_4 is missing")) + val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) + val param_2 = responseAction.params.get("param_2").map(_.toInt).getOrElse(throw new IllegalArgumentException("param_2 is missing")) + val param_3 = responseAction.params.getOrElse("param_3", throw new IllegalArgumentException("param_3 is missing")) + val param_4 = responseAction.params.getOrElse("param_4", throw new IllegalArgumentException("param_4 is missing")) stringFromList(response, param_1, param_2, param_3, param_4) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: extract]: ${assertion.name}") + case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: extract]: ${responseAction.name}") } } @@ -111,13 +111,13 @@ object ResponseExtractJson extends ResponsePerformer { } /** - * This method validates the parameters of the STRING_FROM_LIST type of assertion. + * This method validates the parameters of the STRING_FROM_LIST type of response action. * It ensures none of the required parameters are None and validates that they are non-empty strings. * Additionally, it ensures param_2 is a valid integer. * - * @param assertion The Assertion instance containing the assertion details. + * @param assertion The ResponseAction instance containing the response action details. */ - def validateStringFromList(assertion: Assertion): Unit = { + def validateStringFromList(assertion: ResponseAction): Unit = { val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) val param_2 = assertion.params.getOrElse("param_2", throw new IllegalArgumentException("param_2 is missing")) val param_3 = assertion.params.getOrElse("param_3", throw new IllegalArgumentException("param_3 is missing")) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala new file mode 100644 index 0000000..1ed58bc --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -0,0 +1,82 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response + +import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.logging.Logger +import africa.absa.testing.scapi.utils.validation.ContentValidator + +/** + * Singleton object `ResponseLog` that extends the `ResponsePerformer` trait. + * It provides utilities for validating and performing logging messages. + */ +object LogResponseAction extends ResponsePerformer { + + val INFO = "info" + + /** + * This method validates the content of the response action. + * It checks if the response action's name is "info", then validates if its `param_1` is a non-empty string. + * For all other response action names, it throws an `UndefinedAssertionType` exception. + * + * @param responseAction The response action to be validated. + * @throws UndefinedResponseActionType if the response action's name is not recognized. + */ + def validateContent(responseAction: ResponseAction): Unit = { + responseAction.name.toLowerCase match { + case INFO => + responseAction.params.get("param_1") match { + case param_1 => ContentValidator.validateNonEmptyString(param_1.get, s"ResponseLog.$INFO.param_1") + case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $INFO") + } + case _ => throw UndefinedResponseActionType(responseAction.name) + } + } + + /** + * This method performs the necessary response actions on the response. + * It checks if the response action's name is "info", then logs the `param_1` as info message. + * For all other response action names, it throws an `IllegalArgumentException`. + * + * @param response The response on which the response action are to be performed. + * @param responseAction The responseAction to be performed on the response. + * @throws IllegalArgumentException if the response action's name is not recognized. + */ + def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + responseAction.name match { + case INFO => + val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) + logInfo(param_1) + case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: log]: ${responseAction.name}") + } + } + + /* + dedicated actions + */ + + /** + * This method logs a message at the INFO level. + * + * @param message The message to be logged. + */ + def logInfo(message: String): Boolean = { + Logger.info(message) + true + } +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 4bf33ac..df74355 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.json.ResponseAction case class Response(statusCode: Int, body: String, headers: Map[String, Seq[String]]) @@ -30,39 +30,39 @@ object Response { val GROUP_LOG: String = "log" /** - * Validates an Assertion based on its group type. + * Validates an ResponseAction based on its group type. * Calls the appropriate group's validateContent method based on group type. * - * @param assertion The assertion to be validated. - * @throws IllegalArgumentException If the assertion group type is not supported. + * @param responseAction The responseAction to be validated. + * @throws IllegalArgumentException If the response action group is not supported. */ - def validate(assertion: Assertion): Unit = { - assertion.group match { - case GROUP_ASSERT => ResponseAssertion.validateContent(assertion) - case GROUP_EXTRACT_JSON => ResponseExtractJson.validateContent(assertion) - case GROUP_LOG => ResponseLog.validateContent(assertion) - case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}") + def validate(responseAction: ResponseAction): Unit = { + responseAction.group match { + case GROUP_ASSERT => AssertionResponseAction.validateContent(responseAction) + case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.validateContent(responseAction) + case GROUP_LOG => LogResponseAction.validateContent(responseAction) + case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${responseAction.group}") } } /** * Performs actions on the given Response based on a set of Assertions. - * Each Assertion is resolved by the runtime cache before being used. + * Each response action is resolved by the runtime cache before being used. * The appropriate group's performAssertions method is called based on the group type of each Assertion. * Returns true only if all assertions return true, and false as soon as any assertion returns false. * * @param response The response on which actions will be performed. - * @param assertions The set of assertions that dictate what actions will be performed on the response. - * @return Boolean indicating whether all assertions passed (true) or any assertion failed (false). - * @throws IllegalArgumentException If an assertion group type is not supported. + * @param responseAction The set of response actions that dictate what actions will be performed on the response. + * @return Boolean indicating whether all response actions passed (true) or any response action failed (false). + * @throws IllegalArgumentException If an response action group is not supported. */ - def perform(response: Response, assertions: Set[Assertion]): Boolean = { - assertions.forall { assertion => - val resolvedAssertion: Assertion = assertion.resolveByRuntimeCache() - resolvedAssertion.group match { - case GROUP_ASSERT => ResponseAssertion.performAssertion(response, assertion) - case GROUP_EXTRACT_JSON => ResponseExtractJson.performAssertion(response, assertion) - case GROUP_LOG => ResponseLog.performAssertion(response, assertion) + def perform(response: Response, responseAction: Set[ResponseAction]): Boolean = { + responseAction.forall { assertion => + val resolvedResponseAction: ResponseAction = assertion.resolveByRuntimeCache() + resolvedResponseAction.group match { + case GROUP_ASSERT => AssertionResponseAction.performResponseAction(response, assertion) + case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) + case GROUP_LOG => LogResponseAction.performResponseAction(response, assertion) case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseLog.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseLog.scala deleted file mode 100644 index f5bbc4d..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseLog.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.rest.response - -import africa.absa.testing.scapi.UndefinedAssertionType -import africa.absa.testing.scapi.json.Assertion -import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.utils.validation.ContentValidator - -/** - * Singleton object `ResponseLog` that extends the `ResponsePerformer` trait. - * It provides utilities for validating and performing assertions, and logging info messages. - */ -object ResponseLog extends ResponsePerformer { - - val INFO = "info" - - /** - * This method validates the content of the assertion. - * It checks if the assertion's name is "info", then validates if its `param_1` is a non-empty string. - * For all other assertion names, it throws an `UndefinedAssertionType` exception. - * - * @param assertion The assertion to be validated. - * @throws UndefinedAssertionType if the assertion's name is not recognized. - */ - def validateContent(assertion: Assertion): Unit = { - assertion.name.toLowerCase match { - case INFO => - assertion.params.get("param_1") match { - case param_1 => ContentValidator.validateNonEmptyString(param_1.get, s"ResponseLog.$INFO.param_1") - case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $INFO") - } - case _ => throw UndefinedAssertionType(assertion.name) - } - } - - /** - * This method performs the necessary assertions on the response. - * It checks if the assertion's name is "info", then logs the `param_1` as info message. - * For all other assertion names, it throws an `IllegalArgumentException`. - * - * @param response The response on which the assertions are to be performed. - * @param assertion The assertion to be performed on the response. - * @throws IllegalArgumentException if the assertion's name is not recognized. - */ - def performAssertion(response: Response, assertion: Assertion): Boolean = { - assertion.name match { - case INFO => - val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - logInfo(param_1) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: log]: ${assertion.name}") - } - } - - /* - dedicated actions - */ - - /** - * This method logs a message at the INFO level. - * - * @param message The message to be logged. - */ - def logInfo(message: String): Boolean = { - Logger.info(message) - true - } -} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala index 333dcc1..e430305 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala @@ -16,9 +16,9 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.json.ResponseAction trait ResponsePerformer { - def validateContent(assertion: Assertion): Unit - def performAssertion(response: Response, assertion: Assertion): Boolean + def validateContent(responseAction: ResponseAction): Unit + def performResponseAction(response: Response, responseAction: ResponseAction): Boolean } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index d9b2da1..3a9ae08 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -87,7 +87,7 @@ object SuiteRunner { val response: Response = sendRequest(method, environment, restClientCreator) val isSuccess: Boolean = Response.perform( response = response, - assertions = method.assertions + responseAction = method.responseActions ) val testEndTime: Long = System.currentTimeMillis() @@ -120,7 +120,7 @@ object SuiteRunner { val response: Response = sendRequest(test, environment, restClientCreator) val isSuccess: Boolean = Response.perform( response = response, - assertions = test.assertions + responseAction = test.responseActions ) val testEndTime: Long = System.currentTimeMillis() @@ -158,7 +158,7 @@ object SuiteRunner { val response: Response = sendRequest(method, environment, restClientCreator) val isSuccess: Boolean = Response.perform( response = response, - assertions = method.assertions + responseAction = method.responseActions ) val testEndTime: Long = System.currentTimeMillis() diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index 5be31b9..820563e 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -16,7 +16,7 @@ "url": "{{ env.url }}/AULGUI/user" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index 4b05974..5704da5 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -20,7 +20,7 @@ "url": "{{ env.url }}/path/question" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index 22b8ace..383df6f 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -19,7 +19,7 @@ "url": "{{ env.url }}/AULGUI/user" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "statusCode", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json index a8ae9e2..2c39525 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json @@ -19,7 +19,7 @@ "url": "{{ env.url }}/AULGUI/user" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 7d8dc9c..e25e0c8 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -20,7 +20,7 @@ "url": "{{ env.url }}/GUI/user" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index 6e9c281..4de6dd7 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -27,7 +27,7 @@ ] } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index f1e01df..f793d67 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -20,7 +20,7 @@ "url": "{{ env.url }}/path/question" } ], - "assertions": [ + "responseActions": [ { "group": "assert", "name": "status-code", diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index 6cce77a..2814931 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -33,7 +33,7 @@ class SuiteFactoryTest extends FunSuite { private var out: ByteArrayOutputStream = _ private def initTestLogger(): Unit = { - ctx = (LogManager.getContext(false).asInstanceOf[LoggerContext]) + ctx = LogManager.getContext(false).asInstanceOf[LoggerContext] val config = ctx.getConfiguration val layout = PatternLayout.createDefaultLayout(config) out = new ByteArrayOutputStream() @@ -130,15 +130,15 @@ class SuiteFactoryTest extends FunSuite { test("filterOnlyOrAll - only used - once") { val suitesBundles = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(false)), + SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), )))) val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) @@ -157,11 +157,11 @@ class SuiteFactoryTest extends FunSuite { test("fromFile - only used - twice") { val suitesBundles = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, assertions = Set.empty, only = Some(true)), + SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)), )))) val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 618e795..050153b 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -16,8 +16,8 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.json.Assertion -import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedAssertionType} +import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedResponseActionType} import munit.FunSuite class ResponseAssertionsTest extends FunSuite { @@ -26,69 +26,69 @@ class ResponseAssertionsTest extends FunSuite { validateContent */ test("validateContent - valid status code string") { - val assertion = Assertion(group = Response.GROUP_ASSERT, name = ResponseAssertion.STATUS_CODE, Map("param_1" -> "200")) - ResponseAssertion.validateContent(assertion) + val assertion = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "200")) + AssertionResponseAction.validateContent(assertion) } test("validateContent - invalid status code string") { intercept[ContentValidationFailed] { - ResponseAssertion.validateContent(Assertion(group = Response.GROUP_ASSERT, name = ResponseAssertion.STATUS_CODE, Map("param_1" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "not an integer"))) } } test("validateContent - body is not empty") { - val assertion = Assertion(group = Response.GROUP_ASSERT, name = ResponseAssertion.BODY_CONTAINS, Map("param_1" -> "test content")) - ResponseAssertion.validateContent(assertion) + val assertion = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.BODY_CONTAINS, Map("param_1" -> "test content")) + AssertionResponseAction.validateContent(assertion) } test("validateContent - body is empty") { intercept[ContentValidationFailed] { - ResponseAssertion.validateContent(Assertion(group = Response.GROUP_ASSERT, name = ResponseAssertion.BODY_CONTAINS, Map("param_1" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.BODY_CONTAINS, Map("param_1" -> ""))) } } - test("validateContent - unsupported assertion") { - intercept[UndefinedAssertionType] { - ResponseAssertion.validateContent(Assertion(group = Response.GROUP_ASSERT, name = "unsupported", Map("param_1" -> "value"))) + test("validateContent - unsupported response action") { + intercept[UndefinedResponseActionType] { + AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = "unsupported", Map("param_1" -> "value"))) } } /* - performAssertions + performResponseAction */ test("performAssertions - status code assertion - equals") { - val statusCodeAssertion = Assertion(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) val response = Response(200, "Dummy Body", Map.empty) - assert(ResponseAssertion.performAssertion(response, statusCodeAssertion)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - status code assertion - not equals") { - val statusCodeAssertion = Assertion(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) val response = Response(500, "Dummy Body", Map.empty) - assert(!ResponseAssertion.performAssertion(response, statusCodeAssertion)) + assert(!AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - body contains assertion") { - val bodyContainsAssertion = Assertion(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummy")) + val bodyContainsAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummy")) val response = Response(200, "This is a dummy body", Map.empty) - assert(ResponseAssertion.performAssertion(response, bodyContainsAssertion)) + assert(AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - body does not contains assertion") { - val bodyContainsAssertion = Assertion(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummies")) + val bodyContainsAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummies")) val response = Response(200, "This is a dummy body", Map.empty) - assert(!ResponseAssertion.performAssertion(response, bodyContainsAssertion)) + assert(!AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - unsupported assertion") { - val unsupportedAssertion = Assertion(group = Response.GROUP_ASSERT, name = "unsupported-assertion", Map("param_1" -> "value")) + val unsupportedAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "unsupported-assertion", Map("param_1" -> "value")) val response = Response(200, "Dummy Body", Map.empty) interceptMessage[IllegalArgumentException]("Unsupported assertion[group: assert]: unsupported-assertion") { - ResponseAssertion.performAssertion(response, unsupportedAssertion) + AssertionResponseAction.performResponseAction(response, unsupportedAssertion) } } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index 3f86f79..7da228e 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -16,15 +16,15 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedAssertionType} -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedResponseActionType} +import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite class ResponseExtractTest extends FunSuite { - val assertionStringFromList: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "question_id", "param_2" -> "1", "param_3" -> "id", "param_4" -> "suite")) - val assertionUnsupported: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, "Unsupported", Map("param_1" -> "key", "param_2" -> "200", "param_3" -> "jsonKey", "param_4" -> "Test")) + val assertionStringFromList: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "question_id", "param_2" -> "1", "param_3" -> "id", "param_4" -> "suite")) + val assertionUnsupported: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, "Unsupported", Map("param_1" -> "key", "param_2" -> "200", "param_3" -> "jsonKey", "param_4" -> "Test")) val responseWithID: Response = Response( 200, @@ -44,28 +44,28 @@ class ResponseExtractTest extends FunSuite { */ test("validateContent - STRING_FROM_LIST") { - ResponseExtractJson.validateContent(assertionStringFromList) + ExtractJsonResponseAction.validateContent(assertionStringFromList) } test("validateContent - unsupported option") { - intercept[UndefinedAssertionType] { - ResponseExtractJson.validateContent(assertionUnsupported) + intercept[UndefinedResponseActionType] { + ExtractJsonResponseAction.validateContent(assertionUnsupported) } } /* - performAssertion + performResponseAction */ test("performAssertion - STRING_FROM_LIST") { - val result: Boolean = ResponseExtractJson.performAssertion(responseWithID, assertionStringFromList) + val result: Boolean = ExtractJsonResponseAction.performResponseAction(responseWithID, assertionStringFromList) assert(result) assertEquals("382be85a-1f00-4c15-b607-cbda03ccxxx2", RuntimeCache.get("question_id").get) } test("performAssertion - unsupported assertion") { intercept[IllegalArgumentException] { - ResponseExtractJson.performAssertion(responseWithID, assertionUnsupported) + ExtractJsonResponseAction.performResponseAction(responseWithID, assertionUnsupported) } } @@ -81,7 +81,7 @@ class ResponseExtractTest extends FunSuite { val jsonKey = "id" val runtimeCacheLevel = "Test" interceptMessage[IndexOutOfBoundsException]("10 is out of bounds (min 0, max 2)") { - ResponseExtractJson.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) + ExtractJsonResponseAction.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) } } @@ -90,7 +90,7 @@ class ResponseExtractTest extends FunSuite { val listIndex = 0 val jsonKey = "ids" val runtimeCacheLevel = "Test" - val result = ResponseExtractJson.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) + val result = ExtractJsonResponseAction.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) assert(!result) } @@ -100,7 +100,7 @@ class ResponseExtractTest extends FunSuite { val jsonKey = "id" val runtimeCacheLevel = "Test" - val result = ResponseExtractJson.stringFromList(responseNoJsonBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) + val result = ExtractJsonResponseAction.stringFromList(responseNoJsonBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) assert(!result) } @@ -110,7 +110,7 @@ class ResponseExtractTest extends FunSuite { val jsonKey = "id" val runtimeCacheLevel = "Test" - val result = ResponseExtractJson.stringFromList(responseJsonNoArrayBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) + val result = ExtractJsonResponseAction.stringFromList(responseJsonNoArrayBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) assert(!result) } @@ -121,49 +121,49 @@ class ResponseExtractTest extends FunSuite { // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" test("validateStringFromList - None parameters") { - val assertion1None: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "")) - val assertion2None: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "")) - val assertion3None: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "")) - val assertion4None: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map()) + val assertion1None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "")) + val assertion2None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "")) + val assertion3None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "")) + val assertion4None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map()) interceptMessage[IllegalArgumentException]("param_1 is missing") { - ResponseExtractJson.validateStringFromList(assertion4None) + ExtractJsonResponseAction.validateStringFromList(assertion4None) } interceptMessage[IllegalArgumentException]("param_2 is missing") { - ResponseExtractJson.validateStringFromList(assertion3None) + ExtractJsonResponseAction.validateStringFromList(assertion3None) } interceptMessage[IllegalArgumentException]("param_3 is missing") { - ResponseExtractJson.validateStringFromList(assertion2None) + ExtractJsonResponseAction.validateStringFromList(assertion2None) } interceptMessage[IllegalArgumentException]("param_4 is missing") { - ResponseExtractJson.validateStringFromList(assertion1None) + ExtractJsonResponseAction.validateStringFromList(assertion1None) } } test("validateStringFromList - empty parameters") { - val assertionParam1: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam2: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam3: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "", "param_4" -> "")) - val assertionParam4: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "y", "param_4" -> "")) + val assertionParam1: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "", "param_4" -> "")) + val assertionParam2: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "", "param_3" -> "", "param_4" -> "")) + val assertionParam3: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "", "param_4" -> "")) + val assertionParam4: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "y", "param_4" -> "")) interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_1' is empty.") { - ResponseExtractJson.validateStringFromList(assertionParam1) + ExtractJsonResponseAction.validateStringFromList(assertionParam1) } interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_2' is empty.") { - ResponseExtractJson.validateStringFromList(assertionParam2) + ExtractJsonResponseAction.validateStringFromList(assertionParam2) } interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_3' is empty.") { - ResponseExtractJson.validateStringFromList(assertionParam3) + ExtractJsonResponseAction.validateStringFromList(assertionParam3) } interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_4' is empty.") { - ResponseExtractJson.validateStringFromList(assertionParam4) + ExtractJsonResponseAction.validateStringFromList(assertionParam4) } } test("validateStringFromList - not integer in string") { - val assertion: Assertion = Assertion(Response.GROUP_EXTRACT_JSON, ResponseExtractJson.STRING_FROM_LIST, Map("param_1" -> "key", "param_2" -> "x", "param_3" -> "y", "param_4" -> "y")) + val assertion: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "key", "param_2" -> "x", "param_3" -> "y", "param_4" -> "y")) interceptMessage[ContentValidationFailed]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.param_2' cannot be parsed to an integer: For input string: \"x\"") { - ResponseExtractJson.validateStringFromList(assertion) + ExtractJsonResponseAction.validateStringFromList(assertion) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index 8001b43..bbc586c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -16,8 +16,8 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedAssertionType -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.json.ResponseAction import munit.FunSuite class ResponseLogTest extends FunSuite { @@ -26,33 +26,33 @@ class ResponseLogTest extends FunSuite { validateContent */ test("validateContent - INFO supported") { - val assertionInfo = Assertion(Response.GROUP_LOG, ResponseLog.INFO, Map("param_1" -> "Non-empty string")) + val responseActionInfo = ResponseAction(Response.GROUP_LOG, LogResponseAction.INFO, Map("param_1" -> "Non-empty string")) // no exception thrown, meaning validation passed - ResponseLog.validateContent(assertionInfo) + LogResponseAction.validateContent(responseActionInfo) } test("validateContent - not supported validation type") { - val assertion = Assertion(Response.GROUP_LOG, "not_info", Map("param_1" -> "Some string")) - intercept[UndefinedAssertionType] { - ResponseLog.validateContent(assertion) + val responseAction = ResponseAction(Response.GROUP_LOG, "not_info", Map("param_1" -> "Some string")) + intercept[UndefinedResponseActionType] { + LogResponseAction.validateContent(responseAction) } } /* - performAssertion + performResponseAction */ test("performAssertion - INFO supported") { - val assertion = Assertion(Response.GROUP_LOG, ResponseLog.INFO, Map("param_1" -> "info message")) + val assertion = ResponseAction(Response.GROUP_LOG, LogResponseAction.INFO, Map("param_1" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) - assertEquals(ResponseLog.performAssertion(response, assertion), true) + assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - not supported validation type") { - val assertion = Assertion(Response.GROUP_LOG, "not_info", Map("param_1" -> "info message")) + val assertion = ResponseAction(Response.GROUP_LOG, "not_info", Map("param_1" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) intercept[IllegalArgumentException] { - ResponseLog.performAssertion(response, assertion) + LogResponseAction.performResponseAction(response, assertion) } } @@ -61,6 +61,6 @@ class ResponseLogTest extends FunSuite { */ test("logInfo") { - assertEquals(ResponseLog.logInfo("log message"), true) + assertEquals(LogResponseAction.logInfo("log message"), true) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala index 0d87617..548f0ff 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.json.Assertion +import africa.absa.testing.scapi.json.ResponseAction import munit.FunSuite class ResponseTest extends FunSuite { @@ -26,7 +26,7 @@ class ResponseTest extends FunSuite { */ test("validate - unsupported group") { - val unsupportedAssertion = Assertion("unsupportedGroup", "not needed", Map("param 1" -> "")) + val unsupportedAssertion = ResponseAction("unsupportedGroup", "not needed", Map("param 1" -> "")) intercept[IllegalArgumentException] { Response.validate(unsupportedAssertion) @@ -38,7 +38,7 @@ class ResponseTest extends FunSuite { */ test("perform - unsupported group") { - val unsupportedAssertion = Assertion("unsupportedGroup", "not needed", Map("param 1" -> "")) + val unsupportedAssertion = ResponseAction("unsupportedGroup", "not needed", Map("param 1" -> "")) val response = Response(200, "OK", Map.empty) intercept[IllegalArgumentException] { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index b5a6239..276e5b9 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -16,12 +16,12 @@ package africa.absa.testing.scapi.suite.runner -import africa.absa.testing.scapi.json.{Action, Assertion, Environment, Header} +import africa.absa.testing.scapi.json.{Action, Environment, Header, ResponseAction} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.rest.response.{Response, ResponseAssertion} +import africa.absa.testing.scapi.rest.response.{AssertionResponseAction, Response} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite import org.apache.logging.log4j.Level @@ -31,22 +31,22 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val assertion: Assertion = Assertion(group = Response.GROUP_ASSERT, name = ResponseAssertion.STATUS_CODE, Map("param_1" -> "200")) - val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), assertions = Set(assertion)) - val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), assertions = Set(assertion)) + val assertion: ResponseAction = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "200")) + val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(assertion)) + val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(assertion)) val suitesBundles: Set[SuiteBundle] = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(true)), + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(true)), SuiteTestScenario(name = "test2", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(true)) + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(true)) ))), SuiteBundle( suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -55,7 +55,7 @@ class SuiteRunnerTest extends FunSuite { SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -64,7 +64,7 @@ class SuiteRunnerTest extends FunSuite { SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(methodNotSupported))), )) @@ -74,7 +74,7 @@ class SuiteRunnerTest extends FunSuite { suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), assertions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), )))) val constants: Map[String, String] = Map( From 9d89dc1e951fe0c996924b0f450578d2100fa0df Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 22 Aug 2023 09:53:14 +0200 Subject: [PATCH 02/31] #17 - Assertion rename and simplification * Simplified json files for ResponseAction - ResponseActions group and name by method with meaning "group.name". In code this value is separated for more intuitive usage. --- .../main/resources/schema/after.schema.json | 8 ++----- .../main/resources/schema/before.schema.json | 8 ++----- .../main/resources/schema/suite.schema.json | 8 ++----- .../scapi/json/ReferenceResolver.scala | 10 ++++++--- .../testing/scapi/json/SuiteFactory.scala | 9 ++++---- .../undefinedConstantIssue.suite.json | 3 +-- .../gui-controller/deleteQuestion.suite.json | 3 +-- .../gui-controller/getUserCurrent.after.json | 3 +-- .../gui-controller/getUserCurrent.before.json | 3 +-- .../gui-controller/getUserCurrent.suite.json | 3 +-- .../gui-controller/postQuestion.suite.json | 3 +-- .../gui-controller/putQuestion.suite.json | 3 +-- .../response/ResponseAssertionsTest.scala | 20 ++++++++--------- .../rest/response/ResponseExtractTest.scala | 22 +++++++++---------- .../scapi/rest/response/ResponseLogTest.scala | 8 +++---- .../scapi/rest/response/ResponseTest.scala | 4 ++-- .../scapi/suite/runner/SuiteRunnerTest.scala | 2 +- 17 files changed, 52 insertions(+), 68 deletions(-) diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index e174db4..cb723c2 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -104,10 +104,7 @@ "type": "object", "additionalProperties": false, "properties": { - "group": { - "type": "string" - }, - "name": { + "method": { "type": "string" } }, @@ -117,8 +114,7 @@ } }, "required": [ - "group", - "name", + "method", "param_1" ], "title": "ResponseAction" diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index 6ee3005..f44daee 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -104,10 +104,7 @@ "type": "object", "additionalProperties": false, "properties": { - "group": { - "type": "string" - }, - "name": { + "method": { "type": "string" } }, @@ -117,8 +114,7 @@ } }, "required": [ - "group", - "name", + "method", "param_1" ], "title": "ResponseAction" diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index 020d115..9018bdb 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -114,10 +114,7 @@ "type": "object", "additionalProperties": false, "properties": { - "group": { - "type": "string" - }, - "name": { + "method": { "type": "string" } }, @@ -127,8 +124,7 @@ } }, "required": [ - "group", - "name", + "method", "param_1" ], "title": "ResponseAction" diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index 6754a9b..c15845e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -203,14 +203,18 @@ case class Action private(methodName: String, url: String, body: Option[String] * It implements the `ReferenceResolver` trait to support resolution of reference constants. * * @constructor create a new ResponseAction with a name and value. - * @param name the name of the response action. + * @param method the "group and name" of the response action. * @param params the map containing the parameters of the response action. Each key-value pair in the map * represents a parameter name and its corresponding value. */ -case class ResponseAction private(group: String, - name: String, +case class ResponseAction private(method: String, params: Map[String, String]) extends ReferenceResolver { + private def splitter: Seq[String] = method.split("\\.").toSeq + + def group : String = splitter.head + def name : String = splitter.tail.head + /** * Method to resolve references. * diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index 1be1dd2..8e5a173 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -325,16 +325,15 @@ object ResponseActionJsonProtocol extends DefaultJsonProtocol { implicit object ResponseActionJsonFormat extends RootJsonFormat[ResponseAction] { def write(a: ResponseAction): JsObject = JsObject( - ("group" -> JsString(a.group)) +: - ("name" -> JsString(a.name)) +: + ("method" -> JsString(a.method)) +: a.params.view.mapValues(JsString(_)).toSeq: _* ) def read(value: JsValue): ResponseAction = { - value.asJsObject.getFields("group", "name") match { - case Seq(JsString(group), JsString(name)) => + value.asJsObject.getFields("method") match { + case Seq(JsString(method)) => val params = value.asJsObject.fields.view.filterKeys(_.startsWith("param_")).toMap - ResponseAction(group, name, params.map { case (k, v) => k -> v.convertTo[String] }) + ResponseAction(method, params.map { case (k, v) => k -> v.convertTo[String] }) case _ => throw DeserializationException("Assertion expected") } } diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index 820563e..bf62664 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -18,8 +18,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index 5704da5..e8fe7f8 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -22,8 +22,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index 383df6f..9baf46f 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -21,8 +21,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "statusCode", + "method": "assert.statusCode", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json index 2c39525..be62f7e 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json @@ -21,8 +21,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index e25e0c8..3cdfce9 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -22,8 +22,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index 4de6dd7..12dae5d 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -29,8 +29,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index f793d67..a206ee6 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -22,8 +22,7 @@ ], "responseActions": [ { - "group": "assert", - "name": "status-code", + "method": "assert.status-code", "param_1": "200" } ] diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 050153b..ed6312a 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -26,30 +26,30 @@ class ResponseAssertionsTest extends FunSuite { validateContent */ test("validateContent - valid status code string") { - val assertion = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "200")) + val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "200")) AssertionResponseAction.validateContent(assertion) } test("validateContent - invalid status code string") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "not an integer"))) } } test("validateContent - body is not empty") { - val assertion = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.BODY_CONTAINS, Map("param_1" -> "test content")) + val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("param_1" -> "test content")) AssertionResponseAction.validateContent(assertion) } test("validateContent - body is empty") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.BODY_CONTAINS, Map("param_1" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("param_1" -> ""))) } } test("validateContent - unsupported response action") { intercept[UndefinedResponseActionType] { - AssertionResponseAction.validateContent(ResponseAction(group = Response.GROUP_ASSERT, name = "unsupported", Map("param_1" -> "value"))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported", Map("param_1" -> "value"))) } } @@ -57,34 +57,34 @@ class ResponseAssertionsTest extends FunSuite { performResponseAction */ test("performAssertions - status code assertion - equals") { - val statusCodeAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("param_1" -> "200")) val response = Response(200, "Dummy Body", Map.empty) assert(AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - status code assertion - not equals") { - val statusCodeAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("param_1" -> "200")) val response = Response(500, "Dummy Body", Map.empty) assert(!AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - body contains assertion") { - val bodyContainsAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummy")) + val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("param_1" -> "dummy")) val response = Response(200, "This is a dummy body", Map.empty) assert(AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - body does not contains assertion") { - val bodyContainsAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "body-contains", Map("param_1" -> "dummies")) + val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("param_1" -> "dummies")) val response = Response(200, "This is a dummy body", Map.empty) assert(!AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - unsupported assertion") { - val unsupportedAssertion = ResponseAction(group = Response.GROUP_ASSERT, name = "unsupported-assertion", Map("param_1" -> "value")) + val unsupportedAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("param_1" -> "value")) val response = Response(200, "Dummy Body", Map.empty) interceptMessage[IllegalArgumentException]("Unsupported assertion[group: assert]: unsupported-assertion") { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index 7da228e..453d1b1 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -23,8 +23,8 @@ import munit.FunSuite class ResponseExtractTest extends FunSuite { - val assertionStringFromList: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "question_id", "param_2" -> "1", "param_3" -> "id", "param_4" -> "suite")) - val assertionUnsupported: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, "Unsupported", Map("param_1" -> "key", "param_2" -> "200", "param_3" -> "jsonKey", "param_4" -> "Test")) + val assertionStringFromList: ResponseAction = ResponseAction(method = s"${Response.GROUP_EXTRACT_JSON}.${ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "question_id", "param_2" -> "1", "param_3" -> "id", "param_4" -> "suite")) + val assertionUnsupported: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.Unsupported", Map("param_1" -> "key", "param_2" -> "200", "param_3" -> "jsonKey", "param_4" -> "Test")) val responseWithID: Response = Response( 200, @@ -121,10 +121,10 @@ class ResponseExtractTest extends FunSuite { // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" test("validateStringFromList - None parameters") { - val assertion1None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "")) - val assertion2None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "")) - val assertion3None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "")) - val assertion4None: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map()) + val assertion1None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "", "param_3" -> "")) + val assertion2None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "")) + val assertion3None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "")) + val assertion4None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map()) interceptMessage[IllegalArgumentException]("param_1 is missing") { ExtractJsonResponseAction.validateStringFromList(assertion4None) @@ -141,10 +141,10 @@ class ResponseExtractTest extends FunSuite { } test("validateStringFromList - empty parameters") { - val assertionParam1: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam2: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam3: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "", "param_4" -> "")) - val assertionParam4: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "y", "param_4" -> "")) + val assertionParam1: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "", "param_3" -> "", "param_4" -> "")) + val assertionParam2: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "", "param_3" -> "", "param_4" -> "")) + val assertionParam3: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "", "param_4" -> "")) + val assertionParam4: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "y", "param_4" -> "")) interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_1' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam1) @@ -161,7 +161,7 @@ class ResponseExtractTest extends FunSuite { } test("validateStringFromList - not integer in string") { - val assertion: ResponseAction = ResponseAction(Response.GROUP_EXTRACT_JSON, ExtractJsonResponseAction.STRING_FROM_LIST, Map("param_1" -> "key", "param_2" -> "x", "param_3" -> "y", "param_4" -> "y")) + val assertion: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "key", "param_2" -> "x", "param_3" -> "y", "param_4" -> "y")) interceptMessage[ContentValidationFailed]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.param_2' cannot be parsed to an integer: For input string: \"x\"") { ExtractJsonResponseAction.validateStringFromList(assertion) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index bbc586c..aa0ad58 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -26,13 +26,13 @@ class ResponseLogTest extends FunSuite { validateContent */ test("validateContent - INFO supported") { - val responseActionInfo = ResponseAction(Response.GROUP_LOG, LogResponseAction.INFO, Map("param_1" -> "Non-empty string")) + val responseActionInfo = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("param_1" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseActionInfo) } test("validateContent - not supported validation type") { - val responseAction = ResponseAction(Response.GROUP_LOG, "not_info", Map("param_1" -> "Some string")) + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("param_1" -> "Some string")) intercept[UndefinedResponseActionType] { LogResponseAction.validateContent(responseAction) } @@ -43,13 +43,13 @@ class ResponseLogTest extends FunSuite { */ test("performAssertion - INFO supported") { - val assertion = ResponseAction(Response.GROUP_LOG, LogResponseAction.INFO, Map("param_1" -> "info message")) + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("param_1" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - not supported validation type") { - val assertion = ResponseAction(Response.GROUP_LOG, "not_info", Map("param_1" -> "info message")) + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("param_1" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) intercept[IllegalArgumentException] { LogResponseAction.performResponseAction(response, assertion) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala index 548f0ff..d166efa 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala @@ -26,7 +26,7 @@ class ResponseTest extends FunSuite { */ test("validate - unsupported group") { - val unsupportedAssertion = ResponseAction("unsupportedGroup", "not needed", Map("param 1" -> "")) + val unsupportedAssertion = ResponseAction(method = "unsupportedGroup.not needed", Map("param 1" -> "")) intercept[IllegalArgumentException] { Response.validate(unsupportedAssertion) @@ -38,7 +38,7 @@ class ResponseTest extends FunSuite { */ test("perform - unsupported group") { - val unsupportedAssertion = ResponseAction("unsupportedGroup", "not needed", Map("param 1" -> "")) + val unsupportedAssertion = ResponseAction(method = "unsupportedGroup.not needed", Map("param 1" -> "")) val response = Response(200, "OK", Map.empty) intercept[IllegalArgumentException] { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 276e5b9..ca81c30 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -31,7 +31,7 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val assertion: ResponseAction = ResponseAction(group = Response.GROUP_ASSERT, name = AssertionResponseAction.STATUS_CODE, Map("param_1" -> "200")) + val assertion: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "200")) val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(assertion)) val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(assertion)) From 0b5a476a8819b9dc67a92c09f4aa4a6e6533a321 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 22 Aug 2023 12:31:14 +0200 Subject: [PATCH 03/31] #18 - Refactoring of ResponseAction to dynamic * Refactored responseActions logic to accept random parameter names. * Correct parameters are validated in time of project loading. --- .../main/resources/schema/after.schema.json | 5 ++- .../main/resources/schema/before.schema.json | 5 ++- .../main/resources/schema/suite.schema.json | 5 ++- .../testing/scapi/json/SuiteFactory.scala | 6 ++-- .../response/AssertionResponseAction.scala | 25 +++++++------- .../response/ExtractJsonResponseAction.scala | 34 +++++++++---------- .../rest/response/LogResponseAction.scala | 20 +++++------ .../undefinedConstantIssue.suite.json | 2 +- .../gui-controller/deleteQuestion.suite.json | 2 +- .../gui-controller/getUserCurrent.after.json | 2 +- .../gui-controller/getUserCurrent.before.json | 2 +- .../gui-controller/getUserCurrent.suite.json | 2 +- .../gui-controller/postQuestion.suite.json | 2 +- .../gui-controller/putQuestion.suite.json | 2 +- 14 files changed, 52 insertions(+), 62 deletions(-) diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index cb723c2..2c403c7 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -109,13 +109,12 @@ } }, "patternProperties": { - "^param_[0-9]+$": { + "^[a-zA-Z_][a-zA-Z0-9_]*$": { "type": "string" } }, "required": [ - "method", - "param_1" + "method" ], "title": "ResponseAction" }, diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index f44daee..58b9f09 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -109,13 +109,12 @@ } }, "patternProperties": { - "^param_[0-9]+$": { + "^[a-zA-Z_][a-zA-Z0-9_]*$": { "type": "string" } }, "required": [ - "method", - "param_1" + "method" ], "title": "ResponseAction" }, diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index 9018bdb..da1a15c 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -119,13 +119,12 @@ } }, "patternProperties": { - "^param_[0-9]+$": { + "^[a-zA-Z_][a-zA-Z0-9_]*$": { "type": "string" } }, "required": [ - "method", - "param_1" + "method" ], "title": "ResponseAction" }, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index 8e5a173..0ee31e2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -281,7 +281,7 @@ object SuiteJsonProtocol extends DefaultJsonProtocol { implicit val headerFormat: RootJsonFormat[Header] = jsonFormat2(Header) implicit val paramFormat: RootJsonFormat[Param] = jsonFormat2(Param) implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) - implicit val assertionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat + implicit val responseActionsFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val suiteTestFormat: RootJsonFormat[SuiteTestScenario] = jsonFormat6(SuiteTestScenario) implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) implicit val suiteFormat: RootJsonFormat[Suite] = jsonFormat2(Suite) @@ -313,7 +313,7 @@ object SuiteAfterJsonProtocol extends DefaultJsonProtocol { implicit val headerFormat: RootJsonFormat[Header] = jsonFormat2(Header) implicit val paramFormat: RootJsonFormat[Param] = jsonFormat2(Param) implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) - implicit val assertionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat + implicit val responseActionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) implicit val suiteAfterFormat: RootJsonFormat[SuiteAfter] = jsonFormat2(SuiteAfter) } @@ -332,7 +332,7 @@ object ResponseActionJsonProtocol extends DefaultJsonProtocol { def read(value: JsValue): ResponseAction = { value.asJsObject.getFields("method") match { case Seq(JsString(method)) => - val params = value.asJsObject.fields.view.filterKeys(_.startsWith("param_")).toMap + val params = value.asJsObject.fields.view.toMap ResponseAction(method, params.map { case (k, v) => k -> v.convertTo[String] }) case _ => throw DeserializationException("Assertion expected") } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 574bf0a..9669b41 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -39,22 +39,21 @@ object AssertionResponseAction extends ResponsePerformer { def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { case STATUS_CODE => - responseAction.params.get("param_1") match { - case param_1 => ContentValidator.validateIntegerString(param_1.get, s"ResponseAssertion.$STATUS_CODE.param_1") - case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $STATUS_CODE") + responseAction.params.get("code") match { + case code => ContentValidator.validateIntegerString(code.get, s"ResponseAssertion.$STATUS_CODE.code") + case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $STATUS_CODE logic.") } case BODY_CONTAINS => - responseAction.params.get("param_1") match { - case param_1 => ContentValidator.validateNonEmptyString(param_1.get, s"ResponseAssertion.$BODY_CONTAINS.param_1") - case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $BODY_CONTAINS") + responseAction.params.get("body") match { + case body => ContentValidator.validateNonEmptyString(body.get, s"ResponseAssertion.$BODY_CONTAINS.body") + case None => throw new IllegalArgumentException(s"Missing required 'body' parameter for assertion $BODY_CONTAINS logic.") } case _ => throw UndefinedResponseActionType(responseAction.name) } } - /** - * Performs assertion actions on a response depending on the type of assertion action provided. + * Performs assertion actions on a response depending on the type of assertion method provided. * * @param response The response to perform the assertions on. * @param responseAction The assertion response action to perform on the response. @@ -64,12 +63,12 @@ object AssertionResponseAction extends ResponsePerformer { def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { case STATUS_CODE => - val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - assertStatusCode(response, param_1) + val code = responseAction.params("code") + assertStatusCode(response, code) case BODY_CONTAINS => - val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - assertBodyContains(response, param_1) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: assert]: ${responseAction.name}") + val body = responseAction.params("body") + assertBodyContains(response, body) + case _ => throw new IllegalArgumentException(s"Unsupported assertion method [group: assert]: ${responseAction.name}") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala index 40ee111..610a104 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala @@ -32,8 +32,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { val STRING_FROM_LIST = "string-from-list" /** - * This method validates the response action's content based on the response action's name. - * It supports the STRING_FROM_LIST type of response action. + * Validates the content of an extract response action object depending on its type. * * @param responseAction The ResponseAction instance to be validated. * @throws UndefinedResponseActionType if an unsupported assertion type is encountered. @@ -46,8 +45,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { } /** - * This method performs response actions on a given response based on the response action's name. - * It supports the STRING_FROM_LIST type of response action. + * Performs extract actions on a response depending on the type of assertion method provided. * * @param response The Response instance to perform response action on. * @param responseAction The ResponseAction instance containing the response action details. @@ -56,12 +54,12 @@ object ExtractJsonResponseAction extends ResponsePerformer { def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { case STRING_FROM_LIST => - val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - val param_2 = responseAction.params.get("param_2").map(_.toInt).getOrElse(throw new IllegalArgumentException("param_2 is missing")) - val param_3 = responseAction.params.getOrElse("param_3", throw new IllegalArgumentException("param_3 is missing")) - val param_4 = responseAction.params.getOrElse("param_4", throw new IllegalArgumentException("param_4 is missing")) + val cacheKey = responseAction.params("cacheKey") + val listIndex = responseAction.params("listIndex").toInt + val jsonKey = responseAction.params("jsonKey") + val cacheLevel = responseAction.params("cacheLevel") - stringFromList(response, param_1, param_2, param_3, param_4) + stringFromList(response, cacheKey, listIndex, jsonKey, cacheLevel) case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: extract]: ${responseAction.name}") } } @@ -118,17 +116,17 @@ object ExtractJsonResponseAction extends ResponsePerformer { * @param assertion The ResponseAction instance containing the response action details. */ def validateStringFromList(assertion: ResponseAction): Unit = { - val param_1 = assertion.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - val param_2 = assertion.params.getOrElse("param_2", throw new IllegalArgumentException("param_2 is missing")) - val param_3 = assertion.params.getOrElse("param_3", throw new IllegalArgumentException("param_3 is missing")) - val param_4 = assertion.params.getOrElse("param_4", throw new IllegalArgumentException("param_4 is missing")) + val cacheKey = assertion.params.getOrElse("cacheKey", throw new IllegalArgumentException(s"Missing required 'cacheKey' parameter for extract $STRING_FROM_LIST logic")) + val listIndex = assertion.params.getOrElse("listIndex", throw new IllegalArgumentException(s"Missing required 'listIndex' parameter for extract $STRING_FROM_LIST logic")) + val jsonKey = assertion.params.getOrElse("jsonKey", throw new IllegalArgumentException(s"Missing required 'jsonKey' parameter for extract $STRING_FROM_LIST logic")) + val cacheLevel = assertion.params.getOrElse("cacheLevel", throw new IllegalArgumentException(s"Missing required 'cacheLevel' parameter for extract $STRING_FROM_LIST logic")) - ContentValidator.validateNonEmptyString(param_1, s"ExtractJson.$STRING_FROM_LIST.param_1") - ContentValidator.validateNonEmptyString(param_2, s"ExtractJson.$STRING_FROM_LIST.param_2") - ContentValidator.validateNonEmptyString(param_3, s"ExtractJson.$STRING_FROM_LIST.param_3") - ContentValidator.validateNonEmptyString(param_4, s"ExtractJson.$STRING_FROM_LIST.param_4") + ContentValidator.validateNonEmptyString(cacheKey, s"ExtractJson.$STRING_FROM_LIST.cacheKey") + ContentValidator.validateNonEmptyString(listIndex, s"ExtractJson.$STRING_FROM_LIST.listIndex") + ContentValidator.validateNonEmptyString(jsonKey, s"ExtractJson.$STRING_FROM_LIST.jsonKey") + ContentValidator.validateNonEmptyString(cacheLevel, s"ExtractJson.$STRING_FROM_LIST.cacheLevel") - ContentValidator.validateIntegerString(param_2, s"ExtractJson.$STRING_FROM_LIST.param_2") + ContentValidator.validateIntegerString(listIndex, s"ExtractJson.$STRING_FROM_LIST.listIndex") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index 1ed58bc..77cea94 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -30,9 +30,7 @@ object LogResponseAction extends ResponsePerformer { val INFO = "info" /** - * This method validates the content of the response action. - * It checks if the response action's name is "info", then validates if its `param_1` is a non-empty string. - * For all other response action names, it throws an `UndefinedAssertionType` exception. + * Validates the content of an log response action object depending on its type. * * @param responseAction The response action to be validated. * @throws UndefinedResponseActionType if the response action's name is not recognized. @@ -40,18 +38,16 @@ object LogResponseAction extends ResponsePerformer { def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { case INFO => - responseAction.params.get("param_1") match { - case param_1 => ContentValidator.validateNonEmptyString(param_1.get, s"ResponseLog.$INFO.param_1") - case None => throw new IllegalArgumentException(s"Missing required param_1 for assertion $INFO") + responseAction.params.get("message") match { + case message => ContentValidator.validateNonEmptyString(message.get, s"ResponseLog.$INFO.message") + case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion $INFO logic.") } case _ => throw UndefinedResponseActionType(responseAction.name) } } /** - * This method performs the necessary response actions on the response. - * It checks if the response action's name is "info", then logs the `param_1` as info message. - * For all other response action names, it throws an `IllegalArgumentException`. + * Performs log actions on a response depending on the type of log method provided. * * @param response The response on which the response action are to be performed. * @param responseAction The responseAction to be performed on the response. @@ -60,9 +56,9 @@ object LogResponseAction extends ResponsePerformer { def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { case INFO => - val param_1 = responseAction.params.getOrElse("param_1", throw new IllegalArgumentException("param_1 is missing")) - logInfo(param_1) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: log]: ${responseAction.name}") + val body = responseAction.params("body") + logInfo(body) + case _ => throw new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}") } } diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index bf62664..59b4c26 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -19,7 +19,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index e8fe7f8..9f5839e 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -23,7 +23,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index 9baf46f..094fb74 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -22,7 +22,7 @@ "responseActions": [ { "method": "assert.statusCode", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json index be62f7e..e6faad2 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json @@ -22,7 +22,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 3cdfce9..0ec190d 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -23,7 +23,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index 12dae5d..cc7039c 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -30,7 +30,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index a206ee6..9a36a7e 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -23,7 +23,7 @@ "responseActions": [ { "method": "assert.status-code", - "param_1": "200" + "code": "200" } ] } From 2e686742e64df4cbb5ac478b9185f3a3f7111371 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 22 Aug 2023 14:19:24 +0200 Subject: [PATCH 04/31] #18 - Refactoring of ResponseAction to dynamic * Extended json schemas by descriptions and version. --- .../main/resources/schema/after.schema.json | 71 ++++++--- .../main/resources/schema/before.schema.json | 69 ++++++--- .../resources/schema/constants.schema.json | 3 +- .../src/main/resources/schema/env.schema.json | 3 +- .../main/resources/schema/suite.schema.json | 146 +++++++++++++++--- .../undefinedConstantIssue.suite.json | 1 + .../deleteQuestion.constants.json | 1 + .../gui-controller/deleteQuestion.suite.json | 1 + .../gui-controller/getUserCurrent.after.json | 1 + .../gui-controller/getUserCurrent.before.json | 1 + .../getUserCurrent.constants.json | 1 + .../gui-controller/getUserCurrent.suite.json | 1 + .../postQuestion.constants.json | 1 + .../gui-controller/postQuestion.suite.json | 1 + .../gui-controller/putQuestion.constants.json | 1 + .../gui-controller/putQuestion.suite.json | 1 + 16 files changed, 230 insertions(+), 73 deletions(-) diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index 2c403c7..aff46c1 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -2,51 +2,59 @@ "$schema": "http://json-schema.org/draft-06/schema#", "$ref": "#/definitions/suiteAfter", + "version" : "1.0.0", "definitions": { "suiteAfter": { "type": "object", - "additionalProperties": false, + "additionalProperties": true, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the suite." }, "methods": { "type": "array", "items": { "$ref": "#/definitions/Method" - } + }, + "description": "An array of method objects associated with the suite." } }, "required": [ "name", "methods" ], - "title": "SuiteAfter" + "title": "SuiteAfter", + "description": "Defines a suite with its associated methods to be executed after the main tests." }, - "Method" : { + "Method": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the method." }, "headers": { "type": "array", "items": { "$ref": "#/definitions/Header" - } + }, + "description": "Headers to be sent with the method request." }, "actions": { "type": "array", "items": { "$ref": "#/definitions/Action" - } + }, + "description": "Actions to be performed during the method execution." }, "responseActions": { "type": "array", "items": { "$ref": "#/definitions/ResponseAction" - } + }, + "description": "Actions to be performed on the response of the method." } }, "required": [ @@ -55,57 +63,70 @@ "actions", "responseActions" ], - "title": "Method" + "title": "Method", + "description": "Defines a single method within a suite." }, "Header": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "enum": ["content-type", "authorization"], + "description": "The name of the header. Restricted to specific values." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the header." } }, "required": [ "name", "value" ], - "title": "Header" + "title": "Header", + "description": "Defines a header to be sent with a method request." }, "Action": { "type": "object", "additionalProperties": false, "properties": { "methodName": { - "type": "string" + "type": "string", + "enum": ["get", "post", "put", "delete"], + "description": "The HTTP method name for the action. Restricted to specific values." }, "url": { - "type": "string" + "type": "string", + "description": "The URL for the action." }, "body": { - "type": ["string", "null"] + "type": ["string", "null"], + "description": "The body content for the action." }, "params": { "type": ["array", "null"], "items": { "$ref": "#/definitions/Param" - } + }, + "description": "Parameters for the action." } }, "required": [ "methodName", "url" ], - "title": "Action" + "title": "Action", + "description": "Defines an action to be performed during a method." }, "ResponseAction": { "type": "object", "additionalProperties": false, "properties": { "method": { - "type": "string" + "type": "string", + "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "description": "The method to be used for the response action. Restricted to specific values." } }, "patternProperties": { @@ -116,24 +137,28 @@ "required": [ "method" ], - "title": "ResponseAction" + "title": "ResponseAction", + "description": "Defines an action to be performed on the response of a method." }, "Param": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the parameter." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the parameter." } }, "required": [ "name", "value" ], - "title": "Param" + "title": "Param", + "description": "Defines a parameter for an action." } } } diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index 58b9f09..cfb4465 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -2,51 +2,59 @@ "$schema": "http://json-schema.org/draft-06/schema#", "$ref": "#/definitions/suiteBefore", + "version" : "1.0.0", "definitions": { "suiteBefore": { "type": "object", - "additionalProperties": false, + "additionalProperties": true, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the suite." }, "methods": { "type": "array", "items": { "$ref": "#/definitions/Method" - } + }, + "description": "An array of method objects associated with the suite." } }, "required": [ "name", "methods" ], - "title": "SuiteBefore" + "title": "SuiteBefore", + "description": "Defines a suite with its associated methods." }, - "Method" : { + "Method": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the method." }, "headers": { "type": "array", "items": { "$ref": "#/definitions/Header" - } + }, + "description": "Headers to be sent with the method request." }, "actions": { "type": "array", "items": { "$ref": "#/definitions/Action" - } + }, + "description": "Actions to be performed during the method execution." }, "responseActions": { "type": "array", "items": { "$ref": "#/definitions/ResponseAction" - } + }, + "description": "Actions to be performed on the response of the method." } }, "required": [ @@ -55,57 +63,68 @@ "actions", "responseActions" ], - "title": "Method" + "title": "Method", + "description": "Defines a single method within a suite." }, "Header": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the header." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the header." } }, "required": [ "name", "value" ], - "title": "Header" + "title": "Header", + "description": "Defines a header to be sent with a method request." }, "Action": { "type": "object", "additionalProperties": false, "properties": { "methodName": { - "type": "string" + "type": "string", + "description": "The HTTP method name for the action." }, "url": { - "type": "string" + "type": "string", + "description": "The URL for the action." }, "body": { - "type": ["string", "null"] + "type": ["string", "null"], + "description": "The body content for the action." }, "params": { "type": ["array", "null"], "items": { "$ref": "#/definitions/Param" - } + }, + "description": "Parameters for the action." } }, "required": [ "methodName", "url" ], - "title": "Action" + "title": "Action", + "description": "Defines an action to be performed during a method." }, "ResponseAction": { "type": "object", "additionalProperties": false, "properties": { "method": { - "type": "string" + "type": "string", + "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "description": "The method to be used for the response action." } }, "patternProperties": { @@ -116,24 +135,28 @@ "required": [ "method" ], - "title": "ResponseAction" + "title": "ResponseAction", + "description": "Defines an action to be performed on the response of a method." }, "Param": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the parameter." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the parameter." } }, "required": [ "name", "value" ], - "title": "Param" + "title": "Param", + "description": "Defines a parameter for an action." } } } diff --git a/testApi/src/main/resources/schema/constants.schema.json b/testApi/src/main/resources/schema/constants.schema.json index 2925b22..7acec24 100644 --- a/testApi/src/main/resources/schema/constants.schema.json +++ b/testApi/src/main/resources/schema/constants.schema.json @@ -3,10 +3,11 @@ "$id": "https://africa.absa/schemas/suiteConstants", "$ref": "#/definitions/suiteConstants", + "version" : "1.0.0", "definitions": { "suiteConstants": { "type": "object", - "additionalProperties": false, + "additionalProperties": true, "properties": { "constants": { "$ref": "#/definitions/SuiteConstants" diff --git a/testApi/src/main/resources/schema/env.schema.json b/testApi/src/main/resources/schema/env.schema.json index c3d1771..5efc5a9 100644 --- a/testApi/src/main/resources/schema/env.schema.json +++ b/testApi/src/main/resources/schema/env.schema.json @@ -3,10 +3,11 @@ "$id": "https://africa.absa/schemas/env", "$ref": "#/definitions/env", + "version" : "1.0.0", "definitions": { "env": { "type": "object", - "additionalProperties": false, + "additionalProperties": true, "properties": { "constants": { "$ref": "#/definitions/Constants" diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index da1a15c..e38cf77 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -2,60 +2,70 @@ "$schema": "http://json-schema.org/draft-06/schema#", "$ref": "#/definitions/suite", + "version" : "1.0.0", "definitions": { "suite": { "type": "object", - "additionalProperties": false, + "additionalProperties": true, "properties": { "endpoint": { - "type": "string" + "type": "string", + "description": "The user endpoint name which suite cover by tests." }, "tests": { "type": "array", "items": { "$ref": "#/definitions/Test" - } + }, + "description": "An array of test objects." } }, "required": [ "endpoint", "tests" ], - "title": "suite" + "title": "suite", + "description": "Defines a suite of tests." }, "Test": { "type": "object", "additionalProperties": false, "properties": { "only": { - "type": "boolean" + "type": "boolean", + "description": "Indicates if only this test should be run." }, "name": { - "type": "string" + "type": "string", + "description": "The name of the test." }, "categories": { "type": "array", "items": { "type": "string" - } + }, + "description": "Categories associated with the test." }, "headers": { "type": "array", "items": { "$ref": "#/definitions/Header" - } + }, + "description": "Headers to be sent with the test request." }, "actions": { "type": "array", "items": { "$ref": "#/definitions/Action" - } + }, + "description": "Actions to be performed during the test." }, "responseActions": { "type": "array", "items": { "$ref": "#/definitions/ResponseAction" - } + }, + "description": "Actions to be performed on the response of the test." } }, "required": [ @@ -65,57 +75,67 @@ "actions", "responseActions" ], - "title": "Test" + "title": "Test", + "description": "Defines a single test within a suite." }, "Header": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the header." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the header." } }, "required": [ "name", "value" ], - "title": "Header" + "title": "Header", + "description": "Defines a header to be sent with a test request." }, "Action": { "type": "object", "additionalProperties": false, "properties": { "methodName": { - "type": "string" + "type": "string", + "description": "The HTTP method name for the action." }, "url": { - "type": "string" + "type": "string", + "description": "The URL for the action." }, "body": { - "type": ["string", "null"] + "type": ["string", "null"], + "description": "The body content for the action." }, "params": { "type": ["array", "null"], "items": { "$ref": "#/definitions/Param" - } + }, + "description": "Parameters for the action." } }, "required": [ "methodName", "url" ], - "title": "Action" + "title": "Action", + "description": "Defines an action to be performed during a test." }, "ResponseAction": { "type": "object", - "additionalProperties": false, "properties": { "method": { - "type": "string" + "type": "string", + "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "description": "The method to be used for the response action." } }, "patternProperties": { @@ -123,27 +143,103 @@ "type": "string" } }, + "dependencies": { + "method": { + "oneOf": [ + { + "properties": { + "method": { + "const": "log.info" + } + }, + "required": ["message"] + }, + { + "properties": { + "method": { + "const": "assert.status-code" + } + }, + "required": ["code"] + }, + { + "properties": { + "method": { + "const": "assert.body-contains" + } + }, + "required": ["body"] + }, + { + "properties": { + "method": { + "const": "extractJson.string-from-list" + } + }, + "required": ["cacheKey", "listIndex", "jsonKey", "cacheLevel"] + }, + { + "not": { + "anyOf": [ + { + "properties": { + "method": { + "const": "log.info" + } + } + }, + { + "properties": { + "method": { + "const": "assert.status-code" + } + } + }, + { + "properties": { + "method": { + "const": "assert.body-contains" + } + } + }, + { + "properties": { + "method": { + "const": "extractJson.string-from-list" + } + } + } + ] + } + } + ] + } + }, "required": [ "method" ], - "title": "ResponseAction" + "title": "ResponseAction", + "description": "Defines an action to be performed on the response of a test." }, "Param": { "type": "object", "additionalProperties": false, "properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the parameter." }, "value": { - "type": "string" + "type": "string", + "description": "The value of the parameter." } }, "required": [ "name", "value" ], - "title": "Param" + "title": "Param", + "description": "Defines a parameter for an action." } } } diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index 59b4c26..4256f13 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "endpoint" : "getUserCurrent", "tests": [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.constants.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.constants.json index 63c4445..e762160 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.constants.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.constants.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "constants" : { "header_auth": "Authorization", "header_basic_token": "Basic {{ env.basic_token }}", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index 9f5839e..57e6fd7 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "endpoint" : "deleteQuestion", "tests": [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index 094fb74..ed04228 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "name" : "after.name.1", "methods" : [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json index e6faad2..14c6ddb 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "name" : "before.name.1", "methods" : [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.constants.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.constants.json index cf6b211..c1abc47 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.constants.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.constants.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "constants" : { "header_auth": "Authorization", "header_basic_token": "Basic {{ env.basic_token }}", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 0ec190d..486c231 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "endpoint" : "getUserCurrent", "tests": [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.constants.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.constants.json index ac87ae2..9010d8d 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.constants.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.constants.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "constants" : { "header_auth": "Authorization", "header_bearer_token": "Basic {{ env.basic_token }}", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index cc7039c..2a62d6b 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "endpoint" : "postQuestion", "tests": [ { diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.constants.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.constants.json index ac87ae2..9010d8d 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.constants.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.constants.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "constants" : { "header_auth": "Authorization", "header_bearer_token": "Basic {{ env.basic_token }}", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index 9a36a7e..dd6f93b 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -1,4 +1,5 @@ { + "version" : "1.0.0", "endpoint" : "putQuestion", "tests": [ { From 4d5a6bc95412bba75f912f7506f71eaed86892be Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 22 Aug 2023 14:57:14 +0200 Subject: [PATCH 05/31] * Repairs of unit tests. --- .../src/main/resources/schema/env.schema.json | 2 +- .../rest/response/LogResponseAction.scala | 4 +- .../gui-controller/getUserCurrent.after.json | 2 +- .../response/ResponseAssertionsTest.scala | 22 +++++------ .../rest/response/ResponseExtractTest.scala | 38 +++++++++---------- .../scapi/rest/response/ResponseLogTest.scala | 8 ++-- .../scapi/suite/runner/SuiteRunnerTest.scala | 18 ++++----- 7 files changed, 47 insertions(+), 47 deletions(-) diff --git a/testApi/src/main/resources/schema/env.schema.json b/testApi/src/main/resources/schema/env.schema.json index 5efc5a9..4566eba 100644 --- a/testApi/src/main/resources/schema/env.schema.json +++ b/testApi/src/main/resources/schema/env.schema.json @@ -7,7 +7,7 @@ "definitions": { "env": { "type": "object", - "additionalProperties": true, + "additionalProperties": false, "properties": { "constants": { "$ref": "#/definitions/Constants" diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index 77cea94..ad1aaf2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -56,8 +56,8 @@ object LogResponseAction extends ResponsePerformer { def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { case INFO => - val body = responseAction.params("body") - logInfo(body) + val message = responseAction.params("message") + logInfo(message) case _ => throw new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}") } } diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index ed04228..b7718fa 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -22,7 +22,7 @@ ], "responseActions": [ { - "method": "assert.statusCode", + "method": "assert.status-code", "code": "200" } ] diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index ed6312a..eedd11e 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -26,30 +26,30 @@ class ResponseAssertionsTest extends FunSuite { validateContent */ test("validateContent - valid status code string") { - val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "200")) + val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "200")) AssertionResponseAction.validateContent(assertion) } test("validateContent - invalid status code string") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "not an integer"))) } } test("validateContent - body is not empty") { - val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("param_1" -> "test content")) + val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> "test content")) AssertionResponseAction.validateContent(assertion) } test("validateContent - body is empty") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("param_1" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> ""))) } } test("validateContent - unsupported response action") { intercept[UndefinedResponseActionType] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported", Map("param_1" -> "value"))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported", Map("body" -> "value"))) } } @@ -57,37 +57,37 @@ class ResponseAssertionsTest extends FunSuite { performResponseAction */ test("performAssertions - status code assertion - equals") { - val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("code" -> "200")) val response = Response(200, "Dummy Body", Map.empty) assert(AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - status code assertion - not equals") { - val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("param_1" -> "200")) + val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("code" -> "200")) val response = Response(500, "Dummy Body", Map.empty) assert(!AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) } test("performAssertions - body contains assertion") { - val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("param_1" -> "dummy")) + val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummy")) val response = Response(200, "This is a dummy body", Map.empty) assert(AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - body does not contains assertion") { - val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("param_1" -> "dummies")) + val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummies")) val response = Response(200, "This is a dummy body", Map.empty) assert(!AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) } test("performAssertions - unsupported assertion") { - val unsupportedAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("param_1" -> "value")) + val unsupportedAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) val response = Response(200, "Dummy Body", Map.empty) - interceptMessage[IllegalArgumentException]("Unsupported assertion[group: assert]: unsupported-assertion") { + interceptMessage[IllegalArgumentException]("Unsupported assertion method [group: assert]: unsupported-assertion") { AssertionResponseAction.performResponseAction(response, unsupportedAssertion) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index 453d1b1..fd8eb2d 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -23,8 +23,8 @@ import munit.FunSuite class ResponseExtractTest extends FunSuite { - val assertionStringFromList: ResponseAction = ResponseAction(method = s"${Response.GROUP_EXTRACT_JSON}.${ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "question_id", "param_2" -> "1", "param_3" -> "id", "param_4" -> "suite")) - val assertionUnsupported: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.Unsupported", Map("param_1" -> "key", "param_2" -> "200", "param_3" -> "jsonKey", "param_4" -> "Test")) + val assertionStringFromList: ResponseAction = ResponseAction(method = s"${Response.GROUP_EXTRACT_JSON}.${ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) + val assertionUnsupported: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) val responseWithID: Response = Response( 200, @@ -121,48 +121,48 @@ class ResponseExtractTest extends FunSuite { // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" test("validateStringFromList - None parameters") { - val assertion1None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "", "param_3" -> "")) - val assertion2None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "")) - val assertion3None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "")) + val assertion1None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) + val assertion2None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "")) + val assertion3None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "")) val assertion4None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map()) - interceptMessage[IllegalArgumentException]("param_1 is missing") { + interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion4None) } - interceptMessage[IllegalArgumentException]("param_2 is missing") { + interceptMessage[IllegalArgumentException]("Missing required 'listIndex' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion3None) } - interceptMessage[IllegalArgumentException]("param_3 is missing") { + interceptMessage[IllegalArgumentException]("Missing required 'jsonKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion2None) } - interceptMessage[IllegalArgumentException]("param_4 is missing") { + interceptMessage[IllegalArgumentException]("Missing required 'cacheLevel' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion1None) } } test("validateStringFromList - empty parameters") { - val assertionParam1: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam2: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "", "param_3" -> "", "param_4" -> "")) - val assertionParam3: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "", "param_4" -> "")) - val assertionParam4: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "1", "param_2" -> "x", "param_3" -> "y", "param_4" -> "")) + val assertionParam1: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam2: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam3: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam4: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_1' is empty.") { + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam1) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_2' is empty.") { + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.listIndex' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam2) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_3' is empty.") { + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.jsonKey' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam3) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.param_4' is empty.") { + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheLevel' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam4) } } test("validateStringFromList - not integer in string") { - val assertion: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("param_1" -> "key", "param_2" -> "x", "param_3" -> "y", "param_4" -> "y")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.param_2' cannot be parsed to an integer: For input string: \"x\"") { + val assertion: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { ExtractJsonResponseAction.validateStringFromList(assertion) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index aa0ad58..fbbc80b 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -26,13 +26,13 @@ class ResponseLogTest extends FunSuite { validateContent */ test("validateContent - INFO supported") { - val responseActionInfo = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("param_1" -> "Non-empty string")) + val responseActionInfo = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseActionInfo) } test("validateContent - not supported validation type") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("param_1" -> "Some string")) + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "Some string")) intercept[UndefinedResponseActionType] { LogResponseAction.validateContent(responseAction) } @@ -43,13 +43,13 @@ class ResponseLogTest extends FunSuite { */ test("performAssertion - INFO supported") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("param_1" -> "info message")) + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - not supported validation type") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("param_1" -> "info message")) + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) intercept[IllegalArgumentException] { LogResponseAction.performResponseAction(response, assertion) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index ca81c30..a2960d6 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -31,22 +31,22 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val assertion: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("param_1" -> "200")) - val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(assertion)) - val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(assertion)) + val responseAction: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "200")) + val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(responseAction)) + val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(responseAction)) val suitesBundles: Set[SuiteBundle] = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(true)), + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(true)), SuiteTestScenario(name = "test2", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(true)) + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(true)) ))), SuiteBundle( suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -55,7 +55,7 @@ class SuiteRunnerTest extends FunSuite { SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -64,7 +64,7 @@ class SuiteRunnerTest extends FunSuite { SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(methodNotSupported))), )) @@ -74,7 +74,7 @@ class SuiteRunnerTest extends FunSuite { suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(assertion), only = Some(false)), + headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), )))) val constants: Map[String, String] = Map( From f14b81f7fc10cad4e65ac7476c754f531f33c6f8 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 23 Aug 2023 08:57:12 +0200 Subject: [PATCH 06/31] #8 - Implement method ideas * Implemented full expected methods for Log 'ResponseAction'. --- .../rest/response/LogResponseAction.scala | 49 ++++++++++-- .../scapi/rest/response/ResponseLogTest.scala | 77 ++++++++++++++++++- 2 files changed, 116 insertions(+), 10 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index ad1aaf2..8472eba 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -27,7 +27,10 @@ import africa.absa.testing.scapi.utils.validation.ContentValidator */ object LogResponseAction extends ResponsePerformer { + val ERROR= "error" + val WARN = "warn" val INFO = "info" + val DEBUG = "debug" /** * Validates the content of an log response action object depending on its type. @@ -37,10 +40,10 @@ object LogResponseAction extends ResponsePerformer { */ def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { - case INFO => + case ERROR | WARN | INFO | DEBUG => responseAction.params.get("message") match { - case message => ContentValidator.validateNonEmptyString(message.get, s"ResponseLog.$INFO.message") - case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion $INFO logic.") + case Some(message) => ContentValidator.validateNonEmptyString(message, s"ResponseLog.${responseAction.name}.message") + case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion ${responseAction.name} logic.") } case _ => throw UndefinedResponseActionType(responseAction.name) } @@ -54,10 +57,13 @@ object LogResponseAction extends ResponsePerformer { * @throws IllegalArgumentException if the response action's name is not recognized. */ def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + val message = responseAction.params.getOrElse("message", throw new IllegalArgumentException("Missing 'message' parameter")) + responseAction.name match { - case INFO => - val message = responseAction.params("message") - logInfo(message) + case ERROR => logError(message) + case WARN => logWarn(message) + case INFO => logInfo(message) + case DEBUG => logDebug(message) case _ => throw new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}") } } @@ -66,6 +72,26 @@ object LogResponseAction extends ResponsePerformer { dedicated actions */ + /** + * This method logs a message at the ERROR level. + * + * @param message The message to be logged. + */ + def logError(message: String): Boolean = { + Logger.error(message) + true + } + + /** + * This method logs a message at the WARN level. + * + * @param message The message to be logged. + */ + def logWarn(message: String): Boolean = { + Logger.warn(message) + true + } + /** * This method logs a message at the INFO level. * @@ -75,4 +101,15 @@ object LogResponseAction extends ResponsePerformer { Logger.info(message) true } + + /** + * This method logs a message at the DEBUG level. + * + * @param message The message to be logged. + */ + def logDebug(message: String): Boolean = { + Logger.debug(message) + true + } + } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index fbbc80b..60dd060 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -25,29 +25,72 @@ class ResponseLogTest extends FunSuite { /* validateContent */ + test("validateContent - ERROR supported") { + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.ERROR}", Map("message" -> "Non-empty string")) + // no exception thrown, meaning validation passed + LogResponseAction.validateContent(responseAction) + } + + test("validateContent - WARN supported") { + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.WARN}", Map("message" -> "Non-empty string")) + // no exception thrown, meaning validation passed + LogResponseAction.validateContent(responseAction) + } + test("validateContent - INFO supported") { - val responseActionInfo = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed - LogResponseAction.validateContent(responseActionInfo) + LogResponseAction.validateContent(responseAction) + } + + test("validateContent - DEBUG supported") { + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.DEBUG}", Map("message" -> "Non-empty string")) + // no exception thrown, meaning validation passed + LogResponseAction.validateContent(responseAction) } test("validateContent - not supported validation type") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "Some string")) + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.wrong", Map("message" -> "Some string")) intercept[UndefinedResponseActionType] { LogResponseAction.validateContent(responseAction) } } + test("validateContent - no message provided") { + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map()) + interceptMessage[IllegalArgumentException]("Missing required 'message' for assertion info logic.") { + LogResponseAction.validateContent(responseAction) + } + } + /* performResponseAction */ + test("performAssertion - ERROR supported") { + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.ERROR}", Map("message" -> "info message")) + val response = Response(500, "OK", Map("Content-Type" -> Seq("application/json"))) + assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + } + + test("performAssertion - WARN supported") { + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.WARN}", Map("message" -> "info message")) + val response = Response(401, "OK", Map("Content-Type" -> Seq("application/json"))) + assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + } + test("performAssertion - INFO supported") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } + test("performAssertion - DEBUG supported") { + val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.DEBUG}", Map("message" -> "info message")) + val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) + assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + } + test("performAssertion - not supported validation type") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "info message")) val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) @@ -56,11 +99,37 @@ class ResponseLogTest extends FunSuite { } } + /* + logError + */ + + test("logError") { + assertEquals(LogResponseAction.logError("log error message"), true) + } + + /* + logWarn + */ + + test("logInfo") { + assertEquals(LogResponseAction.logWarn("log warn message"), true) + } + /* logInfo */ test("logInfo") { - assertEquals(LogResponseAction.logInfo("log message"), true) + assertEquals(LogResponseAction.logInfo("log info message"), true) + } + + /* + logDebug + */ + + test("logDebug") { + assertEquals(LogResponseAction.logDebug("log debug message"), true) } + + } From 104415fb929fa4b0d7fe879e19d4d56b20c0e0fc Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 23 Aug 2023 09:47:42 +0200 Subject: [PATCH 07/31] * Implemented methods for Assertion 'ResponseAction' - status-code-... part --- .../main/resources/schema/after.schema.json | 2 +- .../main/resources/schema/before.schema.json | 2 +- .../main/resources/schema/suite.schema.json | 6 +- .../response/AssertionResponseAction.scala | 59 ++++++++-- .../undefinedConstantIssue.suite.json | 2 +- .../gui-controller/deleteQuestion.suite.json | 2 +- .../gui-controller/getUserCurrent.after.json | 2 +- .../gui-controller/getUserCurrent.before.json | 2 +- .../gui-controller/getUserCurrent.suite.json | 2 +- .../gui-controller/postQuestion.suite.json | 2 +- .../gui-controller/putQuestion.suite.json | 2 +- .../response/ResponseAssertionsTest.scala | 103 +++++++++++++++--- .../scapi/suite/runner/SuiteRunnerTest.scala | 2 +- 13 files changed, 153 insertions(+), 35 deletions(-) diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index aff46c1..9ade582 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -125,7 +125,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], "description": "The method to be used for the response action. Restricted to specific values." } }, diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index cfb4465..9a601ab 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -123,7 +123,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index e38cf77..78562a3 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -134,7 +134,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, @@ -157,7 +157,7 @@ { "properties": { "method": { - "const": "assert.status-code" + "const": "assert.status-code-equals" } }, "required": ["code"] @@ -191,7 +191,7 @@ { "properties": { "method": { - "const": "assert.status-code" + "const": "assert.status-code-equals" } } }, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 9669b41..f880bb2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -27,7 +27,10 @@ import africa.absa.testing.scapi.utils.validation.ContentValidator */ object AssertionResponseAction extends ResponsePerformer { - val STATUS_CODE = "status-code" + val STATUS_CODE_EQUALS = "status-code-equals" + val STATUS_CODE_IS_SUCCESS = "status-code-is-success" + val STATUS_CODE_IS_CLIENT_ERROR = "status-code-is_client_error" + val STATUS_CODE_IS_SERVER_ERROR = "status-code-is_server_error" val BODY_CONTAINS = "body-contains" /** @@ -38,11 +41,16 @@ object AssertionResponseAction extends ResponsePerformer { */ def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { - case STATUS_CODE => + + // status-code-... + case STATUS_CODE_EQUALS => responseAction.params.get("code") match { - case code => ContentValidator.validateIntegerString(code.get, s"ResponseAssertion.$STATUS_CODE.code") - case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $STATUS_CODE logic.") + case code => ContentValidator.validateIntegerString(code.get, s"ResponseAssertion.$STATUS_CODE_EQUALS.code") + case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $STATUS_CODE_EQUALS logic.") } + case STATUS_CODE_IS_SUCCESS | STATUS_CODE_IS_CLIENT_ERROR | STATUS_CODE_IS_SERVER_ERROR => () + + // body-... case BODY_CONTAINS => responseAction.params.get("body") match { case body => ContentValidator.validateNonEmptyString(body.get, s"ResponseAssertion.$BODY_CONTAINS.body") @@ -62,9 +70,16 @@ object AssertionResponseAction extends ResponsePerformer { */ def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { - case STATUS_CODE => + + // status-code-... + case STATUS_CODE_EQUALS => val code = responseAction.params("code") - assertStatusCode(response, code) + assertStatusCodeEquals(response, code) + case STATUS_CODE_IS_SUCCESS => assertStatusCodeSuccess(response) + case STATUS_CODE_IS_CLIENT_ERROR => assertStatusCodeIsClientError(response) + case STATUS_CODE_IS_SERVER_ERROR => assertStatusCodeIsServerError(response) + + // body-... case BODY_CONTAINS => val body = responseAction.params("body") assertBodyContains(response, body) @@ -83,7 +98,7 @@ object AssertionResponseAction extends ResponsePerformer { * @param expectedCode The expected status code as a string. * @return A Boolean indicating whether the response's status code matches the expected code. Returns true if they match, false otherwise. */ - def assertStatusCode(response: Response, expectedCode: String): Boolean = { + def assertStatusCodeEquals(response: Response, expectedCode: String): Boolean = { val iExpectedCode: Int = expectedCode.toInt val isSuccess: Boolean = response.statusCode == iExpectedCode @@ -93,6 +108,36 @@ object AssertionResponseAction extends ResponsePerformer { isSuccess } + /** + * Checks if the status code of the given response is in the success range (200-299). + * + * @param response The response object containing the status code. + * @return True if the status code is in the range 200-299, otherwise false. + */ + def assertStatusCodeSuccess(response: Response): Boolean = { + response.statusCode >= 200 && response.statusCode <= 299 + } + + /** + * Checks if the status code of the given response is in the client error range (400-499). + * + * @param response The response object containing the status code. + * @return True if the status code is in the range 400-499, otherwise false. + */ + def assertStatusCodeIsClientError(response: Response): Boolean = { + response.statusCode >= 400 && response.statusCode <= 499 + } + + /** + * Checks if the status code of the given response is in the server error range (500-599). + * + * @param response The response object containing the status code. + * @return True if the status code is in the range 500-599, otherwise false. + */ + def assertStatusCodeIsServerError(response: Response): Boolean = { + response.statusCode >= 500 && response.statusCode <= 599 + } + /** * Asserts that the body of the response contains the expected content. * diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index 4256f13..6759d64 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -19,7 +19,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index 57e6fd7..f3c40da 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -23,7 +23,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json index b7718fa..7d206f0 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.after.json @@ -22,7 +22,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json index 14c6ddb..b891121 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.before.json @@ -22,7 +22,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 486c231..72a5654 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -23,7 +23,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index 2a62d6b..f9c0c67 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -30,7 +30,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index dd6f93b..01dce18 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -23,7 +23,7 @@ ], "responseActions": [ { - "method": "assert.status-code", + "method": "assert.status-code-equals", "code": "200" } ] diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index eedd11e..ed8ac07 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -25,20 +25,25 @@ class ResponseAssertionsTest extends FunSuite { /* validateContent */ + + // status-code-... + test("validateContent - valid status code string") { - val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "200")) - AssertionResponseAction.validateContent(assertion) + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) + AssertionResponseAction.validateContent(responseAction) } test("validateContent - invalid status code string") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "not an integer"))) } } + // body-... + test("validateContent - body is not empty") { - val assertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> "test content")) - AssertionResponseAction.validateContent(assertion) + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> "test content")) + AssertionResponseAction.validateContent(responseAction) } test("validateContent - body is empty") { @@ -47,6 +52,7 @@ class ResponseAssertionsTest extends FunSuite { } } + test("validateContent - unsupported response action") { intercept[UndefinedResponseActionType] { AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported", Map("body" -> "value"))) @@ -56,39 +62,106 @@ class ResponseAssertionsTest extends FunSuite { /* performResponseAction */ + + // status-code-... + test("performAssertions - status code assertion - equals") { - val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) val response = Response(200, "Dummy Body", Map.empty) - assert(AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) } test("performAssertions - status code assertion - not equals") { - val statusCodeAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.status-code", Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) val response = Response(500, "Dummy Body", Map.empty) - assert(!AssertionResponseAction.performResponseAction(response, statusCodeAssertion)) + assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + } + + test("performAssertions - status code - is success") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map()) + val response200 = Response(200, "Dummy Body", Map.empty) + val response299 = Response(299, "Dummy Body", Map.empty) + + assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response299, statusCodeResponseAction)) } + test("performAssertions - status code - is not success") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map()) + val response199 = Response(199, "Dummy Body", Map.empty) + val response300 = Response(300, "Dummy Body", Map.empty) + val response500 = Response(500, "Dummy Body", Map.empty) + + assert(!AssertionResponseAction.performResponseAction(response199, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response300, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) + } + + test("performAssertions - status code - is client error") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map()) + val response400 = Response(400, "Dummy Body", Map.empty) + val response499 = Response(499, "Dummy Body", Map.empty) + + assert(AssertionResponseAction.performResponseAction(response400, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) + } + + test("performAssertions - status code - is not client error") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map()) + val response399 = Response(399, "Dummy Body", Map.empty) + val response500 = Response(500, "Dummy Body", Map.empty) + val response200 = Response(200, "Dummy Body", Map.empty) + + assert(!AssertionResponseAction.performResponseAction(response399, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) + } + + test("performAssertions - status code - is server error") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map()) + val response500 = Response(500, "Dummy Body", Map.empty) + val response599 = Response(599, "Dummy Body", Map.empty) + + assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response599, statusCodeResponseAction)) + } + + test("performAssertions - status code - is not server error") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map()) + val response499 = Response(499, "Dummy Body", Map.empty) + val response600 = Response(600, "Dummy Body", Map.empty) + val response200 = Response(200, "Dummy Body", Map.empty) + + assert(!AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response600, statusCodeResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) + } + + + // body-... + test("performAssertions - body contains assertion") { - val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummy")) + val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummy")) val response = Response(200, "This is a dummy body", Map.empty) - assert(AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) + assert(AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) } test("performAssertions - body does not contains assertion") { - val bodyContainsAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummies")) + val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummies")) val response = Response(200, "This is a dummy body", Map.empty) - assert(!AssertionResponseAction.performResponseAction(response, bodyContainsAssertion)) + assert(!AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) } + test("performAssertions - unsupported assertion") { - val unsupportedAssertion = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) + val unsupportedResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) val response = Response(200, "Dummy Body", Map.empty) interceptMessage[IllegalArgumentException]("Unsupported assertion method [group: assert]: unsupported-assertion") { - AssertionResponseAction.performResponseAction(response, unsupportedAssertion) + AssertionResponseAction.performResponseAction(response, unsupportedResponseAction) } } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index a2960d6..8ea9e58 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -31,7 +31,7 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val responseAction: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE}", Map("code" -> "200")) + val responseAction: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(responseAction)) val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(responseAction)) From 2559bb20fdc295d255242810696ffa97f95f5856 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 24 Aug 2023 13:26:33 +0200 Subject: [PATCH 08/31] * Implemented methods for Assertion 'ResponseAction' - response-time-... part * Implemented methods for Assertion 'ResponseAction' - header-... part * Implemented methods for Assertion 'ResponseAction' - content-type-... part * Updated log message to keep same format - on debug level. * Migrate several Set to Seq to keep order of elements which is required by logic of test design. --- project/Dependencies.scala | 2 + .../main/resources/schema/after.schema.json | 2 +- .../main/resources/schema/before.schema.json | 2 +- .../main/resources/schema/suite.schema.json | 2 +- .../absa/testing/scapi/json/Requestable.scala | 6 +- .../absa/testing/scapi/model/Method.scala | 6 +- .../scapi/model/SuiteTestScenario.scala | 8 +- .../scapi/rest/request/RequestHeaders.scala | 2 +- .../request/sender/ScAPIRequestSender.scala | 29 +- .../response/AssertionResponseAction.scala | 172 +++++++++++- .../scapi/rest/response/Response.scala | 35 ++- .../scapi/suite/runner/SuiteRunner.scala | 14 +- .../utils/validation/ContentValidator.scala | 13 + .../gui-controller/getUserCurrent.suite.json | 27 ++ .../scapi/json/RequestHeadersTest.scala | 8 +- .../testing/scapi/json/SuiteFactoryTest.scala | 16 +- .../testing/scapi/rest/RestClientTest.scala | 2 +- .../response/ResponseAssertionsTest.scala | 249 ++++++++++++++++-- .../rest/response/ResponseExtractTest.scala | 23 +- .../scapi/rest/response/ResponseLogTest.scala | 12 +- .../scapi/rest/response/ResponseTest.scala | 4 +- .../suite/runner/FakeScAPIRequestSender.scala | 7 +- .../scapi/suite/runner/SuiteRunnerTest.scala | 28 +- 23 files changed, 562 insertions(+), 107 deletions(-) diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 5d99c25..ef4de28 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -26,6 +26,7 @@ object Dependencies { private val commonsIoVersion = "2.13.0" private val requestsVersion = "0.8.0" private val loggerVersion = "2.14.1" + private val scalaXmlVersion = "1.3.0" def getScalaDependency(scalaVersion: String): ModuleID = "org.scala-lang" % "scala-library" % scalaVersion @@ -40,6 +41,7 @@ object Dependencies { "com.lihaoyi" %% "requests" % requestsVersion, "org.apache.logging.log4j" % "log4j-core" % loggerVersion, "org.apache.logging.log4j" % "log4j-api" % loggerVersion, + "org.scala-lang.modules" %% "scala-xml" % scalaXmlVersion, // test "org.scalameta" %% "munit" % munitVersion % Test diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index 9ade582..1387f36 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -125,7 +125,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action. Restricted to specific values." } }, diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index 9a601ab..f3259e5 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -123,7 +123,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index 78562a3..14d08f0 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -134,7 +134,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.status-code-equals", "assert.body-contains", "log.info", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala index 9830ae3..dd59d1e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/Requestable.scala @@ -19,9 +19,9 @@ package africa.absa.testing.scapi.json trait Requestable { def name: String - def headers: Set[Header] + def headers: Seq[Header] - def actions: Set[Action] + def actions: Seq[Action] - def responseActions: Set[ResponseAction] + def responseActions: Seq[ResponseAction] } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala index 224702d..1264bd4 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala @@ -27,9 +27,9 @@ import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseActi * @param responseActions The set of responseAction objects for the method. */ case class Method(name: String, - headers: Set[Header], - actions: Set[Action], - responseActions: Set[ResponseAction]) extends Requestable { + headers: Seq[Header], + actions: Seq[Action], + responseActions: Seq[ResponseAction]) extends Requestable { /** * Method to resolve references within the Method instance. * diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala index b01efa7..82282cf 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala @@ -29,10 +29,10 @@ import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseActi * @param only The control if test should be only be running when set to true. */ case class SuiteTestScenario(name: String, - categories: Set[String], - headers: Set[Header], - actions: Set[Action], - responseActions: Set[ResponseAction], + categories: Seq[String], + headers: Seq[Header], + actions: Seq[Action], + responseActions: Seq[ResponseAction], only: Option[Boolean] = Some(false)) extends Requestable { /** * Method to resolve references within the SuiteTestScenario instance. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala index 7f9a575..fe29106 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala @@ -35,7 +35,7 @@ object RequestHeaders { * @param headersSet A set of Header objects to be processed. * @return A Map where the key is the header name (lowercase) and the value is the resolved header value. */ - def buildHeaders(headersSet: Set[Header]): Map[String, String] = { + def buildHeaders(headersSet: Seq[Header]): Map[String, String] = { headersSet.foldLeft(Map.empty[String, String]) { (acc, header) => header.name.toLowerCase match { case CONTENT_TYPE => acc + (header.name -> RuntimeCache.resolve(header.value)) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala index 31e7355..1ec5489 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala @@ -23,6 +23,23 @@ import africa.absa.testing.scapi.rest.response.Response * It provides the capability to send different types of HTTP requests including GET, POST, PUT, and DELETE. */ object ScAPIRequestSender extends RequestSender { + + private def sendRequest(requestFunc: => requests.Response, url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { + val startTime = System.nanoTime() + val response = requestFunc + val endTime = System.nanoTime() + + Response( + response.statusCode, + response.text(), + url = response.url, + statusMessage = response.statusMessage, + response.headers, + cookies = response.cookies.view.mapValues(cookie => cookie.toString).toMap, + (endTime - startTime) / 1_000_000 + ) + } + /** * Sends a GET request to the provided URL with the given headers, SSL certificate verification setting, data, and parameters. * @@ -34,8 +51,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the GET request. */ override def get(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - val response = requests.get(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params) - Response(response.statusCode, response.text(), response.headers.toMap) + sendRequest(requests.get(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) } /** @@ -49,8 +65,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the POST request. */ override def post(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - val response = requests.post(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params) - Response(response.statusCode, response.text(), response.headers.toMap) + sendRequest(requests.post(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) } /** @@ -64,8 +79,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the PUT request. */ override def put(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - val response = requests.put(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params) - Response(response.statusCode, response.text(), response.headers.toMap) + sendRequest(requests.put(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) } /** @@ -79,7 +93,6 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the DELETE request. */ override def delete(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - val response = requests.delete(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params) - Response(response.statusCode, response.text(), response.headers.toMap) + sendRequest(requests.delete(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index f880bb2..8bb4749 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -20,6 +20,8 @@ import africa.absa.testing.scapi.UndefinedResponseActionType import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.validation.ContentValidator +import spray.json._ +import scala.xml.XML /** * Object that validates and performs various assertion response actions on the response received. @@ -27,11 +29,27 @@ import africa.absa.testing.scapi.utils.validation.ContentValidator */ object AssertionResponseAction extends ResponsePerformer { + // response-time-... + val RESPONSE_TIME_IS_BELOW = "response-time-is-below" + val RESPONSE_TIME_IS_ABOVE = "response-time-is-above" + + // status-code-... val STATUS_CODE_EQUALS = "status-code-equals" val STATUS_CODE_IS_SUCCESS = "status-code-is-success" - val STATUS_CODE_IS_CLIENT_ERROR = "status-code-is_client_error" - val STATUS_CODE_IS_SERVER_ERROR = "status-code-is_server_error" - val BODY_CONTAINS = "body-contains" + val STATUS_CODE_IS_CLIENT_ERROR = "status-code-is-client-error" + val STATUS_CODE_IS_SERVER_ERROR = "status-code-is-server-error" + + // header-... + val HEADER_EXISTS = "header-exists" + val HEADER_VALUE_EQUALS = "header-value-equals" + + // content-type-... + val CONTENT_TYPE_IS_JSON = "content-type-is-json" + val CONTENT_TYPE_IS_XML = "content-type-is-xml" + val CONTENT_TYPE_IS_HTML = "content-type-is-html" + + // body-... + val BODY_CONTAINS = "body-contains" // TODO - rename it to more specific /** * Validates the content of an assertion response action object depending on its type. @@ -42,14 +60,39 @@ object AssertionResponseAction extends ResponsePerformer { def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { + // response-time-... + case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => + responseAction.params.getOrElse("limit", None) match { + case limit: String => ContentValidator.validateLongString(limit, s"ResponseAssertion.${responseAction.name}.limit") + case None => throw new IllegalArgumentException(s"Missing required 'limit' parameter for assertion ${responseAction.name} logic.") + } + // status-code-... case STATUS_CODE_EQUALS => - responseAction.params.get("code") match { - case code => ContentValidator.validateIntegerString(code.get, s"ResponseAssertion.$STATUS_CODE_EQUALS.code") + responseAction.params.getOrElse("code", None) match { + case code: String => ContentValidator.validateIntegerString(code, s"ResponseAssertion.$STATUS_CODE_EQUALS.code") case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $STATUS_CODE_EQUALS logic.") } case STATUS_CODE_IS_SUCCESS | STATUS_CODE_IS_CLIENT_ERROR | STATUS_CODE_IS_SERVER_ERROR => () + // header-... + case HEADER_EXISTS | HEADER_VALUE_EQUALS => + responseAction.params.getOrElse("headerName", None) match { + case headerName: String => ContentValidator.validateNonEmptyString(headerName, s"ResponseAssertion.${responseAction.name}.headerName") + case None => throw new IllegalArgumentException(s"Missing required 'headerName' parameter for assertion ${responseAction.name} logic.") + } + responseAction.name.toLowerCase match { + case HEADER_VALUE_EQUALS => + responseAction.params.getOrElse("expectedValue", None) match { + case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$HEADER_VALUE_EQUALS.expectedValue") + case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $HEADER_VALUE_EQUALS logic.") + } + case _ => () + } + + // content-type-... + case CONTENT_TYPE_IS_JSON | CONTENT_TYPE_IS_XML | CONTENT_TYPE_IS_HTML => () + // body-... case BODY_CONTAINS => responseAction.params.get("body") match { @@ -71,6 +114,14 @@ object AssertionResponseAction extends ResponsePerformer { def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { responseAction.name match { + // response-time-... + case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => + val limit = responseAction.params("limit") + responseAction.name match { + case RESPONSE_TIME_IS_BELOW => assertResponseTimeIsBelow(response, limit) + case RESPONSE_TIME_IS_ABOVE => assertResponseTimeIsAbove(response, limit) + } + // status-code-... case STATUS_CODE_EQUALS => val code = responseAction.params("code") @@ -79,6 +130,21 @@ object AssertionResponseAction extends ResponsePerformer { case STATUS_CODE_IS_CLIENT_ERROR => assertStatusCodeIsClientError(response) case STATUS_CODE_IS_SERVER_ERROR => assertStatusCodeIsServerError(response) + // header-... + case HEADER_EXISTS | HEADER_VALUE_EQUALS => + val headerName = responseAction.params("headerName") + responseAction.name match { + case HEADER_EXISTS => assertHeaderExists(response, headerName) + case HEADER_VALUE_EQUALS => + val expectedValue = responseAction.params("expectedValue") + assertHeaderValueEquals(response, headerName, expectedValue) + } + + // content-type-... + case CONTENT_TYPE_IS_JSON => assertContentTypeIsJson(response) + case CONTENT_TYPE_IS_XML => assertContentTypeIsXml(response) + case CONTENT_TYPE_IS_HTML => assertContentTypeIsHtml(response) + // body-... case BODY_CONTAINS => val body = responseAction.params("body") @@ -91,6 +157,30 @@ object AssertionResponseAction extends ResponsePerformer { dedicated actions */ + /** + * Asserts that the response time is below the specified maximum time. + * + * @param response The response whose duration is to be checked. + * @param maxTimeMillis The maximum allowed time in milliseconds as a string. + * @return A Boolean indicating whether the response's duration is below the specified maximum time. Returns true if it's below, false otherwise. + */ + def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Boolean = { + val lMaxTimeMillis: Long = maxTimeMillis.toLong + response.duration <= lMaxTimeMillis + } + + /** + * Asserts that the response time is above the specified minimum time. + * + * @param response The response whose duration is to be checked. + * @param minTimeMillis The minimum required time in milliseconds as a string. + * @return A Boolean indicating whether the response's duration is above the specified minimum time. Returns true if it's above, false otherwise. + */ + def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Boolean = { + val lMinTimeMillis: Long = minTimeMillis.toLong + response.duration >= lMinTimeMillis + } + /** * Asserts that the status code of the response matches the expected status code. * @@ -138,6 +228,78 @@ object AssertionResponseAction extends ResponsePerformer { response.statusCode >= 500 && response.statusCode <= 599 } + /** + * Checks if the specified header exists in the given response. + * + * @param response The response object containing the headers. + * @param headerName The name of the header to check for. + * @return True if the header exists in the response, otherwise false. + */ + def assertHeaderExists(response: Response, headerName: String): Boolean = { + response.headers.contains(headerName.toLowerCase) + } + + /** + * Asserts that the value of the specified header in the given response matches the expected value. + * + * @param response The response object containing the headers. + * @param headerName The name of the header to check. + * @param expectedValue The expected value of the header. + * @return True if the header value matches the expected value, otherwise false. + */ + def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Boolean = { + if (assertHeaderExists(response, headerName)) + expectedValue.equals(response.headers(headerName.toLowerCase).head) + else + false + } + + /** + * Asserts that the value of the "Content-Type" header in the given response is "application/json". + * + * @param response The response object containing the headers. + * @return True if the "Content-Type" header value is "application/json", otherwise false. + */ + def assertContentTypeIsJson(response: Response): Boolean = { + val isContentTypeJson = assertHeaderValueEquals(response, "content-type", "application/json") + val isBodyJson = try { + response.body.parseJson + true + } catch { + case _: JsonParser.ParsingException => false + } + + isContentTypeJson && isBodyJson + } + + /** + * Asserts that the value of the "Content-Type" header in the given response is "application/xml". + * + * @param response The response object containing the headers. + * @return True if the "Content-Type" header value is "application/xml", otherwise false. + */ + def assertContentTypeIsXml(response: Response): Boolean = { + val isContentTypeXml = assertHeaderValueEquals(response, "content-type", "application/xml") + val isBodyXml = try { + XML.loadString(response.body) + true + } catch { + case _: Exception => false + } + + isContentTypeXml && isBodyXml + } + + /** + * Asserts that the value of the "Content-Type" header in the given response is "text/html". + * + * @param response The response object containing the headers. + * @return True if the "Content-Type" header value is "text/html", otherwise false. + */ + def assertContentTypeIsHtml(response: Response): Boolean = { + assertHeaderValueEquals(response, "content-type", "text/html") + } + /** * Asserts that the body of the response contains the expected content. * diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index df74355..3c8c33e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -17,8 +17,9 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.logging.Logger -case class Response(statusCode: Int, body: String, headers: Map[String, Seq[String]]) +case class Response(statusCode: Int, body: String, url: String, statusMessage: String, headers: Map[String, Seq[String]], cookies: Map[String, String], duration: Long) /** * A singleton object that is responsible for managing and handling responses. @@ -56,14 +57,34 @@ object Response { * @return Boolean indicating whether all response actions passed (true) or any response action failed (false). * @throws IllegalArgumentException If an response action group is not supported. */ - def perform(response: Response, responseAction: Set[ResponseAction]): Boolean = { + def perform(response: Response, responseAction: Seq[ResponseAction]): Boolean = { + def logParameters(response: Response, resolvedResponseAction: ResponseAction, exception: Option[Throwable] = None): Unit = { + val filteredParams = resolvedResponseAction.params.filter(_._1 != "method").map { case (k, v) => s"$k->$v" }.mkString(", ") + val baseLog = s"\nParameters received: \n\tRequired Response-Action: \n\t\tGroup->'${resolvedResponseAction.group}', \n\t\tMethod->'${resolvedResponseAction.name}', \n\t\tParams->'${filteredParams}', \n\tActual Response: \n\t\t$response" + val exceptionLog = exception.map(e => s"\nException: ${e.getMessage}").getOrElse("") + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - error details:$baseLog$exceptionLog") + } + responseAction.forall { assertion => val resolvedResponseAction: ResponseAction = assertion.resolveByRuntimeCache() - resolvedResponseAction.group match { - case GROUP_ASSERT => AssertionResponseAction.performResponseAction(response, assertion) - case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) - case GROUP_LOG => LogResponseAction.performResponseAction(response, assertion) - case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}") + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - Started.") + + try { + val res = resolvedResponseAction.group match { + case GROUP_ASSERT => AssertionResponseAction.performResponseAction(response, assertion) + case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) + case GROUP_LOG => LogResponseAction.performResponseAction(response, assertion) + case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}") + } + + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - ${if (res) "completed successfully" else "failed"}.") + if (!res) logParameters(response, resolvedResponseAction) + res + } catch { + case e: IllegalArgumentException => + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - failed with exception.") + logParameters(response, resolvedResponseAction, Some(e)) + throw e } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index 3a9ae08..852b575 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -39,7 +39,7 @@ object SuiteRunner { */ def runSuites(suiteBundles: Set[SuiteBundle], environment: Environment, restClientCreator: RestClientCreator): List[SuiteResults] = { suiteBundles.foldLeft(List[SuiteResults]()) { (resultList, suiteBundle) => - Logger.debug(s"Running Suite: ${suiteBundle.suite.endpoint}") + Logger.debug(s"Suite: ${suiteBundle.suite.endpoint} - Started") val resultSuiteBefore: List[SuiteResults] = suiteBundle.suiteBefore.toList.flatMap { suiteBefore => suiteBefore.methods.map { method => runSuiteBefore(suiteBundle.suite.endpoint, suiteBefore.name, method, environment, restClientCreator) } @@ -80,7 +80,7 @@ object SuiteRunner { * @return SuiteResults after the execution of the suite-before method. */ private def runSuiteBefore(suiteEndpoint: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { - Logger.debug(s"Running Suite-Before: ${suiteBeforeName}") + Logger.debug(s"Suite-Before: ${suiteBeforeName} - Started") val testStartTime: Long = System.currentTimeMillis() try { @@ -91,7 +91,7 @@ object SuiteRunner { ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"Before method '${method.name}' finished. Response statusCode is '${response.statusCode}'") + Logger.debug(s"Suite-Before: method '${method.name}' - ${if (isSuccess) "completed successfully" else "failed"}.") SuiteResults.withBooleanStatus( resultType = SuiteResults.RESULT_TYPE_BEFORE_METHOD, suiteName = suiteEndpoint, @@ -113,7 +113,7 @@ object SuiteRunner { * @return SuiteResults after the execution of the suite-test. */ private def runSuiteTest(suiteEndpoint: String, test: SuiteTestScenario, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { - Logger.debug(s"Running Suite-Test: ${test.name}") + Logger.debug(s"Suite-Test: ${test.name} - Started") val testStartTime: Long = System.currentTimeMillis() try { @@ -124,7 +124,7 @@ object SuiteRunner { ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"Test '${test.name}' finished. Response statusCode is '${response.statusCode}'") + Logger.debug(s"Suite-Test: '${test.name}' - ${if (isSuccess) "completed successfully" else "failed"}.") SuiteResults.withBooleanStatus( resultType = SuiteResults.RESULT_TYPE_TEST, suiteName = suiteEndpoint, @@ -151,7 +151,7 @@ object SuiteRunner { * @return SuiteResults after the execution of the suite-after method. */ private def runSuiteAfter(suiteEndpoint: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { - Logger.debug(s"Running Suite-After: ${suiteAfterName}") + Logger.debug(s"Suite-After: ${suiteAfterName} - Started") val testStartTime: Long = System.currentTimeMillis() try { @@ -162,7 +162,7 @@ object SuiteRunner { ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"After method '${method.name}' finished. Response statusCode is '${response.statusCode}'") + Logger.debug(s"After method '${method.name}' ${if (isSuccess) "completed successfully" else "failed"}.") SuiteResults.withBooleanStatus( resultType = SuiteResults.RESULT_TYPE_AFTER_METHOD, suiteName = suiteEndpoint, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala index 4193b67..97f8581 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala @@ -37,6 +37,19 @@ object ContentValidator { } } + /** + * Validates that a string can be parsed to a long. Throws an exception if the string cannot be parsed. + * + * @param input The string to be validated. + * @throws ContentValidationFailed if the input string cannot be parsed to a long. + */ + def validateLongString(input: String, param: String): Unit = { + Try(input.toLong) match { + case Success(_) => // Do nothing + case Failure(e) => throw ContentValidationFailed(input, s"Received value of '$param' cannot be parsed to a long: ${e.getMessage}") + } + } + /** * Validates that a string is not empty. Throws an exception if the string is empty. * diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 72a5654..1e6b29b 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -25,6 +25,33 @@ { "method": "assert.status-code-equals", "code": "200" + }, + { + "method": "assert.status-code-is-success" + }, + { + "method": "log.error", + "message": "Dummy error log message." + }, + { + "method": "log.warn", + "message": "Dummy warn log message." + }, + { + "method": "log.info", + "message": "Dummy info log message." + }, + { + "method": "log.debug", + "message": "Dummy debug log message." + }, + { + "method": "assert.response-time-is-below", + "limit": "600000" + }, + { + "method": "assert.response-time-is-above", + "limit": "1" } ] } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala index b432db3..e3db63a 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala @@ -27,7 +27,7 @@ class RequestHeadersTest extends FunSuite { */ test("buildHeaders - should correctly build headers map") { - val headersSet = Set( + val headersSeq = Seq( Header("Content-Type", "application/json"), Header("Authorization", "Bearer abcdefg12345"), Header("Custom-Header", "customValue") @@ -39,15 +39,15 @@ class RequestHeadersTest extends FunSuite { "Custom-Header" -> "customValue" ) - val actualMap = RequestHeaders.buildHeaders(headersSet) + val actualMap = RequestHeaders.buildHeaders(headersSeq) assertEquals(actualMap, expectedMap) } test("buildHeaders - should return an empty map if no headers are provided") { - val headersSet = Set.empty[Header] + val headersSeq = Seq.empty[Header] val expectedMap = Map.empty[String, String] - val actualMap = RequestHeaders.buildHeaders(headersSet) + val actualMap = RequestHeaders.buildHeaders(headersSeq) assertEquals(actualMap, expectedMap) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index 2814931..64ce4f7 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -130,15 +130,15 @@ class SuiteFactoryTest extends FunSuite { test("filterOnlyOrAll - only used - once") { val suitesBundles = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), )))) val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) @@ -157,11 +157,11 @@ class SuiteFactoryTest extends FunSuite { test("fromFile - only used - twice") { val suitesBundles = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(false)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)) + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), + SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), headers = Set.empty, actions = Set.empty, responseActions = Set.empty, only = Some(true)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)), )))) val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala index 97f62ad..79213e2 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala @@ -30,7 +30,7 @@ class RestClientTest extends FunSuite { assert(data == "testData") assert(params == Map("param1" -> "value1")) - Response(200, "test response", Map.empty[String, Seq[String]]) + Response(200, "test response", "", "", Map.empty[String, Seq[String]], Map.empty, 100) } override def get(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index ed8ac07..64f9220 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -26,6 +26,39 @@ class ResponseAssertionsTest extends FunSuite { validateContent */ + // response-time-... + + test("validateContent - response time is below - limit is integer string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "200")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - response time is below - limit is not integer string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "not_integer")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-below.limit' cannot be parsed to a long: For input string: \"not_integer\"") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - response time is above - limit is integer string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "200")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - response time is above - limit is not integer string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "not_integer")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-above.limit' cannot be parsed to a long: For input string: \"not_integer\"") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - response time is above - missing limit parameter") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map.empty) + interceptMessage[IllegalArgumentException]("Missing required 'limit' parameter for assertion response-time-is-above logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + // status-code-... test("validateContent - valid status code string") { @@ -39,6 +72,67 @@ class ResponseAssertionsTest extends FunSuite { } } + test("validateContent - status code equals - missing code parameter") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map.empty) + interceptMessage[IllegalArgumentException]("Missing required 'code' parameter for assertion status-code-equals logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + // header-... + + test("validateContent - header exists - valid header name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "content-type")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - header exists - invalid header name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-exists.headerName' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - header exists - missing header name parameter") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map.empty) + interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-exists logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - header value equals - valid header name and value strings") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - header value equals - invalid header name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "", "expectedValue" -> "application/json")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.headerName' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - header value equals - invalid expected value string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.expectedValue' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - header value equals - missing header name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("expectedValue" -> "application/json")) + interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-value-equals logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - header value equals - missing header value string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type")) + interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion header-value-equals logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + // body-... test("validateContent - body is not empty") { @@ -63,36 +157,66 @@ class ResponseAssertionsTest extends FunSuite { performResponseAction */ + // response-time-... + + test("performAssertions - response time is below limit - success") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "100")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) + + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + } + + test("performAssertions - response time is below limit - failed") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "100")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) + + assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + } + + test("performAssertions - response time is above limit - success") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "100")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) + + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + } + + test("performAssertions - response time is above limit - failed") { + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "100")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) + + assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + } + // status-code-... test("performAssertions - status code assertion - equals") { val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) - val response = Response(200, "Dummy Body", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) } test("performAssertions - status code assertion - not equals") { val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) - val response = Response(500, "Dummy Body", Map.empty) + val response = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) } test("performAssertions - status code - is success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map()) - val response200 = Response(200, "Dummy Body", Map.empty) - val response299 = Response(299, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map.empty) + val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response299 = Response(299, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) assert(AssertionResponseAction.performResponseAction(response299, statusCodeResponseAction)) } test("performAssertions - status code - is not success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map()) - val response199 = Response(199, "Dummy Body", Map.empty) - val response300 = Response(300, "Dummy Body", Map.empty) - val response500 = Response(500, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map.empty) + val response199 = Response(199, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response300 = Response(300, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(!AssertionResponseAction.performResponseAction(response199, statusCodeResponseAction)) assert(!AssertionResponseAction.performResponseAction(response300, statusCodeResponseAction)) @@ -100,19 +224,19 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is client error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map()) - val response400 = Response(400, "Dummy Body", Map.empty) - val response499 = Response(499, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map.empty) + val response400 = Response(400, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response400, statusCodeResponseAction)) assert(AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) } test("performAssertions - status code - is not client error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map()) - val response399 = Response(399, "Dummy Body", Map.empty) - val response500 = Response(500, "Dummy Body", Map.empty) - val response200 = Response(200, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map.empty) + val response399 = Response(399, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(!AssertionResponseAction.performResponseAction(response399, statusCodeResponseAction)) assert(!AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) @@ -120,37 +244,110 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is server error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map()) - val response500 = Response(500, "Dummy Body", Map.empty) - val response599 = Response(599, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map.empty) + val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response599 = Response(599, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) assert(AssertionResponseAction.performResponseAction(response599, statusCodeResponseAction)) } test("performAssertions - status code - is not server error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map()) - val response499 = Response(499, "Dummy Body", Map.empty) - val response600 = Response(600, "Dummy Body", Map.empty) - val response200 = Response(200, "Dummy Body", Map.empty) + val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map.empty) + val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response600 = Response(600, "Dummy Body", "", "", Map.empty, Map.empty, 100) + val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(!AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) assert(!AssertionResponseAction.performResponseAction(response600, statusCodeResponseAction)) assert(!AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) } + // header-... + + test("performAssertions - header exists") { + val headerExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "Content-Type")) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction)) + } + + test("performAssertions - header does not exists") { + val headerExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "headerValue")) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, headerExistsResponseAction)) + } + + test("performAssertions - header value is equals") { + val headerValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction)) + } + + test("performAssertions - header value is not equals") { + val headerValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "someName", "expectedValue" -> "someValue")) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction)) + } + + // content-type-... + + test("performAssertions - content type is json") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_JSON}", Map.empty) + val response = Response(200, "{}", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } + + test("performAssertions - content type is not json") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_JSON}", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } + + test("performAssertions - content type is xml") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_XML}", Map.empty) + val response = Response(200, """QADevDon't forget to test it!""", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) + + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } + + test("performAssertions - content type is not xml") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_XML}", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } + + test("performAssertions - content type is html") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_HTML}", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("text/html")), Map.empty, 100) + + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } + + test("performAssertions - content type is not html") { + val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_HTML}", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + } // body-... test("performAssertions - body contains assertion") { val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummy")) - val response = Response(200, "This is a dummy body", Map.empty) + val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) } test("performAssertions - body does not contains assertion") { val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummies")) - val response = Response(200, "This is a dummy body", Map.empty) + val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(!AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) } @@ -158,7 +355,7 @@ class ResponseAssertionsTest extends FunSuite { test("performAssertions - unsupported assertion") { val unsupportedResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) - val response = Response(200, "Dummy Body", Map.empty) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) interceptMessage[IllegalArgumentException]("Unsupported assertion method [group: assert]: unsupported-assertion") { AssertionResponseAction.performResponseAction(response, unsupportedResponseAction) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index fd8eb2d..c768f33 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -29,15 +29,30 @@ class ResponseExtractTest extends FunSuite { val responseWithID: Response = Response( 200, "[{\"id\":\"efa01eeb-34cb-42da-b150-ca6dbe52xxx1\",\"domainName\":\"Domain1\"},{\"id\":\"382be85a-1f00-4c15-b607-cbda03ccxxx2\",\"domainName\":\"Domain2\"},{\"id\":\"65173a5b-b13c-4db0-bd1b-24b3e3abxxx3\",\"domainName\":\"Domain3\"}]", - Map("Content-Type" -> Seq("application/json"))) + "", + "", + Map("Content-Type" -> Seq("application/json")), + Map.empty, + 100 + ) val responseNoJsonBody: Response = Response( 200, "no json here", - Map("Content-Type" -> Seq("application/json"))) + "", + "", + Map("Content-Type" -> Seq("application/json")), + Map.empty, + 100 + ) val responseJsonNoArrayBody: Response = Response( 200, "{\"id\":\"efa01eeb-34cb-42da-b150-ca6dbe52xxx1\",\"domainName\":\"Domain1\"}", - Map("Content-Type" -> Seq("application/json"))) + "", + "", + Map("Content-Type" -> Seq("application/json")), + Map.empty, + 100 + ) /* validateContent @@ -124,7 +139,7 @@ class ResponseExtractTest extends FunSuite { val assertion1None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) val assertion2None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "")) val assertion3None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "")) - val assertion4None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map()) + val assertion4None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion4None) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index 60dd060..b6fcecd 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -57,7 +57,7 @@ class ResponseLogTest extends FunSuite { } test("validateContent - no message provided") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map()) + val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'message' for assertion info logic.") { LogResponseAction.validateContent(responseAction) } @@ -69,31 +69,31 @@ class ResponseLogTest extends FunSuite { test("performAssertion - ERROR supported") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.ERROR}", Map("message" -> "info message")) - val response = Response(500, "OK", Map("Content-Type" -> Seq("application/json"))) + val response = Response(500, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - WARN supported") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.WARN}", Map("message" -> "info message")) - val response = Response(401, "OK", Map("Content-Type" -> Seq("application/json"))) + val response = Response(401, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - INFO supported") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "info message")) - val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) + val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - DEBUG supported") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.DEBUG}", Map("message" -> "info message")) - val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) + val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion), true) } test("performAssertion - not supported validation type") { val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "info message")) - val response = Response(200, "OK", Map("Content-Type" -> Seq("application/json"))) + val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) intercept[IllegalArgumentException] { LogResponseAction.performResponseAction(response, assertion) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala index d166efa..1dd68dc 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala @@ -39,10 +39,10 @@ class ResponseTest extends FunSuite { test("perform - unsupported group") { val unsupportedAssertion = ResponseAction(method = "unsupportedGroup.not needed", Map("param 1" -> "")) - val response = Response(200, "OK", Map.empty) + val response = Response(200, "OK", "", "", Map.empty, Map.empty, 100) intercept[IllegalArgumentException] { - Response.perform(response, Set(unsupportedAssertion)) + Response.perform(response, Seq(unsupportedAssertion)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/FakeScAPIRequestSender.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/FakeScAPIRequestSender.scala index e400a43..6e2a001 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/FakeScAPIRequestSender.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/FakeScAPIRequestSender.scala @@ -26,7 +26,12 @@ object FakeScAPIRequestSender extends RequestSender { var mockResponse: Response = Response( 200, "[{\"id\":\"efa01eeb-34cb-42da-b150-ca6dbe52xxx1\",\"domainName\":\"Domain1\"},{\"id\":\"382be85a-1f00-4c15-b607-cbda03ccxxx2\",\"domainName\":\"Domain2\"},{\"id\":\"65173a5b-b13c-4db0-bd1b-24b3e3abxxx3\",\"domainName\":\"Domain3\"}]", - Map("Content-Type" -> Seq("application/json"))) + "no url", + "fake status messsage", + Map("Content-Type" -> Seq("application/json")), + Map.empty, + 100 + ) override def get(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { mockResponse diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 8ea9e58..4f6847c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -32,21 +32,21 @@ class SuiteRunnerTest extends FunSuite { val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") val responseAction: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) - val method: Method = Method(name = "test", headers = Set(header), actions = Set(action), responseActions = Set(responseAction)) - val methodNotSupported: Method = Method(name = "test", headers = Set(header), actions = Set(actionNotSupported), responseActions = Set(responseAction)) + val method: Method = Method(name = "test", headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction)) + val methodNotSupported: Method = Method(name = "test", headers = Seq(header), actions = Seq(actionNotSupported), responseActions = Seq(responseAction)) val suitesBundles: Set[SuiteBundle] = Set( SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(true)), - SuiteTestScenario(name = "test2", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(true)) + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(true)), + SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(true)) ))), SuiteBundle( suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -54,8 +54,8 @@ class SuiteRunnerTest extends FunSuite { val suitesBundleNoBefore: Set[SuiteBundle] = Set( SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), )) @@ -63,8 +63,8 @@ class SuiteRunnerTest extends FunSuite { val suitesBundleAfterMethodNotSupported: Set[SuiteBundle] = Set( SuiteBundle( suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(methodNotSupported))), )) @@ -73,8 +73,8 @@ class SuiteRunnerTest extends FunSuite { SuiteBundle( suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), suite = Suite(endpoint = "endpoint2", tests = Set( - SuiteTestScenario(name = "test1", categories = Set("SMOKE"), - headers = Set(header), actions = Set(action), responseActions = Set(responseAction), only = Some(false)), + SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), + headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )))) val constants: Map[String, String] = Map( From 643a68a891decef1b961fe037b6747405c7c5d51 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 24 Aug 2023 16:16:05 +0200 Subject: [PATCH 09/31] * Implemented methods for Assertion 'ResponseAction' - cookie-... part --- .../main/resources/schema/after.schema.json | 2 +- .../main/resources/schema/before.schema.json | 2 +- .../main/resources/schema/suite.schema.json | 2 +- .../request/sender/ScAPIRequestSender.scala | 9 +- .../response/AssertionResponseAction.scala | 114 ++++++++++++-- .../scapi/rest/response/Response.scala | 2 +- .../response/ResponseAssertionsTest.scala | 141 +++++++++++++++++- 7 files changed, 247 insertions(+), 25 deletions(-) diff --git a/testApi/src/main/resources/schema/after.schema.json b/testApi/src/main/resources/schema/after.schema.json index 1387f36..ef2df79 100644 --- a/testApi/src/main/resources/schema/after.schema.json +++ b/testApi/src/main/resources/schema/after.schema.json @@ -125,7 +125,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.cookie-exists", "assert.cookie-value-equals", "assert.cookie-is-secured", "assert.cookie-is-not-secured", "assert.body-contains-text", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action. Restricted to specific values." } }, diff --git a/testApi/src/main/resources/schema/before.schema.json b/testApi/src/main/resources/schema/before.schema.json index f3259e5..7ffa859 100644 --- a/testApi/src/main/resources/schema/before.schema.json +++ b/testApi/src/main/resources/schema/before.schema.json @@ -123,7 +123,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.cookie-exists", "assert.cookie-value-equals", "assert.cookie-is-secured", "assert.cookie-is-not-secured", "assert.body-contains-text", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index 14d08f0..77d139a 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -134,7 +134,7 @@ "properties": { "method": { "type": "string", - "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.body-contains", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], + "enum": ["assert.response-time-is-below", "assert.response-time-is-above", "assert.status-code-equals", "assert.status-code-is-success", "assert.status-code-is-client-error", "assert.status-code-is-server-error", "assert.header-exists", "assert.header-value-equals", "assert.content-type-is-json", "assert.content-type-is-xml", "assert.content-type-is-html", "assert.cookie-exists", "assert.cookie-value-equals", "assert.cookie-is-secured", "assert.cookie-is-not-secured", "assert.body-contains-text", "log.error", "log.warn", "log.info", "log.debug", "extractJson.string-from-list"], "description": "The method to be used for the response action." } }, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala index 1ec5489..bac21ed 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala @@ -18,6 +18,8 @@ package africa.absa.testing.scapi.rest.request.sender import africa.absa.testing.scapi.rest.response.Response +import java.net.HttpCookie + /** * ScAPIRequestSender is an implementation of the RequestSender interface. * It provides the capability to send different types of HTTP requests including GET, POST, PUT, and DELETE. @@ -29,13 +31,18 @@ object ScAPIRequestSender extends RequestSender { val response = requestFunc val endTime = System.nanoTime() + val extractedCookies: Map[String, (String, Boolean)] = response.cookies.view.map { + case (name, cookie: HttpCookie) => + (name, (cookie.getValue, cookie.getSecure)) + }.toMap + Response( response.statusCode, response.text(), url = response.url, statusMessage = response.statusMessage, response.headers, - cookies = response.cookies.view.mapValues(cookie => cookie.toString).toMap, + cookies = extractedCookies, (endTime - startTime) / 1_000_000 ) } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 8bb4749..414538b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -48,8 +48,14 @@ object AssertionResponseAction extends ResponsePerformer { val CONTENT_TYPE_IS_XML = "content-type-is-xml" val CONTENT_TYPE_IS_HTML = "content-type-is-html" + // cookies-... + val COOKIE_EXISTS = "cookie-exists" + val COOKIE_VALUE_EQUALS = "cookie-value-equals" + val COOKIE_IS_SECURED = "cookie-is-secured" + val COOKIE_IS_NOT_SECURED = "cookie-is-not-secured" + // body-... - val BODY_CONTAINS = "body-contains" // TODO - rename it to more specific + val BODY_CONTAINS_TEXT = "body-contains-text" /** * Validates the content of an assertion response action object depending on its type. @@ -93,11 +99,26 @@ object AssertionResponseAction extends ResponsePerformer { // content-type-... case CONTENT_TYPE_IS_JSON | CONTENT_TYPE_IS_XML | CONTENT_TYPE_IS_HTML => () + // cookies-... + case COOKIE_EXISTS | COOKIE_VALUE_EQUALS | COOKIE_IS_SECURED | COOKIE_IS_NOT_SECURED => + responseAction.params.getOrElse("cookieName", None) match { + case cookieName: String => ContentValidator.validateNonEmptyString(cookieName, s"ResponseAssertion.${responseAction.name}.cookieName") + case None => throw new IllegalArgumentException(s"Missing required 'cookieName' parameter for assertion ${responseAction.name} logic.") + } + responseAction.name.toLowerCase match { + case COOKIE_VALUE_EQUALS => + responseAction.params.getOrElse("expectedValue", None) match { + case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$COOKIE_VALUE_EQUALS.expectedValue") + case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $COOKIE_VALUE_EQUALS logic.") + } + case _ => () + } + // body-... - case BODY_CONTAINS => - responseAction.params.get("body") match { - case body => ContentValidator.validateNonEmptyString(body.get, s"ResponseAssertion.$BODY_CONTAINS.body") - case None => throw new IllegalArgumentException(s"Missing required 'body' parameter for assertion $BODY_CONTAINS logic.") + case BODY_CONTAINS_TEXT => + responseAction.params.getOrElse("text", None) match { + case text: String => ContentValidator.validateNonEmptyString(text, s"ResponseAssertion.$BODY_CONTAINS_TEXT.text") + case None => throw new IllegalArgumentException(s"Missing required 'text' parameter for assertion $BODY_CONTAINS_TEXT logic.") } case _ => throw UndefinedResponseActionType(responseAction.name) } @@ -145,10 +166,23 @@ object AssertionResponseAction extends ResponsePerformer { case CONTENT_TYPE_IS_XML => assertContentTypeIsXml(response) case CONTENT_TYPE_IS_HTML => assertContentTypeIsHtml(response) + // cookies-... + case COOKIE_EXISTS | COOKIE_VALUE_EQUALS | COOKIE_IS_SECURED | COOKIE_IS_NOT_SECURED => + val cookieName = responseAction.params("cookieName") + responseAction.name match { + case COOKIE_EXISTS => assertCookieExists(response, cookieName) + case COOKIE_VALUE_EQUALS => + val expectedValue = responseAction.params("expectedValue") + assertCookieValueEquals(response, cookieName, expectedValue) + case COOKIE_IS_SECURED => assertCookieIsSecured(response, cookieName) + case COOKIE_IS_NOT_SECURED => assertCookieIsNotSecured(response, cookieName) + } + // body-... - case BODY_CONTAINS => - val body = responseAction.params("body") - assertBodyContains(response, body) + case BODY_CONTAINS_TEXT => + val text = responseAction.params("text") + assertBodyContainsText(response, text) + case _ => throw new IllegalArgumentException(s"Unsupported assertion method [group: assert]: ${responseAction.name}") } } @@ -300,17 +334,73 @@ object AssertionResponseAction extends ResponsePerformer { assertHeaderValueEquals(response, "content-type", "text/html") } + // cookies-... + + /** + * Asserts that the specified cookie exists in the given response. + * + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check for existence. + * @return True if the specified cookie exists in the response, otherwise false. + */ + def assertCookieExists(response: Response, cookieName: String): Boolean = { + response.cookies.contains(cookieName) + } + + /** + * Asserts that the value of the specified cookie in the given response equals the expected value. + * + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check. + * @param expectedValue The expected value of the cookie. + * @return True if the value of the specified cookie matches the expected value, otherwise false. + */ + def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Boolean = { + if (assertCookieExists(response, cookieName)) + response.cookies(cookieName)._1 == expectedValue + else + false + } + + /** + * Asserts that the specified cookie in the given response is secured. + * + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check. + * @return True if the specified cookie is secured, otherwise false. + */ + def assertCookieIsSecured(response: Response, cookieName: String): Boolean = { + if (assertCookieExists(response, cookieName)) + response.cookies(cookieName)._2 + else + false + } + + /** + * Asserts that the specified cookie in the given response is not secured. + * + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check. + * @return True if the specified cookie is not secured, otherwise false. + */ + def assertCookieIsNotSecured(response: Response, cookieName: String): Boolean = { + if (assertCookieExists(response, cookieName)) + !response.cookies(cookieName)._2 + else + false + } + /** * Asserts that the body of the response contains the expected content. * * @param response The HTTP response to check the body of. - * @param expectedContent The expected content present in the response body as a string. + * @param text The expected text present in the response body as a string. * @return A Boolean indicating whether the expected content is present in the response body or not. */ - def assertBodyContains(response: Response, expectedContent: String): Boolean = { - val isSuccess: Boolean = response.body.contains(expectedContent) + def assertBodyContainsText(response: Response, text: String): Boolean = { + val isSuccess: Boolean = response.body.contains(text) if (!isSuccess) - Logger.error(s"Expected body to contain $expectedContent") + Logger.error(s"Expected body to contain $text") isSuccess } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 3c8c33e..dad1d7d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -case class Response(statusCode: Int, body: String, url: String, statusMessage: String, headers: Map[String, Seq[String]], cookies: Map[String, String], duration: Long) +case class Response(statusCode: Int, body: String, url: String, statusMessage: String, headers: Map[String, Seq[String]], cookies: Map[String, (String, Boolean)], duration: Long) /** * A singleton object that is responsible for managing and handling responses. diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 64f9220..25d36ba 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -133,19 +133,78 @@ class ResponseAssertionsTest extends FunSuite { } } + // cookies-... + + test("validateContent - cookie exists - valid cookie name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "testCookie")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - cookie exists - invalid cookie name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-exists.cookieName' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - cookie exists - missing cookie name parameter") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map()) + interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-exists logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - cookie value equals - valid cookie name and value strings") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + AssertionResponseAction.validateContent(responseAction) + } + + test("validateContent - cookie value equals - invalid cookie name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "", "expectedValue" -> "cookieValue")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.cookieName' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - cookie value equals - invalid cookie value string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "")) + interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.expectedValue' is empty.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - cookie value equals - missing cookie name string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("expectedValue" -> "cookieValue")) + interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-value-equals logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + + test("validateContent - cookie value equals - missing cookie value string") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie")) + interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion cookie-value-equals logic.") { + AssertionResponseAction.validateContent(responseAction) + } + } + // body-... - test("validateContent - body is not empty") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> "test content")) + test("validateContent - body contains text - body is not empty") { + val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "test content")) AssertionResponseAction.validateContent(responseAction) } - test("validateContent - body is empty") { + test("validateContent - body contains text - body is empty") { intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS}", Map("body" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> ""))) } } + test("validateContent - body contains text - body parameter is missing") { + interceptMessage[IllegalArgumentException]("Missing required 'text' parameter for assertion body-contains-text logic.") { + AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map.empty)) + } + } test("validateContent - unsupported response action") { intercept[UndefinedResponseActionType] { @@ -337,21 +396,87 @@ class ResponseAssertionsTest extends FunSuite { assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) } + // cookies-... + + test("performAssertions - cookie exists") { + val cookieExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "testCookie")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) + + assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction)) + } + + test("performAssertions - cookie does not exists") { + val cookieExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "anotherCookie")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) + + assert(!AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction)) + } + + test("performAssertions - cookie value is equals") { + val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("cookieValue", false)), 100) + + assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + } + + test("performAssertions - cookie value is not equals") { + val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("anotherValue", false)), 100) + + assert(!AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + } + + test("performAssertions - cookie value equals - cookie does not exist") { + val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + } + + test("performAssertions - cookie is secured") { + val cookieIsSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_SECURED}", Map("cookieName" -> "securedCookie")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> ("someValue", true)), 100) + + assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction)) + } + + test("performAssertions - cookie is secured - cookie does not exist") { + val cookieIsSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_SECURED}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction)) + } + + test("performAssertions - cookie is not secured") { + val cookieIsNotSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_NOT_SECURED}", Map("cookieName" -> "notSecuredCookie")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> ("someValue", false)), 100) + + assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction)) + } + + test("performAssertions - cookie is not secured - cookie does not exist") { + val cookieIsNotSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_NOT_SECURED}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) + + assert(!AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction)) + } + // body-... test("performAssertions - body contains assertion") { - val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummy")) + val bodyContainsTextResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "dummy")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction)) } test("performAssertions - body does not contains assertion") { - val bodyContainsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.body-contains", Map("body" -> "dummies")) + val bodyContainsTextResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "dummies")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, bodyContainsResponseAction)) + assert(!AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction)) } + // unsupported test("performAssertions - unsupported assertion") { val unsupportedResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) From 6032a6431c2645db83b934a09e6dd6d90a719282 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 7 Sep 2023 16:54:36 +0200 Subject: [PATCH 10/31] * Fix multiline strings review note. * Fix not used method parameters review note. --- .../scapi/rest/request/sender/ScAPIRequestSender.scala | 10 +++++----- .../absa/testing/scapi/rest/response/Response.scala | 10 +++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala index bac21ed..8a1e41e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala @@ -26,7 +26,7 @@ import java.net.HttpCookie */ object ScAPIRequestSender extends RequestSender { - private def sendRequest(requestFunc: => requests.Response, url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { + private def sendRequest(requestFunc: => requests.Response): Response = { val startTime = System.nanoTime() val response = requestFunc val endTime = System.nanoTime() @@ -58,7 +58,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the GET request. */ override def get(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - sendRequest(requests.get(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) + sendRequest(requests.get(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params)) } /** @@ -72,7 +72,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the POST request. */ override def post(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - sendRequest(requests.post(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) + sendRequest(requests.post(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params)) } /** @@ -86,7 +86,7 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the PUT request. */ override def put(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - sendRequest(requests.put(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) + sendRequest(requests.put(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params)) } /** @@ -100,6 +100,6 @@ object ScAPIRequestSender extends RequestSender { * @return Response Returns the response from the DELETE request. */ override def delete(url: String, headers: Map[String, String], verifySslCerts: Boolean, data: String, params: Map[String, String]): Response = { - sendRequest(requests.delete(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params), url, headers, verifySslCerts, data, params) + sendRequest(requests.delete(url = url, headers = headers, verifySslCerts = verifySslCerts, data = data, params = params)) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index dad1d7d..81c2784 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -60,7 +60,15 @@ object Response { def perform(response: Response, responseAction: Seq[ResponseAction]): Boolean = { def logParameters(response: Response, resolvedResponseAction: ResponseAction, exception: Option[Throwable] = None): Unit = { val filteredParams = resolvedResponseAction.params.filter(_._1 != "method").map { case (k, v) => s"$k->$v" }.mkString(", ") - val baseLog = s"\nParameters received: \n\tRequired Response-Action: \n\t\tGroup->'${resolvedResponseAction.group}', \n\t\tMethod->'${resolvedResponseAction.name}', \n\t\tParams->'${filteredParams}', \n\tActual Response: \n\t\t$response" + val baseLog = + s""" + |Parameters received: + | Required Response-Action: + | Group->'${resolvedResponseAction.group}', + | Method->'${resolvedResponseAction.name}', + | Params->'${filteredParams}', + | Actual Response: + | $response""".stripMargin val exceptionLog = exception.map(e => s"\nException: ${e.getMessage}").getOrElse("") Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - error details:$baseLog$exceptionLog") } From c203ab6e0a2670215c2b1f00296202274cfbd634 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 21 Sep 2023 09:03:29 +0200 Subject: [PATCH 11/31] * Fix - multiline strings review note. * Fix - not used method parameters review note. * Fix - String to Enum * Fix - replace boolean return values in XYZResponseAction methods. --- .../absa/testing/scapi/Exceptions.scala | 23 +- .../absa/testing/scapi/ScAPIRunner.scala | 6 +- .../scapi/json/ReferenceResolver.scala | 17 +- .../testing/scapi/json/SuiteFactory.scala | 24 +- .../json/schema/JsonSchemaValidator.scala | 4 +- .../testing/scapi/model/SuiteResult.scala | 50 ++++ .../testing/scapi/model/SuiteResultType.scala | 22 ++ .../testing/scapi/model/SuiteResults.scala | 81 ------ .../scapi/reporter/StdOutReporter.scala | 25 +- .../scapi/rest/request/RequestBody.scala | 8 +- .../scapi/rest/request/RequestHeaders.scala | 6 +- .../response/AssertionResponseAction.scala | 173 +++++++++---- .../response/ExtractJsonResponseAction.scala | 22 +- .../rest/response/LogResponseAction.scala | 30 +-- .../scapi/rest/response/Response.scala | 47 ++-- .../response/ResponseActionGroupType.scala | 33 +++ .../rest/response/ResponsePerformer.scala | 4 +- .../scapi/suite/runner/SuiteRunner.scala | 93 +++---- .../utils/validation/ContentValidator.scala | 18 +- .../absa/testing/scapi/ScAPIRunnerTest.scala | 2 +- .../scapi/json/EnvironmentFactoryTest.scala | 6 +- .../testing/scapi/json/EnvironmentTest.scala | 4 +- .../testing/scapi/json/RequestBodyTest.scala | 4 +- .../scapi/json/RequestHeadersTest.scala | 8 +- .../scapi/json/RequestParamsTest.scala | 4 +- .../testing/scapi/json/SuiteFactoryTest.scala | 8 +- .../scapi/reporter/StdOutReporterTest.scala | 40 +-- .../response/ResponseAssertionsTest.scala | 236 +++++++++--------- .../rest/response/ResponseExtractTest.scala | 48 ++-- .../scapi/rest/response/ResponseLogTest.scala | 47 ++-- .../scapi/rest/response/ResponseTest.scala | 49 ---- .../scapi/suite/runner/SuiteRunnerTest.scala | 42 ++-- .../validation/ContentValidatorTest.scala | 8 +- 33 files changed, 628 insertions(+), 564 deletions(-) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResults.scala create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala delete mode 100644 testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala b/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala index 78b1227..a74d999 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/Exceptions.scala @@ -20,23 +20,30 @@ import com.networknt.schema.ValidationMessage import scala.collection.mutable -case class UndefinedConstantsInProperties(undefinedConstants: Set[String], source: String) +case class UndefinedConstantsInPropertiesException(undefinedConstants: Set[String], source: String) extends Exception(s"Undefined constant(s): '${undefinedConstants.mkString(", ")}' in '$source'.") -case class PropertyNotFound(property: String) extends Exception(s"Property not found: '$property'.") +case class PropertyNotFoundException(property: String) extends Exception(s"Property not found: '$property'.") -case class JsonInvalidSchema(filePath: String, messages: mutable.Set[ValidationMessage]) +case class JsonInvalidSchemaException(filePath: String, messages: mutable.Set[ValidationMessage]) extends Exception(s"Json file '$filePath' not valid to defined json schema. " + messages.mkString("\n")) -case class ProjectLoadFailed() extends Exception("Problems during project loading.") +case class ProjectLoadFailedException() extends Exception("Problems during project loading.") -case class SuiteLoadFailed(detail: String) extends Exception(s"Problems during project loading. Details: $detail") +case class SuiteLoadFailedException(detail: String) + extends Exception(s"Problems during project loading. Details: $detail") -case class UndefinedHeaderType(undefinedType: String) +case class SuiteBeforeFailedException(detail: String) + extends Exception(s"Problems during running before suite logic. Details: $detail") + +case class UndefinedHeaderTypeException(undefinedType: String) extends Exception(s"Undefined Header content type: '$undefinedType'") -case class UndefinedResponseActionType(undefinedType: String) +case class UndefinedResponseActionTypeException(undefinedType: String) extends Exception(s"Undefined response action content type: '$undefinedType'") -case class ContentValidationFailed(value: String, message: String) +case class ContentValidationFailedException(value: String, message: String) extends Exception(s"Content validation failed for value: '$value': $message") + +case class AssertionException(message: String) + extends Exception(s"Assertion failed: $message") diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala index faeef59..cc6c724 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi import africa.absa.testing.scapi.config.ScAPIRunnerConfig import africa.absa.testing.scapi.json.{Environment, EnvironmentFactory, SuiteFactory} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.{SuiteBundle, SuiteResults} +import africa.absa.testing.scapi.model.{SuiteBundle, SuiteResult} import africa.absa.testing.scapi.reporter.StdOutReporter import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.sender.ScAPIRequestSender @@ -47,7 +47,7 @@ object ScAPIRunner { Logger.setLevel(if (cmd.debug) Level.DEBUG else Level.INFO) cmd.logConfigInfo() - if (!Files.exists(Paths.get(cmd.testRootPath, "suites"))) throw SuiteLoadFailed("'suites' directory have to exist in project root.") + if (!Files.exists(Paths.get(cmd.testRootPath, "suites"))) throw SuiteLoadFailedException("'suites' directory have to exist in project root.") // jsons to objects val environment: Environment = EnvironmentFactory.fromFile(cmd.envPath) @@ -59,7 +59,7 @@ object ScAPIRunner { Logger.info("Validate only => end run.") } else { Logger.info("Running tests") - val testResults: List[SuiteResults] = SuiteRunner.runSuites(suiteBundles, environment, () => new RestClient(ScAPIRequestSender)) + val testResults: List[SuiteResult] = SuiteRunner.runSuites(suiteBundles, environment, () => new RestClient(ScAPIRequestSender)) StdOutReporter.printReport(testResults) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index c15845e..d30401a 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -16,8 +16,9 @@ package africa.absa.testing.scapi.json +import africa.absa.testing.scapi.rest.response.ResponseActionGroupType.ResponseActionGroupType import africa.absa.testing.scapi.utils.cache.RuntimeCache -import africa.absa.testing.scapi.{PropertyNotFound, UndefinedConstantsInProperties} +import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedConstantsInPropertiesException} import scala.util.matching.Regex @@ -56,10 +57,10 @@ sealed protected trait ReferenceResolver { * If there are any unresolved references, it throws an exception. * * @param notResolvedReferences A set of unresolved reference keys. - * @throws UndefinedConstantsInProperties If there are any unresolved references. + * @throws UndefinedConstantsInPropertiesException If there are any unresolved references. */ private def notResolved(notResolvedReferences: Set[String]): Unit = - if (notResolvedReferences.nonEmpty) throw UndefinedConstantsInProperties(notResolvedReferences, s"'${getClass.getSimpleName}' action.") + if (notResolvedReferences.nonEmpty) throw UndefinedConstantsInPropertiesException(notResolvedReferences, s"'${getClass.getSimpleName}' action.") /** * Resolve a map of references to their actual values. It iteratively updates the map with resolved values. @@ -114,7 +115,7 @@ case class Environment private(constants: Map[String, String], properties: Map[S * @param key The key to retrieve the value for. * @return The value corresponding to the key. */ - def apply(key: String): String = properties.getOrElse(key, constants.getOrElse(key, throw PropertyNotFound(key))) + def apply(key: String): String = properties.getOrElse(key, constants.getOrElse(key, throw PropertyNotFoundException(key))) /** * Method to resolve all the references in the environment's properties. @@ -207,14 +208,10 @@ case class Action private(methodName: String, url: String, body: Option[String] * @param params the map containing the parameters of the response action. Each key-value pair in the map * represents a parameter name and its corresponding value. */ -case class ResponseAction private(method: String, +case class ResponseAction private(group: ResponseActionGroupType, + name: String, params: Map[String, String]) extends ReferenceResolver { - private def splitter: Seq[String] = method.split("\\.").toSeq - - def group : String = splitter.head - def name : String = splitter.tail.head - /** * Method to resolve references. * diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index 0ee31e2..a24c695 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -21,7 +21,7 @@ import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSche import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} -import africa.absa.testing.scapi.rest.response.Response +import africa.absa.testing.scapi.rest.response.{Response, ResponseActionGroupType} import africa.absa.testing.scapi.utils.file.{FileUtils, JsonUtils} import spray.json._ @@ -71,7 +71,7 @@ object SuiteFactory { failedSuites.foreach { case (key, value) => Logger.error(s"$key => $value") } - throw ProjectLoadFailed() + throw ProjectLoadFailedException() } } @@ -324,16 +324,26 @@ object SuiteAfterJsonProtocol extends DefaultJsonProtocol { object ResponseActionJsonProtocol extends DefaultJsonProtocol { implicit object ResponseActionJsonFormat extends RootJsonFormat[ResponseAction] { - def write(a: ResponseAction): JsObject = JsObject( - ("method" -> JsString(a.method)) +: - a.params.view.mapValues(JsString(_)).toSeq: _* - ) + def write(a: ResponseAction): JsObject = { + val fixedFields = Seq( + "group" -> JsString(a.group.toString), + "name" -> JsString(a.name) + ) + + val paramFields = a.params.view.mapValues(JsString(_)).toSeq + + JsObject((fixedFields ++ paramFields): _*) + } def read(value: JsValue): ResponseAction = { value.asJsObject.getFields("method") match { case Seq(JsString(method)) => + val splitter: Seq[String] = method.split("\\.").toSeq + val group = ResponseActionGroupType.fromString(splitter.head).getOrElse( + throw new IllegalArgumentException(s"Invalid action group: ${splitter.head}")) + val name = splitter.tail.head val params = value.asJsObject.fields.view.toMap - ResponseAction(method, params.map { case (k, v) => k -> v.convertTo[String] }) + ResponseAction(group, name, params.map { case (k, v) => k -> v.convertTo[String] }) case _ => throw DeserializationException("Assertion expected") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala index 29e98a2..3730f42 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json.schema -import africa.absa.testing.scapi.JsonInvalidSchema +import africa.absa.testing.scapi.JsonInvalidSchemaException import africa.absa.testing.scapi.utils.file.JsonUtils import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.networknt.schema.{JsonSchema, JsonSchemaFactory, SpecVersion} @@ -61,7 +61,7 @@ case class JsonSchemaValidator(jsonPath: String, schemaPath: URL) { val errors = jsonSchema.validate(jsonNode) import scala.jdk.CollectionConverters._ - if (!errors.isEmpty) throw JsonInvalidSchema(jsonPath, errors.asScala) + if (!errors.isEmpty) throw JsonInvalidSchemaException(jsonPath, errors.asScala) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala new file mode 100644 index 0000000..9592a1a --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.model + +import africa.absa.testing.scapi.model.SuiteResultType.SuiteResultType + +import scala.util.{Failure, Try} + +/** + * Case class representing the results of a suite test. + * + * @param resultType The type of the result (e.g. Before, Test, After) + * @param suiteName The name of the suite + * @param name The name of the test or method + * @param duration The duration of the test, if applicable + * @param categories The categories of the test, if any + * TODO + */ +case class SuiteResult(resultType: SuiteResultType, + suiteName: String, + name: String, + result: Try[Unit], + duration: Option[Long], + categories: Option[String] = None) { + /** + * Checks if the suite result was a success. + * + * @return true if the suite result was a success, false otherwise + */ + def isSuccess: Boolean = result.isSuccess + + def errorMsg: Option[String] = result match { + case Failure(t) => Some(t.getMessage) + case _ => None + } +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala new file mode 100644 index 0000000..4398c71 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala @@ -0,0 +1,22 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.model + +object SuiteResultType extends Enumeration { + val BEFORE_SUITE, TEST_SUITE, AFTER_SUITE = Value + type SuiteResultType = Value +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResults.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResults.scala deleted file mode 100644 index 41f6eaf..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResults.scala +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.model - -/** - * Case class representing the results of a suite test. - * - * @param resultType The type of the result (e.g. Before, Test, After) - * @param suiteName The name of the suite - * @param name The name of the test or method - * @param status The status of the result (e.g. Success, Failure) - * @param duration The duration of the test, if applicable - * @param errMessage The error message, if any - * @param categories The categories of the test, if any - */ -case class SuiteResults(resultType: String, - suiteName: String, - name: String, - status: String, - duration: Option[Long], - errMessage: Option[String] = None, - categories: Option[String] = None) { - /** - * Checks if the suite result was a success. - * - * @return true if the suite result was a success, false otherwise - */ - def isSuccess: Boolean = this.status == SuiteResults.Success -} - -object SuiteResults { - val Success: String = "Success" - val Failure: String = "Failure" - - val RESULT_TYPE_BEFORE_METHOD = "Before" - val RESULT_TYPE_TEST = "Test" - val RESULT_TYPE_AFTER_METHOD = "After" - - /** - * Creates and returns a `SuiteResults` object for a method setup operation. This is typically used for storing test setup operation results. - * - * @param resultType Type of result. - * @param suiteName Name of the suite that this setup operation belongs to. - * @param name Name of the setup operation. - * @param status Boolean indicating the success (true) or failure (false) of the setup operation. - * @param duration Optional duration of the setup operation in milliseconds. None if not available. - * @param errMessage Optional error message if the setup operation failed. None if not available. - * @param categories Optional string representing categories the setup operation belongs to. None if not available. - * @return A `SuiteResults` object containing the provided details of the setup operation. - */ - def withBooleanStatus(resultType: String, - suiteName: String, - name: String, - status: Boolean, - duration: Option[Long], - errMessage: Option[String] = None, - categories: Option[String] = None): SuiteResults = { - SuiteResults(resultType, - suiteName, - name, - if (status) Success else Failure, - duration, - errMessage, - categories - ) - } -} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala index 5dfde82..4905600 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.reporter -import africa.absa.testing.scapi.model.SuiteResults +import africa.absa.testing.scapi.model.{SuiteResult, SuiteResultType} /** * A singleton object to manage the standard output reporting of test results. @@ -27,7 +27,7 @@ object StdOutReporter { * * @param testResults The set of test suite results to be reported. */ - def printReport(testResults: List[SuiteResults]): Unit = { + def printReport(testResults: List[SuiteResult]): Unit = { def createFormattedLine(line: Option[String] = None, maxChars: Int = 80, repeatChar: Char = '*'): String = line match { case Some(text) => s"${repeatChar.toString * ((maxChars - text.length - 2) / 2)} $text ${repeatChar.toString * ((maxChars - text.length - 2) / 2)}" @@ -58,8 +58,8 @@ object StdOutReporter { printHeader("Simple Text Report") - val successCount = testResults.count(r => r.status == SuiteResults.Success && r.resultType == SuiteResults.RESULT_TYPE_TEST) - val failureCount = testResults.count(r => r.status == SuiteResults.Failure && r.resultType == SuiteResults.RESULT_TYPE_TEST) + val successCount = testResults.count(r => r.isSuccess && r.resultType == SuiteResultType.TEST_SUITE) + val failureCount = testResults.count(r => !r.isSuccess && r.resultType == SuiteResultType.TEST_SUITE) println(s"Number of tests run: ${successCount + failureCount}") println(s"Number of successful tests: $successCount") @@ -67,10 +67,10 @@ object StdOutReporter { if (testResults.nonEmpty) { val suiteSummary = testResults - .filter(_.resultType == SuiteResults.RESULT_TYPE_TEST) + .filter(_.resultType == SuiteResultType.TEST_SUITE) .groupBy(_.suiteName).map { case (suiteName, results) => - (suiteName, results.size, results.count(_.status == SuiteResults.Success)) + (suiteName, results.size, results.count(_.isSuccess)) } printInnerHeader("Suites Summary") @@ -83,10 +83,15 @@ object StdOutReporter { printTableRowSplitter() println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %-13s | %-7s | %-${maxTestCategoriesLength}s | ".format("Suite Name", "Test Name", "Duration (ms)", "Status", "Categories")) printTableRowSplitter() - val resultsList = testResults.filter(_.resultType == SuiteResults.RESULT_TYPE_TEST) + val resultsList = testResults.filter(_.resultType == SuiteResultType.TEST_SUITE) resultsList.zipWithIndex.foreach { case (result, index) => val duration = result.duration.map(_.toString).getOrElse("NA") - println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %13s | %-7s | %-${maxTestCategoriesLength}s | ".format(result.suiteName, result.name, duration, result.status, result.categories.getOrElse(""))) + println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %13s | %-7s | %-${maxTestCategoriesLength}s | ".format( + result.suiteName, + result.name, + duration, + if (result.isSuccess) "Success" else "Failure", + result.categories.getOrElse(""))) // Check if the index + 1 is divisible by 4 (since index is 0-based) if ((index + 1) % 3 == 0) printTableRowSplitter() @@ -94,10 +99,10 @@ object StdOutReporter { if (failureCount > 0) { printInnerHeader("Details of failed tests") - testResults.filter(_.status == SuiteResults.Failure).sortBy(_.name).foreach { result => + testResults.filter(!_.isSuccess).sortBy(_.name).foreach { result => println(s"Suite: ${result.suiteName}") println(s"Test: ${result.name}") - println(s"Error: ${result.errMessage.getOrElse("No details available")}") + println(s"Error: ${result.errorMsg.getOrElse("No details available")}") println(s"Duration: ${result.duration.getOrElse("NA")} ms") println(s"Category: ${result.categories}") println() diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestBody.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestBody.scala index e75a92c..11c9e9e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestBody.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestBody.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.request -import africa.absa.testing.scapi.ContentValidationFailed +import africa.absa.testing.scapi.ContentValidationFailedException import africa.absa.testing.scapi.utils.cache.RuntimeCache import spray.json._ @@ -33,7 +33,7 @@ object RequestBody { * * @param jsonBody An optional string containing the JSON body. If None or empty string, an empty JSON object ("{}") is returned. * @return A string representing the HTTP request body. - * @throws ContentValidationFailed if JSON body parsing to a string fails at runtime. + * @throws ContentValidationFailedException if JSON body parsing to a string fails at runtime. */ def buildBody(jsonBody: Option[String] = None): String = { jsonBody match { @@ -47,7 +47,7 @@ object RequestBody { * If the JSON body cannot be parsed, a ContentValidationFailed exception is thrown. * * @param jsonBody An optional string containing the JSON body to validate. If None or empty, the method simply returns. - * @throws ContentValidationFailed if the provided JSON body cannot be parsed. + * @throws ContentValidationFailedException if the provided JSON body cannot be parsed. */ def validateContent(jsonBody: Option[String]): Unit = { jsonBody match { @@ -57,7 +57,7 @@ object RequestBody { body.parseJson } match { case Failure(e) => - throw ContentValidationFailed(body, s"Received value cannot be parsed to json: ${e.getMessage}") + throw ContentValidationFailedException(body, s"Received value cannot be parsed to json: ${e.getMessage}") case _ => () } case _ => () diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala index fe29106..21eeb88 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/RequestHeaders.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.request -import africa.absa.testing.scapi.UndefinedHeaderType +import africa.absa.testing.scapi.UndefinedHeaderTypeException import africa.absa.testing.scapi.json.Header import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator @@ -52,13 +52,13 @@ object RequestHeaders { * For any other header type, it throws an UndefinedHeaderType exception. * * @param header The Header object to be validated. - * @throws UndefinedHeaderType If an undefined header type is encountered. + * @throws UndefinedHeaderTypeException If an undefined header type is encountered. */ def validateContent(header: Header): Unit = { header.name.toLowerCase match { case CONTENT_TYPE => ContentValidator.validateNonEmptyString(header.value, s"Header.${header.name}") case AUTHORIZATION => ContentValidator.validateNonEmptyString(header.value, s"Header.${header.name}") - case _ => throw UndefinedHeaderType(header.name) + case _ => throw UndefinedHeaderTypeException(header.name) } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 414538b..88e9096 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -16,11 +16,13 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.validation.ContentValidator import spray.json._ + +import scala.util.{Failure, Success, Try} import scala.xml.XML /** @@ -61,7 +63,7 @@ object AssertionResponseAction extends ResponsePerformer { * Validates the content of an assertion response action object depending on its type. * * @param responseAction The response action object to be validated. - * @throws UndefinedResponseActionType If the response action type is not recognized. + * @throws UndefinedResponseActionTypeException If the response action type is not recognized. */ def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { @@ -120,7 +122,7 @@ object AssertionResponseAction extends ResponsePerformer { case text: String => ContentValidator.validateNonEmptyString(text, s"ResponseAssertion.$BODY_CONTAINS_TEXT.text") case None => throw new IllegalArgumentException(s"Missing required 'text' parameter for assertion $BODY_CONTAINS_TEXT logic.") } - case _ => throw UndefinedResponseActionType(responseAction.name) + case _ => throw UndefinedResponseActionTypeException(responseAction.name) } } @@ -129,10 +131,10 @@ object AssertionResponseAction extends ResponsePerformer { * * @param response The response to perform the assertions on. * @param responseAction The assertion response action to perform on the response. - * @return Boolean value indicating whether the assertion passed or failed. + * @return Boolean value indicating whether the assertion passed or failed. TODO - update all similar docs * @throws IllegalArgumentException If the assertion type is not supported. */ - def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { responseAction.name match { // response-time-... @@ -183,7 +185,7 @@ object AssertionResponseAction extends ResponsePerformer { val text = responseAction.params("text") assertBodyContainsText(response, text) - case _ => throw new IllegalArgumentException(s"Unsupported assertion method [group: assert]: ${responseAction.name}") + case _ => Failure(new IllegalArgumentException(s"Unsupported assertion method [group: assert]: ${responseAction.name}")) } } @@ -198,9 +200,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param maxTimeMillis The maximum allowed time in milliseconds as a string. * @return A Boolean indicating whether the response's duration is below the specified maximum time. Returns true if it's below, false otherwise. */ - def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Boolean = { + def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Try[Unit] = { val lMaxTimeMillis: Long = maxTimeMillis.toLong - response.duration <= lMaxTimeMillis + + if (response.duration <= lMaxTimeMillis) { + Success(()) + } else { + Failure(AssertionException(s"Expected maximal length '$lMaxTimeMillis' is smaller then received '${response.duration}' one.")) + } } /** @@ -210,9 +217,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param minTimeMillis The minimum required time in milliseconds as a string. * @return A Boolean indicating whether the response's duration is above the specified minimum time. Returns true if it's above, false otherwise. */ - def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Boolean = { + def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Try[Unit] = { val lMinTimeMillis: Long = minTimeMillis.toLong - response.duration >= lMinTimeMillis + + if (response.duration >= lMinTimeMillis) { + Success(()) + } else { + Failure(AssertionException(s"Expected minimal length '$lMinTimeMillis' is bigger then received '${response.duration}' one.")) + } } /** @@ -222,14 +234,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param expectedCode The expected status code as a string. * @return A Boolean indicating whether the response's status code matches the expected code. Returns true if they match, false otherwise. */ - def assertStatusCodeEquals(response: Response, expectedCode: String): Boolean = { + def assertStatusCodeEquals(response: Response, expectedCode: String): Try[Unit] = { val iExpectedCode: Int = expectedCode.toInt - val isSuccess: Boolean = response.statusCode == iExpectedCode - if (!isSuccess) { - Logger.error(s"Expected $iExpectedCode, but got ${response.statusCode}") + if (response.statusCode == iExpectedCode) { + Success(()) + } else { + Failure(new IllegalArgumentException(s"Expected $iExpectedCode, but got ${response.statusCode}")) } - isSuccess } /** @@ -238,8 +250,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the status code. * @return True if the status code is in the range 200-299, otherwise false. */ - def assertStatusCodeSuccess(response: Response): Boolean = { - response.statusCode >= 200 && response.statusCode <= 299 + def assertStatusCodeSuccess(response: Response): Try[Unit] = { + if (response.statusCode >= 200 && response.statusCode <= 299) { + Success(()) + } else { + Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (200 - 299).")) + } } /** @@ -248,8 +264,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the status code. * @return True if the status code is in the range 400-499, otherwise false. */ - def assertStatusCodeIsClientError(response: Response): Boolean = { - response.statusCode >= 400 && response.statusCode <= 499 + def assertStatusCodeIsClientError(response: Response): Try[Unit] = { + if (response.statusCode >= 400 && response.statusCode <= 499) { + Success(()) + } else { + Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (400 - 499).")) + } } /** @@ -258,8 +278,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the status code. * @return True if the status code is in the range 500-599, otherwise false. */ - def assertStatusCodeIsServerError(response: Response): Boolean = { - response.statusCode >= 500 && response.statusCode <= 599 + def assertStatusCodeIsServerError(response: Response): Try[Unit] = { + if (response.statusCode >= 500 && response.statusCode <= 599) { + Success(()) + } else { + Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (500 - 599).")) + } } /** @@ -269,8 +293,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param headerName The name of the header to check for. * @return True if the header exists in the response, otherwise false. */ - def assertHeaderExists(response: Response, headerName: String): Boolean = { - response.headers.contains(headerName.toLowerCase) + def assertHeaderExists(response: Response, headerName: String): Try[Unit] = { + if (response.headers.contains(headerName.toLowerCase)) { + Success(()) + } else { + Failure(AssertionException(s"Expected header '$headerName' not found.")) + } } /** @@ -281,11 +309,17 @@ object AssertionResponseAction extends ResponsePerformer { * @param expectedValue The expected value of the header. * @return True if the header value matches the expected value, otherwise false. */ - def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Boolean = { - if (assertHeaderExists(response, headerName)) - expectedValue.equals(response.headers(headerName.toLowerCase).head) + def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Try[Unit] = { + if (assertHeaderExists(response, headerName).isSuccess) { + if (expectedValue.equals(response.headers(headerName.toLowerCase).head)) { + Success(()) + } else { + Failure(AssertionException(s"Expected header '$headerName' value '$expectedValue' is not equal to " + + s"received header value '$response.headers(headerName.toLowerCase).head'.")) + } + } else - false + Failure(AssertionException(s"Expected header '$headerName' not found.")) } /** @@ -294,7 +328,7 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the headers. * @return True if the "Content-Type" header value is "application/json", otherwise false. */ - def assertContentTypeIsJson(response: Response): Boolean = { + def assertContentTypeIsJson(response: Response): Try[Unit] = { val isContentTypeJson = assertHeaderValueEquals(response, "content-type", "application/json") val isBodyJson = try { response.body.parseJson @@ -303,7 +337,11 @@ object AssertionResponseAction extends ResponsePerformer { case _: JsonParser.ParsingException => false } - isContentTypeJson && isBodyJson + if (isContentTypeJson.isSuccess && isBodyJson) { + Success(()) + } else { + Failure(AssertionException("Received content is not JSON type.")) + } } /** @@ -312,7 +350,7 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the headers. * @return True if the "Content-Type" header value is "application/xml", otherwise false. */ - def assertContentTypeIsXml(response: Response): Boolean = { + def assertContentTypeIsXml(response: Response): Try[Unit] = { val isContentTypeXml = assertHeaderValueEquals(response, "content-type", "application/xml") val isBodyXml = try { XML.loadString(response.body) @@ -321,7 +359,11 @@ object AssertionResponseAction extends ResponsePerformer { case _: Exception => false } - isContentTypeXml && isBodyXml + if (isContentTypeXml.isSuccess && isBodyXml) { + Success(()) + } else { + Failure(AssertionException("Received content is not XML type.")) + } } /** @@ -330,8 +372,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the headers. * @return True if the "Content-Type" header value is "text/html", otherwise false. */ - def assertContentTypeIsHtml(response: Response): Boolean = { - assertHeaderValueEquals(response, "content-type", "text/html") + def assertContentTypeIsHtml(response: Response): Try[Unit] = { + val res = assertHeaderValueEquals(response, "content-type", "text/html") + + res match { + case Success(_) => Success(()) + case Failure(exception) => + Failure(AssertionException(s"Received content is not HTML type. Details: ${exception.getMessage}")) + } } // cookies-... @@ -343,8 +391,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param cookieName The name of the cookie to check for existence. * @return True if the specified cookie exists in the response, otherwise false. */ - def assertCookieExists(response: Response, cookieName: String): Boolean = { - response.cookies.contains(cookieName) + def assertCookieExists(response: Response, cookieName: String): Try[Unit] = { + if (response.cookies.contains(cookieName)) { + Success(()) + } else { + Failure(AssertionException(s"Cookie '$cookieName' does not exist in the response.")) + } } /** @@ -355,11 +407,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param expectedValue The expected value of the cookie. * @return True if the value of the specified cookie matches the expected value, otherwise false. */ - def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Boolean = { - if (assertCookieExists(response, cookieName)) - response.cookies(cookieName)._1 == expectedValue - else - false + def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Try[Unit] = { + assertCookieExists(response, cookieName).flatMap { _ => + if (response.cookies(cookieName)._1 == expectedValue) { + Success(()) + } else { + Failure(AssertionException(s"Cookie '$cookieName' value does not match expected value '$expectedValue'.")) + } + } } /** @@ -369,11 +424,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param cookieName The name of the cookie to check. * @return True if the specified cookie is secured, otherwise false. */ - def assertCookieIsSecured(response: Response, cookieName: String): Boolean = { - if (assertCookieExists(response, cookieName)) - response.cookies(cookieName)._2 - else - false + def assertCookieIsSecured(response: Response, cookieName: String): Try[Unit] = { + assertCookieExists(response, cookieName).flatMap { _ => + if (response.cookies(cookieName)._2) { + Success(()) + } else { + Failure(AssertionException(s"Cookie '$cookieName' is not secured.")) + } + } } /** @@ -383,11 +441,14 @@ object AssertionResponseAction extends ResponsePerformer { * @param cookieName The name of the cookie to check. * @return True if the specified cookie is not secured, otherwise false. */ - def assertCookieIsNotSecured(response: Response, cookieName: String): Boolean = { - if (assertCookieExists(response, cookieName)) - !response.cookies(cookieName)._2 - else - false + def assertCookieIsNotSecured(response: Response, cookieName: String): Try[Unit] = { + assertCookieExists(response, cookieName).flatMap { _ => + if (!response.cookies(cookieName)._2) { + Success(()) + } else { + Failure(AssertionException(s"Cookie '$cookieName' is secured.")) + } + } } /** @@ -397,10 +458,12 @@ object AssertionResponseAction extends ResponsePerformer { * @param text The expected text present in the response body as a string. * @return A Boolean indicating whether the expected content is present in the response body or not. */ - def assertBodyContainsText(response: Response, text: String): Boolean = { - val isSuccess: Boolean = response.body.contains(text) - if (!isSuccess) - Logger.error(s"Expected body to contain $text") - isSuccess + def assertBodyContainsText(response: Response, text: String): Try[Unit] = { + if (response.body.contains(text)) { + Success(()) + } else { + Logger.error(s"Expected body to contain $text") + Failure(AssertionException(s"Body does not contain expected text '$text'.")) + } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala index 610a104..07d97fe 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala @@ -16,13 +16,15 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator import spray.json._ +import scala.util.{Failure, Success, Try} + /** * ExtractJsonResponseAction is an object that extends ResponsePerformer. * It is designed to extract specific data from a JSON response and perform validations. @@ -35,23 +37,23 @@ object ExtractJsonResponseAction extends ResponsePerformer { * Validates the content of an extract response action object depending on its type. * * @param responseAction The ResponseAction instance to be validated. - * @throws UndefinedResponseActionType if an unsupported assertion type is encountered. + * @throws UndefinedResponseActionTypeException if an unsupported assertion type is encountered. */ def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { case STRING_FROM_LIST => validateStringFromList(responseAction) - case _ => throw UndefinedResponseActionType(responseAction.name) + case _ => throw UndefinedResponseActionTypeException(responseAction.name) } } /** * Performs extract actions on a response depending on the type of assertion method provided. * - * @param response The Response instance to perform response action on. + * @param response The Response instance to perform response action on. * @param responseAction The ResponseAction instance containing the response action details. * @throws IllegalArgumentException if an unsupported response action name is encountered. */ - def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { + def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { responseAction.name match { case STRING_FROM_LIST => val cacheKey = responseAction.params("cacheKey") @@ -79,7 +81,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { * @param runtimeCacheLevel The expiration level to use when storing the extracted string in the runtime cache. * @return Boolean indicating whether the string extraction and caching operation was successful. */ - def stringFromList(response: Response, cacheKey: String, listIndex: Int, jsonKey: String, runtimeCacheLevel: String): Boolean = { + def stringFromList(response: Response, cacheKey: String, listIndex: Int, jsonKey: String, runtimeCacheLevel: String): Try[Unit] = { try { val jsonAst = response.body.parseJson @@ -87,7 +89,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { case JsArray(array) => array case _ => Logger.error("Expected a JSON array") - return false + return Failure(AssertionException("Expected a JSON array in the response.")) } // Extract "jsonKey" from the object at the given index @@ -96,15 +98,15 @@ object ExtractJsonResponseAction extends ResponsePerformer { case Seq(JsNumber(value)) => value.toString() case _ => Logger.error(s"Expected '$jsonKey' field not found in provided json.") - return false + return Failure(AssertionException(s"Expected '$jsonKey' field not found in provided json.")) } RuntimeCache.put(key = cacheKey, value = value, RuntimeCache.determineLevel(runtimeCacheLevel)) - true + Success(()) } catch { case e: spray.json.JsonParser.ParsingException => Logger.error(s"Expected json string in response body. JSON parsing error: ${e.getMessage}") - false + Failure(AssertionException(s"Expected json string in response body. JSON parsing error: ${e.getMessage}")) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index 8472eba..cdb9180 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -16,11 +16,13 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.UndefinedResponseActionTypeException import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.validation.ContentValidator +import scala.util.{Failure, Success, Try} + /** * Singleton object `ResponseLog` that extends the `ResponsePerformer` trait. * It provides utilities for validating and performing logging messages. @@ -36,7 +38,7 @@ object LogResponseAction extends ResponsePerformer { * Validates the content of an log response action object depending on its type. * * @param responseAction The response action to be validated. - * @throws UndefinedResponseActionType if the response action's name is not recognized. + * @throws UndefinedResponseActionTypeException if the response action's name is not recognized. */ def validateContent(responseAction: ResponseAction): Unit = { responseAction.name.toLowerCase match { @@ -45,7 +47,7 @@ object LogResponseAction extends ResponsePerformer { case Some(message) => ContentValidator.validateNonEmptyString(message, s"ResponseLog.${responseAction.name}.message") case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion ${responseAction.name} logic.") } - case _ => throw UndefinedResponseActionType(responseAction.name) + case _ => throw UndefinedResponseActionTypeException(responseAction.name) } } @@ -56,15 +58,15 @@ object LogResponseAction extends ResponsePerformer { * @param responseAction The responseAction to be performed on the response. * @throws IllegalArgumentException if the response action's name is not recognized. */ - def performResponseAction(response: Response, responseAction: ResponseAction): Boolean = { - val message = responseAction.params.getOrElse("message", throw new IllegalArgumentException("Missing 'message' parameter")) + def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { + val message = responseAction.params.getOrElse("message", return Failure(new IllegalArgumentException("Missing 'message' parameter"))) responseAction.name match { case ERROR => logError(message) case WARN => logWarn(message) case INFO => logInfo(message) case DEBUG => logDebug(message) - case _ => throw new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}") + case _ => Failure(new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}")) } } @@ -77,9 +79,9 @@ object LogResponseAction extends ResponsePerformer { * * @param message The message to be logged. */ - def logError(message: String): Boolean = { + def logError(message: String): Try[Unit] = { Logger.error(message) - true + Success(()) } /** @@ -87,9 +89,9 @@ object LogResponseAction extends ResponsePerformer { * * @param message The message to be logged. */ - def logWarn(message: String): Boolean = { + def logWarn(message: String): Try[Unit] = { Logger.warn(message) - true + Success(()) } /** @@ -97,9 +99,9 @@ object LogResponseAction extends ResponsePerformer { * * @param message The message to be logged. */ - def logInfo(message: String): Boolean = { + def logInfo(message: String): Try[Unit] = { Logger.info(message) - true + Success(()) } /** @@ -107,9 +109,9 @@ object LogResponseAction extends ResponsePerformer { * * @param message The message to be logged. */ - def logDebug(message: String): Boolean = { + def logDebug(message: String): Try[Unit] = { Logger.debug(message) - true + Success(()) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 81c2784..df4ca6b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -19,6 +19,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger +import scala.util.{Failure, Success, Try} + case class Response(statusCode: Int, body: String, url: String, statusMessage: String, headers: Map[String, Seq[String]], cookies: Map[String, (String, Boolean)], duration: Long) /** @@ -26,10 +28,6 @@ case class Response(statusCode: Int, body: String, url: String, statusMessage: S */ object Response { - val GROUP_ASSERT: String = "assert" - val GROUP_EXTRACT_JSON: String = "extractJson" - val GROUP_LOG: String = "log" - /** * Validates an ResponseAction based on its group type. * Calls the appropriate group's validateContent method based on group type. @@ -39,9 +37,9 @@ object Response { */ def validate(responseAction: ResponseAction): Unit = { responseAction.group match { - case GROUP_ASSERT => AssertionResponseAction.validateContent(responseAction) - case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.validateContent(responseAction) - case GROUP_LOG => LogResponseAction.validateContent(responseAction) + case ResponseActionGroupType.ASSERT => AssertionResponseAction.validateContent(responseAction) + case ResponseActionGroupType.EXTRACT_JSON => ExtractJsonResponseAction.validateContent(responseAction) + case ResponseActionGroupType.LOG => LogResponseAction.validateContent(responseAction) case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${responseAction.group}") } } @@ -54,10 +52,10 @@ object Response { * * @param response The response on which actions will be performed. * @param responseAction The set of response actions that dictate what actions will be performed on the response. - * @return Boolean indicating whether all response actions passed (true) or any response action failed (false). + * @return Boolean indicating whether all response actions passed (true) or any response action failed (false). TODO * @throws IllegalArgumentException If an response action group is not supported. */ - def perform(response: Response, responseAction: Seq[ResponseAction]): Boolean = { + def perform(response: Response, responseAction: Seq[ResponseAction]): Try[Unit] = { def logParameters(response: Response, resolvedResponseAction: ResponseAction, exception: Option[Throwable] = None): Unit = { val filteredParams = resolvedResponseAction.params.filter(_._1 != "method").map { case (k, v) => s"$k->$v" }.mkString(", ") val baseLog = @@ -73,27 +71,28 @@ object Response { Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - error details:$baseLog$exceptionLog") } - responseAction.forall { assertion => + responseAction.iterator.map { assertion => val resolvedResponseAction: ResponseAction = assertion.resolveByRuntimeCache() Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - Started.") - try { - val res = resolvedResponseAction.group match { - case GROUP_ASSERT => AssertionResponseAction.performResponseAction(response, assertion) - case GROUP_EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) - case GROUP_LOG => LogResponseAction.performResponseAction(response, assertion) - case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}") - } + val res: Try[Unit] = resolvedResponseAction.group match { + case ResponseActionGroupType.ASSERT => AssertionResponseAction.performResponseAction(response, assertion) + case ResponseActionGroupType.EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) + case ResponseActionGroupType.LOG => LogResponseAction.performResponseAction(response, assertion) + case _ => Failure(new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}")) + } - Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - ${if (res) "completed successfully" else "failed"}.") - if (!res) logParameters(response, resolvedResponseAction) - res - } catch { - case e: IllegalArgumentException => + res match { + case Success(_) => + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - completed successfully.") + case Failure(e: IllegalArgumentException) => Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - failed with exception.") logParameters(response, resolvedResponseAction, Some(e)) - throw e + case Failure(e) => + Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - failed with unexpected exception.") + logParameters(response, resolvedResponseAction, Some(e)) } - } + res + }.find(_.isFailure).getOrElse(Success(())) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala new file mode 100644 index 0000000..58a12f0 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala @@ -0,0 +1,33 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response + +object ResponseActionGroupType extends Enumeration { + val ASSERT, EXTRACT_JSON, LOG = Value + type ResponseActionGroupType = Value + + private val stringToValueMap = Map( + "assert" -> ASSERT, + "extractJson" -> EXTRACT_JSON, + "log" -> LOG + ) + + def fromString(s: String): Option[ResponseActionGroupType] = stringToValueMap.get(s) +} + + + diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala index e430305..2cf45bd 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala @@ -18,7 +18,9 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction +import scala.util.Try + trait ResponsePerformer { def validateContent(responseAction: ResponseAction): Unit - def performResponseAction(response: Response, responseAction: ResponseAction): Boolean + def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index 852b575..eac3010 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -16,14 +16,17 @@ package africa.absa.testing.scapi.suite.runner +import africa.absa.testing.scapi.SuiteBeforeFailedException import africa.absa.testing.scapi.json.{Environment, Requestable} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.{Method, SuiteBundle, SuiteResults, SuiteTestScenario} +import africa.absa.testing.scapi.model.{Method, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.cache.{RuntimeCache, SuiteLevel, TestLevel} +import scala.util.{Failure, Try} + /** * Main object handling the running of test suites. */ @@ -37,36 +40,39 @@ object SuiteRunner { * @param environment The current environment. * @return Set of SuiteResults. */ - def runSuites(suiteBundles: Set[SuiteBundle], environment: Environment, restClientCreator: RestClientCreator): List[SuiteResults] = { - suiteBundles.foldLeft(List[SuiteResults]()) { (resultList, suiteBundle) => + def runSuites(suiteBundles: Set[SuiteBundle], environment: Environment, restClientCreator: RestClientCreator): List[SuiteResult] = { + suiteBundles.foldLeft(List[SuiteResult]()) { (resultList, suiteBundle) => Logger.debug(s"Suite: ${suiteBundle.suite.endpoint} - Started") - val resultSuiteBefore: List[SuiteResults] = suiteBundle.suiteBefore.toList.flatMap { suiteBefore => + val suiteBeforeResult: List[SuiteResult] = suiteBundle.suiteBefore.toList.flatMap { suiteBefore => suiteBefore.methods.map { method => runSuiteBefore(suiteBundle.suite.endpoint, suiteBefore.name, method, environment, restClientCreator) } } - var resultSuite: List[SuiteResults] = List.empty - var resultSuiteAfter: List[SuiteResults] = List.empty - if (!resultSuiteBefore.forall(_.isSuccess)) { - Logger.error(s"Suite-Before for Suite: ${suiteBundle.suite.endpoint} has failed methods. Not executing main tests and Suite-After.") - resultSuite = resultSuite :+ SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_TEST, + var suiteResult: List[SuiteResult] = List.empty + var suiteAfterResult: List[SuiteResult] = List.empty + if (!suiteBeforeResult.forall(_.isSuccess)) { + val errorMsg = s"Suite-Before for Suite: ${suiteBundle.suite.endpoint} has failed methods. Not executing main tests and Suite-After." + Logger.error(errorMsg) + + // add failed Test suite result instance and it will not be started + suiteResult = suiteResult :+ SuiteResult( + resultType = SuiteResultType.TEST_SUITE, suiteName = suiteBundle.suite.endpoint, name = "SKIPPED", - status = false, + result = Failure(SuiteBeforeFailedException(errorMsg)), duration = Some(0L), categories = Some("SKIPPED")) } else { - resultSuite = suiteBundle.suite.tests.toList.map(test => + suiteResult = suiteBundle.suite.tests.toList.map(test => this.runSuiteTest(suiteBundle.suite.endpoint, test, environment, restClientCreator)) - resultSuiteAfter = suiteBundle.suiteAfter.toList.flatMap { suiteAfter => + suiteAfterResult = suiteBundle.suiteAfter.toList.flatMap { suiteAfter => suiteAfter.methods.map { method => runSuiteAfter(suiteBundle.suite.endpoint, suiteAfter.name, method, environment, restClientCreator) } } } RuntimeCache.expire(SuiteLevel) - resultList ++ resultSuiteBefore ++ resultSuite ++ resultSuiteAfter + resultList ++ suiteBeforeResult ++ suiteResult ++ suiteAfterResult } } @@ -79,24 +85,24 @@ object SuiteRunner { * @param environment The current environment. * @return SuiteResults after the execution of the suite-before method. */ - private def runSuiteBefore(suiteEndpoint: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { + private def runSuiteBefore(suiteEndpoint: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-Before: ${suiteBeforeName} - Started") val testStartTime: Long = System.currentTimeMillis() try { val response: Response = sendRequest(method, environment, restClientCreator) - val isSuccess: Boolean = Response.perform( + val result: Try[Unit] = Response.perform( response = response, responseAction = method.responseActions ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"Suite-Before: method '${method.name}' - ${if (isSuccess) "completed successfully" else "failed"}.") - SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_BEFORE_METHOD, + Logger.debug(s"Suite-Before: method '${method.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") + SuiteResult( + resultType = SuiteResultType.BEFORE_SUITE, suiteName = suiteEndpoint, name = method.name, - status = isSuccess, + result = result, duration = Some(testEndTime - testStartTime) ) } catch { @@ -112,24 +118,24 @@ object SuiteRunner { * @param environment The current environment. * @return SuiteResults after the execution of the suite-test. */ - private def runSuiteTest(suiteEndpoint: String, test: SuiteTestScenario, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { + private def runSuiteTest(suiteEndpoint: String, test: SuiteTestScenario, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-Test: ${test.name} - Started") val testStartTime: Long = System.currentTimeMillis() try { val response: Response = sendRequest(test, environment, restClientCreator) - val isSuccess: Boolean = Response.perform( + val result: Try[Unit] = Response.perform( response = response, responseAction = test.responseActions ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"Suite-Test: '${test.name}' - ${if (isSuccess) "completed successfully" else "failed"}.") - SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_TEST, + Logger.debug(s"Suite-Test: '${test.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") + SuiteResult( + resultType = SuiteResultType.TEST_SUITE, suiteName = suiteEndpoint, name = test.name, - status = isSuccess, + result = result, duration = Some(testEndTime - testStartTime), categories = Some(test.categories.mkString(",")) ) @@ -150,24 +156,24 @@ object SuiteRunner { * @param environment The current environment. * @return SuiteResults after the execution of the suite-after method. */ - private def runSuiteAfter(suiteEndpoint: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResults = { + private def runSuiteAfter(suiteEndpoint: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-After: ${suiteAfterName} - Started") val testStartTime: Long = System.currentTimeMillis() try { val response: Response = sendRequest(method, environment, restClientCreator) - val isSuccess: Boolean = Response.perform( + val result: Try[Unit] = Response.perform( response = response, responseAction = method.responseActions ) val testEndTime: Long = System.currentTimeMillis() - Logger.debug(s"After method '${method.name}' ${if (isSuccess) "completed successfully" else "failed"}.") - SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_AFTER_METHOD, + Logger.debug(s"After method '${method.name}' ${if (result.isSuccess) "completed successfully" else "failed"}.") + SuiteResult( + resultType = SuiteResultType.AFTER_SUITE, suiteName = suiteEndpoint, name = method.name, - status = isSuccess, + result = result, duration = Some(testEndTime - testStartTime) ) } catch { @@ -203,37 +209,34 @@ object SuiteRunner { * @param resultType The type of the suite or test ("Before", "Test", or "After"). * @return SuiteResults after the exception handling. */ - private def handleException(e: Throwable, suiteEndpoint: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResults = { + private def handleException(e: Throwable, suiteEndpoint: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResult = { val testEndTime = System.currentTimeMillis() val message = e match { case _ => s"Request exception occurred while running suite: ${suiteEndpoint}, ${resultType}: ${name}. Exception: ${e.getMessage}" } Logger.error(message) resultType match { - case "Before" => SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_BEFORE_METHOD, + case "Before" => SuiteResult( + resultType = SuiteResultType.BEFORE_SUITE, suiteName = suiteEndpoint, name = name, - status = false, - errMessage = Some(e.getMessage), + result = Failure(e), duration = Some(testEndTime - testStartTime)) - case "Test" => SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_TEST, + case "Test" => SuiteResult( + resultType = SuiteResultType.TEST_SUITE, suiteName = suiteEndpoint, name = name, - status = false, - errMessage = Some(e.getMessage), + result = Failure(e), duration = Some(testEndTime - testStartTime), categories = categories ) - case "After" => SuiteResults.withBooleanStatus( - resultType = SuiteResults.RESULT_TYPE_AFTER_METHOD, + case "After" => SuiteResult( + resultType = SuiteResultType.AFTER_SUITE, suiteName = suiteEndpoint, name = name, - status = false, - errMessage = Some(e.getMessage), + result = Failure(e), duration = Some(testEndTime - testStartTime)) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala index 97f8581..b5727b4 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.utils.validation -import africa.absa.testing.scapi.ContentValidationFailed +import africa.absa.testing.scapi.ContentValidationFailedException import scala.util.{Failure, Success, Try} /** @@ -28,12 +28,12 @@ object ContentValidator { * Validates that a string can be parsed to an integer. Throws an exception if the string cannot be parsed. * * @param input The string to be validated. - * @throws ContentValidationFailed if the input string cannot be parsed to an integer. + * @throws ContentValidationFailedException if the input string cannot be parsed to an integer. */ def validateIntegerString(input: String, param: String): Unit = { Try(input.toInt) match { case Success(_) => // Do nothing - case Failure(e) => throw ContentValidationFailed(input, s"Received value of '$param' cannot be parsed to an integer: ${e.getMessage}") + case Failure(e) => throw ContentValidationFailedException(input, s"Received value of '$param' cannot be parsed to an integer: ${e.getMessage}") } } @@ -41,12 +41,12 @@ object ContentValidator { * Validates that a string can be parsed to a long. Throws an exception if the string cannot be parsed. * * @param input The string to be validated. - * @throws ContentValidationFailed if the input string cannot be parsed to a long. + * @throws ContentValidationFailedException if the input string cannot be parsed to a long. */ def validateLongString(input: String, param: String): Unit = { Try(input.toLong) match { case Success(_) => // Do nothing - case Failure(e) => throw ContentValidationFailed(input, s"Received value of '$param' cannot be parsed to a long: ${e.getMessage}") + case Failure(e) => throw ContentValidationFailedException(input, s"Received value of '$param' cannot be parsed to a long: ${e.getMessage}") } } @@ -54,11 +54,11 @@ object ContentValidator { * Validates that a string is not empty. Throws an exception if the string is empty. * * @param input The string to be validated. - * @throws ContentValidationFailed if the input string is empty. + * @throws ContentValidationFailedException if the input string is empty. */ def validateNonEmptyString(input: String, param: String): Unit = { if (input.isEmpty) { - throw ContentValidationFailed(input, s"Received string value of '$param' is empty.") + throw ContentValidationFailedException(input, s"Received string value of '$param' is empty.") } } @@ -67,12 +67,12 @@ object ContentValidator { * * @param input The Option[String] to be validated. * @param paramName The name of the parameter, used in error messaging. - * @throws ContentValidationFailed if the input Option[String] is None. + * @throws ContentValidationFailedException if the input Option[String] is None. */ def validateNotNone(input: Option[String], paramName: String): Unit = { input match { case Some(_) => // do nothing, input is valid - case None => throw new ContentValidationFailed(paramName, "Input cannot be None") + case None => throw new ContentValidationFailedException(paramName, "Input cannot be None") } } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/ScAPIRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/ScAPIRunnerTest.scala index fc3f432..07f02d7 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/ScAPIRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/ScAPIRunnerTest.scala @@ -64,7 +64,7 @@ class ScAPIRunnerTest extends FunSuite { "--env", "localhost.env.json", "--test-root-path", "/random/path/without/suite") - interceptMessage[SuiteLoadFailed]("Problems during project loading. Details: 'suites' directory have to exist in project root.") { + interceptMessage[SuiteLoadFailedException]("Problems during project loading. Details: 'suites' directory have to exist in project root.") { ScAPIRunner.main(args) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala index dc65c6a..64927c4 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala @@ -17,7 +17,7 @@ package africa.absa.testing.scapi.json import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSchema} -import africa.absa.testing.scapi.{JsonInvalidSchema, UndefinedConstantsInProperties} +import africa.absa.testing.scapi.{JsonInvalidSchemaException, UndefinedConstantsInPropertiesException} import munit.FunSuite import java.net.URL @@ -61,7 +61,7 @@ class EnvironmentFactoryTest extends FunSuite { } test("fromFile - missing referenced constant") { - intercept[UndefinedConstantsInProperties] { + intercept[UndefinedConstantsInPropertiesException] { val envPath: String = getClass.getResource("/missing_constant_env.json").getPath EnvironmentFactory.fromFile(envPath) } @@ -79,7 +79,7 @@ class EnvironmentFactoryTest extends FunSuite { def validateEnvJson(name: String, resourcePath: String): Unit = { test(name) { - intercept[JsonInvalidSchema] { + intercept[JsonInvalidSchemaException] { val envSchemaPath: URL = ScAPIJsonSchema.ENVIRONMENT val envPath: String = getClass.getResource(resourcePath).getPath diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala index 4cf3b3c..ee73b71 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.PropertyNotFound +import africa.absa.testing.scapi.PropertyNotFoundException import munit.FunSuite class EnvironmentTest extends FunSuite { @@ -58,7 +58,7 @@ class EnvironmentTest extends FunSuite { test("apply - properties does not exist") { val env: Environment = Environment(constants, propertiesResolved) - interceptMessage[PropertyNotFound]("Property not found: 'no_exist'.") { + interceptMessage[PropertyNotFoundException]("Property not found: 'no_exist'.") { env("no_exist") } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala index 1cfc274..41a9d88 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.ContentValidationFailed +import africa.absa.testing.scapi.ContentValidationFailedException import africa.absa.testing.scapi.rest.request.RequestBody import munit.FunSuite import spray.json.JsonParser.ParsingException @@ -79,7 +79,7 @@ class RequestBodyTest extends FunSuite { test("validateContent - fail when body is a non json string") { val jsonBody = Some("""not json string""") - intercept[ContentValidationFailed] { + intercept[ContentValidationFailedException] { RequestBody.validateContent(jsonBody) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala index e3db63a..e9ad9a9 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala @@ -17,7 +17,7 @@ package africa.absa.testing.scapi.json import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedHeaderType} +import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedHeaderTypeException} import munit.FunSuite class RequestHeadersTest extends FunSuite { @@ -62,7 +62,7 @@ class RequestHeadersTest extends FunSuite { test("validateContent - CONTENT_TYPE header - empty") { val header = Header(RequestHeaders.CONTENT_TYPE, "") - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'Header.content-type' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'Header.content-type' is empty.") { RequestHeaders.validateContent(header) } } @@ -74,14 +74,14 @@ class RequestHeadersTest extends FunSuite { test("validateContent - AUTHORIZATION header - empty") { val header = Header(RequestHeaders.AUTHORIZATION, "") - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'Header.authorization' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'Header.authorization' is empty.") { RequestHeaders.validateContent(header) } } test("validateContent - Unsupported header type") { val header = Header("unsupported-header", "value") - intercept[UndefinedHeaderType] { + intercept[UndefinedHeaderTypeException] { RequestHeaders.validateContent(header) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala index e4f62df..41967b7 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.ContentValidationFailed +import africa.absa.testing.scapi.ContentValidationFailedException import africa.absa.testing.scapi.rest.request.RequestParams import munit.FunSuite @@ -61,7 +61,7 @@ class RequestParamsTest extends FunSuite { test("validateContent - should throw exception for empty name") { val params = Set(Param("", "value")) - intercept[ContentValidationFailed] { + intercept[ContentValidationFailedException] { RequestParams.validateContent(Some(params)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index 64ce4f7..f064982 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.{ProjectLoadFailed, UndefinedConstantsInProperties} +import africa.absa.testing.scapi.{ProjectLoadFailedException, UndefinedConstantsInPropertiesException} import africa.absa.testing.scapi.model.{Suite, SuiteBundle, SuiteTestScenario} import munit.FunSuite import org.apache.logging.log4j.LogManager @@ -66,11 +66,11 @@ class SuiteFactoryTest extends FunSuite { initTestLogger() try { - val caught = intercept[ProjectLoadFailed] { + val caught = intercept[ProjectLoadFailedException] { SuiteFactory.fromFiles(environment, testRootPath, "(.*)", "json") } - assert(caught.isInstanceOf[ProjectLoadFailed]) + assert(caught.isInstanceOf[ProjectLoadFailedException]) assert(out.toString.contains("Undefined constant(s): 'constants.no_provided' in ''Header' action.")) assert(out.toString.contains("Not all suites loaded. Failed suites:")) } finally { @@ -119,7 +119,7 @@ class SuiteFactoryTest extends FunSuite { val suiteName = "getUserCurrent" val properties: Map[String, String] = Map.empty - intercept[UndefinedConstantsInProperties] { + intercept[UndefinedConstantsInPropertiesException] { SuiteFactory.loadJsonSuiteConstants(suiteFilePath, suiteName, properties).constants } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index e1b4018..194200c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -16,53 +16,54 @@ package africa.absa.testing.scapi.reporter -import africa.absa.testing.scapi.model.SuiteResults +import africa.absa.testing.scapi.AssertionException +import africa.absa.testing.scapi.model.{SuiteResult, SuiteResultType} import munit.FunSuite import java.io.ByteArrayOutputStream +import scala.util.{Failure, Success} class StdOutReporterTest extends FunSuite { - val successTestResults: List[SuiteResults] = List( - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + val successTestResults: List[SuiteResult] = List( + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 1", name = "Test 1", - status = true, + result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 1", name = "Test 2", - status = true, + result = Success(()), duration = Some(200L), categories = Some("Category 2") ), - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 2", name = "Test 1", - status = true, + result = Success(()), duration = Some(50L), categories = Some("Category 3")) ) - val mixedSuccessTestResults: List[SuiteResults] = List( - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + val mixedSuccessTestResults: List[SuiteResult] = List( + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 1", name = "Test 1", - status = true, + result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 1", name = "Test 2", - status = false, + result = Failure(AssertionException("Error message")), duration = Some(200L), - categories = Some("Category 2"), - errMessage = Some("Error message")), - SuiteResults.withBooleanStatus(SuiteResults.RESULT_TYPE_TEST, + categories = Some("Category 2")), + SuiteResult(SuiteResultType.TEST_SUITE, suiteName = "Suite 2", name = "Test 1", - status = true, + result = Success(()), duration = Some(50L), categories = Some("Category 3")) ) @@ -88,7 +89,7 @@ class StdOutReporterTest extends FunSuite { assertEquals(clue(output.contains("End Report")), true) } - test("full results with failed") { + test("full results with failed".only) { /* "Full": min 1 Success test @@ -96,7 +97,6 @@ class StdOutReporterTest extends FunSuite { min 2 Suites min 1 suites with min 2 tests */ - var failedTestResults = successTestResults val baos = new ByteArrayOutputStream() @@ -126,7 +126,7 @@ class StdOutReporterTest extends FunSuite { assertEquals(clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|")), true) // error from detail - assertEquals(clue(output.contains("Error: Error message")), true) + assertEquals(clue(output.contains("Assertion failed: Error message")), true) } test("results all success") { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 25d36ba..2cefb62 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -17,7 +17,7 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction -import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedResponseActionType} +import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import munit.FunSuite class ResponseAssertionsTest extends FunSuite { @@ -29,31 +29,31 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("validateContent - response time is below - limit is integer string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is below - limit is not integer string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "not_integer")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-below.limit' cannot be parsed to a long: For input string: \"not_integer\"") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "not_integer")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-below.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - limit is integer string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is above - limit is not integer string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "not_integer")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-above.limit' cannot be parsed to a long: For input string: \"not_integer\"") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "not_integer")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-above.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - missing limit parameter") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'limit' parameter for assertion response-time-is-above logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -62,18 +62,18 @@ class ResponseAssertionsTest extends FunSuite { // status-code-... test("validateContent - valid status code string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - invalid status code string") { - intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "not an integer"))) + intercept[ContentValidationFailedException] { + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "not an integer"))) } } test("validateContent - status code equals - missing code parameter") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'code' parameter for assertion status-code-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -82,52 +82,52 @@ class ResponseAssertionsTest extends FunSuite { // header-... test("validateContent - header exists - valid header name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "content-type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "content-type")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header exists - invalid header name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-exists.headerName' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-exists.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header exists - missing header name parameter") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - valid header name and value strings") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header value equals - invalid header name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "", "expectedValue" -> "application/json")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.headerName' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "", "expectedValue" -> "application/json")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - invalid expected value string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.expectedValue' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("expectedValue" -> "application/json")) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header value string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -136,52 +136,52 @@ class ResponseAssertionsTest extends FunSuite { // cookies-... test("validateContent - cookie exists - valid cookie name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie exists - invalid cookie name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-exists.cookieName' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-exists.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie exists - missing cookie name parameter") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map()) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map()) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - valid cookie name and value strings") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie value equals - invalid cookie name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "", "expectedValue" -> "cookieValue")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.cookieName' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "", "expectedValue" -> "cookieValue")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - invalid cookie value string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.expectedValue' is empty.") { + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie name string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("expectedValue" -> "cookieValue")) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie value string") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -190,25 +190,25 @@ class ResponseAssertionsTest extends FunSuite { // body-... test("validateContent - body contains text - body is not empty") { - val responseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "test content")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "test content")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - body contains text - body is empty") { - intercept[ContentValidationFailed] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> ""))) + intercept[ContentValidationFailedException] { + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> ""))) } } test("validateContent - body contains text - body parameter is missing") { interceptMessage[IllegalArgumentException]("Missing required 'text' parameter for assertion body-contains-text logic.") { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map.empty)) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map.empty)) } } test("validateContent - unsupported response action") { - intercept[UndefinedResponseActionType] { - AssertionResponseAction.validateContent(ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported", Map("body" -> "value"))) + intercept[UndefinedResponseActionTypeException] { + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = "unsupported", Map("body" -> "value"))) } } @@ -219,271 +219,269 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("performAssertions - response time is below limit - success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) - assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is below limit - failed") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_BELOW}", Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) - assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - response time is above limit - success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) - assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is above limit - failed") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.RESPONSE_TIME_IS_ABOVE}", Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) - assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } // status-code-... test("performAssertions - status code assertion - equals") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - status code assertion - not equals") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) val response = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - status code - is success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SUCCESS, Map.empty) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response299 = Response(299, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) - assert(AssertionResponseAction.performResponseAction(response299, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction).isSuccess) + assert(AssertionResponseAction.performResponseAction(response299, statusCodeResponseAction).isSuccess) } test("performAssertions - status code - is not success") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SUCCESS}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SUCCESS, Map.empty) val response199 = Response(199, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response300 = Response(300, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response199, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response300, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response199, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response300, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction).isFailure) } test("performAssertions - status code - is client error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) val response400 = Response(400, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response400, statusCodeResponseAction)) - assert(AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response400, statusCodeResponseAction).isSuccess) + assert(AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction).isSuccess) } test("performAssertions - status code - is not client error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) val response399 = Response(399, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response399, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response399, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction).isFailure) } test("performAssertions - status code - is server error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR, Map.empty) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response599 = Response(599, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction)) - assert(AssertionResponseAction.performResponseAction(response599, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response500, statusCodeResponseAction).isSuccess) + assert(AssertionResponseAction.performResponseAction(response599, statusCodeResponseAction).isSuccess) } test("performAssertions - status code - is not server error") { - val statusCodeResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR}", Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR, Map.empty) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response600 = Response(600, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response600, statusCodeResponseAction)) - assert(!AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction)) + assert(AssertionResponseAction.performResponseAction(response499, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response600, statusCodeResponseAction).isFailure) + assert(AssertionResponseAction.performResponseAction(response200, statusCodeResponseAction).isFailure) } // header-... test("performAssertions - header exists") { - val headerExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "Content-Type")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "Content-Type")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isSuccess) } test("performAssertions - header does not exists") { - val headerExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_EXISTS}", Map("headerName" -> "headerValue")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "headerValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, headerExistsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isFailure) } test("performAssertions - header value is equals") { - val headerValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isSuccess) } test("performAssertions - header value is not equals") { - val headerValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.HEADER_VALUE_EQUALS}", Map("headerName" -> "someName", "expectedValue" -> "someValue")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "someName", "expectedValue" -> "someValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isFailure) } // content-type-... test("performAssertions - content type is json") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_JSON}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_JSON, Map.empty) val response = Response(200, "{}", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not json") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_JSON}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_JSON, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is xml") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_XML}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_XML, Map.empty) val response = Response(200, """QADevDon't forget to test it!""", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not xml") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_XML}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_XML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is html") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_HTML}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_HTML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("text/html")), Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not html") { - val contentTypeIsJsonResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.CONTENT_TYPE_IS_HTML}", Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_HTML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } // cookies-... test("performAssertions - cookie exists") { - val cookieExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "testCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) - assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isSuccess) } test("performAssertions - cookie does not exists") { - val cookieExistsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_EXISTS}", Map("cookieName" -> "anotherCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "anotherCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) - assert(!AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isFailure) } test("performAssertions - cookie value is equals") { - val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("cookieValue", false)), 100) - assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isSuccess) } test("performAssertions - cookie value is not equals") { - val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("anotherValue", false)), 100) - assert(!AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie value equals - cookie does not exist") { - val cookieValueEqualsResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_VALUE_EQUALS}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie is secured") { - val cookieIsSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_SECURED}", Map("cookieName" -> "securedCookie")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_SECURED, Map("cookieName" -> "securedCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> ("someValue", true)), 100) - assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isSuccess) } test("performAssertions - cookie is secured - cookie does not exist") { - val cookieIsSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_SECURED}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isFailure) } test("performAssertions - cookie is not secured") { - val cookieIsNotSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_NOT_SECURED}", Map("cookieName" -> "notSecuredCookie")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "notSecuredCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> ("someValue", false)), 100) - assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isSuccess) } test("performAssertions - cookie is not secured - cookie does not exist") { - val cookieIsNotSecuredResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.COOKIE_IS_NOT_SECURED}", Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isFailure) } // body-... test("performAssertions - body contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "dummy")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "dummy")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) - assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isSuccess) } test("performAssertions - body does not contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.BODY_CONTAINS_TEXT}", Map("text" -> "dummies")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "dummies")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) - assert(!AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction)) + assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isFailure) } // unsupported test("performAssertions - unsupported assertion") { - val unsupportedResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.unsupported-assertion", Map("nonsense" -> "value")) + val unsupportedResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = "unsupported-assertion", Map("nonsense" -> "value")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) - interceptMessage[IllegalArgumentException]("Unsupported assertion method [group: assert]: unsupported-assertion") { - AssertionResponseAction.performResponseAction(response, unsupportedResponseAction) - } + assert(AssertionResponseAction.performResponseAction(response, unsupportedResponseAction).isFailure) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index c768f33..ab9d01f 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -16,15 +16,17 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.{ContentValidationFailed, UndefinedResponseActionType} +import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite +import scala.util.Try + class ResponseExtractTest extends FunSuite { - val assertionStringFromList: ResponseAction = ResponseAction(method = s"${Response.GROUP_EXTRACT_JSON}.${ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) - val assertionUnsupported: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) + val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) + val assertionUnsupported: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = "Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) val responseWithID: Response = Response( 200, @@ -63,7 +65,7 @@ class ResponseExtractTest extends FunSuite { } test("validateContent - unsupported option") { - intercept[UndefinedResponseActionType] { + intercept[UndefinedResponseActionTypeException] { ExtractJsonResponseAction.validateContent(assertionUnsupported) } } @@ -73,8 +75,8 @@ class ResponseExtractTest extends FunSuite { */ test("performAssertion - STRING_FROM_LIST") { - val result: Boolean = ExtractJsonResponseAction.performResponseAction(responseWithID, assertionStringFromList) - assert(result) + val result: Try[Unit] = ExtractJsonResponseAction.performResponseAction(responseWithID, assertionStringFromList) + assert(result.isSuccess) assertEquals("382be85a-1f00-4c15-b607-cbda03ccxxx2", RuntimeCache.get("question_id").get) } @@ -106,7 +108,7 @@ class ResponseExtractTest extends FunSuite { val jsonKey = "ids" val runtimeCacheLevel = "Test" val result = ExtractJsonResponseAction.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result) + assert(!result.isSuccess) } test("stringFromList - incorrect parameters - no json body in response") { @@ -116,7 +118,7 @@ class ResponseExtractTest extends FunSuite { val runtimeCacheLevel = "Test" val result = ExtractJsonResponseAction.stringFromList(responseNoJsonBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result) + assert(!result.isSuccess) } test("stringFromList - incorrect parameters - no json arrays in response body") { @@ -126,7 +128,7 @@ class ResponseExtractTest extends FunSuite { val runtimeCacheLevel = "Test" val result = ExtractJsonResponseAction.stringFromList(responseJsonNoArrayBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result) + assert(!result.isSuccess) } /* @@ -136,10 +138,10 @@ class ResponseExtractTest extends FunSuite { // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" test("validateStringFromList - None parameters") { - val assertion1None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) - val assertion2None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "")) - val assertion3None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "")) - val assertion4None: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map.empty) + val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) + val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "")) + val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "")) + val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion4None) @@ -156,28 +158,28 @@ class ResponseExtractTest extends FunSuite { } test("validateStringFromList - empty parameters") { - val assertionParam1: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam2: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam3: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam4: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) + val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam1) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.listIndex' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.listIndex' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam2) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.jsonKey' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.jsonKey' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam3) } - interceptMessage[ContentValidationFailed]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheLevel' is empty.") { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheLevel' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam4) } } test("validateStringFromList - not integer in string") { - val assertion: ResponseAction = ResponseAction(method = s"{Response.GROUP_EXTRACT_JSON}.&{ExtractJsonResponseAction.STRING_FROM_LIST}", Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) - interceptMessage[ContentValidationFailed]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { + val assertion: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { ExtractJsonResponseAction.validateStringFromList(assertion) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index b6fcecd..c75db51 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionType +import africa.absa.testing.scapi.UndefinedResponseActionTypeException import africa.absa.testing.scapi.json.ResponseAction import munit.FunSuite @@ -26,38 +26,38 @@ class ResponseLogTest extends FunSuite { validateContent */ test("validateContent - ERROR supported") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.ERROR}", Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.ERROR, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - WARN supported") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.WARN}", Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.WARN, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - INFO supported") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - DEBUG supported") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.DEBUG}", Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.DEBUG, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - not supported validation type") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.wrong", Map("message" -> "Some string")) - intercept[UndefinedResponseActionType] { + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = "wrong", Map("message" -> "Some string")) + intercept[UndefinedResponseActionTypeException] { LogResponseAction.validateContent(responseAction) } } test("validateContent - no message provided") { - val responseAction = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'message' for assertion info logic.") { LogResponseAction.validateContent(responseAction) } @@ -68,35 +68,34 @@ class ResponseLogTest extends FunSuite { */ test("performAssertion - ERROR supported") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.ERROR}", Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.ERROR, Map("message" -> "info message")) val response = Response(500, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - WARN supported") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.WARN}", Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.WARN, Map("message" -> "info message")) val response = Response(401, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - INFO supported") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.INFO}", Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - DEBUG supported") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.${LogResponseAction.DEBUG}", Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.DEBUG, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion), true) + assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - not supported validation type") { - val assertion = ResponseAction(method = s"${Response.GROUP_LOG}.not_info", Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = "not_info", Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - intercept[IllegalArgumentException] { - LogResponseAction.performResponseAction(response, assertion) - } + + assert(LogResponseAction.performResponseAction(response, assertion).isFailure) } /* @@ -104,7 +103,7 @@ class ResponseLogTest extends FunSuite { */ test("logError") { - assertEquals(LogResponseAction.logError("log error message"), true) + assertEquals(LogResponseAction.logError("log error message").isSuccess, true) } /* @@ -112,7 +111,7 @@ class ResponseLogTest extends FunSuite { */ test("logInfo") { - assertEquals(LogResponseAction.logWarn("log warn message"), true) + assertEquals(LogResponseAction.logWarn("log warn message").isSuccess, true) } /* @@ -120,7 +119,7 @@ class ResponseLogTest extends FunSuite { */ test("logInfo") { - assertEquals(LogResponseAction.logInfo("log info message"), true) + assertEquals(LogResponseAction.logInfo("log info message").isSuccess, true) } /* @@ -128,7 +127,7 @@ class ResponseLogTest extends FunSuite { */ test("logDebug") { - assertEquals(LogResponseAction.logDebug("log debug message"), true) + assertEquals(LogResponseAction.logDebug("log debug message").isSuccess, true) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala deleted file mode 100644 index 1dd68dc..0000000 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseTest.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.rest.response - -import africa.absa.testing.scapi.json.ResponseAction -import munit.FunSuite - -class ResponseTest extends FunSuite { - - /* - validate - */ - - test("validate - unsupported group") { - val unsupportedAssertion = ResponseAction(method = "unsupportedGroup.not needed", Map("param 1" -> "")) - - intercept[IllegalArgumentException] { - Response.validate(unsupportedAssertion) - } - } - - /* - perform - */ - - test("perform - unsupported group") { - val unsupportedAssertion = ResponseAction(method = "unsupportedGroup.not needed", Map("param 1" -> "")) - val response = Response(200, "OK", "", "", Map.empty, Map.empty, 100) - - intercept[IllegalArgumentException] { - Response.perform(response, Seq(unsupportedAssertion)) - } - } - -} diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 4f6847c..7253f65 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -21,7 +21,7 @@ import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.rest.response.{AssertionResponseAction, Response} +import africa.absa.testing.scapi.rest.response.{AssertionResponseAction, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite import org.apache.logging.log4j.Level @@ -31,7 +31,7 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val responseAction: ResponseAction = ResponseAction(method = s"${Response.GROUP_ASSERT}.${AssertionResponseAction.STATUS_CODE_EQUALS}", Map("code" -> "200")) + val responseAction: ResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) val method: Method = Method(name = "test", headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction)) val methodNotSupported: Method = Method(name = "test", headers = Seq(header), actions = Seq(actionNotSupported), responseActions = Seq(responseAction)) @@ -101,55 +101,55 @@ class SuiteRunnerTest extends FunSuite { */ test("runSuite - SuiteBefore exists") { - val suiteResults: List[SuiteResults] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) - val beforeSuiteResult: SuiteResults = suiteResults.find(result => - result.resultType == SuiteResults.RESULT_TYPE_BEFORE_METHOD && result.suiteName == "endpoint2").get + val beforeSuiteResult: SuiteResult = suiteResults.find(result => + result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2").get assertEquals(5, suiteResults.size) assertEquals("test", beforeSuiteResult.name) - assertEquals("Success", beforeSuiteResult.status) + assertEquals(true, beforeSuiteResult.isSuccess) } test("runSuite - SuiteBefore empty") { - val suiteResults: List[SuiteResults] = SuiteRunner.runSuites(suitesBundleNoBefore, environment, () => new RestClient(FakeScAPIRequestSender)) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoBefore, environment, () => new RestClient(FakeScAPIRequestSender)) - val beforeSuiteResult: Option[SuiteResults] = suiteResults.find(result => - result.resultType == SuiteResults.RESULT_TYPE_BEFORE_METHOD && result.suiteName == "endpoint2") + val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => + result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2") assertEquals(2, suiteResults.size) assert(beforeSuiteResult.isEmpty) } test("runSuite - SuiteAfter exists") { - val suiteResults: List[SuiteResults] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) - val afterSuiteResult: SuiteResults = suiteResults.find(result => - result.resultType == SuiteResults.RESULT_TYPE_AFTER_METHOD && result.suiteName == "endpoint2").get + val afterSuiteResult: SuiteResult = suiteResults.find(result => + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get assertEquals(5, suiteResults.size) assertEquals("test", afterSuiteResult.name) - assertEquals("Success", afterSuiteResult.status) + assertEquals(true, afterSuiteResult.isSuccess) } test("runSuite - SuiteAfter empty") { - val suiteResults: List[SuiteResults] = SuiteRunner.runSuites(suitesBundleNoAfter, environment, () => new RestClient(FakeScAPIRequestSender)) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoAfter, environment, () => new RestClient(FakeScAPIRequestSender)) - val afterSuiteResult: Option[SuiteResults] = suiteResults.find(result => - result.resultType == SuiteResults.RESULT_TYPE_AFTER_METHOD && result.suiteName == "endpoint2") + val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2") assertEquals(2, suiteResults.size) assert(afterSuiteResult.isEmpty) } test("runSuite - SuiteAfter empty methods") { - val suiteResults: List[SuiteResults] = SuiteRunner.runSuites(suitesBundleAfterMethodNotSupported, environment, () => new RestClient(FakeScAPIRequestSender)) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleAfterMethodNotSupported, environment, () => new RestClient(FakeScAPIRequestSender)) - val afterSuiteResult: SuiteResults = suiteResults.find(result => - result.resultType == SuiteResults.RESULT_TYPE_AFTER_METHOD && result.suiteName == "endpoint2").get + val afterSuiteResult: SuiteResult = suiteResults.find(result => + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get assertEquals(2, suiteResults.size) - assertEquals("Failure", afterSuiteResult.status) - assertEquals("RestClient:sendRequest - unexpected action method called", afterSuiteResult.errMessage.get) + assertEquals(false, afterSuiteResult.isSuccess) + assertEquals("RestClient:sendRequest - unexpected action method called", afterSuiteResult.errorMsg.get) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/utils/validation/ContentValidatorTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/utils/validation/ContentValidatorTest.scala index 0c0c1d9..f27edd5 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/utils/validation/ContentValidatorTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/utils/validation/ContentValidatorTest.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.utils.validation -import africa.absa.testing.scapi.ContentValidationFailed +import africa.absa.testing.scapi.ContentValidationFailedException import munit.FunSuite class ContentValidatorTest extends FunSuite { @@ -30,13 +30,13 @@ class ContentValidatorTest extends FunSuite { } test("validateIntegerString - fails with non-integer string") { - intercept[ContentValidationFailed] { + intercept[ContentValidationFailedException] { ContentValidator.validateIntegerString("not an integer", "unitTest") } } test("validateIntegerString - fails with empty string") { - intercept[ContentValidationFailed] { + intercept[ContentValidationFailedException] { ContentValidator.validateIntegerString("", "unitTest") } } @@ -50,7 +50,7 @@ class ContentValidatorTest extends FunSuite { } test("validateNonEmptyString - fails with empty string") { - intercept[ContentValidationFailed] { + intercept[ContentValidationFailedException] { ContentValidator.validateNonEmptyString("", "unitTest") } } From 2e251aeeb8d90762628f8d6456e2a9c08e9d882d Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 21 Sep 2023 11:17:40 +0200 Subject: [PATCH 12/31] * Fix - replace Assert type of response actions by enum. * Fix - replace Log type of response actions by enum. * Fix - replace ExtractJson type of response actions by enum. --- .../scapi/json/ReferenceResolver.scala | 15 ++- .../response/AssertResponseActionType.scala | 60 +++++++++ .../response/AssertionResponseAction.scala | 45 ++----- .../response/ExtractJsonResponseAction.scala | 9 +- .../ExtractJsonResponseActionType.scala | 37 ++++++ .../rest/response/LogResponseAction.scala | 15 +-- .../rest/response/LogResponseActionType.scala | 37 ++++++ .../response/ResponseAssertionsTest.scala | 120 +++++++++--------- .../rest/response/ResponseExtractTest.scala | 20 +-- .../scapi/rest/response/ResponseLogTest.scala | 35 ++--- .../scapi/suite/runner/SuiteRunnerTest.scala | 4 +- 11 files changed, 246 insertions(+), 151 deletions(-) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index d30401a..eff24c0 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -199,14 +199,15 @@ case class Action private(methodName: String, url: String, body: Option[String] } /** - * Case class that represents ResponseAction. - * This class is used to hold test response action. - * It implements the `ReferenceResolver` trait to support resolution of reference constants. + * Represents a `ResponseAction` case class. + * + *

This class encapsulates the details of a test response action and provides + * functionality to resolve reference constants through the `ReferenceResolver` trait.

* - * @constructor create a new ResponseAction with a name and value. - * @param method the "group and name" of the response action. - * @param params the map containing the parameters of the response action. Each key-value pair in the map - * represents a parameter name and its corresponding value. + * @param group The type of the response action group. + * @param name The name that identifies the response action. + * @param params A map containing the parameters of the response action. Each entry in the map + * corresponds to a parameter name and its associated value. */ case class ResponseAction private(group: ResponseActionGroupType, name: String, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala new file mode 100644 index 0000000..4ab1153 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala @@ -0,0 +1,60 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response + +import africa.absa.testing.scapi.rest.response + +import scala.language.implicitConversions + +object AssertResponseActionType extends Enumeration { + type AssertResponseActionType = Value + + // response-time-... + val RESPONSE_TIME_IS_BELOW: response.AssertResponseActionType.Value = Value("response-time-is-below") + val RESPONSE_TIME_IS_ABOVE: response.AssertResponseActionType.Value = Value("response-time-is-above") + + // status-code-... + val STATUS_CODE_EQUALS: response.AssertResponseActionType.Value = Value("status-code-equals") + val STATUS_CODE_IS_SUCCESS: response.AssertResponseActionType.Value = Value("status-code-is-success") + val STATUS_CODE_IS_CLIENT_ERROR: response.AssertResponseActionType.Value = Value("status-code-is-client-error") + val STATUS_CODE_IS_SERVER_ERROR: response.AssertResponseActionType.Value = Value("status-code-is-server-error") + + // header-... + val HEADER_EXISTS: response.AssertResponseActionType.Value = Value("header-exists") + val HEADER_VALUE_EQUALS: response.AssertResponseActionType.Value = Value("header-value-equals") + + // content-type-... + val CONTENT_TYPE_IS_JSON: response.AssertResponseActionType.Value = Value("content-type-is-json") + val CONTENT_TYPE_IS_XML: response.AssertResponseActionType.Value = Value("content-type-is-xml") + val CONTENT_TYPE_IS_HTML: response.AssertResponseActionType.Value = Value("content-type-is-html") + + // cookies-... + val COOKIE_EXISTS: response.AssertResponseActionType.Value = Value("cookie-exists") + val COOKIE_VALUE_EQUALS: response.AssertResponseActionType.Value = Value("cookie-value-equals") + val COOKIE_IS_SECURED: response.AssertResponseActionType.Value = Value("cookie-is-secured") + val COOKIE_IS_NOT_SECURED: response.AssertResponseActionType.Value = Value("cookie-is-not-secured") + + // body-... + val BODY_CONTAINS_TEXT: response.AssertResponseActionType.Value = Value("body-contains-text") + + private val stringToValueMap = values.map(v => v.toString -> v).toMap + + def fromString(s: String): Option[AssertResponseActionType] = stringToValueMap.get(s) + + // Implicit conversion from AssertResponseActionType to String + implicit def enumValueToString(value: AssertResponseActionType): String = value.toString +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 88e9096..43ad52c 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -21,6 +21,7 @@ import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.validation.ContentValidator import spray.json._ +import africa.absa.testing.scapi.rest.response.AssertResponseActionType._ import scala.util.{Failure, Success, Try} import scala.xml.XML @@ -31,34 +32,6 @@ import scala.xml.XML */ object AssertionResponseAction extends ResponsePerformer { - // response-time-... - val RESPONSE_TIME_IS_BELOW = "response-time-is-below" - val RESPONSE_TIME_IS_ABOVE = "response-time-is-above" - - // status-code-... - val STATUS_CODE_EQUALS = "status-code-equals" - val STATUS_CODE_IS_SUCCESS = "status-code-is-success" - val STATUS_CODE_IS_CLIENT_ERROR = "status-code-is-client-error" - val STATUS_CODE_IS_SERVER_ERROR = "status-code-is-server-error" - - // header-... - val HEADER_EXISTS = "header-exists" - val HEADER_VALUE_EQUALS = "header-value-equals" - - // content-type-... - val CONTENT_TYPE_IS_JSON = "content-type-is-json" - val CONTENT_TYPE_IS_XML = "content-type-is-xml" - val CONTENT_TYPE_IS_HTML = "content-type-is-html" - - // cookies-... - val COOKIE_EXISTS = "cookie-exists" - val COOKIE_VALUE_EQUALS = "cookie-value-equals" - val COOKIE_IS_SECURED = "cookie-is-secured" - val COOKIE_IS_NOT_SECURED = "cookie-is-not-secured" - - // body-... - val BODY_CONTAINS_TEXT = "body-contains-text" - /** * Validates the content of an assertion response action object depending on its type. * @@ -66,7 +39,8 @@ object AssertionResponseAction extends ResponsePerformer { * @throws UndefinedResponseActionTypeException If the response action type is not recognized. */ def validateContent(responseAction: ResponseAction): Unit = { - responseAction.name.toLowerCase match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { // response-time-... case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => @@ -89,7 +63,7 @@ object AssertionResponseAction extends ResponsePerformer { case headerName: String => ContentValidator.validateNonEmptyString(headerName, s"ResponseAssertion.${responseAction.name}.headerName") case None => throw new IllegalArgumentException(s"Missing required 'headerName' parameter for assertion ${responseAction.name} logic.") } - responseAction.name.toLowerCase match { + action match { case HEADER_VALUE_EQUALS => responseAction.params.getOrElse("expectedValue", None) match { case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$HEADER_VALUE_EQUALS.expectedValue") @@ -107,7 +81,7 @@ object AssertionResponseAction extends ResponsePerformer { case cookieName: String => ContentValidator.validateNonEmptyString(cookieName, s"ResponseAssertion.${responseAction.name}.cookieName") case None => throw new IllegalArgumentException(s"Missing required 'cookieName' parameter for assertion ${responseAction.name} logic.") } - responseAction.name.toLowerCase match { + action match { case COOKIE_VALUE_EQUALS => responseAction.params.getOrElse("expectedValue", None) match { case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$COOKIE_VALUE_EQUALS.expectedValue") @@ -135,12 +109,13 @@ object AssertionResponseAction extends ResponsePerformer { * @throws IllegalArgumentException If the assertion type is not supported. */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { - responseAction.name match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { // response-time-... case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => val limit = responseAction.params("limit") - responseAction.name match { + action match { case RESPONSE_TIME_IS_BELOW => assertResponseTimeIsBelow(response, limit) case RESPONSE_TIME_IS_ABOVE => assertResponseTimeIsAbove(response, limit) } @@ -156,7 +131,7 @@ object AssertionResponseAction extends ResponsePerformer { // header-... case HEADER_EXISTS | HEADER_VALUE_EQUALS => val headerName = responseAction.params("headerName") - responseAction.name match { + action match { case HEADER_EXISTS => assertHeaderExists(response, headerName) case HEADER_VALUE_EQUALS => val expectedValue = responseAction.params("expectedValue") @@ -171,7 +146,7 @@ object AssertionResponseAction extends ResponsePerformer { // cookies-... case COOKIE_EXISTS | COOKIE_VALUE_EQUALS | COOKIE_IS_SECURED | COOKIE_IS_NOT_SECURED => val cookieName = responseAction.params("cookieName") - responseAction.name match { + action match { case COOKIE_EXISTS => assertCookieExists(response, cookieName) case COOKIE_VALUE_EQUALS => val expectedValue = responseAction.params("expectedValue") diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala index 07d97fe..b8e34da 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala @@ -22,6 +22,7 @@ import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator import spray.json._ +import africa.absa.testing.scapi.rest.response.ExtractJsonResponseActionType._ import scala.util.{Failure, Success, Try} @@ -31,8 +32,6 @@ import scala.util.{Failure, Success, Try} */ object ExtractJsonResponseAction extends ResponsePerformer { - val STRING_FROM_LIST = "string-from-list" - /** * Validates the content of an extract response action object depending on its type. * @@ -40,7 +39,8 @@ object ExtractJsonResponseAction extends ResponsePerformer { * @throws UndefinedResponseActionTypeException if an unsupported assertion type is encountered. */ def validateContent(responseAction: ResponseAction): Unit = { - responseAction.name.toLowerCase match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { case STRING_FROM_LIST => validateStringFromList(responseAction) case _ => throw UndefinedResponseActionTypeException(responseAction.name) } @@ -54,7 +54,8 @@ object ExtractJsonResponseAction extends ResponsePerformer { * @throws IllegalArgumentException if an unsupported response action name is encountered. */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { - responseAction.name match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { case STRING_FROM_LIST => val cacheKey = responseAction.params("cacheKey") val listIndex = responseAction.params("listIndex").toInt diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala new file mode 100644 index 0000000..2849396 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response + +import africa.absa.testing.scapi.rest.response + +import scala.language.implicitConversions + +object ExtractJsonResponseActionType extends Enumeration { + type ExtractJsonResponseActionType = Value + + val STRING_FROM_LIST: response.ExtractJsonResponseActionType.Value = Value("string-from-list") + + private val stringToValueMap = values.map(v => v.toString -> v).toMap + + def fromString(s: String): Option[ExtractJsonResponseActionType] = stringToValueMap.get(s) + + // Implicit conversion from AssertResponseActionType to String + implicit def enumValueToString(value: ExtractJsonResponseActionType): String = value.toString +} + + + diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index cdb9180..e141095 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -19,6 +19,7 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.UndefinedResponseActionTypeException import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger +import africa.absa.testing.scapi.rest.response.LogResponseActionType._ import africa.absa.testing.scapi.utils.validation.ContentValidator import scala.util.{Failure, Success, Try} @@ -29,11 +30,6 @@ import scala.util.{Failure, Success, Try} */ object LogResponseAction extends ResponsePerformer { - val ERROR= "error" - val WARN = "warn" - val INFO = "info" - val DEBUG = "debug" - /** * Validates the content of an log response action object depending on its type. * @@ -41,13 +37,14 @@ object LogResponseAction extends ResponsePerformer { * @throws UndefinedResponseActionTypeException if the response action's name is not recognized. */ def validateContent(responseAction: ResponseAction): Unit = { - responseAction.name.toLowerCase match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { case ERROR | WARN | INFO | DEBUG => responseAction.params.get("message") match { case Some(message) => ContentValidator.validateNonEmptyString(message, s"ResponseLog.${responseAction.name}.message") case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion ${responseAction.name} logic.") } - case _ => throw UndefinedResponseActionTypeException(responseAction.name) + case _ => throw UndefinedResponseActionTypeException(responseAction.name.toString) } } @@ -60,8 +57,8 @@ object LogResponseAction extends ResponsePerformer { */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { val message = responseAction.params.getOrElse("message", return Failure(new IllegalArgumentException("Missing 'message' parameter"))) - - responseAction.name match { + val action = fromString(responseAction.name.toLowerCase).getOrElse(None) + action match { case ERROR => logError(message) case WARN => logWarn(message) case INFO => logInfo(message) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala new file mode 100644 index 0000000..1bcf2f6 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response + +import africa.absa.testing.scapi.rest.response + +import scala.language.implicitConversions + +object LogResponseActionType extends Enumeration { + type LogResponseActionType = Value + + val ERROR: response.LogResponseActionType.Value = Value("error") + val WARN: response.LogResponseActionType.Value = Value("warn") + val INFO: response.LogResponseActionType.Value = Value("info") + val DEBUG: response.LogResponseActionType.Value = Value("debug") + + private val stringToValueMap = values.map(v => v.toString -> v).toMap + + def fromString(s: String): Option[LogResponseActionType] = stringToValueMap.get(s) + + // Implicit conversion from AssertResponseActionType to String + implicit def enumValueToString(value: LogResponseActionType): String = value.toString +} diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 2cefb62..fcd2d42 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -29,31 +29,31 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("validateContent - response time is below - limit is integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is below - limit is not integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "not_integer")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "not_integer")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-below.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - limit is integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is above - limit is not integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "not_integer")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "not_integer")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-above.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - missing limit parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'limit' parameter for assertion response-time-is-above logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -62,18 +62,18 @@ class ResponseAssertionsTest extends FunSuite { // status-code-... test("validateContent - valid status code string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - invalid status code string") { intercept[ContentValidationFailedException] { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "not an integer"))) } } test("validateContent - status code equals - missing code parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'code' parameter for assertion status-code-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -82,52 +82,52 @@ class ResponseAssertionsTest extends FunSuite { // header-... test("validateContent - header exists - valid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "content-type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "content-type")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header exists - invalid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-exists.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header exists - missing header name parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - valid header name and value strings") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header value equals - invalid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "", "expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "", "expectedValue" -> "application/json")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - invalid expected value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("expectedValue" -> "application/json")) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -136,52 +136,52 @@ class ResponseAssertionsTest extends FunSuite { // cookies-... test("validateContent - cookie exists - valid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie exists - invalid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-exists.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie exists - missing cookie name parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map()) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map()) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - valid cookie name and value strings") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie value equals - invalid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "", "expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "", "expectedValue" -> "cookieValue")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - invalid cookie value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("expectedValue" -> "cookieValue")) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -190,19 +190,19 @@ class ResponseAssertionsTest extends FunSuite { // body-... test("validateContent - body contains text - body is not empty") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "test content")) + val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "test content")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - body contains text - body is empty") { intercept[ContentValidationFailedException] { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> ""))) } } test("validateContent - body contains text - body parameter is missing") { interceptMessage[IllegalArgumentException]("Missing required 'text' parameter for assertion body-contains-text logic.") { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map.empty)) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map.empty)) } } @@ -219,28 +219,28 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("performAssertions - response time is below limit - success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is below limit - failed") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - response time is above limit - success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is above limit - failed") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) @@ -249,21 +249,21 @@ class ResponseAssertionsTest extends FunSuite { // status-code-... test("performAssertions - status code assertion - equals") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - status code assertion - not equals") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) val response = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - status code - is success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SUCCESS, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SUCCESS, Map.empty) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response299 = Response(299, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -272,7 +272,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SUCCESS, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SUCCESS, Map.empty) val response199 = Response(199, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response300 = Response(300, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -283,7 +283,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is client error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) val response400 = Response(400, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -292,7 +292,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not client error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) val response399 = Response(399, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -303,7 +303,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is server error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SERVER_ERROR, Map.empty) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response599 = Response(599, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -312,7 +312,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not server error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_IS_SERVER_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SERVER_ERROR, Map.empty) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response600 = Response(600, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -325,28 +325,28 @@ class ResponseAssertionsTest extends FunSuite { // header-... test("performAssertions - header exists") { - val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "Content-Type")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "Content-Type")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isSuccess) } test("performAssertions - header does not exists") { - val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_EXISTS, Map("headerName" -> "headerValue")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "headerValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isFailure) } test("performAssertions - header value is equals") { - val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isSuccess) } test("performAssertions - header value is not equals") { - val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.HEADER_VALUE_EQUALS, Map("headerName" -> "someName", "expectedValue" -> "someValue")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "someName", "expectedValue" -> "someValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isFailure) @@ -355,42 +355,42 @@ class ResponseAssertionsTest extends FunSuite { // content-type-... test("performAssertions - content type is json") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_JSON, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_JSON, Map.empty) val response = Response(200, "{}", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not json") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_JSON, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_JSON, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is xml") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_XML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_XML, Map.empty) val response = Response(200, """QADevDon't forget to test it!""", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not xml") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_XML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_XML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is html") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_HTML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_HTML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("text/html")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not html") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.CONTENT_TYPE_IS_HTML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_HTML, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) @@ -399,63 +399,63 @@ class ResponseAssertionsTest extends FunSuite { // cookies-... test("performAssertions - cookie exists") { - val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isSuccess) } test("performAssertions - cookie does not exists") { - val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_EXISTS, Map("cookieName" -> "anotherCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "anotherCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isFailure) } test("performAssertions - cookie value is equals") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("cookieValue", false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isSuccess) } test("performAssertions - cookie value is not equals") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("anotherValue", false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie value equals - cookie does not exist") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie is secured") { - val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_SECURED, Map("cookieName" -> "securedCookie")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_SECURED, Map("cookieName" -> "securedCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> ("someValue", true)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isSuccess) } test("performAssertions - cookie is secured - cookie does not exist") { - val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isFailure) } test("performAssertions - cookie is not secured") { - val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "notSecuredCookie")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "notSecuredCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> ("someValue", false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isSuccess) } test("performAssertions - cookie is not secured - cookie does not exist") { - val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isFailure) @@ -464,13 +464,13 @@ class ResponseAssertionsTest extends FunSuite { // body-... test("performAssertions - body contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "dummy")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "dummy")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isSuccess) } test("performAssertions - body does not contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.BODY_CONTAINS_TEXT, Map("text" -> "dummies")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "dummies")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isFailure) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index ab9d01f..d189d04 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -25,7 +25,7 @@ import scala.util.Try class ResponseExtractTest extends FunSuite { - val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) + val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) val assertionUnsupported: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = "Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) val responseWithID: Response = Response( @@ -138,10 +138,10 @@ class ResponseExtractTest extends FunSuite { // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" test("validateStringFromList - None parameters") { - val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) - val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "")) - val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "")) - val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map.empty) + val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) + val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "")) + val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "")) + val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateStringFromList(assertion4None) @@ -158,10 +158,10 @@ class ResponseExtractTest extends FunSuite { } test("validateStringFromList - empty parameters") { - val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) + val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { ExtractJsonResponseAction.validateStringFromList(assertionParam1) @@ -178,7 +178,7 @@ class ResponseExtractTest extends FunSuite { } test("validateStringFromList - not integer in string") { - val assertion: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseAction.STRING_FROM_LIST, Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) + val assertion: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { ExtractJsonResponseAction.validateStringFromList(assertion) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index c75db51..12cc130 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -16,48 +16,42 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionTypeException import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.rest.response.{LogResponseActionType => LogType} import munit.FunSuite + class ResponseLogTest extends FunSuite { /* validateContent */ test("validateContent - ERROR supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.ERROR, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.ERROR, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - WARN supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.WARN, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.WARN, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - INFO supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - DEBUG supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.DEBUG, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.DEBUG, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } - test("validateContent - not supported validation type") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = "wrong", Map("message" -> "Some string")) - intercept[UndefinedResponseActionTypeException] { - LogResponseAction.validateContent(responseAction) - } - } - test("validateContent - no message provided") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'message' for assertion info logic.") { LogResponseAction.validateContent(responseAction) } @@ -68,36 +62,29 @@ class ResponseLogTest extends FunSuite { */ test("performAssertion - ERROR supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.ERROR, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.ERROR, Map("message" -> "info message")) val response = Response(500, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - WARN supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.WARN, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.WARN, Map("message" -> "info message")) val response = Response(401, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - INFO supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.INFO, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } test("performAssertion - DEBUG supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogResponseAction.DEBUG, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.DEBUG, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) } - test("performAssertion - not supported validation type") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = "not_info", Map("message" -> "info message")) - val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - - assert(LogResponseAction.performResponseAction(response, assertion).isFailure) - } - /* logError */ diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 7253f65..acbcf9b 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -21,7 +21,7 @@ import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.rest.response.{AssertionResponseAction, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite import org.apache.logging.log4j.Level @@ -31,7 +31,7 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val responseAction: ResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertionResponseAction.STATUS_CODE_EQUALS, Map("code" -> "200")) + val responseAction: ResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS.toString, Map("code" -> "200")) val method: Method = Method(name = "test", headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction)) val methodNotSupported: Method = Method(name = "test", headers = Seq(header), actions = Seq(actionNotSupported), responseActions = Seq(responseAction)) From 3dc366b4b082314d12bdddc560dc5cd11fc42c45 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Tue, 3 Oct 2023 12:10:06 +0200 Subject: [PATCH 13/31] * Fix - Update of javaDoc after migration from boolean to Try[Unit] return values. * Fix - make response perform method private. * Fix - Update tests checking exceptions to check meesages too. * Fix - Update assert method to assert values with clues where missing. --- .../testing/scapi/model/SuiteResult.scala | 12 +- .../response/AssertionResponseAction.scala | 139 +++++++++--------- .../response/ExtractJsonResponseAction.scala | 10 +- .../rest/response/LogResponseAction.scala | 33 +++-- .../scapi/json/EnvironmentFactoryTest.scala | 2 +- .../testing/scapi/json/RequestBodyTest.scala | 12 +- .../scapi/json/RequestHeadersTest.scala | 6 +- .../scapi/json/RequestParamsTest.scala | 10 +- .../testing/scapi/json/SuiteFactoryTest.scala | 12 +- .../scapi/reporter/StdOutReporterTest.scala | 52 +++---- .../testing/scapi/rest/RestClientTest.scala | 16 +- .../response/ResponseAssertionsTest.scala | 6 +- .../rest/response/ResponseExtractTest.scala | 137 +++++++---------- .../scapi/rest/response/ResponseLogTest.scala | 42 +----- .../scapi/suite/runner/SuiteRunnerTest.scala | 20 +-- .../scapi/utils/cache/RuntimeCacheTest.scala | 62 ++++---- 16 files changed, 256 insertions(+), 315 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala index 9592a1a..71117fb 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala @@ -21,14 +21,14 @@ import africa.absa.testing.scapi.model.SuiteResultType.SuiteResultType import scala.util.{Failure, Try} /** - * Case class representing the results of a suite test. + * Represents the results of a suite test. * * @param resultType The type of the result (e.g. Before, Test, After) - * @param suiteName The name of the suite - * @param name The name of the test or method - * @param duration The duration of the test, if applicable - * @param categories The categories of the test, if any - * TODO + * @param suiteName The name of the test suite + * @param name The specific name of the test or method within the suite + * @param result The outcome of the test (e.g. Success, Failure) + * @param duration The time taken to execute the test, if applicable (in milliseconds) + * @param categories The categories or tags associated with the test, if any */ case class SuiteResult(resultType: SuiteResultType, suiteName: String, diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala index 43ad52c..dda803c 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala @@ -103,10 +103,10 @@ object AssertionResponseAction extends ResponsePerformer { /** * Performs assertion actions on a response depending on the type of assertion method provided. * - * @param response The response to perform the assertions on. - * @param responseAction The assertion response action to perform on the response. - * @return Boolean value indicating whether the assertion passed or failed. TODO - update all similar docs - * @throws IllegalArgumentException If the assertion type is not supported. + * @param response The response on which the assertions are to be performed. + * @param responseAction The assertion response action to be performed on the response. + * @throws UndefinedResponseActionTypeException If the assertion type is not supported. + * @return A Try[Unit] indicating the success of the assertion operation. */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) @@ -160,7 +160,7 @@ object AssertionResponseAction extends ResponsePerformer { val text = responseAction.params("text") assertBodyContainsText(response, text) - case _ => Failure(new IllegalArgumentException(s"Unsupported assertion method [group: assert]: ${responseAction.name}")) + case _ => Failure(UndefinedResponseActionTypeException(s"Unsupported assertion method [group: assert]: ${responseAction.name}")) } } @@ -169,13 +169,13 @@ object AssertionResponseAction extends ResponsePerformer { */ /** - * Asserts that the response time is below the specified maximum time. + * Asserts that the response duration is below the specified maximum time. * - * @param response The response whose duration is to be checked. - * @param maxTimeMillis The maximum allowed time in milliseconds as a string. - * @return A Boolean indicating whether the response's duration is below the specified maximum time. Returns true if it's below, false otherwise. + * @param response The response object containing the duration to be checked. + * @param maxTimeMillis The maximum allowed duration in milliseconds, provided as a string. + * @return A Try[Unit] that succeeds if the response's duration is below the specified maximum time, and fails with an AssertionException otherwise. */ - def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Try[Unit] = { + private def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Try[Unit] = { val lMaxTimeMillis: Long = maxTimeMillis.toLong if (response.duration <= lMaxTimeMillis) { @@ -186,13 +186,13 @@ object AssertionResponseAction extends ResponsePerformer { } /** - * Asserts that the response time is above the specified minimum time. + * Asserts that the response duration is greater than or equal to the specified minimum time. * - * @param response The response whose duration is to be checked. - * @param minTimeMillis The minimum required time in milliseconds as a string. - * @return A Boolean indicating whether the response's duration is above the specified minimum time. Returns true if it's above, false otherwise. + * @param response The response object containing the duration to be checked. + * @param minTimeMillis The minimum required duration in milliseconds, provided as a string. + * @return A Try[Unit] that is a Success if the response's duration is greater than or equal to the specified minimum time, and a Failure with an AssertionException otherwise. */ - def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Try[Unit] = { + private def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Try[Unit] = { val lMinTimeMillis: Long = minTimeMillis.toLong if (response.duration >= lMinTimeMillis) { @@ -203,29 +203,30 @@ object AssertionResponseAction extends ResponsePerformer { } /** - * Asserts that the status code of the response matches the expected status code. + * Compares the status code of the given response with the expected status code. * - * @param response The response whose status code is to be checked. - * @param expectedCode The expected status code as a string. - * @return A Boolean indicating whether the response's status code matches the expected code. Returns true if they match, false otherwise. + * @param response The HTTP response object to be evaluated. + * @param expectedCode The expected HTTP status code as a string. + * @return A Try[Unit] that is successful if the response's status code matches the expected code, and contains an exception otherwise. + * @throws AssertionException if the response's status code does not match the expected code. */ - def assertStatusCodeEquals(response: Response, expectedCode: String): Try[Unit] = { + private def assertStatusCodeEquals(response: Response, expectedCode: String): Try[Unit] = { val iExpectedCode: Int = expectedCode.toInt if (response.statusCode == iExpectedCode) { Success(()) } else { - Failure(new IllegalArgumentException(s"Expected $iExpectedCode, but got ${response.statusCode}")) + Failure(AssertionException(s"Expected $iExpectedCode, but got ${response.statusCode}")) } } /** - * Checks if the status code of the given response is in the success range (200-299). + * Asserts if the status code of the given response is within the success range (200-299). * - * @param response The response object containing the status code. - * @return True if the status code is in the range 200-299, otherwise false. + * @param response The HTTP response object containing the status code. + * @return A Try[Unit] that is a Success if the status code is within the range 200-299, and a Failure with an AssertionException otherwise. */ - def assertStatusCodeSuccess(response: Response): Try[Unit] = { + private def assertStatusCodeSuccess(response: Response): Try[Unit] = { if (response.statusCode >= 200 && response.statusCode <= 299) { Success(()) } else { @@ -234,12 +235,12 @@ object AssertionResponseAction extends ResponsePerformer { } /** - * Checks if the status code of the given response is in the client error range (400-499). + * Asserts that the status code of the given response is within the client error range (400-499). * - * @param response The response object containing the status code. - * @return True if the status code is in the range 400-499, otherwise false. + * @param response The response object containing the status code. + * @return A Try[Unit] that is a Success if the status code is within the range 400-499, and a Failure with an AssertionException otherwise. */ - def assertStatusCodeIsClientError(response: Response): Try[Unit] = { + private def assertStatusCodeIsClientError(response: Response): Try[Unit] = { if (response.statusCode >= 400 && response.statusCode <= 499) { Success(()) } else { @@ -248,12 +249,12 @@ object AssertionResponseAction extends ResponsePerformer { } /** - * Checks if the status code of the given response is in the server error range (500-599). + * Asserts that the status code of the given response is within the server error range (500-599). * - * @param response The response object containing the status code. - * @return True if the status code is in the range 500-599, otherwise false. + * @param response The response object containing the status code. + * @return A Try[Unit] that is a Success if the status code is within the range 500-599, and a Failure with an AssertionException otherwise. */ - def assertStatusCodeIsServerError(response: Response): Try[Unit] = { + private def assertStatusCodeIsServerError(response: Response): Try[Unit] = { if (response.statusCode >= 500 && response.statusCode <= 599) { Success(()) } else { @@ -262,13 +263,13 @@ object AssertionResponseAction extends ResponsePerformer { } /** - * Checks if the specified header exists in the given response. + * Asserts that the specified header exists in the given response. * - * @param response The response object containing the headers. - * @param headerName The name of the header to check for. - * @return True if the header exists in the response, otherwise false. + * @param response The response object containing the headers. + * @param headerName The name of the header to check for. + * @return A Try[Unit] that is a Success if the header exists in the response, and a Failure with an AssertionException otherwise. */ - def assertHeaderExists(response: Response, headerName: String): Try[Unit] = { + private def assertHeaderExists(response: Response, headerName: String): Try[Unit] = { if (response.headers.contains(headerName.toLowerCase)) { Success(()) } else { @@ -279,12 +280,12 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the value of the specified header in the given response matches the expected value. * - * @param response The response object containing the headers. - * @param headerName The name of the header to check. + * @param response The response object containing the headers. + * @param headerName The name of the header to check. * @param expectedValue The expected value of the header. - * @return True if the header value matches the expected value, otherwise false. + * @return A Try[Unit] that is a Success if the header value matches the expected value, and a Failure with an AssertionException otherwise. */ - def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Try[Unit] = { + private def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Try[Unit] = { if (assertHeaderExists(response, headerName).isSuccess) { if (expectedValue.equals(response.headers(headerName.toLowerCase).head)) { Success(()) @@ -300,10 +301,10 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the value of the "Content-Type" header in the given response is "application/json". * - * @param response The response object containing the headers. - * @return True if the "Content-Type" header value is "application/json", otherwise false. + * @param response The response object containing the headers. + * @return A Try[Unit] that is a Success if the "Content-Type" header value is "application/json", and a Failure with an AssertionException otherwise. */ - def assertContentTypeIsJson(response: Response): Try[Unit] = { + private def assertContentTypeIsJson(response: Response): Try[Unit] = { val isContentTypeJson = assertHeaderValueEquals(response, "content-type", "application/json") val isBodyJson = try { response.body.parseJson @@ -322,10 +323,10 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the value of the "Content-Type" header in the given response is "application/xml". * - * @param response The response object containing the headers. - * @return True if the "Content-Type" header value is "application/xml", otherwise false. + * @param response The response object containing the headers. + * @return A Try[Unit] that is a Success if the "Content-Type" header value is "application/xml", and a Failure with an AssertionException otherwise. */ - def assertContentTypeIsXml(response: Response): Try[Unit] = { + private def assertContentTypeIsXml(response: Response): Try[Unit] = { val isContentTypeXml = assertHeaderValueEquals(response, "content-type", "application/xml") val isBodyXml = try { XML.loadString(response.body) @@ -344,10 +345,10 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the value of the "Content-Type" header in the given response is "text/html". * - * @param response The response object containing the headers. - * @return True if the "Content-Type" header value is "text/html", otherwise false. + * @param response The response object containing the headers. + * @return A Try[Unit] that is a Success if the "Content-Type" header value is "text/html", and a Failure with an AssertionException otherwise. */ - def assertContentTypeIsHtml(response: Response): Try[Unit] = { + private def assertContentTypeIsHtml(response: Response): Try[Unit] = { val res = assertHeaderValueEquals(response, "content-type", "text/html") res match { @@ -362,11 +363,11 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the specified cookie exists in the given response. * - * @param response The response object containing the cookies. - * @param cookieName The name of the cookie to check for existence. - * @return True if the specified cookie exists in the response, otherwise false. + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check for existence. + * @return A Try[Unit] that is a Success if the specified cookie exists in the response, and a Failure with an AssertionException otherwise. */ - def assertCookieExists(response: Response, cookieName: String): Try[Unit] = { + private def assertCookieExists(response: Response, cookieName: String): Try[Unit] = { if (response.cookies.contains(cookieName)) { Success(()) } else { @@ -380,9 +381,9 @@ object AssertionResponseAction extends ResponsePerformer { * @param response The response object containing the cookies. * @param cookieName The name of the cookie to check. * @param expectedValue The expected value of the cookie. - * @return True if the value of the specified cookie matches the expected value, otherwise false. + * @return A Try[Unit] that is a Success if the value of the specified cookie matches the expected value, and a Failure with an AssertionException otherwise. */ - def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Try[Unit] = { + private def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => if (response.cookies(cookieName)._1 == expectedValue) { Success(()) @@ -395,11 +396,11 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the specified cookie in the given response is secured. * - * @param response The response object containing the cookies. - * @param cookieName The name of the cookie to check. - * @return True if the specified cookie is secured, otherwise false. + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check. + * @return A Try[Unit] that is a Success if the specified cookie is secured, and a Failure with an AssertionException otherwise. */ - def assertCookieIsSecured(response: Response, cookieName: String): Try[Unit] = { + private def assertCookieIsSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => if (response.cookies(cookieName)._2) { Success(()) @@ -412,11 +413,11 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the specified cookie in the given response is not secured. * - * @param response The response object containing the cookies. - * @param cookieName The name of the cookie to check. - * @return True if the specified cookie is not secured, otherwise false. + * @param response The response object containing the cookies. + * @param cookieName The name of the cookie to check. + * @return A Try[Unit] that is a Success if the specified cookie is not secured, and a Failure with an AssertionException otherwise. */ - def assertCookieIsNotSecured(response: Response, cookieName: String): Try[Unit] = { + private def assertCookieIsNotSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => if (!response.cookies(cookieName)._2) { Success(()) @@ -429,11 +430,11 @@ object AssertionResponseAction extends ResponsePerformer { /** * Asserts that the body of the response contains the expected content. * - * @param response The HTTP response to check the body of. - * @param text The expected text present in the response body as a string. - * @return A Boolean indicating whether the expected content is present in the response body or not. + * @param response The HTTP response to check the body of. + * @param text The expected text present in the response body as a string. + * @return A Try[Unit] that is a Success if the body contains the expected text, and a Failure with an AssertionException otherwise. */ - def assertBodyContainsText(response: Response, text: String): Try[Unit] = { + private def assertBodyContainsText(response: Response, text: String): Try[Unit] = { if (response.body.contains(text)) { Success(()) } else { diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala index b8e34da..8d1d000 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala @@ -51,7 +51,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { * * @param response The Response instance to perform response action on. * @param responseAction The ResponseAction instance containing the response action details. - * @throws IllegalArgumentException if an unsupported response action name is encountered. + * @throws UndefinedResponseActionTypeException if an unsupported response action name is encountered. */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) @@ -63,7 +63,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { val cacheLevel = responseAction.params("cacheLevel") stringFromList(response, cacheKey, listIndex, jsonKey, cacheLevel) - case _ => throw new IllegalArgumentException(s"Unsupported assertion[group: extract]: ${responseAction.name}") + case _ => throw UndefinedResponseActionTypeException(s"Unsupported assertion[group: extract]: ${responseAction.name}") } } @@ -80,9 +80,9 @@ object ExtractJsonResponseAction extends ResponsePerformer { * @param listIndex The index in the JSON array from which to extract the string. * @param jsonKey The key in the JSON object from which to extract the string. * @param runtimeCacheLevel The expiration level to use when storing the extracted string in the runtime cache. - * @return Boolean indicating whether the string extraction and caching operation was successful. + * @return A Try[Unit] indicating whether the string extraction and caching operation was successful or not. */ - def stringFromList(response: Response, cacheKey: String, listIndex: Int, jsonKey: String, runtimeCacheLevel: String): Try[Unit] = { + private def stringFromList(response: Response, cacheKey: String, listIndex: Int, jsonKey: String, runtimeCacheLevel: String): Try[Unit] = { try { val jsonAst = response.body.parseJson @@ -118,7 +118,7 @@ object ExtractJsonResponseAction extends ResponsePerformer { * * @param assertion The ResponseAction instance containing the response action details. */ - def validateStringFromList(assertion: ResponseAction): Unit = { + private def validateStringFromList(assertion: ResponseAction): Unit = { val cacheKey = assertion.params.getOrElse("cacheKey", throw new IllegalArgumentException(s"Missing required 'cacheKey' parameter for extract $STRING_FROM_LIST logic")) val listIndex = assertion.params.getOrElse("listIndex", throw new IllegalArgumentException(s"Missing required 'listIndex' parameter for extract $STRING_FROM_LIST logic")) val jsonKey = assertion.params.getOrElse("jsonKey", throw new IllegalArgumentException(s"Missing required 'jsonKey' parameter for extract $STRING_FROM_LIST logic")) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala index e141095..efaa53c 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.UndefinedResponseActionTypeException +import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.rest.response.LogResponseActionType._ @@ -51,19 +51,20 @@ object LogResponseAction extends ResponsePerformer { /** * Performs log actions on a response depending on the type of log method provided. * - * @param response The response on which the response action are to be performed. - * @param responseAction The responseAction to be performed on the response. - * @throws IllegalArgumentException if the response action's name is not recognized. + * @param response The response on which the response action is to be performed. + * @param responseAction The response action to be performed on the response. + * @throws UndefinedResponseActionTypeException if the response action's name is not recognized. + * @throws PropertyNotFoundException if the required 'message' parameter is missing. */ def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { - val message = responseAction.params.getOrElse("message", return Failure(new IllegalArgumentException("Missing 'message' parameter"))) + val message = responseAction.params.getOrElse("message", return Failure(PropertyNotFoundException("Missing 'message' parameter"))) val action = fromString(responseAction.name.toLowerCase).getOrElse(None) action match { case ERROR => logError(message) case WARN => logWarn(message) case INFO => logInfo(message) case DEBUG => logDebug(message) - case _ => Failure(new IllegalArgumentException(s"Unsupported log method [group: log]: ${responseAction.name}")) + case _ => Failure(UndefinedResponseActionTypeException(s"Unsupported log method [group: log]: ${responseAction.name}")) } } @@ -72,41 +73,45 @@ object LogResponseAction extends ResponsePerformer { */ /** - * This method logs a message at the ERROR level. + * Logs a message at the ERROR level. * * @param message The message to be logged. + * @return A Try[Unit] indicating the success of the logging operation. */ - def logError(message: String): Try[Unit] = { + private def logError(message: String): Try[Unit] = { Logger.error(message) Success(()) } /** - * This method logs a message at the WARN level. + * Logs a message at the WARN level. * * @param message The message to be logged. + * @return A Try[Unit] indicating the success of the logging operation. */ - def logWarn(message: String): Try[Unit] = { + private def logWarn(message: String): Try[Unit] = { Logger.warn(message) Success(()) } /** - * This method logs a message at the INFO level. + * Logs a message at the INFO level. * * @param message The message to be logged. + * @return A Try[Unit] indicating the success of the logging operation. */ - def logInfo(message: String): Try[Unit] = { + private def logInfo(message: String): Try[Unit] = { Logger.info(message) Success(()) } /** - * This method logs a message at the DEBUG level. + * Logs a message at the DEBUG level. * * @param message The message to be logged. + * @return A Try[Unit] indicating the success of the logging operation. */ - def logDebug(message: String): Try[Unit] = { + private def logDebug(message: String): Try[Unit] = { Logger.debug(message) Success(()) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala index 64927c4..98fe80c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala @@ -61,7 +61,7 @@ class EnvironmentFactoryTest extends FunSuite { } test("fromFile - missing referenced constant") { - intercept[UndefinedConstantsInPropertiesException] { + interceptMessage[UndefinedConstantsInPropertiesException]("Undefined constant(s): 'errPort' in ''Environment' action.'.") { val envPath: String = getClass.getResource("/missing_constant_env.json").getPath EnvironmentFactory.fromFile(envPath) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala index 41a9d88..2bb8e66 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestBodyTest.scala @@ -30,32 +30,32 @@ class RequestBodyTest extends FunSuite { test("buildBody - return string representation of JSON when jsonBody is not empty") { val jsonBody = Some("""{"key":"value"}""") val result = RequestBody.buildBody(jsonBody) - assertEquals(result, """{"key":"value"}""") + assertEquals("""{"key":"value"}""", result) } test("buildBody - throw exception when non json string received") { val jsonBody = Some("""not json string""") - intercept[ParsingException] { + interceptMessage[ParsingException]("Unexpected character 'o' at input index 0 (line 1, position 1), expected JSON Value:\nnot json string\n^\n") { RequestBody.buildBody(jsonBody) } } test("buildBody - return empty string representation of JSON when no body received") { val result = RequestBody.buildBody() - assertEquals(result, """{}""") + assertEquals("""{}""", result) } test("buildBody - return empty JSON object string when jsonBody is empty") { val jsonBody = Some("") val result = RequestBody.buildBody(jsonBody) - assertEquals(result, "{}") + assertEquals("{}", result) } test("buildBody - return empty JSON object string when jsonBody is None") { val jsonBody: Option[String] = None val result = RequestBody.buildBody(jsonBody) - assertEquals(result, "{}") + assertEquals("{}", result) } /* @@ -79,7 +79,7 @@ class RequestBodyTest extends FunSuite { test("validateContent - fail when body is a non json string") { val jsonBody = Some("""not json string""") - intercept[ContentValidationFailedException] { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not json string': Received value cannot be parsed to json: Unexpected character 'o' at input index 0 (line 1, position 1), expected JSON Value:\nnot json string\n^\n") { RequestBody.validateContent(jsonBody) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala index e9ad9a9..67094ef 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala @@ -40,7 +40,7 @@ class RequestHeadersTest extends FunSuite { ) val actualMap = RequestHeaders.buildHeaders(headersSeq) - assertEquals(actualMap, expectedMap) + assertEquals(clue(expectedMap), clue(actualMap)) } test("buildHeaders - should return an empty map if no headers are provided") { @@ -48,7 +48,7 @@ class RequestHeadersTest extends FunSuite { val expectedMap = Map.empty[String, String] val actualMap = RequestHeaders.buildHeaders(headersSeq) - assertEquals(actualMap, expectedMap) + assertEquals(clue(expectedMap), clue(actualMap)) } /* @@ -81,7 +81,7 @@ class RequestHeadersTest extends FunSuite { test("validateContent - Unsupported header type") { val header = Header("unsupported-header", "value") - intercept[UndefinedHeaderTypeException] { + interceptMessage[UndefinedHeaderTypeException]("Undefined Header content type: 'unsupported-header'") { RequestHeaders.validateContent(header) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala index 41967b7..082c6a1 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala @@ -29,25 +29,25 @@ class RequestParamsTest extends FunSuite { test("buildParams - no params") { val paramsSet: Option[Set[Param]] = None val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(result, Map.empty[String, String]) + assertEquals(clue(Map.empty[String, String]), clue(result)) } test("buildParams - single valid param") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name", "value"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(result, Map("name" -> "value")) + assertEquals(clue(Map("name" -> "value")), clue(result)) } test("buildParams - multiple valid params") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name1", "value1"), Param("name2", "value2"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(result, Map("name1" -> "value1", "name2" -> "value2")) + assertEquals(clue(Map("name1" -> "value1", "name2" -> "value2")), clue(result)) } test("buildParams - params with empty name or value should be ignored") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name", ""), Param("", "value"), Param("name2", "value2"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(result, Map("name2" -> "value2")) + assertEquals(clue(Map("name2" -> "value2")), clue(result)) } /* @@ -61,7 +61,7 @@ class RequestParamsTest extends FunSuite { test("validateContent - should throw exception for empty name") { val params = Set(Param("", "value")) - intercept[ContentValidationFailedException] { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'Param.' is empty.") { RequestParams.validateContent(Some(params)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index f064982..86203e2 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -119,7 +119,7 @@ class SuiteFactoryTest extends FunSuite { val suiteName = "getUserCurrent" val properties: Map[String, String] = Map.empty - intercept[UndefinedConstantsInPropertiesException] { + interceptMessage[UndefinedConstantsInPropertiesException]("Undefined constant(s): 'env.basic_token' in ''SuiteConstants' action.'.") { SuiteFactory.loadJsonSuiteConstants(suiteFilePath, suiteName, properties).constants } } @@ -146,12 +146,12 @@ class SuiteFactoryTest extends FunSuite { assertEquals(filteredSuiteBundles.size, 1) val filteredSuite = filteredSuiteBundles.head.suite - assertEquals(filteredSuite.endpoint, "endpoint1") - assertEquals(filteredSuite.tests.size, 1) + assertEquals(clue("endpoint1"), clue(filteredSuite.endpoint)) + assertEquals(clue(1), clue(filteredSuite.tests.size)) val filteredTest = filteredSuite.tests.head - assertEquals(filteredTest.name, "test2") - assertEquals(filteredTest.only, Some(true)) + assertEquals(clue("test2"), clue(filteredTest.name)) + assertEquals(clue(Some(true)), clue(filteredTest.only)) } test("fromFile - only used - twice") { @@ -166,6 +166,6 @@ class SuiteFactoryTest extends FunSuite { val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) - assertEquals(filteredSuiteBundles.size, 0) + assertEquals(clue(0), clue(filteredSuiteBundles.size)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index 194200c..12b1b6d 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -82,11 +82,11 @@ class StdOutReporterTest extends FunSuite { val output = baos.toString // Assertions - assertEquals(clue(output.contains("Simple Text Report")), true) - assertEquals(clue(output.contains("Number of tests run: 0")), true) - assertEquals(clue(output.contains("Number of successful tests: 0")), true) - assertEquals(clue(output.contains("Number of failed tests: 0")), true) - assertEquals(clue(output.contains("End Report")), true) + assertEquals(true, clue(output.contains("Simple Text Report"))) + assertEquals(true, clue(output.contains("Number of tests run: 0"))) + assertEquals(true, clue(output.contains("Number of successful tests: 0"))) + assertEquals(true, clue(output.contains("Number of failed tests: 0"))) + assertEquals(true, clue(output.contains("End Report"))) } test("full results with failed".only) { @@ -109,24 +109,24 @@ class StdOutReporterTest extends FunSuite { // Assertions // report header & tail - assertEquals(clue(output.contains("Simple Text Report")), true) - assertEquals(clue(output.contains("Number of tests run: 3")), true) - assertEquals(clue(output.contains("Number of successful tests: 2")), true) - assertEquals(clue(output.contains("Number of failed tests: 1")), true) - assertEquals(clue(output.contains("End Report")), true) + assertEquals(true, clue(output.contains("Simple Text Report"))) + assertEquals(true, clue(output.contains("Number of tests run: 3"))) + assertEquals(true, clue(output.contains("Number of successful tests: 2"))) + assertEquals(true, clue(output.contains("Number of failed tests: 1"))) + assertEquals(true, clue(output.contains("End Report"))) // suite summary - assertEquals(clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 1, Failed: 1")), true) - assertEquals(clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0")), true) + assertEquals(true, clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 1, Failed: 1"))) + assertEquals(true, clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) // summary of all tests val updatedOutput = output.replace(" ", "") - assertEquals(clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|")), true) - assertEquals(clue(updatedOutput.contains("|Suite1|Test2|200|Failure|Category2|")), true) - assertEquals(clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|")), true) + assertEquals(true, clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) + assertEquals(true, clue(updatedOutput.contains("|Suite1|Test2|200|Failure|Category2|"))) + assertEquals(true, clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) // error from detail - assertEquals(clue(output.contains("Assertion failed: Error message")), true) + assertEquals(true, clue(output.contains("Assertion failed: Error message"))) } test("results all success") { @@ -141,20 +141,20 @@ class StdOutReporterTest extends FunSuite { // Assertions // report header & tail - assertEquals(clue(output.contains("Simple Text Report")), true) - assertEquals(clue(output.contains("Number of tests run: 3")), true) - assertEquals(clue(output.contains("Number of successful tests: 3")), true) - assertEquals(clue(output.contains("Number of failed tests: 0")), true) - assertEquals(clue(output.contains("End Report")), true) + assertEquals(true, clue(output.contains("Simple Text Report"))) + assertEquals(true, clue(output.contains("Number of tests run: 3"))) + assertEquals(true, clue(output.contains("Number of successful tests: 3"))) + assertEquals(true, clue(output.contains("Number of failed tests: 0"))) + assertEquals(true, clue(output.contains("End Report"))) // suite summary - assertEquals(clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 2, Failed: 0")), true) - assertEquals(clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0")), true) + assertEquals(true, clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 2, Failed: 0"))) + assertEquals(true, clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) // summary of all tests val updatedOutput = output.replace(" ", "") - assertEquals(clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|")), true) - assertEquals(clue(updatedOutput.contains("|Suite1|Test2|200|Success|Category2|")), true) - assertEquals(clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|")), true) + assertEquals(true, clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) + assertEquals(true, clue(updatedOutput.contains("|Suite1|Test2|200|Success|Category2|"))) + assertEquals(true, clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala index 79213e2..eefb604 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/RestClientTest.scala @@ -58,32 +58,32 @@ class RestClientTest extends FunSuite { val restClient: RestClient = new RestClient(mockRequestSender) val response: Response = restClient.sendRequest("get", "testUrl", "testData", Map("Authorization" -> "Bearer testToken"), Map("param1" -> "value1"), false) - assert(response.statusCode == 200) - assert(response.body == "test response") + assertEquals(200, response.statusCode) + assertEquals("test response", response.body) } test("sendRequest - call post with correct parameters") { val restClient: RestClient = new RestClient(mockRequestSender) val response: Response = restClient.sendRequest("post", "testUrl", "testData", Map("Authorization" -> "Bearer testToken"), Map("param1" -> "value1"), false) - assert(response.statusCode == 200) - assert(response.body == "test response") + assertEquals(200, response.statusCode) + assertEquals("test response", response.body) } test("sendRequest - call put with correct parameters") { val restClient: RestClient = new RestClient(mockRequestSender) val response: Response = restClient.sendRequest("put", "testUrl", "testData", Map("Authorization" -> "Bearer testToken"), Map("param1" -> "value1"), false) - assert(response.statusCode == 200) - assert(response.body == "test response") + assertEquals(200, response.statusCode) + assertEquals("test response", response.body) } test("sendRequest - call delete with correct parameters") { val restClient: RestClient = new RestClient(mockRequestSender) val response: Response = restClient.sendRequest("delete", "testUrl", "testData", Map("Authorization" -> "Bearer testToken"), Map("param1" -> "value1"), false) - assert(response.statusCode == 200) - assert(response.body == "test response") + assertEquals(200, response.statusCode) + assertEquals("test response", response.body) } test("sendRequest - call not supported action") { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index fcd2d42..6a4e035 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -67,7 +67,7 @@ class ResponseAssertionsTest extends FunSuite { } test("validateContent - invalid status code string") { - intercept[ContentValidationFailedException] { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not an integer': Received value of 'ResponseAssertion.status-code-equals.code' cannot be parsed to an integer: For input string: \"not an integer\"") { AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "not an integer"))) } } @@ -195,7 +195,7 @@ class ResponseAssertionsTest extends FunSuite { } test("validateContent - body contains text - body is empty") { - intercept[ContentValidationFailedException] { + interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.body-contains-text.text' is empty.") { AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> ""))) } } @@ -207,7 +207,7 @@ class ResponseAssertionsTest extends FunSuite { } test("validateContent - unsupported response action") { - intercept[UndefinedResponseActionTypeException] { + interceptMessage[UndefinedResponseActionTypeException]("Undefined response action content type: 'unsupported'") { AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = "unsupported", Map("body" -> "value"))) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index d189d04..7d3dd30 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -64,124 +64,93 @@ class ResponseExtractTest extends FunSuite { ExtractJsonResponseAction.validateContent(assertionStringFromList) } - test("validateContent - unsupported option") { - intercept[UndefinedResponseActionTypeException] { - ExtractJsonResponseAction.validateContent(assertionUnsupported) - } - } - - /* - performResponseAction - */ - - test("performAssertion - STRING_FROM_LIST") { - val result: Try[Unit] = ExtractJsonResponseAction.performResponseAction(responseWithID, assertionStringFromList) - assert(result.isSuccess) - assertEquals("382be85a-1f00-4c15-b607-cbda03ccxxx2", RuntimeCache.get("question_id").get) - } - - test("performAssertion - unsupported assertion") { - intercept[IllegalArgumentException] { - ExtractJsonResponseAction.performResponseAction(responseWithID, assertionUnsupported) - } - } - - /* - stringFromList - */ - - // positive test "stringFromList - correct parameters" - tested during "performAssertion - STRING_FROM_LIST" - - test("stringFromList - incorrect parameters - wrong list index") { - val cacheKey = "question_id" - val listIndex = 10 - val jsonKey = "id" - val runtimeCacheLevel = "Test" - interceptMessage[IndexOutOfBoundsException]("10 is out of bounds (min 0, max 2)") { - ExtractJsonResponseAction.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) + test("validateContent - validateStringFromList - not integer in string") { + val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("listIndex", "x")) + interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { + ExtractJsonResponseAction.validateContent(notValidAssertionStringFromList) } } - test("stringFromList - incorrect parameters - wrong jsonKey") { - val cacheKey = "question_id" - val listIndex = 0 - val jsonKey = "ids" - val runtimeCacheLevel = "Test" - val result = ExtractJsonResponseAction.stringFromList(responseWithID, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result.isSuccess) - } - - test("stringFromList - incorrect parameters - no json body in response") { - val cacheKey = "question_id" - val listIndex = 0 - val jsonKey = "id" - val runtimeCacheLevel = "Test" - - val result = ExtractJsonResponseAction.stringFromList(responseNoJsonBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result.isSuccess) - } - - test("stringFromList - incorrect parameters - no json arrays in response body") { - val cacheKey = "question_id" - val listIndex = 0 - val jsonKey = "id" - val runtimeCacheLevel = "Test" - - val result = ExtractJsonResponseAction.stringFromList(responseJsonNoArrayBody, cacheKey, listIndex, jsonKey, runtimeCacheLevel) - assert(!result.isSuccess) - } - - /* - validateStringFromList - */ - - // positive test "stringFromList - correct parameters" - tested during "validateContent - STRING_FROM_LIST" - - test("validateStringFromList - None parameters") { + test("validateContent - validateStringFromList - None parameters") { val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "")) val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "")) val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { - ExtractJsonResponseAction.validateStringFromList(assertion4None) + ExtractJsonResponseAction.validateContent(assertion4None) } interceptMessage[IllegalArgumentException]("Missing required 'listIndex' parameter for extract string-from-list logic") { - ExtractJsonResponseAction.validateStringFromList(assertion3None) + ExtractJsonResponseAction.validateContent(assertion3None) } interceptMessage[IllegalArgumentException]("Missing required 'jsonKey' parameter for extract string-from-list logic") { - ExtractJsonResponseAction.validateStringFromList(assertion2None) + ExtractJsonResponseAction.validateContent(assertion2None) } interceptMessage[IllegalArgumentException]("Missing required 'cacheLevel' parameter for extract string-from-list logic") { - ExtractJsonResponseAction.validateStringFromList(assertion1None) + ExtractJsonResponseAction.validateContent(assertion1None) } } - test("validateStringFromList - empty parameters") { + test("validateContent - validateStringFromList - empty parameters") { val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { - ExtractJsonResponseAction.validateStringFromList(assertionParam1) + ExtractJsonResponseAction.validateContent(assertionParam1) } interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.listIndex' is empty.") { - ExtractJsonResponseAction.validateStringFromList(assertionParam2) + ExtractJsonResponseAction.validateContent(assertionParam2) } interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.jsonKey' is empty.") { - ExtractJsonResponseAction.validateStringFromList(assertionParam3) + ExtractJsonResponseAction.validateContent(assertionParam3) } interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheLevel' is empty.") { - ExtractJsonResponseAction.validateStringFromList(assertionParam4) + ExtractJsonResponseAction.validateContent(assertionParam4) } } - test("validateStringFromList - not integer in string") { - val assertion: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "key", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "y")) - interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'x': Received value of 'ExtractJson.string-from-list.listIndex' cannot be parsed to an integer: For input string: \"x\"") { - ExtractJsonResponseAction.validateStringFromList(assertion) + test("validateContent - unsupported option") { + interceptMessage[UndefinedResponseActionTypeException]("Undefined response action content type: 'Unsupported'") { + ExtractJsonResponseAction.validateContent(assertionUnsupported) + } + } + + /* + performResponseAction + */ + + test("performAssertion - STRING_FROM_LIST") { + val result: Try[Unit] = ExtractJsonResponseAction.performResponseAction(responseWithID, assertionStringFromList) + assert(result.isSuccess) + assertEquals("382be85a-1f00-4c15-b607-cbda03ccxxx2", RuntimeCache.get("question_id").get) + } + + // string-from-... + + test("performAssertion - stringFromList - incorrect parameters - wrong list index") { + val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("listIndex", "10")) + interceptMessage[IndexOutOfBoundsException]("10 is out of bounds (min 0, max 2)") { + ExtractJsonResponseAction.performResponseAction(responseWithID, notValidAssertionStringFromList) } + } + + test("performAssertion - stringFromList - incorrect parameters - wrong jsonKey") { + val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("jsonKey", "ids")) + val res = ExtractJsonResponseAction.performResponseAction(responseWithID, notValidAssertionStringFromList) + assert(res.isFailure) + } + + test("performAssertion - stringFromList - incorrect parameters - no json arrays in response body") { + val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("listIndex", "0")) + val res = ExtractJsonResponseAction.performResponseAction(responseNoJsonBody, notValidAssertionStringFromList) + assert(res.isFailure) + } + test("performAssertion - unsupported assertion") { + interceptMessage[UndefinedResponseActionTypeException]("Undefined response action content type: 'Unsupported assertion[group: extract]: Unsupported'") { + ExtractJsonResponseAction.performResponseAction(responseWithID, assertionUnsupported) + } } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index 12cc130..a1898da 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -64,58 +64,24 @@ class ResponseLogTest extends FunSuite { test("performAssertion - ERROR supported") { val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.ERROR, Map("message" -> "info message")) val response = Response(500, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) + assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - WARN supported") { val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.WARN, Map("message" -> "info message")) val response = Response(401, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) + assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - INFO supported") { val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) + assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - DEBUG supported") { val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.DEBUG, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) - assertEquals(LogResponseAction.performResponseAction(response, assertion).isSuccess, true) + assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } - - /* - logError - */ - - test("logError") { - assertEquals(LogResponseAction.logError("log error message").isSuccess, true) - } - - /* - logWarn - */ - - test("logInfo") { - assertEquals(LogResponseAction.logWarn("log warn message").isSuccess, true) - } - - /* - logInfo - */ - - test("logInfo") { - assertEquals(LogResponseAction.logInfo("log info message").isSuccess, true) - } - - /* - logDebug - */ - - test("logDebug") { - assertEquals(LogResponseAction.logDebug("log debug message").isSuccess, true) - } - - } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index acbcf9b..bc64f83 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -106,9 +106,9 @@ class SuiteRunnerTest extends FunSuite { val beforeSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2").get - assertEquals(5, suiteResults.size) - assertEquals("test", beforeSuiteResult.name) - assertEquals(true, beforeSuiteResult.isSuccess) + assertEquals(5, clue(suiteResults.size)) + assertEquals("test", clue(beforeSuiteResult.name)) + assertEquals(true, clue(beforeSuiteResult.isSuccess)) } test("runSuite - SuiteBefore empty") { @@ -117,7 +117,7 @@ class SuiteRunnerTest extends FunSuite { val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2") - assertEquals(2, suiteResults.size) + assertEquals(2, clue(suiteResults.size)) assert(beforeSuiteResult.isEmpty) } @@ -127,9 +127,9 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get - assertEquals(5, suiteResults.size) - assertEquals("test", afterSuiteResult.name) - assertEquals(true, afterSuiteResult.isSuccess) + assertEquals(5, clue(suiteResults.size)) + assertEquals("test", clue(afterSuiteResult.name)) + assertEquals(true, clue(afterSuiteResult.isSuccess)) } test("runSuite - SuiteAfter empty") { @@ -138,7 +138,7 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2") - assertEquals(2, suiteResults.size) + assertEquals(2, clue(suiteResults.size)) assert(afterSuiteResult.isEmpty) } @@ -148,8 +148,8 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get - assertEquals(2, suiteResults.size) - assertEquals(false, afterSuiteResult.isSuccess) + assertEquals(2, clue(suiteResults.size)) + assertEquals(false, clue(afterSuiteResult.isSuccess)) assertEquals("RestClient:sendRequest - unexpected action method called", afterSuiteResult.errorMsg.get) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala index 03a0e63..2a593b4 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala @@ -31,28 +31,28 @@ class RuntimeCacheTest extends FunSuite { test("put") { RuntimeCache.put("key", "value") - assertEquals(RuntimeCache.get("key"), Some("value")) + assertEquals(clue(Some("value")), clue(RuntimeCache.get("key"))) } test("put - with level") { RuntimeCache.put("g", "g", GlobalLevel) RuntimeCache.put("s", "s", SuiteLevel) RuntimeCache.put("t", "t", TestLevel) - assertEquals(RuntimeCache.get("g"), Some("g")) - assertEquals(RuntimeCache.get("s"), Some("s")) - assertEquals(RuntimeCache.get("t"), Some("t")) + assertEquals(clue(Some("g")), clue(RuntimeCache.get("g"))) + assertEquals(clue(Some("s")), clue(RuntimeCache.get("s"))) + assertEquals(clue(Some("t")), clue(RuntimeCache.get("t"))) } test("put - already exists - on same level") { RuntimeCache.put("key", "valueA") RuntimeCache.put("key", "valueB") - assertEquals(RuntimeCache.get("key"), Some("valueA")) + assertEquals(clue(Some("valueA")), clue(RuntimeCache.get("key"))) } test("put - already exists - on different level") { RuntimeCache.put("key", "valueA", TestLevel) RuntimeCache.put("key", "valueB", SuiteLevel) - assertEquals(RuntimeCache.get("key"), Some("valueA")) + assertEquals(clue(Some("valueA")), clue(RuntimeCache.get("key"))) } /* @@ -61,7 +61,7 @@ class RuntimeCacheTest extends FunSuite { // smoke possitive tested during put tests - skipped here test("get - nonexistent key") { - assertEquals(None, RuntimeCache.get("nonexistent")) + assertEquals(None, clue(RuntimeCache.get("nonexistent"))) } /* @@ -71,11 +71,11 @@ class RuntimeCacheTest extends FunSuite { test("update") { RuntimeCache.put("key", "value") RuntimeCache.update("key", "newValue") - assertEquals(RuntimeCache.get("key"), Some("newValue")) + assertEquals(clue(Some("newValue")), clue(RuntimeCache.get("key"))) } test("update - nonexistent key") { - intercept[NoSuchElementException] { + interceptMessage[NoSuchElementException]("Key nonexistent not found in cache") { RuntimeCache.update("nonexistent", "value") } } @@ -86,7 +86,7 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(RuntimeCache.get("key"), Some("newValue")) + assertEquals(clue(Some("newValue")), clue(RuntimeCache.get("key"))) } test("update - with level down") { @@ -95,7 +95,7 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(None, RuntimeCache.get("nonexistent")) + assertEquals(None, clue(RuntimeCache.get("nonexistent"))) } /* @@ -125,9 +125,9 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(GlobalLevel) - assertEquals(None, RuntimeCache.get("key1")) - assertEquals(None, RuntimeCache.get("key2")) - assertEquals(None, RuntimeCache.get("key3")) + assertEquals(None, clue(RuntimeCache.get("key1"))) + assertEquals(None, clue(RuntimeCache.get("key2"))) + assertEquals(None, clue(RuntimeCache.get("key3"))) } test("expire - suite level") { @@ -136,8 +136,8 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(SuiteLevel) - assertEquals(None, RuntimeCache.get("key1")) - assertEquals(None, RuntimeCache.get("key2")) + assertEquals(None, clue(RuntimeCache.get("key1"))) + assertEquals(None, clue(RuntimeCache.get("key2"))) } test("expire - test level") { @@ -146,8 +146,8 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(None, RuntimeCache.get("key2")) - assertEquals(RuntimeCache.get("key1"), Some("value1")) + assertEquals(None, clue(RuntimeCache.get("key2"))) + assertEquals(clue(Some("value1")), clue(RuntimeCache.get("key1"))) } /* @@ -161,9 +161,9 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.reset() - assertEquals(None, RuntimeCache.get("key1")) - assertEquals(None, RuntimeCache.get("key2")) - assertEquals(None, RuntimeCache.get("key3")) + assertEquals(None, clue(RuntimeCache.get("key1"))) + assertEquals(None, clue(RuntimeCache.get("key2"))) + assertEquals(None, clue(RuntimeCache.get("key3"))) } /* @@ -171,10 +171,10 @@ class RuntimeCacheTest extends FunSuite { */ test("determineLevel") { - assertEquals(RuntimeCache.determineLevel("global"), GlobalLevel) - assertEquals(RuntimeCache.determineLevel("suite"), SuiteLevel) - assertEquals(RuntimeCache.determineLevel("test"), TestLevel) - assertEquals(RuntimeCache.determineLevel("unknown"), TestLevel) + assertEquals(GlobalLevel, clue(RuntimeCache.determineLevel("global"))) + assertEquals(SuiteLevel, clue(RuntimeCache.determineLevel("suite"))) + assertEquals(TestLevel, clue(RuntimeCache.determineLevel("test"))) + assertEquals(TestLevel, clue(RuntimeCache.determineLevel("unknown"))) } /* @@ -183,11 +183,11 @@ class RuntimeCacheTest extends FunSuite { test("resolve") { RuntimeCache.put("key", "value") - assertEquals(RuntimeCache.resolve("{{ cache.key }}"), "value") + assertEquals("value", clue(RuntimeCache.resolve("{{ cache.key }}"))) } test("resolve - key not exist") { - intercept[NoSuchElementException] { + interceptMessage[NoSuchElementException]("Key not found in cache: notExist") { RuntimeCache.resolve("{{ cache.notExist }}") } } @@ -201,22 +201,22 @@ class RuntimeCacheTest extends FunSuite { test("resolve - no placeholder to resolve") { RuntimeCache.put("key", "value") - assertEquals(RuntimeCache.resolve("cache.key"), "cache.key") + assertEquals("cache.key", clue(RuntimeCache.resolve("cache.key"))) } test("resolve - mixed placeholders") { RuntimeCache.put("key", "value") - assertEquals(RuntimeCache.resolve("{{ cache.key }} and {{ not.cache.key }}"), "value and {{ not.cache.key }}") + assertEquals("value and {{ not.cache.key }}", clue(RuntimeCache.resolve("{{ cache.key }} and {{ not.cache.key }}"))) } test("resolve - empty key") { - intercept[NoSuchElementException] { + interceptMessage[NoSuchElementException]("Key not found in cache: ") { RuntimeCache.resolve("{{ cache. }}") } } test("resolve - empty value") { RuntimeCache.put("key", "") - assertEquals(RuntimeCache.resolve("{{ cache.key }}"), "") + assertEquals("", clue(RuntimeCache.resolve("{{ cache.key }}"))) } } From 02a24474d8c7e60091272f42e3c5542b9b39efa6 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 6 Oct 2023 10:15:16 +0200 Subject: [PATCH 14/31] * Fix - replaced tuple by new CookieValue class. --- .../scapi/json/ReferenceResolver.scala | 2 +- .../testing/scapi/json/SuiteFactory.scala | 3 +- .../request/sender/ScAPIRequestSender.scala | 5 +- .../response/AssertResponseActionType.scala | 60 ------------------- .../scapi/rest/response/Response.scala | 11 +++- .../AssertionResponseAction.scala | 13 ++-- .../ExtractJsonResponseAction.scala | 7 ++- .../{ => action}/LogResponseAction.scala | 7 ++- .../enum/AssertResponseActionType.scala | 58 ++++++++++++++++++ .../ExtractJsonResponseActionType.scala | 6 +- .../{ => enum}/LogResponseActionType.scala | 12 ++-- .../{ => enum}/ResponseActionGroupType.scala | 2 +- .../response/ResponseAssertionsTest.scala | 15 +++-- .../rest/response/ResponseExtractTest.scala | 2 + .../scapi/rest/response/ResponseLogTest.scala | 3 +- .../scapi/suite/runner/SuiteRunnerTest.scala | 2 +- 16 files changed, 111 insertions(+), 97 deletions(-) delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => action}/AssertionResponseAction.scala (98%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => action}/ExtractJsonResponseAction.scala (96%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => action}/LogResponseAction.scala (95%) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => enum}/ExtractJsonResponseActionType.scala (84%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => enum}/LogResponseActionType.scala (74%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ => enum}/ResponseActionGroupType.scala (94%) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index eff24c0..7e25103 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.rest.response.ResponseActionGroupType.ResponseActionGroupType +import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType.ResponseActionGroupType import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedConstantsInPropertiesException} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index a24c695..7bcc5a5 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -21,7 +21,8 @@ import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSche import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} -import africa.absa.testing.scapi.rest.response.{Response, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.Response +import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType import africa.absa.testing.scapi.utils.file.{FileUtils, JsonUtils} import spray.json._ diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala index 8a1e41e..80456a2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/request/sender/ScAPIRequestSender.scala @@ -16,6 +16,7 @@ package africa.absa.testing.scapi.rest.request.sender +import africa.absa.testing.scapi.rest.model.CookieValue import africa.absa.testing.scapi.rest.response.Response import java.net.HttpCookie @@ -31,9 +32,9 @@ object ScAPIRequestSender extends RequestSender { val response = requestFunc val endTime = System.nanoTime() - val extractedCookies: Map[String, (String, Boolean)] = response.cookies.view.map { + val extractedCookies: Map[String, CookieValue] = response.cookies.view.map { case (name, cookie: HttpCookie) => - (name, (cookie.getValue, cookie.getSecure)) + (name, CookieValue(cookie.getValue, cookie.getSecure)) }.toMap Response( diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala deleted file mode 100644 index 4ab1153..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertResponseActionType.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.rest.response - -import africa.absa.testing.scapi.rest.response - -import scala.language.implicitConversions - -object AssertResponseActionType extends Enumeration { - type AssertResponseActionType = Value - - // response-time-... - val RESPONSE_TIME_IS_BELOW: response.AssertResponseActionType.Value = Value("response-time-is-below") - val RESPONSE_TIME_IS_ABOVE: response.AssertResponseActionType.Value = Value("response-time-is-above") - - // status-code-... - val STATUS_CODE_EQUALS: response.AssertResponseActionType.Value = Value("status-code-equals") - val STATUS_CODE_IS_SUCCESS: response.AssertResponseActionType.Value = Value("status-code-is-success") - val STATUS_CODE_IS_CLIENT_ERROR: response.AssertResponseActionType.Value = Value("status-code-is-client-error") - val STATUS_CODE_IS_SERVER_ERROR: response.AssertResponseActionType.Value = Value("status-code-is-server-error") - - // header-... - val HEADER_EXISTS: response.AssertResponseActionType.Value = Value("header-exists") - val HEADER_VALUE_EQUALS: response.AssertResponseActionType.Value = Value("header-value-equals") - - // content-type-... - val CONTENT_TYPE_IS_JSON: response.AssertResponseActionType.Value = Value("content-type-is-json") - val CONTENT_TYPE_IS_XML: response.AssertResponseActionType.Value = Value("content-type-is-xml") - val CONTENT_TYPE_IS_HTML: response.AssertResponseActionType.Value = Value("content-type-is-html") - - // cookies-... - val COOKIE_EXISTS: response.AssertResponseActionType.Value = Value("cookie-exists") - val COOKIE_VALUE_EQUALS: response.AssertResponseActionType.Value = Value("cookie-value-equals") - val COOKIE_IS_SECURED: response.AssertResponseActionType.Value = Value("cookie-is-secured") - val COOKIE_IS_NOT_SECURED: response.AssertResponseActionType.Value = Value("cookie-is-not-secured") - - // body-... - val BODY_CONTAINS_TEXT: response.AssertResponseActionType.Value = Value("body-contains-text") - - private val stringToValueMap = values.map(v => v.toString -> v).toMap - - def fromString(s: String): Option[AssertResponseActionType] = stringToValueMap.get(s) - - // Implicit conversion from AssertResponseActionType to String - implicit def enumValueToString(value: AssertResponseActionType): String = value.toString -} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index df4ca6b..2db6cb2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -18,10 +18,19 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger +import africa.absa.testing.scapi.rest.model.CookieValue +import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType +import africa.absa.testing.scapi.rest.response.action.{AssertionResponseAction, ExtractJsonResponseAction, LogResponseAction} import scala.util.{Failure, Success, Try} -case class Response(statusCode: Int, body: String, url: String, statusMessage: String, headers: Map[String, Seq[String]], cookies: Map[String, (String, Boolean)], duration: Long) +case class Response(statusCode: Int, + body: String, + url: String, + statusMessage: String, + headers: Map[String, Seq[String]], + cookies: Map[String, CookieValue], + duration: Long) /** * A singleton object that is responsible for managing and handling responses. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala similarity index 98% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala index dda803c..aaf56fb 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala @@ -14,14 +14,15 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.action -import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger +import africa.absa.testing.scapi.rest.response.`enum`.AssertResponseActionType._ +import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} import africa.absa.testing.scapi.utils.validation.ContentValidator +import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import spray.json._ -import africa.absa.testing.scapi.rest.response.AssertResponseActionType._ import scala.util.{Failure, Success, Try} import scala.xml.XML @@ -385,7 +386,7 @@ object AssertionResponseAction extends ResponsePerformer { */ private def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (response.cookies(cookieName)._1 == expectedValue) { + if (response.cookies(cookieName).value == expectedValue) { Success(()) } else { Failure(AssertionException(s"Cookie '$cookieName' value does not match expected value '$expectedValue'.")) @@ -402,7 +403,7 @@ object AssertionResponseAction extends ResponsePerformer { */ private def assertCookieIsSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (response.cookies(cookieName)._2) { + if (response.cookies(cookieName).secured) { Success(()) } else { Failure(AssertionException(s"Cookie '$cookieName' is not secured.")) @@ -419,7 +420,7 @@ object AssertionResponseAction extends ResponsePerformer { */ private def assertCookieIsNotSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (!response.cookies(cookieName)._2) { + if (!response.cookies(cookieName).secured) { Success(()) } else { Failure(AssertionException(s"Cookie '$cookieName' is secured.")) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala similarity index 96% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala index 8d1d000..503405f 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala @@ -14,15 +14,16 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.action -import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger +import africa.absa.testing.scapi.rest.response.`enum`.ExtractJsonResponseActionType._ +import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator +import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import spray.json._ -import africa.absa.testing.scapi.rest.response.ExtractJsonResponseActionType._ import scala.util.{Failure, Success, Try} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala similarity index 95% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index efaa53c..884a9d7 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -14,13 +14,14 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.action -import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.LogResponseActionType._ +import africa.absa.testing.scapi.rest.response.`enum`.LogResponseActionType._ +import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} import africa.absa.testing.scapi.utils.validation.ContentValidator +import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} import scala.util.{Failure, Success, Try} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala new file mode 100644 index 0000000..31f7dab --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.response.`enum` + +import scala.language.implicitConversions + +object AssertResponseActionType extends Enumeration { + type AssertResponseActionType = Value + + // response-time-... + val RESPONSE_TIME_IS_BELOW: AssertResponseActionType.Value = Value("response-time-is-below") + val RESPONSE_TIME_IS_ABOVE: AssertResponseActionType.Value = Value("response-time-is-above") + + // status-code-... + val STATUS_CODE_EQUALS: AssertResponseActionType.Value = Value("status-code-equals") + val STATUS_CODE_IS_SUCCESS: AssertResponseActionType.Value = Value("status-code-is-success") + val STATUS_CODE_IS_CLIENT_ERROR: AssertResponseActionType.Value = Value("status-code-is-client-error") + val STATUS_CODE_IS_SERVER_ERROR: AssertResponseActionType.Value = Value("status-code-is-server-error") + + // header-... + val HEADER_EXISTS: AssertResponseActionType.Value = Value("header-exists") + val HEADER_VALUE_EQUALS: AssertResponseActionType.Value = Value("header-value-equals") + + // content-type-... + val CONTENT_TYPE_IS_JSON: AssertResponseActionType.Value = Value("content-type-is-json") + val CONTENT_TYPE_IS_XML: AssertResponseActionType.Value = Value("content-type-is-xml") + val CONTENT_TYPE_IS_HTML: AssertResponseActionType.Value = Value("content-type-is-html") + + // cookies-... + val COOKIE_EXISTS: AssertResponseActionType.Value = Value("cookie-exists") + val COOKIE_VALUE_EQUALS: AssertResponseActionType.Value = Value("cookie-value-equals") + val COOKIE_IS_SECURED: AssertResponseActionType.Value = Value("cookie-is-secured") + val COOKIE_IS_NOT_SECURED: AssertResponseActionType.Value = Value("cookie-is-not-secured") + + // body-... + val BODY_CONTAINS_TEXT: AssertResponseActionType.Value = Value("body-contains-text") + + private val stringToValueMap = values.map(v => v.toString -> v).toMap + + def fromString(s: String): Option[AssertResponseActionType] = stringToValueMap.get(s) + + // Implicit conversion from AssertResponseActionType to String + implicit def enumValueToString(value: AssertResponseActionType): String = value.toString +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala similarity index 84% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala index 2849396..7706f6d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ExtractJsonResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala @@ -14,16 +14,14 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response - -import africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.`enum` import scala.language.implicitConversions object ExtractJsonResponseActionType extends Enumeration { type ExtractJsonResponseActionType = Value - val STRING_FROM_LIST: response.ExtractJsonResponseActionType.Value = Value("string-from-list") + val STRING_FROM_LIST: ExtractJsonResponseActionType.Value = Value("string-from-list") private val stringToValueMap = values.map(v => v.toString -> v).toMap diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala similarity index 74% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala index 1bcf2f6..6b82d42 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/LogResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala @@ -14,19 +14,17 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response - -import africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.`enum` import scala.language.implicitConversions object LogResponseActionType extends Enumeration { type LogResponseActionType = Value - val ERROR: response.LogResponseActionType.Value = Value("error") - val WARN: response.LogResponseActionType.Value = Value("warn") - val INFO: response.LogResponseActionType.Value = Value("info") - val DEBUG: response.LogResponseActionType.Value = Value("debug") + val ERROR: LogResponseActionType.Value = Value("error") + val WARN: LogResponseActionType.Value = Value("warn") + val INFO: LogResponseActionType.Value = Value("info") + val DEBUG: LogResponseActionType.Value = Value("debug") private val stringToValueMap = values.map(v => v.toString -> v).toMap diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala similarity index 94% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala index 58a12f0..789e1f9 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponseActionGroupType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.`enum` object ResponseActionGroupType extends Enumeration { val ASSERT, EXTRACT_JSON, LOG = Value diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 6a4e035..c490d7b 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -17,6 +17,9 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.rest.model.CookieValue +import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.action.AssertionResponseAction import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import munit.FunSuite @@ -400,28 +403,28 @@ class ResponseAssertionsTest extends FunSuite { test("performAssertions - cookie exists") { val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isSuccess) } test("performAssertions - cookie does not exists") { val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "anotherCookie")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("", false)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isFailure) } test("performAssertions - cookie value is equals") { val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("cookieValue", false)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "cookieValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isSuccess) } test("performAssertions - cookie value is not equals") { val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> ("anotherValue", false)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "anotherValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } @@ -435,7 +438,7 @@ class ResponseAssertionsTest extends FunSuite { test("performAssertions - cookie is secured") { val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_SECURED, Map("cookieName" -> "securedCookie")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> ("someValue", true)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> CookieValue(value = "someValue", secured = true)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isSuccess) } @@ -449,7 +452,7 @@ class ResponseAssertionsTest extends FunSuite { test("performAssertions - cookie is not secured") { val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "notSecuredCookie")) - val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> ("someValue", false)), 100) + val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> CookieValue(value = "someValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isSuccess) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index 7d3dd30..e867e3f 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -18,6 +18,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.rest.response.`enum`.{ExtractJsonResponseActionType, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.action.ExtractJsonResponseAction import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index a1898da..4de298c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -17,7 +17,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction -import africa.absa.testing.scapi.rest.response.{LogResponseActionType => LogType} +import africa.absa.testing.scapi.rest.response.`enum`.{ResponseActionGroupType, LogResponseActionType => LogType} +import africa.absa.testing.scapi.rest.response.action.LogResponseAction import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index bc64f83..edfba22 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -21,7 +21,7 @@ import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.rest.response.{AssertResponseActionType, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite import org.apache.logging.log4j.Level From 11293dcc6b1762816cfcd832e4fa189b42882327 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 6 Oct 2023 10:15:37 +0200 Subject: [PATCH 15/31] * Fix - add missed class file. --- .../scapi/rest/model/CookieValue.scala | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/rest/model/CookieValue.scala diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/model/CookieValue.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/model/CookieValue.scala new file mode 100644 index 0000000..12ee53d --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/model/CookieValue.scala @@ -0,0 +1,19 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.rest.model + +case class CookieValue(value: String, secured: Boolean) From 0227000d682936650cd970317a5ef02ca3451ba8 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 6 Oct 2023 10:56:53 +0200 Subject: [PATCH 16/31] * Fix - review of code warnings. * Fix - update of visibility on methods and attributes. * Fix - removed old no more used object LoggerConfig. --- .../scapi/config/ScAPIRunnerConfig.scala | 8 ++-- .../testing/scapi/json/SuiteFactory.scala | 15 +++--- .../json/schema/JsonSchemaValidator.scala | 8 ++-- .../testing/scapi/logging/LoggerConfig.scala | 21 --------- .../scapi/rest/response/Response.scala | 2 +- .../response/action/LogResponseAction.scala | 2 +- .../scapi/suite/runner/SuiteRunner.scala | 46 ++++++++++--------- .../scapi/utils/cache/RuntimeCache.scala | 3 +- .../utils/validation/ContentValidator.scala | 2 +- 9 files changed, 44 insertions(+), 63 deletions(-) delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/logging/LoggerConfig.scala diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/config/ScAPIRunnerConfig.scala b/testApi/src/main/scala/africa/absa/testing/scapi/config/ScAPIRunnerConfig.scala index 87f9be9..46cd9fa 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/config/ScAPIRunnerConfig.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/config/ScAPIRunnerConfig.scala @@ -115,23 +115,23 @@ object ScAPIRunnerConfig { opt[String]("filter") .optional() .action((value, config) => { config.copy(filter = value) }) - .text(s"Filter rule to select test definitions file (recursive) to include into test suite. Default is all '${DefaultFilter}'") + .text(s"Filter rule to select test definitions file (recursive) to include into test suite. Default is all '$DefaultFilter'") opt[Seq[String]]("categories") .optional() .valueName(",") .action((value, config) => { config.copy(categories = value.toSet) }) - .text(s"Select which test categories will be included into test suite. Default is all '${DefaultCategories}'") + .text(s"Select which test categories will be included into test suite. Default is all '$DefaultCategories'") opt[Int]("thread-count") .optional() .action((value, config) => { config.copy(threadCount = value) }) - .text(s"Maximum count of thread used to run test suite. Default is '${DefaultThreadCount}'") + .text(s"Maximum count of thread used to run test suite. Default is '$DefaultThreadCount'") opt[String]("file-format") .optional() .action((value, config) => { config.copy(fileFormat = value) }) - .text(s"Format of definition files. Default is all '${DefaultFileFormat}'") + .text(s"Format of definition files. Default is all '$DefaultFileFormat'") opt[String]("report") .optional() diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala index 7bcc5a5..c99e81b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala @@ -127,7 +127,7 @@ object SuiteFactory { * @param environmentMap The map containing environment variables. * @return A SuiteBundle instance. */ - def loadJsonSuiteBundle(suitePath: String, environmentMap: Map[String, String]): SuiteBundle = { + private def loadJsonSuiteBundle(suitePath: String, environmentMap: Map[String, String]): SuiteBundle = { val (suiteFilePath, suiteFileName) = FileUtils.splitPathAndFileName(suitePath) val suiteName = suiteFileName.stripSuffix(".suite.json") @@ -189,7 +189,8 @@ object SuiteFactory { * @param extension The file extension. * @param parser The parser function used to parse JSON string. * @return A Suite instance. - */ def loadJsonSuite[T <: SuiteAround](suiteFilePath: String, + */ + private def loadJsonSuite[T <: SuiteAround](suiteFilePath: String, suiteName: String, properties: Map[String, String], jsonSchema: URL, @@ -212,7 +213,7 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A SuiteConstants instance. */ - def parseToSuiteConstant(jsonString: String): SuiteConstants = { + private def parseToSuiteConstant(jsonString: String): SuiteConstants = { import SuiteConstantJsonProtocol.suiteConstantFormat jsonString.parseJson.convertTo[SuiteConstants] } @@ -223,7 +224,7 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A SuiteBefore instance. */ - def parseToSuiteBefore(jsonString: String): SuiteBefore = { + private def parseToSuiteBefore(jsonString: String): SuiteBefore = { import SuiteBeforeJsonProtocol.suiteBeforeFormat jsonString.parseJson.convertTo[SuiteBefore] } @@ -234,7 +235,7 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A SuiteAfter instance. */ - def parseToSuiteAfter(jsonString: String): SuiteAfter = { + private def parseToSuiteAfter(jsonString: String): SuiteAfter = { import SuiteAfterJsonProtocol.suiteAfterFormat jsonString.parseJson.convertTo[SuiteAfter] } @@ -245,7 +246,7 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A Suite instance. */ - def parseToSuite(jsonString: String): Suite = { + private def parseToSuite(jsonString: String): Suite = { import SuiteJsonProtocol.suiteFormat jsonString.parseJson.convertTo[Suite] } @@ -333,7 +334,7 @@ object ResponseActionJsonProtocol extends DefaultJsonProtocol { val paramFields = a.params.view.mapValues(JsString(_)).toSeq - JsObject((fixedFields ++ paramFields): _*) + JsObject(fixedFields ++ paramFields: _*) } def read(value: JsValue): ResponseAction = { diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala index 3730f42..1531dd7 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/schema/JsonSchemaValidator.scala @@ -31,28 +31,28 @@ import java.net.URL * @param schemaPath Path to the JSON Schema file. */ case class JsonSchemaValidator(jsonPath: String, schemaPath: URL) { - protected val mapper: ObjectMapper = new ObjectMapper() + private val mapper: ObjectMapper = new ObjectMapper() /** * Method to read JSON data from the specified file path. * * @return JsonNode object representing the JSON data. */ - def jsonNode: JsonNode = mapper.readTree(JsonUtils.stringFromPath(jsonPath)) + private def jsonNode: JsonNode = mapper.readTree(JsonUtils.stringFromPath(jsonPath)) /** * Method to create a JsonSchemaFactory instance. * * @return JsonSchemaFactory instance. */ - def jsonSchemaFactory: JsonSchemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012) + private def jsonSchemaFactory: JsonSchemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012) /** * Method to generate a JsonSchema from the provided schema file path. * * @return JsonSchema object representing the JSON schema. */ - def jsonSchema: JsonSchema = jsonSchemaFactory.getSchema(JsonUtils.stringFromPath(schemaPath)) + private def jsonSchema: JsonSchema = jsonSchemaFactory.getSchema(JsonUtils.stringFromPath(schemaPath)) /** * Method to validate the JSON data against the provided schema. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/logging/LoggerConfig.scala b/testApi/src/main/scala/africa/absa/testing/scapi/logging/LoggerConfig.scala deleted file mode 100644 index db00150..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/logging/LoggerConfig.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.logging - -object LoggerConfig { - var logLevel: String = _ -} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 2db6cb2..0106435 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -73,7 +73,7 @@ object Response { | Required Response-Action: | Group->'${resolvedResponseAction.group}', | Method->'${resolvedResponseAction.name}', - | Params->'${filteredParams}', + | Params->'$filteredParams', | Actual Response: | $response""".stripMargin val exceptionLog = exception.map(e => s"\nException: ${e.getMessage}").getOrElse("") diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index 884a9d7..e8baaa2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -45,7 +45,7 @@ object LogResponseAction extends ResponsePerformer { case Some(message) => ContentValidator.validateNonEmptyString(message, s"ResponseLog.${responseAction.name}.message") case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion ${responseAction.name} logic.") } - case _ => throw UndefinedResponseActionTypeException(responseAction.name.toString) + case _ => throw UndefinedResponseActionTypeException(responseAction.name) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index eac3010..f65a456 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -31,7 +31,7 @@ import scala.util.{Failure, Try} * Main object handling the running of test suites. */ object SuiteRunner { - type RestClientCreator = () => RestClient + private type RestClientCreator = () => RestClient /** * Run a set of test suites. @@ -86,16 +86,11 @@ object SuiteRunner { * @return SuiteResults after the execution of the suite-before method. */ private def runSuiteBefore(suiteEndpoint: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { - Logger.debug(s"Suite-Before: ${suiteBeforeName} - Started") + Logger.debug(s"Suite-Before: $suiteBeforeName - Started") val testStartTime: Long = System.currentTimeMillis() try { - val response: Response = sendRequest(method, environment, restClientCreator) - val result: Try[Unit] = Response.perform( - response = response, - responseAction = method.responseActions - ) - + val result: Try[Unit] = processRequest(method, environment, restClientCreator) val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Before: method '${method.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( @@ -123,12 +118,7 @@ object SuiteRunner { val testStartTime: Long = System.currentTimeMillis() try { - val response: Response = sendRequest(test, environment, restClientCreator) - val result: Try[Unit] = Response.perform( - response = response, - responseAction = test.responseActions - ) - + val result: Try[Unit] = processRequest(test, environment, restClientCreator) val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Test: '${test.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( @@ -157,16 +147,11 @@ object SuiteRunner { * @return SuiteResults after the execution of the suite-after method. */ private def runSuiteAfter(suiteEndpoint: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { - Logger.debug(s"Suite-After: ${suiteAfterName} - Started") + Logger.debug(s"Suite-After: $suiteAfterName - Started") val testStartTime: Long = System.currentTimeMillis() try { - val response: Response = sendRequest(method, environment, restClientCreator) - val result: Try[Unit] = Response.perform( - response = response, - responseAction = method.responseActions - ) - + val result: Try[Unit] = processRequest(method, environment, restClientCreator) val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"After method '${method.name}' ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( @@ -199,6 +184,23 @@ object SuiteRunner { ) } + /** + * Process the request and perform the associated response actions. + * + * @param requestable The request-able method containing the actions and response actions. + * @param environment The current environment. + * @param restClientCreator A creator function for the REST client. + * @return A Try containing the result of the response actions. + */ + private def processRequest(requestable: Requestable, environment: Environment, restClientCreator: RestClientCreator): Try[Unit] = { + val response: Response = sendRequest(requestable, environment, restClientCreator) + val result: Try[Unit] = Response.perform( + response = response, + responseAction = requestable.responseActions + ) + result + } + /** * Handles exceptions occurring during suite running. * @@ -212,7 +214,7 @@ object SuiteRunner { private def handleException(e: Throwable, suiteEndpoint: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResult = { val testEndTime = System.currentTimeMillis() val message = e match { - case _ => s"Request exception occurred while running suite: ${suiteEndpoint}, ${resultType}: ${name}. Exception: ${e.getMessage}" + case _ => s"Request exception occurred while running suite: $suiteEndpoint, $resultType: $name. Exception: ${e.getMessage}" } Logger.error(message) resultType match { diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/utils/cache/RuntimeCache.scala b/testApi/src/main/scala/africa/absa/testing/scapi/utils/cache/RuntimeCache.scala index 99c6287..aaec997 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/utils/cache/RuntimeCache.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/utils/cache/RuntimeCache.scala @@ -130,10 +130,9 @@ object RuntimeCache { case "global" => GlobalLevel case "suite" => SuiteLevel case "test" => TestLevel - case _ => { + case _ => Logger.warn(s"Not known expiration cache level: '$level'. Used default TEST level.") TestLevel - } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala index b5727b4..94e5e81 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/utils/validation/ContentValidator.scala @@ -72,7 +72,7 @@ object ContentValidator { def validateNotNone(input: Option[String], paramName: String): Unit = { input match { case Some(_) => // do nothing, input is valid - case None => throw new ContentValidationFailedException(paramName, "Input cannot be None") + case None => throw ContentValidationFailedException(paramName, "Input cannot be None") } } } From 8b4c12e126c52507c653815cea2bb1bfaabef9df Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Mon, 9 Oct 2023 13:16:45 +0200 Subject: [PATCH 17/31] * Fix - Removed no more used class and object TestResults.scala. * Rename of variable in code to fit to real usage. --- .../absa/testing/scapi/ScAPIRunner.scala | 4 +- .../testing/scapi/model/TestResults.scala | 42 ------------------- 2 files changed, 2 insertions(+), 44 deletions(-) delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/TestResults.scala diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala index cc6c724..c83038b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala @@ -59,8 +59,8 @@ object ScAPIRunner { Logger.info("Validate only => end run.") } else { Logger.info("Running tests") - val testResults: List[SuiteResult] = SuiteRunner.runSuites(suiteBundles, environment, () => new RestClient(ScAPIRequestSender)) - StdOutReporter.printReport(testResults) + val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suiteBundles, environment, () => new RestClient(ScAPIRequestSender)) + StdOutReporter.printReport(suiteResults) } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/TestResults.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/TestResults.scala deleted file mode 100644 index d78474c..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/TestResults.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.model - -case class TestResults(suiteName: String, - testName: String, - status: String, - duration: Option[Long] = None, - errMessage: Option[String] = None, - categories: Option[String] = None) - -object TestResults { - val Success: String = "Success" - val Failure: String = "Failure" - - def withBooleanStatus(suiteName: String, - testName: String, - status: Boolean, - duration: Option[Long] = None, - errMessage: Option[String] = None, - categories: Option[String] = None): TestResults = - TestResults(suiteName = suiteName, - testName = testName, - status = if (status) Success else Failure, - duration = duration, - errMessage = errMessage, - categories = categories) -} From 1aa261be28604354362175ab0c0de8726e3793cd Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 12:32:09 +0200 Subject: [PATCH 18/31] * Fix - moved Factory classes to dedicated package. * Fix - moved Suite related models classes to new suite package in model package. --- .../main/scala/africa/absa/testing/scapi/ScAPIRunner.scala | 5 +++-- .../scapi/json/{ => factory}/EnvironmentFactory.scala | 3 ++- .../absa/testing/scapi/json/{ => factory}/SuiteFactory.scala | 4 +++- .../africa/absa/testing/scapi/model/{ => suite}/Method.scala | 2 +- .../africa/absa/testing/scapi/model/{ => suite}/Suite.scala | 2 +- .../absa/testing/scapi/model/{ => suite}/SuiteAfter.scala | 2 +- .../absa/testing/scapi/model/{ => suite}/SuiteAround.scala | 2 +- .../absa/testing/scapi/model/{ => suite}/SuiteBefore.scala | 2 +- .../absa/testing/scapi/model/{ => suite}/SuiteBundle.scala | 2 +- .../absa/testing/scapi/model/{ => suite}/SuiteResult.scala | 4 ++-- .../testing/scapi/model/{ => suite}/SuiteResultType.scala | 2 +- .../testing/scapi/model/{ => suite}/SuiteTestScenario.scala | 2 +- .../africa/absa/testing/scapi/reporter/StdOutReporter.scala | 2 +- .../africa/absa/testing/scapi/suite/runner/SuiteRunner.scala | 2 +- .../absa/testing/scapi/json/EnvironmentFactoryTest.scala | 1 + .../africa/absa/testing/scapi/json/EnvironmentTest.scala | 1 + .../africa/absa/testing/scapi/json/SuiteFactoryTest.scala | 3 ++- .../absa/testing/scapi/reporter/StdOutReporterTest.scala | 2 +- .../absa/testing/scapi/suite/runner/SuiteRunnerTest.scala | 1 + 19 files changed, 26 insertions(+), 18 deletions(-) rename testApi/src/main/scala/africa/absa/testing/scapi/json/{ => factory}/EnvironmentFactory.scala (96%) rename testApi/src/main/scala/africa/absa/testing/scapi/json/{ => factory}/SuiteFactory.scala (98%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/Method.scala (97%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/Suite.scala (96%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteAfter.scala (95%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteAround.scala (96%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteBefore.scala (95%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteBundle.scala (96%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteResult.scala (93%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteResultType.scala (94%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/{ => suite}/SuiteTestScenario.scala (97%) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala index c83038b..fe0f1c6 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala @@ -17,9 +17,10 @@ package africa.absa.testing.scapi import africa.absa.testing.scapi.config.ScAPIRunnerConfig -import africa.absa.testing.scapi.json.{Environment, EnvironmentFactory, SuiteFactory} +import africa.absa.testing.scapi.json.factory.{EnvironmentFactory, SuiteFactory} +import africa.absa.testing.scapi.json.Environment import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.{SuiteBundle, SuiteResult} +import africa.absa.testing.scapi.model.suite.{SuiteBundle, SuiteResult} import africa.absa.testing.scapi.reporter.StdOutReporter import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.sender.ScAPIRequestSender diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/EnvironmentFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/EnvironmentFactory.scala similarity index 96% rename from testApi/src/main/scala/africa/absa/testing/scapi/json/EnvironmentFactory.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/json/factory/EnvironmentFactory.scala index ee9b9b8..157a54e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/EnvironmentFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/EnvironmentFactory.scala @@ -14,8 +14,9 @@ * limitations under the License. */ -package africa.absa.testing.scapi.json +package africa.absa.testing.scapi.json.factory +import africa.absa.testing.scapi.json.Environment import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSchema} import africa.absa.testing.scapi.utils.file.JsonUtils import spray.json._ diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala similarity index 98% rename from testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala index c99e81b..e3e8521 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala @@ -14,12 +14,14 @@ * limitations under the License. */ -package africa.absa.testing.scapi.json +package africa.absa.testing.scapi.json.factory import africa.absa.testing.scapi._ +import africa.absa.testing.scapi.json._ import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSchema} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ +import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteAfter, SuiteAround, SuiteBefore, SuiteBundle, SuiteTestScenario} import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Method.scala similarity index 97% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Method.scala index 1264bd4..9e2a742 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/Method.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Method.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseAction} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/Suite.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala similarity index 96% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/Suite.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala index ea4092d..61ae90e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/Suite.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite /** * A suite case class that represents a collection of test scenarios for a specific endpoint. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAfter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala similarity index 95% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAfter.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala index 36d6bde..e6b660d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAfter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite /** * Case class that represents a suite after methods. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAround.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala similarity index 96% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAround.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala index 388ebd8..b88a5d3 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteAround.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite /** * Abstract class that represents a suite support methods. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBefore.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala similarity index 95% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBefore.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala index e8fb895..35fbd37 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBefore.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite /** * Case class that represents a suite before methods. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBundle.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala similarity index 96% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBundle.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala index d7de8d2..076aea6 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteBundle.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite /** * Represents a suite of tests, with optional "before" and "after" setup/teardown. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala similarity index 93% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala index 71117fb..5aaca15 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResult.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala @@ -14,9 +14,9 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite -import africa.absa.testing.scapi.model.SuiteResultType.SuiteResultType +import africa.absa.testing.scapi.model.suite.SuiteResultType.SuiteResultType import scala.util.{Failure, Try} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala similarity index 94% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala index 4398c71..824d99d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteResultType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite object SuiteResultType extends Enumeration { val BEFORE_SUITE, TEST_SUITE, AFTER_SUITE = Value diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteTestScenario.scala similarity index 97% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteTestScenario.scala index 82282cf..9c58482 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/SuiteTestScenario.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteTestScenario.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model +package africa.absa.testing.scapi.model.suite import africa.absa.testing.scapi.json.{Action, Header, Requestable, ResponseAction} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala index 4905600..5b29a26 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.reporter -import africa.absa.testing.scapi.model.{SuiteResult, SuiteResultType} +import africa.absa.testing.scapi.model.suite.{SuiteResult, SuiteResultType} /** * A singleton object to manage the standard output reporting of test results. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index f65a456..a8df1bf 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.SuiteBeforeFailedException import africa.absa.testing.scapi.json.{Environment, Requestable} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.{Method, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite.{Method, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala index 98fe80c..f143072 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentFactoryTest.scala @@ -16,6 +16,7 @@ package africa.absa.testing.scapi.json +import africa.absa.testing.scapi.json.factory.EnvironmentFactory import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSchema} import africa.absa.testing.scapi.{JsonInvalidSchemaException, UndefinedConstantsInPropertiesException} import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala index ee73b71..3872dc5 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala @@ -17,6 +17,7 @@ package africa.absa.testing.scapi.json import africa.absa.testing.scapi.PropertyNotFoundException +import africa.absa.testing.scapi.json.factory.EnvironmentFactory import munit.FunSuite class EnvironmentTest extends FunSuite { diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index 86203e2..55a73e2 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -16,8 +16,9 @@ package africa.absa.testing.scapi.json +import africa.absa.testing.scapi.json.factory.SuiteFactory +import africa.absa.testing.scapi.model.suite.{Suite, SuiteBundle, SuiteTestScenario} import africa.absa.testing.scapi.{ProjectLoadFailedException, UndefinedConstantsInPropertiesException} -import africa.absa.testing.scapi.model.{Suite, SuiteBundle, SuiteTestScenario} import munit.FunSuite import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.core.LoggerContext diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index 12b1b6d..e8d07de 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -17,7 +17,7 @@ package africa.absa.testing.scapi.reporter import africa.absa.testing.scapi.AssertionException -import africa.absa.testing.scapi.model.{SuiteResult, SuiteResultType} +import africa.absa.testing.scapi.model.suite.{SuiteResult, SuiteResultType} import munit.FunSuite import java.io.ByteArrayOutputStream diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index edfba22..4d655dd 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -19,6 +19,7 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.json.{Action, Environment, Header, ResponseAction} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ +import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteAfter, SuiteBefore, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} From d51747d44b2076aee14c84b3679a573578f750d0 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 13:35:20 +0200 Subject: [PATCH 19/31] * Fix - rename Suite to TestSet. * Fix - rename SuiteAround to SuitePreAndPostProcessing. * Fix - rename SuiteBefore to BeforeTestSet * Fix - rename SuiteAfter to AfterTestSet * Fix - rename SuiteBundle to Suite * Fix - rename ResponsePerformer to ResponseActions * Fix - move ResponseAction related file into new package action * Fix - rename "endpoint" to "name" as this parameters is used as name for suite not as endpoint. --- .../main/resources/schema/suite.schema.json | 6 +- .../absa/testing/scapi/ScAPIRunner.scala | 4 +- .../scapi/json/factory/SuiteFactory.scala | 66 +++++++++---------- .../{SuiteAfter.scala => AfterTestSet.scala} | 6 +- ...{SuiteBefore.scala => BeforeTestSet.scala} | 6 +- .../testing/scapi/model/suite/Suite.scala | 22 ++----- .../scapi/model/suite/SuiteBundle.scala | 27 -------- ....scala => SuitePreAndPostProcessing.scala} | 4 +- .../testing/scapi/model/suite/TestSet.scala | 37 +++++++++++ .../action/AssertionResponseAction.scala | 4 +- .../action/ExtractJsonResponseAction.scala | 4 +- .../response/action/LogResponseAction.scala | 4 +- .../ResponseActions.scala} | 5 +- .../scapi/suite/runner/SuiteRunner.scala | 52 +++++++-------- .../undefinedConstantIssue.suite.json | 2 +- .../gui-controller/deleteQuestion.suite.json | 2 +- .../gui-controller/getUserCurrent.suite.json | 2 +- .../gui-controller/postQuestion.suite.json | 2 +- .../gui-controller/putQuestion.suite.json | 2 +- .../testing/scapi/json/SuiteFactoryTest.scala | 18 ++--- .../scapi/suite/runner/SuiteRunnerTest.scala | 48 +++++++------- 21 files changed, 162 insertions(+), 161 deletions(-) rename testApi/src/main/scala/africa/absa/testing/scapi/model/suite/{SuiteAfter.scala => AfterTestSet.scala} (85%) rename testApi/src/main/scala/africa/absa/testing/scapi/model/suite/{SuiteBefore.scala => BeforeTestSet.scala} (85%) delete mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala rename testApi/src/main/scala/africa/absa/testing/scapi/model/suite/{SuiteAround.scala => SuitePreAndPostProcessing.scala} (86%) create mode 100644 testApi/src/main/scala/africa/absa/testing/scapi/model/suite/TestSet.scala rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{ResponsePerformer.scala => action/ResponseActions.scala} (86%) diff --git a/testApi/src/main/resources/schema/suite.schema.json b/testApi/src/main/resources/schema/suite.schema.json index 79f5014..ea01388 100644 --- a/testApi/src/main/resources/schema/suite.schema.json +++ b/testApi/src/main/resources/schema/suite.schema.json @@ -7,9 +7,9 @@ "type": "object", "additionalProperties": true, "properties": { - "endpoint": { + "name": { "type": "string", - "description": "The user endpoint name which suite cover by tests." + "description": "The suite name." }, "tests": { "type": "array", @@ -20,7 +20,7 @@ } }, "required": [ - "endpoint", + "name", "tests" ], "title": "suite", diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala index fe0f1c6..328ea4f 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/ScAPIRunner.scala @@ -20,7 +20,7 @@ import africa.absa.testing.scapi.config.ScAPIRunnerConfig import africa.absa.testing.scapi.json.factory.{EnvironmentFactory, SuiteFactory} import africa.absa.testing.scapi.json.Environment import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.suite.{SuiteBundle, SuiteResult} +import africa.absa.testing.scapi.model.suite.{Suite, SuiteResult} import africa.absa.testing.scapi.reporter.StdOutReporter import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.sender.ScAPIRequestSender @@ -52,7 +52,7 @@ object ScAPIRunner { // jsons to objects val environment: Environment = EnvironmentFactory.fromFile(cmd.envPath) - val suiteBundles: Set[SuiteBundle] = SuiteFactory.fromFiles(environment, cmd.testRootPath, cmd.filter, cmd.fileFormat) + val suiteBundles: Set[Suite] = SuiteFactory.fromFiles(environment, cmd.testRootPath, cmd.filter, cmd.fileFormat) SuiteFactory.validateSuiteContent(suiteBundles) // run tests and result reporting - use categories for test filtering diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala index e3e8521..60366c8 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala @@ -21,7 +21,7 @@ import africa.absa.testing.scapi.json._ import africa.absa.testing.scapi.json.schema.{JsonSchemaValidator, ScAPIJsonSchema} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ -import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteAfter, SuiteAround, SuiteBefore, SuiteBundle, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite.{Method, TestSet, AfterTestSet, SuitePreAndPostProcessing, BeforeTestSet, Suite, SuiteTestScenario} import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType @@ -45,10 +45,10 @@ object SuiteFactory { * @param format The format of suite JSON files. * @return Set of Suite instances. */ - def fromFiles(environment: Environment, testRootPath: String, filter: String, format: String): Set[SuiteBundle] = { + def fromFiles(environment: Environment, testRootPath: String, filter: String, format: String): Set[Suite] = { // NOTE: format not used as json is only supported format in time od development - val suiteLoadingResults: Map[String, Try[SuiteBundle]] = { + val suiteLoadingResults: Map[String, Try[Suite]] = { val suiteJsonFiles = findSuiteJsonFiles(testRootPath, filter) val suiteTries = suiteJsonFiles.map { file => val suiteTry = Try(loadJsonSuiteBundle(file, environment.asMap())) @@ -59,7 +59,7 @@ object SuiteFactory { if (suiteLoadingResults.values.forall(_.isSuccess)) { Logger.info("All suites loaded.") - val suiteBundles: Set[SuiteBundle] = suiteLoadingResults.values.collect { + val suiteBundles: Set[Suite] = suiteLoadingResults.values.collect { case Success(suiteBundle) => suiteBundle }.toSet @@ -89,8 +89,8 @@ object SuiteFactory { * @param suiteBundles The set of SuiteBundles to be filtered. * @return A set of filtered SuiteBundles based on 'only' attribute. */ - def filterOnlyOrAll(suiteBundles: Set[SuiteBundle]): Set[SuiteBundle] = { - val (suitesWithOnlyTest, others) = suiteBundles.foldLeft((List.empty[SuiteBundle], List.empty[SuiteBundle])) { + def filterOnlyOrAll(suiteBundles: Set[Suite]): Set[Suite] = { + val (suitesWithOnlyTest, others) = suiteBundles.foldLeft((List.empty[Suite], List.empty[Suite])) { case ((onlySuites, normalSuites), suiteBundle) => val suite = suiteBundle.suite val onlyTests = suite.tests.filter(_.only.getOrElse(false)) @@ -98,7 +98,7 @@ object SuiteFactory { case 0 => (onlySuites, suiteBundle :: normalSuites) // No 'only' test case 1 => (suiteBundle.copy(suite = suite.copy(tests = onlyTests)) :: onlySuites, normalSuites) // Exactly one 'only' test case _ => - Logger.error(s"Suite ${suite.endpoint} has more than one test marked as only.") + Logger.error(s"Suite ${suite.name} has more than one test marked as only.") (onlySuites, normalSuites) // More than one 'only' test in a suite is an error } } @@ -107,9 +107,9 @@ object SuiteFactory { case 0 => others.toSet // If no suite with 'only' test(s), return all other suites case 1 => suitesWithOnlyTest.toSet // Only one 'only' test across all suites case _ => // More than one 'only' test across all suites is an error - val testNames = suitesWithOnlyTest.flatMap(suiteBundle => suiteBundle.suite.tests.map(test => s"${suiteBundle.suite.endpoint}.${test.name}")).mkString(", ") + val testNames = suitesWithOnlyTest.flatMap(suiteBundle => suiteBundle.suite.tests.map(test => s"${suiteBundle.suite.name}.${test.name}")).mkString(", ") Logger.error(s"Detected more than one test with defined only option. Tests: $testNames") - Set.empty[SuiteBundle] + Set.empty[Suite] } } @@ -129,7 +129,7 @@ object SuiteFactory { * @param environmentMap The map containing environment variables. * @return A SuiteBundle instance. */ - private def loadJsonSuiteBundle(suitePath: String, environmentMap: Map[String, String]): SuiteBundle = { + private def loadJsonSuiteBundle(suitePath: String, environmentMap: Map[String, String]): Suite = { val (suiteFilePath, suiteFileName) = FileUtils.splitPathAndFileName(suitePath) val suiteName = suiteFileName.stripSuffix(".suite.json") @@ -137,7 +137,7 @@ object SuiteFactory { // TODO - code proposal - will be solved in #4 // val functions: Map[String, String] = loadJsonSuiteFunctions(suiteFilePath, environmentMap) - val beforeActions: Option[SuiteBefore] = loadJsonSuite[SuiteBefore]( + val beforeActions: Option[BeforeTestSet] = loadJsonSuite[BeforeTestSet]( suiteFilePath, suiteName, environmentMap ++ suiteConstants.constants, @@ -145,7 +145,7 @@ object SuiteFactory { "before", parseToSuiteBefore ) - val afterActions: Option[SuiteAfter] = loadJsonSuite[SuiteAfter]( + val afterActions: Option[AfterTestSet] = loadJsonSuite[AfterTestSet]( suiteFilePath, suiteName, environmentMap ++ suiteConstants.constants, @@ -156,9 +156,9 @@ object SuiteFactory { JsonSchemaValidator.validate(suitePath, ScAPIJsonSchema.SUITE) val jsonString: String = JsonUtils.stringFromPath(suitePath) - val notResolvedSuite: Suite = parseToSuite(jsonString) - val resolvedSuite: Suite = notResolvedSuite.resolveReferences(environmentMap ++ suiteConstants.constants) - SuiteBundle(resolvedSuite, beforeActions, afterActions) + val notResolvedSuite: TestSet = parseToSuite(jsonString) + val resolvedSuite: TestSet = notResolvedSuite.resolveReferences(environmentMap ++ suiteConstants.constants) + Suite(resolvedSuite, beforeActions, afterActions) } /** @@ -192,12 +192,12 @@ object SuiteFactory { * @param parser The parser function used to parse JSON string. * @return A Suite instance. */ - private def loadJsonSuite[T <: SuiteAround](suiteFilePath: String, - suiteName: String, - properties: Map[String, String], - jsonSchema: URL, - extension: String, - parser: String => T): Option[T] = { + private def loadJsonSuite[T <: SuitePreAndPostProcessing](suiteFilePath: String, + suiteName: String, + properties: Map[String, String], + jsonSchema: URL, + extension: String, + parser: String => T): Option[T] = { val filePath: Path = Paths.get(suiteFilePath, s"$suiteName.$extension.json") if (!Files.exists(filePath)) { None @@ -226,9 +226,9 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A SuiteBefore instance. */ - private def parseToSuiteBefore(jsonString: String): SuiteBefore = { + private def parseToSuiteBefore(jsonString: String): BeforeTestSet = { import SuiteBeforeJsonProtocol.suiteBeforeFormat - jsonString.parseJson.convertTo[SuiteBefore] + jsonString.parseJson.convertTo[BeforeTestSet] } /** @@ -237,9 +237,9 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A SuiteAfter instance. */ - private def parseToSuiteAfter(jsonString: String): SuiteAfter = { + private def parseToSuiteAfter(jsonString: String): AfterTestSet = { import SuiteAfterJsonProtocol.suiteAfterFormat - jsonString.parseJson.convertTo[SuiteAfter] + jsonString.parseJson.convertTo[AfterTestSet] } /** @@ -248,9 +248,9 @@ object SuiteFactory { * @param jsonString The JSON string to be parsed. * @return A Suite instance. */ - private def parseToSuite(jsonString: String): Suite = { + private def parseToSuite(jsonString: String): TestSet = { import SuiteJsonProtocol.suiteFormat - jsonString.parseJson.convertTo[Suite] + jsonString.parseJson.convertTo[TestSet] } /** @@ -259,7 +259,7 @@ object SuiteFactory { * * @param suiteBundles The set of SuiteBundles to be validated. */ - def validateSuiteContent(suiteBundles: Set[SuiteBundle]): Unit = suiteBundles.foreach(validateSuiteContent) + def validateSuiteContent(suiteBundles: Set[Suite]): Unit = suiteBundles.foreach(validateSuiteContent) /** * This method validates the content of a SuiteBundle. @@ -267,8 +267,8 @@ object SuiteFactory { * * @param suiteBundle The SuiteBundle to be validated. */ - def validateSuiteContent(suiteBundle: SuiteBundle): Unit = { - Logger.debug(s"Validation content of suite: ${suiteBundle.suite.endpoint}") + def validateSuiteContent(suiteBundle: Suite): Unit = { + Logger.debug(s"Validation content of suite: ${suiteBundle.suite.name}") suiteBundle.suite.tests.foreach(test => { test.headers.foreach(header => RequestHeaders.validateContent(header)) RequestBody.validateContent(test.actions.head.body) @@ -288,7 +288,7 @@ object SuiteJsonProtocol extends DefaultJsonProtocol { implicit val responseActionsFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val suiteTestFormat: RootJsonFormat[SuiteTestScenario] = jsonFormat6(SuiteTestScenario) implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) - implicit val suiteFormat: RootJsonFormat[Suite] = jsonFormat2(Suite) + implicit val suiteFormat: RootJsonFormat[TestSet] = jsonFormat2(TestSet) } /** @@ -307,7 +307,7 @@ object SuiteBeforeJsonProtocol extends DefaultJsonProtocol { implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) implicit val responseActionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) - implicit val suiteBeforeFormat: RootJsonFormat[SuiteBefore] = jsonFormat2(SuiteBefore) + implicit val suiteBeforeFormat: RootJsonFormat[BeforeTestSet] = jsonFormat2(BeforeTestSet) } /** @@ -319,7 +319,7 @@ object SuiteAfterJsonProtocol extends DefaultJsonProtocol { implicit val testActionFormat: RootJsonFormat[Action] = jsonFormat4(Action) implicit val responseActionFormat: RootJsonFormat[ResponseAction] = ResponseActionJsonProtocol.ResponseActionJsonFormat implicit val methodFormat: RootJsonFormat[Method] = jsonFormat4(Method) - implicit val suiteAfterFormat: RootJsonFormat[SuiteAfter] = jsonFormat2(SuiteAfter) + implicit val suiteAfterFormat: RootJsonFormat[AfterTestSet] = jsonFormat2(AfterTestSet) } /** diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/AfterTestSet.scala similarity index 85% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/AfterTestSet.scala index e6b660d..cb85c2d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAfter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/AfterTestSet.scala @@ -22,9 +22,9 @@ package africa.absa.testing.scapi.model.suite * @param name The name of the after methods. * @param methods The set of suite after methods. */ -case class SuiteAfter(name: String, methods: Set[Method]) extends SuiteAround(name, methods) { - override def resolveReferences(references: Map[String, String]): SuiteAround = { - SuiteAfter( +case class AfterTestSet(name: String, methods: Set[Method]) extends SuitePreAndPostProcessing(name, methods) { + override def resolveReferences(references: Map[String, String]): SuitePreAndPostProcessing = { + AfterTestSet( name, methods.map(c => c.resolveReferences(references)) ) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/BeforeTestSet.scala similarity index 85% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/BeforeTestSet.scala index 35fbd37..d641532 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBefore.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/BeforeTestSet.scala @@ -22,9 +22,9 @@ package africa.absa.testing.scapi.model.suite * @param name The name of the before methods. * @param methods The set of suite before methods. */ -case class SuiteBefore(name: String, methods: Set[Method]) extends SuiteAround(name, methods) { - override def resolveReferences(references: Map[String, String]): SuiteAround = { - SuiteBefore( +case class BeforeTestSet(name: String, methods: Set[Method]) extends SuitePreAndPostProcessing(name, methods) { + override def resolveReferences(references: Map[String, String]): SuitePreAndPostProcessing = { + BeforeTestSet( name, methods.map(c => c.resolveReferences(references)) ) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala index 61ae90e..d072c75 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/Suite.scala @@ -17,21 +17,11 @@ package africa.absa.testing.scapi.model.suite /** - * A suite case class that represents a collection of test scenarios for a specific endpoint. + * Represents a suite of tests, with optional "before" and "after" setup/teardown. * - * @param endpoint The endpoint which the suite of tests is targeting. - * @param tests A set of `SuiteTestScenario` which define the tests in this suite. - * @constructor Creates a new instance of a Suite. + * @constructor Create a new suite bundle with a suite and optional "before" and "after" actions. + * @param suite The core suite of tests to be run. + * @param suiteBefore An optional SuiteBefore object, representing any setup actions to be run before the suite. + * @param suiteAfter An optional SuiteAfter object, representing any teardown actions to be run after the suite. */ -case class Suite(endpoint: String, tests: Set[SuiteTestScenario]) { - - /** - * Method to resolve references in the test scenarios using a provided map of references. - * - * @param references A map of string keys and values which will be used to resolve references in the test scenarios. - * @return Returns a new Suite with resolved references in its test scenarios. - */ - def resolveReferences(references: Map[String, String]): Suite = { - Suite(endpoint, tests.map(c => c.resolveReferences(references))) - } -} +case class Suite(suite: TestSet, suiteBefore: Option[BeforeTestSet] = None, suiteAfter: Option[AfterTestSet] = None) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala deleted file mode 100644 index 076aea6..0000000 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteBundle.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2023 ABSA Group Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package africa.absa.testing.scapi.model.suite - -/** - * Represents a suite of tests, with optional "before" and "after" setup/teardown. - * - * @constructor Create a new suite bundle with a suite and optional "before" and "after" actions. - * @param suite The core suite of tests to be run. - * @param suiteBefore An optional SuiteBefore object, representing any setup actions to be run before the suite. - * @param suiteAfter An optional SuiteAfter object, representing any teardown actions to be run after the suite. - */ -case class SuiteBundle(suite: Suite, suiteBefore: Option[SuiteBefore] = None, suiteAfter: Option[SuiteAfter] = None) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuitePreAndPostProcessing.scala similarity index 86% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuitePreAndPostProcessing.scala index b88a5d3..a654095 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteAround.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuitePreAndPostProcessing.scala @@ -22,12 +22,12 @@ package africa.absa.testing.scapi.model.suite * @param name The name of the after methods. * @param methods The set of suite after methods. */ -abstract class SuiteAround(name: String, methods: Set[Method]) { +abstract class SuitePreAndPostProcessing(name: String, methods: Set[Method]) { /** * Method to resolve references within the before methods instance. * * @param references A map containing the references to be resolved. * @return A new SuiteBefore instance where all references are resolved. */ - def resolveReferences(references: Map[String, String]): SuiteAround + def resolveReferences(references: Map[String, String]): SuitePreAndPostProcessing } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/TestSet.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/TestSet.scala new file mode 100644 index 0000000..086a9a2 --- /dev/null +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/TestSet.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2023 ABSA Group Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package africa.absa.testing.scapi.model.suite + +/** + * A suite case class that represents a collection of test scenarios. + * + * @param name The name of the suite. + * @param tests A set of `SuiteTestScenario` which define the tests in this suite. + * @constructor Creates a new instance of a Suite. + */ +case class TestSet(name: String, tests: Set[SuiteTestScenario]) { + + /** + * Method to resolve references in the test scenarios using a provided map of references. + * + * @param references A map of string keys and values which will be used to resolve references in the test scenarios. + * @return Returns a new Suite with resolved references in its test scenarios. + */ + def resolveReferences(references: Map[String, String]): TestSet = { + TestSet(name, tests.map(c => c.resolveReferences(references))) + } +} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala index aaf56fb..b41a9a2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.rest.response.`enum`.AssertResponseActionType._ -import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} +import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import spray.json._ @@ -31,7 +31,7 @@ import scala.xml.XML * Object that validates and performs various assertion response actions on the response received. * It extends the functionality of ResponsePerformer. */ -object AssertionResponseAction extends ResponsePerformer { +object AssertionResponseAction extends ResponseActions { /** * Validates the content of an assertion response action object depending on its type. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala index 503405f..5fd9721 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.rest.response.`enum`.ExtractJsonResponseActionType._ -import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} +import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} @@ -31,7 +31,7 @@ import scala.util.{Failure, Success, Try} * ExtractJsonResponseAction is an object that extends ResponsePerformer. * It is designed to extract specific data from a JSON response and perform validations. */ -object ExtractJsonResponseAction extends ResponsePerformer { +object ExtractJsonResponseAction extends ResponseActions { /** * Validates the content of an extract response action object depending on its type. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index e8baaa2..75aa9c6 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.rest.response.`enum`.LogResponseActionType._ -import africa.absa.testing.scapi.rest.response.{Response, ResponsePerformer} +import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} @@ -29,7 +29,7 @@ import scala.util.{Failure, Success, Try} * Singleton object `ResponseLog` that extends the `ResponsePerformer` trait. * It provides utilities for validating and performing logging messages. */ -object LogResponseAction extends ResponsePerformer { +object LogResponseAction extends ResponseActions { /** * Validates the content of an log response action object depending on its type. diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ResponseActions.scala similarity index 86% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ResponseActions.scala index 2cf45bd..8f3bcf9 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/ResponsePerformer.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ResponseActions.scala @@ -14,13 +14,14 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response +package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction +import africa.absa.testing.scapi.rest.response.Response import scala.util.Try -trait ResponsePerformer { +trait ResponseActions { def validateContent(responseAction: ResponseAction): Unit def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index a8df1bf..67d4420 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.SuiteBeforeFailedException import africa.absa.testing.scapi.json.{Environment, Requestable} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.suite.{Method, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteResult, SuiteResultType, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response @@ -40,34 +40,34 @@ object SuiteRunner { * @param environment The current environment. * @return Set of SuiteResults. */ - def runSuites(suiteBundles: Set[SuiteBundle], environment: Environment, restClientCreator: RestClientCreator): List[SuiteResult] = { + def runSuites(suiteBundles: Set[Suite], environment: Environment, restClientCreator: RestClientCreator): List[SuiteResult] = { suiteBundles.foldLeft(List[SuiteResult]()) { (resultList, suiteBundle) => - Logger.debug(s"Suite: ${suiteBundle.suite.endpoint} - Started") + Logger.debug(s"Suite: ${suiteBundle.suite.name} - Started") val suiteBeforeResult: List[SuiteResult] = suiteBundle.suiteBefore.toList.flatMap { suiteBefore => - suiteBefore.methods.map { method => runSuiteBefore(suiteBundle.suite.endpoint, suiteBefore.name, method, environment, restClientCreator) } + suiteBefore.methods.map { method => runSuiteBefore(suiteBundle.suite.name, suiteBefore.name, method, environment, restClientCreator) } } var suiteResult: List[SuiteResult] = List.empty var suiteAfterResult: List[SuiteResult] = List.empty if (!suiteBeforeResult.forall(_.isSuccess)) { - val errorMsg = s"Suite-Before for Suite: ${suiteBundle.suite.endpoint} has failed methods. Not executing main tests and Suite-After." + val errorMsg = s"Suite-Before for Suite: ${suiteBundle.suite.name} has failed methods. Not executing main tests and Suite-After." Logger.error(errorMsg) // add failed Test suite result instance and it will not be started suiteResult = suiteResult :+ SuiteResult( resultType = SuiteResultType.TEST_SUITE, - suiteName = suiteBundle.suite.endpoint, + suiteName = suiteBundle.suite.name, name = "SKIPPED", result = Failure(SuiteBeforeFailedException(errorMsg)), duration = Some(0L), categories = Some("SKIPPED")) } else { suiteResult = suiteBundle.suite.tests.toList.map(test => - this.runSuiteTest(suiteBundle.suite.endpoint, test, environment, restClientCreator)) + this.runSuiteTest(suiteBundle.suite.name, test, environment, restClientCreator)) suiteAfterResult = suiteBundle.suiteAfter.toList.flatMap { suiteAfter => - suiteAfter.methods.map { method => runSuiteAfter(suiteBundle.suite.endpoint, suiteAfter.name, method, environment, restClientCreator) } + suiteAfter.methods.map { method => runSuiteAfter(suiteBundle.suite.name, suiteAfter.name, method, environment, restClientCreator) } } } @@ -79,13 +79,13 @@ object SuiteRunner { /** * Runs all the suite-before methods for a given test suite. * - * @param suiteEndpoint Suite's endpoint. + * @param suiteName Suite's name. * @param suiteBeforeName SuiteBefore's name. * @param method Method to execute. * @param environment The current environment. * @return SuiteResults after the execution of the suite-before method. */ - private def runSuiteBefore(suiteEndpoint: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { + private def runSuiteBefore(suiteName: String, suiteBeforeName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-Before: $suiteBeforeName - Started") val testStartTime: Long = System.currentTimeMillis() @@ -95,25 +95,25 @@ object SuiteRunner { Logger.debug(s"Suite-Before: method '${method.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( resultType = SuiteResultType.BEFORE_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = method.name, result = result, duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteEndpoint, suiteBeforeName, testStartTime, "Before") + case e: Exception => handleException(e, suiteName, suiteBeforeName, testStartTime, "Before") } } /** * Runs all the suite-tests methods for a given test suite. * - * @param suiteEndpoint Suite's endpoint. + * @param suiteName Suite's name. * @param test The test to run. * @param environment The current environment. * @return SuiteResults after the execution of the suite-test. */ - private def runSuiteTest(suiteEndpoint: String, test: SuiteTestScenario, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { + private def runSuiteTest(suiteName: String, test: SuiteTestScenario, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-Test: ${test.name} - Started") val testStartTime: Long = System.currentTimeMillis() @@ -123,7 +123,7 @@ object SuiteRunner { Logger.debug(s"Suite-Test: '${test.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( resultType = SuiteResultType.TEST_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = test.name, result = result, duration = Some(testEndTime - testStartTime), @@ -131,7 +131,7 @@ object SuiteRunner { ) } catch { - case e: Exception => handleException(e, suiteEndpoint, test.name, testStartTime, "Test", Some(test.categories.mkString(","))) + case e: Exception => handleException(e, suiteName, test.name, testStartTime, "Test", Some(test.categories.mkString(","))) } finally { RuntimeCache.expire(TestLevel) } @@ -140,13 +140,13 @@ object SuiteRunner { /** * Runs all the suite-after methods for a given test suite. * - * @param suiteEndpoint Suite's endpoint. + * @param suiteName Suite's name. * @param suiteAfterName SuiteAfter's name. * @param method Method to execute. * @param environment The current environment. * @return SuiteResults after the execution of the suite-after method. */ - private def runSuiteAfter(suiteEndpoint: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { + private def runSuiteAfter(suiteName: String, suiteAfterName: String, method: Method, environment: Environment, restClientCreator: RestClientCreator): SuiteResult = { Logger.debug(s"Suite-After: $suiteAfterName - Started") val testStartTime: Long = System.currentTimeMillis() @@ -156,13 +156,13 @@ object SuiteRunner { Logger.debug(s"After method '${method.name}' ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( resultType = SuiteResultType.AFTER_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = method.name, result = result, duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteEndpoint, suiteAfterName, testStartTime, "After") + case e: Exception => handleException(e, suiteName, suiteAfterName, testStartTime, "After") } } @@ -205,29 +205,29 @@ object SuiteRunner { * Handles exceptions occurring during suite running. * * @param e The exception to handle. - * @param suiteEndpoint Suite's endpoint. + * @param suiteName Suite's name. * @param name The name of the suite or test. * @param testStartTime The starting time of the suite or test. * @param resultType The type of the suite or test ("Before", "Test", or "After"). * @return SuiteResults after the exception handling. */ - private def handleException(e: Throwable, suiteEndpoint: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResult = { + private def handleException(e: Throwable, suiteName: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResult = { val testEndTime = System.currentTimeMillis() val message = e match { - case _ => s"Request exception occurred while running suite: $suiteEndpoint, $resultType: $name. Exception: ${e.getMessage}" + case _ => s"Request exception occurred while running suite: $suiteName, $resultType: $name. Exception: ${e.getMessage}" } Logger.error(message) resultType match { case "Before" => SuiteResult( resultType = SuiteResultType.BEFORE_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = name, result = Failure(e), duration = Some(testEndTime - testStartTime)) case "Test" => SuiteResult( resultType = SuiteResultType.TEST_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = name, result = Failure(e), duration = Some(testEndTime - testStartTime), @@ -236,7 +236,7 @@ object SuiteRunner { case "After" => SuiteResult( resultType = SuiteResultType.AFTER_SUITE, - suiteName = suiteEndpoint, + suiteName = suiteName, name = name, result = Failure(e), duration = Some(testEndTime - testStartTime)) diff --git a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json index ef14988..0e2fc01 100644 --- a/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json +++ b/testApi/src/test/resources/project_with_issues/suites/aulgui-controller/undefinedConstantIssue.suite.json @@ -1,5 +1,5 @@ { - "endpoint" : "getUserCurrent", + "name" : "getUserCurrent", "tests": [ { "name" : "test-name-1", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json index ce5610c..adc4c21 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/deleteQuestion.suite.json @@ -1,5 +1,5 @@ { - "endpoint" : "deleteQuestion", + "name" : "deleteQuestion", "tests": [ { "name" : "test-name-1", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json index 5cd8bd0..15039e7 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/getUserCurrent.suite.json @@ -1,5 +1,5 @@ { - "endpoint" : "getUserCurrent", + "name" : "getUserCurrent", "tests": [ { "name" : "get current user", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json index 3f1540b..fe6cfe7 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/postQuestion.suite.json @@ -1,5 +1,5 @@ { - "endpoint" : "postQuestion", + "name" : "postQuestion", "tests": [ { "name" : "test-name-1", diff --git a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json index 39e3618..c6ca547 100644 --- a/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json +++ b/testApi/src/test/resources/test_project/suites/gui-controller/putQuestion.suite.json @@ -1,5 +1,5 @@ { - "endpoint" : "putQuestion", + "name" : "putQuestion", "tests": [ { "name" : "test-name-1", diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index 55a73e2..d73662a 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -17,7 +17,7 @@ package africa.absa.testing.scapi.json import africa.absa.testing.scapi.json.factory.SuiteFactory -import africa.absa.testing.scapi.model.suite.{Suite, SuiteBundle, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite.{TestSet, Suite, SuiteTestScenario} import africa.absa.testing.scapi.{ProjectLoadFailedException, UndefinedConstantsInPropertiesException} import munit.FunSuite import org.apache.logging.log4j.LogManager @@ -130,24 +130,24 @@ class SuiteFactoryTest extends FunSuite { */ test("filterOnlyOrAll - only used - once") { val suitesBundles = Set( - SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( + Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), - SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( + Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), - SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( + Suite(suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), )))) - val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) + val filteredSuiteBundles: Set[Suite] = SuiteFactory.filterOnlyOrAll(suitesBundles) assertEquals(filteredSuiteBundles.size, 1) val filteredSuite = filteredSuiteBundles.head.suite - assertEquals(clue("endpoint1"), clue(filteredSuite.endpoint)) + assertEquals(clue("name1"), clue(filteredSuite.name)) assertEquals(clue(1), clue(filteredSuite.tests.size)) val filteredTest = filteredSuite.tests.head @@ -157,15 +157,15 @@ class SuiteFactoryTest extends FunSuite { test("fromFile - only used - twice") { val suitesBundles = Set( - SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( + Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)) ))), - SuiteBundle(suite = Suite(endpoint = "endpoint2", tests = Set( + Suite(suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(true)), )))) - val filteredSuiteBundles: Set[SuiteBundle] = SuiteFactory.filterOnlyOrAll(suitesBundles) + val filteredSuiteBundles: Set[Suite] = SuiteFactory.filterOnlyOrAll(suitesBundles) assertEquals(clue(0), clue(filteredSuiteBundles.size)) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 4d655dd..4ace43f 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.json.{Action, Environment, Header, ResponseAction} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ -import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteAfter, SuiteBefore, SuiteBundle, SuiteResult, SuiteResultType, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} @@ -36,44 +36,44 @@ class SuiteRunnerTest extends FunSuite { val method: Method = Method(name = "test", headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction)) val methodNotSupported: Method = Method(name = "test", headers = Seq(header), actions = Seq(actionNotSupported), responseActions = Seq(responseAction)) - val suitesBundles: Set[SuiteBundle] = Set( - SuiteBundle(suite = Suite(endpoint = "endpoint1", tests = Set( + val suitesBundles: Set[Suite] = Set( + Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(true)), SuiteTestScenario(name = "test2", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(true)) ))), - SuiteBundle( - suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), - suite = Suite(endpoint = "endpoint2", tests = Set( + Suite( + suiteBefore = Some(BeforeTestSet(name = "suiteBefore", methods = Set(method))), + suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), - suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), + suiteAfter = Some(AfterTestSet(name = "suiteAfter", methods = Set(method))), )) - val suitesBundleNoBefore: Set[SuiteBundle] = Set( - SuiteBundle( - suite = Suite(endpoint = "endpoint2", tests = Set( + val suitesBundleNoBefore: Set[Suite] = Set( + Suite( + suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), - suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(method))), + suiteAfter = Some(AfterTestSet(name = "suiteAfter", methods = Set(method))), )) - val suitesBundleAfterMethodNotSupported: Set[SuiteBundle] = Set( - SuiteBundle( - suite = Suite(endpoint = "endpoint2", tests = Set( + val suitesBundleAfterMethodNotSupported: Set[Suite] = Set( + Suite( + suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )), - suiteAfter = Some(SuiteAfter(name = "suiteAfter", methods = Set(methodNotSupported))), + suiteAfter = Some(AfterTestSet(name = "suiteAfter", methods = Set(methodNotSupported))), )) - val suitesBundleNoAfter: Set[SuiteBundle] = Set( - SuiteBundle( - suiteBefore = Some(SuiteBefore(name = "suiteBefore", methods = Set(method))), - suite = Suite(endpoint = "endpoint2", tests = Set( + val suitesBundleNoAfter: Set[Suite] = Set( + Suite( + suiteBefore = Some(BeforeTestSet(name = "suiteBefore", methods = Set(method))), + suite = TestSet(name = "name2", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction), only = Some(false)), )))) @@ -105,7 +105,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2").get + result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "name2").get assertEquals(5, clue(suiteResults.size)) assertEquals("test", clue(beforeSuiteResult.name)) @@ -116,7 +116,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoBefore, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "endpoint2") + result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "name2") assertEquals(2, clue(suiteResults.size)) assert(beforeSuiteResult.isEmpty) @@ -126,7 +126,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2").get assertEquals(5, clue(suiteResults.size)) assertEquals("test", clue(afterSuiteResult.name)) @@ -137,7 +137,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoAfter, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2") + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2") assertEquals(2, clue(suiteResults.size)) assert(afterSuiteResult.isEmpty) @@ -147,7 +147,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleAfterMethodNotSupported, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "endpoint2").get + result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2").get assertEquals(2, clue(suiteResults.size)) assertEquals(false, clue(afterSuiteResult.isSuccess)) From 0f823566a8ba1af7ac857eec4776d44a79d4e298 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 13:38:25 +0200 Subject: [PATCH 20/31] * Fix - removed only keyword. --- .../africa/absa/testing/scapi/reporter/StdOutReporterTest.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index e8d07de..b921a05 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -89,7 +89,7 @@ class StdOutReporterTest extends FunSuite { assertEquals(true, clue(output.contains("End Report"))) } - test("full results with failed".only) { + test("full results with failed") { /* "Full": min 1 Success test From 2f579ace6aa8a071bed91051003afac85071a8cd Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 14:01:23 +0200 Subject: [PATCH 21/31] * Change: set jacoco-report debug to find source of logic failing. --- .github/workflows/ci-check-jacoco.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci-check-jacoco.yml b/.github/workflows/ci-check-jacoco.yml index 2d15347..8679ce6 100644 --- a/.github/workflows/ci-check-jacoco.yml +++ b/.github/workflows/ci-check-jacoco.yml @@ -28,6 +28,7 @@ jobs: min-coverage-changed-files: 80.0 title: JaCoCo code coverage report - ScAPI update-comment: true + debug: true - name: Get the Coverage info run: | echo "Total coverage ${{ steps.jacoco.outputs.coverage-overall }}" From f353d5461619a5300de262f2e92ed395d9a10c72 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 14:03:29 +0200 Subject: [PATCH 22/31] * Change: set jacoco-report debug to find source of logic failing. --- .github/workflows/ci-check-jacoco.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-check-jacoco.yml b/.github/workflows/ci-check-jacoco.yml index 8679ce6..ac5c5ec 100644 --- a/.github/workflows/ci-check-jacoco.yml +++ b/.github/workflows/ci-check-jacoco.yml @@ -28,7 +28,7 @@ jobs: min-coverage-changed-files: 80.0 title: JaCoCo code coverage report - ScAPI update-comment: true - debug: true + debug-mode: true - name: Get the Coverage info run: | echo "Total coverage ${{ steps.jacoco.outputs.coverage-overall }}" From aca858703aff82df73b09de1fea158833929b8c0 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 14:11:17 +0200 Subject: [PATCH 23/31] * Fix - expected change to fix jacoco report issue and better package name and location. --- .../africa/absa/testing/scapi/json/ReferenceResolver.scala | 2 +- .../africa/absa/testing/scapi/json/factory/SuiteFactory.scala | 2 +- .../africa/absa/testing/scapi/rest/response/Response.scala | 2 +- .../scapi/rest/response/action/AssertionResponseAction.scala | 2 +- .../scapi/rest/response/action/ExtractJsonResponseAction.scala | 2 +- .../testing/scapi/rest/response/action/LogResponseAction.scala | 2 +- .../{enum => action/types}/AssertResponseActionType.scala | 2 +- .../{enum => action/types}/ExtractJsonResponseActionType.scala | 2 +- .../response/{enum => action/types}/LogResponseActionType.scala | 2 +- .../{enum => action/types}/ResponseActionGroupType.scala | 2 +- .../testing/scapi/rest/response/ResponseAssertionsTest.scala | 2 +- .../absa/testing/scapi/rest/response/ResponseExtractTest.scala | 2 +- .../absa/testing/scapi/rest/response/ResponseLogTest.scala | 2 +- .../absa/testing/scapi/suite/runner/SuiteRunnerTest.scala | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{enum => action/types}/AssertResponseActionType.scala (97%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{enum => action/types}/ExtractJsonResponseActionType.scala (95%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{enum => action/types}/LogResponseActionType.scala (95%) rename testApi/src/main/scala/africa/absa/testing/scapi/rest/response/{enum => action/types}/ResponseActionGroupType.scala (93%) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala index 7e25103..47101e7 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/ReferenceResolver.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.json -import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType.ResponseActionGroupType +import africa.absa.testing.scapi.rest.response.action.types.ResponseActionGroupType.ResponseActionGroupType import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedConstantsInPropertiesException} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala index 60366c8..aabe8da 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/json/factory/SuiteFactory.scala @@ -24,7 +24,7 @@ import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.model.suite.{Method, TestSet, AfterTestSet, SuitePreAndPostProcessing, BeforeTestSet, Suite, SuiteTestScenario} import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response -import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType +import africa.absa.testing.scapi.rest.response.action.types.ResponseActionGroupType import africa.absa.testing.scapi.utils.file.{FileUtils, JsonUtils} import spray.json._ diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 0106435..5e9e902 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.rest.model.CookieValue -import africa.absa.testing.scapi.rest.response.`enum`.ResponseActionGroupType +import africa.absa.testing.scapi.rest.response.action.types.ResponseActionGroupType import africa.absa.testing.scapi.rest.response.action.{AssertionResponseAction, ExtractJsonResponseAction, LogResponseAction} import scala.util.{Failure, Success, Try} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala index b41a9a2..fbae10e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala @@ -18,7 +18,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.`enum`.AssertResponseActionType._ +import africa.absa.testing.scapi.rest.response.action.types.AssertResponseActionType._ import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala index 5fd9721..3bc0342 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala @@ -18,7 +18,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.`enum`.ExtractJsonResponseActionType._ +import africa.absa.testing.scapi.rest.response.action.types.ExtractJsonResponseActionType._ import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index 75aa9c6..528374f 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -18,7 +18,7 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.`enum`.LogResponseActionType._ +import africa.absa.testing.scapi.rest.response.action.types.LogResponseActionType._ import africa.absa.testing.scapi.rest.response.Response import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala similarity index 97% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala index 31f7dab..7c70d7d 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/AssertResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response.`enum` +package africa.absa.testing.scapi.rest.response.action.types import scala.language.implicitConversions diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala similarity index 95% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala index 7706f6d..b438e84 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ExtractJsonResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response.`enum` +package africa.absa.testing.scapi.rest.response.action.types import scala.language.implicitConversions diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala similarity index 95% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala index 6b82d42..e385057 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/LogResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response.`enum` +package africa.absa.testing.scapi.rest.response.action.types import scala.language.implicitConversions diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala similarity index 93% rename from testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala index 789e1f9..bd568ca 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/enum/ResponseActionGroupType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala @@ -14,7 +14,7 @@ * limitations under the License. */ -package africa.absa.testing.scapi.rest.response.`enum` +package africa.absa.testing.scapi.rest.response.action.types object ResponseActionGroupType extends Enumeration { val ASSERT, EXTRACT_JSON, LOG = Value diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index c490d7b..04c8e45 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -18,8 +18,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.rest.model.CookieValue -import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.rest.response.action.AssertionResponseAction +import africa.absa.testing.scapi.rest.response.action.types.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index e867e3f..ff8ae22 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -18,8 +18,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction -import africa.absa.testing.scapi.rest.response.`enum`.{ExtractJsonResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.rest.response.action.ExtractJsonResponseAction +import africa.absa.testing.scapi.rest.response.action.types.{ExtractJsonResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index 4de298c..359dd96 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -17,8 +17,8 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction -import africa.absa.testing.scapi.rest.response.`enum`.{ResponseActionGroupType, LogResponseActionType => LogType} import africa.absa.testing.scapi.rest.response.action.LogResponseAction +import africa.absa.testing.scapi.rest.response.action.types.{ResponseActionGroupType, LogResponseActionType => LogType} import munit.FunSuite diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 4ace43f..f230b92 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -22,7 +22,7 @@ import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.model.suite._ import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders -import africa.absa.testing.scapi.rest.response.`enum`.{AssertResponseActionType, ResponseActionGroupType} +import africa.absa.testing.scapi.rest.response.action.types.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite import org.apache.logging.log4j.Level From 1d2c8ab52ea4fd2d2e6ea1ff9feff31b1df0f32d Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Fri, 13 Oct 2023 14:22:09 +0200 Subject: [PATCH 24/31] * Fix - expected change to fix jacoco report issue and better package name and location. Second part: refactor Enumeration for SuiteResultType. --- .../testing/scapi/model/suite/SuiteResult.scala | 2 +- .../suite/{ => types}/SuiteResultType.scala | 7 +++++-- .../testing/scapi/reporter/StdOutReporter.scala | 11 ++++++----- .../scapi/suite/runner/SuiteRunner.scala | 17 +++++++++-------- .../scapi/reporter/StdOutReporterTest.scala | 15 ++++++++------- .../scapi/suite/runner/SuiteRunnerTest.scala | 11 ++++++----- 6 files changed, 35 insertions(+), 28 deletions(-) rename testApi/src/main/scala/africa/absa/testing/scapi/model/suite/{ => types}/SuiteResultType.scala (72%) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala index 5aaca15..db71d5a 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResult.scala @@ -16,7 +16,7 @@ package africa.absa.testing.scapi.model.suite -import africa.absa.testing.scapi.model.suite.SuiteResultType.SuiteResultType +import africa.absa.testing.scapi.model.suite.types.SuiteResultType.SuiteResultType import scala.util.{Failure, Try} diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala similarity index 72% rename from testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala rename to testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala index 824d99d..11ea8e7 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/SuiteResultType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala @@ -14,9 +14,12 @@ * limitations under the License. */ -package africa.absa.testing.scapi.model.suite +package africa.absa.testing.scapi.model.suite.types object SuiteResultType extends Enumeration { - val BEFORE_SUITE, TEST_SUITE, AFTER_SUITE = Value type SuiteResultType = Value + + val BEFORE_TEST_SET: SuiteResultType.Value = Value("before-test-set") + val TEST_SET: SuiteResultType.Value = Value("test-set") + val AFTER_TEST_SET: SuiteResultType.Value = Value("after-test-set") } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala index 5b29a26..26c8512 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala @@ -16,7 +16,8 @@ package africa.absa.testing.scapi.reporter -import africa.absa.testing.scapi.model.suite.{SuiteResult, SuiteResultType} +import africa.absa.testing.scapi.model.suite.SuiteResult +import africa.absa.testing.scapi.model.suite.types.SuiteResultType /** * A singleton object to manage the standard output reporting of test results. @@ -58,8 +59,8 @@ object StdOutReporter { printHeader("Simple Text Report") - val successCount = testResults.count(r => r.isSuccess && r.resultType == SuiteResultType.TEST_SUITE) - val failureCount = testResults.count(r => !r.isSuccess && r.resultType == SuiteResultType.TEST_SUITE) + val successCount = testResults.count(r => r.isSuccess && r.resultType == SuiteResultType.TEST_SET) + val failureCount = testResults.count(r => !r.isSuccess && r.resultType == SuiteResultType.TEST_SET) println(s"Number of tests run: ${successCount + failureCount}") println(s"Number of successful tests: $successCount") @@ -67,7 +68,7 @@ object StdOutReporter { if (testResults.nonEmpty) { val suiteSummary = testResults - .filter(_.resultType == SuiteResultType.TEST_SUITE) + .filter(_.resultType == SuiteResultType.TEST_SET) .groupBy(_.suiteName).map { case (suiteName, results) => (suiteName, results.size, results.count(_.isSuccess)) @@ -83,7 +84,7 @@ object StdOutReporter { printTableRowSplitter() println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %-13s | %-7s | %-${maxTestCategoriesLength}s | ".format("Suite Name", "Test Name", "Duration (ms)", "Status", "Categories")) printTableRowSplitter() - val resultsList = testResults.filter(_.resultType == SuiteResultType.TEST_SUITE) + val resultsList = testResults.filter(_.resultType == SuiteResultType.TEST_SET) resultsList.zipWithIndex.foreach { case (result, index) => val duration = result.duration.map(_.toString).getOrElse("NA") println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %13s | %-7s | %-${maxTestCategoriesLength}s | ".format( diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index 67d4420..06090bc 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -19,7 +19,8 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.SuiteBeforeFailedException import africa.absa.testing.scapi.json.{Environment, Requestable} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteResult, SuiteResultType, SuiteTestScenario} +import africa.absa.testing.scapi.model.suite.types.SuiteResultType +import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteResult, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} import africa.absa.testing.scapi.rest.response.Response @@ -56,7 +57,7 @@ object SuiteRunner { // add failed Test suite result instance and it will not be started suiteResult = suiteResult :+ SuiteResult( - resultType = SuiteResultType.TEST_SUITE, + resultType = SuiteResultType.TEST_SET, suiteName = suiteBundle.suite.name, name = "SKIPPED", result = Failure(SuiteBeforeFailedException(errorMsg)), @@ -94,7 +95,7 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Before: method '${method.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.BEFORE_SUITE, + resultType = SuiteResultType.BEFORE_TEST_SET, suiteName = suiteName, name = method.name, result = result, @@ -122,7 +123,7 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Test: '${test.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.TEST_SUITE, + resultType = SuiteResultType.TEST_SET, suiteName = suiteName, name = test.name, result = result, @@ -155,7 +156,7 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"After method '${method.name}' ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.AFTER_SUITE, + resultType = SuiteResultType.AFTER_TEST_SET, suiteName = suiteName, name = method.name, result = result, @@ -219,14 +220,14 @@ object SuiteRunner { Logger.error(message) resultType match { case "Before" => SuiteResult( - resultType = SuiteResultType.BEFORE_SUITE, + resultType = SuiteResultType.BEFORE_TEST_SET, suiteName = suiteName, name = name, result = Failure(e), duration = Some(testEndTime - testStartTime)) case "Test" => SuiteResult( - resultType = SuiteResultType.TEST_SUITE, + resultType = SuiteResultType.TEST_SET, suiteName = suiteName, name = name, result = Failure(e), @@ -235,7 +236,7 @@ object SuiteRunner { ) case "After" => SuiteResult( - resultType = SuiteResultType.AFTER_SUITE, + resultType = SuiteResultType.AFTER_TEST_SET, suiteName = suiteName, name = name, result = Failure(e), diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index b921a05..a6990a6 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -17,7 +17,8 @@ package africa.absa.testing.scapi.reporter import africa.absa.testing.scapi.AssertionException -import africa.absa.testing.scapi.model.suite.{SuiteResult, SuiteResultType} +import africa.absa.testing.scapi.model.suite.SuiteResult +import africa.absa.testing.scapi.model.suite.types.SuiteResultType import munit.FunSuite import java.io.ByteArrayOutputStream @@ -26,20 +27,20 @@ import scala.util.{Failure, Success} class StdOutReporterTest extends FunSuite { val successTestResults: List[SuiteResult] = List( - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 1", name = "Test 1", result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 1", name = "Test 2", result = Success(()), duration = Some(200L), categories = Some("Category 2") ), - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 2", name = "Test 1", result = Success(()), @@ -48,19 +49,19 @@ class StdOutReporterTest extends FunSuite { ) val mixedSuccessTestResults: List[SuiteResult] = List( - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 1", name = "Test 1", result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 1", name = "Test 2", result = Failure(AssertionException("Error message")), duration = Some(200L), categories = Some("Category 2")), - SuiteResult(SuiteResultType.TEST_SUITE, + SuiteResult(SuiteResultType.TEST_SET, suiteName = "Suite 2", name = "Test 1", result = Success(()), diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index f230b92..4cea6b3 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -20,6 +20,7 @@ import africa.absa.testing.scapi.json.{Action, Environment, Header, ResponseActi import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.model.suite._ +import africa.absa.testing.scapi.model.suite.types.SuiteResultType import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.RequestHeaders import africa.absa.testing.scapi.rest.response.action.types.{AssertResponseActionType, ResponseActionGroupType} @@ -105,7 +106,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "name2").get + result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2").get assertEquals(5, clue(suiteResults.size)) assertEquals("test", clue(beforeSuiteResult.name)) @@ -116,7 +117,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoBefore, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_SUITE && result.suiteName == "name2") + result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2") assertEquals(2, clue(suiteResults.size)) assert(beforeSuiteResult.isEmpty) @@ -126,7 +127,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2").get + result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get assertEquals(5, clue(suiteResults.size)) assertEquals("test", clue(afterSuiteResult.name)) @@ -137,7 +138,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoAfter, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2") + result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2") assertEquals(2, clue(suiteResults.size)) assert(afterSuiteResult.isEmpty) @@ -147,7 +148,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleAfterMethodNotSupported, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_SUITE && result.suiteName == "name2").get + result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get assertEquals(2, clue(suiteResults.size)) assertEquals(false, clue(afterSuiteResult.isSuccess)) From e2fec8f3d140ec059a477083233993167a414e5e Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 1 Nov 2023 13:25:49 +0100 Subject: [PATCH 25/31] * Fix - log action methods returns Unit. --- .../response/action/LogResponseAction.scala | 35 ++++++++----------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index 528374f..b502647 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -18,12 +18,12 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.action.types.LogResponseActionType._ import africa.absa.testing.scapi.rest.response.Response +import africa.absa.testing.scapi.rest.response.action.types.LogResponseActionType._ import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{PropertyNotFoundException, UndefinedResponseActionTypeException} -import scala.util.{Failure, Success, Try} +import scala.util.{Failure, Try} /** * Singleton object `ResponseLog` that extends the `ResponsePerformer` trait. @@ -60,12 +60,14 @@ object LogResponseAction extends ResponseActions { def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { val message = responseAction.params.getOrElse("message", return Failure(PropertyNotFoundException("Missing 'message' parameter"))) val action = fromString(responseAction.name.toLowerCase).getOrElse(None) - action match { - case ERROR => logError(message) - case WARN => logWarn(message) - case INFO => logInfo(message) - case DEBUG => logDebug(message) - case _ => Failure(UndefinedResponseActionTypeException(s"Unsupported log method [group: log]: ${responseAction.name}")) + Try { + action match { + case ERROR => logError(message) + case WARN => logWarn(message) + case INFO => logInfo(message) + case DEBUG => logDebug(message) + case _ => Failure(UndefinedResponseActionTypeException(s"Unsupported log method [group: log]: ${responseAction.name}")) + } } } @@ -77,44 +79,35 @@ object LogResponseAction extends ResponseActions { * Logs a message at the ERROR level. * * @param message The message to be logged. - * @return A Try[Unit] indicating the success of the logging operation. */ - private def logError(message: String): Try[Unit] = { + private def logError(message: String): Unit = { Logger.error(message) - Success(()) } /** * Logs a message at the WARN level. * * @param message The message to be logged. - * @return A Try[Unit] indicating the success of the logging operation. */ - private def logWarn(message: String): Try[Unit] = { + private def logWarn(message: String): Unit = { Logger.warn(message) - Success(()) } /** * Logs a message at the INFO level. * * @param message The message to be logged. - * @return A Try[Unit] indicating the success of the logging operation. */ - private def logInfo(message: String): Try[Unit] = { + private def logInfo(message: String): Unit = { Logger.info(message) - Success(()) } /** * Logs a message at the DEBUG level. * * @param message The message to be logged. - * @return A Try[Unit] indicating the success of the logging operation. */ - private def logDebug(message: String): Try[Unit] = { + private def logDebug(message: String): Unit = { Logger.debug(message) - Success(()) } - } From 470efbf47cb176cacc35e7a6844b09088c352756 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 1 Nov 2023 14:16:52 +0100 Subject: [PATCH 26/31] * Fix - Improved usage of resultType enums. --- .../scapi/suite/runner/SuiteRunner.scala | 55 ++++++------------- 1 file changed, 18 insertions(+), 37 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index 06090bc..99be2c4 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -20,6 +20,7 @@ import africa.absa.testing.scapi.SuiteBeforeFailedException import africa.absa.testing.scapi.json.{Environment, Requestable} import africa.absa.testing.scapi.logging.Logger import africa.absa.testing.scapi.model.suite.types.SuiteResultType +import africa.absa.testing.scapi.model.suite.types.SuiteResultType.SuiteResultType import africa.absa.testing.scapi.model.suite.{Method, Suite, SuiteResult, SuiteTestScenario} import africa.absa.testing.scapi.rest.RestClient import africa.absa.testing.scapi.rest.request.{RequestBody, RequestHeaders, RequestParams} @@ -102,7 +103,7 @@ object SuiteRunner { duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteName, suiteBeforeName, testStartTime, "Before") + case e: Exception => handleException(e, suiteName, suiteBeforeName, testStartTime, SuiteResultType.BEFORE_TEST_SET) } } @@ -132,7 +133,7 @@ object SuiteRunner { ) } catch { - case e: Exception => handleException(e, suiteName, test.name, testStartTime, "Test", Some(test.categories.mkString(","))) + case e: Exception => handleException(e, suiteName, test.name, testStartTime, SuiteResultType.TEST_SET, Some(test.categories.mkString(","))) } finally { RuntimeCache.expire(TestLevel) } @@ -163,7 +164,7 @@ object SuiteRunner { duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteName, suiteAfterName, testStartTime, "After") + case e: Exception => handleException(e, suiteName, suiteAfterName, testStartTime, SuiteResultType.AFTER_TEST_SET) } } @@ -205,42 +206,22 @@ object SuiteRunner { /** * Handles exceptions occurring during suite running. * - * @param e The exception to handle. - * @param suiteName Suite's name. - * @param name The name of the suite or test. - * @param testStartTime The starting time of the suite or test. - * @param resultType The type of the suite or test ("Before", "Test", or "After"). + * @param e The exception to handle. + * @param suiteName Suite's name. + * @param name The name of the suite or test. + * @param testStartTime The starting time of the suite or test. + * @param suiteResultType The type of the suite or test ("Before", "Test", or "After"). * @return SuiteResults after the exception handling. */ - private def handleException(e: Throwable, suiteName: String, name: String, testStartTime: Long, resultType: String, categories: Option[String] = None): SuiteResult = { + private def handleException(e: Throwable, suiteName: String, name: String, testStartTime: Long, suiteResultType: SuiteResultType, categories: Option[String] = None): SuiteResult = { val testEndTime = System.currentTimeMillis() - val message = e match { - case _ => s"Request exception occurred while running suite: $suiteName, $resultType: $name. Exception: ${e.getMessage}" - } - Logger.error(message) - resultType match { - case "Before" => SuiteResult( - resultType = SuiteResultType.BEFORE_TEST_SET, - suiteName = suiteName, - name = name, - result = Failure(e), - duration = Some(testEndTime - testStartTime)) - - case "Test" => SuiteResult( - resultType = SuiteResultType.TEST_SET, - suiteName = suiteName, - name = name, - result = Failure(e), - duration = Some(testEndTime - testStartTime), - categories = categories - ) - - case "After" => SuiteResult( - resultType = SuiteResultType.AFTER_TEST_SET, - suiteName = suiteName, - name = name, - result = Failure(e), - duration = Some(testEndTime - testStartTime)) - } + Logger.error(s"Request exception occurred while running suite: $suiteName, $suiteResultType: $name. Exception: ${e.getMessage}") + + SuiteResult( + resultType = suiteResultType, + suiteName = suiteName, + name = name, + result = Failure(e), + duration = Some(testEndTime - testStartTime)) } } From a15a4201defe36c53ed748e66e4bad34aa6372ac Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 1 Nov 2023 15:52:37 +0100 Subject: [PATCH 27/31] * Fix - Removed usage of Success from Action implementations. --- .../action/AssertionResponseAction.scala | 178 +++++++++--------- .../action/ExtractJsonResponseAction.scala | 15 +- .../rest/response/ResponseExtractTest.scala | 32 +++- 3 files changed, 123 insertions(+), 102 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala index fbae10e..59bfe6a 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala @@ -18,13 +18,13 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.action.types.AssertResponseActionType._ import africa.absa.testing.scapi.rest.response.Response +import africa.absa.testing.scapi.rest.response.action.types.AssertResponseActionType._ import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import spray.json._ -import scala.util.{Failure, Success, Try} +import scala.util.{Failure, Try} import scala.xml.XML /** @@ -177,12 +177,12 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that succeeds if the response's duration is below the specified maximum time, and fails with an AssertionException otherwise. */ private def assertResponseTimeIsBelow(response: Response, maxTimeMillis: String): Try[Unit] = { - val lMaxTimeMillis: Long = maxTimeMillis.toLong + Try { + val lMaxTimeMillis: Long = maxTimeMillis.toLong - if (response.duration <= lMaxTimeMillis) { - Success(()) - } else { - Failure(AssertionException(s"Expected maximal length '$lMaxTimeMillis' is smaller then received '${response.duration}' one.")) + if (response.duration > lMaxTimeMillis) { + throw AssertionException(s"Expected maximal length '$lMaxTimeMillis' is smaller then received '${response.duration}' one.") + } } } @@ -194,12 +194,12 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the response's duration is greater than or equal to the specified minimum time, and a Failure with an AssertionException otherwise. */ private def assertResponseTimeIsAbove(response: Response, minTimeMillis: String): Try[Unit] = { - val lMinTimeMillis: Long = minTimeMillis.toLong + Try { + val lMinTimeMillis: Long = minTimeMillis.toLong - if (response.duration >= lMinTimeMillis) { - Success(()) - } else { - Failure(AssertionException(s"Expected minimal length '$lMinTimeMillis' is bigger then received '${response.duration}' one.")) + if (response.duration < lMinTimeMillis) { + throw AssertionException(s"Expected minimal length '$lMinTimeMillis' is bigger then received '${response.duration}' one.") + } } } @@ -212,12 +212,12 @@ object AssertionResponseAction extends ResponseActions { * @throws AssertionException if the response's status code does not match the expected code. */ private def assertStatusCodeEquals(response: Response, expectedCode: String): Try[Unit] = { - val iExpectedCode: Int = expectedCode.toInt + Try { + val iExpectedCode: Int = expectedCode.toInt - if (response.statusCode == iExpectedCode) { - Success(()) - } else { - Failure(AssertionException(s"Expected $iExpectedCode, but got ${response.statusCode}")) + if (response.statusCode != iExpectedCode) { + throw AssertionException(s"Expected $iExpectedCode, but got ${response.statusCode}") + } } } @@ -228,10 +228,10 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the status code is within the range 200-299, and a Failure with an AssertionException otherwise. */ private def assertStatusCodeSuccess(response: Response): Try[Unit] = { - if (response.statusCode >= 200 && response.statusCode <= 299) { - Success(()) - } else { - Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (200 - 299).")) + Try { + if (!(response.statusCode >= 200 && response.statusCode <= 299)) { + throw AssertionException(s"Received status code '${response.statusCode}' is not in expected range (200 - 299).") + } } } @@ -242,10 +242,10 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the status code is within the range 400-499, and a Failure with an AssertionException otherwise. */ private def assertStatusCodeIsClientError(response: Response): Try[Unit] = { - if (response.statusCode >= 400 && response.statusCode <= 499) { - Success(()) - } else { - Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (400 - 499).")) + Try { + if (!(response.statusCode >= 400 && response.statusCode <= 499)) { + throw AssertionException(s"Received status code '${response.statusCode}' is not in expected range (400 - 499).") + } } } @@ -256,10 +256,10 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the status code is within the range 500-599, and a Failure with an AssertionException otherwise. */ private def assertStatusCodeIsServerError(response: Response): Try[Unit] = { - if (response.statusCode >= 500 && response.statusCode <= 599) { - Success(()) - } else { - Failure(AssertionException(s"Received status code '${response.statusCode}' is not in expected range (500 - 599).")) + Try { + if (!(response.statusCode >= 500 && response.statusCode <= 599)) { + throw AssertionException(s"Received status code '${response.statusCode}' is not in expected range (500 - 599).") + } } } @@ -271,10 +271,10 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the header exists in the response, and a Failure with an AssertionException otherwise. */ private def assertHeaderExists(response: Response, headerName: String): Try[Unit] = { - if (response.headers.contains(headerName.toLowerCase)) { - Success(()) - } else { - Failure(AssertionException(s"Expected header '$headerName' not found.")) + Try { + if (!response.headers.contains(headerName.toLowerCase)) { + throw AssertionException(s"Expected header '$headerName' not found.") + } } } @@ -287,16 +287,14 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the header value matches the expected value, and a Failure with an AssertionException otherwise. */ private def assertHeaderValueEquals(response: Response, headerName: String, expectedValue: String): Try[Unit] = { - if (assertHeaderExists(response, headerName).isSuccess) { - if (expectedValue.equals(response.headers(headerName.toLowerCase).head)) { - Success(()) - } else { - Failure(AssertionException(s"Expected header '$headerName' value '$expectedValue' is not equal to " + - s"received header value '$response.headers(headerName.toLowerCase).head'.")) + Try { + if (assertHeaderExists(response, headerName).isFailure) { + throw AssertionException(s"Expected header '$headerName' not found.") + } else if (!expectedValue.equals(response.headers(headerName.toLowerCase).head)) { + throw AssertionException(s"Expected header '$headerName' value '$expectedValue' is not equal to " + + s"received header value '${response.headers(headerName.toLowerCase).head}'.") } } - else - Failure(AssertionException(s"Expected header '$headerName' not found.")) } /** @@ -306,18 +304,18 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the "Content-Type" header value is "application/json", and a Failure with an AssertionException otherwise. */ private def assertContentTypeIsJson(response: Response): Try[Unit] = { - val isContentTypeJson = assertHeaderValueEquals(response, "content-type", "application/json") - val isBodyJson = try { - response.body.parseJson - true - } catch { - case _: JsonParser.ParsingException => false - } + Try { + val isContentTypeJson = assertHeaderValueEquals(response, "content-type", "application/json") + val isBodyJson = try { + response.body.parseJson + true + } catch { + case _: JsonParser.ParsingException => false + } - if (isContentTypeJson.isSuccess && isBodyJson) { - Success(()) - } else { - Failure(AssertionException("Received content is not JSON type.")) + if (!isContentTypeJson.isSuccess || !isBodyJson) { + throw AssertionException("Received content is not JSON type.") + } } } @@ -328,18 +326,18 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the "Content-Type" header value is "application/xml", and a Failure with an AssertionException otherwise. */ private def assertContentTypeIsXml(response: Response): Try[Unit] = { - val isContentTypeXml = assertHeaderValueEquals(response, "content-type", "application/xml") - val isBodyXml = try { - XML.loadString(response.body) - true - } catch { - case _: Exception => false - } + Try { + val isContentTypeXml = assertHeaderValueEquals(response, "content-type", "application/xml") + val isBodyXml = try { + XML.loadString(response.body) + true + } catch { + case _: Exception => false + } - if (isContentTypeXml.isSuccess && isBodyXml) { - Success(()) - } else { - Failure(AssertionException("Received content is not XML type.")) + if (!isContentTypeXml.isSuccess || !isBodyXml) { + throw AssertionException("Received content is not XML type.") + } } } @@ -350,12 +348,12 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the "Content-Type" header value is "text/html", and a Failure with an AssertionException otherwise. */ private def assertContentTypeIsHtml(response: Response): Try[Unit] = { - val res = assertHeaderValueEquals(response, "content-type", "text/html") - - res match { - case Success(_) => Success(()) - case Failure(exception) => - Failure(AssertionException(s"Received content is not HTML type. Details: ${exception.getMessage}")) + Try { + assertHeaderValueEquals(response, "content-type", "text/html") match { + case Failure(exception) => + throw AssertionException(s"Received content is not HTML type. Details: ${exception.getMessage}") + case _ => // Do nothing for Success + } } } @@ -369,10 +367,10 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the specified cookie exists in the response, and a Failure with an AssertionException otherwise. */ private def assertCookieExists(response: Response, cookieName: String): Try[Unit] = { - if (response.cookies.contains(cookieName)) { - Success(()) - } else { - Failure(AssertionException(s"Cookie '$cookieName' does not exist in the response.")) + Try { + if (!response.cookies.contains(cookieName)) { + throw AssertionException(s"Cookie '$cookieName' does not exist in the response.") + } } } @@ -386,10 +384,10 @@ object AssertionResponseAction extends ResponseActions { */ private def assertCookieValueEquals(response: Response, cookieName: String, expectedValue: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (response.cookies(cookieName).value == expectedValue) { - Success(()) - } else { - Failure(AssertionException(s"Cookie '$cookieName' value does not match expected value '$expectedValue'.")) + Try { + if (!(response.cookies(cookieName).value == expectedValue)) { + throw AssertionException(s"Cookie '$cookieName' value does not match expected value '$expectedValue'.") + } } } } @@ -403,10 +401,10 @@ object AssertionResponseAction extends ResponseActions { */ private def assertCookieIsSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (response.cookies(cookieName).secured) { - Success(()) - } else { - Failure(AssertionException(s"Cookie '$cookieName' is not secured.")) + Try { + if (!response.cookies(cookieName).secured) { + throw AssertionException(s"Cookie '$cookieName' is not secured.") + } } } } @@ -420,10 +418,10 @@ object AssertionResponseAction extends ResponseActions { */ private def assertCookieIsNotSecured(response: Response, cookieName: String): Try[Unit] = { assertCookieExists(response, cookieName).flatMap { _ => - if (!response.cookies(cookieName).secured) { - Success(()) - } else { - Failure(AssertionException(s"Cookie '$cookieName' is secured.")) + Try { + if (response.cookies(cookieName).secured) { + throw AssertionException(s"Cookie '$cookieName' is secured.") + } } } } @@ -436,11 +434,11 @@ object AssertionResponseAction extends ResponseActions { * @return A Try[Unit] that is a Success if the body contains the expected text, and a Failure with an AssertionException otherwise. */ private def assertBodyContainsText(response: Response, text: String): Try[Unit] = { - if (response.body.contains(text)) { - Success(()) - } else { - Logger.error(s"Expected body to contain $text") - Failure(AssertionException(s"Body does not contain expected text '$text'.")) + Try { + if (!response.body.contains(text)) { + Logger.error(s"Expected body to contain $text") + throw AssertionException(s"Body does not contain expected text '$text'.") + } } } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala index 3bc0342..8b56f7c 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala @@ -18,14 +18,14 @@ package africa.absa.testing.scapi.rest.response.action import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.rest.response.action.types.ExtractJsonResponseActionType._ import africa.absa.testing.scapi.rest.response.Response +import africa.absa.testing.scapi.rest.response.action.types.ExtractJsonResponseActionType._ import africa.absa.testing.scapi.utils.cache.RuntimeCache import africa.absa.testing.scapi.utils.validation.ContentValidator import africa.absa.testing.scapi.{AssertionException, UndefinedResponseActionTypeException} import spray.json._ -import scala.util.{Failure, Success, Try} +import scala.util.Try /** * ExtractJsonResponseAction is an object that extends ResponsePerformer. @@ -84,14 +84,14 @@ object ExtractJsonResponseAction extends ResponseActions { * @return A Try[Unit] indicating whether the string extraction and caching operation was successful or not. */ private def stringFromList(response: Response, cacheKey: String, listIndex: Int, jsonKey: String, runtimeCacheLevel: String): Try[Unit] = { - try { + Try { val jsonAst = response.body.parseJson val objects = jsonAst match { case JsArray(array) => array case _ => Logger.error("Expected a JSON array") - return Failure(AssertionException("Expected a JSON array in the response.")) + throw AssertionException("Expected a JSON array in the response.") } // Extract "jsonKey" from the object at the given index @@ -100,15 +100,14 @@ object ExtractJsonResponseAction extends ResponseActions { case Seq(JsNumber(value)) => value.toString() case _ => Logger.error(s"Expected '$jsonKey' field not found in provided json.") - return Failure(AssertionException(s"Expected '$jsonKey' field not found in provided json.")) + throw AssertionException(s"Expected '$jsonKey' field not found in provided json.") } RuntimeCache.put(key = cacheKey, value = value, RuntimeCache.determineLevel(runtimeCacheLevel)) - Success(()) - } catch { + } recover { case e: spray.json.JsonParser.ParsingException => Logger.error(s"Expected json string in response body. JSON parsing error: ${e.getMessage}") - Failure(AssertionException(s"Expected json string in response body. JSON parsing error: ${e.getMessage}")) + throw AssertionException(s"Expected json string in response body. JSON parsing error: ${e.getMessage}") } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index ff8ae22..49d163a 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -16,14 +16,14 @@ package africa.absa.testing.scapi.rest.response -import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} +import africa.absa.testing.scapi.{AssertionException, ContentValidationFailedException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.rest.response.action.ExtractJsonResponseAction import africa.absa.testing.scapi.rest.response.action.types.{ExtractJsonResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite -import scala.util.Try +import scala.util.{Failure, Try} class ResponseExtractTest extends FunSuite { @@ -133,21 +133,45 @@ class ResponseExtractTest extends FunSuite { test("performAssertion - stringFromList - incorrect parameters - wrong list index") { val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("listIndex", "10")) - interceptMessage[IndexOutOfBoundsException]("10 is out of bounds (min 0, max 2)") { - ExtractJsonResponseAction.performResponseAction(responseWithID, notValidAssertionStringFromList) + val res = ExtractJsonResponseAction.performResponseAction(responseWithID, notValidAssertionStringFromList) + + assert(res.isFailure) + + res match { + case Failure(exception: IndexOutOfBoundsException) => + assert(exception.getMessage == "10 is out of bounds (min 0, max 2)") + case _ => + fail("Expected a Failure with the specific exception type and message.") } } test("performAssertion - stringFromList - incorrect parameters - wrong jsonKey") { val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("jsonKey", "ids")) val res = ExtractJsonResponseAction.performResponseAction(responseWithID, notValidAssertionStringFromList) + assert(res.isFailure) + + res match { + case Failure(exception: AssertionException) => + assert(exception.getMessage.contains("Expected 'ids' field not found in provided json.")) + case _ => + fail("Expected a Failure with the specific exception type and message.") + } } test("performAssertion - stringFromList - incorrect parameters - no json arrays in response body") { val notValidAssertionStringFromList: ResponseAction = assertionStringFromList.copy(params = assertionStringFromList.params.updated("listIndex", "0")) val res = ExtractJsonResponseAction.performResponseAction(responseNoJsonBody, notValidAssertionStringFromList) + assert(res.isFailure) + + res match { + case Failure(exception: AssertionException) => + assert(exception.getMessage.contains("Expected json string in response body. JSON parsing error:")) + assert(exception.getMessage.contains("Unexpected character 'o' at input index 0")) + case _ => + fail("Expected a Failure with the specific exception type and message.") + } } test("performAssertion - unsupported assertion") { From 5ec5a73137e30cedef0c0cab5593948d1f27d33c Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Wed, 1 Nov 2023 16:27:09 +0100 Subject: [PATCH 28/31] * Fix - Renamed and moved Type to String implicit conversion as they are used only in tests. --- .../response/action/types/AssertResponseActionType.scala | 3 --- .../action/types/ExtractJsonResponseActionType.scala | 3 --- .../rest/response/action/types/LogResponseActionType.scala | 3 --- .../testing/scapi/rest/response/ResponseAssertionsTest.scala | 5 +++++ .../testing/scapi/rest/response/ResponseExtractTest.scala | 4 ++++ .../absa/testing/scapi/rest/response/ResponseLogTest.scala | 5 +++++ 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala index 7c70d7d..a0b07b3 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala @@ -52,7 +52,4 @@ object AssertResponseActionType extends Enumeration { private val stringToValueMap = values.map(v => v.toString -> v).toMap def fromString(s: String): Option[AssertResponseActionType] = stringToValueMap.get(s) - - // Implicit conversion from AssertResponseActionType to String - implicit def enumValueToString(value: AssertResponseActionType): String = value.toString } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala index b438e84..7b362a2 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala @@ -26,9 +26,6 @@ object ExtractJsonResponseActionType extends Enumeration { private val stringToValueMap = values.map(v => v.toString -> v).toMap def fromString(s: String): Option[ExtractJsonResponseActionType] = stringToValueMap.get(s) - - // Implicit conversion from AssertResponseActionType to String - implicit def enumValueToString(value: ExtractJsonResponseActionType): String = value.toString } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala index e385057..3cd29c3 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala @@ -29,7 +29,4 @@ object LogResponseActionType extends Enumeration { private val stringToValueMap = values.map(v => v.toString -> v).toMap def fromString(s: String): Option[LogResponseActionType] = stringToValueMap.get(s) - - // Implicit conversion from AssertResponseActionType to String - implicit def enumValueToString(value: LogResponseActionType): String = value.toString } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 04c8e45..948e0a5 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -19,12 +19,17 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.rest.model.CookieValue import africa.absa.testing.scapi.rest.response.action.AssertionResponseAction +import africa.absa.testing.scapi.rest.response.action.types.AssertResponseActionType.AssertResponseActionType import africa.absa.testing.scapi.rest.response.action.types.{AssertResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.{ContentValidationFailedException, UndefinedResponseActionTypeException} import munit.FunSuite +import scala.language.implicitConversions + class ResponseAssertionsTest extends FunSuite { + implicit def assertResponseActionType2String(value: AssertResponseActionType): String = value.toString + /* validateContent */ diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index 49d163a..df18095 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -19,14 +19,18 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.{AssertionException, ContentValidationFailedException, UndefinedResponseActionTypeException} import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.rest.response.action.ExtractJsonResponseAction +import africa.absa.testing.scapi.rest.response.action.types.ExtractJsonResponseActionType.ExtractJsonResponseActionType import africa.absa.testing.scapi.rest.response.action.types.{ExtractJsonResponseActionType, ResponseActionGroupType} import africa.absa.testing.scapi.utils.cache.RuntimeCache import munit.FunSuite +import scala.language.implicitConversions import scala.util.{Failure, Try} class ResponseExtractTest extends FunSuite { + implicit def extractJsonResponseActionType2String(value: ExtractJsonResponseActionType): String = value.toString + val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) val assertionUnsupported: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = "Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index 359dd96..d4d754f 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -18,12 +18,17 @@ package africa.absa.testing.scapi.rest.response import africa.absa.testing.scapi.json.ResponseAction import africa.absa.testing.scapi.rest.response.action.LogResponseAction +import africa.absa.testing.scapi.rest.response.action.types.LogResponseActionType.LogResponseActionType import africa.absa.testing.scapi.rest.response.action.types.{ResponseActionGroupType, LogResponseActionType => LogType} import munit.FunSuite +import scala.language.implicitConversions + class ResponseLogTest extends FunSuite { + implicit def logResponseActionType2String(value: LogResponseActionType): String = value.toString + /* validateContent */ From e4ce58a7c77dbf45231650d473569648ba87886e Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 2 Nov 2023 09:10:26 +0100 Subject: [PATCH 29/31] * Fix - correct usage clue calls in assert (not assertEquals) method. --- .../testing/scapi/json/EnvironmentTest.scala | 8 +-- .../scapi/json/RequestHeadersTest.scala | 4 +- .../scapi/json/RequestParamsTest.scala | 8 +-- .../testing/scapi/json/SuiteFactoryTest.scala | 16 ++--- .../scapi/reporter/StdOutReporterTest.scala | 52 ++++++++--------- .../scapi/suite/runner/SuiteRunnerTest.scala | 23 ++++---- .../scapi/utils/cache/RuntimeCacheTest.scala | 58 +++++++++---------- .../scapi/utils/file/FileUtilsTest.scala | 28 ++++----- .../scapi/utils/file/JsonUtilsTest.scala | 4 +- 9 files changed, 100 insertions(+), 101 deletions(-) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala index 3872dc5..d708fc1 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/EnvironmentTest.scala @@ -53,8 +53,8 @@ class EnvironmentTest extends FunSuite { val actual_value_from_properties: String = env("url") val actual_value_from_constants: String = env("server") - assertEquals(clue(expected_value_from_properties), clue(actual_value_from_properties)) - assertEquals(clue(expected_value_from_constants), clue(actual_value_from_constants)) + assert(clue(expected_value_from_properties) == clue(actual_value_from_properties)) + assert(clue(expected_value_from_constants) == clue(actual_value_from_constants)) } test("apply - properties does not exist") { @@ -71,7 +71,7 @@ class EnvironmentTest extends FunSuite { val expected: String = propertyPort val actual: String = env("port") - assertEquals(clue(expected), clue(actual)) + assert(clue(expected) == clue(actual)) } /* @@ -95,6 +95,6 @@ class EnvironmentTest extends FunSuite { val actual: Environment = notResolverEnv.resolveReferences - assertEquals(clue(expected), clue(actual)) + assert(clue(expected) == clue(actual)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala index 67094ef..43eb358 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestHeadersTest.scala @@ -40,7 +40,7 @@ class RequestHeadersTest extends FunSuite { ) val actualMap = RequestHeaders.buildHeaders(headersSeq) - assertEquals(clue(expectedMap), clue(actualMap)) + assert(clue(expectedMap) == clue(actualMap)) } test("buildHeaders - should return an empty map if no headers are provided") { @@ -48,7 +48,7 @@ class RequestHeadersTest extends FunSuite { val expectedMap = Map.empty[String, String] val actualMap = RequestHeaders.buildHeaders(headersSeq) - assertEquals(clue(expectedMap), clue(actualMap)) + assert(clue(expectedMap) == clue(actualMap)) } /* diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala index 082c6a1..39f74d8 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/RequestParamsTest.scala @@ -29,25 +29,25 @@ class RequestParamsTest extends FunSuite { test("buildParams - no params") { val paramsSet: Option[Set[Param]] = None val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(clue(Map.empty[String, String]), clue(result)) + assert(clue(Map.empty[String, String]) == clue(result)) } test("buildParams - single valid param") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name", "value"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(clue(Map("name" -> "value")), clue(result)) + assert(clue(Map("name" -> "value")) == clue(result)) } test("buildParams - multiple valid params") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name1", "value1"), Param("name2", "value2"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(clue(Map("name1" -> "value1", "name2" -> "value2")), clue(result)) + assert(clue(Map("name1" -> "value1", "name2" -> "value2")) == clue(result)) } test("buildParams - params with empty name or value should be ignored") { val paramsSet: Option[Set[Param]] = Some(Set(Param("name", ""), Param("", "value"), Param("name2", "value2"))) val result: Map[String, String] = RequestParams.buildParams(paramsSet) - assertEquals(clue(Map("name2" -> "value2")), clue(result)) + assert(clue(Map("name2" -> "value2")) == clue(result)) } /* diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index d73662a..fda2e90 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -101,7 +101,7 @@ class SuiteFactoryTest extends FunSuite { val actual: Map[String, String] = SuiteFactory.loadJsonSuiteConstants(suiteFilePath, suiteName, properties).constants - assertEquals(clue(expected), clue(actual)) + assert(clue(expected) == clue(actual)) } test("loadJsonSuite - no constants file exist") { @@ -112,7 +112,7 @@ class SuiteFactoryTest extends FunSuite { val actual: Map[String, String] = SuiteFactory.loadJsonSuiteConstants(suiteFilePath, suiteName, properties).constants - assertEquals(clue(expected), clue(actual)) + assert(clue(expected) == clue(actual)) } test("loadJsonSuite - not all references resolved") { @@ -128,7 +128,7 @@ class SuiteFactoryTest extends FunSuite { /* filterOnlyOrAll */ - test("filterOnlyOrAll - only used - once") { + test("filterOnlyOrAll - only used - once".only) { val suitesBundles = Set( Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), @@ -147,12 +147,12 @@ class SuiteFactoryTest extends FunSuite { assertEquals(filteredSuiteBundles.size, 1) val filteredSuite = filteredSuiteBundles.head.suite - assertEquals(clue("name1"), clue(filteredSuite.name)) - assertEquals(clue(1), clue(filteredSuite.tests.size)) + assert("name1" == clue(filteredSuite.name)) + assert(1 == clue(filteredSuite.tests.size)) val filteredTest = filteredSuite.tests.head - assertEquals(clue("test2"), clue(filteredTest.name)) - assertEquals(clue(Some(true)), clue(filteredTest.only)) + assert("test2" == clue(filteredTest.name)) + assert(clue(Some(true)) == clue(filteredTest.only)) } test("fromFile - only used - twice") { @@ -167,6 +167,6 @@ class SuiteFactoryTest extends FunSuite { val filteredSuiteBundles: Set[Suite] = SuiteFactory.filterOnlyOrAll(suitesBundles) - assertEquals(clue(0), clue(filteredSuiteBundles.size)) + assert(0 == clue(filteredSuiteBundles.size)) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index a6990a6..e3d68a4 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -83,11 +83,11 @@ class StdOutReporterTest extends FunSuite { val output = baos.toString // Assertions - assertEquals(true, clue(output.contains("Simple Text Report"))) - assertEquals(true, clue(output.contains("Number of tests run: 0"))) - assertEquals(true, clue(output.contains("Number of successful tests: 0"))) - assertEquals(true, clue(output.contains("Number of failed tests: 0"))) - assertEquals(true, clue(output.contains("End Report"))) + assert(clue(output.contains("Simple Text Report"))) + assert(clue(output.contains("Number of tests run: 0"))) + assert(clue(output.contains("Number of successful tests: 0"))) + assert(clue(output.contains("Number of failed tests: 0"))) + assert(clue(output.contains("End Report"))) } test("full results with failed") { @@ -110,24 +110,24 @@ class StdOutReporterTest extends FunSuite { // Assertions // report header & tail - assertEquals(true, clue(output.contains("Simple Text Report"))) - assertEquals(true, clue(output.contains("Number of tests run: 3"))) - assertEquals(true, clue(output.contains("Number of successful tests: 2"))) - assertEquals(true, clue(output.contains("Number of failed tests: 1"))) - assertEquals(true, clue(output.contains("End Report"))) + assert(clue(output.contains("Simple Text Report"))) + assert(clue(output.contains("Number of tests run: 3"))) + assert(clue(output.contains("Number of successful tests: 2"))) + assert(clue(output.contains("Number of failed tests: 1"))) + assert(clue(output.contains("End Report"))) // suite summary - assertEquals(true, clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 1, Failed: 1"))) - assertEquals(true, clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) + assert(clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 1, Failed: 1"))) + assert(clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) // summary of all tests val updatedOutput = output.replace(" ", "") - assertEquals(true, clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) - assertEquals(true, clue(updatedOutput.contains("|Suite1|Test2|200|Failure|Category2|"))) - assertEquals(true, clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) + assert(clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) + assert(clue(updatedOutput.contains("|Suite1|Test2|200|Failure|Category2|"))) + assert(clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) // error from detail - assertEquals(true, clue(output.contains("Assertion failed: Error message"))) + assert(clue(output.contains("Assertion failed: Error message"))) } test("results all success") { @@ -142,20 +142,20 @@ class StdOutReporterTest extends FunSuite { // Assertions // report header & tail - assertEquals(true, clue(output.contains("Simple Text Report"))) - assertEquals(true, clue(output.contains("Number of tests run: 3"))) - assertEquals(true, clue(output.contains("Number of successful tests: 3"))) - assertEquals(true, clue(output.contains("Number of failed tests: 0"))) - assertEquals(true, clue(output.contains("End Report"))) + assert(clue(output.contains("Simple Text Report"))) + assert(clue(output.contains("Number of tests run: 3"))) + assert(clue(output.contains("Number of successful tests: 3"))) + assert(clue(output.contains("Number of failed tests: 0"))) + assert(clue(output.contains("End Report"))) // suite summary - assertEquals(true, clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 2, Failed: 0"))) - assertEquals(true, clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) + assert(clue(output.contains("Suite: Suite 1, Total tests: 2, Successful: 2, Failed: 0"))) + assert(clue(output.contains("Suite: Suite 2, Total tests: 1, Successful: 1, Failed: 0"))) // summary of all tests val updatedOutput = output.replace(" ", "") - assertEquals(true, clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) - assertEquals(true, clue(updatedOutput.contains("|Suite1|Test2|200|Success|Category2|"))) - assertEquals(true, clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) + assert(clue(updatedOutput.contains("|Suite1|Test1|100|Success|Category1|"))) + assert(clue(updatedOutput.contains("|Suite1|Test2|200|Success|Category2|"))) + assert(clue(updatedOutput.contains("|Suite2|Test1|50|Success|Category3|"))) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index 4cea6b3..e1b9e19 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -18,7 +18,6 @@ package africa.absa.testing.scapi.suite.runner import africa.absa.testing.scapi.json.{Action, Environment, Header, ResponseAction} import africa.absa.testing.scapi.logging.Logger -import africa.absa.testing.scapi.model._ import africa.absa.testing.scapi.model.suite._ import africa.absa.testing.scapi.model.suite.types.SuiteResultType import africa.absa.testing.scapi.rest.RestClient @@ -108,9 +107,9 @@ class SuiteRunnerTest extends FunSuite { val beforeSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2").get - assertEquals(5, clue(suiteResults.size)) - assertEquals("test", clue(beforeSuiteResult.name)) - assertEquals(true, clue(beforeSuiteResult.isSuccess)) + assert(5 == clue(suiteResults.size)) + assert("test" == clue(beforeSuiteResult.name)) + assert(clue(beforeSuiteResult.isSuccess)) } test("runSuite - SuiteBefore empty") { @@ -119,7 +118,7 @@ class SuiteRunnerTest extends FunSuite { val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2") - assertEquals(2, clue(suiteResults.size)) + assert(2 == clue(suiteResults.size)) assert(beforeSuiteResult.isEmpty) } @@ -129,9 +128,9 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get - assertEquals(5, clue(suiteResults.size)) - assertEquals("test", clue(afterSuiteResult.name)) - assertEquals(true, clue(afterSuiteResult.isSuccess)) + assert(5 == clue(suiteResults.size)) + assert("test" == clue(afterSuiteResult.name)) + assert(clue(afterSuiteResult.isSuccess)) } test("runSuite - SuiteAfter empty") { @@ -140,7 +139,7 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2") - assertEquals(2, clue(suiteResults.size)) + assert(2 == clue(suiteResults.size)) assert(afterSuiteResult.isEmpty) } @@ -150,8 +149,8 @@ class SuiteRunnerTest extends FunSuite { val afterSuiteResult: SuiteResult = suiteResults.find(result => result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get - assertEquals(2, clue(suiteResults.size)) - assertEquals(false, clue(afterSuiteResult.isSuccess)) - assertEquals("RestClient:sendRequest - unexpected action method called", afterSuiteResult.errorMsg.get) + assert(2 == clue(suiteResults.size)) + assert(clue(!afterSuiteResult.isSuccess)) + assert("RestClient:sendRequest - unexpected action method called" == afterSuiteResult.errorMsg.get) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala index 2a593b4..7e90eb9 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/utils/cache/RuntimeCacheTest.scala @@ -31,28 +31,28 @@ class RuntimeCacheTest extends FunSuite { test("put") { RuntimeCache.put("key", "value") - assertEquals(clue(Some("value")), clue(RuntimeCache.get("key"))) + assert(clue(Some("value")) == clue(RuntimeCache.get("key"))) } test("put - with level") { RuntimeCache.put("g", "g", GlobalLevel) RuntimeCache.put("s", "s", SuiteLevel) RuntimeCache.put("t", "t", TestLevel) - assertEquals(clue(Some("g")), clue(RuntimeCache.get("g"))) - assertEquals(clue(Some("s")), clue(RuntimeCache.get("s"))) - assertEquals(clue(Some("t")), clue(RuntimeCache.get("t"))) + assert(clue(Some("g")) == clue(RuntimeCache.get("g"))) + assert(clue(Some("s")) == clue(RuntimeCache.get("s"))) + assert(clue(Some("t")) == clue(RuntimeCache.get("t"))) } test("put - already exists - on same level") { RuntimeCache.put("key", "valueA") RuntimeCache.put("key", "valueB") - assertEquals(clue(Some("valueA")), clue(RuntimeCache.get("key"))) + assert(clue(Some("valueA")) == clue(RuntimeCache.get("key"))) } test("put - already exists - on different level") { RuntimeCache.put("key", "valueA", TestLevel) RuntimeCache.put("key", "valueB", SuiteLevel) - assertEquals(clue(Some("valueA")), clue(RuntimeCache.get("key"))) + assert(clue(Some("valueA")) == clue(RuntimeCache.get("key"))) } /* @@ -61,7 +61,7 @@ class RuntimeCacheTest extends FunSuite { // smoke possitive tested during put tests - skipped here test("get - nonexistent key") { - assertEquals(None, clue(RuntimeCache.get("nonexistent"))) + assert(clue(RuntimeCache.get("nonexistent")).isEmpty) } /* @@ -71,7 +71,7 @@ class RuntimeCacheTest extends FunSuite { test("update") { RuntimeCache.put("key", "value") RuntimeCache.update("key", "newValue") - assertEquals(clue(Some("newValue")), clue(RuntimeCache.get("key"))) + assert(clue(Some("newValue")) == clue(RuntimeCache.get("key"))) } test("update - nonexistent key") { @@ -86,7 +86,7 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(clue(Some("newValue")), clue(RuntimeCache.get("key"))) + assert(clue(Some("newValue")) == clue(RuntimeCache.get("key"))) } test("update - with level down") { @@ -95,7 +95,7 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(None, clue(RuntimeCache.get("nonexistent"))) + assert(clue(RuntimeCache.get("nonexistent")).isEmpty) } /* @@ -106,7 +106,7 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.put("key", "value") RuntimeCache.remove("key") - assertEquals(None, RuntimeCache.get("nonexistent")) + assert(RuntimeCache.get("nonexistent").isEmpty) } test("remove - key no exist") { @@ -125,9 +125,9 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(GlobalLevel) - assertEquals(None, clue(RuntimeCache.get("key1"))) - assertEquals(None, clue(RuntimeCache.get("key2"))) - assertEquals(None, clue(RuntimeCache.get("key3"))) + assert(clue(RuntimeCache.get("key1")).isEmpty) + assert(clue(RuntimeCache.get("key2")).isEmpty) + assert(clue(RuntimeCache.get("key3")).isEmpty) } test("expire - suite level") { @@ -136,8 +136,8 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(SuiteLevel) - assertEquals(None, clue(RuntimeCache.get("key1"))) - assertEquals(None, clue(RuntimeCache.get("key2"))) + assert(clue(RuntimeCache.get("key1")).isEmpty) + assert(clue(RuntimeCache.get("key2")).isEmpty) } test("expire - test level") { @@ -146,8 +146,8 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.expire(TestLevel) - assertEquals(None, clue(RuntimeCache.get("key2"))) - assertEquals(clue(Some("value1")), clue(RuntimeCache.get("key1"))) + assert(clue(RuntimeCache.get("key2")).isEmpty) + assert(clue(Some("value1")) == clue(RuntimeCache.get("key1"))) } /* @@ -161,9 +161,9 @@ class RuntimeCacheTest extends FunSuite { RuntimeCache.reset() - assertEquals(None, clue(RuntimeCache.get("key1"))) - assertEquals(None, clue(RuntimeCache.get("key2"))) - assertEquals(None, clue(RuntimeCache.get("key3"))) + assert(clue(RuntimeCache.get("key1")).isEmpty) + assert(clue(RuntimeCache.get("key2")).isEmpty) + assert(clue(RuntimeCache.get("key3")).isEmpty) } /* @@ -171,10 +171,10 @@ class RuntimeCacheTest extends FunSuite { */ test("determineLevel") { - assertEquals(GlobalLevel, clue(RuntimeCache.determineLevel("global"))) - assertEquals(SuiteLevel, clue(RuntimeCache.determineLevel("suite"))) - assertEquals(TestLevel, clue(RuntimeCache.determineLevel("test"))) - assertEquals(TestLevel, clue(RuntimeCache.determineLevel("unknown"))) + assert(GlobalLevel == clue(RuntimeCache.determineLevel("global"))) + assert(SuiteLevel == clue(RuntimeCache.determineLevel("suite"))) + assert(TestLevel == clue(RuntimeCache.determineLevel("test"))) + assert(TestLevel == clue(RuntimeCache.determineLevel("unknown"))) } /* @@ -183,7 +183,7 @@ class RuntimeCacheTest extends FunSuite { test("resolve") { RuntimeCache.put("key", "value") - assertEquals("value", clue(RuntimeCache.resolve("{{ cache.key }}"))) + assert("value".==(clue(RuntimeCache.resolve("{{ cache.key }}")))) } test("resolve - key not exist") { @@ -201,12 +201,12 @@ class RuntimeCacheTest extends FunSuite { test("resolve - no placeholder to resolve") { RuntimeCache.put("key", "value") - assertEquals("cache.key", clue(RuntimeCache.resolve("cache.key"))) + assert("cache.key" == clue(RuntimeCache.resolve("cache.key"))) } test("resolve - mixed placeholders") { RuntimeCache.put("key", "value") - assertEquals("value and {{ not.cache.key }}", clue(RuntimeCache.resolve("{{ cache.key }} and {{ not.cache.key }}"))) + assert("value and {{ not.cache.key }}" == clue(RuntimeCache.resolve("{{ cache.key }} and {{ not.cache.key }}"))) } test("resolve - empty key") { @@ -217,6 +217,6 @@ class RuntimeCacheTest extends FunSuite { test("resolve - empty value") { RuntimeCache.put("key", "") - assertEquals("", clue(RuntimeCache.resolve("{{ cache.key }}"))) + assert("".==(clue(RuntimeCache.resolve("{{ cache.key }}")))) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/FileUtilsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/FileUtilsTest.scala index 6347568..be65da7 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/FileUtilsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/FileUtilsTest.scala @@ -45,7 +45,7 @@ class FileUtilsTest extends FunSuite { val matchingFiles = FileUtils.findMatchingFiles(tmpDir.toString) - assertEquals(clue(expectedFiles), clue(matchingFiles)) + assert(clue(expectedFiles) == clue(matchingFiles)) } test("find matching files - custom filter") { @@ -54,7 +54,7 @@ class FileUtilsTest extends FunSuite { val matchingFiles = FileUtils.findMatchingFiles(tmpDir.toString, "(.*).json") - assertEquals(clue(expectedFiles), clue(matchingFiles)) + assert(clue(expectedFiles) == clue(matchingFiles)) } test("find matching files - no found") { @@ -63,7 +63,7 @@ class FileUtilsTest extends FunSuite { val matchingFiles = FileUtils.findMatchingFiles(tmpDir.toString, "(.*).nonsense") - assertEquals(clue(expectedFiles), clue(matchingFiles)) + assert(clue(expectedFiles) == clue(matchingFiles)) } test("find matching files - subdirectories") { @@ -72,7 +72,7 @@ class FileUtilsTest extends FunSuite { val matchingFiles = FileUtils.findMatchingFiles(tmpDir.toString, "(.*).xml") - assertEquals(clue(expectedFiles), clue(matchingFiles)) + assert(clue(expectedFiles) == clue(matchingFiles)) } /* @@ -85,8 +85,8 @@ class FileUtilsTest extends FunSuite { val (actualPath, actualFileName) = FileUtils.splitPathAndFileName(filePath) - assertEquals(clue(expectedPath), clue(actualPath)) - assertEquals(clue(expectedFileName), clue(actualFileName)) + assert(clue(expectedPath) == clue(actualPath)) + assert(clue(expectedFileName) == clue(actualFileName)) } test("split to path and fileName - empty input") { @@ -94,8 +94,8 @@ class FileUtilsTest extends FunSuite { val (actualPath, actualFileName) = FileUtils.splitPathAndFileName(filePath) - assertEquals("", clue(actualPath)) - assertEquals("", clue(actualFileName)) + assert("".==(clue(actualPath))) + assert("".==(clue(actualFileName))) } test("split to path and fileName - fileName only") { @@ -103,8 +103,8 @@ class FileUtilsTest extends FunSuite { val (path, fileName) = FileUtils.splitPathAndFileName(filePath) - assertEquals(clue(path), "") - assertEquals(clue(fileName), "filename.txt") + assert("".==(clue(path))) + assert("filename.txt".==(clue(fileName))) } test("split to path and fileName - dir path only") { @@ -115,9 +115,9 @@ class FileUtilsTest extends FunSuite { val (actualPath, actualFileName) = FileUtils.splitPathAndFileName(filePath) val (actualPathEndSlash, actualFileNameEndSlash) = FileUtils.splitPathAndFileName(filePathEndSlash) - assertEquals(clue(expectedPath), clue(actualPath)) - assertEquals(clue(expectedPath), clue(actualPathEndSlash)) - assertEquals("to", clue(actualFileName)) - assertEquals("to", clue(actualFileNameEndSlash)) + assert(clue(expectedPath) == clue(actualPath)) + assert(clue(expectedPath) == clue(actualPathEndSlash)) + assert("to".==(clue(actualFileName))) + assert("to".==(clue(actualFileNameEndSlash))) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/JsonUtilsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/JsonUtilsTest.scala index daf99ed..2d6b513 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/JsonUtilsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/utils/file/JsonUtilsTest.scala @@ -36,7 +36,7 @@ class JsonUtilsTest extends FunSuite { emptyFile.deleteOnExit() val result = JsonUtils.stringFromPath(emptyFile.getAbsolutePath) - assertEquals("", clue(result)) + assert("" == clue(result)) } test("jsonStringFromPath with valid JSON file") { @@ -48,6 +48,6 @@ class JsonUtilsTest extends FunSuite { } val result = JsonUtils.stringFromPath(jsonFile.getAbsolutePath) - assertEquals("""{"name": "test"}""", clue(result)) + assert("""{"name": "test"}""" == clue(result)) } } From 236cbae225eb8148bcbf446e20de165d9aa08a79 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 2 Nov 2023 09:46:35 +0100 Subject: [PATCH 30/31] * Fix - removed used only keyword from test name. --- .../scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala index fda2e90..579ef7a 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/json/SuiteFactoryTest.scala @@ -128,7 +128,7 @@ class SuiteFactoryTest extends FunSuite { /* filterOnlyOrAll */ - test("filterOnlyOrAll - only used - once".only) { + test("filterOnlyOrAll - only used - once") { val suitesBundles = Set( Suite(suite = TestSet(name = "name1", tests = Set( SuiteTestScenario(name = "test1", categories = Seq("SMOKE"), headers = Seq.empty, actions = Seq.empty, responseActions = Seq.empty, only = Some(false)), From 4e0d029d469d328ef6092c7a0947d3e6deab8015 Mon Sep 17 00:00:00 2001 From: miroslavpojer Date: Thu, 2 Nov 2023 15:50:50 +0100 Subject: [PATCH 31/31] * Fix - Applied Scala CamelCase to enumaration contants. --- .../model/suite/types/SuiteResultType.scala | 6 +- .../scapi/reporter/StdOutReporter.scala | 8 +- .../scapi/rest/response/Response.scala | 12 +- .../action/AssertionResponseAction.scala | 72 +++++----- .../action/ExtractJsonResponseAction.scala | 22 ++-- .../response/action/LogResponseAction.scala | 10 +- .../types/AssertResponseActionType.scala | 32 ++--- .../types/ExtractJsonResponseActionType.scala | 2 +- .../action/types/LogResponseActionType.scala | 8 +- .../types/ResponseActionGroupType.scala | 8 +- .../scapi/suite/runner/SuiteRunner.scala | 14 +- .../scapi/reporter/StdOutReporterTest.scala | 12 +- .../response/ResponseAssertionsTest.scala | 124 +++++++++--------- .../rest/response/ResponseExtractTest.scala | 20 +-- .../scapi/rest/response/ResponseLogTest.scala | 18 +-- .../scapi/suite/runner/SuiteRunnerTest.scala | 12 +- 16 files changed, 190 insertions(+), 190 deletions(-) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala index 11ea8e7..543997b 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/model/suite/types/SuiteResultType.scala @@ -19,7 +19,7 @@ package africa.absa.testing.scapi.model.suite.types object SuiteResultType extends Enumeration { type SuiteResultType = Value - val BEFORE_TEST_SET: SuiteResultType.Value = Value("before-test-set") - val TEST_SET: SuiteResultType.Value = Value("test-set") - val AFTER_TEST_SET: SuiteResultType.Value = Value("after-test-set") + val BeforeTestSet: SuiteResultType.Value = Value("before-test-set") + val TestSet: SuiteResultType.Value = Value("test-set") + val AfterTestSet: SuiteResultType.Value = Value("after-test-set") } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala index 26c8512..9413b1e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/reporter/StdOutReporter.scala @@ -59,8 +59,8 @@ object StdOutReporter { printHeader("Simple Text Report") - val successCount = testResults.count(r => r.isSuccess && r.resultType == SuiteResultType.TEST_SET) - val failureCount = testResults.count(r => !r.isSuccess && r.resultType == SuiteResultType.TEST_SET) + val successCount = testResults.count(r => r.isSuccess && r.resultType == SuiteResultType.TestSet) + val failureCount = testResults.count(r => !r.isSuccess && r.resultType == SuiteResultType.TestSet) println(s"Number of tests run: ${successCount + failureCount}") println(s"Number of successful tests: $successCount") @@ -68,7 +68,7 @@ object StdOutReporter { if (testResults.nonEmpty) { val suiteSummary = testResults - .filter(_.resultType == SuiteResultType.TEST_SET) + .filter(_.resultType == SuiteResultType.TestSet) .groupBy(_.suiteName).map { case (suiteName, results) => (suiteName, results.size, results.count(_.isSuccess)) @@ -84,7 +84,7 @@ object StdOutReporter { printTableRowSplitter() println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %-13s | %-7s | %-${maxTestCategoriesLength}s | ".format("Suite Name", "Test Name", "Duration (ms)", "Status", "Categories")) printTableRowSplitter() - val resultsList = testResults.filter(_.resultType == SuiteResultType.TEST_SET) + val resultsList = testResults.filter(_.resultType == SuiteResultType.TestSet) resultsList.zipWithIndex.foreach { case (result, index) => val duration = result.duration.map(_.toString).getOrElse("NA") println(s"| %-${maxSuiteLength}s | %-${maxTestLength}s | %13s | %-7s | %-${maxTestCategoriesLength}s | ".format( diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala index 5e9e902..f3ce594 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/Response.scala @@ -46,9 +46,9 @@ object Response { */ def validate(responseAction: ResponseAction): Unit = { responseAction.group match { - case ResponseActionGroupType.ASSERT => AssertionResponseAction.validateContent(responseAction) - case ResponseActionGroupType.EXTRACT_JSON => ExtractJsonResponseAction.validateContent(responseAction) - case ResponseActionGroupType.LOG => LogResponseAction.validateContent(responseAction) + case ResponseActionGroupType.Assert => AssertionResponseAction.validateContent(responseAction) + case ResponseActionGroupType.ExtractJson => ExtractJsonResponseAction.validateContent(responseAction) + case ResponseActionGroupType.Log => LogResponseAction.validateContent(responseAction) case _ => throw new IllegalArgumentException(s"Unsupported assertion group: ${responseAction.group}") } } @@ -85,9 +85,9 @@ object Response { Logger.debug(s"Response-${resolvedResponseAction.group}: '${resolvedResponseAction.name}' - Started.") val res: Try[Unit] = resolvedResponseAction.group match { - case ResponseActionGroupType.ASSERT => AssertionResponseAction.performResponseAction(response, assertion) - case ResponseActionGroupType.EXTRACT_JSON => ExtractJsonResponseAction.performResponseAction(response, assertion) - case ResponseActionGroupType.LOG => LogResponseAction.performResponseAction(response, assertion) + case ResponseActionGroupType.Assert => AssertionResponseAction.performResponseAction(response, assertion) + case ResponseActionGroupType.ExtractJson => ExtractJsonResponseAction.performResponseAction(response, assertion) + case ResponseActionGroupType.Log => LogResponseAction.performResponseAction(response, assertion) case _ => Failure(new IllegalArgumentException(s"Unsupported assertion group: ${assertion.group}")) } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala index 59bfe6a..84dae75 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/AssertionResponseAction.scala @@ -44,58 +44,58 @@ object AssertionResponseAction extends ResponseActions { action match { // response-time-... - case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => + case ResponseTimeIsBelow | ResponseTimeIsAbove => responseAction.params.getOrElse("limit", None) match { case limit: String => ContentValidator.validateLongString(limit, s"ResponseAssertion.${responseAction.name}.limit") case None => throw new IllegalArgumentException(s"Missing required 'limit' parameter for assertion ${responseAction.name} logic.") } // status-code-... - case STATUS_CODE_EQUALS => + case StatusCodeEquals => responseAction.params.getOrElse("code", None) match { - case code: String => ContentValidator.validateIntegerString(code, s"ResponseAssertion.$STATUS_CODE_EQUALS.code") - case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $STATUS_CODE_EQUALS logic.") + case code: String => ContentValidator.validateIntegerString(code, s"ResponseAssertion.$StatusCodeEquals.code") + case None => throw new IllegalArgumentException(s"Missing required 'code' parameter for assertion $StatusCodeEquals logic.") } - case STATUS_CODE_IS_SUCCESS | STATUS_CODE_IS_CLIENT_ERROR | STATUS_CODE_IS_SERVER_ERROR => () + case StatusCodeIsSuccess | StatusCodeIsClientError | StatusCodeIsServerError => () // header-... - case HEADER_EXISTS | HEADER_VALUE_EQUALS => + case HeaderExists | HeaderValueEquals => responseAction.params.getOrElse("headerName", None) match { case headerName: String => ContentValidator.validateNonEmptyString(headerName, s"ResponseAssertion.${responseAction.name}.headerName") case None => throw new IllegalArgumentException(s"Missing required 'headerName' parameter for assertion ${responseAction.name} logic.") } action match { - case HEADER_VALUE_EQUALS => + case HeaderValueEquals => responseAction.params.getOrElse("expectedValue", None) match { - case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$HEADER_VALUE_EQUALS.expectedValue") - case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $HEADER_VALUE_EQUALS logic.") + case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$HeaderValueEquals.expectedValue") + case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $HeaderValueEquals logic.") } case _ => () } // content-type-... - case CONTENT_TYPE_IS_JSON | CONTENT_TYPE_IS_XML | CONTENT_TYPE_IS_HTML => () + case ContentTypeIsJson | ContentTypeIsXml | ContentTypeIsHtml => () // cookies-... - case COOKIE_EXISTS | COOKIE_VALUE_EQUALS | COOKIE_IS_SECURED | COOKIE_IS_NOT_SECURED => + case CookieExists | CookieValueEquals | CookieIsSecured | CookieIsNotSecured => responseAction.params.getOrElse("cookieName", None) match { case cookieName: String => ContentValidator.validateNonEmptyString(cookieName, s"ResponseAssertion.${responseAction.name}.cookieName") case None => throw new IllegalArgumentException(s"Missing required 'cookieName' parameter for assertion ${responseAction.name} logic.") } action match { - case COOKIE_VALUE_EQUALS => + case CookieValueEquals => responseAction.params.getOrElse("expectedValue", None) match { - case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$COOKIE_VALUE_EQUALS.expectedValue") - case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $COOKIE_VALUE_EQUALS logic.") + case expectedValue: String => ContentValidator.validateNonEmptyString(expectedValue, s"ResponseAssertion.$CookieValueEquals.expectedValue") + case None => throw new IllegalArgumentException(s"Missing required 'expectedValue' parameter for assertion $CookieValueEquals logic.") } case _ => () } // body-... - case BODY_CONTAINS_TEXT => + case BodyContainsText => responseAction.params.getOrElse("text", None) match { - case text: String => ContentValidator.validateNonEmptyString(text, s"ResponseAssertion.$BODY_CONTAINS_TEXT.text") - case None => throw new IllegalArgumentException(s"Missing required 'text' parameter for assertion $BODY_CONTAINS_TEXT logic.") + case text: String => ContentValidator.validateNonEmptyString(text, s"ResponseAssertion.$BodyContainsText.text") + case None => throw new IllegalArgumentException(s"Missing required 'text' parameter for assertion $BodyContainsText logic.") } case _ => throw UndefinedResponseActionTypeException(responseAction.name) } @@ -114,50 +114,50 @@ object AssertionResponseAction extends ResponseActions { action match { // response-time-... - case RESPONSE_TIME_IS_BELOW | RESPONSE_TIME_IS_ABOVE => + case ResponseTimeIsBelow | ResponseTimeIsAbove => val limit = responseAction.params("limit") action match { - case RESPONSE_TIME_IS_BELOW => assertResponseTimeIsBelow(response, limit) - case RESPONSE_TIME_IS_ABOVE => assertResponseTimeIsAbove(response, limit) + case ResponseTimeIsBelow => assertResponseTimeIsBelow(response, limit) + case ResponseTimeIsAbove => assertResponseTimeIsAbove(response, limit) } // status-code-... - case STATUS_CODE_EQUALS => + case StatusCodeEquals => val code = responseAction.params("code") assertStatusCodeEquals(response, code) - case STATUS_CODE_IS_SUCCESS => assertStatusCodeSuccess(response) - case STATUS_CODE_IS_CLIENT_ERROR => assertStatusCodeIsClientError(response) - case STATUS_CODE_IS_SERVER_ERROR => assertStatusCodeIsServerError(response) + case StatusCodeIsSuccess => assertStatusCodeSuccess(response) + case StatusCodeIsClientError => assertStatusCodeIsClientError(response) + case StatusCodeIsServerError => assertStatusCodeIsServerError(response) // header-... - case HEADER_EXISTS | HEADER_VALUE_EQUALS => + case HeaderExists | HeaderValueEquals => val headerName = responseAction.params("headerName") action match { - case HEADER_EXISTS => assertHeaderExists(response, headerName) - case HEADER_VALUE_EQUALS => + case HeaderExists => assertHeaderExists(response, headerName) + case HeaderValueEquals => val expectedValue = responseAction.params("expectedValue") assertHeaderValueEquals(response, headerName, expectedValue) } // content-type-... - case CONTENT_TYPE_IS_JSON => assertContentTypeIsJson(response) - case CONTENT_TYPE_IS_XML => assertContentTypeIsXml(response) - case CONTENT_TYPE_IS_HTML => assertContentTypeIsHtml(response) + case ContentTypeIsJson => assertContentTypeIsJson(response) + case ContentTypeIsXml => assertContentTypeIsXml(response) + case ContentTypeIsHtml => assertContentTypeIsHtml(response) // cookies-... - case COOKIE_EXISTS | COOKIE_VALUE_EQUALS | COOKIE_IS_SECURED | COOKIE_IS_NOT_SECURED => + case CookieExists | CookieValueEquals | CookieIsSecured | CookieIsNotSecured => val cookieName = responseAction.params("cookieName") action match { - case COOKIE_EXISTS => assertCookieExists(response, cookieName) - case COOKIE_VALUE_EQUALS => + case CookieExists => assertCookieExists(response, cookieName) + case CookieValueEquals => val expectedValue = responseAction.params("expectedValue") assertCookieValueEquals(response, cookieName, expectedValue) - case COOKIE_IS_SECURED => assertCookieIsSecured(response, cookieName) - case COOKIE_IS_NOT_SECURED => assertCookieIsNotSecured(response, cookieName) + case CookieIsSecured => assertCookieIsSecured(response, cookieName) + case CookieIsNotSecured => assertCookieIsNotSecured(response, cookieName) } // body-... - case BODY_CONTAINS_TEXT => + case BodyContainsText => val text = responseAction.params("text") assertBodyContainsText(response, text) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala index 8b56f7c..e3cd7d9 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/ExtractJsonResponseAction.scala @@ -42,7 +42,7 @@ object ExtractJsonResponseAction extends ResponseActions { def validateContent(responseAction: ResponseAction): Unit = { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) action match { - case STRING_FROM_LIST => validateStringFromList(responseAction) + case StringFromList => validateStringFromList(responseAction) case _ => throw UndefinedResponseActionTypeException(responseAction.name) } } @@ -57,7 +57,7 @@ object ExtractJsonResponseAction extends ResponseActions { def performResponseAction(response: Response, responseAction: ResponseAction): Try[Unit] = { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) action match { - case STRING_FROM_LIST => + case StringFromList => val cacheKey = responseAction.params("cacheKey") val listIndex = responseAction.params("listIndex").toInt val jsonKey = responseAction.params("jsonKey") @@ -119,17 +119,17 @@ object ExtractJsonResponseAction extends ResponseActions { * @param assertion The ResponseAction instance containing the response action details. */ private def validateStringFromList(assertion: ResponseAction): Unit = { - val cacheKey = assertion.params.getOrElse("cacheKey", throw new IllegalArgumentException(s"Missing required 'cacheKey' parameter for extract $STRING_FROM_LIST logic")) - val listIndex = assertion.params.getOrElse("listIndex", throw new IllegalArgumentException(s"Missing required 'listIndex' parameter for extract $STRING_FROM_LIST logic")) - val jsonKey = assertion.params.getOrElse("jsonKey", throw new IllegalArgumentException(s"Missing required 'jsonKey' parameter for extract $STRING_FROM_LIST logic")) - val cacheLevel = assertion.params.getOrElse("cacheLevel", throw new IllegalArgumentException(s"Missing required 'cacheLevel' parameter for extract $STRING_FROM_LIST logic")) + val cacheKey = assertion.params.getOrElse("cacheKey", throw new IllegalArgumentException(s"Missing required 'cacheKey' parameter for extract $StringFromList logic")) + val listIndex = assertion.params.getOrElse("listIndex", throw new IllegalArgumentException(s"Missing required 'listIndex' parameter for extract $StringFromList logic")) + val jsonKey = assertion.params.getOrElse("jsonKey", throw new IllegalArgumentException(s"Missing required 'jsonKey' parameter for extract $StringFromList logic")) + val cacheLevel = assertion.params.getOrElse("cacheLevel", throw new IllegalArgumentException(s"Missing required 'cacheLevel' parameter for extract $StringFromList logic")) - ContentValidator.validateNonEmptyString(cacheKey, s"ExtractJson.$STRING_FROM_LIST.cacheKey") - ContentValidator.validateNonEmptyString(listIndex, s"ExtractJson.$STRING_FROM_LIST.listIndex") - ContentValidator.validateNonEmptyString(jsonKey, s"ExtractJson.$STRING_FROM_LIST.jsonKey") - ContentValidator.validateNonEmptyString(cacheLevel, s"ExtractJson.$STRING_FROM_LIST.cacheLevel") + ContentValidator.validateNonEmptyString(cacheKey, s"ExtractJson.$StringFromList.cacheKey") + ContentValidator.validateNonEmptyString(listIndex, s"ExtractJson.$StringFromList.listIndex") + ContentValidator.validateNonEmptyString(jsonKey, s"ExtractJson.$StringFromList.jsonKey") + ContentValidator.validateNonEmptyString(cacheLevel, s"ExtractJson.$StringFromList.cacheLevel") - ContentValidator.validateIntegerString(listIndex, s"ExtractJson.$STRING_FROM_LIST.listIndex") + ContentValidator.validateIntegerString(listIndex, s"ExtractJson.$StringFromList.listIndex") } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala index b502647..c2f278e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/LogResponseAction.scala @@ -40,7 +40,7 @@ object LogResponseAction extends ResponseActions { def validateContent(responseAction: ResponseAction): Unit = { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) action match { - case ERROR | WARN | INFO | DEBUG => + case Error | Warn | Info | Debug => responseAction.params.get("message") match { case Some(message) => ContentValidator.validateNonEmptyString(message, s"ResponseLog.${responseAction.name}.message") case None => throw new IllegalArgumentException(s"Missing required 'message' for assertion ${responseAction.name} logic.") @@ -62,10 +62,10 @@ object LogResponseAction extends ResponseActions { val action = fromString(responseAction.name.toLowerCase).getOrElse(None) Try { action match { - case ERROR => logError(message) - case WARN => logWarn(message) - case INFO => logInfo(message) - case DEBUG => logDebug(message) + case Error => logError(message) + case Warn => logWarn(message) + case Info => logInfo(message) + case Debug => logDebug(message) case _ => Failure(UndefinedResponseActionTypeException(s"Unsupported log method [group: log]: ${responseAction.name}")) } } diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala index a0b07b3..fb91c9e 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/AssertResponseActionType.scala @@ -22,32 +22,32 @@ object AssertResponseActionType extends Enumeration { type AssertResponseActionType = Value // response-time-... - val RESPONSE_TIME_IS_BELOW: AssertResponseActionType.Value = Value("response-time-is-below") - val RESPONSE_TIME_IS_ABOVE: AssertResponseActionType.Value = Value("response-time-is-above") + val ResponseTimeIsBelow: AssertResponseActionType.Value = Value("response-time-is-below") + val ResponseTimeIsAbove: AssertResponseActionType.Value = Value("response-time-is-above") // status-code-... - val STATUS_CODE_EQUALS: AssertResponseActionType.Value = Value("status-code-equals") - val STATUS_CODE_IS_SUCCESS: AssertResponseActionType.Value = Value("status-code-is-success") - val STATUS_CODE_IS_CLIENT_ERROR: AssertResponseActionType.Value = Value("status-code-is-client-error") - val STATUS_CODE_IS_SERVER_ERROR: AssertResponseActionType.Value = Value("status-code-is-server-error") + val StatusCodeEquals: AssertResponseActionType.Value = Value("status-code-equals") + val StatusCodeIsSuccess: AssertResponseActionType.Value = Value("status-code-is-success") + val StatusCodeIsClientError: AssertResponseActionType.Value = Value("status-code-is-client-error") + val StatusCodeIsServerError: AssertResponseActionType.Value = Value("status-code-is-server-error") // header-... - val HEADER_EXISTS: AssertResponseActionType.Value = Value("header-exists") - val HEADER_VALUE_EQUALS: AssertResponseActionType.Value = Value("header-value-equals") + val HeaderExists: AssertResponseActionType.Value = Value("header-exists") + val HeaderValueEquals: AssertResponseActionType.Value = Value("header-value-equals") // content-type-... - val CONTENT_TYPE_IS_JSON: AssertResponseActionType.Value = Value("content-type-is-json") - val CONTENT_TYPE_IS_XML: AssertResponseActionType.Value = Value("content-type-is-xml") - val CONTENT_TYPE_IS_HTML: AssertResponseActionType.Value = Value("content-type-is-html") + val ContentTypeIsJson: AssertResponseActionType.Value = Value("content-type-is-json") + val ContentTypeIsXml: AssertResponseActionType.Value = Value("content-type-is-xml") + val ContentTypeIsHtml: AssertResponseActionType.Value = Value("content-type-is-html") // cookies-... - val COOKIE_EXISTS: AssertResponseActionType.Value = Value("cookie-exists") - val COOKIE_VALUE_EQUALS: AssertResponseActionType.Value = Value("cookie-value-equals") - val COOKIE_IS_SECURED: AssertResponseActionType.Value = Value("cookie-is-secured") - val COOKIE_IS_NOT_SECURED: AssertResponseActionType.Value = Value("cookie-is-not-secured") + val CookieExists: AssertResponseActionType.Value = Value("cookie-exists") + val CookieValueEquals: AssertResponseActionType.Value = Value("cookie-value-equals") + val CookieIsSecured: AssertResponseActionType.Value = Value("cookie-is-secured") + val CookieIsNotSecured: AssertResponseActionType.Value = Value("cookie-is-not-secured") // body-... - val BODY_CONTAINS_TEXT: AssertResponseActionType.Value = Value("body-contains-text") + val BodyContainsText: AssertResponseActionType.Value = Value("body-contains-text") private val stringToValueMap = values.map(v => v.toString -> v).toMap diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala index 7b362a2..99b82eb 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ExtractJsonResponseActionType.scala @@ -21,7 +21,7 @@ import scala.language.implicitConversions object ExtractJsonResponseActionType extends Enumeration { type ExtractJsonResponseActionType = Value - val STRING_FROM_LIST: ExtractJsonResponseActionType.Value = Value("string-from-list") + val StringFromList: ExtractJsonResponseActionType.Value = Value("string-from-list") private val stringToValueMap = values.map(v => v.toString -> v).toMap diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala index 3cd29c3..9c91945 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/LogResponseActionType.scala @@ -21,10 +21,10 @@ import scala.language.implicitConversions object LogResponseActionType extends Enumeration { type LogResponseActionType = Value - val ERROR: LogResponseActionType.Value = Value("error") - val WARN: LogResponseActionType.Value = Value("warn") - val INFO: LogResponseActionType.Value = Value("info") - val DEBUG: LogResponseActionType.Value = Value("debug") + val Error: LogResponseActionType.Value = Value("error") + val Warn: LogResponseActionType.Value = Value("warn") + val Info: LogResponseActionType.Value = Value("info") + val Debug: LogResponseActionType.Value = Value("debug") private val stringToValueMap = values.map(v => v.toString -> v).toMap diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala index bd568ca..1ed1b70 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/rest/response/action/types/ResponseActionGroupType.scala @@ -17,13 +17,13 @@ package africa.absa.testing.scapi.rest.response.action.types object ResponseActionGroupType extends Enumeration { - val ASSERT, EXTRACT_JSON, LOG = Value + val Assert, ExtractJson, Log = Value type ResponseActionGroupType = Value private val stringToValueMap = Map( - "assert" -> ASSERT, - "extractJson" -> EXTRACT_JSON, - "log" -> LOG + "assert" -> Assert, + "extractJson" -> ExtractJson, + "log" -> Log ) def fromString(s: String): Option[ResponseActionGroupType] = stringToValueMap.get(s) diff --git a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala index 99be2c4..05bc8be 100644 --- a/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala +++ b/testApi/src/main/scala/africa/absa/testing/scapi/suite/runner/SuiteRunner.scala @@ -58,7 +58,7 @@ object SuiteRunner { // add failed Test suite result instance and it will not be started suiteResult = suiteResult :+ SuiteResult( - resultType = SuiteResultType.TEST_SET, + resultType = SuiteResultType.TestSet, suiteName = suiteBundle.suite.name, name = "SKIPPED", result = Failure(SuiteBeforeFailedException(errorMsg)), @@ -96,14 +96,14 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Before: method '${method.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.BEFORE_TEST_SET, + resultType = SuiteResultType.BeforeTestSet, suiteName = suiteName, name = method.name, result = result, duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteName, suiteBeforeName, testStartTime, SuiteResultType.BEFORE_TEST_SET) + case e: Exception => handleException(e, suiteName, suiteBeforeName, testStartTime, SuiteResultType.BeforeTestSet) } } @@ -124,7 +124,7 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"Suite-Test: '${test.name}' - ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.TEST_SET, + resultType = SuiteResultType.TestSet, suiteName = suiteName, name = test.name, result = result, @@ -133,7 +133,7 @@ object SuiteRunner { ) } catch { - case e: Exception => handleException(e, suiteName, test.name, testStartTime, SuiteResultType.TEST_SET, Some(test.categories.mkString(","))) + case e: Exception => handleException(e, suiteName, test.name, testStartTime, SuiteResultType.TestSet, Some(test.categories.mkString(","))) } finally { RuntimeCache.expire(TestLevel) } @@ -157,14 +157,14 @@ object SuiteRunner { val testEndTime: Long = System.currentTimeMillis() Logger.debug(s"After method '${method.name}' ${if (result.isSuccess) "completed successfully" else "failed"}.") SuiteResult( - resultType = SuiteResultType.AFTER_TEST_SET, + resultType = SuiteResultType.AfterTestSet, suiteName = suiteName, name = method.name, result = result, duration = Some(testEndTime - testStartTime) ) } catch { - case e: Exception => handleException(e, suiteName, suiteAfterName, testStartTime, SuiteResultType.AFTER_TEST_SET) + case e: Exception => handleException(e, suiteName, suiteAfterName, testStartTime, SuiteResultType.AfterTestSet) } } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala index e3d68a4..606a15c 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/reporter/StdOutReporterTest.scala @@ -27,20 +27,20 @@ import scala.util.{Failure, Success} class StdOutReporterTest extends FunSuite { val successTestResults: List[SuiteResult] = List( - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 1", name = "Test 1", result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 1", name = "Test 2", result = Success(()), duration = Some(200L), categories = Some("Category 2") ), - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 2", name = "Test 1", result = Success(()), @@ -49,19 +49,19 @@ class StdOutReporterTest extends FunSuite { ) val mixedSuccessTestResults: List[SuiteResult] = List( - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 1", name = "Test 1", result = Success(()), duration = Some(100L), categories = Some("Category 1")), - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 1", name = "Test 2", result = Failure(AssertionException("Error message")), duration = Some(200L), categories = Some("Category 2")), - SuiteResult(SuiteResultType.TEST_SET, + SuiteResult(SuiteResultType.TestSet, suiteName = "Suite 2", name = "Test 1", result = Success(()), diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala index 948e0a5..cf9217e 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseAssertionsTest.scala @@ -37,31 +37,31 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("validateContent - response time is below - limit is integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsBelow, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is below - limit is not integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "not_integer")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsBelow, Map("limit" -> "not_integer")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-below.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - limit is integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsAbove, Map("limit" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - response time is above - limit is not integer string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "not_integer")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsAbove, Map("limit" -> "not_integer")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not_integer': Received value of 'ResponseAssertion.response-time-is-above.limit' cannot be parsed to a long: For input string: \"not_integer\"") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - response time is above - missing limit parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsAbove, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'limit' parameter for assertion response-time-is-above logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -70,18 +70,18 @@ class ResponseAssertionsTest extends FunSuite { // status-code-... test("validateContent - valid status code string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals, Map("code" -> "200")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - invalid status code string") { interceptMessage[ContentValidationFailedException]("Content validation failed for value: 'not an integer': Received value of 'ResponseAssertion.status-code-equals.code' cannot be parsed to an integer: For input string: \"not an integer\"") { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "not an integer"))) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals, Map("code" -> "not an integer"))) } } test("validateContent - status code equals - missing code parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'code' parameter for assertion status-code-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -90,52 +90,52 @@ class ResponseAssertionsTest extends FunSuite { // header-... test("validateContent - header exists - valid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "content-type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderExists, Map("headerName" -> "content-type")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header exists - invalid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderExists, Map("headerName" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-exists.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header exists - missing header name parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderExists, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - valid header name and value strings") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - header value equals - invalid header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "", "expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "", "expectedValue" -> "application/json")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.headerName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - invalid expected value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "Content-Type", "expectedValue" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.header-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("expectedValue" -> "application/json")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("expectedValue" -> "application/json")) interceptMessage[IllegalArgumentException]("Missing required 'headerName' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - header value equals - missing header value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "Content-Type")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion header-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -144,52 +144,52 @@ class ResponseAssertionsTest extends FunSuite { // cookies-... test("validateContent - cookie exists - valid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieExists, Map("cookieName" -> "testCookie")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie exists - invalid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieExists, Map("cookieName" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-exists.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie exists - missing cookie name parameter") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map()) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieExists, Map()) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-exists logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - valid cookie name and value strings") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - cookie value equals - invalid cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "", "expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "", "expectedValue" -> "cookieValue")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.cookieName' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - invalid cookie value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie", "expectedValue" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.cookie-value-equals.expectedValue' is empty.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie name string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("expectedValue" -> "cookieValue")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("expectedValue" -> "cookieValue")) interceptMessage[IllegalArgumentException]("Missing required 'cookieName' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } } test("validateContent - cookie value equals - missing cookie value string") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie")) interceptMessage[IllegalArgumentException]("Missing required 'expectedValue' parameter for assertion cookie-value-equals logic.") { AssertionResponseAction.validateContent(responseAction) } @@ -198,25 +198,25 @@ class ResponseAssertionsTest extends FunSuite { // body-... test("validateContent - body contains text - body is not empty") { - val responseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "test content")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.BodyContainsText, Map("text" -> "test content")) AssertionResponseAction.validateContent(responseAction) } test("validateContent - body contains text - body is empty") { interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ResponseAssertion.body-contains-text.text' is empty.") { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> ""))) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.BodyContainsText, Map("text" -> ""))) } } test("validateContent - body contains text - body parameter is missing") { interceptMessage[IllegalArgumentException]("Missing required 'text' parameter for assertion body-contains-text logic.") { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map.empty)) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.BodyContainsText, Map.empty)) } } test("validateContent - unsupported response action") { interceptMessage[UndefinedResponseActionTypeException]("Undefined response action content type: 'unsupported'") { - AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.ASSERT, name = "unsupported", Map("body" -> "value"))) + AssertionResponseAction.validateContent(ResponseAction(group = ResponseActionGroupType.Assert, name = "unsupported", Map("body" -> "value"))) } } @@ -227,28 +227,28 @@ class ResponseAssertionsTest extends FunSuite { // response-time-... test("performAssertions - response time is below limit - success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsBelow, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is below limit - failed") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_BELOW, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsBelow, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - response time is above limit - success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsAbove, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 101) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - response time is above limit - failed") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.RESPONSE_TIME_IS_ABOVE, Map("limit" -> "100")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ResponseTimeIsAbove, Map("limit" -> "100")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 99) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) @@ -257,21 +257,21 @@ class ResponseAssertionsTest extends FunSuite { // status-code-... test("performAssertions - status code assertion - equals") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals, Map("code" -> "200")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isSuccess) } test("performAssertions - status code assertion - not equals") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS, Map("code" -> "200")) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals, Map("code" -> "200")) val response = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, statusCodeResponseAction).isFailure) } test("performAssertions - status code - is success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SUCCESS, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsSuccess, Map.empty) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response299 = Response(299, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -280,7 +280,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not success") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SUCCESS, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsSuccess, Map.empty) val response199 = Response(199, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response300 = Response(300, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -291,7 +291,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is client error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsClientError, Map.empty) val response400 = Response(400, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -300,7 +300,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not client error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_CLIENT_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsClientError, Map.empty) val response399 = Response(399, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -311,7 +311,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is server error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SERVER_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsServerError, Map.empty) val response500 = Response(500, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response599 = Response(599, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -320,7 +320,7 @@ class ResponseAssertionsTest extends FunSuite { } test("performAssertions - status code - is not server error") { - val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_IS_SERVER_ERROR, Map.empty) + val statusCodeResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeIsServerError, Map.empty) val response499 = Response(499, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response600 = Response(600, "Dummy Body", "", "", Map.empty, Map.empty, 100) val response200 = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) @@ -333,28 +333,28 @@ class ResponseAssertionsTest extends FunSuite { // header-... test("performAssertions - header exists") { - val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "Content-Type")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderExists, Map("headerName" -> "Content-Type")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isSuccess) } test("performAssertions - header does not exists") { - val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_EXISTS, Map("headerName" -> "headerValue")) + val headerExistsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderExists, Map("headerName" -> "headerValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerExistsResponseAction).isFailure) } test("performAssertions - header value is equals") { - val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "Content-Type", "expectedValue" -> "application/json")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isSuccess) } test("performAssertions - header value is not equals") { - val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.HEADER_VALUE_EQUALS, Map("headerName" -> "someName", "expectedValue" -> "someValue")) + val headerValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.HeaderValueEquals, Map("headerName" -> "someName", "expectedValue" -> "someValue")) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, headerValueEqualsResponseAction).isFailure) @@ -363,42 +363,42 @@ class ResponseAssertionsTest extends FunSuite { // content-type-... test("performAssertions - content type is json") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_JSON, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsJson, Map.empty) val response = Response(200, "{}", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not json") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_JSON, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsJson, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is xml") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_XML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsXml, Map.empty) val response = Response(200, """QADevDon't forget to test it!""", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not xml") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_XML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsXml, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/json")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) } test("performAssertions - content type is html") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_HTML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsHtml, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("text/html")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isSuccess) } test("performAssertions - content type is not html") { - val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.CONTENT_TYPE_IS_HTML, Map.empty) + val contentTypeIsJsonResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.ContentTypeIsHtml, Map.empty) val response = Response(200, "Dummy Body", "", "", Map("content-type" -> Seq("application/xml")), Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, contentTypeIsJsonResponseAction).isFailure) @@ -407,63 +407,63 @@ class ResponseAssertionsTest extends FunSuite { // cookies-... test("performAssertions - cookie exists") { - val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "testCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieExists, Map("cookieName" -> "testCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isSuccess) } test("performAssertions - cookie does not exists") { - val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_EXISTS, Map("cookieName" -> "anotherCookie")) + val cookieExistsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieExists, Map("cookieName" -> "anotherCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieExistsResponseAction).isFailure) } test("performAssertions - cookie value is equals") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "cookieValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isSuccess) } test("performAssertions - cookie value is not equals") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("testCookie" -> CookieValue(value = "anotherValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie value equals - cookie does not exist") { - val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_VALUE_EQUALS, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieValueEqualsResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieValueEquals, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieValueEqualsResponseAction).isFailure) } test("performAssertions - cookie is secured") { - val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_SECURED, Map("cookieName" -> "securedCookie")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieIsSecured, Map("cookieName" -> "securedCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("securedCookie" -> CookieValue(value = "someValue", secured = true)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isSuccess) } test("performAssertions - cookie is secured - cookie does not exist") { - val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieIsSecured, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsSecuredResponseAction).isFailure) } test("performAssertions - cookie is not secured") { - val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "notSecuredCookie")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieIsNotSecured, Map("cookieName" -> "notSecuredCookie")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map("notSecuredCookie" -> CookieValue(value = "someValue", secured = false)), 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isSuccess) } test("performAssertions - cookie is not secured - cookie does not exist") { - val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.COOKIE_IS_NOT_SECURED, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) + val cookieIsNotSecuredResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.CookieIsNotSecured, Map("cookieName" -> "testCookie", "expectedValue" -> "cookieValue")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, cookieIsNotSecuredResponseAction).isFailure) @@ -472,13 +472,13 @@ class ResponseAssertionsTest extends FunSuite { // body-... test("performAssertions - body contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "dummy")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.BodyContainsText, Map("text" -> "dummy")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isSuccess) } test("performAssertions - body does not contains assertion") { - val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.BODY_CONTAINS_TEXT, Map("text" -> "dummies")) + val bodyContainsTextResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.BodyContainsText, Map("text" -> "dummies")) val response = Response(200, "This is a dummy body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, bodyContainsTextResponseAction).isFailure) @@ -487,7 +487,7 @@ class ResponseAssertionsTest extends FunSuite { // unsupported test("performAssertions - unsupported assertion") { - val unsupportedResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = "unsupported-assertion", Map("nonsense" -> "value")) + val unsupportedResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = "unsupported-assertion", Map("nonsense" -> "value")) val response = Response(200, "Dummy Body", "", "", Map.empty, Map.empty, 100) assert(AssertionResponseAction.performResponseAction(response, unsupportedResponseAction).isFailure) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala index df18095..a834885 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseExtractTest.scala @@ -31,8 +31,8 @@ class ResponseExtractTest extends FunSuite { implicit def extractJsonResponseActionType2String(value: ExtractJsonResponseActionType): String = value.toString - val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) - val assertionUnsupported: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = "Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) + val assertionStringFromList: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "question_id", "listIndex" -> "1", "jsonKey" -> "id", "cacheLevel" -> "suite")) + val assertionUnsupported: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = "Unsupported", Map("cacheKey" -> "key", "listIndex" -> "200", "jsonKey" -> "jsonKey", "cacheLevel" -> "Test")) val responseWithID: Response = Response( 200, @@ -78,10 +78,10 @@ class ResponseExtractTest extends FunSuite { } test("validateContent - validateStringFromList - None parameters") { - val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) - val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "")) - val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "")) - val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map.empty) + val assertion1None: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "")) + val assertion2None: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "", "listIndex" -> "")) + val assertion3None: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "")) + val assertion4None: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'cacheKey' parameter for extract string-from-list logic") { ExtractJsonResponseAction.validateContent(assertion4None) @@ -98,10 +98,10 @@ class ResponseExtractTest extends FunSuite { } test("validateContent - validateStringFromList - empty parameters") { - val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) - val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.EXTRACT_JSON, name = ExtractJsonResponseActionType.STRING_FROM_LIST, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) + val assertionParam1: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam2: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "1", "listIndex" -> "", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam3: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "", "cacheLevel" -> "")) + val assertionParam4: ResponseAction = ResponseAction(group = ResponseActionGroupType.ExtractJson, name = ExtractJsonResponseActionType.StringFromList, Map("cacheKey" -> "1", "listIndex" -> "x", "jsonKey" -> "y", "cacheLevel" -> "")) interceptMessage[ContentValidationFailedException]("Content validation failed for value: '': Received string value of 'ExtractJson.string-from-list.cacheKey' is empty.") { ExtractJsonResponseAction.validateContent(assertionParam1) diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala index d4d754f..25cf4c5 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/rest/response/ResponseLogTest.scala @@ -33,31 +33,31 @@ class ResponseLogTest extends FunSuite { validateContent */ test("validateContent - ERROR supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.ERROR, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Error, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - WARN supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.WARN, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Warn, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - INFO supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Info, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - DEBUG supported") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.DEBUG, Map("message" -> "Non-empty string")) + val responseAction = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Debug, Map("message" -> "Non-empty string")) // no exception thrown, meaning validation passed LogResponseAction.validateContent(responseAction) } test("validateContent - no message provided") { - val responseAction = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map.empty) + val responseAction = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Info, Map.empty) interceptMessage[IllegalArgumentException]("Missing required 'message' for assertion info logic.") { LogResponseAction.validateContent(responseAction) } @@ -68,25 +68,25 @@ class ResponseLogTest extends FunSuite { */ test("performAssertion - ERROR supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.ERROR, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Error, Map("message" -> "info message")) val response = Response(500, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - WARN supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.WARN, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Warn, Map("message" -> "info message")) val response = Response(401, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - INFO supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.INFO, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Info, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } test("performAssertion - DEBUG supported") { - val assertion = ResponseAction(group = ResponseActionGroupType.LOG, name = LogType.DEBUG, Map("message" -> "info message")) + val assertion = ResponseAction(group = ResponseActionGroupType.Log, name = LogType.Debug, Map("message" -> "info message")) val response = Response(200, "OK", "", "", Map("Content-Type" -> Seq("application/json")), Map.empty, 100) assert(LogResponseAction.performResponseAction(response, assertion).isSuccess) } diff --git a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala index e1b9e19..ddc62ad 100644 --- a/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala +++ b/testApi/src/test/scala/africa/absa/testing/scapi/suite/runner/SuiteRunnerTest.scala @@ -32,7 +32,7 @@ class SuiteRunnerTest extends FunSuite { val header: Header = Header(name = RequestHeaders.AUTHORIZATION, value = "Basic abcdefg") val action: Action = Action(methodName = "get", url = "nice url") val actionNotSupported: Action = Action(methodName = "wrong", url = "nice url") - val responseAction: ResponseAction = ResponseAction(group = ResponseActionGroupType.ASSERT, name = AssertResponseActionType.STATUS_CODE_EQUALS.toString, Map("code" -> "200")) + val responseAction: ResponseAction = ResponseAction(group = ResponseActionGroupType.Assert, name = AssertResponseActionType.StatusCodeEquals.toString, Map("code" -> "200")) val method: Method = Method(name = "test", headers = Seq(header), actions = Seq(action), responseActions = Seq(responseAction)) val methodNotSupported: Method = Method(name = "test", headers = Seq(header), actions = Seq(actionNotSupported), responseActions = Seq(responseAction)) @@ -105,7 +105,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2").get + result.resultType == SuiteResultType.BeforeTestSet && result.suiteName == "name2").get assert(5 == clue(suiteResults.size)) assert("test" == clue(beforeSuiteResult.name)) @@ -116,7 +116,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoBefore, environment, () => new RestClient(FakeScAPIRequestSender)) val beforeSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.BEFORE_TEST_SET && result.suiteName == "name2") + result.resultType == SuiteResultType.BeforeTestSet && result.suiteName == "name2") assert(2 == clue(suiteResults.size)) assert(beforeSuiteResult.isEmpty) @@ -126,7 +126,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundles, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get + result.resultType == SuiteResultType.AfterTestSet && result.suiteName == "name2").get assert(5 == clue(suiteResults.size)) assert("test" == clue(afterSuiteResult.name)) @@ -137,7 +137,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleNoAfter, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: Option[SuiteResult] = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2") + result.resultType == SuiteResultType.AfterTestSet && result.suiteName == "name2") assert(2 == clue(suiteResults.size)) assert(afterSuiteResult.isEmpty) @@ -147,7 +147,7 @@ class SuiteRunnerTest extends FunSuite { val suiteResults: List[SuiteResult] = SuiteRunner.runSuites(suitesBundleAfterMethodNotSupported, environment, () => new RestClient(FakeScAPIRequestSender)) val afterSuiteResult: SuiteResult = suiteResults.find(result => - result.resultType == SuiteResultType.AFTER_TEST_SET && result.suiteName == "name2").get + result.resultType == SuiteResultType.AfterTestSet && result.suiteName == "name2").get assert(2 == clue(suiteResults.size)) assert(clue(!afterSuiteResult.isSuccess))