aboutsummaryrefslogtreecommitdiff
path: root/src/test/scala/xyz
diff options
context:
space:
mode:
Diffstat (limited to 'src/test/scala/xyz')
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala35
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/Mocks.scala88
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapterSuite.scala285
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/db/QueryBuilderParametersSuite.scala310
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/error/UnexpectedFilterException.scala3
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/logging/PhiStringContextSuite.scala31
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/parsers/SearchFilterParserSuite.scala185
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/pdf/MockPdfRenderer.scala25
-rw-r--r--src/test/scala/xyz/driver/pdsuicommon/utils/DiffUtils.scala68
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/DocumentSuite.scala87
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala36
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/BridgeUploadQueueFormat.scala32
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala68
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala74
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala32
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala47
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExportFormatSuite.scala124
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala95
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala28
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala63
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordFormatSuite.scala77
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala32
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordIssueFormatSuite.scala47
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala55
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientEligibleTrialFormatSuite.scala62
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala36
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHistoryFormatSuite.scala32
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala31
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala44
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala76
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala24
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala50
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala32
-rw-r--r--src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialIssueFormatSuite.scala49
-rw-r--r--src/test/scala/xyz/driver/restquery/db/SearchFilterExprSuite.scala (renamed from src/test/scala/xyz/driver/pdsuicommon/db/SearchFilterExprSuite.scala)3
-rw-r--r--src/test/scala/xyz/driver/restquery/rest/parsers/PaginationParserSuite.scala (renamed from src/test/scala/xyz/driver/pdsuicommon/parsers/PaginationParserSuite.scala)74
-rw-r--r--src/test/scala/xyz/driver/restquery/rest/parsers/SearchFilterParserSuite.scala261
-rw-r--r--src/test/scala/xyz/driver/restquery/rest/parsers/SortingParserSuite.scala (renamed from src/test/scala/xyz/driver/pdsuicommon/parsers/SortingParserSuite.scala)41
-rw-r--r--src/test/scala/xyz/driver/restquery/rest/parsers/TestUtils.scala (renamed from src/test/scala/xyz/driver/pdsuicommon/parsers/TestUtils.scala)15
-rw-r--r--src/test/scala/xyz/driver/restquery/utils/StringOpsSuite.scala (renamed from src/test/scala/xyz/driver/pdsuicommon/utils/StringOpsSuite.scala)17
40 files changed, 343 insertions, 2431 deletions
diff --git a/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala
deleted file mode 100644
index 7c9d8c4..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala
+++ /dev/null
@@ -1,35 +0,0 @@
-package xyz.driver.pdsuicommon
-
-import java.time.{LocalDateTime, ZoneId}
-
-import org.scalatest.FreeSpecLike
-import org.scalatest.concurrent.ScalaFutures
-import org.scalatest.time.{Millis, Span}
-import xyz.driver.pdsuicommon.db._
-import xyz.driver.pdsuicommon.domain._
-import xyz.driver.pdsuicommon.error.UnexpectedFilterException
-import xyz.driver.pdsuicommon.utils.DiffUtils
-
-trait BaseSuite extends FreeSpecLike with DiffUtils with ScalaFutures {
-
- implicit val defaultPatience = PatienceConfig(timeout = Span(1000, Millis), interval = Span(20, Millis))
- implicit val sqlContext = new MockMySqlContext()
-
- def sampleUser(role: User.Role, email: String = "test@example.com", password: String = "123") = User(
- id = StringId("2001"),
- email = Email(email),
- name = "Test",
- roles = Set(role),
- latestActivity = Some(LocalDateTime.now(ZoneId.of("Z"))),
- deleted = None
- )
-
- def createMockQueryBuilder[T](isExpectedFilter: SearchFilterExpr => Boolean): MysqlQueryBuilder[T] = {
- MockQueryBuilder[T] {
- case (filter, _, _) if isExpectedFilter(filter) => Seq.empty
- case (filter, _, _) => throw new UnexpectedFilterException(s"Filter is unexpected: $filter")
- } {
- case _ => (0, Option.empty[LocalDateTime])
- }
- }
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/Mocks.scala b/src/test/scala/xyz/driver/pdsuicommon/Mocks.scala
deleted file mode 100644
index 51d39e5..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/Mocks.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-package xyz.driver.pdsuicommon
-
-import java.io.{Closeable, PrintWriter}
-import java.net.URL
-import java.sql.Connection
-import java.util.logging.Logger
-import javax.sql.DataSource
-
-import com.typesafe.config.ConfigFactory
-import xyz.driver.pdsuicommon.db._
-import xyz.driver.pdsuicommon.http.HttpFetcher
-
-import scala.concurrent.Future
-
-class MockDataSource extends DataSource with Closeable {
- override def getConnection: Connection = throw new NotImplementedError("MockDataSource.getConnection")
- override def getConnection(username: String, password: String): Connection = {
- throw new NotImplementedError(s"MockDataSource.getConnection($username, $password)")
- }
- override def close(): Unit = throw new NotImplementedError("MockDataSource.close")
- override def setLogWriter(out: PrintWriter): Unit = throw new NotImplementedError("MockDataSource.setLogWriter")
- override def getLoginTimeout: Int = throw new NotImplementedError("MockDataSource.getLoginTimeout")
- override def setLoginTimeout(seconds: Int): Unit = throw new NotImplementedError("MockDataSource.setLoginTimeout")
- override def getParentLogger: Logger = throw new NotImplementedError("MockDataSource.getParentLogger")
- override def getLogWriter: PrintWriter = throw new NotImplementedError("MockDataSource.getLogWriter")
- override def unwrap[T](iface: Class[T]): T = throw new NotImplementedError("MockDataSource.unwrap")
- override def isWrapperFor(iface: Class[_]): Boolean = throw new NotImplementedError("MockDataSource.isWrapperFor")
-}
-
-object MockMySqlContext {
-
- val Settings = MySqlContext.Settings(
- credentials = MySqlContext.DbCredentials(
- user = "test",
- password = "test",
- host = "localhost",
- port = 3248,
- dbName = "test",
- dbCreateFlag = false,
- dbContext = "test",
- connectionParams = "",
- url = ""
- ),
- connection = ConfigFactory.empty(),
- threadPoolSize = 10
- )
-}
-
-class MockMySqlContext() extends MySqlContext(new MockDataSource, MockMySqlContext.Settings) {
- override protected def withConnection[T](f: Connection => T): Nothing = {
- throw new NotImplementedError("MockSqlContext.withConnection")
- }
-}
-
-class MockFactory()(implicit val sqlContext: MySqlContext) {
- val MockHttpFetcher: HttpFetcher = { (url: URL) =>
- Future.successful(Array.empty[Byte])
- }
-}
-
-object MockQueryBuilder {
-
- type MockRunnerIn = (SearchFilterExpr, Sorting, Option[Pagination])
- type MockRunnerOut[T] = Seq[T]
- type MockCountRunnerOut = QueryBuilder.CountResult
-
- def apply[T](matcher: PartialFunction[MockRunnerIn, MockRunnerOut[T]])(
- countMatcher: PartialFunction[MockRunnerIn, MockCountRunnerOut])(
- implicit context: MySqlContext): MysqlQueryBuilder[T] = {
-
- val runner: QueryBuilder.Runner[T] = { parameters =>
- matcher((parameters.filter, parameters.sorting, parameters.pagination))
- }
-
- val countRunner: QueryBuilder.CountRunner = { parameters =>
- countMatcher((parameters.filter, parameters.sorting, parameters.pagination))
- }
-
- MysqlQueryBuilder[T](
- tableName = "",
- lastUpdateFieldName = Option.empty[String],
- nullableFields = Set.empty[String],
- links = Set.empty[TableLink],
- runner = runner,
- countRunner = countRunner
- )
- }
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapterSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapterSuite.scala
deleted file mode 100644
index 8b38316..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapterSuite.scala
+++ /dev/null
@@ -1,285 +0,0 @@
-package xyz.driver.pdsuicommon.concurrent
-
-import java.util.concurrent.ThreadLocalRandom
-
-import xyz.driver.pdsuicommon.BaseSuite
-import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueueRepositoryAdapter.Strategy
-import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueueRepositoryAdapter.Strategy.{OnAttempt, OnComplete}
-import xyz.driver.pdsuicommon.db.{FakeDbIo, MysqlQueryBuilder}
-import xyz.driver.pdsuicommon.db.repositories.BridgeUploadQueueRepository
-
-import scala.concurrent.Future
-import scala.concurrent.duration.DurationInt
-
-class BridgeUploadQueueRepositoryAdapterSuite extends BaseSuite {
-
- // IDEA have some issue here with imports
- private implicit val executionContext = scala.concurrent.ExecutionContext.global
-
- "Strategy" - {
- "LimitExponential" - {
- "on" - {
- val strategy = Strategy.LimitExponential(
- startInterval = 10.seconds,
- intervalFactor = 1.4,
- maxInterval = 50.seconds,
- onComplete = OnComplete.Delete
- )
-
- "a new interval should be greater than the previous one if the limit not reached" in {
- val previous = strategy.on(1)
- val current = strategy.on(2)
-
- (previous, current) match {
- case (OnAttempt.Continue(a), OnAttempt.Continue(b)) => assert(a < b)
- case x => fail(s"Unexpected result: $x")
- }
- }
-
- "should limit intervals" in {
- assert(strategy.on(20) == OnAttempt.Continue(strategy.maxInterval))
- }
-
- "should not fail, if there is many attempts" in {
- assert(strategy.on(1000) == OnAttempt.Continue(strategy.maxInterval))
- }
- }
- }
- }
-
- "complete" - {
- "onComplete == mark" - {
- "should update the item" in {
- var done = false
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
-
- override def delete(kind: String, tag: String): Unit = throw new IllegalStateException("Impossible call")
-
- override def update(entity: EntityT): EntityT = {
- assert(entity.kind == item.kind, "repository.delete, kind")
- assert(entity.tag == item.tag, "repository.delete, tag")
- done = true
- entity
- }
-
- override def getById(kind: String, tag: String): Option[EntityT] = Some(item)
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = Strategy.Stop(OnComplete.Mark),
- repository = repository,
- dbIo = FakeDbIo
- )
-
- assert(adapter.complete(item.kind, item.tag).isReadyWithin(100.millis))
- assert(done)
- }
- }
-
- "onComplete == delete" - {
- "should delete the item" in {
- var done = false
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
-
- override def delete(kind: String, tag: String): Unit = {
- assert(kind == item.kind, "repository.delete, kind")
- assert(tag == item.tag, "repository.delete, tag")
- done = true
- }
- override def update(entity: EntityT): EntityT = throw new IllegalStateException("Impossible call")
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = Strategy.Stop(OnComplete.Delete),
- repository = repository,
- dbIo = FakeDbIo
- )
-
- assert(adapter.complete(item.kind, item.tag).isReadyWithin(100.millis))
- assert(done)
- }
- }
- }
-
- "tryRetry" - {
-
- "when all attempts are not out" - {
-
- val defaultStrategy = Strategy.Constant(10.seconds)
-
- "should return an updated item" in {
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
-
- override def update(draft: EntityT): EntityT = draft
- override def delete(kind: String, tag: String): Unit = throw new IllegalAccessError(s"kind=$kind, tag=$tag")
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- )
-
- val item = defaultItem
- val r = adapter.tryRetry(item).futureValue
- assert(r.isDefined)
- assert(!r.contains(item))
- }
-
- "should update an item with increased attempts" in {
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
-
- override def update(draft: EntityT): EntityT = {
- assert(draft.attempts === (item.attempts + 1), "repository.add")
- draft
- }
- override def delete(kind: String, tag: String): Unit = throw new IllegalAccessError(s"kind=$kind, tag=$tag")
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- )
-
- assert(adapter.tryRetry(item).isReadyWithin(100.millis))
- }
-
- "should remove an old item" in {
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
- override def update(draft: EntityT): EntityT = draft
- override def delete(kind: String, tag: String): Unit = {
- assert(kind == item.kind, "repository.delete, kind")
- assert(tag == item.tag, "repository.delete, kind")
- }
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- )
-
- assert(adapter.tryRetry(item).isReadyWithin(100.millis))
- }
-
- "should update time of the next attempt" in {
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
-
- override def update(draft: EntityT): EntityT = {
- assert(draft.nextAttempt.isAfter(item.nextAttempt), "repository.add")
- draft
- }
- override def delete(kind: String, tag: String): Unit = throw new IllegalAccessError(s"kind=$kind, tag=$tag")
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- )
-
- assert(adapter.tryRetry(item).isReadyWithin(100.millis))
- }
-
- }
-
- "when all attempts are out" - {
-
- val defaultStrategy = Strategy.Stop()
-
- "should not return an item" in {
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
- override def update(entity: EntityT): EntityT = fail("update should not be used!")
-
- override def delete(kind: String, tag: String): Unit = {}
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- )
-
- val r = adapter.tryRetry(defaultItem).futureValue
- assert(r.isEmpty)
- }
-
- "should complete the item" in {
- var taskWasCompleted = false
- val item = defaultItem
-
- val repository = new BridgeUploadQueueRepository {
- override def add(draft: EntityT): EntityT = draft
- override def getOne(kind: String): Option[EntityT] = fail("getOne should not be used!")
- override def buildQuery: MysqlQueryBuilder[EntityT] = fail("buildQuery should not be used!")
- override def getById(kind: String, tag: String): Option[EntityT] = fail("getById should not be used!")
- override def update(entity: EntityT): EntityT = fail("update should not be used!")
-
- override def delete(kind: String, tag: String): Unit = {}
- }
-
- val adapter = new BridgeUploadQueueRepositoryAdapter(
- strategy = defaultStrategy,
- repository = repository,
- dbIo = FakeDbIo
- ) {
- override def complete(kind: String, tag: String): Future[Unit] = Future {
- assert(kind == item.kind, "adapter.complete, kind")
- assert(tag == item.tag, "adapter.complete, tag")
- taskWasCompleted = true
- }
- }
-
- val r = adapter.tryRetry(item).futureValue
- assert(r.isEmpty)
- assert(taskWasCompleted)
- }
-
- }
-
- }
-
- private def defaultItem = BridgeUploadQueue.Item(
- "test",
- ThreadLocalRandom.current().nextInt().toString
- )
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/db/QueryBuilderParametersSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/db/QueryBuilderParametersSuite.scala
deleted file mode 100644
index 2c23b92..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/db/QueryBuilderParametersSuite.scala
+++ /dev/null
@@ -1,310 +0,0 @@
-package xyz.driver.pdsuicommon.db
-
-import java.time.LocalDateTime
-
-import io.getquill.MysqlEscape
-import org.scalatest.FreeSpecLike
-import xyz.driver.pdsuicommon.db.QueryBuilder.TableData
-import xyz.driver.pdsuicommon.domain._
-
-class QueryBuilderParametersSuite extends FreeSpecLike {
-
- import SearchFilterBinaryOperation._
- import SearchFilterExpr.{Dimension => _, _}
- import SearchFilterNAryOperation._
- import Sorting._
- import SortingOrder._
-
- val tableName = "Entity"
-
- case class Entity(id: LongId[Entity],
- name: String,
- email: Email,
- optionUser: Option[StringId[User]],
- date: LocalDateTime,
- optionDate: Option[LocalDateTime],
- kindId: Long)
-
- def queryBuilderParameters = MysqlQueryBuilderParameters(
- tableData = TableData(
- tableName = tableName,
- nullableFields = Set("optionUser", "optionDate")
- ),
- links = Map(
- "Kind" -> TableLink("kindId", "Kind", "id"),
- "User" -> TableLink("optionUser", "User", "id")
- )
- )
-
- val queryBasis =
- s"""select `$tableName`.*
- |from `$tableName`""".stripMargin.trim
-
- "toSql" - {
- "should generate correct SQL query" - {
- "with default parameters" in {
- val (sql, _) = queryBuilderParameters.toSql(namingStrategy = MysqlEscape)
- assert(sql == queryBasis)
- }
-
- "with filtering: " - {
- "single atom filter" in {
- val (sql, _) =
- queryBuilderParameters.copy(filter = Atom.Binary("name", Eq, "x")).toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where `$tableName`.`name` = ?""".stripMargin)
- }
-
- "single atom filter for optional field with NotEq operation" in {
- val (sql, _) = queryBuilderParameters
- .copy(filter = Atom.Binary("optionUser", NotEq, "x"))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where (`$tableName`.`optionUser` is null or `$tableName`.`optionUser` != ?)""".stripMargin)
- }
-
- "single atom filter for field with IN operation" in {
- val (sql, _) = queryBuilderParameters
- .copy(filter = Atom.NAry("date", In, Seq("x", "x", "x")))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where `$tableName`.`date` in (?, ?, ?)""".stripMargin)
- }
-
- "multiple intersected filters" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- filter = Intersection(
- Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x")
- )))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where (`$tableName`.`name` > ? and `$tableName`.`optionDate` >= ?)""".stripMargin)
- }
-
- "multiple intersected nested filters" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- filter = Intersection(
- Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x"),
- Intersection(Seq(
- Atom.Binary("optionUser", Eq, "x"),
- Atom.Binary("date", LtEq, "x")
- ))
- )))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"$queryBasis\nwhere (`$tableName`.`name` > ? and `$tableName`.`optionDate` >= ?" +
- s" and (`$tableName`.`optionUser` = ? and `$tableName`.`date` <= ?))")
- }
-
- "multiple unionized filters" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- filter = Union(
- Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x")
- )))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where (`$tableName`.`name` > ? or `$tableName`.`optionDate` >= ?)""".stripMargin.trim)
- }
-
- "multiple unionized nested filters" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- filter = Union(
- Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x"),
- Union(Seq(
- Atom.Binary("optionUser", Eq, "x"),
- Atom.Binary("date", LtEq, "x")
- ))
- )))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |where (`$tableName`.`name` > ? or `$tableName`.`optionDate` >= ? or (`$tableName`.`optionUser` = ? or `$tableName`.`date` <= ?))""".stripMargin)
- }
-
- "multiple unionized and intersected nested filters" in {
- val (sql, _) = queryBuilderParameters
- .copy(filter = Union(Seq(
- Intersection(Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x")
- )),
- Intersection(Seq(
- Atom.Binary("optionUser", Eq, "x"),
- Atom.Binary("date", LtEq, "x")
- ))
- )))
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"$queryBasis\nwhere ((`$tableName`.`name` > ? and `$tableName`.`optionDate` >= ?) " +
- s"or (`$tableName`.`optionUser` = ? and `$tableName`.`date` <= ?))")
- }
-
- "single field from foreign table" in {
- val (sql, _) = queryBuilderParameters
- .copy(filter = Atom.Binary(SearchFilterExpr.Dimension(Some("Kind"), "name"), Eq, "x"))
- .toSql(namingStrategy = MysqlEscape)
- val pattern =
- s"""select `$tableName`.*
- |from `$tableName`
- |inner join `Kind` on `Entity`.`kindId` = `Kind`.`id`
- |where `Kind`.`name` = ?""".stripMargin
- assert(sql == pattern)
- }
- }
-
- "with sorting:" - {
- "single field sorting" in {
- val (sql, _) = queryBuilderParameters
- .copy(sorting = Dimension(None, "name", Ascending))
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"""$queryBasis
- |order by `$tableName`.`name` asc""".stripMargin)
- }
-
- "single foreign sorting field" in {
- val (sql, _) = queryBuilderParameters
- .copy(sorting = Dimension(Some("Kind"), "name", Ascending))
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"""select `$tableName`.*
- |from `$tableName`
- |inner join `Kind` on `Entity`.`kindId` = `Kind`.`id`
- |order by `Kind`.`name` asc""".stripMargin)
- }
-
- "multiple fields sorting" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- sorting = Sequential(
- Seq(
- Dimension(None, "name", Ascending),
- Dimension(None, "date", Descending)
- )))
- .toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |order by `$tableName`.`name` asc, `$tableName`.`date` desc""".stripMargin)
- }
-
- "multiple foreign sorting field" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- sorting = Sequential(
- Seq(
- Dimension(Some("Kind"), "name", Ascending),
- Dimension(Some("User"), "name", Descending)
- )))
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"""select `$tableName`.*
- |from `$tableName`
- |inner join `Kind` on `$tableName`.`kindId` = `Kind`.`id`
- |inner join `User` on `$tableName`.`optionUser` = `User`.`id`
- |order by `Kind`.`name` asc, `User`.`name` desc""".stripMargin)
- }
-
- "multiple field sorting (including foreign tables)" in {
- val (sql, _) = queryBuilderParameters
- .copy(
- sorting = Sequential(
- Seq(
- Dimension(Some("Kind"), "name", Ascending),
- Dimension(None, "date", Descending)
- )))
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"""select `$tableName`.*
- |from `$tableName`
- |inner join `Kind` on `$tableName`.`kindId` = `Kind`.`id`
- |order by `Kind`.`name` asc, `$tableName`.`date` desc""".stripMargin)
- }
- }
-
- "with pagination" in {
- val (sql, _) =
- queryBuilderParameters.copy(pagination = Some(Pagination(5, 3))).toSql(namingStrategy = MysqlEscape)
- assert(
- sql ==
- s"""$queryBasis
- |limit 10, 5""".stripMargin)
- }
-
- "combined" in {
- val filter = Union(
- Seq(
- Intersection(
- Seq(
- Atom.Binary("name", Gt, "x"),
- Atom.Binary("optionDate", GtEq, "x")
- )),
- Intersection(
- Seq(
- Atom.Binary("optionUser", Eq, "x"),
- Atom.Binary("date", LtEq, "x")
- ))
- ))
- val sorting = Sequential(
- Seq(
- Dimension(Some("Kind"), "name", Ascending),
- Dimension(None, "name", Ascending),
- Dimension(None, "date", Descending)
- ))
-
- val (sql, _) = queryBuilderParameters
- .copy(
- filter = filter,
- sorting = sorting,
- pagination = Some(Pagination(5, 3))
- )
- .toSql(namingStrategy = MysqlEscape)
-
- assert(
- sql ==
- s"""select `$tableName`.*
- |from `$tableName`
- |inner join `Kind` on `$tableName`.`kindId` = `Kind`.`id`
- |where ((`$tableName`.`name` > ? and `$tableName`.`optionDate` >= ?) or (`$tableName`.`optionUser` = ? and `$tableName`.`date` <= ?))
- |order by `Kind`.`name` asc, `$tableName`.`name` asc, `$tableName`.`date` desc
- |limit 10, 5""".stripMargin)
- }
-
- }
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/error/UnexpectedFilterException.scala b/src/test/scala/xyz/driver/pdsuicommon/error/UnexpectedFilterException.scala
deleted file mode 100644
index 567661a..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/error/UnexpectedFilterException.scala
+++ /dev/null
@@ -1,3 +0,0 @@
-package xyz.driver.pdsuicommon.error
-
-class UnexpectedFilterException(message: String) extends RuntimeException(message)
diff --git a/src/test/scala/xyz/driver/pdsuicommon/logging/PhiStringContextSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/logging/PhiStringContextSuite.scala
deleted file mode 100644
index eb9d9b4..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/logging/PhiStringContextSuite.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-package xyz.driver.pdsuicommon.logging
-
-import org.scalatest.FreeSpecLike
-
-class PhiStringContextSuite extends FreeSpecLike {
-
- class Foo(x: Int, y: String) {
- val z: Boolean = true
- }
-
- case class Bar(y: Boolean)
-
- implicit def fooToPhiString(foo: Foo): PhiString = new PhiString(s"Foo(z=${foo.z})")
-
- "should not compile if there is no PhiString implicit" in assertDoesNotCompile(
- """val bar = Bar(true)
- |phi"bar is $bar"""".stripMargin
- )
-
- "should compile if there is a PhiString implicit" in assertCompiles(
- """val foo = new Foo(1, "test")
- |println(phi"foo is $foo}")""".stripMargin
- )
-
- "should not contain private info" in {
- val foo = new Foo(42, "test")
- val result = phi"foo is $foo".text
- assert(!result.contains("test"))
- assert(!result.contains("42"))
- }
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/parsers/SearchFilterParserSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/parsers/SearchFilterParserSuite.scala
deleted file mode 100644
index 5cd2dc9..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/parsers/SearchFilterParserSuite.scala
+++ /dev/null
@@ -1,185 +0,0 @@
-package xyz.driver.pdsuicommon.parsers
-
-import xyz.driver.pdsuicommon.db.SearchFilterExpr.Dimension
-import xyz.driver.pdsuicommon.db.{SearchFilterBinaryOperation, SearchFilterExpr, SearchFilterNAryOperation}
-import xyz.driver.pdsuicommon.utils.Implicits.toStringOps
-import xyz.driver.pdsuicommon.parsers.TestUtils._
-import fastparse.core.Parsed
-import org.scalacheck.Arbitrary.arbitrary
-import org.scalacheck.{Gen, Prop}
-import org.scalatest.FreeSpecLike
-import org.scalatest.prop.Checkers
-
-object SearchFilterParserSuite {
-
- class UnexpectedSearchFilterExprException(x: SearchFilterExpr) extends Exception(s"unexpected $x")
-
-}
-
-class SearchFilterParserSuite extends FreeSpecLike with Checkers {
-
- import SearchFilterParserSuite._
-
- "parse" - {
- "dimensions" - {
- "with table name" in check {
- val dimensionGen = {
- for (left <- Gen.identifier; right <- Gen.identifier)
- yield left -> right
- }
- Prop.forAllNoShrink(dimensionGen) {
- case (left, right) =>
- val raw = s"$left.$right"
- SearchFilterParser.dimensionParser.parse(raw) match {
- case Parsed.Success(Dimension(Some(`left`), `right`), _) => true
- case res => false
- }
- }
- }
- "just with field name" in check {
- Prop.forAllNoShrink(Gen.identifier) { s =>
- SearchFilterParser.dimensionParser.parse(s) match {
- case Parsed.Success(Dimension(None, `s`), _) => true
- case _ => false
- }
- }
- }
- }
- "atoms" - {
- "binary" - {
- "common operators" - {
- "should be parsed with text values" in check {
- import SearchFilterBinaryOperation._
-
- val testQueryGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = commonBinaryOpsGen,
- valueGen = nonEmptyString
- )
-
- Prop.forAllNoShrink(testQueryGen) { query =>
- SearchFilterParser.parse(Seq("filters" -> query))
- .map {
- case SearchFilterExpr.Atom.Binary(_, Eq | NotEq | Like, _) => true
- case x => throw new UnexpectedSearchFilterExprException(x)
- }
- .successProp
- }
- }
- }
-
- "numeric operators" - {
- "should not be parsed with text values" in check {
- val testQueryGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = numericBinaryOpsGen,
- valueGen = nonEmptyString.filter { s => !s.matches("^\\d+$") }
- )
-
- Prop.forAllNoShrink(testQueryGen) { query =>
- SearchFilterParser.parse(Seq("filters" -> query)).failureProp
- }
- }
- }
-
- "all operators" - {
- "should be parsed with numeric values" in check {
- val testQueryGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = allBinaryOpsGen,
- valueGen = numericBinaryAtomValuesGen
- )
-
- Prop.forAllNoShrink(testQueryGen) { query =>
- SearchFilterParser.parse(Seq("filters" -> query))
- .map {
- case _: SearchFilterExpr.Atom.Binary => true
- case x => throw new UnexpectedSearchFilterExprException(x)
- }
- .successProp
- }
- }
- }
- }
-
- "n-ary" - {
- "in" in check {
- val testQueryGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = Gen.const("in"),
- valueGen = inValuesGen
- )
-
- Prop.forAllNoShrink(testQueryGen) { query =>
- SearchFilterParser.parse(Seq("filters" -> query))
- .map {
- case SearchFilterExpr.Atom.NAry(_, SearchFilterNAryOperation.In, _) => true
- case x => throw new UnexpectedSearchFilterExprException(x)
- }
- .successProp
- }
- }
- }
- }
-
- "intersections" - {
- "should be parsed" in check {
- val commonAtomsGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = commonBinaryOpsGen,
- valueGen = nonEmptyString
- )
-
- val numericAtomsGen = queryGen(
- dimensionGen = Gen.identifier,
- opGen = numericBinaryOpsGen,
- valueGen = numericBinaryAtomValuesGen
- )
-
- val allAtomsGen = Gen.oneOf(commonAtomsGen, numericAtomsGen)
- val intersectionsGen = Gen.choose(1, 3).flatMap { size =>
- Gen.containerOfN[Seq, String](size, allAtomsGen)
- }
-
- Prop.forAllNoShrink(intersectionsGen) { queries =>
- SearchFilterParser.parse(queries.map(query => "filters" -> query)).successProp
- }
- }
- }
- }
-
- private val CommonBinaryOps = Seq("eq", "noteq", "like")
- private val NumericBinaryOps = Seq("gt", "gteq", "lt", "lteq")
-
- private val allBinaryOpsGen: Gen[String] = Gen.oneOf(CommonBinaryOps ++ NumericBinaryOps).flatMap(randomCapitalization)
- private val commonBinaryOpsGen: Gen[String] = Gen.oneOf(CommonBinaryOps).flatMap(randomCapitalization)
- private val numericBinaryOpsGen: Gen[String] = Gen.oneOf(NumericBinaryOps).flatMap(randomCapitalization)
-
- private val inValueCharsGen: Gen[Char] = arbitrary[Char].filter(_ != ',')
-
- private val nonEmptyString = arbitrary[String].filter { s => !s.safeTrim.isEmpty }
-
- private val numericBinaryAtomValuesGen: Gen[String] = arbitrary[BigInt].map(_.toString)
- private val inValueGen: Gen[String] = {
- Gen.nonEmptyContainerOf[Seq, Char](inValueCharsGen).map(_.mkString).filter(_.safeTrim.nonEmpty)
- }
- private val inValuesGen: Gen[String] = Gen.choose(1, 5).flatMap { size =>
- Gen.containerOfN[Seq, String](size, inValueGen).map(_.mkString(","))
- }
-
- private def queryGen(dimensionGen: Gen[String], opGen: Gen[String], valueGen: Gen[String]): Gen[String] = for {
- dimension <- dimensionGen
- op <- opGen
- value <- valueGen
- } yield s"$dimension $op $value"
-
- private def randomCapitalization(input: String): Gen[String] = {
- Gen.containerOfN[Seq, Boolean](input.length, arbitrary[Boolean]).map { capitalize =>
- input.view.zip(capitalize).map {
- case (currChar, true) => currChar.toUpper
- case (currChar, false) => currChar
- }.mkString
- }
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/pdf/MockPdfRenderer.scala b/src/test/scala/xyz/driver/pdsuicommon/pdf/MockPdfRenderer.scala
deleted file mode 100644
index 8dfd29c..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/pdf/MockPdfRenderer.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-package xyz.driver.pdsuicommon.pdf
-
-import java.nio.file.{Path, Paths}
-
-import xyz.driver.pdsuicommon.logging._
-
-object MockPdfRenderer extends PdfRenderer with PhiLogging {
-
- private lazy val defaultDocument: Path = {
- val uri = getClass.getResource("/pdf/example.pdf").toURI
- Paths.get(uri)
- }
-
- override def render(html: String, documentName: String, force: Boolean = false): Path = {
- logger.trace(phi"render(html, documentName=${Unsafe(documentName)})")
- defaultDocument
- }
-
- override def delete(documentName: String): Unit = {
- logger.trace(phi"delete(${Unsafe(documentName)})")
- }
-
- override def getPath(documentName: String): Path = defaultDocument
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/utils/DiffUtils.scala b/src/test/scala/xyz/driver/pdsuicommon/utils/DiffUtils.scala
deleted file mode 100644
index 156cb08..0000000
--- a/src/test/scala/xyz/driver/pdsuicommon/utils/DiffUtils.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-package xyz.driver.pdsuicommon.utils
-
-import java.net.URI
-import java.time.{LocalDate, LocalDateTime}
-
-import ai.x.diff._
-import org.scalatest.Assertions
-import xyz.driver.pdsuidomain.entities.{Document, ExtractedData, MedicalRecord}
-
-import scala.io.AnsiColor
-
-trait DiffUtils { this: Assertions =>
-
- def assertIdentical[T: DiffShow](left: T, right: T): Unit = {
- val diff = DiffShow.diff(left, right)
- assert(diff.isIdentical, s"\n${AnsiColor.RESET}$diff") // reset red color
- }
-
- implicit def localTimeDiffShow: DiffShow[LocalDateTime] = new DiffShow[LocalDateTime] {
- def show(x: LocalDateTime): String = s"LocalTime($x)"
- def diff(left: LocalDateTime, right: LocalDateTime): Comparison = {
- if (left.isEqual(right)) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
- implicit def localDateDiffShow: DiffShow[LocalDate] = new DiffShow[LocalDate] {
- def show(x: LocalDate): String = s"LocalDate($x)"
- def diff(left: LocalDate, right: LocalDate): Comparison = {
- if (left.isEqual(right)) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
- implicit def urlDiffShow: DiffShow[URI] = new DiffShow[URI] {
- def show(x: URI): String = s"URI($x)"
- def diff(left: URI, right: URI): Comparison = {
- if (left.equals(right)) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
- implicit def metaDiffShow: DiffShow[MedicalRecord.Meta] = new DiffShow[MedicalRecord.Meta] {
- def show(x: MedicalRecord.Meta): String = s"MedicalRecord.Meta($x)"
- def diff(left: MedicalRecord.Meta, right: MedicalRecord.Meta): Comparison = {
- if (left.equals(right)) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
- implicit def extractedDataMetaDiffShow: DiffShow[ExtractedData.Meta] = new DiffShow[ExtractedData.Meta] {
- def show(x: ExtractedData.Meta): String = s"ExtractedData.Meta($x)"
- def diff(left: ExtractedData.Meta, right: ExtractedData.Meta): Comparison = {
- if (left.equals(right)) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
- implicit def documentDiffShow: DiffShow[Document] = new DiffShow[Document] {
- def show(x: Document): String = s"Document($x)"
-
- def diff(left: Document, right: Document): Comparison = {
- if (left == right) Identical(show(left))
- else Different(showChange(left, right))
- }
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/DocumentSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/DocumentSuite.scala
deleted file mode 100644
index f851680..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/DocumentSuite.scala
+++ /dev/null
@@ -1,87 +0,0 @@
-package xyz.driver.pdsuidomain
-
-import java.time.{LocalDate, LocalDateTime}
-import java.time.temporal.ChronoUnit
-
-import xyz.driver.pdsuicommon.BaseSuite
-import xyz.driver.pdsuicommon.domain.{LongId, TextJson}
-import xyz.driver.pdsuidomain.entities.Document
-
-class DocumentSuite extends BaseSuite {
-
- "validation" - {
- "can't submit invalid data" - {
- val base = sampleDocument
-
- val now = LocalDate.now()
- val past1 = now.minus(2, ChronoUnit.DAYS)
- val past2 = past1.plus(1, ChronoUnit.DAYS)
- val future1 = now.plus(1, ChronoUnit.DAYS)
- val future2 = future1.plus(1, ChronoUnit.DAYS)
-
- Seq(
- "startDate should be non-empty" -> base.copy(startDate = None),
- "startDate should be greater, than endDate" -> base.copy(startDate = Some(past2), endDate = Some(past1)),
- "startDate and endDate should be in the past" -> base.copy(startDate = Some(future1), endDate = Some(future2))
- ).foreach {
- case (title, orig) =>
- s"$title" in {
- val r = Document.validator(orig)
- assert(r.isLeft, s"should fail, but: ${r.right}")
- }
- }
- }
- }
-
- "getRequiredType" - {
- "getOPNType" in {
- val documentForOPNType = sampleDocument.copy(
- typeId = Some(LongId(1L)),
- providerTypeId = Some(LongId(1L)),
- startDate = Some(LocalDate.now().minus(2, ChronoUnit.DAYS))
- )
- val r = documentForOPNType.getRequiredType("Outpatient Physician Note", "Medical Oncology")
- assert(r.contains(Document.RequiredType.OPN), s"document should have the requiredType=OPN, but:$r")
- }
-
- "getPNType" in {
- val documentForPNType = sampleDocument.copy(
- typeId = Some(LongId(6))
- )
- val r = documentForPNType.getRequiredType("Pathology Report", "")
- assert(r.contains(Document.RequiredType.PN), s"document should have the requiredType=PN, but:$r")
- }
- "get None" in {
- val document = sampleDocument.copy(
- typeId = Some(LongId(1L)),
- providerTypeId = Some(LongId(1L)),
- startDate = Some(LocalDate.now().minus(7, ChronoUnit.MONTHS))
- )
- val r = document.getRequiredType("Outpatient Physician Note", "Medical Oncology")
- assert(r.isEmpty, s"document should have the requiredType=None, but:$r")
- }
- }
-
- private def sampleDocument = {
- val lastUpdate = LocalDateTime.now()
-
- Document(
- id = LongId(2002),
- status = Document.Status.New,
- previousStatus = None,
- assignee = None,
- previousAssignee = None,
- lastActiveUserId = None,
- recordId = LongId(2003),
- physician = None,
- typeId = Some(LongId(123)),
- providerName = Some("etst"),
- providerTypeId = Some(LongId(123)),
- requiredType = None,
- startDate = Some(lastUpdate.toLocalDate.minusDays(2)),
- endDate = None,
- lastUpdate = lastUpdate,
- meta = Some(TextJson(Document.Meta(None, 1.1, 2.2)))
- )
- }
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala
deleted file mode 100644
index e7d37a0..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.Arm
-
-class ArmFormatSuite extends FlatSpec with Matchers {
- import arm._
-
- "Json format for Arm" should "read and write correct JSON" in {
- val arm = Arm(
- id = LongId(10),
- trialId = StringId("NCT000001"),
- name = "arm name",
- originalName = "orig arm name"
- )
- val writtenJson = armFormat.write(arm)
-
- writtenJson should be("""{"id":10,"trialId":"NCT000001","name":"arm name","originalName":"orig arm name"}""".parseJson)
-
- val createArmJson = """{"trialId":"NCT000001","name":"arm name"}""".parseJson
- val parsedArm = armFormat.read(createArmJson)
- val expectedCreatedArm = arm.copy(
- id = LongId(0),
- originalName = "arm name"
- )
- parsedArm should be(expectedCreatedArm)
-
- val updateArmJson = """{"name":"new arm name"}""".parseJson
- val expectedUpdatedArm = arm.copy(name = "new arm name")
- val parsedUpdateArm = applyUpdateToArm(updateArmJson, arm)
- parsedUpdateArm should be(expectedUpdatedArm)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/BridgeUploadQueueFormat.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/BridgeUploadQueueFormat.scala
deleted file mode 100644
index 854f51f..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/BridgeUploadQueueFormat.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueue
-
-class BridgeUploadQueueFormat extends FlatSpec with Matchers {
- import bridgeuploadqueue._
-
- "Json format for BridgeUploadQueue.Item" should "read and write correct JSON" in {
- val item = BridgeUploadQueue.Item(
- kind = "kind",
- tag = "tag",
- created = LocalDateTime.parse("2017-08-10T18:00:00"),
- attempts = 0,
- nextAttempt = LocalDateTime.parse("2017-08-10T18:10:00"),
- completed = false,
- dependencyKind = Some("dependency king"),
- dependencyTag = None
- )
- val writtenJson = queueUploadItemFormat.write(item)
-
- writtenJson should be(
- """{"kind":"kind","tag":"tag","created":"2017-08-10T18:00Z","attempts":0,"nextAttempt":"2017-08-10T18:10Z","completed":false}""".parseJson)
-
- val parsedItem = queueUploadItemFormat.read(writtenJson)
- parsedItem should be(item.copy(dependencyKind = None, completed = true))
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala
deleted file mode 100644
index d24c4c1..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.{Arm, Criterion, CriterionLabel}
-import xyz.driver.pdsuidomain.services.CriterionService.RichCriterion
-
-class CriterionFormatSuite extends FlatSpec with Matchers {
- import criterion._
-
- "Json format for Criterion" should "read and write correct JSON" in {
- val criterion = Criterion(
- id = LongId(10),
- trialId = StringId("NCT000001"),
- text = Some("text"),
- isCompound = false,
- meta = "{}"
- )
- val labels = List(
- CriterionLabel(
- id = LongId(1L),
- labelId = Some(LongId(101)),
- criterionId = criterion.id,
- categoryId = Some(LongId(3)),
- value = Some(true),
- isDefining = true
- ),
- CriterionLabel(
- id = LongId(2L),
- labelId = Some(LongId(102)),
- criterionId = criterion.id,
- categoryId = Some(LongId(3)),
- value = Some(false),
- isDefining = true
- )
- )
- val arms = List(LongId[Arm](20), LongId[Arm](21), LongId[Arm](21))
- val richCriterion = RichCriterion(
- criterion = criterion,
- armIds = arms,
- labels = labels
- )
- val writtenJson = richCriterionFormat.write(richCriterion)
-
- writtenJson should be(
- """{"text":"text","isCompound":false,"trialId":"NCT000001","arms":[20,21,21],"id":10,"meta":"{}",
- "labels":[{"labelId":101,"categoryId":3,"value":"Yes","isDefining":true},
- {"labelId":102,"categoryId":3,"value":"No","isDefining":true}]}""".parseJson)
-
- val createCriterionJson =
- """{"text":"text","isCompound":false,"trialId":"NCT000001",
- "arms":[20,21,21],"meta":"{}","labels":[{"labelId":101,"categoryId":3,"value":"Yes","isDefining":true},
- {"labelId":102,"categoryId":3,"value":"No","isDefining":true}]}""".parseJson
- val parsedRichCriterion = richCriterionFormat.read(createCriterionJson)
- val expectedRichCriterion = richCriterion.copy(
- criterion = criterion.copy(id = LongId(0)),
- labels = labels.map(_.copy(id = LongId(0), criterionId = LongId(0)))
- )
- parsedRichCriterion should be(expectedRichCriterion)
-
- val updateCriterionJson = """{"meta":null,"text":"new text","isCompound":true}""".parseJson
- val expectedUpdatedCriterion = richCriterion.copy(criterion = criterion.copy(text = Some("new text"), isCompound = true, meta = "{}"))
- val parsedUpdateCriterion = applyUpdateToCriterion(updateCriterionJson, richCriterion)
- parsedUpdateCriterion should be(expectedUpdatedCriterion)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala
deleted file mode 100644
index 9394735..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.{LocalDate, LocalDateTime}
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, TextJson}
-import xyz.driver.pdsuidomain.entities.Document
-
-class DocumentFormatSuite extends FlatSpec with Matchers {
- import document._
-
- "Json format for Document" should "read and write correct JSON" in {
- val orig = Document(
- id = LongId(1),
- status = Document.Status.New,
- assignee = None,
- previousStatus = None,
- previousAssignee = None,
- lastActiveUserId = None,
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- recordId = LongId(101),
- physician = Some("physician"),
- typeId = Some(LongId(10)),
- providerName = Some("provider 21"),
- providerTypeId = Some(LongId(21)),
- requiredType = Some(Document.RequiredType.OPN),
- meta = None,
- startDate = None,
- endDate = None
- )
- val writtenJson = documentFormat.write(orig)
-
- writtenJson should be (
- """{"id":1,"recordId":101,"physician":"physician","typeId":10,"provider":"provider 21","providerTypeId":21,
- "requiredType":"OPN","startDate":null,"endDate":null,"status":"New","assignee":null,"previousStatus":null,
- "previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z","meta":null}""".parseJson)
-
- val createDocumentJson =
- """{"recordId":101,"physician":"physician","typeId":10,"provider":"provider 21","providerTypeId":21}""".parseJson
- val expectedCreatedDocument = orig.copy(
- id = LongId(0),
- lastUpdate = LocalDateTime.MIN,
- requiredType = None
- )
- val parsedCreatedDocument = documentFormat.read(createDocumentJson)
- parsedCreatedDocument should be(expectedCreatedDocument)
-
- val updateDocumentJson =
- """{"startDate":"2017-08-10","endDate":"2018-08-10","meta":{"predicted":true,"startPage":1.0,"endPage":2.0}}""".parseJson
- val expectedUpdatedDocument = orig.copy(
- startDate = Some(LocalDate.parse("2017-08-10")),
- endDate = Some(LocalDate.parse("2018-08-10")),
- meta = Some(TextJson(Document.Meta(predicted = Some(true), startPage = 1.0, endPage = 2.0)))
- )
- val parsedUpdatedDocument = applyUpdateToDocument(updateDocumentJson, orig)
- parsedUpdatedDocument should be(expectedUpdatedDocument)
- }
-
- "Json format for Document.Meta" should "read and write correct JSON" in {
- val meta = Document.Meta(predicted = None, startPage = 1.0, endPage = 2.0)
- val writtenJson = documentMetaFormat.write(meta)
- writtenJson should be ("""{"startPage":1.0,"endPage":2.0}""".parseJson)
-
- val metaJsonWithoutPredicted = """{"startPage":1.0,"endPage":2.0}""".parseJson
- val parsedMetaWithoutPredicted = documentMetaFormat.read(metaJsonWithoutPredicted)
- parsedMetaWithoutPredicted should be(meta)
-
- val metaJsonWithPredicted = """{"predicted":true,"startPage":1.0,"endPage":2.0}""".parseJson
- val parsedMetaWithPredicted = documentMetaFormat.read(metaJsonWithPredicted)
- parsedMetaWithPredicted should be(meta.copy(predicted = Some(true)))
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala
deleted file mode 100644
index ddbda1d..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.DocumentHistory
-
-class DocumentHistoryFormatSuite extends FlatSpec with Matchers {
- import documenthistory._
-
- "Json format for DocumentHistory" should "read and write correct JSON" in {
- val documentHistory = DocumentHistory(
- id = LongId(10),
- documentId = LongId(1),
- executor = StringId("userId-001"),
- state = DocumentHistory.State.Extract,
- action = DocumentHistory.Action.Start,
- created = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val writtenJson = documentHistoryFormat.write(documentHistory)
-
- writtenJson should be(
- """{"id":10,"executor":"userId-001","documentId":1,"state":"Extract",
- "action":"Start","created":"2017-08-10T18:00Z"}""".parseJson)
-
- val parsedDocumentHistory = documentHistoryFormat.read(writtenJson)
- parsedDocumentHistory should be(documentHistory)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala
deleted file mode 100644
index 1a8e3f0..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.DocumentIssue
-
-class DocumentIssueFormatSuite extends FlatSpec with Matchers {
- import documentissue._
-
- "Json format for DocumentIssue" should "read and write correct JSON" in {
- val documentIssue = DocumentIssue(
- id = LongId(10),
- documentId = LongId(1),
- userId = StringId("userId-001"),
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- isDraft = false,
- text = "message text",
- archiveRequired = false,
- startPage = Some(1.0),
- endPage = Some(2.0)
- )
- val writtenJson = documentIssueWriter.write(documentIssue)
-
- writtenJson should be(
- """{"id":10,"userId":"userId-001","lastUpdate":"2017-08-10T18:00Z","isDraft":false,
- "text":"message text","archiveRequired":false,"startPage":1.0,"endPage":2.0}""".parseJson)
-
- val createDocumentIssueJson = """{"text":"message text","startPage":1.0,"endPage":2.0}""".parseJson
- val expectedCreatedDocumentIssue = documentIssue.copy(id = LongId(0), lastUpdate = LocalDateTime.MIN, isDraft = true)
- val parsedCreateDocumentIssue = jsValueToDocumentIssue(createDocumentIssueJson, LongId(1), StringId("userId-001"))
- parsedCreateDocumentIssue should be(expectedCreatedDocumentIssue)
-
- val updateDocumentIssueJson =
- """{"text":"new issue text","evidence":"issue evidence","archiveRequired":true,"startPage":1.0,"endPage":4.0}""".parseJson
- val expectedUpdatedDocumentIssue = documentIssue.copy(
- text = "new issue text",
- archiveRequired = true,
- endPage = Some(4.0)
- )
- val parsedUpdateDocumentIssue = applyUpdateToDocumentIssue(updateDocumentIssueJson, documentIssue)
- parsedUpdateDocumentIssue should be(expectedUpdatedDocumentIssue)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExportFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExportFormatSuite.scala
deleted file mode 100644
index d0d4d1a..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExportFormatSuite.scala
+++ /dev/null
@@ -1,124 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.{LocalDate, LocalDateTime}
-import java.util.UUID
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{FuzzyValue, LongId, StringId, UuidId}
-import xyz.driver.pdsuidomain.entities.RecordRequestId
-
-class ExportFormatSuite extends FlatSpec with Matchers {
- import export._
-
- "Json format for ExportPatientWithLabels" should "read and write correct JSON" in {
- import xyz.driver.pdsuidomain.entities.export.patient._
- val document = ExportPatientLabelEvidenceDocument(
- documentId = LongId(101),
- requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")),
- documentType = "document type",
- providerType = "provider type",
- date = LocalDate.parse("2017-08-10")
- )
- val labels = List(
- ExportPatientLabel(
- id = LongId(1),
- evidences = List(
- ExportPatientLabelEvidence(
- id = LongId(11),
- value = FuzzyValue.Yes,
- evidenceText = "evidence text 11",
- document = document
- ),
- ExportPatientLabelEvidence(
- id = LongId(12),
- value = FuzzyValue.No,
- evidenceText = "evidence text 12",
- document = document
- )
- )
- ),
- ExportPatientLabel(
- id = LongId(2),
- evidences = List(
- ExportPatientLabelEvidence(
- id = LongId(12),
- value = FuzzyValue.Yes,
- evidenceText = "evidence text 12",
- document = document
- ),
- ExportPatientLabelEvidence(
- id = LongId(13),
- value = FuzzyValue.Yes,
- evidenceText = "evidence text 13",
- document = document
- )
- )
- )
- )
- val patientWithLabels = ExportPatientWithLabels(
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- labelVersion = 1L,
- labels = labels
- )
-
- val writtenJson = patientWithLabelsWriter.write(patientWithLabels)
- writtenJson should be(
- """{"patientId":"748b5884-3528-4cb9-904b-7a8151d6e343","labelVersion":1,"labels":[{"labelId":1,"evidence":[{"evidenceId":11,
- "labelValue":"Yes","evidenceText":"evidence text 11","document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9",
- "documentType":"document type","providerType":"provider type","date":"2017-08-10"}},{"evidenceId":12,"labelValue":"No",
- "evidenceText":"evidence text 12","document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9",
- "documentType":"document type","providerType":"provider type","date":"2017-08-10"}}]},
- {"labelId":2,"evidence":[{"evidenceId":12,"labelValue":"Yes","evidenceText":"evidence text 12","document":
- {"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","documentType":"document type",
- "providerType":"provider type","date":"2017-08-10"}},{"evidenceId":13,"labelValue":"Yes","evidenceText":"evidence text 13",
- "document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","documentType":"document type",
- "providerType":"provider type","date":"2017-08-10"}}]}]}""".parseJson)
- }
-
- "Json format for ApiExportTrialWithLabels" should "read and write correct JSON" in {
- import xyz.driver.pdsuidomain.entities.export.trial._
- val arms = List(
- ExportTrialArm(armId = LongId(1), armName = "arm 1"),
- ExportTrialArm(armId = LongId(2), armName = "arm 2")
- )
- val criteriaList = List(
- ExportTrialLabelCriterion(
- criterionId = LongId(10),
- value = Some(true),
- labelId = LongId(21),
- armIds = Set(LongId(1), LongId(2)),
- criteria = "criteria 10 text",
- isCompound = false,
- isDefining = false
- ),
- ExportTrialLabelCriterion(
- criterionId = LongId(11),
- value = None,
- labelId = LongId(21),
- armIds = Set(LongId(2)),
- criteria = "criteria 11 text",
- isCompound = true,
- isDefining = false
- )
- )
- val trialWithLabels = ExportTrialWithLabels(
- nctId = StringId("NCT000001"),
- trialId = UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"),
- condition = "Breast",
- lastReviewed = LocalDateTime.parse("2017-08-10T18:00:00"),
- labelVersion = 1L,
- arms = arms,
- criteria = criteriaList
- )
-
- val writtenJson = trialWithLabelsWriter.write(trialWithLabels)
- writtenJson should be(
- """{"nctId":"NCT000001","trialId":"40892a07-c638-49d2-9795-1edfefbbcc7c","disease":"Breast","lastReviewed":"2017-08-10T18:00Z",
- "labelVersion":1,"arms":[{"armId":1,"armName":"arm 1"},{"armId":2,"armName":"arm 2"}],"criteria":[
- {"value":"Yes","labelId":21,"criterionId":10,"criterionText":"criteria 10 text","armIds":[1,2],"isCompound":false,"isDefining":false},
- {"value":"Unknown","labelId":21,"criterionId":11,"criterionText":"criteria 11 text","armIds":[2],"isCompound":true,"isDefining":false}]}""".parseJson)
- }
-
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala
deleted file mode 100644
index a4b8bab..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{FuzzyValue, LongId, TextJson}
-import xyz.driver.pdsuidomain.entities.ExtractedData.Meta
-import xyz.driver.pdsuidomain.entities.{ExtractedData, ExtractedDataLabel}
-import xyz.driver.pdsuidomain.services.ExtractedDataService.RichExtractedData
-
-class ExtractedDataFormatSuite extends FlatSpec with Matchers {
- import extracteddata._
-
- "Json format for ExtractedData" should "read and write correct JSON" in {
- val extractedData = ExtractedData(
- id = LongId(1),
- documentId = LongId(101),
- keywordId = Some(LongId(201)),
- evidenceText = Some("evidence text"),
- meta = None
- )
- val extractedDataLabels = List(
- ExtractedDataLabel(
- id = LongId(1),
- dataId = extractedData.id,
- labelId = None,
- categoryId = None,
- value = Some(FuzzyValue.Yes)
- ),
- ExtractedDataLabel(
- id = LongId(2),
- dataId = extractedData.id,
- labelId = Some(LongId(12)),
- categoryId = Some(LongId(1)),
- value = Some(FuzzyValue.No)
- )
- )
- val origRichExtractedData = RichExtractedData(
- extractedData = extractedData,
- labels = extractedDataLabels
- )
- val writtenJson = extractedDataFormat.write(origRichExtractedData)
-
- writtenJson should be (
- """{"id":1,"documentId":101,"keywordId":201,"evidence":"evidence text","meta":null,
- "labels":[{"id":null,"categoryId":null,"value":"Yes"},{"id":12,"categoryId":1,"value":"No"}]}""".parseJson)
-
- val createExtractedDataJson =
- """{"documentId":101,"keywordId":201,"evidence":"evidence text",
- "labels":[{"value":"Yes"},{"id":12,"categoryId":1,"value":"No"}]}""".parseJson
- val expectedCreatedExtractedData = origRichExtractedData.copy(
- extractedData = extractedData.copy(id = LongId(0)),
- labels = extractedDataLabels.map(_.copy(id = LongId(0), dataId = LongId(0)))
- )
- val parsedCreatedExtractedData = extractedDataFormat.read(createExtractedDataJson)
- parsedCreatedExtractedData should be(expectedCreatedExtractedData)
-
- val updateExtractedDataJson =
- """{"evidence":"new evidence text","meta":{"keyword":{"page":1,"index":2,"sortIndex":"ASC"},
- "evidence":{"pageRatio":1.0,"start":{"page":1,"index":3,"offset":2},"end":{"page":2,"index":3,"offset":10}}},
- "labels":[{"id":20,"categoryId":1,"value":"Yes"},{"id":12,"categoryId":1,"value":"No"}]}""".parseJson
- val updatedExtractedDataLabels = List(
- ExtractedDataLabel(
- id = LongId(0),
- dataId = extractedData.id,
- labelId = Some(LongId(20)),
- categoryId = Some(LongId(1)),
- value = Some(FuzzyValue.Yes)
- ),
- ExtractedDataLabel(
- id = LongId(0),
- dataId = extractedData.id,
- labelId = Some(LongId(12)),
- categoryId = Some(LongId(1)),
- value = Some(FuzzyValue.No)
- )
- )
- val expectedUpdatedExtractedData = origRichExtractedData.copy(
- extractedData = extractedData.copy(
- evidenceText = Some("new evidence text"),
- meta = Some(TextJson(Meta(
- keyword = Meta.Keyword(page = 1, pageRatio = None, index = 2, sortIndex = "ASC"),
- evidence = Meta.Evidence(
- pageRatio = 1.0,
- start = Meta.TextLayerPosition(page = 1, index = 3, offset = 2),
- end = Meta.TextLayerPosition(page = 2, index = 3, offset = 10)
- )
- )))
- ),
- labels = updatedExtractedDataLabels
- )
- val parsedUpdatedExtractedData = applyUpdateToExtractedData(updateExtractedDataJson, origRichExtractedData)
- parsedUpdatedExtractedData should be(expectedUpdatedExtractedData)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala
deleted file mode 100644
index 306fb17..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.UuidId
-import xyz.driver.pdsuidomain.entities.Hypothesis
-
-class HypothesisFormatSuite extends FlatSpec with Matchers {
- import hypothesis._
-
- "Json format for Hypothesis" should "read and write correct JSON" in {
- val hypothesis = Hypothesis(
- id = UuidId("3b80b2e2-5372-4cf5-a342-6e4ebe10fafd"),
- name = "hypothesis name",
- treatmentType = "treatment type",
- description = "descr"
- )
- val writtenJson = hypothesisFormat.write(hypothesis)
-
- writtenJson should be(
- """{"id":"3b80b2e2-5372-4cf5-a342-6e4ebe10fafd","name":"hypothesis name",
- "treatmentType":"treatment type","description":"descr"}""".parseJson)
-
- val parsedHypothesis = hypothesisFormat.read(writtenJson)
- parsedHypothesis should be(hypothesis)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala
deleted file mode 100644
index 784a655..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.{Intervention, InterventionArm, InterventionType, InterventionWithArms}
-
-class InterventionFormatSuite extends FlatSpec with Matchers {
- import intervention._
-
- "Json format for Intervention" should "read and write correct JSON" in {
- val intervention = Intervention(
- id = LongId(1),
- trialId = StringId("NCT000001"),
- name = "intervention name",
- originalName = "orig name",
- typeId = Some(LongId(10)),
- originalType = Some("orig type"),
- description = "",
- originalDescription = "",
- isActive = true
- )
- val arms = List(
- InterventionArm(interventionId = intervention.id, armId = LongId(20)),
- InterventionArm(interventionId = intervention.id, armId = LongId(21)),
- InterventionArm(interventionId = intervention.id, armId = LongId(22))
- )
- val orig = InterventionWithArms(
- intervention = intervention,
- arms = arms
- )
- val writtenJson = interventionWriter.write(orig)
-
- writtenJson should be(
- """{"id":1,"name":"intervention name","typeId":10,"description":"","isActive":true,"arms":[20,21,22],
- "trialId":"NCT000001","originalName":"orig name","originalDescription":"","originalType":"orig type"}""".parseJson)
-
- val updateInterventionJson = """{"description":"descr","arms":[21,22]}""".parseJson
- val expectedUpdatedIntervention = orig.copy(
- intervention = intervention.copy(description = "descr"),
- arms = List(
- InterventionArm(interventionId = intervention.id, armId = LongId(21)),
- InterventionArm(interventionId = intervention.id, armId = LongId(22))
- )
- )
- val parsedUpdateIntervention = applyUpdateToInterventionWithArms(updateInterventionJson, orig)
- parsedUpdateIntervention should be(expectedUpdatedIntervention)
- }
-
- "Json format for InterventionType" should "read and write correct JSON" in {
- val interventionType = InterventionType(
- id = LongId(10),
- name = "type name"
- )
- val writtenJson = interventionTypeFormat.write(interventionType)
-
- writtenJson should be("""{"id":10,"name":"type name"}""".parseJson)
-
- val parsedInterventionType = interventionTypeFormat.read(writtenJson)
- parsedInterventionType should be(interventionType)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordFormatSuite.scala
deleted file mode 100644
index 899e5c9..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordFormatSuite.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-import java.util.UUID
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, TextJson, UuidId}
-import xyz.driver.pdsuidomain.entities.{MedicalRecord, RecordRequestId}
-
-class MedicalRecordFormatSuite extends FlatSpec with Matchers {
- import record._
- import MedicalRecord._
-
- "Json format for MedicalRecord" should "read and write correct JSON" in {
- val orig = MedicalRecord(
- id = LongId(1),
- status = Status.New,
- assignee = None,
- previousStatus = None,
- previousAssignee = None,
- lastActiveUserId = None,
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- physician = Some("physician"),
- meta = None,
- predictedMeta = None,
- predictedDocuments = None,
- disease = "Breast",
- requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")),
- caseId = None,
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343")
- )
- val writtenJson = recordFormat.write(orig)
-
- writtenJson should be (
- """{"id":1,"status":"New","assignee":null,"previousStatus":null,"previousAssignee":null,"lastActiveUser":null,
- "lastUpdate":"2017-08-10T18:00Z","meta":[],"patientId":"748b5884-3528-4cb9-904b-7a8151d6e343","caseId":null,
- "requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","disease":"Breast","physician":"physician"}""".parseJson)
-
- val createRecordJson =
- """{"disease":"Breast","patientId":"748b5884-3528-4cb9-904b-7a8151d6e343","requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9"}""".parseJson
- val expectedCreatedRecord = MedicalRecord(
- id = LongId(0),
- status = MedicalRecord.Status.New,
- previousStatus = None,
- assignee = None,
- previousAssignee = None,
- lastActiveUserId = None,
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")),
- disease = "Breast",
- caseId = None,
- physician = None,
- meta = None,
- predictedMeta = None,
- predictedDocuments = None,
- lastUpdate = LocalDateTime.now()
- )
- val parsedCreatedRecord = recordFormat.read(createRecordJson).copy(lastUpdate = expectedCreatedRecord.lastUpdate)
- parsedCreatedRecord should be(expectedCreatedRecord)
-
- val updateRecordJson =
- """{"meta":[{"type":"duplicate","predicted":true,"startPage":1.0,"endPage":2.0,"startOriginalPage":1.0},
- {"type":"reorder","items":[1,2]},
- {"type":"rotation","items":{"item1":1,"item2":2}}]}""".parseJson
- val expectedUpdatedRecord = orig.copy(
- meta = Some(TextJson(List(
- Meta.Duplicate(predicted = Some(true), startPage = 1.0, endPage = 2.0, startOriginalPage = 1.0, endOriginalPage = None),
- Meta.Reorder(predicted = None, items = Seq(1, 2)),
- Meta.Rotation(predicted = None, items = Map("item1" -> 1, "item2" -> 2))
- )))
- )
- val parsedUpdatedRecord = applyUpdateToMedicalRecord(updateRecordJson, orig)
- parsedUpdatedRecord should be(expectedUpdatedRecord)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala
deleted file mode 100644
index 5cd6c8d..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.MedicalRecordHistory
-
-class MedicalRecordHistoryFormatSuite extends FlatSpec with Matchers {
- import recordhistory._
-
- "Json format for MedicalRecordHistory" should "read and write correct JSON" in {
- val recordHistory = MedicalRecordHistory(
- id = LongId(10),
- recordId = LongId(1),
- executor = StringId("userId-001"),
- state = MedicalRecordHistory.State.Clean,
- action = MedicalRecordHistory.Action.Start,
- created = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val writtenJson = recordHistoryFormat.write(recordHistory)
-
- writtenJson should be(
- """{"id":10,"executor":"userId-001","recordId":1,"state":"Clean",
- "action":"Start","created":"2017-08-10T18:00Z"}""".parseJson)
-
- val parsedRecordHistory = recordHistoryFormat.read(writtenJson)
- parsedRecordHistory should be(recordHistory)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordIssueFormatSuite.scala
deleted file mode 100644
index 9b89c97..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordIssueFormatSuite.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.MedicalRecordIssue
-
-class MedicalRecordIssueFormatSuite extends FlatSpec with Matchers {
- import recordissue._
-
- "Json format for MedicalRecordIssue" should "read and write correct JSON" in {
- val recordIssue = MedicalRecordIssue(
- id = LongId(10),
- recordId = LongId(1),
- userId = StringId("userId-001"),
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- isDraft = false,
- text = "message text",
- archiveRequired = false,
- startPage = Some(1.0),
- endPage = Some(2.0)
- )
- val writtenJson = recordIssueWriter.write(recordIssue)
-
- writtenJson should be(
- """{"id":10,"userId":"userId-001","lastUpdate":"2017-08-10T18:00Z","isDraft":false,
- "text":"message text","archiveRequired":false,"startPage":1.0,"endPage":2.0}""".parseJson)
-
- val createRecordIssueJson = """{"text":"message text","startPage":1.0,"endPage":2.0}""".parseJson
- val expectedCreatedRecordIssue = recordIssue.copy(id = LongId(0), lastUpdate = LocalDateTime.MIN, isDraft = true)
- val parsedCreateRecordIssue = jsValueToRecordIssue(createRecordIssueJson, LongId(1), StringId("userId-001"))
- parsedCreateRecordIssue should be(expectedCreatedRecordIssue)
-
- val updateRecordIssueJson =
- """{"text":"new issue text","evidence":"issue evidence","archiveRequired":true,"startPage":1.0,"endPage":4.0}""".parseJson
- val expectedUpdatedRecordIssue = recordIssue.copy(
- text = "new issue text",
- archiveRequired = true,
- endPage = Some(4.0)
- )
- val parsedUpdateRecordIssue = applyUpdateToRecordIssue(updateRecordIssueJson, recordIssue)
- parsedUpdateRecordIssue should be(expectedUpdatedRecordIssue)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala
deleted file mode 100644
index 0f5e4e2..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{FuzzyValue, LongId, StringId}
-import xyz.driver.pdsuidomain.entities.{PatientCriterion, PatientCriterionArm}
-import xyz.driver.pdsuidomain.services.PatientCriterionService.DraftPatientCriterion
-
-class PatientCriterionFormatSuite extends FlatSpec with Matchers {
- import patientcriterion._
-
- "Json format for PatientCriterion" should "read and write correct JSON" in {
- val orig = PatientCriterion(
- id = LongId(1),
- patientLabelId = LongId(1),
- trialId = 0L,
- nctId = StringId("NCT00001"),
- criterionId = LongId(101),
- criterionText = "criterion text",
- criterionValue = Some(true),
- criterionIsDefining = false,
- eligibilityStatus = Some(FuzzyValue.Yes),
- verifiedEligibilityStatus = None,
- isVisible = true,
- isVerified = true,
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val arms = List(
- PatientCriterionArm(patientCriterionId = LongId(1), armId = LongId(31), armName = "arm 31"),
- PatientCriterionArm(patientCriterionId = LongId(1), armId = LongId(32), armName = "arm 32")
- )
- val writtenJson = patientCriterionWriter.write((orig, LongId(21), arms))
-
- writtenJson should be (
- """{"id":1,"labelId":21,"nctId":"NCT00001","criterionId":101,"criterionText":"criterion text","criterionValue":"Yes",
- "criterionIsDefining":false,"criterionIsCompound":false,"eligibilityStatus":"Yes","verifiedEligibilityStatus":null,
- "isVisible":true,"isVerified":true,"lastUpdate":"2017-08-10T18:00Z","arms":["arm 31","arm 32"]}""".parseJson)
-
- val updatePatientCriterionJson = """{"verifiedEligibilityStatus":"No"}""".parseJson
- val expectedUpdatedPatientCriterion = orig.copy(verifiedEligibilityStatus = Some(FuzzyValue.No))
- val parsedUpdatePatientCriterion = applyUpdateToPatientCriterion(updatePatientCriterionJson, orig)
- parsedUpdatePatientCriterion should be(expectedUpdatedPatientCriterion)
-
- val updateBulkPatientCriterionJson = """[{"id":1,"eligibilityStatus":"No"},{"id":2,"isVerified":false}]""".parseJson
- val expectedDraftPatientCriterionList = List(
- DraftPatientCriterion(id = LongId(1), eligibilityStatus = Some(FuzzyValue.No), isVerified = None),
- DraftPatientCriterion(id = LongId(2), eligibilityStatus = None, isVerified = Some(false))
- )
- val parsedDraftPatientCriterionList = draftPatientCriterionListReader.read(updateBulkPatientCriterionJson)
- parsedDraftPatientCriterionList should be(expectedDraftPatientCriterionList)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientEligibleTrialFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientEligibleTrialFormatSuite.scala
deleted file mode 100644
index ad54946..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientEligibleTrialFormatSuite.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{FuzzyValue, LongId, StringId, UuidId}
-import xyz.driver.pdsuidomain.entities.{PatientCriterionArm, PatientTrialArmGroupView, Trial}
-import xyz.driver.pdsuidomain.services.PatientEligibleTrialService.RichPatientEligibleTrial
-
-class PatientEligibleTrialFormatSuite extends FlatSpec with Matchers {
- import patienteligibletrial._
-
- "Json format for PatientEligibleTrial" should "read and write correct JSON" in {
- val trial = Trial(
- id = StringId("NCT000001"),
- externalId = UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"),
- status = Trial.Status.Done,
- assignee = None,
- previousStatus = None,
- previousAssignee = None,
- lastActiveUserId = None,
- lastUpdate = LocalDateTime.parse("2017-08-10T18:16:19"),
- condition = Trial.Condition.Breast,
- phase = "",
- hypothesisId = Some(UuidId("e76e2fc4-a29c-44fb-a81b-8856d06bb1d4")),
- studyDesignId = Some(LongId(321)),
- originalStudyDesign = None,
- isPartner = false,
- overview = None,
- overviewTemplate = "",
- isUpdated = false,
- title = "trial title",
- originalTitle = "orig trial title"
- )
- val group = PatientTrialArmGroupView(
- id = LongId(1),
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- trialId = StringId("NCT000001"),
- hypothesisId = UuidId("e76e2fc4-a29c-44fb-a81b-8856d06bb1d4"),
- eligibilityStatus = Some(FuzzyValue.Yes),
- verifiedEligibilityStatus = Some(FuzzyValue.Yes),
- isVerified = false
- )
- val arms = List(
- PatientCriterionArm(patientCriterionId = LongId(1), armId = LongId(31), armName = "arm 31"),
- PatientCriterionArm(patientCriterionId = LongId(1), armId = LongId(32), armName = "arm 32")
- )
- val orig = RichPatientEligibleTrial(trial, group, arms)
- val writtenJson = patientEligibleTrialWriter.write(orig)
-
- writtenJson should be (
- """{"id":1,"patientId":"748b5884-3528-4cb9-904b-7a8151d6e343","trialId":"NCT000001","trialTitle":"trial title",
- "hypothesisId":"e76e2fc4-a29c-44fb-a81b-8856d06bb1d4","verifiedEligibilityStatus":"Yes","isVerified":false,"arms":["arm 31","arm 32"]}""".parseJson)
-
- val updatePatientEligibleTrialJson = """{"isVerified":true}""".parseJson
- val expectedUpdatedPatientTrialArmGroup = group.copy(isVerified = true)
- val parsedUpdatePatientTrialArmGroup = applyUpdateToTrialArmGroup(updatePatientEligibleTrialJson, group)
- parsedUpdatePatientTrialArmGroup should be(expectedUpdatedPatientTrialArmGroup)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala
deleted file mode 100644
index 2761d6a..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.{LocalDate, LocalDateTime}
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.UuidId
-import xyz.driver.pdsuidomain.entities.{Patient, PatientOrderId}
-
-class PatientFormatSuite extends FlatSpec with Matchers {
- import patient._
-
- "Json format for Patient" should "read and write correct JSON" in {
- val orig = Patient(
- id = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- status = Patient.Status.New,
- name = "John Doe",
- dob = LocalDate.parse("1980-06-30"),
- assignee = None,
- previousStatus = None,
- previousAssignee = None,
- lastActiveUserId = None,
- isUpdateRequired = false,
- condition = "breast",
- orderId = PatientOrderId("7b54a75d-4197-4b27-9045-b9b6cb131be9"),
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val writtenJson = patientWriter.write(orig)
-
- writtenJson should be (
- """{"id":"748b5884-3528-4cb9-904b-7a8151d6e343","dob":"1980-06-30","name":"John Doe","status":"New","assignee":null,
- "previousStatus":null,"previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z",
- "orderId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","condition":"breast"}""".parseJson)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHistoryFormatSuite.scala
deleted file mode 100644
index c6a5a9f..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHistoryFormatSuite.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId}
-import xyz.driver.pdsuidomain.entities.PatientHistory
-
-class PatientHistoryFormatSuite extends FlatSpec with Matchers {
- import patienthistory._
-
- "Json format for PatientHistory" should "read and write correct JSON" in {
- val patientHistory = PatientHistory(
- id = LongId(10),
- patientId = UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"),
- executor = StringId("userId-001"),
- state = PatientHistory.State.Verify,
- action = PatientHistory.Action.Start,
- created = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val writtenJson = patientHistoryFormat.write(patientHistory)
-
- writtenJson should be(
- """{"id":10,"executor":"userId-001","patientId":"40892a07-c638-49d2-9795-1edfefbbcc7c","state":"Verify",
- "action":"Start","created":"2017-08-10T18:00Z"}""".parseJson)
-
- val parsedPatientHistory = patientHistoryFormat.read(writtenJson)
- parsedPatientHistory should be(patientHistory)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala
deleted file mode 100644
index 2999cc1..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.UuidId
-import xyz.driver.pdsuidomain.entities.PatientHypothesis
-
-class PatientHypothesisFormatSuite extends FlatSpec with Matchers {
- import patienthypothesis._
-
- "Json format for PatientHypothesis" should "read and write correct JSON" in {
- val orig = PatientHypothesis(
- id = UuidId("815d9715-1089-4775-b120-3afb983b9a97"),
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- hypothesisId = UuidId("e76e2fc4-a29c-44fb-a81b-8856d06bb1d4"),
- rationale = None,
- matchedTrials = 1
- )
- val writtenJson = patientHypothesisWriter.write((orig, true))
-
- writtenJson should be (
- """{"id":"815d9715-1089-4775-b120-3afb983b9a97","patientId":"748b5884-3528-4cb9-904b-7a8151d6e343",
- "hypothesisId":"e76e2fc4-a29c-44fb-a81b-8856d06bb1d4","rationale":null,"matchedTrials":1,"isRationaleRequired":true}""".parseJson)
-
- val updatePatientHypothesisJson = """{"rationale":"rationale"}""".parseJson
- val expectedUpdatedPatientHypothesis = orig.copy(rationale = Some("rationale"))
- val parsedUpdatePatientHypothesis = applyUpdateToPatientHypothesis(updatePatientHypothesisJson, orig)
- parsedUpdatePatientHypothesis should be(expectedUpdatedPatientHypothesis)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala
deleted file mode 100644
index 1e2a11e..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId}
-import xyz.driver.pdsuidomain.entities.PatientIssue
-
-class PatientIssueFormatSuite extends FlatSpec with Matchers {
- import patientissue._
-
- "Json format for PatientIssue" should "read and write correct JSON" in {
- val patientIssue = PatientIssue(
- id = LongId(10),
- patientId = UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"),
- userId = StringId("userId-001"),
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- isDraft = false,
- text = "message text",
- archiveRequired = false
- )
- val writtenJson = patientIssueWriter.write(patientIssue)
-
- writtenJson should be(
- """{"id":10,"userId":"userId-001","lastUpdate":"2017-08-10T18:00Z","isDraft":false,
- "text":"message text","archiveRequired":false}""".parseJson)
-
- val createPatientIssueJson = """{"text":"message text"}""".parseJson
- val expectedCreatedPatientIssue = patientIssue.copy(id = LongId(0), lastUpdate = LocalDateTime.MIN, isDraft = true)
- val parsedCreatePatientIssue = jsValueToPatientIssue(createPatientIssueJson, UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"), StringId("userId-001"))
- parsedCreatePatientIssue should be(expectedCreatedPatientIssue)
-
- val updatePatientIssueJson =
- """{"text":"new issue text","evidence":"issue evidence","archiveRequired":true}""".parseJson
- val expectedUpdatedPatientIssue = patientIssue.copy(
- text = "new issue text",
- archiveRequired = true
- )
- val parsedUpdatePatientIssue = applyUpdateToPatientIssue(updatePatientIssueJson, patientIssue)
- parsedUpdatePatientIssue should be(expectedUpdatedPatientIssue)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala
deleted file mode 100644
index e18239c..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala
+++ /dev/null
@@ -1,76 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDate
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{FuzzyValue, LongId, UuidId}
-import xyz.driver.pdsuidomain.entities.{PatientLabel, PatientLabelEvidenceView}
-
-class PatientLabelFormatSuite extends FlatSpec with Matchers {
-
- "Json format for PatientLabel" should "read and write correct JSON" in {
- import patientlabel._
- val orig = PatientLabel(
- id = LongId(1),
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- labelId = LongId(20),
- primaryValue = Some(FuzzyValue.Yes),
- verifiedPrimaryValue = None,
- isVisible = true,
- score = 1,
- isImplicitMatch = false
- )
- val writtenJson = patientLabelWriter.write((orig, true))
-
- writtenJson should be (
- """{"id":1,"labelId":20,"primaryValue":"Yes","verifiedPrimaryValue":null,"isVisible":true,"isVerified":true,
- "score":1,"isImplicitMatch":false}""".parseJson)
-
- val updatePatientLabelJson = """{"verifiedPrimaryValue":"No"}""".parseJson
- val expectedUpdatedPatientLabel = orig.copy(verifiedPrimaryValue = Some(FuzzyValue.No))
- val parsedUpdatePatientLabel = applyUpdateToPatientLabel(updatePatientLabelJson, orig)
- parsedUpdatePatientLabel should be(expectedUpdatedPatientLabel)
- }
-
- "Json format for PatientLabelEvidence" should "read and write correct JSON" in {
- import patientlabel._
- val orig = PatientLabelEvidenceView(
- id = LongId(1),
- value = FuzzyValue.Maybe,
- evidenceText = "evidence text",
- documentId = Some(LongId(21)),
- evidenceId = Some(LongId(10)),
- reportId = None,
- documentType = "document type",
- date = Some(LocalDate.parse("2017-08-10")),
- providerType = "provider type",
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- labelId = LongId(20),
- isImplicitMatch = false
- )
- val writtenJson = patientLabelEvidenceWriter.write(orig)
-
- writtenJson should be (
- """{"id":1,"value":"Maybe","evidenceText":"evidence text","documentId":21,"evidenceId":10,"reportId":null,
- "documentType":"document type","date":"2017-08-10","providerType":"provider type"}""".parseJson)
- }
-
- "Json format for PatientLabelDefiningCriteria" should "read and write correct JSON" in {
- import patientdefiningcriteria._
- val orig = PatientLabel(
- id = LongId(1),
- patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"),
- labelId = LongId(20),
- primaryValue = Some(FuzzyValue.Yes),
- verifiedPrimaryValue = Some(FuzzyValue.Yes),
- isVisible = true,
- score = 1,
- isImplicitMatch = false
- )
- val writtenJson = patientLabelDefiningCriteriaWriter.write(orig)
-
- writtenJson should be ("""{"id":1,"value":"Yes"}""".parseJson)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala
deleted file mode 100644
index 9cf9b5f..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.LongId
-import xyz.driver.pdsuidomain.entities.StudyDesign
-
-class StudyDesignFormatSuite extends FlatSpec with Matchers {
- import studydesign._
-
- "Json format for StudyDesign" should "read and write correct JSON" in {
- val studyDesign = StudyDesign(
- id = LongId(10),
- name = "study design name"
- )
- val writtenJson = studyDesignFormat.write(studyDesign)
-
- writtenJson should be("""{"id":10,"name":"study design name"}""".parseJson)
-
- val parsedStudyDesign = studyDesignFormat.read(writtenJson)
- parsedStudyDesign should be(studyDesign)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala
deleted file mode 100644
index 59cf779..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId}
-import xyz.driver.pdsuidomain.entities.Trial
-
-class TrialFormatSuite extends FlatSpec with Matchers {
- import trial._
-
- "Json format for Trial" should "read and write correct JSON" in {
- val orig = Trial(
- id = StringId("NCT000001"),
- externalId = UuidId("40892a07-c638-49d2-9795-1edfefbbcc7c"),
- status = Trial.Status.New,
- assignee = None,
- previousStatus = None,
- previousAssignee = None,
- lastActiveUserId = None,
- lastUpdate = LocalDateTime.parse("2017-08-10T18:16:19"),
- condition = Trial.Condition.Breast,
- phase = "",
- hypothesisId = Some(UuidId("3b80b2e2-5372-4cf5-a342-6e4ebe10fafd")),
- studyDesignId = Some(LongId(321)),
- originalStudyDesign = None,
- isPartner = false,
- overview = None,
- overviewTemplate = "",
- isUpdated = false,
- title = "trial title",
- originalTitle = "orig trial title"
- )
- val writtenJson = trialWriter.write(orig)
-
- writtenJson should be (
- """{"isPartner":false,"assignee":null,"lastUpdate":"2017-08-10T18:16:19Z","previousStatus":null,
- "isUpdated":false,"overviewTemplate":"","phase":"","originalStudyDesignId":null,
- "hypothesisId":"3b80b2e2-5372-4cf5-a342-6e4ebe10fafd","originalTitle":"orig trial title",
- "studyDesignId":321,"lastActiveUser":null,"externalid":"40892a07-c638-49d2-9795-1edfefbbcc7c",
- "id":"NCT000001","condition":"Breast","status":"New","overview":null,"previousAssignee":null,"title":"trial title"}""".parseJson)
-
- val updateTrialJson = """{"hypothesisId":null,"overview":"new overview"}""".parseJson
- val expectedUpdatedTrial = orig.copy(hypothesisId = None, overview = Some("new overview"))
- val parsedUpdateTrial = applyUpdateToTrial(updateTrialJson, orig)
- parsedUpdateTrial should be(expectedUpdatedTrial)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala
deleted file mode 100644
index dbb143c..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.TrialHistory
-
-class TrialHistoryFormatSuite extends FlatSpec with Matchers {
- import trialhistory._
-
- "Json format for TrialHistory" should "read and write correct JSON" in {
- val trialHistory = TrialHistory(
- id = LongId(10),
- trialId = StringId("NCT000001"),
- executor = StringId("userId-001"),
- state = TrialHistory.State.Summarize,
- action = TrialHistory.Action.Start,
- created = LocalDateTime.parse("2017-08-10T18:00:00")
- )
- val writtenJson = trialHistoryFormat.write(trialHistory)
-
- writtenJson should be(
- """{"id":10,"executor":"userId-001","trialId":"NCT000001","state":"Summarize",
- "action":"Start","created":"2017-08-10T18:00Z"}""".parseJson)
-
- val parsedTrialHistory = trialHistoryFormat.read(writtenJson)
- parsedTrialHistory should be(trialHistory)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialIssueFormatSuite.scala
deleted file mode 100644
index 02e14ba..0000000
--- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialIssueFormatSuite.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-package xyz.driver.pdsuidomain.formats.json.sprayformats
-
-import java.time.LocalDateTime
-
-import spray.json._
-import org.scalatest.{FlatSpec, Matchers}
-import xyz.driver.pdsuicommon.domain.{LongId, StringId}
-import xyz.driver.pdsuidomain.entities.TrialIssue
-
-class TrialIssueFormatSuite extends FlatSpec with Matchers {
- import trialissue._
-
- "Json format for TrialIssue" should "read and write correct JSON" in {
- val trialIssue = TrialIssue(
- id = LongId(10),
- trialId = StringId("NCT000001"),
- userId = StringId("userId-001"),
- lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00"),
- isDraft = false,
- text = "message text",
- evidence = "evidence",
- archiveRequired = false,
- meta = "{}"
- )
- val writtenJson = trialIssueWriter.write(trialIssue)
-
- writtenJson should be(
- """{"id":10,"userId":"userId-001","lastUpdate":"2017-08-10T18:00Z","isDraft":false,
- "text":"message text","evidence":"evidence","archiveRequired":false,"meta":"{}"}""".parseJson)
-
- val createTrialIssueJson = """{"text":"message text","evidence":"evidence","meta":"{}"}""".parseJson
- val expectedCreatedTrialIssue = trialIssue.copy(id = LongId(0), lastUpdate = LocalDateTime.MIN, isDraft = true)
- val parsedCreateTrialIssue = jsValueToTrialIssue(createTrialIssueJson, StringId("NCT000001"), StringId("userId-001"))
- parsedCreateTrialIssue should be(expectedCreatedTrialIssue)
-
- val updateTrialIssueJson =
- """{"text":"new issue text","evidence":"issue evidence","archiveRequired":true,
- "meta":"{\"startPage\":1.0,\"endPage\":2.0}"}""".parseJson
- val expectedUpdatedTrialIssue = trialIssue.copy(
- text = "new issue text",
- evidence = "issue evidence",
- archiveRequired = true,
- meta = """{"startPage":1.0,"endPage":2.0}"""
- )
- val parsedUpdateTrialIssue = applyUpdateToTrialIssue(updateTrialIssueJson, trialIssue)
- parsedUpdateTrialIssue should be(expectedUpdatedTrialIssue)
- }
-
-}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/db/SearchFilterExprSuite.scala b/src/test/scala/xyz/driver/restquery/db/SearchFilterExprSuite.scala
index 35c8d30..56ad545 100644
--- a/src/test/scala/xyz/driver/pdsuicommon/db/SearchFilterExprSuite.scala
+++ b/src/test/scala/xyz/driver/restquery/db/SearchFilterExprSuite.scala
@@ -1,6 +1,7 @@
-package xyz.driver.pdsuicommon.db
+package xyz.driver.restquery.db
import org.scalatest.{FreeSpecLike, MustMatchers}
+import xyz.driver.restquery.query.{SearchFilterBinaryOperation, SearchFilterExpr, SearchFilterNAryOperation}
class SearchFilterExprSuite extends FreeSpecLike with MustMatchers {
diff --git a/src/test/scala/xyz/driver/pdsuicommon/parsers/PaginationParserSuite.scala b/src/test/scala/xyz/driver/restquery/rest/parsers/PaginationParserSuite.scala
index 48fc99b..e806f85 100644
--- a/src/test/scala/xyz/driver/pdsuicommon/parsers/PaginationParserSuite.scala
+++ b/src/test/scala/xyz/driver/restquery/rest/parsers/PaginationParserSuite.scala
@@ -1,8 +1,8 @@
-package xyz.driver.pdsuicommon.parsers
+package xyz.driver.restquery.rest.parsers
-import xyz.driver.pdsuicommon.db.Pagination
-import xyz.driver.pdsuicommon.parsers.TestUtils._
+import xyz.driver.restquery.rest.parsers.TestUtils._
import org.scalatest.{FreeSpecLike, MustMatchers}
+import xyz.driver.restquery.query.Pagination
import scala.util.{Failure, Try}
@@ -11,36 +11,40 @@ class PaginationParserSuite extends FreeSpecLike with MustMatchers {
"parse" - {
"pageSize" - {
"should parse positive value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "10",
- "pageNumber" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "10",
+ "pageNumber" -> "1"
+ ))
pagination must success
pagination.get.pageSize mustBe 10
}
"should return a default value if there is no one" in {
- val pagination = PaginationParser.parse(Seq(
- "pageNumber" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageNumber" -> "1"
+ ))
pagination must success
pagination.get.pageSize mustBe 100
}
"should return a error for zero value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "0",
- "pageNumber" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "0",
+ "pageNumber" -> "1"
+ ))
checkFailedValidationOnlyOn(pagination, "pageSize")
}
"should return a error for negative value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "-10",
- "pageNumber" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "-10",
+ "pageNumber" -> "1"
+ ))
checkFailedValidationOnlyOn(pagination, "pageSize")
}
@@ -48,36 +52,40 @@ class PaginationParserSuite extends FreeSpecLike with MustMatchers {
"pageNumber" - {
"should parse positive value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "1",
- "pageNumber" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "1",
+ "pageNumber" -> "1"
+ ))
pagination must success
pagination.get.pageSize mustBe 1
}
"should return a default value if there is no one" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "1"
+ ))
pagination must success
pagination.get.pageNumber mustBe 1
}
"should return a error for zero value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "1",
- "pageNumber" -> "0"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "1",
+ "pageNumber" -> "0"
+ ))
checkFailedValidationOnlyOn(pagination, "pageNumber")
}
"should return a error for negative value" in {
- val pagination = PaginationParser.parse(Seq(
- "pageSize" -> "1",
- "pageNumber" -> "-1"
- ))
+ val pagination = PaginationParser.parse(
+ Seq(
+ "pageSize" -> "1",
+ "pageNumber" -> "-1"
+ ))
checkFailedValidationOnlyOn(pagination, "pageNumber")
}
diff --git a/src/test/scala/xyz/driver/restquery/rest/parsers/SearchFilterParserSuite.scala b/src/test/scala/xyz/driver/restquery/rest/parsers/SearchFilterParserSuite.scala
new file mode 100644
index 0000000..e0a1696
--- /dev/null
+++ b/src/test/scala/xyz/driver/restquery/rest/parsers/SearchFilterParserSuite.scala
@@ -0,0 +1,261 @@
+package xyz.driver.restquery.rest.parsers
+
+import java.util.UUID
+
+import fastparse.core.Parsed
+import org.scalacheck.Arbitrary.arbitrary
+import org.scalacheck.{Gen, Prop}
+import org.scalatest.FreeSpecLike
+import org.scalatest.prop.Checkers
+import xyz.driver.restquery.query.SearchFilterBinaryOperation.Eq
+import xyz.driver.restquery.query.SearchFilterExpr.Dimension
+import xyz.driver.restquery.query.SearchFilterNAryOperation.In
+import xyz.driver.restquery.query.{SearchFilterExpr, SearchFilterNAryOperation}
+import xyz.driver.restquery.rest.parsers.TestUtils._
+import xyz.driver.restquery.utils.Utils
+import xyz.driver.restquery.utils.Utils._
+
+import scala.util._
+
+object SearchFilterParserSuite {
+
+ class UnexpectedSearchFilterExprException(x: SearchFilterExpr) extends Exception(s"unexpected $x")
+
+}
+
+class SearchFilterParserSuite extends FreeSpecLike with Checkers {
+
+ import SearchFilterParserSuite._
+
+ "parse" - {
+ "should convert column names to snake case" in {
+ import xyz.driver.restquery.query.SearchFilterBinaryOperation._
+
+ val filter = SearchFilterParser.parse(
+ Seq(
+ "filters" -> "status IN Summarized,ReviewCriteria,Flagged,Done",
+ "filters" -> "previousStatus NOTEQ New",
+ "filters" -> "previousStatus NOTEQ ReviewSummary"
+ ))
+
+ assert(
+ filter === Success(SearchFilterExpr.Intersection(List(
+ SearchFilterExpr.Atom
+ .NAry(Dimension(None, "status"), In, Seq("Summarized", "ReviewCriteria", "Flagged", "Done")),
+ SearchFilterExpr.Atom.Binary(Dimension(None, "previous_status"), NotEq, "New"),
+ SearchFilterExpr.Atom.Binary(Dimension(None, "previous_status"), NotEq, "ReviewSummary")
+ ))))
+ }
+ "dimensions" - {
+ "with table name" in check {
+ val dimensionGen = {
+ for (left <- Gen.identifier; right <- Gen.identifier)
+ yield left -> right
+ }
+ Prop.forAllNoShrink(dimensionGen) {
+ case (left, right) =>
+ val raw = s"$left.$right"
+ val l = toSnakeCase(left)
+ val r = toSnakeCase(right)
+ SearchFilterParser.dimensionParser.parse(raw) match {
+ case Parsed.Success(Dimension(Some(`l`), `r`), _) => true
+ case _ => false
+ }
+ }
+ }
+ "just with field name" in check {
+ Prop.forAllNoShrink(Gen.identifier) { s =>
+ val databaseS = Utils.toSnakeCase(s)
+ SearchFilterParser.dimensionParser.parse(s) match {
+ case Parsed.Success(Dimension(None, `databaseS`), _) => true
+ case _ => false
+ }
+ }
+ }
+ }
+ "atoms" - {
+ "binary" - {
+ "common operators" - {
+ "should be parsed with text values" in check {
+ import xyz.driver.restquery.query.SearchFilterBinaryOperation._
+
+ val testQueryGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = commonBinaryOpsGen,
+ valueGen = nonEmptyString
+ )
+
+ Prop.forAllNoShrink(testQueryGen) { query =>
+ SearchFilterParser
+ .parse(Seq("filters" -> query))
+ .map {
+ case SearchFilterExpr.Atom.Binary(_, Eq | NotEq | Like, _) => true
+ case x => throw new UnexpectedSearchFilterExprException(x)
+ }
+ .successProp
+ }
+ }
+ }
+
+ "numeric operators" - {
+ "should not be parsed with text values" in check {
+ val testQueryGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = numericBinaryOpsGen,
+ valueGen = nonEmptyString.filter { s =>
+ !s.matches("^\\d+$")
+ }
+ )
+
+ Prop.forAllNoShrink(testQueryGen) { query =>
+ SearchFilterParser.parse(Seq("filters" -> query)).failureProp
+ }
+ }
+ }
+
+ "actual recordId" - {
+ "should not be parsed with numeric values" in {
+ val filter = SearchFilterParser.parse(Seq("filters" -> "recordId EQ 1"))
+ assert(filter === Success(SearchFilterExpr.Atom.Binary(Dimension(None, "record_id"), Eq, Long.box(1))))
+ }
+ }
+
+ "actual isVisible boolean" - {
+ "should not be parsed with boolean values" in {
+ val filter = SearchFilterParser.parse(Seq("filters" -> "isVisible EQ true"))
+ assert(
+ filter === Success(SearchFilterExpr.Atom.Binary(Dimension(None, "is_visible"), Eq, Boolean.box(true))))
+ }
+ }
+
+ "actual patientId uuid" - {
+ "should parse the full UUID as java.util.UUID type" in {
+ val filter = SearchFilterParser.parse(Seq("filters" -> "patientId EQ 4b4879f7-42b3-4b7c-a685-5c97d9e69e7c"))
+ assert(
+ filter === Success(SearchFilterExpr.Atom
+ .Binary(Dimension(None, "patient_id"), Eq, UUID.fromString("4b4879f7-42b3-4b7c-a685-5c97d9e69e7c"))))
+ }
+ }
+
+ "all operators" - {
+ "should be parsed with numeric values" in check {
+ val testQueryGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = allBinaryOpsGen,
+ valueGen = numericBinaryAtomValuesGen
+ )
+
+ Prop.forAllNoShrink(testQueryGen) { query =>
+ SearchFilterParser
+ .parse(Seq("filters" -> query))
+ .map {
+ case _: SearchFilterExpr.Atom.Binary => true
+ case x => throw new UnexpectedSearchFilterExprException(x)
+ }
+ .successProp
+ }
+ }
+ }
+ }
+
+ "n-ary" - {
+ "actual record Ids" - {
+ "should not be parsed with text values" in {
+ val filter = SearchFilterParser.parse(Seq("filters" -> "id IN 1,5"))
+ filter match {
+ case Success(_) => ()
+ case Failure(t) => t.printStackTrace()
+ }
+ assert(
+ filter === Success(SearchFilterExpr.Atom.NAry(Dimension(None, "id"), In, Seq(Long.box(1), Long.box(5)))))
+ }
+ }
+
+ "in" in check {
+ val testQueryGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = Gen.const("in"),
+ valueGen = inValuesGen
+ )
+
+ Prop.forAllNoShrink(testQueryGen) { query =>
+ SearchFilterParser
+ .parse(Seq("filters" -> query))
+ .map {
+ case SearchFilterExpr.Atom.NAry(_, SearchFilterNAryOperation.In, _) => true
+ case x => throw new UnexpectedSearchFilterExprException(x)
+ }
+ .successProp
+ }
+ }
+ }
+ }
+
+ "intersections" - {
+ "should be parsed" in check {
+ val commonAtomsGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = commonBinaryOpsGen,
+ valueGen = nonEmptyString
+ )
+
+ val numericAtomsGen = queryGen(
+ dimensionGen = Gen.identifier,
+ opGen = numericBinaryOpsGen,
+ valueGen = numericBinaryAtomValuesGen
+ )
+
+ val allAtomsGen = Gen.oneOf(commonAtomsGen, numericAtomsGen)
+ val intersectionsGen = Gen.choose(1, 3).flatMap { size =>
+ Gen.containerOfN[Seq, String](size, allAtomsGen)
+ }
+
+ Prop.forAllNoShrink(intersectionsGen) { queries =>
+ SearchFilterParser.parse(queries.map(query => "filters" -> query)).successProp
+ }
+ }
+ }
+ }
+
+ private val CommonBinaryOps = Seq("eq", "noteq", "like")
+ private val NumericBinaryOps = Seq("gt", "gteq", "lt", "lteq")
+
+ private val allBinaryOpsGen: Gen[String] =
+ Gen.oneOf(CommonBinaryOps ++ NumericBinaryOps).flatMap(randomCapitalization)
+ private val commonBinaryOpsGen: Gen[String] = Gen.oneOf(CommonBinaryOps).flatMap(randomCapitalization)
+ private val numericBinaryOpsGen: Gen[String] = Gen.oneOf(NumericBinaryOps).flatMap(randomCapitalization)
+
+ private val inValueCharsGen: Gen[Char] = arbitrary[Char].filter(_ != ',')
+
+ private val nonEmptyString = arbitrary[String].filter { s =>
+ !Utils.safeTrim(s).isEmpty
+ }
+
+ private val numericBinaryAtomValuesGen: Gen[String] = arbitrary[Long].map(_.toString)
+ private val inValueGen: Gen[String] = {
+ Gen.nonEmptyContainerOf[Seq, Char](inValueCharsGen).map(_.mkString).filter(s => Utils.safeTrim(s).nonEmpty)
+ }
+ private val inValuesGen: Gen[String] = Gen.choose(1, 5).flatMap { size =>
+ Gen.containerOfN[Seq, String](size, inValueGen).map(_.mkString(","))
+ }
+
+ private def queryGen(dimensionGen: Gen[String], opGen: Gen[String], valueGen: Gen[String]): Gen[String] =
+ for {
+ dimension <- dimensionGen
+ op <- opGen
+ value <- valueGen
+ } yield s"$dimension $op $value"
+
+ private def randomCapitalization(input: String): Gen[String] = {
+ Gen.containerOfN[Seq, Boolean](input.length, arbitrary[Boolean]).map { capitalize =>
+ input.view
+ .zip(capitalize)
+ .map {
+ case (currChar, true) => currChar.toUpper
+ case (currChar, false) => currChar
+ }
+ .mkString
+ }
+ }
+
+}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/parsers/SortingParserSuite.scala b/src/test/scala/xyz/driver/restquery/rest/parsers/SortingParserSuite.scala
index e46015c..a18ac1e 100644
--- a/src/test/scala/xyz/driver/pdsuicommon/parsers/SortingParserSuite.scala
+++ b/src/test/scala/xyz/driver/restquery/rest/parsers/SortingParserSuite.scala
@@ -1,6 +1,6 @@
-package xyz.driver.pdsuicommon.parsers
+package xyz.driver.restquery.rest.parsers
-import xyz.driver.pdsuicommon.parsers.TestUtils._
+import xyz.driver.restquery.rest.parsers.TestUtils._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Gen, Prop}
import org.scalatest.prop.Checkers
@@ -12,7 +12,7 @@ class SortingParserSuite extends FreeSpecLike with MustMatchers with Checkers {
"single dimension" - commonTests(singleSortingQueryGen)
"multiple dimensions in one query" - commonTests(multipleSortingQueryGen)
"multiple queries" in {
- val r = SortingParser.parse(Set("foo", "bar"), Seq("sort" -> "foo", "sort" ->"bar"))
+ val r = SortingParser.parse(Set("foo", "bar"), Seq("sort" -> "foo", "sort" -> "bar"))
r must failWith[ParseQueryArgException]
}
}
@@ -21,7 +21,7 @@ class SortingParserSuite extends FreeSpecLike with MustMatchers with Checkers {
"valid" in check {
val inputGen: Gen[(Set[String], String)] = for {
validDimensions <- dimensionsGen
- sorting <- queryGen(validDimensions)
+ sorting <- queryGen(validDimensions)
} yield (validDimensions, sorting)
Prop.forAllNoShrink(inputGen) {
@@ -33,7 +33,9 @@ class SortingParserSuite extends FreeSpecLike with MustMatchers with Checkers {
"invalid" in check {
val inputGen: Gen[(Set[String], String)] = for {
validDimensions <- dimensionsGen
- invalidDimensions <- dimensionsGen.filter { xs => xs.intersect(validDimensions).isEmpty }
+ invalidDimensions <- dimensionsGen.filter { xs =>
+ xs.intersect(validDimensions).isEmpty
+ }
sorting <- queryGen(invalidDimensions)
} yield (validDimensions, sorting)
@@ -46,12 +48,12 @@ class SortingParserSuite extends FreeSpecLike with MustMatchers with Checkers {
private val dimensionsGen: Gen[Set[String]] = for {
unPrefixedSize <- Gen.choose(0, 3)
- prefixedSize <- Gen.choose(0, 3)
+ prefixedSize <- Gen.choose(0, 3)
if (unPrefixedSize + prefixedSize) > 0
unPrefixedDimensions <- Gen.containerOfN[Set, String](unPrefixedSize, Gen.identifier)
- prefixes <- Gen.containerOfN[Set, String](prefixedSize, Gen.identifier)
+ prefixes <- Gen.containerOfN[Set, String](prefixedSize, Gen.identifier)
dimensions <- Gen.containerOfN[Set, String](prefixedSize, Gen.identifier)
} yield {
val prefixedDimensions = prefixes.zip(dimensions).map {
@@ -62,30 +64,33 @@ class SortingParserSuite extends FreeSpecLike with MustMatchers with Checkers {
private def multipleSortingQueryGen(validDimensions: Set[String]): Gen[String] = {
val validDimensionsSeq = validDimensions.toSeq
- val indexGen = Gen.oneOf(validDimensionsSeq.indices)
+ val indexGen = Gen.oneOf(validDimensionsSeq.indices)
val multipleDimensionsGen = Gen.nonEmptyContainerOf[Set, Int](indexGen).filter(_.size >= 2).map { indices =>
indices.map(validDimensionsSeq.apply)
}
for {
- dimensions <- multipleDimensionsGen
+ dimensions <- multipleDimensionsGen
isAscending <- Gen.containerOfN[Seq, Boolean](dimensions.size, arbitrary[Boolean])
} yield {
- isAscending.zip(dimensions)
+ isAscending
+ .zip(dimensions)
.map {
- case (true, dimension) => dimension
+ case (true, dimension) => dimension
case (false, dimension) => "-" + dimension
}
.mkString(",")
}
}
- private def singleSortingQueryGen(validDimensions: Set[String]): Gen[String] = for {
- isAscending <- arbitrary[Boolean]
- dimensions <- Gen.oneOf(validDimensions.toSeq)
- } yield isAscending match {
- case true => dimensions
- case false => "-" + dimensions
- }
+ private def singleSortingQueryGen(validDimensions: Set[String]): Gen[String] =
+ for {
+ isAscending <- arbitrary[Boolean]
+ dimensions <- Gen.oneOf(validDimensions.toSeq)
+ } yield
+ isAscending match {
+ case true => dimensions
+ case false => "-" + dimensions
+ }
}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/parsers/TestUtils.scala b/src/test/scala/xyz/driver/restquery/rest/parsers/TestUtils.scala
index 4892b95..22ce5a0 100644
--- a/src/test/scala/xyz/driver/pdsuicommon/parsers/TestUtils.scala
+++ b/src/test/scala/xyz/driver/restquery/rest/parsers/TestUtils.scala
@@ -1,9 +1,9 @@
-package xyz.driver.pdsuicommon.parsers
+package xyz.driver.restquery.rest.parsers
import org.scalacheck.Prop
import org.scalacheck.Prop.BooleanOperators
import org.scalatest.matchers.{MatchResult, Matcher}
-import xyz.driver.pdsuicommon.utils.Utils
+import xyz.driver.restquery.utils.Utils
import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}
@@ -21,9 +21,10 @@ object TestUtils {
MatchResult(
left.isFailure && left.failed.get.getClass == ct.runtimeClass,
left match {
- case Success(x) => s"$left did not fail"
- case Failure(e) => s"$left did fail with ${Utils.getClassSimpleName(e.getClass)}, " +
- s"not ${Utils.getClassSimpleName(ct.runtimeClass)}"
+ case Success(_) => s"$left did not fail"
+ case Failure(e) =>
+ s"$left did fail with ${Utils.getClassSimpleName(e.getClass)}, " +
+ s"not ${Utils.getClassSimpleName(ct.runtimeClass)}"
},
left match {
case Success(_) => s"$left failed with ${Utils.getClassSimpleName(ct.runtimeClass)}"
@@ -33,7 +34,7 @@ object TestUtils {
}
}
- def failWith[ThrowableT <:Throwable](implicit ct: ClassTag[ThrowableT]) = new FailWith[ThrowableT]
+ def failWith[ThrowableT <: Throwable](implicit ct: ClassTag[ThrowableT]) = new FailWith[ThrowableT]
final implicit class TryPropOps(val self: Try[Any]) extends AnyVal {
@@ -44,7 +45,7 @@ object TestUtils {
def failureProp: Prop = self match {
case Success(x) => false :| s"invalid: $x"
- case Failure(e) => true
+ case Failure(_) => true
}
}
diff --git a/src/test/scala/xyz/driver/pdsuicommon/utils/StringOpsSuite.scala b/src/test/scala/xyz/driver/restquery/utils/StringOpsSuite.scala
index 9bd4382..97a432f 100644
--- a/src/test/scala/xyz/driver/pdsuicommon/utils/StringOpsSuite.scala
+++ b/src/test/scala/xyz/driver/restquery/utils/StringOpsSuite.scala
@@ -1,33 +1,32 @@
-package xyz.driver.pdsuicommon.utils
+package xyz.driver.restquery.utils
-import xyz.driver.pdsuicommon.utils.Implicits.toStringOps
import org.scalatest.FreeSpecLike
class StringOpsSuite extends FreeSpecLike {
"safeTrim" - {
"empty string" in {
- assert("".safeTrim == "")
+ assert(Utils.safeTrim("") == "")
}
"string with whitespace symbols" in {
- assert("\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000".safeTrim == "")
+ assert(Utils.safeTrim("\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000") == "")
}
"string with control symbols" in {
- assert("\u001f\u007f\t\n".safeTrim == "")
+ assert(Utils.safeTrim("\u001f\u007f\t\n") == "")
}
"whitespaces and control symbols from the left side" in {
- assert("\u001f\u2002\u007f\nfoo".safeTrim == "foo")
+ assert(Utils.safeTrim("\u001f\u2002\u007f\nfoo") == "foo")
}
"whitespaces and control symbols from the right side" in {
- assert("foo\u001f\u2002\u007f\n".safeTrim == "foo")
+ assert(Utils.safeTrim("foo\u001f\u2002\u007f\n") == "foo")
}
"already trimmed string" in {
- assert("foo".safeTrim == "foo")
+ assert(Utils.safeTrim("foo") == "foo")
}
}
-} \ No newline at end of file
+}