From 54b15dae509212f6661dc1f1bc4ca248cb487443 Mon Sep 17 00:00:00 2001 From: Kseniya Tomskikh Date: Fri, 20 Oct 2017 16:25:04 +0700 Subject: PDSUI-2336 Deleted api classes of play format, userhistory and message services --- .../pdsuidomain/formats/json/ArmFormatSuite.scala | 37 ++++++ .../json/BridgeUploadQueueFormatSuite.scala | 32 ++++++ .../formats/json/CriterionFormatSuite.scala | 75 +++++++++++++ .../formats/json/DocumentFormatSuite.scala | 73 ++++++++++++ .../formats/json/DocumentHistoryFormatSuite.scala | 31 ++++++ .../formats/json/DocumentIssueFormatSuite.scala | 48 ++++++++ .../EligibilityArmWithDiseasesFormatSuite.scala | 55 +++++++++ .../formats/json/ExportFormatSuite.scala | 124 +++++++++++++++++++++ .../formats/json/ExtractedDataFormatSuite.scala | 97 ++++++++++++++++ .../formats/json/HypothesisFormatSuite.scala | 27 +++++ .../formats/json/InterventionFormatSuite.scala | 73 ++++++++++++ .../formats/json/ListResponseFormatSuite.scala | 101 +++++++++++++++++ .../formats/json/MedicalRecordFormatSuite.scala | 77 +++++++++++++ .../json/MedicalRecordHistoryFormatSuite.scala | 31 ++++++ .../json/MedicalRecordIssueFormatSuite.scala | 47 ++++++++ .../formats/json/PatientCriterionFormatSuite.scala | 58 ++++++++++ .../json/PatientEligibleTrialFormatSuite.scala | 62 +++++++++++ .../formats/json/PatientFormatSuite.scala | 39 +++++++ .../formats/json/PatientHistoryFormatSuite.scala | 32 ++++++ .../json/PatientHypothesisFormatSuite.scala | 47 ++++++++ .../formats/json/PatientIssueFormatSuite.scala | 45 ++++++++ .../formats/json/PatientLabelFormatSuite.scala | 79 +++++++++++++ .../formats/json/SlotArmFormatSuite.scala | 36 ++++++ .../formats/json/StudyDesignFormatSuite.scala | 20 ++++ .../formats/json/TrialFormatSuite.scala | 49 ++++++++ .../formats/json/TrialHistoryFormatSuite.scala | 31 ++++++ .../formats/json/TrialIssueFormatSuite.scala | 49 ++++++++ .../formats/json/sprayformats/ArmFormatSuite.scala | 37 ------ .../sprayformats/BridgeUploadQueueFormat.scala | 32 ------ .../json/sprayformats/CriterionFormatSuite.scala | 75 ------------- .../json/sprayformats/DocumentFormatSuite.scala | 73 ------------ .../sprayformats/DocumentHistoryFormatSuite.scala | 31 ------ .../sprayformats/DocumentIssueFormatSuite.scala | 48 -------- .../EligibilityArmWithDiseasesFormatSuite.scala | 55 --------- .../json/sprayformats/ExportFormatSuite.scala | 124 --------------------- .../sprayformats/ExtractedDataFormatSuite.scala | 97 ---------------- .../json/sprayformats/HypothesisFormatSuite.scala | 27 ----- .../sprayformats/InterventionFormatSuite.scala | 73 ------------ .../sprayformats/ListResponseFormatSuite.scala | 101 ----------------- .../sprayformats/MedicalRecordFormatSuite.scala | 77 ------------- .../MedicalRecordHistoryFormatSuite.scala | 31 ------ .../MedicalRecordIssueFormatSuite.scala | 47 -------- .../sprayformats/PatientCriterionFormatSuite.scala | 58 ---------- .../PatientEligibleTrialFormatSuite.scala | 62 ----------- .../json/sprayformats/PatientFormatSuite.scala | 39 ------- .../sprayformats/PatientHistoryFormatSuite.scala | 32 ------ .../PatientHypothesisFormatSuite.scala | 47 -------- .../sprayformats/PatientIssueFormatSuite.scala | 45 -------- .../sprayformats/PatientLabelFormatSuite.scala | 79 ------------- .../json/sprayformats/SlotArmFormatSuite.scala | 36 ------ .../json/sprayformats/StudyDesignFormatSuite.scala | 20 ---- .../json/sprayformats/TrialFormatSuite.scala | 49 -------- .../sprayformats/TrialHistoryFormatSuite.scala | 31 ------ .../json/sprayformats/TrialIssueFormatSuite.scala | 49 -------- 54 files changed, 1475 insertions(+), 1475 deletions(-) create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/ArmFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/BridgeUploadQueueFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/CriterionFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentHistoryFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentIssueFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/EligibilityArmWithDiseasesFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/ExportFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/ExtractedDataFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/HypothesisFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/InterventionFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/ListResponseFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordHistoryFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordIssueFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientCriterionFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientEligibleTrialFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHistoryFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHypothesisFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientIssueFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientLabelFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/SlotArmFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/StudyDesignFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialHistoryFormatSuite.scala create mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialIssueFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/BridgeUploadQueueFormat.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/EligibilityArmWithDiseasesFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExportFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponseFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordIssueFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientEligibleTrialFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHistoryFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/SlotArmFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialIssueFormatSuite.scala (limited to 'src/test') diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/ArmFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ArmFormatSuite.scala new file mode 100644 index 0000000..3cab4a1 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ArmFormatSuite.scala @@ -0,0 +1,37 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/BridgeUploadQueueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/BridgeUploadQueueFormatSuite.scala new file mode 100644 index 0000000..9aaecae --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/BridgeUploadQueueFormatSuite.scala @@ -0,0 +1,32 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDateTime + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueue + +class BridgeUploadQueueFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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/CriterionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/CriterionFormatSuite.scala new file mode 100644 index 0000000..a227afa --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/CriterionFormatSuite.scala @@ -0,0 +1,75 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuicommon.domain.{LongId, StringId} +import xyz.driver.pdsuidomain.entities.{EligibilityArm, Criterion, CriterionLabel} +import xyz.driver.pdsuidomain.services.CriterionService.RichCriterion + +class CriterionFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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 = "{}", + inclusion = None + ) + 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[EligibilityArm](20), LongId[EligibilityArm](21), LongId[EligibilityArm](21)) + val richCriterion = RichCriterion( + criterion = criterion, + armIds = arms, + labels = labels + ) + val writtenJson = richCriterionFormat.write(richCriterion) + + writtenJson should be( + """{"text":"text","isCompound":false,"trialId":"NCT000001","inclusion":null,"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","inclusion":null, + "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,"inclusion":true}""".parseJson + val expectedUpdatedCriterion = richCriterion.copy( + criterion = criterion.copy( + text = Some("new text"), + isCompound = true, + meta = "{}", + inclusion = Some(true) + )) + val parsedUpdateCriterion = applyUpdateToCriterion(updateCriterionJson, richCriterion) + parsedUpdateCriterion should be(expectedUpdatedCriterion) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentFormatSuite.scala new file mode 100644 index 0000000..5e33805 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentFormatSuite.scala @@ -0,0 +1,73 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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)), + institutionName = Some("institution name"), + requiredType = Some(Document.RequiredType.OPN), + meta = None, + startDate = None, + endDate = None, + labelVersion = 0 + ) + val writtenJson = documentFormat.write(orig) + + writtenJson should be( + """{"id":1,"recordId":101,"physician":"physician","typeId":10,"provider":"provider 21","providerTypeId":21, + "requiredType":"OPN","institutionName":"institution name","startDate":null,"endDate":null,"status":"New","assignee":null,"previousStatus":null, + "previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z","meta":null,"labelVersion":0}""".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, + institutionName = None + ) + val parsedCreatedDocument = documentFormat.read(createDocumentJson) + parsedCreatedDocument should be(expectedCreatedDocument) + + val updateDocumentJson = + """{"startDate":"2017-08-10","endDate":"2018-08-10","meta":{"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(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(startPage = 1.0, endPage = 2.0) + val writtenJson = documentMetaFormat.write(meta) + writtenJson should be("""{"startPage":1.0,"endPage":2.0}""".parseJson) + + val metaJson = """{"startPage":1.0,"endPage":2.0}""".parseJson + val parsedMeta = documentMetaFormat.read(metaJson) + parsedMeta should be(meta) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentHistoryFormatSuite.scala new file mode 100644 index 0000000..e4a0733 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentHistoryFormatSuite.scala @@ -0,0 +1,31 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/DocumentIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentIssueFormatSuite.scala new file mode 100644 index 0000000..7f34725 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/DocumentIssueFormatSuite.scala @@ -0,0 +1,48 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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 = documentIssueFormat.write(documentIssue) + + writtenJson should be( + """{"id":10,"userId":"userId-001","documentId":1,"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/EligibilityArmWithDiseasesFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/EligibilityArmWithDiseasesFormatSuite.scala new file mode 100644 index 0000000..054f2f6 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/EligibilityArmWithDiseasesFormatSuite.scala @@ -0,0 +1,55 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.entities.patient.CancerType +import xyz.driver.pdsuicommon.domain.{LongId, StringId} +import xyz.driver.pdsuidomain.entities.{EligibilityArm, EligibilityArmDisease, EligibilityArmWithDiseases} + +class EligibilityArmWithDiseasesFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.eligibilityarm._ + + "Json format for EligibilityArmWithDiseases" should "read and write correct JSON" in { + val name = "arm name" + + val arm = EligibilityArm( + id = LongId(0), + trialId = StringId("NCT000001"), + name = name, + originalName = name + ) + + val disease = EligibilityArmDisease( + arm.id, + disease = CancerType.Lung + ) + + val eligibilityArmWithDiseases = + EligibilityArmWithDiseases( + arm, + Seq(disease) + ) + + val writtenJson = eligibilityArmWithDiseasesWriter.write(eligibilityArmWithDiseases) + + writtenJson should be( + """{"id":0,"trialId":"NCT000001","name":"arm name","originalName":"arm name","diseases":["Lung"]}""".parseJson) + + val createArmWithDiseasesJson = """{"trialId":"NCT000001","name":"arm name","diseases":["Lung"]}""".parseJson + val parsedArmWithDiseases = eligibilityArmWithDiseasesReader.read(createArmWithDiseasesJson) + parsedArmWithDiseases should be(eligibilityArmWithDiseases) + + val updateArmWithDiseasesJson = """{"name":"new arm name"}""".parseJson + val expectedUpdatedArmWithDiseases = eligibilityArmWithDiseases.copy( + eligibilityArm = eligibilityArmWithDiseases.eligibilityArm.copy(name = "new arm name") + ) + + val parsedUpdateArmWithDiseases = + applyUpdateToEligibilityArmWithDiseases( + updateArmWithDiseasesJson, + eligibilityArmWithDiseases + ) + + parsedUpdateArmWithDiseases should be(expectedUpdatedArmWithDiseases) + } +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/ExportFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ExportFormatSuite.scala new file mode 100644 index 0000000..1f024c3 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ExportFormatSuite.scala @@ -0,0 +1,124 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.{LocalDate, LocalDateTime} +import java.util.UUID + +import org.scalatest.{FlatSpec, Matchers} +import spray.json._ +import xyz.driver.entities.labels.LabelValue +import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId} +import xyz.driver.pdsuidomain.entities.{DocumentType, ProviderType, RecordRequestId} + +class ExportFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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 = DocumentType.OutpatientPhysicianNote, + providerType = ProviderType.Surgery, + date = LocalDate.parse("2017-08-10") + ) + + val labels = List( + ExportPatientLabel( + id = LongId(1), + evidences = List( + ExportPatientLabelEvidence( + id = LongId(11), + value = LabelValue.Yes, + evidenceText = "evidence text 11", + document = document + ), + ExportPatientLabelEvidence( + id = LongId(12), + value = LabelValue.No, + evidenceText = "evidence text 12", + document = document + ) + ) + ), + ExportPatientLabel( + id = LongId(2), + evidences = List( + ExportPatientLabelEvidence( + id = LongId(12), + value = LabelValue.Yes, + evidenceText = "evidence text 12", + document = document + ), + ExportPatientLabelEvidence( + id = LongId(13), + value = LabelValue.Yes, + evidenceText = "evidence text 13", + document = document + ) + ) + ) + ) + val patientWithLabels = ExportPatientWithLabels( + patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), + labelVersion = 1L, + labels = labels + ) + + val writtenJson = patientWithLabelsFormat.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":{"id":1,"name":"Outpatient Physician Note"},"providerType":{"id":2,"name":"Surgery"},"date":"2017-08-10"}}, + {"evidenceId":12,"labelValue":"No","evidenceText":"evidence text 12","document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9", + "documentType":{"id":1,"name":"Outpatient Physician Note"},"providerType":{"id":2,"name":"Surgery"},"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":{"id":1,"name":"Outpatient Physician Note"}, + "providerType":{"id":2,"name":"Surgery"},"date":"2017-08-10"}},{"evidenceId":13,"labelValue":"Yes","evidenceText":"evidence text 13", + "document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","documentType":{"id":1,"name":"Outpatient Physician Note"}, + "providerType":{"id":2,"name":"Surgery"},"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", diseaseList = Seq("Breast")), + ExportTrialArm(armId = LongId(2), armName = "arm 2", diseaseList = Seq("Breast")) + ) + 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"), + lastReviewed = LocalDateTime.parse("2017-08-10T18:00:00"), + labelVersion = 1L, + arms = arms, + criteria = criteriaList + ) + + val writtenJson = trialWithLabelsFormat.write(trialWithLabels) + writtenJson should be( + """{"nctId":"NCT000001","trialId":"40892a07-c638-49d2-9795-1edfefbbcc7c","lastReviewed":"2017-08-10T18:00Z", + "labelVersion":1,"arms":[{"armId":1,"armName":"arm 1","diseaseList":["Breast"]},{"armId":2,"armName":"arm 2","diseaseList":["Breast"]}],"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/ExtractedDataFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ExtractedDataFormatSuite.scala new file mode 100644 index 0000000..bc20280 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ExtractedDataFormatSuite.scala @@ -0,0 +1,97 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.entities.labels.LabelValue +import xyz.driver.pdsuicommon.domain.{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 xyz.driver.pdsuidomain.formats.json.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(LabelValue.Yes) + ), + ExtractedDataLabel( + id = LongId(2), + dataId = extractedData.id, + labelId = Some(LongId(12)), + categoryId = Some(LongId(1)), + value = Some(LabelValue.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(LabelValue.Yes) + ), + ExtractedDataLabel( + id = LongId(0), + dataId = extractedData.id, + labelId = Some(LongId(12)), + categoryId = Some(LongId(1)), + value = Some(LabelValue.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/HypothesisFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/HypothesisFormatSuite.scala new file mode 100644 index 0000000..6d51873 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/HypothesisFormatSuite.scala @@ -0,0 +1,27 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/InterventionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/InterventionFormatSuite.scala new file mode 100644 index 0000000..ac01c34 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/InterventionFormatSuite.scala @@ -0,0 +1,73 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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"), + dosage = "", + originalDosage = "", + isActive = true, + deliveryMethod = Some("pill") + ) + 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 = interventionFormat.write(orig) + + writtenJson should be( + """{"id":1,"name":"intervention name","typeId":10,"dosage":"","isActive":true,"arms":[20,21,22], + "trialId":"NCT000001","deliveryMethod":"pill","originalName":"orig name","originalDosage":"","originalType":"orig type"}""".parseJson) + + val createInterventionJson = + """{"id":1,"name":"intervention name","typeId":10,"dosage":"","isActive":true,"arms":[20,21,22], + "trialId":"NCT000001","deliveryMethod":"pill"}""".parseJson + val parsedCreateIntervention = interventionFormat.read(createInterventionJson) + val expectedCreateIntervention = parsedCreateIntervention.copy( + intervention = intervention.copy(id = LongId(0), originalType = None, originalName = "intervention name"), + arms = arms.map(_.copy(interventionId = LongId(0))) + ) + parsedCreateIntervention should be(expectedCreateIntervention) + + val updateInterventionJson = """{"dosage":"descr","arms":[21,22]}""".parseJson + val expectedUpdatedIntervention = orig.copy( + intervention = intervention.copy(dosage = "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.SurgeryProcedure + val writtenJson = interventionTypeFormat.write(interventionType) + + writtenJson should be( + """{"id":9,"name":"Surgery/Procedure","deliveryMethods":["Radio-Frequency Ablation (RFA)", + "Cryoablation","Therapeutic Conventional Surgery","Robotic Assisted Laparoscopic Surgery"]}""".parseJson) + + val parsedInterventionType = interventionTypeFormat.read(writtenJson) + parsedInterventionType should be(interventionType) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/ListResponseFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ListResponseFormatSuite.scala new file mode 100644 index 0000000..c561412 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/ListResponseFormatSuite.scala @@ -0,0 +1,101 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDateTime +import java.util.UUID + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuicommon.domain.{LongId, UuidId} +import xyz.driver.pdsuidomain.ListResponse +import xyz.driver.pdsuidomain.entities.MedicalRecord.Status +import xyz.driver.pdsuidomain.entities._ +import xyz.driver.pdsuidomain.formats.json.record.recordFormat +import xyz.driver.pdsuidomain.formats.json.listresponse._ + + +class ListResponseFormatSuite extends FlatSpec with Matchers { + + private val lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00") + private val lastUpdateToLocal = "2017-08-10T18:00Z" + + def metaJsonObjectAsString(meta: ListResponse.Meta) = { + import meta._ + val lastUpdate = meta.lastUpdate + .map(_ => s""","lastUpdate":"$lastUpdateToLocal"""") + .getOrElse("") + + s"""{"itemsCount":$itemsCount,"pageNumber":$pageNumber,"pageSize":$pageSize$lastUpdate}""" + } + + "Json format for ListResponse.Meta" should "read and write correct JSON" in { + val meta1 = + ListResponse.Meta( + itemsCount = 5, + pageNumber = 6, + pageSize = 7, + lastUpdate = None + ) + + val writtenJson1 = listResponseMetaFormat.write(meta1) + + writtenJson1 should be(metaJsonObjectAsString(meta1).parseJson) + + val parsedItem1: ListResponse.Meta = listResponseMetaFormat.read(writtenJson1) + + meta1 shouldBe parsedItem1 + + val meta2 = + ListResponse.Meta( + itemsCount = 1, + pageNumber = 4, + pageSize = 3, + lastUpdate = Some(lastUpdate) + ) + + val writtenJson2 = listResponseMetaFormat.write(meta2) + + writtenJson2 should be(metaJsonObjectAsString(meta2).parseJson) + + val parsedItem2: ListResponse.Meta = listResponseMetaFormat.read(writtenJson2) + + meta2 shouldBe parsedItem2 + } + + "Json format for ListResponse" should "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, + disease = "Breast", + requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")), + caseId = None, + patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), + totalPages = 10 + ) + + val recordJsonAsString = recordFormat.write(orig) + + val meta = + ListResponse.Meta( + itemsCount = 5, + pageNumber = 6, + pageSize = 7, + lastUpdate = None + ) + + val listResponse = ListResponse(Seq(orig), meta) + + val writtenJson = listResponseWriter[MedicalRecord].write(listResponse) + val expectedJson = s"""{"items":[$recordJsonAsString],"meta":${listResponseMetaFormat.write(meta)}}""" + + writtenJson should be(expectedJson.parseJson) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordFormatSuite.scala new file mode 100644 index 0000000..e811a29 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordFormatSuite.scala @@ -0,0 +1,77 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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, + disease = "Breast", + requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")), + caseId = None, + patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), + totalPages = 10 + ) + 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","totalPages":10}""".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, + lastUpdate = LocalDateTime.now(), + totalPages = 0 + ) + val parsedCreatedRecord = recordFormat.read(createRecordJson).copy(lastUpdate = expectedCreatedRecord.lastUpdate) + parsedCreatedRecord should be(expectedCreatedRecord) + + val updateRecordJson = + """{"meta":[{"type":"duplicate","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(startPage = 1.0, endPage = 2.0, startOriginalPage = 1.0, endOriginalPage = None), + Meta.Reorder(Seq(1, 2)), + Meta.Rotation(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/MedicalRecordHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordHistoryFormatSuite.scala new file mode 100644 index 0000000..ca4058e --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordHistoryFormatSuite.scala @@ -0,0 +1,31 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/MedicalRecordIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordIssueFormatSuite.scala new file mode 100644 index 0000000..c7c82a4 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/MedicalRecordIssueFormatSuite.scala @@ -0,0 +1,47 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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 = recordIssueFormat.write(recordIssue) + + writtenJson should be( + """{"id":10,"recordId":1,"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/PatientCriterionFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientCriterionFormatSuite.scala new file mode 100644 index 0000000..2e193c7 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientCriterionFormatSuite.scala @@ -0,0 +1,58 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDateTime + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.entities.labels.LabelValue +import xyz.driver.pdsuicommon.domain.{LongId, StringId} +import xyz.driver.pdsuidomain.entities.{PatientCriterion, PatientCriterionArm} +import xyz.driver.pdsuidomain.services.PatientCriterionService.{DraftPatientCriterion, RichPatientCriterion} + +class PatientCriterionFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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(LabelValue.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 richPatientCriterion = RichPatientCriterion(orig, LongId(21), arms) + val writtenJson = patientCriterionWriter.write(richPatientCriterion) + + 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(LabelValue.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(LabelValue.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/PatientEligibleTrialFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientEligibleTrialFormatSuite.scala new file mode 100644 index 0000000..b5fbf3f --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientEligibleTrialFormatSuite.scala @@ -0,0 +1,62 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDateTime + +import org.scalatest.{FlatSpec, Matchers} +import spray.json._ +import xyz.driver.entities.labels.LabelValue +import xyz.driver.pdsuicommon.domain.{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 xyz.driver.pdsuidomain.formats.json.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"), + 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(LabelValue.Yes), + verifiedEligibilityStatus = Some(LabelValue.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/PatientFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientFormatSuite.scala new file mode 100644 index 0000000..c296f84 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientFormatSuite.scala @@ -0,0 +1,39 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.{LocalDate, LocalDateTime} + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.entities.common.FullName +import xyz.driver.entities.patient.CancerType +import xyz.driver.pdsuicommon.domain.UuidId +import xyz.driver.pdsuidomain.entities.{Patient, PatientOrderId} + +class PatientFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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 = FullName.fromStrings("John", "", "Doe"), + dob = LocalDate.parse("1980-06-30"), + assignee = None, + previousStatus = None, + previousAssignee = None, + lastActiveUserId = None, + isUpdateRequired = false, + disease = CancerType.Breast, + orderId = PatientOrderId("7b54a75d-4197-4b27-9045-b9b6cb131be9"), + lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00") + ) + val writtenJson = patientFormat.write(orig) + + writtenJson should be( + """{"id":"748b5884-3528-4cb9-904b-7a8151d6e343","dob":"1980-06-30", + "name":{"firstName":"John","middleName":"","lastName":"Doe"},"status":"New","assignee":null, + "previousStatus":null,"previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z", + "orderId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","disease":"Breast"}""".parseJson) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHistoryFormatSuite.scala new file mode 100644 index 0000000..e46cf50 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHistoryFormatSuite.scala @@ -0,0 +1,32 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/PatientHypothesisFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHypothesisFormatSuite.scala new file mode 100644 index 0000000..270a04d --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientHypothesisFormatSuite.scala @@ -0,0 +1,47 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuicommon.domain.UuidId +import xyz.driver.pdsuidomain.entities.PatientHypothesis +import xyz.driver.pdsuidomain.services.PatientHypothesisService.RichPatientHypothesis + +class PatientHypothesisFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.patienthypothesis._ + + "Json format for RichPatientHypothesis" 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 = richPatientHypothesisWriter.write(RichPatientHypothesis(orig, isRequired = 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) + } + + "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) + + 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}""".parseJson) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientIssueFormatSuite.scala new file mode 100644 index 0000000..0d56918 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientIssueFormatSuite.scala @@ -0,0 +1,45 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/PatientLabelFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientLabelFormatSuite.scala new file mode 100644 index 0000000..95dfa68 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/PatientLabelFormatSuite.scala @@ -0,0 +1,79 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDate + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.entities.labels.LabelValue +import xyz.driver.pdsuicommon.domain.{LongId, UuidId} +import xyz.driver.pdsuidomain.entities._ +import xyz.driver.pdsuidomain.services.PatientLabelService.RichPatientLabel + +class PatientLabelFormatSuite extends FlatSpec with Matchers { + + "Json format for RichPatientLabel" should "read and write correct JSON" in { + import xyz.driver.pdsuidomain.formats.json.patientlabel._ + val orig = PatientLabel( + id = LongId(1), + patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), + labelId = LongId(20), + primaryValue = Some(LabelValue.Yes), + verifiedPrimaryValue = None, + isVisible = true, + score = 1, + isImplicitMatch = false + ) + val writtenJson = richPatientLabelWriter.write(RichPatientLabel(orig, isVerified = 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(LabelValue.No)) + val parsedUpdatePatientLabel = applyUpdateToPatientLabel(updatePatientLabelJson, orig) + parsedUpdatePatientLabel should be(expectedUpdatedPatientLabel) + } + + "Json format for PatientLabelEvidence" should "read and write correct JSON" in { + import xyz.driver.pdsuidomain.formats.json.patientlabel._ + val orig = PatientLabelEvidenceView( + id = LongId(1), + value = LabelValue.Maybe, + evidenceText = "evidence text", + documentId = Some(LongId(21)), + evidenceId = Some(LongId(10)), + reportId = None, + documentType = DocumentType.LaboratoryReport, + date = Some(LocalDate.parse("2017-08-10")), + providerType = ProviderType.EmergencyMedicine, + 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":{"id":3,"name":"Laboratory Report"},"date":"2017-08-10", + "providerType":{"id":26,"name":"Emergency Medicine"}}""".parseJson) + } + + "Json format for PatientLabelDefiningCriteria" should "read and write correct JSON" in { + import xyz.driver.pdsuidomain.formats.json.patientdefiningcriteria._ + val orig = PatientLabel( + id = LongId(1), + patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), + labelId = LongId(20), + primaryValue = Some(LabelValue.Yes), + verifiedPrimaryValue = Some(LabelValue.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/SlotArmFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/SlotArmFormatSuite.scala new file mode 100644 index 0000000..95853f6 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/SlotArmFormatSuite.scala @@ -0,0 +1,36 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuicommon.domain.{LongId, StringId} +import xyz.driver.pdsuidomain.entities.SlotArm + +class SlotArmFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.slotarm._ + + "Json format for SlotArm" should "read and write correct JSON" in { + val arm = SlotArm( + id = LongId(10), + trialId = StringId("NCT000001"), + name = "arm name", + originalName = "orig arm name" + ) + val writtenJson = slotArmFormat.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 = slotArmFormat.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/StudyDesignFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/StudyDesignFormatSuite.scala new file mode 100644 index 0000000..f3a4c83 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/StudyDesignFormatSuite.scala @@ -0,0 +1,20 @@ +package xyz.driver.pdsuidomain.formats.json + +import spray.json._ +import org.scalatest.{FlatSpec, Matchers} +import xyz.driver.pdsuidomain.entities.StudyDesign + +class StudyDesignFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.studydesign._ + + "Json format for StudyDesign" should "read and write correct JSON" in { + val studyDesign = StudyDesign.Randomized + val writtenJson = studyDesignFormat.write(studyDesign) + + writtenJson should be("""{"id":1,"name":"Randomized"}""".parseJson) + + val parsedStudyDesign = studyDesignFormat.read(writtenJson) + parsedStudyDesign should be(studyDesign) + } + +} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialFormatSuite.scala new file mode 100644 index 0000000..b832733 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialFormatSuite.scala @@ -0,0 +1,49 @@ +package xyz.driver.pdsuidomain.formats.json + +import java.time.LocalDateTime + +import org.scalatest.{FlatSpec, Matchers} +import spray.json._ +import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId} +import xyz.driver.pdsuidomain.entities.Trial + +class TrialFormatSuite extends FlatSpec with Matchers { + import xyz.driver.pdsuidomain.formats.json.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"), + 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 = trialFormat.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","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/TrialHistoryFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialHistoryFormatSuite.scala new file mode 100644 index 0000000..aa0b404 --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialHistoryFormatSuite.scala @@ -0,0 +1,31 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/TrialIssueFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialIssueFormatSuite.scala new file mode 100644 index 0000000..5c6aa8d --- /dev/null +++ b/src/test/scala/xyz/driver/pdsuidomain/formats/json/TrialIssueFormatSuite.scala @@ -0,0 +1,49 @@ +package xyz.driver.pdsuidomain.formats.json + +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 xyz.driver.pdsuidomain.formats.json.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/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala deleted file mode 100644 index 35b0fad..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ArmFormatSuite.scala +++ /dev/null @@ -1,37 +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 51665d2..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/CriterionFormatSuite.scala +++ /dev/null @@ -1,75 +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.{EligibilityArm, 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 = "{}", - inclusion = None - ) - 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[EligibilityArm](20), LongId[EligibilityArm](21), LongId[EligibilityArm](21)) - val richCriterion = RichCriterion( - criterion = criterion, - armIds = arms, - labels = labels - ) - val writtenJson = richCriterionFormat.write(richCriterion) - - writtenJson should be( - """{"text":"text","isCompound":false,"trialId":"NCT000001","inclusion":null,"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","inclusion":null, - "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,"inclusion":true}""".parseJson - val expectedUpdatedCriterion = richCriterion.copy( - criterion = criterion.copy( - text = Some("new text"), - isCompound = true, - meta = "{}", - inclusion = Some(true) - )) - 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 111da6e..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentFormatSuite.scala +++ /dev/null @@ -1,73 +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)), - institutionName = Some("institution name"), - requiredType = Some(Document.RequiredType.OPN), - meta = None, - startDate = None, - endDate = None, - labelVersion = 0 - ) - val writtenJson = documentFormat.write(orig) - - writtenJson should be( - """{"id":1,"recordId":101,"physician":"physician","typeId":10,"provider":"provider 21","providerTypeId":21, - "requiredType":"OPN","institutionName":"institution name","startDate":null,"endDate":null,"status":"New","assignee":null,"previousStatus":null, - "previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z","meta":null,"labelVersion":0}""".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, - institutionName = None - ) - val parsedCreatedDocument = documentFormat.read(createDocumentJson) - parsedCreatedDocument should be(expectedCreatedDocument) - - val updateDocumentJson = - """{"startDate":"2017-08-10","endDate":"2018-08-10","meta":{"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(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(startPage = 1.0, endPage = 2.0) - val writtenJson = documentMetaFormat.write(meta) - writtenJson should be("""{"startPage":1.0,"endPage":2.0}""".parseJson) - - val metaJson = """{"startPage":1.0,"endPage":2.0}""".parseJson - val parsedMeta = documentMetaFormat.read(metaJson) - parsedMeta should be(meta) - } - -} 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 5975919..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentHistoryFormatSuite.scala +++ /dev/null @@ -1,31 +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 54cfe90..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/DocumentIssueFormatSuite.scala +++ /dev/null @@ -1,48 +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 = documentIssueFormat.write(documentIssue) - - writtenJson should be( - """{"id":10,"userId":"userId-001","documentId":1,"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/EligibilityArmWithDiseasesFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/EligibilityArmWithDiseasesFormatSuite.scala deleted file mode 100644 index 22adc98..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/EligibilityArmWithDiseasesFormatSuite.scala +++ /dev/null @@ -1,55 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import spray.json._ -import org.scalatest.{FlatSpec, Matchers} -import xyz.driver.entities.patient.CancerType -import xyz.driver.pdsuicommon.domain.{LongId, StringId} -import xyz.driver.pdsuidomain.entities.{EligibilityArm, EligibilityArmDisease, EligibilityArmWithDiseases} - -class EligibilityArmWithDiseasesFormatSuite extends FlatSpec with Matchers { - import eligibilityarm._ - - "Json format for EligibilityArmWithDiseases" should "read and write correct JSON" in { - val name = "arm name" - - val arm = EligibilityArm( - id = LongId(0), - trialId = StringId("NCT000001"), - name = name, - originalName = name - ) - - val disease = EligibilityArmDisease( - arm.id, - disease = CancerType.Lung - ) - - val eligibilityArmWithDiseases = - EligibilityArmWithDiseases( - arm, - Seq(disease) - ) - - val writtenJson = eligibilityArmWithDiseasesWriter.write(eligibilityArmWithDiseases) - - writtenJson should be( - """{"id":0,"trialId":"NCT000001","name":"arm name","originalName":"arm name","diseases":["Lung"]}""".parseJson) - - val createArmWithDiseasesJson = """{"trialId":"NCT000001","name":"arm name","diseases":["Lung"]}""".parseJson - val parsedArmWithDiseases = eligibilityArmWithDiseasesReader.read(createArmWithDiseasesJson) - parsedArmWithDiseases should be(eligibilityArmWithDiseases) - - val updateArmWithDiseasesJson = """{"name":"new arm name"}""".parseJson - val expectedUpdatedArmWithDiseases = eligibilityArmWithDiseases.copy( - eligibilityArm = eligibilityArmWithDiseases.eligibilityArm.copy(name = "new arm name") - ) - - val parsedUpdateArmWithDiseases = - applyUpdateToEligibilityArmWithDiseases( - updateArmWithDiseasesJson, - eligibilityArmWithDiseases - ) - - parsedUpdateArmWithDiseases should be(expectedUpdatedArmWithDiseases) - } -} 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 d78e754..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 org.scalatest.{FlatSpec, Matchers} -import spray.json._ -import xyz.driver.entities.labels.LabelValue -import xyz.driver.pdsuicommon.domain.{LongId, StringId, UuidId} -import xyz.driver.pdsuidomain.entities.{DocumentType, ProviderType, 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 = DocumentType.OutpatientPhysicianNote, - providerType = ProviderType.Surgery, - date = LocalDate.parse("2017-08-10") - ) - - val labels = List( - ExportPatientLabel( - id = LongId(1), - evidences = List( - ExportPatientLabelEvidence( - id = LongId(11), - value = LabelValue.Yes, - evidenceText = "evidence text 11", - document = document - ), - ExportPatientLabelEvidence( - id = LongId(12), - value = LabelValue.No, - evidenceText = "evidence text 12", - document = document - ) - ) - ), - ExportPatientLabel( - id = LongId(2), - evidences = List( - ExportPatientLabelEvidence( - id = LongId(12), - value = LabelValue.Yes, - evidenceText = "evidence text 12", - document = document - ), - ExportPatientLabelEvidence( - id = LongId(13), - value = LabelValue.Yes, - evidenceText = "evidence text 13", - document = document - ) - ) - ) - ) - val patientWithLabels = ExportPatientWithLabels( - patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), - labelVersion = 1L, - labels = labels - ) - - val writtenJson = patientWithLabelsFormat.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":{"id":1,"name":"Outpatient Physician Note"},"providerType":{"id":2,"name":"Surgery"},"date":"2017-08-10"}}, - {"evidenceId":12,"labelValue":"No","evidenceText":"evidence text 12","document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9", - "documentType":{"id":1,"name":"Outpatient Physician Note"},"providerType":{"id":2,"name":"Surgery"},"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":{"id":1,"name":"Outpatient Physician Note"}, - "providerType":{"id":2,"name":"Surgery"},"date":"2017-08-10"}},{"evidenceId":13,"labelValue":"Yes","evidenceText":"evidence text 13", - "document":{"documentId":101,"requestId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","documentType":{"id":1,"name":"Outpatient Physician Note"}, - "providerType":{"id":2,"name":"Surgery"},"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", diseaseList = Seq("Breast")), - ExportTrialArm(armId = LongId(2), armName = "arm 2", diseaseList = Seq("Breast")) - ) - 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"), - lastReviewed = LocalDateTime.parse("2017-08-10T18:00:00"), - labelVersion = 1L, - arms = arms, - criteria = criteriaList - ) - - val writtenJson = trialWithLabelsFormat.write(trialWithLabels) - writtenJson should be( - """{"nctId":"NCT000001","trialId":"40892a07-c638-49d2-9795-1edfefbbcc7c","lastReviewed":"2017-08-10T18:00Z", - "labelVersion":1,"arms":[{"armId":1,"armName":"arm 1","diseaseList":["Breast"]},{"armId":2,"armName":"arm 2","diseaseList":["Breast"]}],"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 1feca6a..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ExtractedDataFormatSuite.scala +++ /dev/null @@ -1,97 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import spray.json._ -import org.scalatest.{FlatSpec, Matchers} -import xyz.driver.entities.labels.LabelValue -import xyz.driver.pdsuicommon.domain.{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(LabelValue.Yes) - ), - ExtractedDataLabel( - id = LongId(2), - dataId = extractedData.id, - labelId = Some(LongId(12)), - categoryId = Some(LongId(1)), - value = Some(LabelValue.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(LabelValue.Yes) - ), - ExtractedDataLabel( - id = LongId(0), - dataId = extractedData.id, - labelId = Some(LongId(12)), - categoryId = Some(LongId(1)), - value = Some(LabelValue.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 76d90f5..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/HypothesisFormatSuite.scala +++ /dev/null @@ -1,27 +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 4532da4..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/InterventionFormatSuite.scala +++ /dev/null @@ -1,73 +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"), - dosage = "", - originalDosage = "", - isActive = true, - deliveryMethod = Some("pill") - ) - 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 = interventionFormat.write(orig) - - writtenJson should be( - """{"id":1,"name":"intervention name","typeId":10,"dosage":"","isActive":true,"arms":[20,21,22], - "trialId":"NCT000001","deliveryMethod":"pill","originalName":"orig name","originalDosage":"","originalType":"orig type"}""".parseJson) - - val createInterventionJson = - """{"id":1,"name":"intervention name","typeId":10,"dosage":"","isActive":true,"arms":[20,21,22], - "trialId":"NCT000001","deliveryMethod":"pill"}""".parseJson - val parsedCreateIntervention = interventionFormat.read(createInterventionJson) - val expectedCreateIntervention = parsedCreateIntervention.copy( - intervention = intervention.copy(id = LongId(0), originalType = None, originalName = "intervention name"), - arms = arms.map(_.copy(interventionId = LongId(0))) - ) - parsedCreateIntervention should be(expectedCreateIntervention) - - val updateInterventionJson = """{"dosage":"descr","arms":[21,22]}""".parseJson - val expectedUpdatedIntervention = orig.copy( - intervention = intervention.copy(dosage = "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.SurgeryProcedure - val writtenJson = interventionTypeFormat.write(interventionType) - - writtenJson should be( - """{"id":9,"name":"Surgery/Procedure","deliveryMethods":["Radio-Frequency Ablation (RFA)", - "Cryoablation","Therapeutic Conventional Surgery","Robotic Assisted Laparoscopic Surgery"]}""".parseJson) - - val parsedInterventionType = interventionTypeFormat.read(writtenJson) - parsedInterventionType should be(interventionType) - } - -} diff --git a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponseFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponseFormatSuite.scala deleted file mode 100644 index d6752d6..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponseFormatSuite.scala +++ /dev/null @@ -1,101 +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, UuidId} -import xyz.driver.pdsuidomain.ListResponse -import xyz.driver.pdsuidomain.entities.MedicalRecord.Status -import xyz.driver.pdsuidomain.entities._ -import xyz.driver.pdsuidomain.formats.json.sprayformats.record.recordFormat -import xyz.driver.pdsuidomain.formats.json.sprayformats.listresponse._ - - -class ListResponseFormatSuite extends FlatSpec with Matchers { - - private val lastUpdate = LocalDateTime.parse("2017-08-10T18:00:00") - private val lastUpdateToLocal = "2017-08-10T18:00Z" - - def metaJsonObjectAsString(meta: ListResponse.Meta) = { - import meta._ - val lastUpdate = meta.lastUpdate - .map(_ => s""","lastUpdate":"$lastUpdateToLocal"""") - .getOrElse("") - - s"""{"itemsCount":$itemsCount,"pageNumber":$pageNumber,"pageSize":$pageSize$lastUpdate}""" - } - - "Json format for ListResponse.Meta" should "read and write correct JSON" in { - val meta1 = - ListResponse.Meta( - itemsCount = 5, - pageNumber = 6, - pageSize = 7, - lastUpdate = None - ) - - val writtenJson1 = listResponseMetaFormat.write(meta1) - - writtenJson1 should be(metaJsonObjectAsString(meta1).parseJson) - - val parsedItem1: ListResponse.Meta = listResponseMetaFormat.read(writtenJson1) - - meta1 shouldBe parsedItem1 - - val meta2 = - ListResponse.Meta( - itemsCount = 1, - pageNumber = 4, - pageSize = 3, - lastUpdate = Some(lastUpdate) - ) - - val writtenJson2 = listResponseMetaFormat.write(meta2) - - writtenJson2 should be(metaJsonObjectAsString(meta2).parseJson) - - val parsedItem2: ListResponse.Meta = listResponseMetaFormat.read(writtenJson2) - - meta2 shouldBe parsedItem2 - } - - "Json format for ListResponse" should "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, - disease = "Breast", - requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")), - caseId = None, - patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), - totalPages = 10 - ) - - val recordJsonAsString = recordFormat.write(orig) - - val meta = - ListResponse.Meta( - itemsCount = 5, - pageNumber = 6, - pageSize = 7, - lastUpdate = None - ) - - val listResponse = ListResponse(Seq(orig), meta) - - val writtenJson = listResponseWriter[MedicalRecord].write(listResponse) - val expectedJson = s"""{"items":[$recordJsonAsString],"meta":${listResponseMetaFormat.write(meta)}}""" - - writtenJson should be(expectedJson.parseJson) - } - -} 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 9616e70..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, - disease = "Breast", - requestId = RecordRequestId(UUID.fromString("7b54a75d-4197-4b27-9045-b9b6cb131be9")), - caseId = None, - patientId = UuidId("748b5884-3528-4cb9-904b-7a8151d6e343"), - totalPages = 10 - ) - 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","totalPages":10}""".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, - lastUpdate = LocalDateTime.now(), - totalPages = 0 - ) - val parsedCreatedRecord = recordFormat.read(createRecordJson).copy(lastUpdate = expectedCreatedRecord.lastUpdate) - parsedCreatedRecord should be(expectedCreatedRecord) - - val updateRecordJson = - """{"meta":[{"type":"duplicate","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(startPage = 1.0, endPage = 2.0, startOriginalPage = 1.0, endOriginalPage = None), - Meta.Reorder(Seq(1, 2)), - Meta.Rotation(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 a8634d9..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/MedicalRecordHistoryFormatSuite.scala +++ /dev/null @@ -1,31 +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 5fa740b..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 = recordIssueFormat.write(recordIssue) - - writtenJson should be( - """{"id":10,"recordId":1,"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 b254013..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientCriterionFormatSuite.scala +++ /dev/null @@ -1,58 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import java.time.LocalDateTime - -import spray.json._ -import org.scalatest.{FlatSpec, Matchers} -import xyz.driver.entities.labels.LabelValue -import xyz.driver.pdsuicommon.domain.{LongId, StringId} -import xyz.driver.pdsuidomain.entities.{PatientCriterion, PatientCriterionArm} -import xyz.driver.pdsuidomain.services.PatientCriterionService.{DraftPatientCriterion, RichPatientCriterion} - -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(LabelValue.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 richPatientCriterion = RichPatientCriterion(orig, LongId(21), arms) - val writtenJson = patientCriterionWriter.write(richPatientCriterion) - - 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(LabelValue.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(LabelValue.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 b8f6f8e..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 org.scalatest.{FlatSpec, Matchers} -import spray.json._ -import xyz.driver.entities.labels.LabelValue -import xyz.driver.pdsuicommon.domain.{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"), - 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(LabelValue.Yes), - verifiedEligibilityStatus = Some(LabelValue.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 128cad1..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientFormatSuite.scala +++ /dev/null @@ -1,39 +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.entities.common.FullName -import xyz.driver.entities.patient.CancerType -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 = FullName.fromStrings("John", "", "Doe"), - dob = LocalDate.parse("1980-06-30"), - assignee = None, - previousStatus = None, - previousAssignee = None, - lastActiveUserId = None, - isUpdateRequired = false, - disease = CancerType.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":{"firstName":"John","middleName":"","lastName":"Doe"},"status":"New","assignee":null, - "previousStatus":null,"previousAssignee":null,"lastActiveUser":null,"lastUpdate":"2017-08-10T18:00Z", - "orderId":"7b54a75d-4197-4b27-9045-b9b6cb131be9","disease":"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 71cbbad..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientHypothesisFormatSuite.scala +++ /dev/null @@ -1,47 +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 -import xyz.driver.pdsuidomain.services.PatientHypothesisService.RichPatientHypothesis - -class PatientHypothesisFormatSuite extends FlatSpec with Matchers { - import patienthypothesis._ - - "Json format for RichPatientHypothesis" 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 = richPatientHypothesisWriter.write(RichPatientHypothesis(orig, isRequired = 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) - } - - "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) - - 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}""".parseJson) - } - -} 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 2776dcc..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientIssueFormatSuite.scala +++ /dev/null @@ -1,45 +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 2122777..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/PatientLabelFormatSuite.scala +++ /dev/null @@ -1,79 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import java.time.LocalDate - -import spray.json._ -import org.scalatest.{FlatSpec, Matchers} -import xyz.driver.entities.labels.LabelValue -import xyz.driver.pdsuicommon.domain.{LongId, UuidId} -import xyz.driver.pdsuidomain.entities._ -import xyz.driver.pdsuidomain.services.PatientLabelService.RichPatientLabel - -class PatientLabelFormatSuite extends FlatSpec with Matchers { - - "Json format for RichPatientLabel" 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(LabelValue.Yes), - verifiedPrimaryValue = None, - isVisible = true, - score = 1, - isImplicitMatch = false - ) - val writtenJson = richPatientLabelWriter.write(RichPatientLabel(orig, isVerified = 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(LabelValue.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 = LabelValue.Maybe, - evidenceText = "evidence text", - documentId = Some(LongId(21)), - evidenceId = Some(LongId(10)), - reportId = None, - documentType = DocumentType.LaboratoryReport, - date = Some(LocalDate.parse("2017-08-10")), - providerType = ProviderType.EmergencyMedicine, - 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":{"id":3,"name":"Laboratory Report"},"date":"2017-08-10", - "providerType":{"id":26,"name":"Emergency Medicine"}}""".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(LabelValue.Yes), - verifiedPrimaryValue = Some(LabelValue.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/SlotArmFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/SlotArmFormatSuite.scala deleted file mode 100644 index 7dd085c..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/SlotArmFormatSuite.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.SlotArm - -class SlotArmFormatSuite extends FlatSpec with Matchers { - import slotarm._ - - "Json format for SlotArm" should "read and write correct JSON" in { - val arm = SlotArm( - id = LongId(10), - trialId = StringId("NCT000001"), - name = "arm name", - originalName = "orig arm name" - ) - val writtenJson = slotArmFormat.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 = slotArmFormat.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/StudyDesignFormatSuite.scala b/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala deleted file mode 100644 index e847445..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/StudyDesignFormatSuite.scala +++ /dev/null @@ -1,20 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import spray.json._ -import org.scalatest.{FlatSpec, Matchers} -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.Randomized - val writtenJson = studyDesignFormat.write(studyDesign) - - writtenJson should be("""{"id":1,"name":"Randomized"}""".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 c9dc85f..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialFormatSuite.scala +++ /dev/null @@ -1,49 +0,0 @@ -package xyz.driver.pdsuidomain.formats.json.sprayformats - -import java.time.LocalDateTime - -import org.scalatest.{FlatSpec, Matchers} -import spray.json._ -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"), - 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","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 d5ad2ec..0000000 --- a/src/test/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/TrialHistoryFormatSuite.scala +++ /dev/null @@ -1,31 +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 4a9ea4f..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) - } - -} -- cgit v1.2.3 From e3b8e6ce8f659bff81b9a4bc3a79e3d2c3dd734f Mon Sep 17 00:00:00 2001 From: Kseniya Tomskikh Date: Mon, 23 Oct 2017 15:34:13 +0700 Subject: Removed quill query builder --- .../BridgeUploadQueueRepositoryAdapter.scala | 140 --------- .../xyz/driver/pdsuicommon/db/DbCommand.scala | 15 - .../driver/pdsuicommon/db/DbCommandFactory.scala | 14 - .../scala/xyz/driver/pdsuicommon/db/DbIo.scala | 13 - .../pdsuicommon/db/EntityExtractorDerivation.scala | 66 ---- .../scala/xyz/driver/pdsuicommon/db/FakeDbIo.scala | 9 - .../scala/xyz/driver/pdsuicommon/db/JdbcDbIo.scala | 28 -- .../xyz/driver/pdsuicommon/db/MySqlContext.scala | 90 ------ .../driver/pdsuicommon/db/MysqlQueryBuilder.scala | 88 ------ .../driver/pdsuicommon/db/PostgresContext.scala | 27 +- .../pdsuicommon/db/PostgresQueryBuilder.scala | 108 ------- .../xyz/driver/pdsuicommon/db/QueryBuilder.scala | 340 --------------------- .../driver/pdsuicommon/db/SlickQueryBuilder.scala | 2 +- .../repositories/BridgeUploadQueueRepository.scala | 21 -- .../pdsuicommon/db/repositories/Repository.scala | 4 - .../db/repositories/RepositoryLogging.scala | 62 ---- .../scala/xyz/driver/pdsuicommon/BaseSuite.scala | 12 - src/test/scala/xyz/driver/pdsuicommon/Mocks.scala | 51 +--- .../BridgeUploadQueueRepositoryAdapterSuite.scala | 285 ----------------- .../db/QueryBuilderParametersSuite.scala | 310 ------------------- 20 files changed, 14 insertions(+), 1671 deletions(-) delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapter.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/DbCommand.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/DbCommandFactory.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/DbIo.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/EntityExtractorDerivation.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/FakeDbIo.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/JdbcDbIo.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/MySqlContext.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/MysqlQueryBuilder.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/PostgresQueryBuilder.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/QueryBuilder.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/repositories/BridgeUploadQueueRepository.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/repositories/Repository.scala delete mode 100644 src/main/scala/xyz/driver/pdsuicommon/db/repositories/RepositoryLogging.scala delete mode 100644 src/test/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapterSuite.scala delete mode 100644 src/test/scala/xyz/driver/pdsuicommon/db/QueryBuilderParametersSuite.scala (limited to 'src/test') diff --git a/src/main/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapter.scala b/src/main/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapter.scala deleted file mode 100644 index 3bf9192..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/concurrent/BridgeUploadQueueRepositoryAdapter.scala +++ /dev/null @@ -1,140 +0,0 @@ -package xyz.driver.pdsuicommon.concurrent - -import java.time.LocalDateTime -import java.time.temporal.ChronoUnit - -import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueue.Item -import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueueRepositoryAdapter.Strategy -import xyz.driver.pdsuicommon.db._ -import xyz.driver.pdsuicommon.db.repositories.BridgeUploadQueueRepository -import xyz.driver.pdsuicommon.logging._ - -import scala.concurrent.duration.{Duration, FiniteDuration} -import scala.concurrent.{ExecutionContext, Future} -import scala.util.Try - -object BridgeUploadQueueRepositoryAdapter { - - /** - * Defines how we work with queue, when an user attempts to remove/tryRetry an item. - */ - sealed trait Strategy { - - def onComplete: Strategy.OnComplete - - def on(attempt: Int): Strategy.OnAttempt - - } - - object Strategy { - - /** - * Works forever, but has a limit for intervals. - */ - final case class LimitExponential(startInterval: FiniteDuration, - intervalFactor: Double, - maxInterval: FiniteDuration, - onComplete: OnComplete) - extends Strategy { - - override def on(attempt: Int): OnAttempt = { - OnAttempt.Continue(intervalFor(attempt).min(maxInterval)) - } - - private def intervalFor(attempt: Int): Duration = { - Try(startInterval * Math.pow(intervalFactor, attempt.toDouble)) - .getOrElse(maxInterval) - } - } - - /** - * Used only in tests. - */ - final case class Stop(onComplete: OnComplete = OnComplete.Delete) extends Strategy { - - override def on(attempt: Int) = OnAttempt.Complete - - } - - /** - * Used only in tests. - */ - final case class Constant(interval: FiniteDuration) extends Strategy { - - override val onComplete = OnComplete.Delete - - override def on(attempt: Int) = OnAttempt.Continue(interval) - - } - - sealed trait OnComplete - object OnComplete { - case object Delete extends OnComplete - case object Mark extends OnComplete - - implicit def toPhiString(x: OnAttempt): PhiString = Unsafe(x.toString) - } - - sealed trait OnAttempt - object OnAttempt { - case object Complete extends OnAttempt - final case class Continue(interval: Duration) extends OnAttempt - - implicit def toPhiString(x: OnAttempt): PhiString = Unsafe(x.toString) - } - } -} - -class BridgeUploadQueueRepositoryAdapter(strategy: Strategy, repository: BridgeUploadQueueRepository, dbIo: DbIo)( - implicit executionContext: ExecutionContext) - extends BridgeUploadQueue with PhiLogging { - - override def add(item: Item): Future[Item] = dbIo.runAsync(repository.add(item)) - - override def get(kind: String): Future[Option[Item]] = dbIo.runAsync(repository.getOne(kind)) - - override def complete(kind: String, tag: String): Future[Unit] = { - import Strategy.OnComplete._ - - strategy.onComplete match { - case Delete => dbIo.runAsync(repository.delete(kind, tag)) - case Mark => - dbIo.runAsyncTx { - repository.getById(kind, tag) match { - case Some(x) => repository.update(x.copy(completed = true)) - case None => throw new RuntimeException(s"Can not find the task: kind=$kind, tag=$tag") - } - } - } - } - - /** - * Tries to continue the task or complete it - */ - override def tryRetry(item: Item): Future[Option[Item]] = { - import Strategy.OnAttempt._ - - logger.trace(phi"tryRetry($item)") - - val newAttempts = item.attempts + 1 - val action = strategy.on(newAttempts) - logger.debug(phi"Action for ${Unsafe(newAttempts)}: $action") - - action match { - case Continue(newInterval) => - val draftItem = item.copy( - attempts = newAttempts, - nextAttempt = LocalDateTime.now().plus(newInterval.toMillis, ChronoUnit.MILLIS) - ) - - logger.debug(draftItem) - dbIo.runAsync { - Some(repository.update(draftItem)) - } - - case Complete => - logger.warn(phi"All attempts are out for $item, complete the task") - complete(item.kind, item.tag).map(_ => None) - } - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/DbCommand.scala b/src/main/scala/xyz/driver/pdsuicommon/db/DbCommand.scala deleted file mode 100644 index 0af104e..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/DbCommand.scala +++ /dev/null @@ -1,15 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import scala.concurrent.Future - -trait DbCommand { - def runSync(): Unit - def runAsync(transactions: DbIo): Future[Unit] -} - -object DbCommand { - val Empty: DbCommand = new DbCommand { - override def runSync(): Unit = {} - override def runAsync(transactions: DbIo): Future[Unit] = Future.successful(()) - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/DbCommandFactory.scala b/src/main/scala/xyz/driver/pdsuicommon/db/DbCommandFactory.scala deleted file mode 100644 index 1e2fb74..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/DbCommandFactory.scala +++ /dev/null @@ -1,14 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import scala.concurrent.{ExecutionContext, Future} - -trait DbCommandFactory[T] { - def createCommand(orig: T)(implicit ec: ExecutionContext): Future[DbCommand] -} - -object DbCommandFactory { - def empty[T]: DbCommandFactory[T] = new DbCommandFactory[T] { - override def createCommand(orig: T)(implicit ec: ExecutionContext): Future[DbCommand] = - Future.successful(DbCommand.Empty) - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/DbIo.scala b/src/main/scala/xyz/driver/pdsuicommon/db/DbIo.scala deleted file mode 100644 index 7c290d1..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/DbIo.scala +++ /dev/null @@ -1,13 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import scala.concurrent.Future - -/** - * Where queries should run - */ -trait DbIo { - def runAsync[T](f: => T): Future[T] - def runSync[T](f: => T): T = f - def runAsyncTx[T](f: => T): Future[T] - def runSyncTx[T](f: => T): Unit -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/EntityExtractorDerivation.scala b/src/main/scala/xyz/driver/pdsuicommon/db/EntityExtractorDerivation.scala deleted file mode 100644 index 02ba322..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/EntityExtractorDerivation.scala +++ /dev/null @@ -1,66 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import java.sql.ResultSet - -import io.getquill.NamingStrategy -import io.getquill.dsl.EncodingDsl - -import scala.language.experimental.macros -import scala.reflect.macros.blackbox - -trait EntityExtractorDerivation[Naming <: NamingStrategy] { this: EncodingDsl => - - /* - Simple Quill extractor derivation for [[T]] - Only case classes available. Type parameters is not supported - */ - def entityExtractor[T]: (ResultSet => T) = macro EntityExtractorDerivation.impl[T] -} - -object EntityExtractorDerivation { - def impl[T: c.WeakTypeTag](c: blackbox.Context): c.Tree = { - import c.universe._ - val namingStrategy = c.prefix.actualType - .baseType(c.weakTypeOf[EntityExtractorDerivation[NamingStrategy]].typeSymbol) - .typeArgs - .head - .typeSymbol - .companion - val functionBody = { - val tpe = weakTypeOf[T] - val resultOpt = tpe.decls.collectFirst { - // Find first constructor of T - case cons: MethodSymbol if cons.isConstructor => - // Create param list for constructor - val params = cons.paramLists.flatten.map { param => - val t = param.typeSignature - val paramName = param.name.toString - val col = q"$namingStrategy.column($paramName)" - // Resolve implicit decoders (from SqlContext) and apply ResultSet for each - val d = q"implicitly[${c.prefix}.Decoder[$t]]" - // Minus 1 cause Quill JDBC decoders make plus one. - // ¯\_(ツ)_/¯ - val i = q"row.findColumn($col) - 1" - val decoderName = TermName(paramName + "Decoder") - val valueName = TermName(paramName + "Value") - ( - q"val $decoderName = $d", - q"val $valueName = $decoderName($i, row)", - valueName - ) - } - // Call constructor with param list - q""" - ..${params.map(_._1)} - ..${params.map(_._2)} - new $tpe(..${params.map(_._3)}) - """ - } - resultOpt match { - case Some(result) => result - case None => c.abort(c.enclosingPosition, s"Can not derive extractor for $tpe. Constructor not found.") - } - } - q"(row: java.sql.ResultSet) => $functionBody" - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/FakeDbIo.scala b/src/main/scala/xyz/driver/pdsuicommon/db/FakeDbIo.scala deleted file mode 100644 index ac42a34..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/FakeDbIo.scala +++ /dev/null @@ -1,9 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import scala.concurrent.Future - -object FakeDbIo extends DbIo { - override def runAsync[T](f: => T): Future[T] = Future.successful(f) - override def runAsyncTx[T](f: => T): Future[T] = Future.successful(f) - override def runSyncTx[T](f: => T): Unit = f -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/JdbcDbIo.scala b/src/main/scala/xyz/driver/pdsuicommon/db/JdbcDbIo.scala deleted file mode 100644 index 44f177c..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/JdbcDbIo.scala +++ /dev/null @@ -1,28 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import xyz.driver.pdsuicommon.logging._ - -import scala.concurrent.Future -import scala.util.{Failure, Success, Try} - -class JdbcDbIo(sqlContext: TransactionalContext) extends DbIo with PhiLogging { - - override def runAsync[T](f: => T): Future[T] = { - Future(f)(sqlContext.executionContext) - } - - override def runAsyncTx[T](f: => T): Future[T] = { - import sqlContext.executionContext - - Future(sqlContext.transaction(f)).andThen { - case Failure(e) => logger.error(phi"Can't run a transaction: $e") - } - } - - override def runSyncTx[T](f: => T): Unit = { - Try(sqlContext.transaction(f)) match { - case Success(_) => - case Failure(e) => logger.error(phi"Can't run a transaction: $e") - } - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/MySqlContext.scala b/src/main/scala/xyz/driver/pdsuicommon/db/MySqlContext.scala deleted file mode 100644 index 9d2664d..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/MySqlContext.scala +++ /dev/null @@ -1,90 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import java.io.Closeable -import java.time._ -import java.util.concurrent.Executors -import javax.sql.DataSource - -import com.typesafe.config.Config -import io.getquill._ -import xyz.driver.pdsuicommon.concurrent.MdcExecutionContext -import xyz.driver.pdsuicommon.db.MySqlContext.Settings -import xyz.driver.pdsuicommon.error.IncorrectIdException -import xyz.driver.pdsuicommon.logging._ - -import scala.concurrent.ExecutionContext -import scala.util.control.NonFatal -import scala.util.{Failure, Success, Try} - -object MySqlContext extends PhiLogging { - - final case class DbCredentials(user: String, - password: String, - host: String, - port: Int, - dbName: String, - dbCreateFlag: Boolean, - dbContext: String, - connectionParams: String, - url: String) - - final case class Settings(credentials: DbCredentials, connection: Config, threadPoolSize: Int) - - def apply(settings: Settings): MySqlContext = { - // Prevent leaking credentials to a log - Try(JdbcContextConfig(settings.connection).dataSource) match { - case Success(dataSource) => new MySqlContext(dataSource, settings) - case Failure(NonFatal(e)) => - logger.error(phi"Can not load dataSource, error: ${Unsafe(e.getClass.getName)}") - throw new IllegalArgumentException("Can not load dataSource from config. Check your database and config") - } - } -} - -class MySqlContext(dataSource: DataSource with Closeable, settings: Settings) - extends MysqlJdbcContext[MysqlEscape](dataSource) with TransactionalContext - with EntityExtractorDerivation[Literal] { - - private val tpe = Executors.newFixedThreadPool(settings.threadPoolSize) - - implicit val executionContext: ExecutionContext = { - val orig = ExecutionContext.fromExecutor(tpe) - MdcExecutionContext.from(orig) - } - - override def close(): Unit = { - super.close() - tpe.shutdownNow() - } - - /** - * Overrode, because Quill JDBC optionDecoder pass null inside decoders. - * If custom decoder don't have special null handler, it will failed. - * - * @see https://github.com/getquill/quill/issues/535 - */ - implicit override def optionDecoder[T](implicit d: Decoder[T]): Decoder[Option[T]] = - decoder( - sqlType = d.sqlType, - row => - index => { - try { - val res = d(index - 1, row) - if (row.wasNull) { - None - } else { - Some(res) - } - } catch { - case _: NullPointerException => None - case _: IncorrectIdException => None - } - } - ) - - final implicit class LocalDateTimeDbOps(val left: LocalDateTime) { - - // scalastyle:off - def <=(right: LocalDateTime): Quoted[Boolean] = quote(infix"$left <= $right".as[Boolean]) - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/MysqlQueryBuilder.scala b/src/main/scala/xyz/driver/pdsuicommon/db/MysqlQueryBuilder.scala deleted file mode 100644 index e2936e3..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/MysqlQueryBuilder.scala +++ /dev/null @@ -1,88 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import java.sql.ResultSet - -import xyz.driver.pdsuicommon.logging._ -import io.getquill.{MySQLDialect, MysqlEscape} - -import scala.collection.breakOut - -object MysqlQueryBuilder extends PhiLogging { - import xyz.driver.pdsuicommon.db.QueryBuilder._ - - def apply[T](tableName: String, - lastUpdateFieldName: Option[String], - nullableFields: Set[String], - links: Set[TableLink], - runner: Runner[T], - countRunner: CountRunner): MysqlQueryBuilder[T] = { - val parameters = MysqlQueryBuilderParameters( - tableData = TableData(tableName, lastUpdateFieldName, nullableFields), - links = links.map(x => x.foreignTableName -> x)(breakOut) - ) - new MysqlQueryBuilder[T](parameters)(runner, countRunner) - } - - def apply[T](tableName: String, - lastUpdateFieldName: Option[String], - nullableFields: Set[String], - links: Set[TableLink], - extractor: (ResultSet) => T)(implicit sqlContext: MySqlContext): MysqlQueryBuilder[T] = { - - val runner: Runner[T] = { parameters => - val (sql, binder) = parameters.toSql(namingStrategy = MysqlEscape) - logger.trace(phi"Query for execute: ${Unsafe(sql)}") - sqlContext.executeQuery[T](sql, binder, { resultSet => - extractor(resultSet) - }) - } - - val countRunner: CountRunner = { parameters => - val (sql, binder) = parameters.toSql(countQuery = true, namingStrategy = MysqlEscape) - logger.trace(phi"Query for execute: ${Unsafe(sql)}") - sqlContext - .executeQuery[CountResult]( - sql, - binder, { resultSet => - val count = resultSet.getInt(1) - val lastUpdate = if (parameters.tableData.lastUpdateFieldName.isDefined) { - Option(sqlContext.localDateTimeDecoder.decoder(2, resultSet)) - } else None - - (count, lastUpdate) - } - ) - .head - } - - apply[T]( - tableName = tableName, - lastUpdateFieldName = lastUpdateFieldName, - nullableFields = nullableFields, - links = links, - runner = runner, - countRunner = countRunner - ) - } -} - -class MysqlQueryBuilder[T](parameters: MysqlQueryBuilderParameters)(implicit runner: QueryBuilder.Runner[T], - countRunner: QueryBuilder.CountRunner) - extends QueryBuilder[T, MySQLDialect, MysqlEscape](parameters) { - - def withFilter(newFilter: SearchFilterExpr): QueryBuilder[T, MySQLDialect, MysqlEscape] = { - new MysqlQueryBuilder[T](parameters.copy(filter = newFilter)) - } - - def withSorting(newSorting: Sorting): QueryBuilder[T, MySQLDialect, MysqlEscape] = { - new MysqlQueryBuilder[T](parameters.copy(sorting = newSorting)) - } - - def withPagination(newPagination: Pagination): QueryBuilder[T, MySQLDialect, MysqlEscape] = { - new MysqlQueryBuilder[T](parameters.copy(pagination = Some(newPagination))) - } - - def resetPagination: QueryBuilder[T, MySQLDialect, MysqlEscape] = { - new MysqlQueryBuilder[T](parameters.copy(pagination = None)) - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/PostgresContext.scala b/src/main/scala/xyz/driver/pdsuicommon/db/PostgresContext.scala index 7bdfd1b..bb8d322 100644 --- a/src/main/scala/xyz/driver/pdsuicommon/db/PostgresContext.scala +++ b/src/main/scala/xyz/driver/pdsuicommon/db/PostgresContext.scala @@ -1,15 +1,12 @@ package xyz.driver.pdsuicommon.db import java.io.Closeable -import java.time._ -import java.util.UUID import java.util.concurrent.Executors import javax.sql.DataSource import io.getquill._ import xyz.driver.pdsuicommon.concurrent.MdcExecutionContext import xyz.driver.pdsuicommon.db.PostgresContext.Settings -import xyz.driver.pdsuicommon.domain.UuidId import xyz.driver.pdsuicommon.logging._ import scala.concurrent.ExecutionContext @@ -35,8 +32,7 @@ object PostgresContext extends PhiLogging { } class PostgresContext(val dataSource: DataSource with Closeable, settings: Settings) - extends PostgresJdbcContext[SnakeCase](dataSource) with TransactionalContext - with EntityExtractorDerivation[SnakeCase] { + extends PostgresJdbcContext[SnakeCase](dataSource) with TransactionalContext { private val tpe = Executors.newFixedThreadPool(settings.threadPoolSize) @@ -49,25 +45,4 @@ class PostgresContext(val dataSource: DataSource with Closeable, settings: Setti super.close() tpe.shutdownNow() } - - /** - * Usable for QueryBuilder's extractors - */ - def timestampToLocalDateTime(timestamp: java.sql.Timestamp): LocalDateTime = { - LocalDateTime.ofInstant(timestamp.toInstant, ZoneOffset.UTC) - } - - implicit def encodeUuidId[T] = MappedEncoding[UuidId[T], String](_.toString) - implicit def decodeUuidId[T] = MappedEncoding[String, UuidId[T]] { uuid => - UuidId[T](UUID.fromString(uuid)) - } - - def decodeOptUuidId[T] = MappedEncoding[Option[String], Option[UuidId[T]]] { - case Some(x) => Option(x).map(y => UuidId[T](UUID.fromString(y))) - case None => None - } - - implicit def decodeUuid[T] = MappedEncoding[String, UUID] { uuid => - UUID.fromString(uuid) - } } diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/PostgresQueryBuilder.scala b/src/main/scala/xyz/driver/pdsuicommon/db/PostgresQueryBuilder.scala deleted file mode 100644 index 0ddf811..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/PostgresQueryBuilder.scala +++ /dev/null @@ -1,108 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import java.sql.ResultSet - -import io.getquill.{PostgresDialect, PostgresEscape} -import xyz.driver.pdsuicommon.db.PostgresQueryBuilder.SmartPostgresEscape - -import scala.collection.breakOut - -object PostgresQueryBuilder { - - import xyz.driver.pdsuicommon.db.QueryBuilder._ - - trait SmartPostgresEscape extends PostgresEscape { - override def column(s: String): String = - if (s.startsWith("$")) s else super.column(s) - override def default(s: String): String = - s.split("\\.").map(ss => s""""$ss"""").mkString(".") - } - - object SmartPostgresEscape extends SmartPostgresEscape - - type Escape = SmartPostgresEscape - val Escape = SmartPostgresEscape - - def apply[T](tableName: String, - lastUpdateFieldName: Option[String], - nullableFields: Set[String], - links: Set[TableLink], - runner: Runner[T], - countRunner: CountRunner): PostgresQueryBuilder[T] = { - val parameters = PostgresQueryBuilderParameters( - tableData = TableData(tableName, lastUpdateFieldName, nullableFields), - links = links.map(x => x.foreignTableName -> x)(breakOut) - ) - new PostgresQueryBuilder[T](parameters)(runner, countRunner) - } - - def apply[T](tableName: String, - lastUpdateFieldName: Option[String], - nullableFields: Set[String], - links: Set[TableLink], - extractor: ResultSet => T)(implicit sqlContext: PostgresContext): PostgresQueryBuilder[T] = { - apply(tableName, QueryBuilderParameters.AllFields, lastUpdateFieldName, nullableFields, links, extractor) - } - - def apply[T](tableName: String, - fields: Set[String], - lastUpdateFieldName: Option[String], - nullableFields: Set[String], - links: Set[TableLink], - extractor: ResultSet => T)(implicit sqlContext: PostgresContext): PostgresQueryBuilder[T] = { - - val runner: Runner[T] = { parameters => - val (sql, binder) = parameters.toSql(countQuery = false, fields = fields, namingStrategy = SmartPostgresEscape) - sqlContext.executeQuery[T](sql, binder, { resultSet => - extractor(resultSet) - }) - } - - val countRunner: CountRunner = { parameters => - val (sql, binder) = parameters.toSql(countQuery = true, namingStrategy = SmartPostgresEscape) - sqlContext - .executeQuery[CountResult]( - sql, - binder, { resultSet => - val count = resultSet.getInt(1) - val lastUpdate = if (parameters.tableData.lastUpdateFieldName.isDefined) { - Option(resultSet.getTimestamp(2)).map(sqlContext.timestampToLocalDateTime) - } else None - - (count, lastUpdate) - } - ) - .head - } - - apply[T]( - tableName = tableName, - lastUpdateFieldName = lastUpdateFieldName, - nullableFields = nullableFields, - links = links, - runner = runner, - countRunner = countRunner - ) - } -} - -class PostgresQueryBuilder[T](parameters: PostgresQueryBuilderParameters)(implicit runner: QueryBuilder.Runner[T], - countRunner: QueryBuilder.CountRunner) - extends QueryBuilder[T, PostgresDialect, PostgresQueryBuilder.Escape](parameters) { - - def withFilter(newFilter: SearchFilterExpr): QueryBuilder[T, PostgresDialect, SmartPostgresEscape] = { - new PostgresQueryBuilder[T](parameters.copy(filter = newFilter)) - } - - def withSorting(newSorting: Sorting): QueryBuilder[T, PostgresDialect, SmartPostgresEscape] = { - new PostgresQueryBuilder[T](parameters.copy(sorting = newSorting)) - } - - def withPagination(newPagination: Pagination): QueryBuilder[T, PostgresDialect, SmartPostgresEscape] = { - new PostgresQueryBuilder[T](parameters.copy(pagination = Some(newPagination))) - } - - def resetPagination: QueryBuilder[T, PostgresDialect, SmartPostgresEscape] = { - new PostgresQueryBuilder[T](parameters.copy(pagination = None)) - } -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/QueryBuilder.scala b/src/main/scala/xyz/driver/pdsuicommon/db/QueryBuilder.scala deleted file mode 100644 index 0bf1ed6..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/QueryBuilder.scala +++ /dev/null @@ -1,340 +0,0 @@ -package xyz.driver.pdsuicommon.db - -import java.sql.PreparedStatement -import java.time.LocalDateTime - -import io.getquill.NamingStrategy -import io.getquill.context.sql.idiom.SqlIdiom -import xyz.driver.pdsuicommon.db.Sorting.{Dimension, Sequential} -import xyz.driver.pdsuicommon.db.SortingOrder.{Ascending, Descending} - -import scala.collection.mutable.ListBuffer - -object QueryBuilder { - - type Runner[T] = QueryBuilderParameters => Seq[T] - - type CountResult = (Int, Option[LocalDateTime]) - - type CountRunner = QueryBuilderParameters => CountResult - - /** - * Binder for PreparedStatement - */ - type Binder = PreparedStatement => PreparedStatement - - final case class TableData(tableName: String, - lastUpdateFieldName: Option[String] = None, - nullableFields: Set[String] = Set.empty) - - val AllFields = Set("*") - -} - -final case class TableLink(keyColumnName: String, foreignTableName: String, foreignKeyColumnName: String) - -object QueryBuilderParameters { - val AllFields = Set("*") -} - -sealed trait QueryBuilderParameters { - - def tableData: QueryBuilder.TableData - def links: Map[String, TableLink] - def filter: SearchFilterExpr - def sorting: Sorting - def pagination: Option[Pagination] - - def findLink(tableName: String): TableLink = links.get(tableName) match { - case None => throw new IllegalArgumentException(s"Cannot find a link for `$tableName`") - case Some(link) => link - } - - def toSql(countQuery: Boolean = false, namingStrategy: NamingStrategy): (String, QueryBuilder.Binder) = { - toSql(countQuery, QueryBuilderParameters.AllFields, namingStrategy) - } - - def toSql(countQuery: Boolean, fields: Set[String], namingStrategy: NamingStrategy): (String, QueryBuilder.Binder) = { - val escapedTableName = namingStrategy.table(tableData.tableName) - val fieldsSql: String = if (countQuery) { - val suffix: String = tableData.lastUpdateFieldName match { - case Some(lastUpdateField) => s", max($escapedTableName.${namingStrategy.column(lastUpdateField)})" - case None => "" - } - "count(*)" + suffix - } else { - if (fields == QueryBuilderParameters.AllFields) { - s"$escapedTableName.*" - } else { - fields - .map { field => - s"$escapedTableName.${namingStrategy.column(field)}" - } - .mkString(", ") - } - } - val (where, bindings) = filterToSql(escapedTableName, filter, namingStrategy) - val orderBy = sortingToSql(escapedTableName, sorting, namingStrategy) - - val limitSql = limitToSql() - - val sql = new StringBuilder() - sql.append("select ") - sql.append(fieldsSql) - sql.append("\nfrom ") - sql.append(escapedTableName) - - val filtersTableLinks: Seq[TableLink] = { - import SearchFilterExpr._ - def aux(expr: SearchFilterExpr): Seq[TableLink] = expr match { - case Atom.TableName(tableName) => List(findLink(tableName)) - case Intersection(xs) => xs.flatMap(aux) - case Union(xs) => xs.flatMap(aux) - case _ => Nil - } - aux(filter) - } - - val sortingTableLinks: Seq[TableLink] = Sorting.collect(sorting) { - case Dimension(Some(foreignTableName), _, _) => findLink(foreignTableName) - } - - // Combine links from sorting and filter without duplicates - val foreignTableLinks = (filtersTableLinks ++ sortingTableLinks).distinct - - foreignTableLinks.foreach { - case TableLink(keyColumnName, foreignTableName, foreignKeyColumnName) => - val escapedForeignTableName = namingStrategy.table(foreignTableName) - - sql.append("\ninner join ") - sql.append(escapedForeignTableName) - sql.append(" on ") - - sql.append(escapedTableName) - sql.append('.') - sql.append(namingStrategy.column(keyColumnName)) - - sql.append(" = ") - - sql.append(escapedForeignTableName) - sql.append('.') - sql.append(namingStrategy.column(foreignKeyColumnName)) - } - - if (where.nonEmpty) { - sql.append("\nwhere ") - sql.append(where) - } - - if (orderBy.nonEmpty && !countQuery) { - sql.append("\norder by ") - sql.append(orderBy) - } - - if (limitSql.nonEmpty && !countQuery) { - sql.append("\n") - sql.append(limitSql) - } - - (sql.toString, binder(bindings)) - } - - /** - * Converts filter expression to SQL expression. - * - * @return Returns SQL string and list of values for binding in prepared statement. - */ - protected def filterToSql(escapedTableName: String, - filter: SearchFilterExpr, - namingStrategy: NamingStrategy): (String, List[AnyRef]) = { - import SearchFilterBinaryOperation._ - import SearchFilterExpr._ - - def isNull(string: AnyRef) = Option(string).isEmpty || string.toString.toLowerCase == "null" - - def placeholder(field: String) = "?" - - def escapeDimension(dimension: SearchFilterExpr.Dimension) = { - val tableName = dimension.tableName.fold(escapedTableName)(namingStrategy.table) - s"$tableName.${namingStrategy.column(dimension.name)}" - } - - def filterToSqlMultiple(operands: Seq[SearchFilterExpr]) = operands.collect { - case x if !SearchFilterExpr.isEmpty(x) => filterToSql(escapedTableName, x, namingStrategy) - } - - filter match { - case x if isEmpty(x) => - ("", List.empty) - - case AllowAll => - ("1", List.empty) - - case DenyAll => - ("0", List.empty) - - case Atom.Binary(dimension, Eq, value) if isNull(value) => - (s"${escapeDimension(dimension)} is NULL", List.empty) - - case Atom.Binary(dimension, NotEq, value) if isNull(value) => - (s"${escapeDimension(dimension)} is not NULL", List.empty) - - case Atom.Binary(dimension, NotEq, value) if tableData.nullableFields.contains(dimension.name) => - // In MySQL NULL <> Any === NULL - // So, to handle NotEq for nullable fields we need to use more complex SQL expression. - // http://dev.mysql.com/doc/refman/5.7/en/working-with-null.html - val escapedColumn = escapeDimension(dimension) - val sql = s"($escapedColumn is null or $escapedColumn != ${placeholder(dimension.name)})" - (sql, List(value)) - - case Atom.Binary(dimension, op, value) => - val operator = op match { - case Eq => "=" - case NotEq => "!=" - case Like => "like" - case Gt => ">" - case GtEq => ">=" - case Lt => "<" - case LtEq => "<=" - } - (s"${escapeDimension(dimension)} $operator ${placeholder(dimension.name)}", List(value)) - - case Atom.NAry(dimension, op, values) => - val sqlOp = op match { - case SearchFilterNAryOperation.In => "in" - case SearchFilterNAryOperation.NotIn => "not in" - } - - val bindings = ListBuffer[AnyRef]() - val sqlPlaceholder = placeholder(dimension.name) - val formattedValues = if (values.nonEmpty) { - values - .map { value => - bindings += value - sqlPlaceholder - } - .mkString(", ") - } else "NULL" - (s"${escapeDimension(dimension)} $sqlOp ($formattedValues)", bindings.toList) - - case Intersection(operands) => - val (sql, bindings) = filterToSqlMultiple(operands).unzip - (sql.mkString("(", " and ", ")"), bindings.flatten.toList) - - case Union(operands) => - val (sql, bindings) = filterToSqlMultiple(operands).unzip - (sql.mkString("(", " or ", ")"), bindings.flatten.toList) - } - } - - protected def limitToSql(): String - - /** - * @param escapedMainTableName Should be escaped - */ - protected def sortingToSql(escapedMainTableName: String, sorting: Sorting, namingStrategy: NamingStrategy): String = { - sorting match { - case Dimension(optSortingTableName, field, order) => - val sortingTableName = optSortingTableName.map(namingStrategy.table).getOrElse(escapedMainTableName) - val fullName = s"$sortingTableName.${namingStrategy.column(field)}" - - s"$fullName ${orderToSql(order)}" - - case Sequential(xs) => - xs.map(sortingToSql(escapedMainTableName, _, namingStrategy)).mkString(", ") - } - } - - protected def orderToSql(x: SortingOrder): String = x match { - case Ascending => "asc" - case Descending => "desc" - } - - protected def binder(bindings: List[AnyRef])(bind: PreparedStatement): PreparedStatement = { - bindings.zipWithIndex.foreach { - case (binding, index) => - bind.setObject(index + 1, binding) - } - - bind - } - -} - -final case class PostgresQueryBuilderParameters(tableData: QueryBuilder.TableData, - links: Map[String, TableLink] = Map.empty, - filter: SearchFilterExpr = SearchFilterExpr.Empty, - sorting: Sorting = Sorting.Empty, - pagination: Option[Pagination] = None) - extends QueryBuilderParameters { - - def limitToSql(): String = { - pagination.map { pagination => - val startFrom = (pagination.pageNumber - 1) * pagination.pageSize - s"limit ${pagination.pageSize} OFFSET $startFrom" - } getOrElse "" - } - -} - -/** - * @param links Links to another tables grouped by foreignTableName - */ -final case class MysqlQueryBuilderParameters(tableData: QueryBuilder.TableData, - links: Map[String, TableLink] = Map.empty, - filter: SearchFilterExpr = SearchFilterExpr.Empty, - sorting: Sorting = Sorting.Empty, - pagination: Option[Pagination] = None) - extends QueryBuilderParameters { - - def limitToSql(): String = - pagination - .map { pagination => - val startFrom = (pagination.pageNumber - 1) * pagination.pageSize - s"limit $startFrom, ${pagination.pageSize}" - } - .getOrElse("") - -} - -abstract class QueryBuilder[T, D <: SqlIdiom, N <: NamingStrategy](val parameters: QueryBuilderParameters)( - implicit runner: QueryBuilder.Runner[T], - countRunner: QueryBuilder.CountRunner) { - - def run: Seq[T] = runner(parameters) - - def runCount: QueryBuilder.CountResult = countRunner(parameters) - - /** - * Runs the query and returns total found rows without considering of pagination. - */ - def runWithCount: (Seq[T], Int, Option[LocalDateTime]) = { - val (total, lastUpdate) = runCount - (run, total, lastUpdate) - } - - def withFilter(newFilter: SearchFilterExpr): QueryBuilder[T, D, N] - - def withFilter(filter: Option[SearchFilterExpr]): QueryBuilder[T, D, N] = { - filter.fold(this)(withFilter) - } - - def resetFilter: QueryBuilder[T, D, N] = withFilter(SearchFilterExpr.Empty) - - def withSorting(newSorting: Sorting): QueryBuilder[T, D, N] - - def withSorting(sorting: Option[Sorting]): QueryBuilder[T, D, N] = { - sorting.fold(this)(withSorting) - } - - def resetSorting: QueryBuilder[T, D, N] = withSorting(Sorting.Empty) - - def withPagination(newPagination: Pagination): QueryBuilder[T, D, N] - - def withPagination(pagination: Option[Pagination]): QueryBuilder[T, D, N] = { - pagination.fold(this)(withPagination) - } - - def resetPagination: QueryBuilder[T, D, N] - -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/SlickQueryBuilder.scala b/src/main/scala/xyz/driver/pdsuicommon/db/SlickQueryBuilder.scala index dc03a52..7366151 100644 --- a/src/main/scala/xyz/driver/pdsuicommon/db/SlickQueryBuilder.scala +++ b/src/main/scala/xyz/driver/pdsuicommon/db/SlickQueryBuilder.scala @@ -70,7 +70,7 @@ sealed trait SlickQueryBuilderParameters { } def toSql(countQuery: Boolean = false)(implicit profile: JdbcProfile): SQLActionBuilder = { - toSql(countQuery, QueryBuilderParameters.AllFields) + toSql(countQuery, SlickQueryBuilderParameters.AllFields) } def toSql(countQuery: Boolean, fields: Set[String])(implicit profile: JdbcProfile): SQLActionBuilder = { diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/BridgeUploadQueueRepository.scala b/src/main/scala/xyz/driver/pdsuicommon/db/repositories/BridgeUploadQueueRepository.scala deleted file mode 100644 index 4c25afa..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/BridgeUploadQueueRepository.scala +++ /dev/null @@ -1,21 +0,0 @@ -package xyz.driver.pdsuicommon.db.repositories - -import xyz.driver.pdsuicommon.concurrent.BridgeUploadQueue -import xyz.driver.pdsuicommon.db.MysqlQueryBuilder - -trait BridgeUploadQueueRepository extends Repository { - - type EntityT = BridgeUploadQueue.Item - - def add(draft: EntityT): EntityT - - def getById(kind: String, tag: String): Option[EntityT] - - def getOne(kind: String): Option[BridgeUploadQueue.Item] - - def update(entity: EntityT): EntityT - - def delete(kind: String, tag: String): Unit - - def buildQuery: MysqlQueryBuilder[EntityT] -} diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/Repository.scala b/src/main/scala/xyz/driver/pdsuicommon/db/repositories/Repository.scala deleted file mode 100644 index d671e80..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/Repository.scala +++ /dev/null @@ -1,4 +0,0 @@ -package xyz.driver.pdsuicommon.db.repositories - -// For further usage and migration to Postgres and slick -trait Repository extends RepositoryLogging diff --git a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/RepositoryLogging.scala b/src/main/scala/xyz/driver/pdsuicommon/db/repositories/RepositoryLogging.scala deleted file mode 100644 index d1ec1da..0000000 --- a/src/main/scala/xyz/driver/pdsuicommon/db/repositories/RepositoryLogging.scala +++ /dev/null @@ -1,62 +0,0 @@ -package xyz.driver.pdsuicommon.db.repositories - -import xyz.driver.pdsuicommon.logging._ - -trait RepositoryLogging extends PhiLogging { - - protected def logCreatedOne[T](x: T)(implicit toPhiString: T => PhiString): T = { - logger.info(phi"An entity was created: $x") - x - } - - protected def logCreatedMultiple[T <: Iterable[_]](xs: T)(implicit toPhiString: T => PhiString): T = { - if (xs.nonEmpty) { - logger.info(phi"Entities were created: $xs") - } - xs - } - - protected def logUpdatedOne(rowsAffected: Long): Long = { - rowsAffected match { - case 0 => logger.trace(phi"The entity is up to date") - case 1 => logger.info(phi"The entity was updated") - case x => logger.warn(phi"The ${Unsafe(x)} entities were updated") - } - rowsAffected - } - - protected def logUpdatedOneUnimportant(rowsAffected: Long): Long = { - rowsAffected match { - case 0 => logger.trace(phi"The entity is up to date") - case 1 => logger.trace(phi"The entity was updated") - case x => logger.warn(phi"The ${Unsafe(x)} entities were updated") - } - rowsAffected - } - - protected def logUpdatedMultiple(rowsAffected: Long): Long = { - rowsAffected match { - case 0 => logger.trace(phi"All entities are up to date") - case x => logger.info(phi"The ${Unsafe(x)} entities were updated") - } - rowsAffected - } - - protected def logDeletedOne(rowsAffected: Long): Long = { - rowsAffected match { - case 0 => logger.trace(phi"The entity does not exist") - case 1 => logger.info(phi"The entity was deleted") - case x => logger.warn(phi"Deleted ${Unsafe(x)} entities, expected one") - } - rowsAffected - } - - protected def logDeletedMultiple(rowsAffected: Long): Long = { - rowsAffected match { - case 0 => logger.trace(phi"Entities do not exist") - case x => logger.info(phi"Deleted ${Unsafe(x)} entities") - } - rowsAffected - } - -} diff --git a/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala b/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala index 7c9d8c4..29e7610 100644 --- a/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala +++ b/src/test/scala/xyz/driver/pdsuicommon/BaseSuite.scala @@ -5,15 +5,12 @@ 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"), @@ -23,13 +20,4 @@ trait BaseSuite extends FreeSpecLike with DiffUtils with ScalaFutures { 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 index 51d39e5..699020c 100644 --- a/src/test/scala/xyz/driver/pdsuicommon/Mocks.scala +++ b/src/test/scala/xyz/driver/pdsuicommon/Mocks.scala @@ -6,7 +6,7 @@ import java.sql.Connection import java.util.logging.Logger import javax.sql.DataSource -import com.typesafe.config.ConfigFactory +import xyz.driver.pdsuicommon.db.SlickQueryBuilder.TableData import xyz.driver.pdsuicommon.db._ import xyz.driver.pdsuicommon.http.HttpFetcher @@ -27,32 +27,7 @@ class MockDataSource extends DataSource with Closeable { 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) { +class MockFactory()(implicit val sqlContext: PostgresContext) { val MockHttpFetcher: HttpFetcher = { (url: URL) => Future.successful(Array.empty[Byte]) } @@ -61,28 +36,26 @@ class MockFactory()(implicit val sqlContext: MySqlContext) { object MockQueryBuilder { type MockRunnerIn = (SearchFilterExpr, Sorting, Option[Pagination]) - type MockRunnerOut[T] = Seq[T] - type MockCountRunnerOut = QueryBuilder.CountResult + type MockRunnerOut[T] = Future[Seq[T]] + type MockCountRunnerOut = SlickQueryBuilder.CountResult def apply[T](matcher: PartialFunction[MockRunnerIn, MockRunnerOut[T]])( countMatcher: PartialFunction[MockRunnerIn, MockCountRunnerOut])( - implicit context: MySqlContext): MysqlQueryBuilder[T] = { + implicit context: PostgresContext): SlickQueryBuilder[T] = { - val runner: QueryBuilder.Runner[T] = { parameters => + val runner: SlickQueryBuilder.Runner[T] = { parameters => matcher((parameters.filter, parameters.sorting, parameters.pagination)) } - val countRunner: QueryBuilder.CountRunner = { parameters => + val countRunner: SlickQueryBuilder.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 + val parameters = SlickPostgresQueryBuilderParameters( + databaseName = "test", + tableData = TableData("", None, Set.empty[String]), + links = Map.empty ) + new SlickPostgresQueryBuilder(parameters)(runner, 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) - } - - } - } - -} -- cgit v1.2.3