From 6fa7c0bb305b65895063e0f213ed022a111578c4 Mon Sep 17 00:00:00 2001 From: Nick Wilson <7313396+TheNickWilson@users.noreply.github.com> Date: Tue, 14 May 2024 14:51:20 +0100 Subject: [PATCH] Valdiate for unexpected pages --- app/models/TraderProfile.scala | 14 +++++++++----- test/models/TraderProfileSpec.scala | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/models/TraderProfile.scala b/app/models/TraderProfile.scala index c9e579db6..beac98681 100644 --- a/app/models/TraderProfile.scala +++ b/app/models/TraderProfile.scala @@ -16,7 +16,7 @@ package models -import cats.data.{Ior, IorNec} +import cats.data.{Ior, IorNec, NonEmptyChain} import cats.implicits._ import pages.{HasNiphlPage, HasNirmsPage, NiphlNumberPage, NirmsNumberPage, UkimsNumberPage} import play.api.libs.json.{Json, OFormat} @@ -40,13 +40,17 @@ object TraderProfile { private def getNirms(answers: UserAnswers): IorNec[ValidationError, Option[String]] = answers.getIor(HasNirmsPage).flatMap { - case true => answers.getIor(NirmsNumberPage).map(Some(_)) - case false => Ior.Right(None) + case true => + answers.getIor(NirmsNumberPage).map(Some(_)) + case false => + if (answers.isDefined(NirmsNumberPage)) Ior.Left(NonEmptyChain.one(UnexpectedPage(NirmsNumberPage))) else Ior.Right(None) } private def getNiphl(answers: UserAnswers): IorNec[ValidationError, Option[String]] = answers.getIor(HasNiphlPage).flatMap { - case true => answers.getIor(NiphlNumberPage).map(Some(_)) - case false => Ior.Right(None) + case true => + answers.getIor(NiphlNumberPage).map(Some(_)) + case false => + if (answers.isDefined(NiphlNumberPage)) Ior.Left(NonEmptyChain.one(UnexpectedPage(NiphlNumberPage))) else Ior.Right(None) } } diff --git a/test/models/TraderProfileSpec.scala b/test/models/TraderProfileSpec.scala index 4cf1cf1a8..0dca8aa3d 100644 --- a/test/models/TraderProfileSpec.scala +++ b/test/models/TraderProfileSpec.scala @@ -101,6 +101,25 @@ class TraderProfileSpec extends AnyFreeSpec with Matchers with TryValues with Op data must not be defined errors.value.toChain.toList must contain only PageMissing(NiphlNumberPage) } + + "when the user said they don't have optional data but it is present" in { + + val answers = + UserAnswers("id") + .set(UkimsNumberPage, "1").success.value + .set(HasNirmsPage, false).success.value + .set(NirmsNumberPage, "2").success.value + .set(HasNiphlPage, false).success.value + .set(NiphlNumberPage, "3").success.value + + val (errors, data) = TraderProfile.build(answers).pad + + data must not be defined + errors.value.toChain.toList must contain theSameElementsAs Seq( + UnexpectedPage(NirmsNumberPage), + UnexpectedPage(NiphlNumberPage) + ) + } } } }