diff --git a/build.gradle.kts b/build.gradle.kts index af46665d..3eeb777f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,28 +7,28 @@ val dialogmeldingVersion = "1.5d21db9" val fellesformat2Version = "1.0329dd1" val flywayVersion = "10.17.3" val hikariVersion = "5.1.0" -val jacksonVersion = "2.17.2" +val jacksonVersion = "2.18.2" val jaxbVersion = "2.3.1" val jsonVersion = "20240303" val kafkaVersion = "3.7.0" val kithApprecVersion = "2019.07.30-04-23-2a0d1388209441ec05d2e92a821eed4f796a3ae2" val kithHodemeldingVersion = "2019.07.30-12-26-5c924ef4f04022bbb850aaf299eb8e4464c1ca6a" val kluentVersion = "1.73" -val ktorVersion = "2.3.12" -val logbackVersion = "1.5.6" +val ktorVersion = "3.0.2" +val logbackVersion = "1.5.12" val logstashEncoderVersion = "7.4" val micrometerRegistryVersion = "1.12.7" -val mockkVersion = "1.13.9" +val mockkVersion = "1.13.13" val mqVersion = "9.3.4.1" -val nimbusjosejwtVersion = "9.40" +val nimbusjosejwtVersion = "9.47" val postgresVersion = "42.7.4" -val postgresEmbeddedVersion = "2.0.7" +val postgresEmbeddedVersion = "2.1.0" val spekVersion = "2.0.19" val syfotjenesterVersion = "1.2021.06.09-13.09-b3d30de9996e" plugins { - kotlin("jvm") version "2.0.20" - id("com.gradleup.shadow") version "8.3.2" + kotlin("jvm") version "2.1.0" + id("com.gradleup.shadow") version "8.3.5" id("org.jlleitschuh.gradle.ktlint") version "11.4.2" } diff --git a/src/main/kotlin/no/nav/syfo/App.kt b/src/main/kotlin/no/nav/syfo/App.kt index 4a82a958..4397ee2a 100644 --- a/src/main/kotlin/no/nav/syfo/App.kt +++ b/src/main/kotlin/no/nav/syfo/App.kt @@ -94,15 +94,22 @@ fun main() { lateinit var dialogmeldingToBehandlerService: DialogmeldingToBehandlerService lateinit var dialogmeldingStatusService: DialogmeldingStatusService - val applicationEngineEnvironment = applicationEngineEnvironment { + val applicationEngineEnvironment = applicationEnvironment { log = logger config = HoconApplicationConfig(ConfigFactory.load()) - - connector { - port = applicationPort - } - - module { + } + val server = embeddedServer( + factory = Netty, + environment = applicationEngineEnvironment, + configure = { + connector { + port = applicationPort + } + connectionGroupSize = 8 + workerGroupSize = 8 + callGroupSize = 16 + }, + module = { databaseModule(environment = environment) behandlerService = BehandlerService( @@ -130,91 +137,81 @@ fun main() { dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, veilederTilgangskontrollClient = veilederTilgangskontrollClient, ) - } - } - - applicationEngineEnvironment.monitor.subscribe(ApplicationStarted) { - applicationState.ready = true - logger.info("Application is ready, running Java VM ${Runtime.version()}") - launchKafkaTaskDialogmeldingBestilling( - applicationState = applicationState, - applicationEnvironmentKafka = environment.kafka, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - ) - val dialogmeldingService = DialogmeldingService( - pdlClient = pdlClient, - mqSender = mqSender, - ) - cronjobModule( - applicationState = applicationState, - environment = environment, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - dialogmeldingService = dialogmeldingService, - dialogmeldingStatusService = dialogmeldingStatusService, - behandlerService = behandlerService, - partnerinfoClient = partnerinfoClient, - legeSuspensjonClient = legeSuspensjonClient, - fastlegeClient = fastlegeClient, - syfohelsenettproxyClient = syfohelsenettproxyClient, - ) - launchKafkaTaskSykmelding( - applicationState = applicationState, - applicationEnvironmentKafka = environment.kafka, - behandlerService = behandlerService, - ) - launchKafkaTaskDialogmeldingFromBehandler( - applicationState = applicationState, - applicationEnvironmentKafka = environment.kafka, - database = applicationDatabase, - ) - launchBackgroundTask( - applicationState = applicationState, - ) { - val factory = connectionFactory(environment) - - factory.createConnection( - environment.serviceuserUsername, - environment.serviceuserPassword, - ).use { connection -> - connection.start() - val session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE) - val inputconsumer = session.consumerForQueue(environment.apprecQueueName) - val apprecService = ApprecService( + monitor.subscribe(ApplicationStarted) { + applicationState.ready = true + logger.info("Application is ready, running Java VM ${Runtime.version()}") + launchKafkaTaskDialogmeldingBestilling( + applicationState = applicationState, + applicationEnvironmentKafka = environment.kafka, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + ) + val dialogmeldingService = DialogmeldingService( + pdlClient = pdlClient, + mqSender = mqSender, + ) + cronjobModule( + applicationState = applicationState, + environment = environment, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + dialogmeldingService = dialogmeldingService, + dialogmeldingStatusService = dialogmeldingStatusService, + behandlerService = behandlerService, + partnerinfoClient = partnerinfoClient, + legeSuspensjonClient = legeSuspensjonClient, + fastlegeClient = fastlegeClient, + syfohelsenettproxyClient = syfohelsenettproxyClient, + ) + launchKafkaTaskSykmelding( + applicationState = applicationState, + applicationEnvironmentKafka = environment.kafka, + behandlerService = behandlerService, + ) + launchKafkaTaskDialogmeldingFromBehandler( + applicationState = applicationState, + applicationEnvironmentKafka = environment.kafka, database = applicationDatabase, ) - val blockingApplicationRunner = ApprecConsumer( + launchBackgroundTask( applicationState = applicationState, + ) { + val factory = connectionFactory(environment) + + factory.createConnection( + environment.serviceuserUsername, + environment.serviceuserPassword, + ).use { connection -> + connection.start() + val session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE) + val inputconsumer = session.consumerForQueue(environment.apprecQueueName) + val apprecService = ApprecService( + database = applicationDatabase, + ) + val blockingApplicationRunner = ApprecConsumer( + applicationState = applicationState, + database = applicationDatabase, + inputconsumer = inputconsumer, + apprecService = apprecService, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + ) + blockingApplicationRunner.run() + } + } + val identhendelseService = IdenthendelseService( database = applicationDatabase, - inputconsumer = inputconsumer, - apprecService = apprecService, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + pdlClient = pdlClient, + ) + val identhendelseConsumerService = IdenthendelseConsumerService( + identhendelseService = identhendelseService, + ) + + launchKafkaTaskIdenthendelse( + applicationState = applicationState, + applicationEnvironmentKafka = environment.kafka, + kafkaIdenthendelseConsumerService = identhendelseConsumerService, ) - blockingApplicationRunner.run() } } - val identhendelseService = IdenthendelseService( - database = applicationDatabase, - pdlClient = pdlClient, - ) - val identhendelseConsumerService = IdenthendelseConsumerService( - identhendelseService = identhendelseService, - ) - - launchKafkaTaskIdenthendelse( - applicationState = applicationState, - applicationEnvironmentKafka = environment.kafka, - kafkaIdenthendelseConsumerService = identhendelseConsumerService, - ) - } - - val server = embeddedServer( - factory = Netty, - environment = applicationEngineEnvironment, - ) { - connectionGroupSize = 8 - workerGroupSize = 8 - callGroupSize = 16 - } + ) Runtime.getRuntime().addShutdownHook( Thread { diff --git a/src/main/kotlin/no/nav/syfo/behandler/api/access/VeilederAPIAccessPipeline.kt b/src/main/kotlin/no/nav/syfo/behandler/api/access/VeilederAPIAccessPipeline.kt index 67baae7e..e1c11ece 100644 --- a/src/main/kotlin/no/nav/syfo/behandler/api/access/VeilederAPIAccessPipeline.kt +++ b/src/main/kotlin/no/nav/syfo/behandler/api/access/VeilederAPIAccessPipeline.kt @@ -1,13 +1,12 @@ package no.nav.syfo.behandler.api.access -import io.ktor.server.application.* -import io.ktor.util.pipeline.* +import io.ktor.server.routing.* import no.nav.syfo.client.veiledertilgang.VeilederTilgangskontrollClient import no.nav.syfo.domain.Personident import no.nav.syfo.util.getBearerHeader import no.nav.syfo.util.getCallId -suspend fun PipelineContext.validateVeilederAccess( +suspend fun RoutingContext.validateVeilederAccess( action: String, personidentToAccess: Personident, veilederTilgangskontrollClient: VeilederTilgangskontrollClient, diff --git a/src/main/kotlin/no/nav/syfo/util/RequestUtil.kt b/src/main/kotlin/no/nav/syfo/util/RequestUtil.kt index d05032b7..dca7f00a 100644 --- a/src/main/kotlin/no/nav/syfo/util/RequestUtil.kt +++ b/src/main/kotlin/no/nav/syfo/util/RequestUtil.kt @@ -2,13 +2,14 @@ package no.nav.syfo.util import io.ktor.server.application.* import io.ktor.http.* +import io.ktor.server.routing.* import io.ktor.util.pipeline.* import net.logstash.logback.argument.StructuredArguments const val NAV_CALL_ID_HEADER = "Nav-Call-Id" const val NAV_PERSONIDENT_HEADER = "nav-personident" -fun PipelineContext.getCallId(): String { +fun RoutingContext.getCallId(): String { return this.call.getCallId() } fun ApplicationCall.getCallId(): String { @@ -17,16 +18,16 @@ fun ApplicationCall.getCallId(): String { fun callIdArgument(callId: String) = StructuredArguments.keyValue("callId", callId)!! -fun PipelineContext.getBearerHeader(): String? { +fun RoutingContext.getBearerHeader(): String? { return this.call.request.headers[HttpHeaders.Authorization]?.removePrefix("Bearer ") } -fun PipelineContext.getPersonidentHeader(): String? { +fun RoutingContext.getPersonidentHeader(): String? { return this.call.request.headers[NAV_PERSONIDENT_HEADER] } -suspend fun PipelineContext.withValidToken( - block: suspend PipelineContext.() -> Unit +suspend fun RoutingContext.withValidToken( + block: suspend RoutingContext.() -> Unit ) { if (getBearerHeader() != null) { block() diff --git a/src/test/kotlin/no/nav/syfo/application/api/OppfolgingsplanSystemApiSpek.kt b/src/test/kotlin/no/nav/syfo/application/api/OppfolgingsplanSystemApiSpek.kt index 19c900de..f6cb9ada 100644 --- a/src/test/kotlin/no/nav/syfo/application/api/OppfolgingsplanSystemApiSpek.kt +++ b/src/test/kotlin/no/nav/syfo/application/api/OppfolgingsplanSystemApiSpek.kt @@ -1,144 +1,141 @@ package no.nav.syfo.application.api -import com.fasterxml.jackson.databind.ObjectMapper +import io.ktor.client.request.* import io.ktor.http.* import io.ktor.server.testing.* -import io.mockk.* +import io.mockk.mockk +import io.mockk.verify import no.nav.syfo.api.sendOppfolgingsplanPath import no.nav.syfo.application.mq.MQSender import no.nav.syfo.dialogmelding.bestilling.database.getDialogmeldingToBehandlerBestillingNotSendt import no.nav.syfo.dialogmelding.bestilling.domain.DialogmeldingType import no.nav.syfo.testhelper.* -import no.nav.syfo.testhelper.generator.* -import no.nav.syfo.util.bearerHeader -import no.nav.syfo.util.configuredJacksonMapper -import org.amshove.kluent.* +import no.nav.syfo.testhelper.generator.generateRSOppfolgingsplan +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class OppfolgingsplanSystemApiSpek : Spek({ - val objectMapper: ObjectMapper = configuredJacksonMapper() val mqSender = mockk(relaxed = true) + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val validToken = generateJWTSystem( + audience = externalMockEnvironment.environment.aadAppClient, + azp = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, + ) - with(TestApplicationEngine()) { - start() - - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val validToken = generateJWTSystem( - audience = externalMockEnvironment.environment.aadAppClient, - azp = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, - ) - application.testApiModule( - externalMockEnvironment = externalMockEnvironment, - ) - - afterEachTest { - database.dropData() - } + afterEachTest { + database.dropData() + } - describe(OppfolgingsplanSystemApiSpek::class.java.simpleName) { - describe("Send oppfolgingsplan for person") { - val url = sendOppfolgingsplanPath - describe("Happy path") { - it("Skal lagre bestilling for oppfølgingsplan (men ikke sende)") { - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null - val rsOppfolgingsplan = generateRSOppfolgingsplan() - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(rsOppfolgingsplan)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } - val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() - storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name - storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr - storedBestilling.sendt shouldBe null + describe(OppfolgingsplanSystemApiSpek::class.java.simpleName) { + describe("Send oppfolgingsplan for person") { + val url = sendOppfolgingsplanPath + describe("Happy path") { + it("Skal lagre bestilling for oppfølgingsplan (men ikke sende)") { + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + val rsOppfolgingsplan = generateRSOppfolgingsplan() + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(rsOppfolgingsplan) } + + response.status shouldBeEqualTo HttpStatusCode.OK + verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } + val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() + storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name + storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr + storedBestilling.sendt shouldBe null } - it("Skal lagre bestilling for oppfølgingsplan når bare vikar for fastlege finnes") { - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null - val rsOppfolgingsplan = generateRSOppfolgingsplan( - arbeidstakerPersonIdent = UserConstants.ARBEIDSTAKER_MED_VIKARFASTLEGE, - ) - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(rsOppfolgingsplan)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() - storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name - storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr + } + it("Skal lagre bestilling for oppfølgingsplan når bare vikar for fastlege finnes") { + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + val rsOppfolgingsplan = generateRSOppfolgingsplan( + arbeidstakerPersonIdent = UserConstants.ARBEIDSTAKER_MED_VIKARFASTLEGE, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(rsOppfolgingsplan) } + + response.status shouldBeEqualTo HttpStatusCode.OK + val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() + storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name + storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr } } - describe("Unhappy paths") { - it("should return error for arbeidstaker with no fastlege or vikar") { - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan(UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR))) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.NotFound - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + } + describe("Unhappy paths") { + it("should return error for arbeidstaker with no fastlege or vikar") { + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan(UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR)) } + + response.status shouldBeEqualTo HttpStatusCode.NotFound + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } + } - it("should return status Unauthorized if no token is supplied") { - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Unauthorized - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + it("should return status Unauthorized if no token is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan(UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR)) } + + response.status shouldBeEqualTo HttpStatusCode.Unauthorized + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } - it("should return status BadRequest if no ClientId is supplied") { - val tokenNoClientId = generateJWTIdporten( - audience = externalMockEnvironment.environment.aadAppClient, - clientId = null, - issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, - ) - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenNoClientId)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + } + it("should return status BadRequest if no ClientId is supplied") { + val tokenNoClientId = generateJWTIdporten( + audience = externalMockEnvironment.environment.aadAppClient, + clientId = null, + issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, + ) + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenNoClientId) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } - } - it("should return status Forbidden if unauthorized ClientId is supplied") { - val tokenUnauthorizedClientId = generateJWTSystem( - audience = externalMockEnvironment.environment.aadAppClient, - azp = "app", - issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, - ) + response.status shouldBeEqualTo HttpStatusCode.BadRequest + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + } + } - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenUnauthorizedClientId)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Forbidden - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + it("should return status Forbidden if unauthorized ClientId is supplied") { + val tokenUnauthorizedClientId = generateJWTSystem( + audience = externalMockEnvironment.environment.aadAppClient, + azp = "app", + issuer = externalMockEnvironment.wellKnownInternalAzureAD.issuer, + ) + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenUnauthorizedClientId) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.Forbidden + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } } } diff --git a/src/test/kotlin/no/nav/syfo/application/api/PodApiSpek.kt b/src/test/kotlin/no/nav/syfo/application/api/PodApiSpek.kt index 3808a76b..bb6f1c3d 100644 --- a/src/test/kotlin/no/nav/syfo/application/api/PodApiSpek.kt +++ b/src/test/kotlin/no/nav/syfo/application/api/PodApiSpek.kt @@ -1,9 +1,12 @@ package no.nav.syfo.application.api +import io.ktor.client.request.* +import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.routing.* import io.ktor.server.testing.* import no.nav.syfo.application.ApplicationState +import no.nav.syfo.application.database.DatabaseInterface import no.nav.syfo.testhelper.TestDatabase import no.nav.syfo.testhelper.TestDatabaseNotResponding import org.amshove.kluent.shouldBeEqualTo @@ -13,91 +16,95 @@ import org.spekframework.spek2.style.specification.describe object PodApiSpek : Spek({ - describe("Successful liveness and readiness checks") { - with(TestApplicationEngine()) { - start() - val database = TestDatabase() - application.routing { + fun ApplicationTestBuilder.setupPodApi(database: DatabaseInterface, applicationState: ApplicationState) { + application { + routing { registerPodApi( - ApplicationState( - alive = true, - ready = true - ), + applicationState = applicationState, database = database, ) } + } + } - it("Returns ok on is_alive") { - with(handleRequest(HttpMethod.Get, "/is_alive")) { - response.status()?.isSuccess() shouldBeEqualTo true - response.content shouldNotBeEqualTo null - } + describe("Successful liveness and readiness checks") { + val database = TestDatabase() + + it("Returns ok on is_alive") { + testApplication { + setupPodApi( + database = database, + applicationState = ApplicationState(alive = true, ready = true), + ) + val response = client.get("/is_alive") + response.status.isSuccess() shouldBeEqualTo true + response.bodyAsText() shouldNotBeEqualTo null } - it("Returns ok on is_alive") { - with(handleRequest(HttpMethod.Get, "/is_ready")) { - println(response.status()) - response.status()?.isSuccess() shouldBeEqualTo true - response.content shouldNotBeEqualTo null - } + } + it("Returns ok on is_ready") { + testApplication { + setupPodApi( + database = database, + applicationState = ApplicationState(alive = true, ready = true), + ) + val response = client.get("/is_ready") + response.status.isSuccess() shouldBeEqualTo true + response.bodyAsText() shouldNotBeEqualTo null } } } describe("Unsuccessful liveness and readiness checks") { - with(TestApplicationEngine()) { - start() - val database = TestDatabase() - application.routing { - registerPodApi( - ApplicationState( - alive = false, - ready = false - ), + val database = TestDatabase() + it("Returns internal server error when liveness check fails") { + testApplication { + setupPodApi( database = database, + applicationState = ApplicationState(alive = false, ready = true), ) + val response = client.get("/is_alive") + response.status shouldBeEqualTo HttpStatusCode.InternalServerError + response.bodyAsText() shouldNotBeEqualTo null } + } - it("Returns internal server error when liveness check fails") { - with(handleRequest(HttpMethod.Get, "/is_alive")) { - response.status() shouldBeEqualTo HttpStatusCode.InternalServerError - response.content shouldNotBeEqualTo null - } - } - - it("Returns internal server error when readiness check fails") { - with(handleRequest(HttpMethod.Get, "/is_ready")) { - response.status() shouldBeEqualTo HttpStatusCode.InternalServerError - response.content shouldNotBeEqualTo null - } + it("Returns internal server error when readiness check fails") { + testApplication { + setupPodApi( + database = database, + applicationState = ApplicationState(alive = true, ready = false), + ) + val response = client.get("/is_ready") + response.status shouldBeEqualTo HttpStatusCode.InternalServerError + response.bodyAsText() shouldNotBeEqualTo null } } } + describe("Successful liveness and unsuccessful readiness checks when database not working") { - with(TestApplicationEngine()) { - start() - val database = TestDatabaseNotResponding() - application.routing { - registerPodApi( - applicationState = ApplicationState( - alive = true, - ready = true, - ), + val database = TestDatabaseNotResponding() + + it("Returns ok on is_alive") { + testApplication { + setupPodApi( database = database, + applicationState = ApplicationState(alive = true, ready = true), ) + val response = client.get("/is_alive") + response.status.isSuccess() shouldBeEqualTo true + response.bodyAsText() shouldNotBeEqualTo null } + } - it("Returns ok on is_alive") { - with(handleRequest(HttpMethod.Get, "/is_alive")) { - response.status()?.isSuccess() shouldBeEqualTo true - response.content shouldNotBeEqualTo null - } - } - - it("Returns internal server error when readiness check fails") { - with(handleRequest(HttpMethod.Get, "/is_ready")) { - response.status() shouldBeEqualTo HttpStatusCode.InternalServerError - response.content shouldNotBeEqualTo null - } + it("Returns internal server error when readiness check fails") { + testApplication { + setupPodApi( + database = database, + applicationState = ApplicationState(alive = true, ready = true), + ) + val response = client.get("/is_ready") + response.status shouldBeEqualTo HttpStatusCode.InternalServerError + response.bodyAsText() shouldNotBeEqualTo null } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/BehandlerServiceSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/BehandlerServiceSpek.kt index b9d6e50e..187935f4 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/BehandlerServiceSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/BehandlerServiceSpek.kt @@ -1,241 +1,137 @@ package no.nav.syfo.behandler -import io.ktor.server.testing.* -import io.mockk.* -import no.nav.syfo.behandler.database.* +import io.mockk.clearMocks +import io.mockk.mockk import no.nav.syfo.behandler.database.domain.toBehandler import no.nav.syfo.behandler.database.getBehandlerByArbeidstaker +import no.nav.syfo.behandler.database.getBehandlerKontorById +import no.nav.syfo.behandler.database.updateBehandlerKontorDialogmeldingEnabled +import no.nav.syfo.behandler.database.updateBehandlerKontorSystem +import no.nav.syfo.behandler.domain.Arbeidstaker +import no.nav.syfo.behandler.domain.BehandlerArbeidstakerRelasjonstype +import no.nav.syfo.behandler.domain.BehandlerKontor import no.nav.syfo.behandler.fastlege.FastlegeClient -import no.nav.syfo.behandler.domain.* import no.nav.syfo.behandler.fastlege.toBehandler import no.nav.syfo.behandler.partnerinfo.PartnerinfoClient import no.nav.syfo.testhelper.* import no.nav.syfo.testhelper.generator.generateFastlegeResponse -import org.amshove.kluent.* -import org.junit.Assert.assertThrows +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldNotBeEqualTo +import org.junit.jupiter.api.Assertions.assertThrows import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.OffsetDateTime class BehandlerServiceSpek : Spek({ describe("BehandlerService") { - with(TestApplicationEngine()) { - start() + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val fastlegeClientMock = mockk() + val partnerinfoClientMock = mockk() + val behandlerService = BehandlerService( + fastlegeClient = fastlegeClientMock, + partnerinfoClient = partnerinfoClientMock, + database = database, + ) - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val fastlegeClientMock = mockk() - val partnerinfoClientMock = mockk() - val behandlerService = BehandlerService( - fastlegeClient = fastlegeClientMock, - partnerinfoClient = partnerinfoClientMock, - database = database, + afterEachTest { + database.dropData() + clearMocks( + fastlegeClientMock, + partnerinfoClientMock, ) + } - afterEachTest { - database.dropData() - clearMocks( - fastlegeClientMock, - partnerinfoClientMock, - ) - } - - describe("createOrGetBehandler") { - it("lagrer behandler for arbeidstaker") { - val behandler = - behandlerService.createOrGetBehandler( - generateFastlegeResponse().toBehandler(UserConstants.PARTNERID), - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - pBehandlerList[0].behandlerRef shouldBeEqualTo behandler.behandlerRef - val pBehandlerKontor = database.getBehandlerKontorById(pBehandlerList[0].kontorId) - pBehandlerKontor.dialogmeldingEnabled shouldNotBeEqualTo null - } - it("lagrer behandler for arbeidstaker og setter dialogmeldingEnabled senere") { - val behandler = - behandlerService.createOrGetBehandler( - generateFastlegeResponse().toBehandler( - partnerId = UserConstants.PARTNERID, - dialogmeldingEnabled = false, - ), - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - val pBehandler = pBehandlerList[0] - val behandlerFromDB = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) - behandlerFromDB.behandlerRef shouldBeEqualTo behandler.behandlerRef - behandlerFromDB.kontor.dialogmeldingEnabled shouldBeEqualTo false - - database.updateBehandlerKontorDialogmeldingEnabled(behandlerFromDB.kontor.partnerId) - - val behandlerFromDBUpdated = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) - behandlerFromDBUpdated.behandlerRef shouldBeEqualTo behandler.behandlerRef - behandlerFromDBUpdated.kontor.dialogmeldingEnabled shouldBeEqualTo true - } - it("Oppdaterer telefonnr på eksisterende behandler når telefonnr endret") { - val behandler = - behandlerService.createOrGetBehandler( - generateFastlegeResponse().toBehandler( - partnerId = UserConstants.PARTNERID, - dialogmeldingEnabled = false, - ), - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - pBehandlerList[0].telefon shouldBeEqualTo "" + describe("createOrGetBehandler") { + it("lagrer behandler for arbeidstaker") { + val behandler = behandlerService.createOrGetBehandler( - behandler.copy(telefon = "987654321"), + generateFastlegeResponse().toBehandler(UserConstants.PARTNERID), Arbeidstaker( arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, mottatt = OffsetDateTime.now(), ), relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - val pBehandlerListUpdated = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerListUpdated.size shouldBeEqualTo 1 - pBehandlerListUpdated[0].telefon shouldBeEqualTo "987654321" - } - it("lagrer behandler for arbeidstaker og setter system senere") { - val behandler = - behandlerService.createOrGetBehandler( - generateFastlegeResponse().toBehandler( - partnerId = UserConstants.PARTNERID, - dialogmeldingEnabled = false, - ), - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - val pBehandler = pBehandlerList[0] - val behandlerFromDB = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) - behandlerFromDB.behandlerRef shouldBeEqualTo behandler.behandlerRef - behandlerFromDB.kontor.system shouldBe null - - database.connection.use { - it.updateBehandlerKontorSystem( - partnerId = behandlerFromDB.kontor.partnerId, - kontor = BehandlerKontor( - partnerId = behandlerFromDB.kontor.partnerId, - herId = behandlerFromDB.kontor.herId, - navn = behandlerFromDB.kontor.navn, - adresse = behandlerFromDB.kontor.adresse, - postnummer = behandlerFromDB.kontor.postnummer, - poststed = behandlerFromDB.kontor.poststed, - orgnummer = behandlerFromDB.kontor.orgnummer, - dialogmeldingEnabled = behandlerFromDB.kontor.dialogmeldingEnabled, - dialogmeldingEnabledLocked = behandlerFromDB.kontor.dialogmeldingEnabledLocked, - system = "EPJ-systemet", - mottatt = OffsetDateTime.now(), - ), - ) - it.commit() - } - val behandlerFromDBUpdated = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) - behandlerFromDBUpdated.behandlerRef shouldBeEqualTo behandler.behandlerRef - behandlerFromDBUpdated.kontor.system shouldBeEqualTo "EPJ-systemet" - } - it("lagrer behandler for arbeidstaker én gang når kalt flere ganger for samme behandler og arbeidstaker") { - val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + pBehandlerList[0].behandlerRef shouldBeEqualTo behandler.behandlerRef + val pBehandlerKontor = database.getBehandlerKontorById(pBehandlerList[0].kontorId) + pBehandlerKontor.dialogmeldingEnabled shouldNotBeEqualTo null + } + it("lagrer behandler for arbeidstaker og setter dialogmeldingEnabled senere") { + val behandler = behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), + generateFastlegeResponse().toBehandler( + partnerId = UserConstants.PARTNERID, + dialogmeldingEnabled = false, ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - behandlerService.createOrGetBehandler( - behandler, Arbeidstaker( arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, mottatt = OffsetDateTime.now(), ), relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - } - it("oppretter ikke duplikate koblinger til arbeidstaker for suspendert behandler") { - val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + val pBehandler = pBehandlerList[0] + val behandlerFromDB = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) + behandlerFromDB.behandlerRef shouldBeEqualTo behandler.behandlerRef + behandlerFromDB.kontor.dialogmeldingEnabled shouldBeEqualTo false + + database.updateBehandlerKontorDialogmeldingEnabled(behandlerFromDB.kontor.partnerId) + + val behandlerFromDBUpdated = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) + behandlerFromDBUpdated.behandlerRef shouldBeEqualTo behandler.behandlerRef + behandlerFromDBUpdated.kontor.dialogmeldingEnabled shouldBeEqualTo true + } + it("Oppdaterer telefonnr på eksisterende behandler når telefonnr endret") { + val behandler = behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), + generateFastlegeResponse().toBehandler( + partnerId = UserConstants.PARTNERID, + dialogmeldingEnabled = false, ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - val pBehandlerListBefore = database.getBehandlerArbeidstakerRelasjoner( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerListBefore.size shouldBeEqualTo 1 - behandlerService.updateBehandlerSuspensjon(behandler.personident!!, true) - behandlerService.createOrGetBehandler( - behandler, Arbeidstaker( arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, mottatt = OffsetDateTime.now(), ), relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - val pBehandlerListAfter = database.getBehandlerArbeidstakerRelasjoner( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerListAfter.size shouldBeEqualTo 1 - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 0 - } - it("lagrer én behandler koblet til begge arbeidstakere når kalt for to ulike arbeidstakere med samme behandler") { - val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + pBehandlerList[0].telefon shouldBeEqualTo "" + behandlerService.createOrGetBehandler( + behandler.copy(telefon = "987654321"), + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val pBehandlerListUpdated = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerListUpdated.size shouldBeEqualTo 1 + pBehandlerListUpdated[0].telefon shouldBeEqualTo "987654321" + } + it("lagrer behandler for arbeidstaker og setter system senere") { + val behandler = behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ANNEN_ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), + generateFastlegeResponse().toBehandler( + partnerId = UserConstants.PARTNERID, + dialogmeldingEnabled = false, ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - behandlerService.createOrGetBehandler( - behandler, Arbeidstaker( arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, mottatt = OffsetDateTime.now(), @@ -243,238 +139,344 @@ class BehandlerServiceSpek : Spek({ relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - val pBehandlerForAnnenArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ANNEN_ARBEIDSTAKER_FNR, - ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 - pBehandlerForAnnenArbeidstakerList.size shouldBeEqualTo 1 - pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo pBehandlerForAnnenArbeidstakerList[0].behandlerRef - } - it("lagrer behandler uten fnr") { - val behandler = - generateFastlegeResponse(null, UserConstants.HERID, UserConstants.HPRID).toBehandler(UserConstants.PARTNERID) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + val pBehandler = pBehandlerList[0] + val behandlerFromDB = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) + behandlerFromDB.behandlerRef shouldBeEqualTo behandler.behandlerRef + behandlerFromDB.kontor.system shouldBe null - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ).size shouldBeEqualTo 1 - } - it("lagrer behandler uten herId") { - val behandler = - generateFastlegeResponse( - UserConstants.FASTLEGE_FNR, - null, - UserConstants.HPRID - ).toBehandler(UserConstants.PARTNERID) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + database.connection.use { + it.updateBehandlerKontorSystem( + partnerId = behandlerFromDB.kontor.partnerId, + kontor = BehandlerKontor( + partnerId = behandlerFromDB.kontor.partnerId, + herId = behandlerFromDB.kontor.herId, + navn = behandlerFromDB.kontor.navn, + adresse = behandlerFromDB.kontor.adresse, + postnummer = behandlerFromDB.kontor.postnummer, + poststed = behandlerFromDB.kontor.poststed, + orgnummer = behandlerFromDB.kontor.orgnummer, + dialogmeldingEnabled = behandlerFromDB.kontor.dialogmeldingEnabled, + dialogmeldingEnabledLocked = behandlerFromDB.kontor.dialogmeldingEnabledLocked, + system = "EPJ-systemet", mottatt = OffsetDateTime.now(), ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ).size shouldBeEqualTo 1 + it.commit() } - it("lagrer behandler uten hprId") { - val behandler = - generateFastlegeResponse( - UserConstants.FASTLEGE_FNR, - UserConstants.HERID, - null - ).toBehandler(UserConstants.PARTNERID) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ).size shouldBeEqualTo 1 - } - it("lagrer ikke behandler uten fnr, herId og hprId") { - val behandler = - generateFastlegeResponse(null, null, null).toBehandler(UserConstants.PARTNERID) + val behandlerFromDBUpdated = pBehandler.toBehandler(database.getBehandlerKontorById(pBehandler.kontorId)) + behandlerFromDBUpdated.behandlerRef shouldBeEqualTo behandler.behandlerRef + behandlerFromDBUpdated.kontor.system shouldBeEqualTo "EPJ-systemet" + } + it("lagrer behandler for arbeidstaker én gang når kalt flere ganger for samme behandler og arbeidstaker") { + val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + } + it("oppretter ikke duplikate koblinger til arbeidstaker for suspendert behandler") { + val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val pBehandlerListBefore = database.getBehandlerArbeidstakerRelasjoner( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerListBefore.size shouldBeEqualTo 1 + behandlerService.updateBehandlerSuspensjon(behandler.personident!!, true) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val pBehandlerListAfter = database.getBehandlerArbeidstakerRelasjoner( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerListAfter.size shouldBeEqualTo 1 + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 0 + } + it("lagrer én behandler koblet til begge arbeidstakere når kalt for to ulike arbeidstakere med samme behandler") { + val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ANNEN_ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - assertThrows(IllegalArgumentException::class.java) { - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - } - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ).size shouldBeEqualTo 0 - } - it("lagrer ikke behandler for arbeidstaker når samme behandler er siste lagrede behandler for arbeidstaker") { - val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) - val existingBehandlerRef = - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR - ) + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + val pBehandlerForAnnenArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ANNEN_ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 + pBehandlerForAnnenArbeidstakerList.size shouldBeEqualTo 1 + pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo pBehandlerForAnnenArbeidstakerList[0].behandlerRef + } + it("lagrer behandler uten fnr") { + val behandler = + generateFastlegeResponse(null, UserConstants.HERID, UserConstants.HPRID).toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ).size shouldBeEqualTo 1 + } + it("lagrer behandler uten herId") { + val behandler = + generateFastlegeResponse( + UserConstants.FASTLEGE_FNR, + null, + UserConstants.HPRID + ).toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 - pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo existingBehandlerRef - } - it("lagrer behandler for arbeidstaker når samme behandler er lagret for annen arbeidstaker") { - val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) - val existingBehandlerRef = - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ANNEN_ARBEIDSTAKER_FNR - ) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ).size shouldBeEqualTo 1 + } + it("lagrer behandler uten hprId") { + val behandler = + generateFastlegeResponse( + UserConstants.FASTLEGE_FNR, + UserConstants.HERID, + null + ).toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 - pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo existingBehandlerRef - } - it("lagrer behandler for arbeidstaker når fastlege er annen enn siste lagrede fastlege for arbeidstaker") { - val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) - val annenBehandler = - generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) - val existingBehandlerRef = - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR - ) + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ).size shouldBeEqualTo 1 + } + it("lagrer ikke behandler uten fnr, herId og hprId") { + val behandler = + generateFastlegeResponse(null, null, null).toBehandler(UserConstants.PARTNERID) + + assertThrows(IllegalArgumentException::class.java) { behandlerService.createOrGetBehandler( - behandler = annenBehandler, + behandler, Arbeidstaker( arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, mottatt = OffsetDateTime.now(), ), relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 2 - pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo existingBehandlerRef - pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo existingBehandlerRef } - it("lagrer behandler for arbeidstaker når fastlege er lagret for arbeidstaker men annen behandler er siste lagrede fastlege for arbeidstaker") { - val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) - val annenBehandler = - generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ).size shouldBeEqualTo 0 + } + it("lagrer ikke behandler for arbeidstaker når samme behandler er siste lagrede behandler for arbeidstaker") { + val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + val existingBehandlerRef = database.createBehandlerForArbeidstaker( behandler = behandler, arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR ) - database.createBehandlerForArbeidstaker( - behandler = annenBehandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR - ) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 3 - pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo behandler.behandlerRef - pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo annenBehandler.behandlerRef - pBehandlerForArbeidstakerList[2].behandlerRef shouldBeEqualTo behandler.behandlerRef - } - it("lagrer behandler for arbeidstaker når behandler har samme partnerId som annen behandler for annen arbeidstaker") { - val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) - val annenBehandler = - generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 + pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo existingBehandlerRef + } + it("lagrer behandler for arbeidstaker når samme behandler er lagret for annen arbeidstaker") { + val behandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + val existingBehandlerRef = database.createBehandlerForArbeidstaker( - behandler = annenBehandler, + behandler = behandler, arbeidstakerPersonident = UserConstants.ANNEN_ARBEIDSTAKER_FNR ) - behandlerService.createOrGetBehandler( - behandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 + pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo existingBehandlerRef + } + it("lagrer behandler for arbeidstaker når fastlege er annen enn siste lagrede fastlege for arbeidstaker") { + val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) + val annenBehandler = + generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) + val existingBehandlerRef = + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 - pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo annenBehandler.behandlerRef - } - it("lagrer behandler for arbeidstaker når samme behandler er lagret for arbeidstaker, men med annen partnerId") { - val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) - val sammeBehandlerAnnenPartnerId = - generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.OTHER_PARTNERID) - val existingBehandlerRef = - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR - ) + behandlerService.createOrGetBehandler( + behandler = annenBehandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - behandlerService.createOrGetBehandler( - behandler = sammeBehandlerAnnenPartnerId, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 2 + pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo existingBehandlerRef + pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo existingBehandlerRef + } + it("lagrer behandler for arbeidstaker når fastlege er lagret for arbeidstaker men annen behandler er siste lagrede fastlege for arbeidstaker") { + val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) + val annenBehandler = + generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR + ) + database.createBehandlerForArbeidstaker( + behandler = annenBehandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR + ) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) - val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 3 + pBehandlerForArbeidstakerList[0].behandlerRef shouldBeEqualTo behandler.behandlerRef + pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo annenBehandler.behandlerRef + pBehandlerForArbeidstakerList[2].behandlerRef shouldBeEqualTo behandler.behandlerRef + } + it("lagrer behandler for arbeidstaker når behandler har samme partnerId som annen behandler for annen arbeidstaker") { + val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) + val annenBehandler = + generateFastlegeResponse(UserConstants.FASTLEGE_ANNEN_FNR).toBehandler(UserConstants.PARTNERID) + database.createBehandlerForArbeidstaker( + behandler = annenBehandler, + arbeidstakerPersonident = UserConstants.ANNEN_ARBEIDSTAKER_FNR + ) + behandlerService.createOrGetBehandler( + behandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 1 + pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo annenBehandler.behandlerRef + } + it("lagrer behandler for arbeidstaker når samme behandler er lagret for arbeidstaker, men med annen partnerId") { + val behandler = generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.PARTNERID) + val sammeBehandlerAnnenPartnerId = + generateFastlegeResponse(UserConstants.FASTLEGE_FNR).toBehandler(UserConstants.OTHER_PARTNERID) + val existingBehandlerRef = + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR ) - pBehandlerForArbeidstakerList.size shouldBeEqualTo 2 - pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo existingBehandlerRef - pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo existingBehandlerRef - } + + behandlerService.createOrGetBehandler( + behandler = sammeBehandlerAnnenPartnerId, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + + val pBehandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerForArbeidstakerList.size shouldBeEqualTo 2 + pBehandlerForArbeidstakerList[0].behandlerRef shouldNotBeEqualTo existingBehandlerRef + pBehandlerForArbeidstakerList[1].behandlerRef shouldBeEqualTo existingBehandlerRef } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/api/BehandlerApiSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/api/BehandlerApiSpek.kt index d269a207..4108c487 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/api/BehandlerApiSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/api/BehandlerApiSpek.kt @@ -1,10 +1,12 @@ package no.nav.syfo.behandler.api -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue +import io.ktor.client.call.* +import io.ktor.client.request.* import io.ktor.http.* import io.ktor.server.testing.* -import no.nav.syfo.behandler.database.* +import no.nav.syfo.behandler.database.getBehandlerByArbeidstaker +import no.nav.syfo.behandler.database.getBehandlerKontorById +import no.nav.syfo.behandler.database.invalidateBehandler import no.nav.syfo.behandler.domain.BehandlerArbeidstakerRelasjonstype import no.nav.syfo.behandler.domain.BehandlerKategori import no.nav.syfo.testhelper.* @@ -16,156 +18,145 @@ import no.nav.syfo.testhelper.UserConstants.PARTNERID import no.nav.syfo.testhelper.generator.generateBehandler import no.nav.syfo.testhelper.generator.generateFastlegeResponse import no.nav.syfo.util.NAV_PERSONIDENT_HEADER -import no.nav.syfo.util.bearerHeader -import no.nav.syfo.util.configuredJacksonMapper import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe -import java.util.UUID +import java.util.* class BehandlerApiSpek : Spek({ - val objectMapper: ObjectMapper = configuredJacksonMapper() + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database - with(TestApplicationEngine()) { - start() - - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - application.testApiModule(externalMockEnvironment = externalMockEnvironment) - - afterEachTest { - database.dropData() - } - - describe(BehandlerApiSpek::class.java.simpleName) { - val validToken = generateJWT( - externalMockEnvironment.environment.aadAppClient, - externalMockEnvironment.wellKnownInternalAzureAD.issuer, - UserConstants.VEILEDER_IDENT, - ) - describe("Get list of Behandler for Personident") { - val url = "$behandlerPath$behandlerPersonident" - val searchUrl = "$behandlerPath$search" - describe("Happy path") { - it("should return list of Behandler and store behandler if request is successful") { - val fastlegeResponse = generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 - - val behandlerForPersonList = database.getBehandlerByArbeidstaker( - ARBEIDSTAKER_FNR, - ) - behandlerForPersonList.size shouldBeEqualTo 1 + afterEachTest { + database.dropData() + } - val behandlerDTO = behandlerList.first() - behandlerDTO.fornavn shouldBeEqualTo fastlegeResponse.fornavn - behandlerDTO.mellomnavn shouldBeEqualTo fastlegeResponse.mellomnavn - behandlerDTO.etternavn shouldBeEqualTo fastlegeResponse.etternavn - behandlerDTO.adresse shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.adresse - behandlerDTO.postnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.postnummer - behandlerDTO.poststed shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.poststed - behandlerDTO.telefon shouldBeEqualTo fastlegeResponse.fastlegekontor.telefon - behandlerDTO.orgnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.orgnummer - behandlerDTO.kontor shouldBeEqualTo fastlegeResponse.fastlegekontor.navn - behandlerDTO.type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name - behandlerDTO.behandlerRef shouldBeEqualTo behandlerForPersonList.first().behandlerRef.toString() - behandlerDTO.fnr shouldBeEqualTo fastlegeResponse.fnr - behandlerDTO.kategori shouldBeEqualTo BehandlerKategori.LEGE.name - behandlerDTO.hprId shouldBeEqualTo fastlegeResponse.helsepersonellregisterId - } - } - it("should return list of Behandler and store behandler connected to kontor with latest dialogmeldingEnabled") { - database.createKontor( - partnerId = OTHER_PARTNERID, - navn = OTHER_PARTNERID.toString() - ) - database.createKontor( - partnerId = PARTNERID, - navn = PARTNERID.toString() + describe(BehandlerApiSpek::class.java.simpleName) { + val validToken = generateJWT( + externalMockEnvironment.environment.aadAppClient, + externalMockEnvironment.wellKnownInternalAzureAD.issuer, + UserConstants.VEILEDER_IDENT, + ) + describe("Get list of Behandler for Personident") { + val url = "$behandlerPath$behandlerPersonident" + val searchUrl = "$behandlerPath$search" + describe("Happy path") { + it("should return list of Behandler and store behandler if request is successful") { + val fastlegeResponse = generateFastlegeResponse() + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 + + val behandlerForPersonList = database.getBehandlerByArbeidstaker( + ARBEIDSTAKER_FNR, ) - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 - val behandlerDTO = behandlerList.first() - behandlerDTO.kontor shouldBeEqualTo PARTNERID.toString() - } + behandlerForPersonList.size shouldBeEqualTo 1 + + val behandlerDTO = behandlerList.first() + behandlerDTO.fornavn shouldBeEqualTo fastlegeResponse.fornavn + behandlerDTO.mellomnavn shouldBeEqualTo fastlegeResponse.mellomnavn + behandlerDTO.etternavn shouldBeEqualTo fastlegeResponse.etternavn + behandlerDTO.adresse shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.adresse + behandlerDTO.postnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.postnummer + behandlerDTO.poststed shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.poststed + behandlerDTO.telefon shouldBeEqualTo fastlegeResponse.fastlegekontor.telefon + behandlerDTO.orgnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.orgnummer + behandlerDTO.kontor shouldBeEqualTo fastlegeResponse.fastlegekontor.navn + behandlerDTO.type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name + behandlerDTO.behandlerRef shouldBeEqualTo behandlerForPersonList.first().behandlerRef.toString() + behandlerDTO.fnr shouldBeEqualTo fastlegeResponse.fnr + behandlerDTO.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + behandlerDTO.hprId shouldBeEqualTo fastlegeResponse.helsepersonellregisterId } - it("should return list of Behandler and store behandler connected to kontor with dialogmeldingEnabled") { - database.createKontor( - partnerId = OTHER_PARTNERID, - navn = OTHER_PARTNERID.toString() - ) - database.createKontor( - partnerId = PARTNERID, - navn = PARTNERID.toString(), - dialogmeldingEnabled = false, - ) - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 - val behandlerDTO = behandlerList.first() - behandlerDTO.kontor shouldBeEqualTo OTHER_PARTNERID.toString() - } + } + it("should return list of Behandler and store behandler connected to kontor with latest dialogmeldingEnabled") { + database.createKontor( + partnerId = OTHER_PARTNERID, + navn = OTHER_PARTNERID.toString() + ) + database.createKontor( + partnerId = PARTNERID, + navn = PARTNERID.toString() + ) + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) + } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 + val behandlerDTO = behandlerList.first() + behandlerDTO.kontor shouldBeEqualTo PARTNERID.toString() } - it("should return list of Behandler and store behandler connected to kontor with largest partnerId if dialogmelding not enabled") { - database.createKontor( - partnerId = OTHER_PARTNERID, - navn = OTHER_PARTNERID.toString(), - dialogmeldingEnabled = false, - ) - database.createKontor( - partnerId = PARTNERID, - navn = PARTNERID.toString(), - dialogmeldingEnabled = false, - ) - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 - val behandlerDTO = behandlerList.first() - behandlerDTO.kontor shouldBeEqualTo OTHER_PARTNERID.toString() - } + } + it("should return list of Behandler and store behandler connected to kontor with dialogmeldingEnabled") { + database.createKontor( + partnerId = OTHER_PARTNERID, + navn = OTHER_PARTNERID.toString() + ) + database.createKontor( + partnerId = PARTNERID, + navn = PARTNERID.toString(), + dialogmeldingEnabled = false, + ) + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) + } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 + val behandlerDTO = behandlerList.first() + behandlerDTO.kontor shouldBeEqualTo OTHER_PARTNERID.toString() + } + } + it("should return list of Behandler and store behandler connected to kontor with largest partnerId if dialogmelding not enabled") { + database.createKontor( + partnerId = OTHER_PARTNERID, + navn = OTHER_PARTNERID.toString(), + dialogmeldingEnabled = false, + ) + database.createKontor( + partnerId = PARTNERID, + navn = PARTNERID.toString(), + dialogmeldingEnabled = false, + ) + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) + } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 + val behandlerDTO = behandlerList.first() + behandlerDTO.kontor shouldBeEqualTo OTHER_PARTNERID.toString() } - it("should exclude suspendert Behandler") { - val fastlegeResponse = generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) + } + it("should exclude suspendert Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = body>() behandlerList.size shouldBeEqualTo 1 val behandlerForPersonList = database.getBehandlerByArbeidstaker( ARBEIDSTAKER_FNR, @@ -173,386 +164,356 @@ class BehandlerApiSpek : Spek({ behandlerForPersonList.size shouldBeEqualTo 1 database.setSuspendert(behandlerList[0].behandlerRef) } - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 0 - val behandlerForPersonList = database.getBehandlerByArbeidstaker( - ARBEIDSTAKER_FNR, - ) - behandlerForPersonList.size shouldBeEqualTo 0 + + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) } + + response.status shouldBeEqualTo HttpStatusCode.OK + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 0 + val behandlerForPersonList = database.getBehandlerByArbeidstaker( + ARBEIDSTAKER_FNR, + ) + behandlerForPersonList.size shouldBeEqualTo 0 } - it("search should return list of Behandler") { - generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("search should return list of Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK } - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Scully") - } - ) { - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Scully") } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 } - it("search should exclude invalidated Behandler") { - generateFastlegeResponse() - val behandlerRef = with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val behandlerList = objectMapper.readValue>(response.content!!) + } + it("search should exclude invalidated Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = body>() behandlerList.size shouldBeEqualTo 1 - UUID.fromString(behandlerList[0].behandlerRef) + database.invalidateBehandler(UUID.fromString(behandlerList[0].behandlerRef)) } - database.invalidateBehandler(behandlerRef) - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Scully") - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 0 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Scully") } + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 0 } - it("search should exclude suspendert Behandler") { - generateFastlegeResponse() - val behandlerRef = with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val behandlerList = objectMapper.readValue>(response.content!!) + } + it("search should exclude suspendert Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = body>() behandlerList.size shouldBeEqualTo 1 - behandlerList[0].behandlerRef + database.setSuspendert(behandlerList[0].behandlerRef) } - database.setSuspendert(behandlerRef) - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Scully") - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 0 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Scully") } + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 0 } - it("search should remove special characters") { - generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("search should remove special characters") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK } - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Scu:lly, Dana: Fas,tle.gen kont:or") - } - ) { - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Scu:lly, Dana: Fas,tle.gen kont:or") } + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 } - it("search with multiple strings should return list of Behandler") { - generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("search with multiple strings should return list of Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK } - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Dan Scully Fastlegens") - } - ) { - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Dan Scully Fastlegens") } + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 } - it("search with lower case kontor navn should return list of Behandler") { - generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("search with lower case kontor navn should return list of Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK } - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "fastlegen") - } - ) { - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "fastlegen") } + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 } - it("search with too short strings should return empty list of Behandler") { - generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("search with too short strings should return empty list of Behandler") { + testApplication { + val client = setupApiAndClient() + client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value) + }.apply { + status shouldBeEqualTo HttpStatusCode.OK } - with( - handleRequest(HttpMethod.Get, searchUrl) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader("searchstring", "Da Sc") - } - ) { - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 0 + + val response = client.get(searchUrl) { + bearerAuth(validToken) + header("searchstring", "Da Sc") } + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 0 } - it("should return empty list of Behandler for arbeidstaker uten fastlege") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - - behandlerList.size shouldBeEqualTo 0 - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, - ).size shouldBeEqualTo 0 + } + it("should return empty list of Behandler for arbeidstaker uten fastlege") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value) } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + + behandlerList.size shouldBeEqualTo 0 + + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, + ).size shouldBeEqualTo 0 } + } - it("should return empty list of Behandler for arbeidstaker med fastlege uten foreldreEnhetHerId") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader( - NAV_PERSONIDENT_HEADER, - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET.value - ) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - - behandlerList.size shouldBeEqualTo 0 - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET, - ).size shouldBeEqualTo 0 + it("should return empty list of Behandler for arbeidstaker med fastlege uten foreldreEnhetHerId") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET.value) } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + + behandlerList.size shouldBeEqualTo 0 + + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET, + ).size shouldBeEqualTo 0 } + } - it("should return empty list of Behandler for arbeidstaker med fastlege uten partnerinfo") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader( - NAV_PERSONIDENT_HEADER, - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO.value - ) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - - behandlerList.size shouldBeEqualTo 0 - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO, - ).size shouldBeEqualTo 0 + it("should return empty list of Behandler for arbeidstaker med fastlege uten partnerinfo") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO.value) } - } - it("should return list of Behandler (with Kontor with largest partnerId) for arbeidstaker with fastlege with multiple partnerinfo") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader( - NAV_PERSONIDENT_HEADER, - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value - ) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() - behandlerList.size shouldBeEqualTo 1 + behandlerList.size shouldBeEqualTo 0 + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO, + ).size shouldBeEqualTo 0 + } + } - val behandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO, - ) - behandlerForArbeidstakerList.size shouldBeEqualTo 1 - val behandlerKontor = - database.getBehandlerKontorById(behandlerForArbeidstakerList.first().kontorId) - behandlerKontor.partnerId shouldBeEqualTo OTHER_PARTNERID.toString() + it("should return list of Behandler (with Kontor with largest partnerId) for arbeidstaker with fastlege with multiple partnerinfo") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO.value) } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + + behandlerList.size shouldBeEqualTo 1 + + val behandlerForArbeidstakerList = database.getBehandlerByArbeidstaker( + ARBEIDSTAKER_MED_FASTLEGE_MED_FLERE_PARTNERINFO, + ) + behandlerForArbeidstakerList.size shouldBeEqualTo 1 + val behandlerKontor = + database.getBehandlerKontorById(behandlerForArbeidstakerList.first().kontorId) + behandlerKontor.partnerId shouldBeEqualTo OTHER_PARTNERID.toString() } + } - it("should return empty list of Behandler for arbeidstaker med fastlege som mangler fnr, hprId og herId") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader( - NAV_PERSONIDENT_HEADER, - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID.value - ) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - - behandlerList.size shouldBeEqualTo 0 - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID, - ).size shouldBeEqualTo 0 + it("should return empty list of Behandler for arbeidstaker med fastlege som mangler fnr, hprId og herId") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID.value) } + + response.status shouldBeEqualTo HttpStatusCode.OK + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 0 + + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID, + ).size shouldBeEqualTo 0 } } - describe("Unhappy paths") { - it("should return status Unauthorized if no token is supplied") { - with( - handleRequest(HttpMethod.Get, url) {} - ) { - response.status() shouldBeEqualTo HttpStatusCode.Unauthorized - } + } + describe("Unhappy paths") { + it("should return status Unauthorized if no token is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) + + response.status shouldBeEqualTo HttpStatusCode.Unauthorized } + } - it("should return status BadRequest if no $NAV_PERSONIDENT_HEADER is supplied") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + it("should return status BadRequest if no $NAV_PERSONIDENT_HEADER is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) } + + response.status shouldBeEqualTo HttpStatusCode.BadRequest } + } - it("should return status BadRequest if $NAV_PERSONIDENT_HEADER with invalid Personident is supplied") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value.drop(1)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + it("should return status BadRequest if $NAV_PERSONIDENT_HEADER with invalid Personident is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_FNR.value.drop(1)) } + + response.status shouldBeEqualTo HttpStatusCode.BadRequest } - it("should return status Forbidden if denied access to personident supplied in $NAV_PERSONIDENT_HEADER") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_VEILEDER_NO_ACCESS.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Forbidden + } + it("should return status Forbidden if denied access to personident supplied in $NAV_PERSONIDENT_HEADER") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, ARBEIDSTAKER_VEILEDER_NO_ACCESS.value) } + + response.status shouldBeEqualTo HttpStatusCode.Forbidden } } } + } - describe("Get behandler for behandlerRef") { - val behandlerRef = UUID.randomUUID() - val url = "$behandlerPath/$behandlerRef" - val behandler = generateBehandler( - behandlerRef = behandlerRef, - partnerId = PARTNERID, - ) - describe("Happy path") { - it("should return behandler for behandlerRef") { - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = ARBEIDSTAKER_FNR, - ) - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - val behandlerDTO = - objectMapper.readValue(response.content!!) - behandlerDTO.behandlerRef shouldBeEqualTo behandlerRef.toString() - behandlerDTO.fornavn shouldBeEqualTo "Dana" - } + describe("Get behandler for behandlerRef") { + val behandlerRef = UUID.randomUUID() + val url = "$behandlerPath/$behandlerRef" + val behandler = generateBehandler( + behandlerRef = behandlerRef, + partnerId = PARTNERID, + ) + describe("Happy path") { + it("should return behandler for behandlerRef") { + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = ARBEIDSTAKER_FNR, + ) + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + } + + val behandlerDTO = response.body() + behandlerDTO.behandlerRef shouldBeEqualTo behandlerRef.toString() + behandlerDTO.fornavn shouldBeEqualTo "Dana" } } - describe("Unhappy path") { - it("should return status NotFound for non-matching behandlerRef") { - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.NotFound + } + describe("Unhappy path") { + it("should return status NotFound for non-matching behandlerRef") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) } + + response.status shouldBeEqualTo HttpStatusCode.NotFound } - it("should return status Unauthorized if no token is supplied") { - with( - handleRequest(HttpMethod.Get, url) {} - ) { - response.status() shouldBeEqualTo HttpStatusCode.Unauthorized - } + } + it("should return status Unauthorized if no token is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) + + response.status shouldBeEqualTo HttpStatusCode.Unauthorized } - it("should return status BadRequest if invalid behandlerRef") { - with( - handleRequest(HttpMethod.Get, "$behandlerPath/123abc") { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + } + it("should return status BadRequest if invalid behandlerRef") { + testApplication { + val client = setupApiAndClient() + val response = client.get("$behandlerPath/123abc") { + bearerAuth(validToken) } + response.status shouldBeEqualTo HttpStatusCode.BadRequest } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonBehandlerApiSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonBehandlerApiSpek.kt index 779beb04..97aaad13 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonBehandlerApiSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonBehandlerApiSpek.kt @@ -1,7 +1,7 @@ package no.nav.syfo.behandler.api.person -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue +import io.ktor.client.call.* +import io.ktor.client.request.* import io.ktor.http.* import io.ktor.server.testing.* import no.nav.syfo.behandler.database.getBehandlerByArbeidstaker @@ -9,257 +9,246 @@ import no.nav.syfo.behandler.domain.BehandlerArbeidstakerRelasjonstype import no.nav.syfo.behandler.domain.BehandlerKategori import no.nav.syfo.testhelper.* import no.nav.syfo.testhelper.generator.generateFastlegeResponse -import no.nav.syfo.util.bearerHeader -import no.nav.syfo.util.configuredJacksonMapper import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class PersonBehandlerApiSpek : Spek({ - val objectMapper: ObjectMapper = configuredJacksonMapper() + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database - with(TestApplicationEngine()) { - start() - - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - application.testApiModule( - externalMockEnvironment = externalMockEnvironment, - ) - - afterEachTest { - database.dropData() - } - - describe(PersonBehandlerApiSpek::class.java.simpleName) { - describe("Get list of Behandler for Personident") { - val dtoClassName = PersonBehandlerDTO::class.java.simpleName - - val url = "$personApiBehandlerPath$personBehandlerSelfPath" - describe("Happy path") { - it("should return list of $dtoClassName and store behandler if request is successful") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) + afterEachTest { + database.dropData() + } - val fastlegeResponse = generateFastlegeResponse() - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val personBehandlerList = - objectMapper.readValue>(response.content!!) - personBehandlerList.size shouldBeEqualTo 1 - - val behandlerForPersonList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - behandlerForPersonList.size shouldBeEqualTo 1 - - val personBehandlerDTO = personBehandlerList.first() - personBehandlerDTO.fornavn shouldBeEqualTo fastlegeResponse.fornavn - personBehandlerDTO.mellomnavn shouldBeEqualTo fastlegeResponse.mellomnavn - personBehandlerDTO.etternavn shouldBeEqualTo fastlegeResponse.etternavn - personBehandlerDTO.adresse shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.adresse - personBehandlerDTO.postnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.postnummer - personBehandlerDTO.poststed shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.poststed - personBehandlerDTO.telefon shouldBeEqualTo fastlegeResponse.fastlegekontor.telefon - personBehandlerDTO.orgnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.orgnummer - personBehandlerDTO.kontor shouldBeEqualTo fastlegeResponse.fastlegekontor.navn - personBehandlerDTO.type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name - personBehandlerDTO.kategori shouldBeEqualTo BehandlerKategori.LEGE.name - personBehandlerDTO.behandlerRef shouldBeEqualTo behandlerForPersonList.first().behandlerRef.toString() - personBehandlerDTO.fnr shouldBeEqualTo fastlegeResponse.fnr - - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ).size shouldBeEqualTo 1 + describe(PersonBehandlerApiSpek::class.java.simpleName) { + describe("Get list of Behandler for Personident") { + val dtoClassName = PersonBehandlerDTO::class.java.simpleName + + val url = "$personApiBehandlerPath$personBehandlerSelfPath" + describe("Happy path") { + it("should return list of $dtoClassName and store behandler if request is successful") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + + val fastlegeResponse = generateFastlegeResponse() + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) } - } - it("should return empty list of $dtoClassName for person missing Fastlege") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value, - ) - - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val personBehandlerList = - objectMapper.readValue>(response.content!!) + response.status shouldBeEqualTo HttpStatusCode.OK - personBehandlerList.size shouldBeEqualTo 0 + val personBehandlerList = response.body>() + personBehandlerList.size shouldBeEqualTo 1 - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, - ).size shouldBeEqualTo 0 - } + val behandlerForPersonList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + behandlerForPersonList.size shouldBeEqualTo 1 + + val personBehandlerDTO = personBehandlerList.first() + personBehandlerDTO.fornavn shouldBeEqualTo fastlegeResponse.fornavn + personBehandlerDTO.mellomnavn shouldBeEqualTo fastlegeResponse.mellomnavn + personBehandlerDTO.etternavn shouldBeEqualTo fastlegeResponse.etternavn + personBehandlerDTO.adresse shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.adresse + personBehandlerDTO.postnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.postnummer + personBehandlerDTO.poststed shouldBeEqualTo fastlegeResponse.fastlegekontor.postadresse?.poststed + personBehandlerDTO.telefon shouldBeEqualTo fastlegeResponse.fastlegekontor.telefon + personBehandlerDTO.orgnummer shouldBeEqualTo fastlegeResponse.fastlegekontor.orgnummer + personBehandlerDTO.kontor shouldBeEqualTo fastlegeResponse.fastlegekontor.navn + personBehandlerDTO.type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name + personBehandlerDTO.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + personBehandlerDTO.behandlerRef shouldBeEqualTo behandlerForPersonList.first().behandlerRef.toString() + personBehandlerDTO.fnr shouldBeEqualTo fastlegeResponse.fnr + + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ).size shouldBeEqualTo 1 } + } + it("should return empty list of $dtoClassName for person missing Fastlege") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + } - it("should return empty list of $dtoClassName for person with Fastlege missing foreldreEnhetHerId") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET.value, - ) + response.status shouldBeEqualTo HttpStatusCode.OK - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + val personBehandlerList = response.body>() + personBehandlerList.size shouldBeEqualTo 0 + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, + ).size shouldBeEqualTo 0 + } + } - val personBehandlerList = - objectMapper.readValue>(response.content!!) + it("should return empty list of $dtoClassName for person with Fastlege missing foreldreEnhetHerId") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + } - personBehandlerList.size shouldBeEqualTo 0 + response.status shouldBeEqualTo HttpStatusCode.OK - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET, - ).size shouldBeEqualTo 0 - } + val personBehandlerList = response.body>() + personBehandlerList.size shouldBeEqualTo 0 + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FORELDREENHET, + ).size shouldBeEqualTo 0 } + } - it("should return empty list of $dtoClassName for person with Fastlege missing partnerinfo") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO.value, - ) - - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + it("should return empty list of $dtoClassName for person with Fastlege missing partnerinfo") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + } - val personBehandlerList = - objectMapper.readValue>(response.content!!) + response.status shouldBeEqualTo HttpStatusCode.OK - personBehandlerList.size shouldBeEqualTo 0 + val personBehandlerList = response.body>() + personBehandlerList.size shouldBeEqualTo 0 - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO, - ).size shouldBeEqualTo 0 - } + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_PARTNERINFO, + ).size shouldBeEqualTo 0 } - it("should return empty list of $dtoClassName for person with fastlege missing fnr, hprId and herId") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID.value, - ) - - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK + } + it("should return empty list of $dtoClassName for person with fastlege missing fnr, hprId and herId") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + } - val personBehandlerList = - objectMapper.readValue>(response.content!!) + response.status shouldBeEqualTo HttpStatusCode.OK - personBehandlerList.size shouldBeEqualTo 0 + val personBehandlerList = response.body>() + personBehandlerList.size shouldBeEqualTo 0 - database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID, - ).size shouldBeEqualTo 0 - } + database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_MED_FASTLEGE_UTEN_FNR_HPRID_HERID, + ).size shouldBeEqualTo 0 } } - describe("Unhappy paths") { - it("should return status Unauthorized if no token is supplied") { - with( - handleRequest(HttpMethod.Get, url) {} - ) { - response.status() shouldBeEqualTo HttpStatusCode.Unauthorized - } - } + } + describe("Unhappy paths") { + it("should return status Unauthorized if no token is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.get(url) - it("should return status BadRequest if no PID is supplied") { - val tokenNoPid = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = null, - ) + response.status shouldBeEqualTo HttpStatusCode.Unauthorized + } + } - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenNoPid)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + it("should return status BadRequest if no PID is supplied") { + val tokenNoPid = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = null, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(tokenNoPid) } - } - it("should return status BadRequest if invalid Personident in PID is supplied") { - val tokenInvalidPid = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.aapSoknadApiClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value.drop(1), - ) + response.status shouldBeEqualTo HttpStatusCode.BadRequest + } + } - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenInvalidPid)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + it("should return status BadRequest if invalid Personident in PID is supplied") { + val tokenInvalidPid = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.aapSoknadApiClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value.drop(1), + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(tokenInvalidPid) } - } - it("should return status BadRequest if valid PID with and no ClientId is supplied") { - val tokenValidPidNoClientId = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = null, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) + response.status shouldBeEqualTo HttpStatusCode.BadRequest + } + } - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenValidPidNoClientId)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest + it("should return status BadRequest if valid PID with and no ClientId is supplied") { + val tokenValidPidNoClientId = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = null, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(tokenValidPidNoClientId) } - } - it("should return status Forbiddden if valid PID with and unauthorized ClientId is supplied") { - val tokenValidPidUnauthorizedClientId = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = "app", - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) + response.status shouldBeEqualTo HttpStatusCode.BadRequest + } + } - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenValidPidUnauthorizedClientId)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Forbidden + it("should return status Forbiddden if valid PID with and unauthorized ClientId is supplied") { + val tokenValidPidUnauthorizedClientId = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = "app", + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(tokenValidPidUnauthorizedClientId) } + + response.status shouldBeEqualTo HttpStatusCode.Forbidden } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonOppfolgingsplanApiSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonOppfolgingsplanApiSpek.kt index c48cfec3..51b3e5c9 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonOppfolgingsplanApiSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/api/person/PersonOppfolgingsplanApiSpek.kt @@ -1,202 +1,201 @@ package no.nav.syfo.behandler.api.person -import com.fasterxml.jackson.databind.ObjectMapper +import io.ktor.client.request.* import io.ktor.http.* import io.ktor.server.testing.* -import io.mockk.* +import io.mockk.mockk +import io.mockk.verify import no.nav.syfo.application.mq.MQSender import no.nav.syfo.dialogmelding.bestilling.database.getDialogmeldingToBehandlerBestillingNotSendt import no.nav.syfo.dialogmelding.bestilling.domain.DialogmeldingType import no.nav.syfo.testhelper.* -import no.nav.syfo.testhelper.generator.* -import no.nav.syfo.util.bearerHeader -import no.nav.syfo.util.configuredJacksonMapper +import no.nav.syfo.testhelper.generator.generateRSOppfolgingsplan import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class PersonOppfolgingsplanApiSpek : Spek({ - val objectMapper: ObjectMapper = configuredJacksonMapper() val mqSender = mockk(relaxed = true) + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database - with(TestApplicationEngine()) { - start() - - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - application.testApiModule( - externalMockEnvironment = externalMockEnvironment, - ) - - afterEachTest { - database.dropData() - } + afterEachTest { + database.dropData() + } - describe(PersonOppfolgingsplanApiSpek::class.java.simpleName) { - describe("Send oppfolgingsplan for person") { - val url = "$personApiOppfolgingsplanPath" - describe("Happy path") { - it("Skal lagre bestilling for oppfølgingsplan") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) - val rsOppfolgingsplan = generateRSOppfolgingsplan() - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(rsOppfolgingsplan)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } - val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() - storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name - storedBestilling.arbeidstakerPersonident shouldBeEqualTo UserConstants.ARBEIDSTAKER_FNR.value - storedBestilling.sendt shouldBe null + describe(PersonOppfolgingsplanApiSpek::class.java.simpleName) { + describe("Send oppfolgingsplan for person") { + val url = personApiOppfolgingsplanPath + describe("Happy path") { + it("Skal lagre bestilling for oppfølgingsplan") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + val rsOppfolgingsplan = generateRSOppfolgingsplan() + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(rsOppfolgingsplan) } - } - it("Skal lagre bestilling for innsendt oppfølgingsplan fra nærmeste leder") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.NARMESTELEDER_FNR.value, - ) - val rsOppfolgingsplan = generateRSOppfolgingsplan() - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(rsOppfolgingsplan)) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } - val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() - storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name - storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr - storedBestilling.sendt shouldBe null + response.status shouldBeEqualTo HttpStatusCode.OK + verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } + val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() + storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name + storedBestilling.arbeidstakerPersonident shouldBeEqualTo UserConstants.ARBEIDSTAKER_FNR.value + storedBestilling.sendt shouldBe null + } + } + it("Skal lagre bestilling for innsendt oppfølgingsplan fra nærmeste leder") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.NARMESTELEDER_FNR.value, + ) + val rsOppfolgingsplan = generateRSOppfolgingsplan() + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(rsOppfolgingsplan) } + + response.status shouldBeEqualTo HttpStatusCode.OK + verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } + val storedBestilling = database.getDialogmeldingToBehandlerBestillingNotSendt().first() + storedBestilling.type shouldBeEqualTo DialogmeldingType.OPPFOLGINGSPLAN.name + storedBestilling.arbeidstakerPersonident shouldBeEqualTo rsOppfolgingsplan.sykmeldtFnr + storedBestilling.sendt shouldBe null } } - describe("Unhappy paths") { - it("should return error for arbeidstaker with no fastlege") { - val validToken = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value, - ) - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan(UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR))) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.NotFound - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + } + describe("Unhappy paths") { + it("should return error for arbeidstaker with no fastlege") { + val validToken = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(validToken) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan(UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR)) } + + response.status shouldBeEqualTo HttpStatusCode.NotFound + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } + } - it("should return status Unauthorized if no token is supplied") { - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Unauthorized - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + it("should return status Unauthorized if no token is supplied") { + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.Unauthorized + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } + } - it("should return status BadRequest if no PID is supplied") { - val tokenNoPid = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = null, - ) - - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenNoPid)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + it("should return status BadRequest if no PID is supplied") { + val tokenNoPid = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = null, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenNoPid) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.BadRequest + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } + } - it("should return status BadRequest if invalid Personident in PID is supplied") { - val tokenInvalidPid = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value.drop(1), - ) - - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenInvalidPid)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest - database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null + it("should return status BadRequest if invalid Personident in PID is supplied") { + val tokenInvalidPid = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = externalMockEnvironment.environment.syfooppfolgingsplanserviceClientId, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value.drop(1), + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenInvalidPid) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.BadRequest + database.getDialogmeldingToBehandlerBestillingNotSendt().firstOrNull() shouldBe null } + } - it("should return status BadRequest if valid PID with and no ClientId is supplied") { - val tokenValidPidNoClientId = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = null, - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) - - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenValidPidNoClientId)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.BadRequest - verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } + it("should return status BadRequest if valid PID with and no ClientId is supplied") { + val tokenValidPidNoClientId = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = null, + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenValidPidNoClientId) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.BadRequest + verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } } + } - it("should return status Forbiddden if valid PID with and unauthorized ClientId is supplied") { - val tokenValidPidUnauthorizedClientId = generateJWTIdporten( - audience = externalMockEnvironment.environment.idportenTokenXClientId, - clientId = "app", - issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, - pid = UserConstants.ARBEIDSTAKER_FNR.value, - ) - - with( - handleRequest(HttpMethod.Post, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(tokenValidPidUnauthorizedClientId)) - addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - setBody(objectMapper.writeValueAsString(generateRSOppfolgingsplan())) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.Forbidden - verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } + it("should return status Forbiddden if valid PID with and unauthorized ClientId is supplied") { + val tokenValidPidUnauthorizedClientId = generateJWTIdporten( + audience = externalMockEnvironment.environment.idportenTokenXClientId, + clientId = "app", + issuer = externalMockEnvironment.wellKnownInternalIdportenTokenX.issuer, + pid = UserConstants.ARBEIDSTAKER_FNR.value, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.post(url) { + bearerAuth(tokenValidPidUnauthorizedClientId) + contentType(ContentType.Application.Json) + setBody(generateRSOppfolgingsplan()) } + + response.status shouldBeEqualTo HttpStatusCode.Forbidden + verify(exactly = 0) { mqSender.sendMessageToEmottak(any()) } } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingfrombehandler/KafkaDialogmeldingFromBehandlerSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingfrombehandler/KafkaDialogmeldingFromBehandlerSpek.kt index 9838b320..a160df97 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingfrombehandler/KafkaDialogmeldingFromBehandlerSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingfrombehandler/KafkaDialogmeldingFromBehandlerSpek.kt @@ -1,17 +1,24 @@ package no.nav.syfo.behandler.kafka.dialogmeldingfrombehandler -import io.ktor.server.testing.* -import io.mockk.* +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify import kotlinx.coroutines.runBlocking import no.nav.syfo.behandler.BehandlerService import no.nav.syfo.behandler.database.getBehandlerByBehandlerRef import no.nav.syfo.behandler.database.getBehandlerKontor -import no.nav.syfo.behandler.domain.* +import no.nav.syfo.behandler.domain.Arbeidstaker +import no.nav.syfo.behandler.domain.BehandlerArbeidstakerRelasjonstype import no.nav.syfo.behandler.fastlege.toBehandler import no.nav.syfo.testhelper.* import no.nav.syfo.testhelper.generator.* -import org.amshove.kluent.* -import org.apache.kafka.clients.consumer.* +import org.amshove.kluent.`should be` +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldNotBe +import org.apache.kafka.clients.consumer.ConsumerRecord +import org.apache.kafka.clients.consumer.ConsumerRecords +import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.common.TopicPartition import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe @@ -20,201 +27,197 @@ import java.time.OffsetDateTime import java.util.* class KafkaDialogmeldingFromBehandlerSpek : Spek({ + val database = ExternalMockEnvironment.instance.database + val behandlerService = BehandlerService( + fastlegeClient = mockk(), + partnerinfoClient = mockk(), + database = database, + ) - with(TestApplicationEngine()) { - start() - val database = ExternalMockEnvironment.instance.database - val behandlerService = BehandlerService( - fastlegeClient = mockk(), - partnerinfoClient = mockk(), - database = database, - ) + afterEachTest { + database.dropData() + } - afterEachTest { - database.dropData() - } + describe("Read dialogmelding sent from behandler to NAV from Kafka Topic") { + + describe("Receive dialogmelding from behandler") { + describe("Happy path") { + it("mark kontor as ready to receive dialogmeldinger") { + addBehandlerAndKontorToDatabase(behandlerService) + val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - describe("Read dialogmelding sent from behandler to NAV from Kafka Topic") { - - describe("Receive dialogmelding from behandler") { - describe("Happy path") { - it("mark kontor as ready to receive dialogmeldinger") { - addBehandlerAndKontorToDatabase(behandlerService) - val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) - kontor?.dialogmeldingEnabled shouldNotBe null + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } - it("do not mark kontor as ready to receive dialogmeldinger if locked") { - addBehandlerAndKontorToDatabase(behandlerService) - database.setDialogmeldingEnabledLocked(UserConstants.PARTNERID.toString()) - val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) - kontor!!.dialogmeldingEnabled shouldBe null + + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) + kontor?.dialogmeldingEnabled shouldNotBe null + } + it("do not mark kontor as ready to receive dialogmeldinger if locked") { + addBehandlerAndKontorToDatabase(behandlerService) + database.setDialogmeldingEnabledLocked(UserConstants.PARTNERID.toString()) + val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } - it("update identer for behandler if stored idents are null") { - val behandlerRef = database.createBehandlerForArbeidstaker( - behandler = generateBehandler( - behandlerRef = UUID.randomUUID(), - partnerId = UserConstants.PARTNERID, - herId = null, - hprId = UserConstants.HPRID, - ), - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) + kontor!!.dialogmeldingEnabled shouldBe null + } + it("update identer for behandler if stored idents are null") { + val behandlerRef = database.createBehandlerForArbeidstaker( + behandler = generateBehandler( + behandlerRef = UUID.randomUUID(), + partnerId = UserConstants.PARTNERID, + herId = null, + hprId = UserConstants.HPRID, + ), + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val dialogmelding = generateDialogmeldingFromBehandlerDTO(fellesformatXMLHealthcareProfessional) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, ) - val dialogmelding = generateDialogmeldingFromBehandlerDTO(fellesformatXMLHealthcareProfessional) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val behandler = database.getBehandlerByBehandlerRef(behandlerRef) - behandler shouldNotBe null - behandler!!.hprId shouldBeEqualTo UserConstants.HPRID.toString() - behandler.herId shouldBeEqualTo UserConstants.OTHER_HERID.toString() } - it("do not update identer when received ident of type XXX") { - val behandlerRef = database.createBehandlerForArbeidstaker( - behandler = generateBehandler( - behandlerRef = UUID.randomUUID(), - partnerId = UserConstants.PARTNERID, - herId = null, - hprId = UserConstants.HPRID, - ), - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + + verify(exactly = 1) { mockConsumer.commitSync() } + val behandler = database.getBehandlerByBehandlerRef(behandlerRef) + behandler shouldNotBe null + behandler!!.hprId shouldBeEqualTo UserConstants.HPRID.toString() + behandler.herId shouldBeEqualTo UserConstants.OTHER_HERID.toString() + } + it("do not update identer when received ident of type XXX") { + val behandlerRef = database.createBehandlerForArbeidstaker( + behandler = generateBehandler( + behandlerRef = UUID.randomUUID(), + partnerId = UserConstants.PARTNERID, + herId = null, + hprId = UserConstants.HPRID, + ), + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + val dialogmelding = generateDialogmeldingFromBehandlerDTO(fellesformatXMLHealthcareProfessionalMedIdenttypeAnnen) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, ) - val dialogmelding = generateDialogmeldingFromBehandlerDTO(fellesformatXMLHealthcareProfessionalMedIdenttypeAnnen) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val behandler = database.getBehandlerByBehandlerRef(behandlerRef) - behandler shouldNotBe null - behandler!!.hprId shouldBeEqualTo UserConstants.HPRID.toString() - behandler.herId shouldBeEqualTo null } + + verify(exactly = 1) { mockConsumer.commitSync() } + val behandler = database.getBehandlerByBehandlerRef(behandlerRef) + behandler shouldNotBe null + behandler!!.hprId shouldBeEqualTo UserConstants.HPRID.toString() + behandler.herId shouldBeEqualTo null } + } - describe("Unhappy path") { - it("don't mark kontor as ready to receive dialogmeldinger if kontor isn't found in database") { - val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) - kontor `should be` null - } + describe("Unhappy path") { + it("don't mark kontor as ready to receive dialogmeldinger if kontor isn't found in database") { + val dialogmelding = generateDialogmeldingFromBehandlerDTO(UUID.randomUUID()) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - it("don't mark kontor as ready to receive dialogmeldinger if no partnerId is found") { - addBehandlerAndKontorToDatabase(behandlerService) - val dialogmelding = generateDialogmeldingFromBehandlerDTOWithInvalidXml(UUID.randomUUID()) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) - kontor shouldNotBe null - kontor!!.dialogmeldingEnabled `should be` null + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } - it("do not update identer for behandler with invalid fnr") { - val dialogmelding = generateDialogmeldingFromBehandlerDTO( - fellesformatXml = fellesformatXMLHealthcareProfessionalInvalidFNR, + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) + kontor `should be` null + } + + it("don't mark kontor as ready to receive dialogmeldinger if no partnerId is found") { + addBehandlerAndKontorToDatabase(behandlerService) + val dialogmelding = generateDialogmeldingFromBehandlerDTOWithInvalidXml(UUID.randomUUID()) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, ) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) + } - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(UserConstants.PARTNERID) + kontor shouldNotBe null + kontor!!.dialogmeldingEnabled `should be` null + } + + it("do not update identer for behandler with invalid fnr") { + val dialogmelding = generateDialogmeldingFromBehandlerDTO( + fellesformatXml = fellesformatXMLHealthcareProfessionalInvalidFNR, + ) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmelding) - verify(exactly = 1) { mockConsumer.commitSync() } + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } - it("don't update behandleridenter if we can't find partnerId in xml") { - val dialogmeldingWithoutValidPartnerIdWithHealthcareProfessional = generateDialogmeldingFromBehandlerDTO(fellesformatXmlWithIdenterWithoutPartnerId) - val behandlerRef = addExistingBehandlerToDatabase(database) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmeldingWithoutValidPartnerIdWithHealthcareProfessional) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val behandler = database.getBehandlerByBehandlerRef(behandlerRef) - behandler shouldNotBe null - behandler!!.herId shouldBe null - behandler.hprId shouldBeEqualTo UserConstants.HPRID.toString() + verify(exactly = 1) { mockConsumer.commitSync() } + } + + it("don't update behandleridenter if we can't find partnerId in xml") { + val dialogmeldingWithoutValidPartnerIdWithHealthcareProfessional = generateDialogmeldingFromBehandlerDTO(fellesformatXmlWithIdenterWithoutPartnerId) + val behandlerRef = addExistingBehandlerToDatabase(database) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmeldingWithoutValidPartnerIdWithHealthcareProfessional) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } - it("don't update behandleridenter if HealthcareProfessional is not in xml") { - val dialogmeldingWithoutHealthcareProfessional = generateDialogmeldingFromBehandlerDTO(fellesformatXml) - val behandlerRef = addExistingBehandlerToDatabase(database) - val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmeldingWithoutHealthcareProfessional) - - runBlocking { - pollAndProcessDialogmeldingFromBehandler( - kafkaConsumerDialogmeldingFromBehandler = mockConsumer, - database = database, - ) - } - - verify(exactly = 1) { mockConsumer.commitSync() } - val behandler = database.getBehandlerByBehandlerRef(behandlerRef) - behandler shouldNotBe null - behandler!!.herId shouldBe null - behandler.hprId shouldBeEqualTo UserConstants.HPRID.toString() + verify(exactly = 1) { mockConsumer.commitSync() } + val behandler = database.getBehandlerByBehandlerRef(behandlerRef) + behandler shouldNotBe null + behandler!!.herId shouldBe null + behandler.hprId shouldBeEqualTo UserConstants.HPRID.toString() + } + + it("don't update behandleridenter if HealthcareProfessional is not in xml") { + val dialogmeldingWithoutHealthcareProfessional = generateDialogmeldingFromBehandlerDTO(fellesformatXml) + val behandlerRef = addExistingBehandlerToDatabase(database) + val mockConsumer = mockKafkaConsumerWithDialogmelding(dialogmeldingWithoutHealthcareProfessional) + + runBlocking { + pollAndProcessDialogmeldingFromBehandler( + kafkaConsumerDialogmeldingFromBehandler = mockConsumer, + database = database, + ) } + + verify(exactly = 1) { mockConsumer.commitSync() } + val behandler = database.getBehandlerByBehandlerRef(behandlerRef) + behandler shouldNotBe null + behandler!!.herId shouldBe null + behandler.hprId shouldBeEqualTo UserConstants.HPRID.toString() } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingtobehandlerbestilling/KafkaDialogmeldingToBehandlerBestillingSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingtobehandlerbestilling/KafkaDialogmeldingToBehandlerBestillingSpek.kt index b42a81b7..27e0f109 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingtobehandlerbestilling/KafkaDialogmeldingToBehandlerBestillingSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingtobehandlerbestilling/KafkaDialogmeldingToBehandlerBestillingSpek.kt @@ -1,275 +1,277 @@ package no.nav.syfo.behandler.kafka.dialogmeldingtobehandlerbestilling -import io.ktor.server.testing.* -import io.mockk.* +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify import kotlinx.coroutines.runBlocking -import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService import no.nav.syfo.client.azuread.AzureAdClient import no.nav.syfo.client.pdl.PdlClient +import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService import no.nav.syfo.dialogmelding.bestilling.database.getBestilling -import no.nav.syfo.dialogmelding.bestilling.kafka.* +import no.nav.syfo.dialogmelding.bestilling.kafka.DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC +import no.nav.syfo.dialogmelding.bestilling.kafka.DialogmeldingToBehandlerBestillingDTO +import no.nav.syfo.dialogmelding.bestilling.kafka.pollAndProcessDialogmeldingBestilling import no.nav.syfo.dialogmelding.status.database.getDialogmeldingStatusNotPublished import no.nav.syfo.dialogmelding.status.domain.DialogmeldingStatusType -import no.nav.syfo.testhelper.* +import no.nav.syfo.testhelper.ExternalMockEnvironment +import no.nav.syfo.testhelper.dropData import no.nav.syfo.testhelper.generator.generateDialogmeldingToBehandlerBestillingDTO import no.nav.syfo.testhelper.testdata.lagreBehandler import org.amshove.kluent.* -import org.apache.kafka.clients.consumer.* +import org.apache.kafka.clients.consumer.ConsumerRecord +import org.apache.kafka.clients.consumer.ConsumerRecords +import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.common.TopicPartition import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.Duration -import java.util.UUID +import java.util.* class KafkaDialogmeldingToBehandlerBestillingSpek : Spek({ - - with(TestApplicationEngine()) { - start() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val environment = externalMockEnvironment.environment - val pdlClient = PdlClient( - azureAdClient = AzureAdClient( - azureAppClientId = environment.aadAppClient, - azureAppClientSecret = environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, - httpClient = externalMockEnvironment.mockHttpClient, - ), - pdlClientId = environment.pdlClientId, - pdlUrl = environment.pdlUrl, + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val environment = externalMockEnvironment.environment + val pdlClient = PdlClient( + azureAdClient = AzureAdClient( + azureAppClientId = environment.aadAppClient, + azureAppClientSecret = environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, httpClient = externalMockEnvironment.mockHttpClient, - ) - val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( - database = database, - pdlClient = pdlClient, - ) + ), + pdlClientId = environment.pdlClientId, + pdlUrl = environment.pdlUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( + database = database, + pdlClient = pdlClient, + ) - afterEachTest { - database.dropData() - } + afterEachTest { + database.dropData() + } - describe(KafkaDialogmeldingToBehandlerBestillingSpek::class.java.simpleName) { + describe(KafkaDialogmeldingToBehandlerBestillingSpek::class.java.simpleName) { - describe("Motta dialogmelding bestillinger") { - val partition = 0 - val dialogmeldingToBehandlerBestillingTopicPartition = TopicPartition( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - ) - describe("Happy path") { - it("should persist incoming bestillinger") { - val behandler = lagreBehandler(database) - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandler.behandlerRef, - ) - val dialogmeldingBestillingRecord = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 1, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val mockConsumer = mockk>() - every { mockConsumer.poll(any()) } returns ConsumerRecords( - mapOf( - dialogmeldingToBehandlerBestillingTopicPartition to listOf( - dialogmeldingBestillingRecord, - ) + describe("Motta dialogmelding bestillinger") { + val partition = 0 + val dialogmeldingToBehandlerBestillingTopicPartition = TopicPartition( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + ) + describe("Happy path") { + it("should persist incoming bestillinger") { + val behandler = lagreBehandler(database) + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandler.behandlerRef, + ) + val dialogmeldingBestillingRecord = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 1, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val mockConsumer = mockk>() + every { mockConsumer.poll(any()) } returns ConsumerRecords( + mapOf( + dialogmeldingToBehandlerBestillingTopicPartition to listOf( + dialogmeldingBestillingRecord, ) ) - every { mockConsumer.commitSync() } returns Unit + ) + every { mockConsumer.commitSync() } returns Unit - runBlocking { - pollAndProcessDialogmeldingBestilling( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, - ) - } + runBlocking { + pollAndProcessDialogmeldingBestilling( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, + ) + } - verify(exactly = 1) { mockConsumer.commitSync() } + verify(exactly = 1) { mockConsumer.commitSync() } - val pBehandlerDialogmeldingBestilling = - database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) - pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null - pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid - pBehandlerDialogmeldingBestilling.tekst!! shouldBeEqualTo dialogmeldingBestilling.dialogmeldingTekst - pBehandlerDialogmeldingBestilling.kilde!! shouldBeEqualTo "SYFO" - } - it("should persist incoming bestilling with no kilde") { - val behandler = lagreBehandler(database) - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandler.behandlerRef, - ).copy( - kilde = null, - ) - val dialogmeldingBestillingRecord = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 1, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val mockConsumer = mockk>() - every { mockConsumer.poll(any()) } returns ConsumerRecords( - mapOf( - dialogmeldingToBehandlerBestillingTopicPartition to listOf( - dialogmeldingBestillingRecord, - ) + val pBehandlerDialogmeldingBestilling = + database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) + pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null + pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid + pBehandlerDialogmeldingBestilling.tekst!! shouldBeEqualTo dialogmeldingBestilling.dialogmeldingTekst + pBehandlerDialogmeldingBestilling.kilde!! shouldBeEqualTo "SYFO" + } + it("should persist incoming bestilling with no kilde") { + val behandler = lagreBehandler(database) + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandler.behandlerRef, + ).copy( + kilde = null, + ) + val dialogmeldingBestillingRecord = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 1, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val mockConsumer = mockk>() + every { mockConsumer.poll(any()) } returns ConsumerRecords( + mapOf( + dialogmeldingToBehandlerBestillingTopicPartition to listOf( + dialogmeldingBestillingRecord, ) ) - every { mockConsumer.commitSync() } returns Unit + ) + every { mockConsumer.commitSync() } returns Unit - runBlocking { - pollAndProcessDialogmeldingBestilling( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, - ) - } + runBlocking { + pollAndProcessDialogmeldingBestilling( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, + ) + } - verify(exactly = 1) { mockConsumer.commitSync() } + verify(exactly = 1) { mockConsumer.commitSync() } - val pBehandlerDialogmeldingBestilling = - database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) - pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null - pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid - pBehandlerDialogmeldingBestilling.tekst!! shouldBeEqualTo dialogmeldingBestilling.dialogmeldingTekst - pBehandlerDialogmeldingBestilling.kilde shouldBe null - } - it("persists dialogmelding-status BESTILT when incoming bestilling") { - val behandler = lagreBehandler(database) - val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( - uuid = UUID.randomUUID(), - behandlerRef = behandler.behandlerRef, - ) - val dialogmeldingBestillingRecord = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 1, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val mockConsumer = mockk>() - every { mockConsumer.poll(any()) } returns ConsumerRecords( - mapOf( - dialogmeldingToBehandlerBestillingTopicPartition to listOf( - dialogmeldingBestillingRecord, - ) + val pBehandlerDialogmeldingBestilling = + database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) + pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null + pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid + pBehandlerDialogmeldingBestilling.tekst!! shouldBeEqualTo dialogmeldingBestilling.dialogmeldingTekst + pBehandlerDialogmeldingBestilling.kilde shouldBe null + } + it("persists dialogmelding-status BESTILT when incoming bestilling") { + val behandler = lagreBehandler(database) + val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( + uuid = UUID.randomUUID(), + behandlerRef = behandler.behandlerRef, + ) + val dialogmeldingBestillingRecord = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 1, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val mockConsumer = mockk>() + every { mockConsumer.poll(any()) } returns ConsumerRecords( + mapOf( + dialogmeldingToBehandlerBestillingTopicPartition to listOf( + dialogmeldingBestillingRecord, ) ) - every { mockConsumer.commitSync() } returns Unit + ) + every { mockConsumer.commitSync() } returns Unit - runBlocking { - pollAndProcessDialogmeldingBestilling( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, - ) - } + runBlocking { + pollAndProcessDialogmeldingBestilling( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, + ) + } - val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() - dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 + val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() + dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 - val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() - val pBehandlerDialogmeldingBestilling = - database.getBestilling( - uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid) - ) - pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.BESTILT.name - pDialogmeldingStatus.tekst.shouldBeNull() - pDialogmeldingStatus.bestillingId shouldBeEqualTo pBehandlerDialogmeldingBestilling?.id - pDialogmeldingStatus.createdAt.shouldNotBeNull() - pDialogmeldingStatus.updatedAt.shouldNotBeNull() - pDialogmeldingStatus.publishedAt.shouldBeNull() - } - } - describe("Should only persist once when duplicates") { - it("Should only persist once when duplicates") { - val behandler = lagreBehandler(database) - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandler.behandlerRef, + val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() + val pBehandlerDialogmeldingBestilling = + database.getBestilling( + uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid) ) - val dialogmeldingBestillingRecord = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 2, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val dialogmeldingBestillingRecordDuplicate = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 3, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val mockConsumer = mockk>() - every { mockConsumer.poll(any()) } returns ConsumerRecords( - mapOf( - dialogmeldingToBehandlerBestillingTopicPartition to listOf( - dialogmeldingBestillingRecord, - dialogmeldingBestillingRecordDuplicate, - ) + pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.BESTILT.name + pDialogmeldingStatus.tekst.shouldBeNull() + pDialogmeldingStatus.bestillingId shouldBeEqualTo pBehandlerDialogmeldingBestilling?.id + pDialogmeldingStatus.createdAt.shouldNotBeNull() + pDialogmeldingStatus.updatedAt.shouldNotBeNull() + pDialogmeldingStatus.publishedAt.shouldBeNull() + } + } + describe("Should only persist once when duplicates") { + it("Should only persist once when duplicates") { + val behandler = lagreBehandler(database) + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandler.behandlerRef, + ) + val dialogmeldingBestillingRecord = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 2, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val dialogmeldingBestillingRecordDuplicate = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 3, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val mockConsumer = mockk>() + every { mockConsumer.poll(any()) } returns ConsumerRecords( + mapOf( + dialogmeldingToBehandlerBestillingTopicPartition to listOf( + dialogmeldingBestillingRecord, + dialogmeldingBestillingRecordDuplicate, ) ) - every { mockConsumer.commitSync() } returns Unit + ) + every { mockConsumer.commitSync() } returns Unit - runBlocking { - pollAndProcessDialogmeldingBestilling( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, - ) - } + runBlocking { + pollAndProcessDialogmeldingBestilling( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, + ) + } - verify(exactly = 1) { mockConsumer.commitSync() } + verify(exactly = 1) { mockConsumer.commitSync() } - val pBehandlerDialogmeldingBestilling = - database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) + val pBehandlerDialogmeldingBestilling = + database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) - pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null - pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid - } + pBehandlerDialogmeldingBestilling shouldNotBeEqualTo null + pBehandlerDialogmeldingBestilling!!.uuid shouldBeEqualTo dialogmeldingBestillingUuid } - describe("Does not persist when behandlerRef not valid") { - it("should not persist incoming bestillinger when behandlerRef is invalid") { - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = UUID.randomUUID(), - ) - val dialogmeldingBestillingRecord = ConsumerRecord( - DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, - partition, - 1, - dialogmeldingBestilling.dialogmeldingUuid, - dialogmeldingBestilling, - ) - val mockConsumer = mockk>() - every { mockConsumer.poll(any()) } returns ConsumerRecords( - mapOf( - dialogmeldingToBehandlerBestillingTopicPartition to listOf( - dialogmeldingBestillingRecord, - ) + } + describe("Does not persist when behandlerRef not valid") { + it("should not persist incoming bestillinger when behandlerRef is invalid") { + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestilling = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = UUID.randomUUID(), + ) + val dialogmeldingBestillingRecord = ConsumerRecord( + DIALOGMELDING_TO_BEHANDLER_BESTILLING_TOPIC, + partition, + 1, + dialogmeldingBestilling.dialogmeldingUuid, + dialogmeldingBestilling, + ) + val mockConsumer = mockk>() + every { mockConsumer.poll(any()) } returns ConsumerRecords( + mapOf( + dialogmeldingToBehandlerBestillingTopicPartition to listOf( + dialogmeldingBestillingRecord, ) ) - every { mockConsumer.commitSync() } returns Unit - - runBlocking { - pollAndProcessDialogmeldingBestilling( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, - ) - } + ) + every { mockConsumer.commitSync() } returns Unit - verify(exactly = 1) { mockConsumer.commitSync() } - val pBehandlerDialogmeldingBestilling = - database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) - pBehandlerDialogmeldingBestilling shouldBeEqualTo null + runBlocking { + pollAndProcessDialogmeldingBestilling( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + kafkaConsumerDialogmeldingToBehandlerBestilling = mockConsumer, + ) } + + verify(exactly = 1) { mockConsumer.commitSync() } + val pBehandlerDialogmeldingBestilling = + database.getBestilling(uuid = UUID.fromString(dialogmeldingBestilling.dialogmeldingUuid)) + pBehandlerDialogmeldingBestilling shouldBeEqualTo null } } } diff --git a/src/test/kotlin/no/nav/syfo/behandler/kafka/sykmelding/KafkaSykmeldingSpek.kt b/src/test/kotlin/no/nav/syfo/behandler/kafka/sykmelding/KafkaSykmeldingSpek.kt index 15428afa..d1fe809b 100644 --- a/src/test/kotlin/no/nav/syfo/behandler/kafka/sykmelding/KafkaSykmeldingSpek.kt +++ b/src/test/kotlin/no/nav/syfo/behandler/kafka/sykmelding/KafkaSykmeldingSpek.kt @@ -1,7 +1,7 @@ package no.nav.syfo.behandler.kafka.sykmelding -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue +import io.ktor.client.call.* +import io.ktor.client.request.* import io.ktor.http.* import io.ktor.server.testing.* import io.mockk.* @@ -30,438 +30,435 @@ import java.util.* class KafkaSykmeldingSpek : Spek({ - val objectMapper: ObjectMapper = configuredJacksonMapper() - - with(TestApplicationEngine()) { - start() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - application.testApiModule(externalMockEnvironment = externalMockEnvironment) - val mockHttpClient = externalMockEnvironment.mockHttpClient - val azureAdClient = AzureAdClient( - azureAppClientId = externalMockEnvironment.environment.aadAppClient, - azureAppClientSecret = externalMockEnvironment.environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = externalMockEnvironment.environment.azureOpenidConfigTokenEndpoint, + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val mockHttpClient = externalMockEnvironment.mockHttpClient + val azureAdClient = AzureAdClient( + azureAppClientId = externalMockEnvironment.environment.aadAppClient, + azureAppClientSecret = externalMockEnvironment.environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = externalMockEnvironment.environment.azureOpenidConfigTokenEndpoint, + httpClient = mockHttpClient, + ) + val behandlerService = BehandlerService( + fastlegeClient = FastlegeClient( + azureAdClient = azureAdClient, + fastlegeRestClientId = externalMockEnvironment.environment.fastlegeRestClientId, + fastlegeRestUrl = externalMockEnvironment.environment.fastlegeRestUrl, httpClient = mockHttpClient, - ) - val behandlerService = BehandlerService( - fastlegeClient = FastlegeClient( - azureAdClient = azureAdClient, - fastlegeRestClientId = externalMockEnvironment.environment.fastlegeRestClientId, - fastlegeRestUrl = externalMockEnvironment.environment.fastlegeRestUrl, - httpClient = mockHttpClient, - ), - partnerinfoClient = PartnerinfoClient( - azureAdClient = azureAdClient, - syfoPartnerinfoClientId = externalMockEnvironment.environment.syfoPartnerinfoClientId, - syfoPartnerinfoUrl = externalMockEnvironment.environment.syfoPartnerinfoUrl, - httpClient = mockHttpClient, - ), - database = database, - ) + ), + partnerinfoClient = PartnerinfoClient( + azureAdClient = azureAdClient, + syfoPartnerinfoClientId = externalMockEnvironment.environment.syfoPartnerinfoClientId, + syfoPartnerinfoUrl = externalMockEnvironment.environment.syfoPartnerinfoUrl, + httpClient = mockHttpClient, + ), + database = database, + ) - val mockConsumer = mockk>() + val mockConsumer = mockk>() - beforeEachTest { - clearMocks(mockConsumer) - every { mockConsumer.commitSync() } returns Unit - } + beforeEachTest { + clearMocks(mockConsumer) + every { mockConsumer.commitSync() } returns Unit + } - afterEachTest { - database.dropData() - } + afterEachTest { + database.dropData() + } - describe(KafkaSykmeldingSpek::class.java.simpleName) { - describe("Motta sykmelding") { - val kafkaPartition = 0 - val sykmeldingTopicPartition = TopicPartition( - SYKMELDING_TOPIC, - kafkaPartition, - ) - - describe("Happy path") { - it("should persist behandlerkontor from incoming sykmelding") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), + describe(KafkaSykmeldingSpek::class.java.simpleName) { + describe("Motta sykmelding") { + val kafkaPartition = 0 + val sykmeldingTopicPartition = TopicPartition( + SYKMELDING_TOPIC, + kafkaPartition, + ) + + describe("Happy path") { + it("should persist behandlerkontor from incoming sykmelding") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + val kontorBefore = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + val behandlereBefore = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + kontorBefore shouldBe null + behandlereBefore.size shouldBeEqualTo 0 + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - val kontorBefore = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - val behandlereBefore = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - kontorBefore shouldBe null - behandlereBefore.size shouldBeEqualTo 0 - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontorAfter = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontorAfter!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontorAfter.herId shouldBeEqualTo sykmelding.legekontorHerId - - val behandlereAfter = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - behandlereAfter.size shouldBeEqualTo 0 } - it("sykmelding from existing fastlege should add new sykmelder-relation") { - val behandler = - behandlerService.createOrGetBehandler( - generateFastlegeResponse().toBehandler(UserConstants.PARTNERID), - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, - ) - - val pBehandlerList = database.getBehandlerByArbeidstaker( - UserConstants.ARBEIDSTAKER_FNR, - ) - pBehandlerList.size shouldBeEqualTo 1 - - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, - personNrLege = behandler.personident!!.value, - behandlerFnr = behandler.personident!!.value, - herId = behandler.herId.toString(), - hprId = behandler.hprId.toString(), - partnerreferanse = UserConstants.PARTNERID.toString(), - kontorHerId = UserConstants.HERID.toString(), - ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontorAfter = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontorAfter!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontorAfter.herId shouldBeEqualTo sykmelding.legekontorHerId + verify(exactly = 1) { mockConsumer.commitSync() } + val kontorAfter = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontorAfter!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontorAfter.herId shouldBeEqualTo sykmelding.legekontorHerId - val pBehandlerListAfter = database.getBehandlerAndRelasjonstypeList( - UserConstants.ARBEIDSTAKER_FNR, + val behandlereAfter = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + behandlereAfter.size shouldBeEqualTo 0 + } + it("sykmelding from existing fastlege should add new sykmelder-relation") { + val behandler = + behandlerService.createOrGetBehandler( + generateFastlegeResponse().toBehandler(UserConstants.PARTNERID), + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, ) - pBehandlerListAfter.size shouldBeEqualTo 2 - pBehandlerListAfter[0].first.personident shouldBeEqualTo sykmelding.personNrLege - pBehandlerListAfter[0].first.kategori shouldBeEqualTo BehandlerKategori.LEGE.name - pBehandlerListAfter[0].second shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.SYKMELDER - pBehandlerListAfter[1].first.personident shouldBeEqualTo sykmelding.personNrLege - pBehandlerListAfter[1].first.kategori shouldBeEqualTo BehandlerKategori.LEGE.name - pBehandlerListAfter[1].second shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE - - val behandlerRelasjonAfter = database.getBehandlerArbeidstakerRelasjon( - personident = UserConstants.ARBEIDSTAKER_FNR, - behandlerRef = behandler.behandlerRef, + + val pBehandlerList = database.getBehandlerByArbeidstaker( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerList.size shouldBeEqualTo 1 + + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, + personNrLege = behandler.personident!!.value, + behandlerFnr = behandler.personident!!.value, + herId = behandler.herId.toString(), + hprId = behandler.hprId.toString(), + partnerreferanse = UserConstants.PARTNERID.toString(), + kontorHerId = UserConstants.HERID.toString(), + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - behandlerRelasjonAfter.size shouldBeEqualTo 2 - behandlerRelasjonAfter[0].type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.SYKMELDER.name - behandlerRelasjonAfter[1].type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name } - it("behandler from sykmelding should not shadow existing fastlege") { - val url = "$behandlerPath$behandlerPersonident" - val validToken = generateJWT( - externalMockEnvironment.environment.aadAppClient, - externalMockEnvironment.wellKnownInternalAzureAD.issuer, - UserConstants.VEILEDER_IDENT, - ) - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - - val behandlerList = - objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 + verify(exactly = 1) { mockConsumer.commitSync() } + val kontorAfter = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontorAfter!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontorAfter.herId shouldBeEqualTo sykmelding.legekontorHerId + + val pBehandlerListAfter = database.getBehandlerAndRelasjonstypeList( + UserConstants.ARBEIDSTAKER_FNR, + ) + pBehandlerListAfter.size shouldBeEqualTo 2 + pBehandlerListAfter[0].first.personident shouldBeEqualTo sykmelding.personNrLege + pBehandlerListAfter[0].first.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + pBehandlerListAfter[0].second shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.SYKMELDER + pBehandlerListAfter[1].first.personident shouldBeEqualTo sykmelding.personNrLege + pBehandlerListAfter[1].first.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + pBehandlerListAfter[1].second shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE + + val behandlerRelasjonAfter = database.getBehandlerArbeidstakerRelasjon( + personident = UserConstants.ARBEIDSTAKER_FNR, + behandlerRef = behandler.behandlerRef, + ) + behandlerRelasjonAfter.size shouldBeEqualTo 2 + behandlerRelasjonAfter[0].type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.SYKMELDER.name + behandlerRelasjonAfter[1].type shouldBeEqualTo BehandlerArbeidstakerRelasjonstype.FASTLEGE.name + } + it("behandler from sykmelding should not shadow existing fastlege") { + val url = "$behandlerPath$behandlerPersonident" + val validToken = generateJWT( + externalMockEnvironment.environment.aadAppClient, + externalMockEnvironment.wellKnownInternalAzureAD.issuer, + UserConstants.VEILEDER_IDENT, + ) + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_FNR.value) } - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, - ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - - val behandler = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - behandler.size shouldBeEqualTo 1 - val fastlegeBehandlerRef = behandler[0].behandlerRef - - with( - handleRequest(HttpMethod.Get, url) { - addHeader(HttpHeaders.Authorization, bearerHeader(validToken)) - addHeader(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_FNR.value) - } - ) { - response.status() shouldBeEqualTo HttpStatusCode.OK - val behandlerList = objectMapper.readValue>(response.content!!) - behandlerList.size shouldBeEqualTo 1 - behandlerList[0].behandlerRef shouldBeEqualTo fastlegeBehandlerRef.toString() - } + response.status shouldBeEqualTo HttpStatusCode.OK - val behandlerAfterAnotherGet = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - behandlerAfterAnotherGet.size shouldBeEqualTo 1 + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 } - it("should update system for kontor") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + } + verify(exactly = 1) { mockConsumer.commitSync() } - val newSykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - avsenderSystemNavn = "Nytt systemnavn", - ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, newSykmelding, 2) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) + val behandler = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + behandler.size shouldBeEqualTo 1 + val fastlegeBehandlerRef = behandler[0].behandlerRef + + testApplication { + val client = setupApiAndClient() + val response = client.get(url) { + bearerAuth(validToken) + header(NAV_PERSONIDENT_HEADER, UserConstants.ARBEIDSTAKER_FNR.value) } - verify(exactly = 2) { mockConsumer.commitSync() } - val kontorAfterSecondMessage = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontorAfterSecondMessage!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontorAfterSecondMessage.system shouldBeEqualTo newSykmelding.sykmelding.avsenderSystem.navn + response.status shouldBeEqualTo HttpStatusCode.OK + + val behandlerList = response.body>() + behandlerList.size shouldBeEqualTo 1 + behandlerList[0].behandlerRef shouldBeEqualTo fastlegeBehandlerRef.toString() } - it("should not update system for kontor if mottatt older than the one already stored") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - avsenderSystemNavn = "Systemnavnet" + + val behandlerAfterAnotherGet = database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + behandlerAfterAnotherGet.size shouldBeEqualTo 1 + } + + it("should update system for kontor") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - - val newSykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - avsenderSystemNavn = "Systemnavnet tidligere", - mottattTidspunkt = LocalDateTime.now().minusDays(1), - behandletTidspunkt = LocalDateTime.now().minusDays(1), + } + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + + val newSykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + avsenderSystemNavn = "Nytt systemnavn", + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, newSykmelding, 2) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, newSykmelding, 2) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 2) { mockConsumer.commitSync() } + } + verify(exactly = 2) { mockConsumer.commitSync() } - val kontorAfterSecondMessage = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontorAfterSecondMessage!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontorAfterSecondMessage.system shouldBeEqualTo sykmelding.sykmelding.avsenderSystem.navn + val kontorAfterSecondMessage = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontorAfterSecondMessage!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontorAfterSecondMessage.system shouldBeEqualTo newSykmelding.sykmelding.avsenderSystem.navn + } + it("should not update system for kontor if mottatt older than the one already stored") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + avsenderSystemNavn = "Systemnavnet" + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, + ) } - it("fastlege-oppslag should update adresse for kontor") { - val fastlegeBehandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, - personNrLege = fastlegeBehandler.personident!!.value, - behandlerFnr = fastlegeBehandler.personident!!.value, - herId = fastlegeBehandler.herId.toString(), - hprId = fastlegeBehandler.hprId.toString(), - partnerreferanse = UserConstants.PARTNERID.toString(), - kontorHerId = UserConstants.HERID.toString(), - mottattTidspunkt = LocalDateTime.now().minusMinutes(1), - behandletTidspunkt = LocalDateTime.now().minusMinutes(1), + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + + val newSykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + avsenderSystemNavn = "Systemnavnet tidligere", + mottattTidspunkt = LocalDateTime.now().minusDays(1), + behandletTidspunkt = LocalDateTime.now().minusDays(1), + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, newSykmelding, 2) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - - val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontor.poststed shouldBe null + } + verify(exactly = 2) { mockConsumer.commitSync() } - behandlerService.createOrGetBehandler( - fastlegeBehandler, - Arbeidstaker( - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - mottatt = OffsetDateTime.now(), - ), - relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + val kontorAfterSecondMessage = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontorAfterSecondMessage!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontorAfterSecondMessage.system shouldBeEqualTo sykmelding.sykmelding.avsenderSystem.navn + } + it("fastlege-oppslag should update adresse for kontor") { + val fastlegeBehandler = generateFastlegeResponse().toBehandler(UserConstants.PARTNERID) + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + personNrPasient = UserConstants.ARBEIDSTAKER_FNR.value, + personNrLege = fastlegeBehandler.personident!!.value, + behandlerFnr = fastlegeBehandler.personident!!.value, + herId = fastlegeBehandler.herId.toString(), + hprId = fastlegeBehandler.hprId.toString(), + partnerreferanse = UserConstants.PARTNERID.toString(), + kontorHerId = UserConstants.HERID.toString(), + mottattTidspunkt = LocalDateTime.now().minusMinutes(1), + behandletTidspunkt = LocalDateTime.now().minusMinutes(1), + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - - val kontorAfterFastlegeOppslag = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - kontorAfterFastlegeOppslag!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse - kontorAfterFastlegeOppslag.adresse shouldBeEqualTo fastlegeBehandler.kontor.adresse - kontorAfterFastlegeOppslag.postnummer shouldBeEqualTo fastlegeBehandler.kontor.postnummer - kontorAfterFastlegeOppslag.poststed shouldBeEqualTo fastlegeBehandler.kontor.poststed } + verify(exactly = 1) { mockConsumer.commitSync() } + + val kontor = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontor!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontor.poststed shouldBe null + + behandlerService.createOrGetBehandler( + fastlegeBehandler, + Arbeidstaker( + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + mottatt = OffsetDateTime.now(), + ), + relasjonstype = BehandlerArbeidstakerRelasjonstype.FASTLEGE, + ) + + val kontorAfterFastlegeOppslag = database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + kontorAfterFastlegeOppslag!!.partnerId shouldBeEqualTo sykmelding.partnerreferanse + kontorAfterFastlegeOppslag.adresse shouldBeEqualTo fastlegeBehandler.kontor.adresse + kontorAfterFastlegeOppslag.postnummer shouldBeEqualTo fastlegeBehandler.kontor.postnummer + kontorAfterFastlegeOppslag.poststed shouldBeEqualTo fastlegeBehandler.kontor.poststed } - describe("Invalid sykmelding") { - it("should ignore when mismatched behandler fnr") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - personNrLege = "01010112345", - behandlerFnr = "01010112346", + } + describe("Invalid sykmelding") { + it("should ignore when mismatched behandler fnr") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + personNrLege = "01010112345", + behandlerFnr = "01010112346", + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = - database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - val behandler = - database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - kontor shouldBe null - behandler.size shouldBeEqualTo 0 } - it("should ignore when invalid behandler kategori") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - legeHelsepersonellkategori = "XX", + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = + database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + val behandler = + database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + kontor shouldBe null + behandler.size shouldBeEqualTo 0 + } + it("should ignore when invalid behandler kategori") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + legeHelsepersonellkategori = "XX", + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = - database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - val behandler = - database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - kontor shouldBe null - behandler.size shouldBeEqualTo 0 } - it("should ignore when missing kontor herId") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - kontorHerId = null, + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = + database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + val behandler = + database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + kontor shouldBe null + behandler.size shouldBeEqualTo 0 + } + it("should ignore when missing kontor herId") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + kontorHerId = null, + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val behandlerKontor = database.getAllBehandlerKontor() - behandlerKontor.size shouldBeEqualTo 0 } - it("should ignore when missing partnerId") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - partnerreferanse = "", + verify(exactly = 1) { mockConsumer.commitSync() } + val behandlerKontor = database.getAllBehandlerKontor() + behandlerKontor.size shouldBeEqualTo 0 + } + it("should ignore when missing partnerId") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + partnerreferanse = "", + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val behandlerKontor = database.getAllBehandlerKontor() - behandlerKontor.size shouldBeEqualTo 0 } - it("should ignore when partnerId is not numeric") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - partnerreferanse = "x", + verify(exactly = 1) { mockConsumer.commitSync() } + val behandlerKontor = database.getAllBehandlerKontor() + behandlerKontor.size shouldBeEqualTo 0 + } + it("should ignore when partnerId is not numeric") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + partnerreferanse = "x", + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val behandlerKontor = database.getAllBehandlerKontor() - behandlerKontor.size shouldBeEqualTo 0 } - it("should ignore when mottatt before cutoff") { - val sykmelding = generateSykmeldingDTO( - uuid = UUID.randomUUID(), - mottattTidspunkt = LocalDateTime.of(LocalDate.of(2021, Month.SEPTEMBER, 1), LocalTime.of(0, 0)) + verify(exactly = 1) { mockConsumer.commitSync() } + val behandlerKontor = database.getAllBehandlerKontor() + behandlerKontor.size shouldBeEqualTo 0 + } + it("should ignore when mottatt before cutoff") { + val sykmelding = generateSykmeldingDTO( + uuid = UUID.randomUUID(), + mottattTidspunkt = LocalDateTime.of(LocalDate.of(2021, Month.SEPTEMBER, 1), LocalTime.of(0, 0)) + ) + every { mockConsumer.poll(any()) } returns + consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) + + runBlocking { + pollAndProcessSykmelding( + kafkaConsumerSykmelding = mockConsumer, + behandlerService = behandlerService, ) - every { mockConsumer.poll(any()) } returns - consumerRecords(sykmeldingTopicPartition, kafkaPartition, sykmelding) - - runBlocking { - pollAndProcessSykmelding( - kafkaConsumerSykmelding = mockConsumer, - behandlerService = behandlerService, - ) - } - verify(exactly = 1) { mockConsumer.commitSync() } - val kontor = - database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) - val behandler = - database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) - kontor shouldBe null - behandler.size shouldBeEqualTo 0 } + verify(exactly = 1) { mockConsumer.commitSync() } + val kontor = + database.connection.getBehandlerKontor(PartnerId(sykmelding.partnerreferanse!!.toInt())) + val behandler = + database.getBehandlerByArbeidstaker(Personident(sykmelding.personNrPasient)) + kontor shouldBe null + behandler.size shouldBeEqualTo 0 } } } diff --git a/src/test/kotlin/no/nav/syfo/cronjob/DialogmeldingCronjobSpek.kt b/src/test/kotlin/no/nav/syfo/cronjob/DialogmeldingCronjobSpek.kt index 92f648de..2dacf9a7 100644 --- a/src/test/kotlin/no/nav/syfo/cronjob/DialogmeldingCronjobSpek.kt +++ b/src/test/kotlin/no/nav/syfo/cronjob/DialogmeldingCronjobSpek.kt @@ -1,262 +1,262 @@ package no.nav.syfo.cronjob -import io.ktor.server.testing.* import io.mockk.* import kotlinx.coroutines.runBlocking import no.nav.syfo.application.mq.MQSender -import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService -import no.nav.syfo.dialogmelding.bestilling.database.getBestilling import no.nav.syfo.client.azuread.AzureAdClient import no.nav.syfo.client.pdl.PdlClient import no.nav.syfo.dialogmelding.DialogmeldingService +import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService +import no.nav.syfo.dialogmelding.bestilling.database.getBestilling import no.nav.syfo.dialogmelding.status.DialogmeldingStatusService import no.nav.syfo.dialogmelding.status.database.getDialogmeldingStatusNotPublished import no.nav.syfo.dialogmelding.status.domain.DialogmeldingStatusType import no.nav.syfo.dialogmelding.status.kafka.DialogmeldingStatusProducer import no.nav.syfo.dialogmelding.status.kafka.KafkaDialogmeldingStatusDTO import no.nav.syfo.domain.PartnerId -import no.nav.syfo.testhelper.* -import no.nav.syfo.testhelper.generator.* +import no.nav.syfo.testhelper.ExternalMockEnvironment +import no.nav.syfo.testhelper.UserConstants +import no.nav.syfo.testhelper.createBehandlerForArbeidstaker +import no.nav.syfo.testhelper.dropData +import no.nav.syfo.testhelper.generator.defaultFellesformatMessageXmlRegex +import no.nav.syfo.testhelper.generator.generateBehandler +import no.nav.syfo.testhelper.generator.generateDialogmeldingToBehandlerBestillingDTO +import no.nav.syfo.testhelper.generator.generateDialogmeldingToBehandlerBestillingOppfolgingsplanDTO import no.nav.syfo.testhelper.testdata.lagreDialogmeldingBestilling -import org.amshove.kluent.* +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldBeNull +import org.amshove.kluent.shouldNotBeEqualTo +import org.amshove.kluent.shouldNotBeNull import org.apache.kafka.clients.producer.KafkaProducer -import org.junit.Assert +import org.junit.jupiter.api.Assertions.assertTrue import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe -import java.util.Random -import java.util.UUID +import java.util.* class DialogmeldingCronjobSpek : Spek({ describe(DialogmeldingSendCronjob::class.java.simpleName) { - with(TestApplicationEngine()) { - start() - val random = Random() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val environment = externalMockEnvironment.environment - val pdlClient = PdlClient( - azureAdClient = AzureAdClient( - azureAppClientId = environment.aadAppClient, - azureAppClientSecret = environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, - httpClient = externalMockEnvironment.mockHttpClient, - ), - pdlClientId = environment.pdlClientId, - pdlUrl = environment.pdlUrl, + val random = Random() + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val environment = externalMockEnvironment.environment + val pdlClient = PdlClient( + azureAdClient = AzureAdClient( + azureAppClientId = environment.aadAppClient, + azureAppClientSecret = environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, httpClient = externalMockEnvironment.mockHttpClient, - ) - val mqSenderMock = mockk() + ), + pdlClientId = environment.pdlClientId, + pdlUrl = environment.pdlUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val mqSenderMock = mockk() - application.testApiModule( - externalMockEnvironment = externalMockEnvironment, + val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( + database = database, + pdlClient = pdlClient, + ) + val dialogmeldingStatusService = DialogmeldingStatusService( + database = database, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + dialogmeldingStatusProducer = DialogmeldingStatusProducer( + kafkaProducer = mockk>() ) + ) + val dialogmeldingService = DialogmeldingService( + pdlClient = pdlClient, + mqSender = mqSenderMock, + ) + val dialogmeldingSendCronjob = DialogmeldingSendCronjob( + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + dialogmeldingService = dialogmeldingService, + dialogmeldingStatusService = dialogmeldingStatusService, + ) - val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( - database = database, - pdlClient = pdlClient, - ) - val dialogmeldingStatusService = DialogmeldingStatusService( - database = database, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - dialogmeldingStatusProducer = DialogmeldingStatusProducer( - kafkaProducer = mockk>() - ) - ) - val dialogmeldingService = DialogmeldingService( - pdlClient = pdlClient, - mqSender = mqSenderMock, - ) - val dialogmeldingSendCronjob = DialogmeldingSendCronjob( - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - dialogmeldingService = dialogmeldingService, - dialogmeldingStatusService = dialogmeldingStatusService, - ) - - beforeEachTest { - database.dropData() - clearAllMocks() - justRun { mqSenderMock.sendMessageToEmottak(any()) } - } + beforeEachTest { + database.dropData() + clearAllMocks() + justRun { mqSenderMock.sendMessageToEmottak(any()) } + } - describe("Cronjob sender bestilte dialogmeldinger") { - it("Sender bestilt dialogmelding") { - val behandlerRef = UUID.randomUUID() - val partnerId = PartnerId(random.nextInt()) - val behandler = generateBehandler(behandlerRef, partnerId) - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) + describe("Cronjob sender bestilte dialogmeldinger") { + it("Sender bestilt dialogmelding") { + val behandlerRef = UUID.randomUUID() + val partnerId = PartnerId(random.nextInt()) + val behandler = generateBehandler(behandlerRef, partnerId) + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandlerRef, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) - lagreDialogmeldingBestilling( - database = database, - behandler = behandler, - dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO, - ) + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandlerRef, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) + lagreDialogmeldingBestilling( + database = database, + behandler = behandler, + dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO, + ) - val pBehandlerDialogmeldingBestillingBefore = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null - pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 + val pBehandlerDialogmeldingBestillingBefore = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null + pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 - runBlocking { - val result = dialogmeldingSendCronjob.dialogmeldingSendJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 1 - } - verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } + runBlocking { + val result = dialogmeldingSendCronjob.dialogmeldingSendJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 1 + } + verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } - val pBehandlerDialogmeldingBestillingAfter = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 + val pBehandlerDialogmeldingBestillingAfter = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 - clearMocks(mqSenderMock) - runBlocking { - val result = dialogmeldingSendCronjob.dialogmeldingSendJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 0 - } - verify(exactly = 0) { mqSenderMock.sendMessageToEmottak(any()) } + clearMocks(mqSenderMock) + runBlocking { + val result = dialogmeldingSendCronjob.dialogmeldingSendJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 0 } - it("Sender bestilt dialogmelding uten relasjon mellom arbeidstaker og behandler") { - val behandlerRef = UUID.randomUUID() - val partnerId = PartnerId(random.nextInt()) - val behandler = generateBehandler(behandlerRef, partnerId) - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) - - val dialogmeldingBestillingUuid = UUID.randomUUID() + verify(exactly = 0) { mqSenderMock.sendMessageToEmottak(any()) } + } + it("Sender bestilt dialogmelding uten relasjon mellom arbeidstaker og behandler") { + val behandlerRef = UUID.randomUUID() + val partnerId = PartnerId(random.nextInt()) + val behandler = generateBehandler(behandlerRef, partnerId) + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) - val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandlerRef, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, - ) - lagreDialogmeldingBestilling( - database = database, - behandler = behandler, - dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO, - ) + val dialogmeldingBestillingUuid = UUID.randomUUID() - val pBehandlerDialogmeldingBestillingBefore = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null - pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 + val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandlerRef, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_UTEN_FASTLEGE_FNR, + ) + lagreDialogmeldingBestilling( + database = database, + behandler = behandler, + dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO, + ) - runBlocking { - val result = dialogmeldingSendCronjob.dialogmeldingSendJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 1 - } - verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } + val pBehandlerDialogmeldingBestillingBefore = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null + pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 - val pBehandlerDialogmeldingBestillingAfter = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 + runBlocking { + val result = dialogmeldingSendCronjob.dialogmeldingSendJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 1 } - it("Sender bestilt oppfølgingsplan") { - clearAllMocks() - val messageSlot = slot() - justRun { mqSenderMock.sendMessageToEmottak(capture(messageSlot)) } - val behandlerRef = UUID.randomUUID() - val partnerId = PartnerId(1) - val behandler = generateBehandler( - behandlerRef = behandlerRef, - partnerId = partnerId, - kontornavn = "navn", - ) - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR_OPPFOLGINGSPLAN, - ) - - val dialogmeldingBestillingUuid = UUID.randomUUID() + verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } - val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingOppfolgingsplanDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandlerRef, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR_OPPFOLGINGSPLAN, - ) - lagreDialogmeldingBestilling( - database = database, - behandler = behandler, - dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO - ) + val pBehandlerDialogmeldingBestillingAfter = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 + } + it("Sender bestilt oppfølgingsplan") { + clearAllMocks() + val messageSlot = slot() + justRun { mqSenderMock.sendMessageToEmottak(capture(messageSlot)) } + val behandlerRef = UUID.randomUUID() + val partnerId = PartnerId(1) + val behandler = generateBehandler( + behandlerRef = behandlerRef, + partnerId = partnerId, + kontornavn = "navn", + ) + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR_OPPFOLGINGSPLAN, + ) - val pBehandlerDialogmeldingBestillingBefore = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null - pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 + val dialogmeldingBestillingUuid = UUID.randomUUID() - runBlocking { - val result = dialogmeldingSendCronjob.dialogmeldingSendJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 1 - } - verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } - val expectedFellesformatMessageAsRegex = defaultFellesformatMessageXmlRegex() - val actualFellesformatMessage = messageSlot.captured + val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingOppfolgingsplanDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandlerRef, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR_OPPFOLGINGSPLAN, + ) + lagreDialogmeldingBestilling( + database = database, + behandler = behandler, + dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO + ) - Assert.assertTrue( - expectedFellesformatMessageAsRegex.matches(actualFellesformatMessage), - ) + val pBehandlerDialogmeldingBestillingBefore = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingBefore shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingBefore!!.sendt shouldBeEqualTo null + pBehandlerDialogmeldingBestillingBefore.sendtTries shouldBeEqualTo 0 - val pBehandlerDialogmeldingBestillingAfter = - database.getBestilling(uuid = dialogmeldingBestillingUuid) - pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null - pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 + runBlocking { + val result = dialogmeldingSendCronjob.dialogmeldingSendJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 1 } - it("Sending av bestilt dialogmelding lagrer dialogmelding-status SENDT") { - val behandlerRef = UUID.randomUUID() - val partnerId = PartnerId(random.nextInt()) - val behandler = generateBehandler(behandlerRef, partnerId) - database.createBehandlerForArbeidstaker( - behandler = behandler, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) + verify(exactly = 1) { mqSenderMock.sendMessageToEmottak(any()) } + val expectedFellesformatMessageAsRegex = defaultFellesformatMessageXmlRegex() + val actualFellesformatMessage = messageSlot.captured - val dialogmeldingBestillingUuid = UUID.randomUUID() - val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( - uuid = dialogmeldingBestillingUuid, - behandlerRef = behandlerRef, - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) - lagreDialogmeldingBestilling( - database = database, - behandler = behandler, - dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO - ) - val pBehandlerDialogmeldingBestilling = database.getBestilling(uuid = dialogmeldingBestillingUuid) + assertTrue( + expectedFellesformatMessageAsRegex.matches(actualFellesformatMessage), + ) - runBlocking { - dialogmeldingSendCronjob.dialogmeldingSendJob() - } + val pBehandlerDialogmeldingBestillingAfter = + database.getBestilling(uuid = dialogmeldingBestillingUuid) + pBehandlerDialogmeldingBestillingAfter!!.sendt shouldNotBeEqualTo null + pBehandlerDialogmeldingBestillingAfter.sendtTries shouldBeEqualTo 1 + } + it("Sending av bestilt dialogmelding lagrer dialogmelding-status SENDT") { + val behandlerRef = UUID.randomUUID() + val partnerId = PartnerId(random.nextInt()) + val behandler = generateBehandler(behandlerRef, partnerId) + database.createBehandlerForArbeidstaker( + behandler = behandler, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) - val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() - dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 + val dialogmeldingBestillingUuid = UUID.randomUUID() + val dialogmeldingBestillingDTO = generateDialogmeldingToBehandlerBestillingDTO( + uuid = dialogmeldingBestillingUuid, + behandlerRef = behandlerRef, + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) + lagreDialogmeldingBestilling( + database = database, + behandler = behandler, + dialogmeldingToBehandlerBestillingDTO = dialogmeldingBestillingDTO + ) + val pBehandlerDialogmeldingBestilling = database.getBestilling(uuid = dialogmeldingBestillingUuid) - val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() - pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.SENDT.name - pDialogmeldingStatus.tekst.shouldBeNull() - pDialogmeldingStatus.bestillingId shouldBeEqualTo pBehandlerDialogmeldingBestilling?.id - pDialogmeldingStatus.createdAt.shouldNotBeNull() - pDialogmeldingStatus.updatedAt.shouldNotBeNull() - pDialogmeldingStatus.publishedAt.shouldBeNull() + runBlocking { + dialogmeldingSendCronjob.dialogmeldingSendJob() } + + val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() + dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 + + val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() + pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.SENDT.name + pDialogmeldingStatus.tekst.shouldBeNull() + pDialogmeldingStatus.bestillingId shouldBeEqualTo pBehandlerDialogmeldingBestilling?.id + pDialogmeldingStatus.createdAt.shouldNotBeNull() + pDialogmeldingStatus.updatedAt.shouldNotBeNull() + pDialogmeldingStatus.publishedAt.shouldBeNull() } } } diff --git a/src/test/kotlin/no/nav/syfo/cronjob/SuspensjonCronjobSpek.kt b/src/test/kotlin/no/nav/syfo/cronjob/SuspensjonCronjobSpek.kt index c1599566..8ebe53e8 100644 --- a/src/test/kotlin/no/nav/syfo/cronjob/SuspensjonCronjobSpek.kt +++ b/src/test/kotlin/no/nav/syfo/cronjob/SuspensjonCronjobSpek.kt @@ -1,6 +1,5 @@ package no.nav.syfo.cronjob -import io.ktor.server.testing.* import kotlinx.coroutines.runBlocking import no.nav.syfo.behandler.BehandlerService import no.nav.syfo.behandler.database.getBehandlerByBehandlerRef @@ -11,88 +10,57 @@ import no.nav.syfo.client.btsys.LegeSuspensjonClient import no.nav.syfo.testhelper.* import no.nav.syfo.testhelper.UserConstants.PARTNERID import no.nav.syfo.testhelper.generator.generateBehandler -import org.amshove.kluent.* +import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.* class SuspensjonCronjobSpek : Spek({ describe(SuspensjonCronjobSpek::class.java.simpleName) { - with(TestApplicationEngine()) { - start() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val environment = externalMockEnvironment.environment - val azureAdClient = AzureAdClient( - azureAppClientId = environment.aadAppClient, - azureAppClientSecret = environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val environment = externalMockEnvironment.environment + val azureAdClient = AzureAdClient( + azureAppClientId = environment.aadAppClient, + azureAppClientSecret = environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val behandlerService = BehandlerService( + fastlegeClient = FastlegeClient( + azureAdClient = azureAdClient, + fastlegeRestClientId = environment.fastlegeRestClientId, + fastlegeRestUrl = environment.fastlegeRestUrl, httpClient = externalMockEnvironment.mockHttpClient, - ) - val behandlerService = BehandlerService( - fastlegeClient = FastlegeClient( - azureAdClient = azureAdClient, - fastlegeRestClientId = environment.fastlegeRestClientId, - fastlegeRestUrl = environment.fastlegeRestUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - partnerinfoClient = PartnerinfoClient( - azureAdClient = azureAdClient, - syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, - syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - database = database, - ) - val cronJob = SuspensjonCronjob( - behandlerService = behandlerService, - legeSuspensjonClient = LegeSuspensjonClient( - azureAdClient = azureAdClient, - endpointClientId = environment.btsysClientId, - endpointUrl = environment.btsysUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - ) - beforeEachTest { - database.dropData() - } + ), + partnerinfoClient = PartnerinfoClient( + azureAdClient = azureAdClient, + syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, + syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ), + database = database, + ) + val cronJob = SuspensjonCronjob( + behandlerService = behandlerService, + legeSuspensjonClient = LegeSuspensjonClient( + azureAdClient = azureAdClient, + endpointClientId = environment.btsysClientId, + endpointUrl = environment.btsysUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ), + ) + beforeEachTest { + database.dropData() + } - describe("Cronjob oppdaterer suspendert for behandlere") { - it("Cronjob virker selv om ingen behandlere") { - runBlocking { - cronJob.checkLegeSuspensjonJob() - } - } - it("Cronjob bevarer suspendert=false for eksisterende behandler") { - val behandlerUUID = database.createBehandlerForArbeidstaker( - behandler = generateBehandler( - behandlerRef = UUID.randomUUID(), - partnerId = PARTNERID, - ), - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) - runBlocking { - cronJob.checkLegeSuspensjonJob() - } - database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo false - } - } - it("Cronjob setter suspendert=true for suspendert behandler") { - val behandlerUUID = database.createBehandlerForArbeidstaker( - behandler = generateBehandler( - behandlerRef = UUID.randomUUID(), - partnerId = PARTNERID, - personident = UserConstants.FASTLEGE_FNR_SUSPENDERT, - ), - arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, - ) - database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo false + describe("Cronjob oppdaterer suspendert for behandlere") { + it("Cronjob virker selv om ingen behandlere") { runBlocking { cronJob.checkLegeSuspensjonJob() } - database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo true } - it("Cronjob setter suspendert=false for behandler som ikke lengre er suspendert") { + it("Cronjob bevarer suspendert=false for eksisterende behandler") { val behandlerUUID = database.createBehandlerForArbeidstaker( behandler = generateBehandler( behandlerRef = UUID.randomUUID(), @@ -100,13 +68,41 @@ class SuspensjonCronjobSpek : Spek({ ), arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, ) - database.setSuspendert(behandlerUUID.toString()) - database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo true runBlocking { cronJob.checkLegeSuspensjonJob() } database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo false } } + it("Cronjob setter suspendert=true for suspendert behandler") { + val behandlerUUID = database.createBehandlerForArbeidstaker( + behandler = generateBehandler( + behandlerRef = UUID.randomUUID(), + partnerId = PARTNERID, + personident = UserConstants.FASTLEGE_FNR_SUSPENDERT, + ), + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) + database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo false + runBlocking { + cronJob.checkLegeSuspensjonJob() + } + database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo true + } + it("Cronjob setter suspendert=false for behandler som ikke lengre er suspendert") { + val behandlerUUID = database.createBehandlerForArbeidstaker( + behandler = generateBehandler( + behandlerRef = UUID.randomUUID(), + partnerId = PARTNERID, + ), + arbeidstakerPersonident = UserConstants.ARBEIDSTAKER_FNR, + ) + database.setSuspendert(behandlerUUID.toString()) + database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo true + runBlocking { + cronJob.checkLegeSuspensjonJob() + } + database.getBehandlerByBehandlerRef(behandlerUUID)!!.suspendert shouldBeEqualTo false + } } }) diff --git a/src/test/kotlin/no/nav/syfo/cronjob/VerifyBehandlereForKontorCronjobSpek.kt b/src/test/kotlin/no/nav/syfo/cronjob/VerifyBehandlereForKontorCronjobSpek.kt index fb7337d0..0e1e235b 100644 --- a/src/test/kotlin/no/nav/syfo/cronjob/VerifyBehandlereForKontorCronjobSpek.kt +++ b/src/test/kotlin/no/nav/syfo/cronjob/VerifyBehandlereForKontorCronjobSpek.kt @@ -1,6 +1,5 @@ package no.nav.syfo.cronjob -import io.ktor.server.testing.* import io.mockk.clearAllMocks import kotlinx.coroutines.runBlocking import no.nav.syfo.behandler.BehandlerService @@ -14,7 +13,7 @@ import no.nav.syfo.client.azuread.AzureAdClient import no.nav.syfo.client.syfohelsenettproxy.SyfohelsenettproxyClient import no.nav.syfo.dialogmelding.apprec.database import no.nav.syfo.domain.Personident -import no.nav.syfo.testhelper.* +import no.nav.syfo.testhelper.ExternalMockEnvironment import no.nav.syfo.testhelper.UserConstants.BEHANDLER_ETTERNAVN import no.nav.syfo.testhelper.UserConstants.BEHANDLER_FORNAVN import no.nav.syfo.testhelper.UserConstants.FASTLEGE_DNR @@ -30,7 +29,12 @@ import no.nav.syfo.testhelper.UserConstants.HPRID_UNKNOWN import no.nav.syfo.testhelper.UserConstants.HPRID_UTEN_KATEGORI import no.nav.syfo.testhelper.UserConstants.KONTOR_NAVN import no.nav.syfo.testhelper.UserConstants.PARTNERID -import org.amshove.kluent.* +import no.nav.syfo.testhelper.createKontor +import no.nav.syfo.testhelper.dropData +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldNotBe +import org.amshove.kluent.shouldNotBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.OffsetDateTime @@ -38,293 +42,290 @@ import java.util.* class VerifyBehandlereForKontorCronjobSpek : Spek({ describe(VerifyBehandlereForKontorCronjobSpek::class.java.simpleName) { - with(TestApplicationEngine()) { - start() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val environment = externalMockEnvironment.environment - val azureAdClient = AzureAdClient( - azureAppClientId = environment.aadAppClient, - azureAppClientSecret = environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, - httpClient = externalMockEnvironment.mockHttpClient, - ) - val syfohelsenettproxyClient = SyfohelsenettproxyClient( - azureAdClient = azureAdClient, - endpointUrl = environment.syfohelsenettproxyUrl, - endpointClientId = environment.syfohelsenettproxyClientId, - httpClient = externalMockEnvironment.mockHttpClient, - ) - val fastlegeClient = FastlegeClient( + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val environment = externalMockEnvironment.environment + val azureAdClient = AzureAdClient( + azureAppClientId = environment.aadAppClient, + azureAppClientSecret = environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val syfohelsenettproxyClient = SyfohelsenettproxyClient( + azureAdClient = azureAdClient, + endpointUrl = environment.syfohelsenettproxyUrl, + endpointClientId = environment.syfohelsenettproxyClientId, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val fastlegeClient = FastlegeClient( + azureAdClient = azureAdClient, + fastlegeRestClientId = environment.fastlegeRestClientId, + fastlegeRestUrl = environment.fastlegeRestUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val behandlerService = BehandlerService( + fastlegeClient = FastlegeClient( azureAdClient = azureAdClient, fastlegeRestClientId = environment.fastlegeRestClientId, fastlegeRestUrl = environment.fastlegeRestUrl, httpClient = externalMockEnvironment.mockHttpClient, - ) - val behandlerService = BehandlerService( - fastlegeClient = FastlegeClient( - azureAdClient = azureAdClient, - fastlegeRestClientId = environment.fastlegeRestClientId, - fastlegeRestUrl = environment.fastlegeRestUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - partnerinfoClient = PartnerinfoClient( - azureAdClient = azureAdClient, - syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, - syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - database = database, - ) - val behandlerToBeUpdated = UUID.randomUUID() - val cronJob = VerifyBehandlereForKontorCronjob( - behandlerService = behandlerService, - fastlegeClient = fastlegeClient, - syfohelsenettproxyClient = syfohelsenettproxyClient, - behandlerToBeUpdated = listOf(behandlerToBeUpdated), - ) - beforeEachTest { - database.dropData() - clearAllMocks() - } + ), + partnerinfoClient = PartnerinfoClient( + azureAdClient = azureAdClient, + syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, + syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ), + database = database, + ) + val behandlerToBeUpdated = UUID.randomUUID() + val cronJob = VerifyBehandlereForKontorCronjob( + behandlerService = behandlerService, + fastlegeClient = fastlegeClient, + syfohelsenettproxyClient = syfohelsenettproxyClient, + behandlerToBeUpdated = listOf(behandlerToBeUpdated), + ) + beforeEachTest { + database.dropData() + clearAllMocks() + } - describe("Cronjob sjekker eksisterende behandlerkontor") { - it("Cronjob virker selv om ingen kontor") { - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } + describe("Cronjob sjekker eksisterende behandlerkontor") { + it("Cronjob virker selv om ingen kontor") { + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob disabler kontor som ikke lengre er aktivt") { - val kontorId = createKontor(HERID_NOT_ACTIVE) - val kontorBefore = database.getBehandlerKontorById(kontorId) - kontorBefore.dialogmeldingEnabled shouldNotBeEqualTo null - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val kontorAfter = database.getBehandlerKontorById(kontorId) - kontorAfter.dialogmeldingEnabled shouldBeEqualTo null + } + it("Cronjob disabler kontor som ikke lengre er aktivt") { + val kontorId = createKontor(HERID_NOT_ACTIVE) + val kontorBefore = database.getBehandlerKontorById(kontorId) + kontorBefore.dialogmeldingEnabled shouldNotBeEqualTo null + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob endrer ikke kontorets aktivflagg hvis fortsatt aktivt ") { - val kontorId = createKontor(HERID_KONTOR_OK) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val kontorAfter = database.getBehandlerKontorById(kontorId) - kontorAfter.dialogmeldingEnabled shouldNotBeEqualTo null + val kontorAfter = database.getBehandlerKontorById(kontorId) + kontorAfter.dialogmeldingEnabled shouldBeEqualTo null + } + it("Cronjob endrer ikke kontorets aktivflagg hvis fortsatt aktivt ") { + val kontorId = createKontor(HERID_KONTOR_OK) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob setter hprId på behandlere som mangler det") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler( - kontorId = kontorId, - hprId = null, - personident = FASTLEGE_FNR, - ) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.hprId shouldBeEqualTo HPRID.toString() + val kontorAfter = database.getBehandlerKontorById(kontorId) + kontorAfter.dialogmeldingEnabled shouldNotBeEqualTo null + } + it("Cronjob setter hprId på behandlere som mangler det") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler( + kontorId = kontorId, + hprId = null, + personident = FASTLEGE_FNR, + ) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob invaliderer behandler som ikke finnes for kontor i Adresseregisteret") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler(kontorId, HPRID_UNKNOWN) - val behandlerBefore = database.getBehandlerById(pBehandler.id) - behandlerBefore!!.invalidated shouldBe null - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.invalidated shouldNotBe null + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.hprId shouldBeEqualTo HPRID.toString() + } + it("Cronjob invaliderer behandler som ikke finnes for kontor i Adresseregisteret") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler(kontorId, HPRID_UNKNOWN) + val behandlerBefore = database.getBehandlerById(pBehandler.id) + behandlerBefore!!.invalidated shouldBe null + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob invaliderer ikke behandler knyttet til Aleris") { - val kontorId = createKontor(ALERIS_HER_ID.toInt()) - val pBehandler = createBehandler(kontorId, HPRID_UNKNOWN) - val behandlerBefore = database.getBehandlerById(pBehandler.id) - behandlerBefore!!.invalidated shouldBe null - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.invalidated shouldBe null + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.invalidated shouldNotBe null + } + it("Cronjob invaliderer ikke behandler knyttet til Aleris") { + val kontorId = createKontor(ALERIS_HER_ID.toInt()) + val pBehandler = createBehandler(kontorId, HPRID_UNKNOWN) + val behandlerBefore = database.getBehandlerById(pBehandler.id) + behandlerBefore!!.invalidated shouldBe null + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob invaliderer behandler som er inaktiv i Adresseregisteret") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler(kontorId) - val behandlerBefore = database.getBehandlerById(pBehandler.id) - behandlerBefore!!.invalidated shouldBe null - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.invalidated shouldNotBe null + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.invalidated shouldBe null + } + it("Cronjob invaliderer behandler som er inaktiv i Adresseregisteret") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler(kontorId) + val behandlerBefore = database.getBehandlerById(pBehandler.id) + behandlerBefore!!.invalidated shouldBe null + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob revaliderer behandler som er aktiv i Adresseregisteret") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler(kontorId, HPRID) - database.invalidateBehandler(pBehandler.behandlerRef) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.invalidated shouldBe null + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.invalidated shouldNotBe null + } + it("Cronjob revaliderer behandler som er aktiv i Adresseregisteret") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler(kontorId, HPRID) + database.invalidateBehandler(pBehandler.behandlerRef) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob revaliderer ikke duplikat") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandlerInaktiv = createBehandler(kontorId, HPRID) - database.invalidateBehandler(pBehandlerInaktiv.behandlerRef) - val pBehandlerAktiv = createBehandler(kontorId, HPRID) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerInaktivAfter = database.getBehandlerById(pBehandlerInaktiv.id) - behandlerInaktivAfter!!.invalidated shouldNotBe null - val behandlerAktivAfter = database.getBehandlerById(pBehandlerAktiv.id) - behandlerAktivAfter!!.invalidated shouldBe null + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.invalidated shouldBe null + } + it("Cronjob revaliderer ikke duplikat") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandlerInaktiv = createBehandler(kontorId, HPRID) + database.invalidateBehandler(pBehandlerInaktiv.behandlerRef) + val pBehandlerAktiv = createBehandler(kontorId, HPRID) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob legger til ny behandlere") { - val kontorId = createKontor(HERID_KONTOR_OK) - val behandlerBefore = database.getBehandlereForKontor(kontorId) - behandlerBefore.size shouldBeEqualTo 0 - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlereForKontor(kontorId) - behandlerAfter.size shouldBeEqualTo 2 + val behandlerInaktivAfter = database.getBehandlerById(pBehandlerInaktiv.id) + behandlerInaktivAfter!!.invalidated shouldNotBe null + val behandlerAktivAfter = database.getBehandlerById(pBehandlerAktiv.id) + behandlerAktivAfter!!.invalidated shouldBe null + } + it("Cronjob legger til ny behandlere") { + val kontorId = createKontor(HERID_KONTOR_OK) + val behandlerBefore = database.getBehandlereForKontor(kontorId) + behandlerBefore.size shouldBeEqualTo 0 + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob oppdaterer eksisterende behandler") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler( - kontorId = kontorId, - hprId = HPRID, - personident = FASTLEGE_FNR, - fornavn = "for", - etternavn = "etter", - kategori = BehandlerKategori.TANNLEGE, - ) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlereForKontor(kontorId) - behandlerAfter.size shouldBeEqualTo 2 - val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } - pBehandlerAfter.id shouldBeEqualTo pBehandler.id - pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef - pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN - pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN - pBehandlerAfter.herId shouldBeEqualTo HERID.toString() - pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + val behandlerAfter = database.getBehandlereForKontor(kontorId) + behandlerAfter.size shouldBeEqualTo 2 + } + it("Cronjob oppdaterer eksisterende behandler") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler( + kontorId = kontorId, + hprId = HPRID, + personident = FASTLEGE_FNR, + fornavn = "for", + etternavn = "etter", + kategori = BehandlerKategori.TANNLEGE, + ) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob oppdaterer eksisterende behandler selv om kategori mangler i Adresseregisteret") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler( - kontorId = kontorId, - hprId = HPRID_UTEN_KATEGORI, - personident = FASTLEGE_UTEN_KATEGORI_FNR, - fornavn = "for", - etternavn = "etter", - kategori = BehandlerKategori.TANNLEGE, - ) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlereForKontor(kontorId) - behandlerAfter.size shouldBeEqualTo 2 - val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID_UTEN_KATEGORI.toString() } - pBehandlerAfter.id shouldBeEqualTo pBehandler.id - pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef - pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN - pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN - pBehandlerAfter.herId shouldBeEqualTo HERID.toString() - pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.TANNLEGE.name + val behandlerAfter = database.getBehandlereForKontor(kontorId) + behandlerAfter.size shouldBeEqualTo 2 + val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } + pBehandlerAfter.id shouldBeEqualTo pBehandler.id + pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef + pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN + pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN + pBehandlerAfter.herId shouldBeEqualTo HERID.toString() + pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + } + it("Cronjob oppdaterer eksisterende behandler selv om kategori mangler i Adresseregisteret") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler( + kontorId = kontorId, + hprId = HPRID_UTEN_KATEGORI, + personident = FASTLEGE_UTEN_KATEGORI_FNR, + fornavn = "for", + etternavn = "etter", + kategori = BehandlerKategori.TANNLEGE, + ) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob oppdaterer eksisterende behandler med DNR der forekomsten i Adresseregisteret har FNR") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler( - kontorId = kontorId, - hprId = HPRID, - personident = FASTLEGE_DNR, - fornavn = "for", - etternavn = "etter", - kategori = BehandlerKategori.LEGE, - ) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlereForKontor(kontorId) - behandlerAfter.size shouldBeEqualTo 2 - val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } - pBehandlerAfter.id shouldBeEqualTo pBehandler.id - pBehandlerAfter.personident shouldBeEqualTo FASTLEGE_FNR.value - pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef - pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN - pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN - pBehandlerAfter.herId shouldBeEqualTo HERID.toString() - pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + val behandlerAfter = database.getBehandlereForKontor(kontorId) + behandlerAfter.size shouldBeEqualTo 2 + val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID_UTEN_KATEGORI.toString() } + pBehandlerAfter.id shouldBeEqualTo pBehandler.id + pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef + pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN + pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN + pBehandlerAfter.herId shouldBeEqualTo HERID.toString() + pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.TANNLEGE.name + } + it("Cronjob oppdaterer eksisterende behandler med DNR der forekomsten i Adresseregisteret har FNR") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler( + kontorId = kontorId, + hprId = HPRID, + personident = FASTLEGE_DNR, + fornavn = "for", + etternavn = "etter", + kategori = BehandlerKategori.LEGE, + ) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob oppdaterer spesifikk behandler") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler( - behandlerRef = behandlerToBeUpdated, - kontorId = kontorId, - hprId = HPRID, - personident = FASTLEGE_TREDJE_FNR, - fornavn = "for", - etternavn = "etter", - kategori = BehandlerKategori.LEGE, - ) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerAfter = database.getBehandlereForKontor(kontorId) - behandlerAfter.size shouldBeEqualTo 2 - val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } - pBehandlerAfter.id shouldBeEqualTo pBehandler.id - pBehandlerAfter.personident shouldBeEqualTo FASTLEGE_FNR.value - pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef - pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN - pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN - pBehandlerAfter.herId shouldBeEqualTo HERID.toString() - pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + val behandlerAfter = database.getBehandlereForKontor(kontorId) + behandlerAfter.size shouldBeEqualTo 2 + val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } + pBehandlerAfter.id shouldBeEqualTo pBehandler.id + pBehandlerAfter.personident shouldBeEqualTo FASTLEGE_FNR.value + pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef + pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN + pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN + pBehandlerAfter.herId shouldBeEqualTo HERID.toString() + pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + } + it("Cronjob oppdaterer spesifikk behandler") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler( + behandlerRef = behandlerToBeUpdated, + kontorId = kontorId, + hprId = HPRID, + personident = FASTLEGE_TREDJE_FNR, + fornavn = "for", + etternavn = "etter", + kategori = BehandlerKategori.LEGE, + ) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob legger til ny behandler og invaliderer eksisterende") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler = createBehandler(kontorId) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) - behandlerForKontorAfter.size shouldBeEqualTo 3 - val behandlerAfter = database.getBehandlerById(pBehandler.id) - behandlerAfter!!.invalidated shouldNotBe null + val behandlerAfter = database.getBehandlereForKontor(kontorId) + behandlerAfter.size shouldBeEqualTo 2 + val pBehandlerAfter = behandlerAfter.first { it.hprId == HPRID.toString() } + pBehandlerAfter.id shouldBeEqualTo pBehandler.id + pBehandlerAfter.personident shouldBeEqualTo FASTLEGE_FNR.value + pBehandlerAfter.behandlerRef shouldBeEqualTo pBehandler.behandlerRef + pBehandlerAfter.fornavn shouldBeEqualTo BEHANDLER_FORNAVN + pBehandlerAfter.etternavn shouldBeEqualTo BEHANDLER_ETTERNAVN + pBehandlerAfter.herId shouldBeEqualTo HERID.toString() + pBehandlerAfter.kategori shouldBeEqualTo BehandlerKategori.LEGE.name + } + it("Cronjob legger til ny behandler og invaliderer eksisterende") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler = createBehandler(kontorId) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob invaliderer duplikater") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler1 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_FNR) - val pBehandler2 = createBehandler(kontorId, HPRID) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) - behandlerForKontorAfter.size shouldBeEqualTo 3 - val behandler1After = database.getBehandlerById(pBehandler1.id) - behandler1After!!.invalidated shouldBe null - val behandler2After = database.getBehandlerById(pBehandler2.id) - behandler2After!!.invalidated shouldNotBe null + val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) + behandlerForKontorAfter.size shouldBeEqualTo 3 + val behandlerAfter = database.getBehandlerById(pBehandler.id) + behandlerAfter!!.invalidated shouldNotBe null + } + it("Cronjob invaliderer duplikater") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler1 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_FNR) + val pBehandler2 = createBehandler(kontorId, HPRID) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } - it("Cronjob invaliderer duplikat med D-nummer") { - val kontorId = createKontor(HERID_KONTOR_OK) - val pBehandler1 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_DNR) - val pBehandler2 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_FNR) - runBlocking { - cronJob.verifyBehandlereForKontorJob() - } - val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) - behandlerForKontorAfter.size shouldBeEqualTo 3 - val behandler1After = database.getBehandlerById(pBehandler1.id) - behandler1After!!.invalidated shouldNotBe null - val behandler2After = database.getBehandlerById(pBehandler2.id) - behandler2After!!.invalidated shouldBe null + val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) + behandlerForKontorAfter.size shouldBeEqualTo 3 + val behandler1After = database.getBehandlerById(pBehandler1.id) + behandler1After!!.invalidated shouldBe null + val behandler2After = database.getBehandlerById(pBehandler2.id) + behandler2After!!.invalidated shouldNotBe null + } + it("Cronjob invaliderer duplikat med D-nummer") { + val kontorId = createKontor(HERID_KONTOR_OK) + val pBehandler1 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_DNR) + val pBehandler2 = createBehandler(kontorId = kontorId, hprId = HPRID, personident = FASTLEGE_FNR) + runBlocking { + cronJob.verifyBehandlereForKontorJob() } + val behandlerForKontorAfter = database.getBehandlereForKontor(kontorId) + behandlerForKontorAfter.size shouldBeEqualTo 3 + val behandler1After = database.getBehandlerById(pBehandler1.id) + behandler1After!!.invalidated shouldNotBe null + val behandler2After = database.getBehandlerById(pBehandler2.id) + behandler2After!!.invalidated shouldBe null } } } diff --git a/src/test/kotlin/no/nav/syfo/cronjob/VerifyPartnerIdCronjobSpek.kt b/src/test/kotlin/no/nav/syfo/cronjob/VerifyPartnerIdCronjobSpek.kt index c439a280..cafc3828 100644 --- a/src/test/kotlin/no/nav/syfo/cronjob/VerifyPartnerIdCronjobSpek.kt +++ b/src/test/kotlin/no/nav/syfo/cronjob/VerifyPartnerIdCronjobSpek.kt @@ -1,6 +1,5 @@ package no.nav.syfo.cronjob -import io.ktor.server.testing.* import io.mockk.clearAllMocks import kotlinx.coroutines.runBlocking import no.nav.syfo.behandler.BehandlerService @@ -8,115 +7,115 @@ import no.nav.syfo.behandler.database.getBehandlerKontorById import no.nav.syfo.behandler.fastlege.FastlegeClient import no.nav.syfo.behandler.partnerinfo.PartnerinfoClient import no.nav.syfo.client.azuread.AzureAdClient -import no.nav.syfo.testhelper.* +import no.nav.syfo.testhelper.ExternalMockEnvironment import no.nav.syfo.testhelper.UserConstants.KONTOR_NAVN import no.nav.syfo.testhelper.UserConstants.OTHER_HERID import no.nav.syfo.testhelper.UserConstants.OTHER_PARTNERID import no.nav.syfo.testhelper.UserConstants.PARTNERID -import org.amshove.kluent.* +import no.nav.syfo.testhelper.createKontor +import no.nav.syfo.testhelper.dropData +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldNotBe import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class VerifyPartnerIdCronjobSpek : Spek({ describe(VerifyPartnerIdCronjobSpek::class.java.simpleName) { - with(TestApplicationEngine()) { - start() - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val environment = externalMockEnvironment.environment - val azureAdClient = AzureAdClient( - azureAppClientId = environment.aadAppClient, - azureAppClientSecret = environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val environment = externalMockEnvironment.environment + val azureAdClient = AzureAdClient( + azureAppClientId = environment.aadAppClient, + azureAppClientSecret = environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = environment.azureOpenidConfigTokenEndpoint, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val partnerinfoClient = PartnerinfoClient( + azureAdClient = azureAdClient, + syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, + syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val behandlerService = BehandlerService( + fastlegeClient = FastlegeClient( + azureAdClient = azureAdClient, + fastlegeRestClientId = environment.fastlegeRestClientId, + fastlegeRestUrl = environment.fastlegeRestUrl, httpClient = externalMockEnvironment.mockHttpClient, - ) - val partnerinfoClient = PartnerinfoClient( + ), + partnerinfoClient = PartnerinfoClient( azureAdClient = azureAdClient, syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, httpClient = externalMockEnvironment.mockHttpClient, - ) - val behandlerService = BehandlerService( - fastlegeClient = FastlegeClient( - azureAdClient = azureAdClient, - fastlegeRestClientId = environment.fastlegeRestClientId, - fastlegeRestUrl = environment.fastlegeRestUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - partnerinfoClient = PartnerinfoClient( - azureAdClient = azureAdClient, - syfoPartnerinfoClientId = environment.syfoPartnerinfoClientId, - syfoPartnerinfoUrl = environment.syfoPartnerinfoUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ), - database = database, - ) - val cronJob = VerifyPartnerIdCronjob( - behandlerService = behandlerService, - partnerinfoClient = partnerinfoClient, - ) - beforeEachTest { - database.dropData() - clearAllMocks() - } + ), + database = database, + ) + val cronJob = VerifyPartnerIdCronjob( + behandlerService = behandlerService, + partnerinfoClient = partnerinfoClient, + ) + beforeEachTest { + database.dropData() + clearAllMocks() + } - describe("Cronjob sjekker eksisterende behandlerkontor") { - it("Cronjob virker selv om ingen kontor") { - runBlocking { - cronJob.verifyPartnerIdJob() - } + describe("Cronjob sjekker eksisterende behandlerkontor") { + it("Cronjob virker selv om ingen kontor") { + runBlocking { + cronJob.verifyPartnerIdJob() } - it("Cronjob disabler duplikat kontor med udatert partnerID") { - val kontorId1 = database.createKontor( - partnerId = PARTNERID, - herId = OTHER_HERID, - navn = KONTOR_NAVN, - ) - val kontorId2 = database.createKontor( - partnerId = OTHER_PARTNERID, - herId = OTHER_HERID, - navn = KONTOR_NAVN, - ) - runBlocking { - cronJob.verifyPartnerIdJob() - } - val kontor1 = database.getBehandlerKontorById(kontorId1) - kontor1.dialogmeldingEnabled shouldBeEqualTo null - val kontor2 = database.getBehandlerKontorById(kontorId2) - kontor2.dialogmeldingEnabled shouldNotBe null + } + it("Cronjob disabler duplikat kontor med udatert partnerID") { + val kontorId1 = database.createKontor( + partnerId = PARTNERID, + herId = OTHER_HERID, + navn = KONTOR_NAVN, + ) + val kontorId2 = database.createKontor( + partnerId = OTHER_PARTNERID, + herId = OTHER_HERID, + navn = KONTOR_NAVN, + ) + runBlocking { + cronJob.verifyPartnerIdJob() } - it("Cronjob gjør ingenting med duplikat kontor med udatert partnerID hvis allerede disabled") { - val kontorId1 = database.createKontor( - partnerId = PARTNERID, - herId = OTHER_HERID, - navn = KONTOR_NAVN, - dialogmeldingEnabled = false, - ) - val kontorId2 = database.createKontor( - partnerId = OTHER_PARTNERID, - herId = OTHER_HERID, - navn = KONTOR_NAVN, - ) - runBlocking { - cronJob.verifyPartnerIdJob() - } - val kontor1 = database.getBehandlerKontorById(kontorId1) - kontor1.dialogmeldingEnabled shouldBeEqualTo null - val kontor2 = database.getBehandlerKontorById(kontorId2) - kontor2.dialogmeldingEnabled shouldNotBe null + val kontor1 = database.getBehandlerKontorById(kontorId1) + kontor1.dialogmeldingEnabled shouldBeEqualTo null + val kontor2 = database.getBehandlerKontorById(kontorId2) + kontor2.dialogmeldingEnabled shouldNotBe null + } + it("Cronjob gjør ingenting med duplikat kontor med udatert partnerID hvis allerede disabled") { + val kontorId1 = database.createKontor( + partnerId = PARTNERID, + herId = OTHER_HERID, + navn = KONTOR_NAVN, + dialogmeldingEnabled = false, + ) + val kontorId2 = database.createKontor( + partnerId = OTHER_PARTNERID, + herId = OTHER_HERID, + navn = KONTOR_NAVN, + ) + runBlocking { + cronJob.verifyPartnerIdJob() } - it("Cronjob gjør ingenting med kontor med udatert partnerID hvis det ikke finnes et annet kontor med samme herId") { - val kontorId = database.createKontor( - partnerId = PARTNERID, - herId = OTHER_HERID, - navn = KONTOR_NAVN, - ) - runBlocking { - cronJob.verifyPartnerIdJob() - } - val kontor = database.getBehandlerKontorById(kontorId) - kontor.dialogmeldingEnabled shouldNotBe null + val kontor1 = database.getBehandlerKontorById(kontorId1) + kontor1.dialogmeldingEnabled shouldBeEqualTo null + val kontor2 = database.getBehandlerKontorById(kontorId2) + kontor2.dialogmeldingEnabled shouldNotBe null + } + it("Cronjob gjør ingenting med kontor med udatert partnerID hvis det ikke finnes et annet kontor med samme herId") { + val kontorId = database.createKontor( + partnerId = PARTNERID, + herId = OTHER_HERID, + navn = KONTOR_NAVN, + ) + runBlocking { + cronJob.verifyPartnerIdJob() } + val kontor = database.getBehandlerKontorById(kontorId) + kontor.dialogmeldingEnabled shouldNotBe null } } } diff --git a/src/test/kotlin/no/nav/syfo/dialogmelding/DialogmeldingServiceSpek.kt b/src/test/kotlin/no/nav/syfo/dialogmelding/DialogmeldingServiceSpek.kt index df5ae21f..3d966c25 100644 --- a/src/test/kotlin/no/nav/syfo/dialogmelding/DialogmeldingServiceSpek.kt +++ b/src/test/kotlin/no/nav/syfo/dialogmelding/DialogmeldingServiceSpek.kt @@ -10,7 +10,7 @@ import no.nav.syfo.domain.PartnerId import no.nav.syfo.domain.Personident import no.nav.syfo.testhelper.* import no.nav.syfo.testhelper.generator.* -import org.junit.Assert.assertTrue +import org.junit.jupiter.api.Assertions.assertTrue import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.* diff --git a/src/test/kotlin/no/nav/syfo/dialogmelding/apprec/ApprecConsumerSpek.kt b/src/test/kotlin/no/nav/syfo/dialogmelding/apprec/ApprecConsumerSpek.kt index 3de22cb0..54a9461f 100644 --- a/src/test/kotlin/no/nav/syfo/dialogmelding/apprec/ApprecConsumerSpek.kt +++ b/src/test/kotlin/no/nav/syfo/dialogmelding/apprec/ApprecConsumerSpek.kt @@ -1,225 +1,225 @@ package no.nav.syfo.dialogmelding.apprec -import io.ktor.server.testing.* -import io.mockk.* +import io.mockk.clearAllMocks +import io.mockk.every +import io.mockk.mockk import kotlinx.coroutines.runBlocking -import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService -import no.nav.syfo.behandler.database.* +import no.nav.syfo.behandler.database.getBehandlerByBehandlerRef import no.nav.syfo.dialogmelding.apprec.consumer.ApprecConsumer import no.nav.syfo.dialogmelding.apprec.database.getApprec +import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService import no.nav.syfo.dialogmelding.status.database.getDialogmeldingStatusNotPublished import no.nav.syfo.dialogmelding.status.domain.DialogmeldingStatusType -import no.nav.syfo.testhelper.* -import no.nav.syfo.testhelper.testdata.* +import no.nav.syfo.testhelper.ExternalMockEnvironment +import no.nav.syfo.testhelper.dropData +import no.nav.syfo.testhelper.getFileAsString +import no.nav.syfo.testhelper.testdata.lagreDialogmeldingBestillingOgBehandler import org.amshove.kluent.* import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe -import java.util.UUID -import javax.jms.* +import java.util.* +import javax.jms.TextMessage val externalMockEnvironment = ExternalMockEnvironment.instance val database = externalMockEnvironment.database class ApprecConsumerSpek : Spek({ describe(ApprecConsumerSpek::class.java.simpleName) { - with(TestApplicationEngine()) { - start() - val incomingMessage = mockk(relaxed = true) + val incomingMessage = mockk(relaxed = true) - val apprecService = ApprecService( - database = database, - ) - val dialogmeldingToBehandlerService = - DialogmeldingToBehandlerService( - database = database, - pdlClient = mockk(), - ) - val apprecConsumer = ApprecConsumer( - applicationState = externalMockEnvironment.applicationState, + val apprecService = ApprecService( + database = database, + ) + val dialogmeldingToBehandlerService = + DialogmeldingToBehandlerService( database = database, - inputconsumer = mockk(), - apprecService = apprecService, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService + pdlClient = mockk(), ) + val apprecConsumer = ApprecConsumer( + applicationState = externalMockEnvironment.applicationState, + database = database, + inputconsumer = mockk(), + apprecService = apprecService, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService + ) + + describe("Prosesserer innkommet melding") { + + beforeEachTest { + database.dropData() + clearAllMocks() + } + it("Prosesserer innkommet melding (melding ok)") { + val apprecId = UUID.randomUUID() + val dialogmeldingBestillingUuid = UUID.randomUUID() + val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecOK.xml") + .replace("FiktivTestdata0001", apprecId.toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) + } - describe("Prosesserer innkommet melding") { + val pApprec = database.getApprec(apprecId) - beforeEachTest { - database.dropData() - clearAllMocks() - } - it("Prosesserer innkommet melding (melding ok)") { - val apprecId = UUID.randomUUID() - val dialogmeldingBestillingUuid = UUID.randomUUID() - val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecOK.xml") - .replace("FiktivTestdata0001", apprecId.toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val pApprec = database.getApprec(apprecId) - - pApprec shouldNotBe null - pApprec!!.uuid shouldBeEqualTo apprecId - pApprec.bestillingId shouldBeEqualTo bestillingId - pApprec.statusKode shouldBeEqualTo "1" - pApprec.statusTekst shouldBeEqualTo "OK" - pApprec.feilKode shouldBe null - pApprec.feilTekst shouldBe null + pApprec shouldNotBe null + pApprec!!.uuid shouldBeEqualTo apprecId + pApprec.bestillingId shouldBeEqualTo bestillingId + pApprec.statusKode shouldBeEqualTo "1" + pApprec.statusTekst shouldBeEqualTo "OK" + pApprec.feilKode shouldBe null + pApprec.feilTekst shouldBe null + } + it("Prosesserer innkommet melding (melding ok, med duplikat)") { + val apprecId = UUID.randomUUID() + val dialogmeldingBestillingUuid = UUID.randomUUID() + lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecOK.xml") + .replace("FiktivTestdata0001", apprecId.toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosesserer innkommet melding (melding ok, med duplikat)") { - val apprecId = UUID.randomUUID() - val dialogmeldingBestillingUuid = UUID.randomUUID() - lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecOK.xml") - .replace("FiktivTestdata0001", apprecId.toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val pApprec = database.getApprec(apprecId) - - pApprec shouldNotBe null - pApprec!!.uuid shouldBeEqualTo apprecId - - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } + + val pApprec = database.getApprec(apprecId) + + pApprec shouldNotBe null + pApprec!!.uuid shouldBeEqualTo apprecId + + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosesserer innkommet melding (melding ok, men ikke knyttet til kjent dialogmelding)") { - val apprecId = UUID.randomUUID() - val dialogmeldingBestillingUuid = UUID.randomUUID() - lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val ukjentDialogmeldingBestillingUuid = UUID.randomUUID() - val apprecXml = - getFileAsString("src/test/resources/apprecOK.xml") - .replace("FiktivTestdata0001", apprecId.toString()) - .replace( - "b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", - ukjentDialogmeldingBestillingUuid.toString() - ) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val pApprec = database.getApprec(apprecId) - - pApprec shouldBe null + } + it("Prosesserer innkommet melding (melding ok, men ikke knyttet til kjent dialogmelding)") { + val apprecId = UUID.randomUUID() + val dialogmeldingBestillingUuid = UUID.randomUUID() + lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val ukjentDialogmeldingBestillingUuid = UUID.randomUUID() + val apprecXml = + getFileAsString("src/test/resources/apprecOK.xml") + .replace("FiktivTestdata0001", apprecId.toString()) + .replace( + "b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", + ukjentDialogmeldingBestillingUuid.toString() + ) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosesserer innkommet melding (melding avvist)") { - val apprecId = UUID.randomUUID() - val dialogmeldingBestillingUuid = UUID.randomUUID() - val (bestillingId, behandler) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecError.xml") - .replace("FiktivTestdata0001", apprecId.toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val pApprec = database.getApprec(apprecId) - - pApprec shouldNotBe null - pApprec!!.uuid shouldBeEqualTo apprecId - pApprec.bestillingId shouldBeEqualTo bestillingId - pApprec.statusKode shouldBeEqualTo "2" - pApprec.statusTekst shouldBeEqualTo "Avvist" - pApprec.feilKode shouldBeEqualTo "X99" - pApprec.feilTekst shouldBeEqualTo "Annen feil" - - val oppdatertBehandler = database.getBehandlerByBehandlerRef(behandler.behandlerRef)!! - oppdatertBehandler.invalidated shouldBe null + + val pApprec = database.getApprec(apprecId) + + pApprec shouldBe null + } + it("Prosesserer innkommet melding (melding avvist)") { + val apprecId = UUID.randomUUID() + val dialogmeldingBestillingUuid = UUID.randomUUID() + val (bestillingId, behandler) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecError.xml") + .replace("FiktivTestdata0001", apprecId.toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosesserer innkommet melding (melding avvist, ukjent mottaker)") { - val apprecId = UUID.randomUUID() - val dialogmeldingBestillingUuid = UUID.randomUUID() - val (bestillingId, behandler) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecErrorUkjentMottaker.xml") - .replace("FiktivTestdata0001", apprecId.toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val pApprec = database.getApprec(apprecId) - - pApprec shouldNotBe null - pApprec!!.uuid shouldBeEqualTo apprecId - pApprec.bestillingId shouldBeEqualTo bestillingId - pApprec.statusKode shouldBeEqualTo "2" - pApprec.statusTekst shouldBeEqualTo "Avvist" - pApprec.feilKode shouldBeEqualTo "E21" - pApprec.feilTekst shouldBeEqualTo "Mottaker finnes ikke" - - val oppdatertBehandler = database.getBehandlerByBehandlerRef(behandler.behandlerRef)!! - oppdatertBehandler.invalidated shouldNotBe null + + val pApprec = database.getApprec(apprecId) + + pApprec shouldNotBe null + pApprec!!.uuid shouldBeEqualTo apprecId + pApprec.bestillingId shouldBeEqualTo bestillingId + pApprec.statusKode shouldBeEqualTo "2" + pApprec.statusTekst shouldBeEqualTo "Avvist" + pApprec.feilKode shouldBeEqualTo "X99" + pApprec.feilTekst shouldBeEqualTo "Annen feil" + + val oppdatertBehandler = database.getBehandlerByBehandlerRef(behandler.behandlerRef)!! + oppdatertBehandler.invalidated shouldBe null + } + it("Prosesserer innkommet melding (melding avvist, ukjent mottaker)") { + val apprecId = UUID.randomUUID() + val dialogmeldingBestillingUuid = UUID.randomUUID() + val (bestillingId, behandler) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecErrorUkjentMottaker.xml") + .replace("FiktivTestdata0001", apprecId.toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosesserer innkommet feilformattert melding") { - val apprecXml = "Ikke noen apprec" - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - // should not get an exception + + val pApprec = database.getApprec(apprecId) + + pApprec shouldNotBe null + pApprec!!.uuid shouldBeEqualTo apprecId + pApprec.bestillingId shouldBeEqualTo bestillingId + pApprec.statusKode shouldBeEqualTo "2" + pApprec.statusTekst shouldBeEqualTo "Avvist" + pApprec.feilKode shouldBeEqualTo "E21" + pApprec.feilTekst shouldBeEqualTo "Mottaker finnes ikke" + + val oppdatertBehandler = database.getBehandlerByBehandlerRef(behandler.behandlerRef)!! + oppdatertBehandler.invalidated shouldNotBe null + } + it("Prosesserer innkommet feilformattert melding") { + val apprecXml = "Ikke noen apprec" + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosessering av innkommet melding OK lagrer dialogmelding-status OK") { - val dialogmeldingBestillingUuid = UUID.randomUUID() - val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecOK.xml") - .replace("FiktivTestdata0001", UUID.randomUUID().toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() - dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 - - val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() - pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.OK.name - pDialogmeldingStatus.tekst?.shouldBeEmpty() - pDialogmeldingStatus.bestillingId shouldBeEqualTo bestillingId - pDialogmeldingStatus.createdAt.shouldNotBeNull() - pDialogmeldingStatus.updatedAt.shouldNotBeNull() - pDialogmeldingStatus.publishedAt.shouldBeNull() + // should not get an exception + } + it("Prosessering av innkommet melding OK lagrer dialogmelding-status OK") { + val dialogmeldingBestillingUuid = UUID.randomUUID() + val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecOK.xml") + .replace("FiktivTestdata0001", UUID.randomUUID().toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } - it("Prosessering av innkommet melding Avvist lagrer dialogmelding-status Avvist") { - val dialogmeldingBestillingUuid = UUID.randomUUID() - val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) - val apprecXml = - getFileAsString("src/test/resources/apprecError.xml") - .replace("FiktivTestdata0001", UUID.randomUUID().toString()) - .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) - every { incomingMessage.text } returns (apprecXml) - runBlocking { - apprecConsumer.processApprecMessage(incomingMessage) - } - - val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() - dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 - - val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() - pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.AVVIST.name - pDialogmeldingStatus.tekst shouldBeEqualTo "Annen feil" - pDialogmeldingStatus.bestillingId shouldBeEqualTo bestillingId - pDialogmeldingStatus.createdAt.shouldNotBeNull() - pDialogmeldingStatus.updatedAt.shouldNotBeNull() - pDialogmeldingStatus.publishedAt.shouldBeNull() + + val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() + dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 + + val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() + pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.OK.name + pDialogmeldingStatus.tekst?.shouldBeEmpty() + pDialogmeldingStatus.bestillingId shouldBeEqualTo bestillingId + pDialogmeldingStatus.createdAt.shouldNotBeNull() + pDialogmeldingStatus.updatedAt.shouldNotBeNull() + pDialogmeldingStatus.publishedAt.shouldBeNull() + } + it("Prosessering av innkommet melding Avvist lagrer dialogmelding-status Avvist") { + val dialogmeldingBestillingUuid = UUID.randomUUID() + val (bestillingId) = lagreDialogmeldingBestillingOgBehandler(database, dialogmeldingBestillingUuid) + val apprecXml = + getFileAsString("src/test/resources/apprecError.xml") + .replace("FiktivTestdata0001", UUID.randomUUID().toString()) + .replace("b62016eb-6c2d-417a-8ecc-157b3c5ee2ca", dialogmeldingBestillingUuid.toString()) + every { incomingMessage.text } returns (apprecXml) + runBlocking { + apprecConsumer.processApprecMessage(incomingMessage) } + + val dialogmeldingStatusNotPublished = database.getDialogmeldingStatusNotPublished() + dialogmeldingStatusNotPublished.size shouldBeEqualTo 1 + + val pDialogmeldingStatus = dialogmeldingStatusNotPublished.first() + pDialogmeldingStatus.status shouldBeEqualTo DialogmeldingStatusType.AVVIST.name + pDialogmeldingStatus.tekst shouldBeEqualTo "Annen feil" + pDialogmeldingStatus.bestillingId shouldBeEqualTo bestillingId + pDialogmeldingStatus.createdAt.shouldNotBeNull() + pDialogmeldingStatus.updatedAt.shouldNotBeNull() + pDialogmeldingStatus.publishedAt.shouldBeNull() } } } diff --git a/src/test/kotlin/no/nav/syfo/dialogmelding/converter/FellesformatConverterSpek.kt b/src/test/kotlin/no/nav/syfo/dialogmelding/converter/FellesformatConverterSpek.kt index 493c25fa..575f1f8f 100644 --- a/src/test/kotlin/no/nav/syfo/dialogmelding/converter/FellesformatConverterSpek.kt +++ b/src/test/kotlin/no/nav/syfo/dialogmelding/converter/FellesformatConverterSpek.kt @@ -7,7 +7,7 @@ import no.nav.syfo.domain.Personident import no.nav.syfo.fellesformat.Fellesformat import no.nav.syfo.testhelper.generator.* import no.nav.syfo.util.JAXB -import org.junit.Assert.assertTrue +import org.junit.jupiter.api.Assertions.assertTrue import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.* diff --git a/src/test/kotlin/no/nav/syfo/dialogmelding/cronjob/DialogmeldingStatusCronjobSpek.kt b/src/test/kotlin/no/nav/syfo/dialogmelding/cronjob/DialogmeldingStatusCronjobSpek.kt index a51de19f..bf228209 100644 --- a/src/test/kotlin/no/nav/syfo/dialogmelding/cronjob/DialogmeldingStatusCronjobSpek.kt +++ b/src/test/kotlin/no/nav/syfo/dialogmelding/cronjob/DialogmeldingStatusCronjobSpek.kt @@ -1,90 +1,92 @@ package no.nav.syfo.dialogmelding.cronjob -import io.ktor.server.testing.* import io.mockk.* import no.nav.syfo.dialogmelding.bestilling.DialogmeldingToBehandlerService import no.nav.syfo.dialogmelding.status.DialogmeldingStatusService import no.nav.syfo.dialogmelding.status.domain.DialogmeldingStatusType import no.nav.syfo.dialogmelding.status.kafka.DialogmeldingStatusProducer import no.nav.syfo.dialogmelding.status.kafka.KafkaDialogmeldingStatusDTO -import no.nav.syfo.testhelper.* +import no.nav.syfo.testhelper.ExternalMockEnvironment +import no.nav.syfo.testhelper.dropData +import no.nav.syfo.testhelper.getDialogmeldingStatuses import no.nav.syfo.testhelper.testdata.lagreDialogmeldingStatusBestiltOgSendt -import org.amshove.kluent.* -import org.apache.kafka.clients.producer.* +import org.amshove.kluent.shouldBeEqualTo +import org.amshove.kluent.shouldBeLessThan +import org.amshove.kluent.shouldNotBeEqualTo +import org.amshove.kluent.shouldNotBeNull +import org.apache.kafka.clients.producer.KafkaProducer +import org.apache.kafka.clients.producer.ProducerRecord +import org.apache.kafka.clients.producer.RecordMetadata import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.concurrent.Future class DialogmeldingStatusCronjobSpek : Spek({ - with(TestApplicationEngine()) { - start() + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( + database = database, + pdlClient = mockk(), + ) + val kafkaProducer = mockk>() + val dialogmeldingStatusService = DialogmeldingStatusService( + database = database, + dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, + dialogmeldingStatusProducer = DialogmeldingStatusProducer(kafkaProducer) + ) + val dialogmeldingStatusCronjob = DialogmeldingStatusCronjob( + dialogmeldingStatusService = dialogmeldingStatusService, + ) - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val dialogmeldingToBehandlerService = DialogmeldingToBehandlerService( - database = database, - pdlClient = mockk(), - ) - val kafkaProducer = mockk>() - val dialogmeldingStatusService = DialogmeldingStatusService( - database = database, - dialogmeldingToBehandlerService = dialogmeldingToBehandlerService, - dialogmeldingStatusProducer = DialogmeldingStatusProducer(kafkaProducer) - ) - val dialogmeldingStatusCronjob = DialogmeldingStatusCronjob( - dialogmeldingStatusService = dialogmeldingStatusService, - ) - - beforeEachTest { - database.dropData() - clearMocks(kafkaProducer) - coEvery { - kafkaProducer.send(any()) - } returns mockk>(relaxed = true) - } + beforeEachTest { + database.dropData() + clearMocks(kafkaProducer) + coEvery { + kafkaProducer.send(any()) + } returns mockk>(relaxed = true) + } - describe(DialogmeldingStatusCronjob::class.java.simpleName) { - it("Publishes unpublished dialogmelding statuses") { - lagreDialogmeldingStatusBestiltOgSendt(database) + describe(DialogmeldingStatusCronjob::class.java.simpleName) { + it("Publishes unpublished dialogmelding statuses") { + lagreDialogmeldingStatusBestiltOgSendt(database) - var result = dialogmeldingStatusCronjob.runJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 2 + var result = dialogmeldingStatusCronjob.runJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 2 - val kafkaRecordSlot1 = slot>() - val kafkaRecordSlot2 = slot>() - verifyOrder { - kafkaProducer.send(capture(kafkaRecordSlot1)) - kafkaProducer.send(capture(kafkaRecordSlot2)) - } - val firstPublishedStatus = kafkaRecordSlot1.captured.value() - val secondPublishedStatus = kafkaRecordSlot2.captured.value() + val kafkaRecordSlot1 = slot>() + val kafkaRecordSlot2 = slot>() + verifyOrder { + kafkaProducer.send(capture(kafkaRecordSlot1)) + kafkaProducer.send(capture(kafkaRecordSlot2)) + } + val firstPublishedStatus = kafkaRecordSlot1.captured.value() + val secondPublishedStatus = kafkaRecordSlot2.captured.value() - firstPublishedStatus.status shouldBeEqualTo DialogmeldingStatusType.BESTILT.name - secondPublishedStatus.status shouldBeEqualTo DialogmeldingStatusType.SENDT.name - firstPublishedStatus.bestillingUuid shouldBeEqualTo secondPublishedStatus.bestillingUuid - firstPublishedStatus.uuid shouldNotBeEqualTo secondPublishedStatus.uuid + firstPublishedStatus.status shouldBeEqualTo DialogmeldingStatusType.BESTILT.name + secondPublishedStatus.status shouldBeEqualTo DialogmeldingStatusType.SENDT.name + firstPublishedStatus.bestillingUuid shouldBeEqualTo secondPublishedStatus.bestillingUuid + firstPublishedStatus.uuid shouldNotBeEqualTo secondPublishedStatus.uuid - result = dialogmeldingStatusCronjob.runJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 0 + result = dialogmeldingStatusCronjob.runJob() + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 0 - val pDialogmeldingStatuses = database.getDialogmeldingStatuses() + val pDialogmeldingStatuses = database.getDialogmeldingStatuses() - pDialogmeldingStatuses.size shouldBeEqualTo 2 - pDialogmeldingStatuses.forEach { pDialogmeldingStatus -> - pDialogmeldingStatus.publishedAt.shouldNotBeNull() - pDialogmeldingStatus.createdAt shouldBeLessThan pDialogmeldingStatus.updatedAt - } + pDialogmeldingStatuses.size shouldBeEqualTo 2 + pDialogmeldingStatuses.forEach { pDialogmeldingStatus -> + pDialogmeldingStatus.publishedAt.shouldNotBeNull() + pDialogmeldingStatus.createdAt shouldBeLessThan pDialogmeldingStatus.updatedAt } - it("Publishes nothing when no unpublished dialogmelding statuses") { - val result = dialogmeldingStatusCronjob.runJob() + } + it("Publishes nothing when no unpublished dialogmelding statuses") { + val result = dialogmeldingStatusCronjob.runJob() - result.failed shouldBeEqualTo 0 - result.updated shouldBeEqualTo 0 + result.failed shouldBeEqualTo 0 + result.updated shouldBeEqualTo 0 - verify(exactly = 0) { kafkaProducer.send(any()) } - } + verify(exactly = 0) { kafkaProducer.send(any()) } } } }) diff --git a/src/test/kotlin/no/nav/syfo/identhendelse/IdenthendelseServiceSpek.kt b/src/test/kotlin/no/nav/syfo/identhendelse/IdenthendelseServiceSpek.kt index b8474a3f..5379b890 100644 --- a/src/test/kotlin/no/nav/syfo/identhendelse/IdenthendelseServiceSpek.kt +++ b/src/test/kotlin/no/nav/syfo/identhendelse/IdenthendelseServiceSpek.kt @@ -1,22 +1,25 @@ package no.nav.syfo.identhendelse -import io.ktor.server.testing.* -import kotlinx.coroutines.* +import kotlinx.coroutines.runBlocking import no.nav.syfo.application.database.DatabaseInterface -import no.nav.syfo.behandler.database.* +import no.nav.syfo.behandler.database.createBehandler +import no.nav.syfo.behandler.database.createBehandlerArbeidstakerRelasjon +import no.nav.syfo.behandler.database.createBehandlerKontor import no.nav.syfo.behandler.domain.Arbeidstaker import no.nav.syfo.behandler.domain.BehandlerArbeidstakerRelasjonstype -import no.nav.syfo.dialogmelding.bestilling.kafka.toDialogmeldingToBehandlerBestilling import no.nav.syfo.client.azuread.AzureAdClient import no.nav.syfo.client.pdl.PdlClient import no.nav.syfo.dialogmelding.bestilling.database.createBehandlerDialogmeldingBestilling +import no.nav.syfo.dialogmelding.bestilling.kafka.toDialogmeldingToBehandlerBestilling import no.nav.syfo.domain.PartnerId import no.nav.syfo.domain.Personident import no.nav.syfo.identhendelse.database.getIdentCount import no.nav.syfo.testhelper.ExternalMockEnvironment import no.nav.syfo.testhelper.UserConstants import no.nav.syfo.testhelper.dropData -import no.nav.syfo.testhelper.generator.* +import no.nav.syfo.testhelper.generator.generateBehandler +import no.nav.syfo.testhelper.generator.generateDialogmeldingToBehandlerBestillingDTO +import no.nav.syfo.testhelper.generator.generateKafkaIdenthendelseDTO import no.nav.syfo.testhelper.getBehandlerArbeidstakerRelasjoner import org.amshove.kluent.internal.assertFailsWith import org.amshove.kluent.shouldBeEqualTo @@ -29,106 +32,101 @@ import java.util.* object IdenthendelseServiceSpek : Spek({ describe(IdenthendelseServiceSpek::class.java.simpleName) { + val externalMockEnvironment = ExternalMockEnvironment.instance + val database = externalMockEnvironment.database + val azureAdClient = AzureAdClient( + azureAppClientId = externalMockEnvironment.environment.aadAppClient, + azureAppClientSecret = externalMockEnvironment.environment.azureAppClientSecret, + azureOpenidConfigTokenEndpoint = externalMockEnvironment.environment.azureOpenidConfigTokenEndpoint, + httpClient = externalMockEnvironment.mockHttpClient, + ) + val pdlClient = PdlClient( + azureAdClient = azureAdClient, + pdlClientId = externalMockEnvironment.environment.pdlClientId, + pdlUrl = externalMockEnvironment.environment.pdlUrl, + httpClient = externalMockEnvironment.mockHttpClient, + ) - with(TestApplicationEngine()) { - start() - - val externalMockEnvironment = ExternalMockEnvironment.instance - val database = externalMockEnvironment.database - val azureAdClient = AzureAdClient( - azureAppClientId = externalMockEnvironment.environment.aadAppClient, - azureAppClientSecret = externalMockEnvironment.environment.azureAppClientSecret, - azureOpenidConfigTokenEndpoint = externalMockEnvironment.environment.azureOpenidConfigTokenEndpoint, - httpClient = externalMockEnvironment.mockHttpClient, - ) - val pdlClient = PdlClient( - azureAdClient = azureAdClient, - pdlClientId = externalMockEnvironment.environment.pdlClientId, - pdlUrl = externalMockEnvironment.environment.pdlUrl, - httpClient = externalMockEnvironment.mockHttpClient, - ) - - val identhendelseService = IdenthendelseService( - database = database, - pdlClient = pdlClient, - ) - - beforeEachTest { - database.dropData() - } + val identhendelseService = IdenthendelseService( + database = database, + pdlClient = pdlClient, + ) - describe("Happy path") { - it("Skal oppdatere gamle identer når person har fått ny ident") { - val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO(hasOldPersonident = true) - val newIdent = kafkaIdenthendelseDTO.getActivePersonident()!! - val oldIdenter = kafkaIdenthendelseDTO.getInactivePersonidenter() + beforeEachTest { + database.dropData() + } - populateDatabase(oldIdenter.first(), database) + describe("Happy path") { + it("Skal oppdatere gamle identer når person har fått ny ident") { + val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO(hasOldPersonident = true) + val newIdent = kafkaIdenthendelseDTO.getActivePersonident()!! + val oldIdenter = kafkaIdenthendelseDTO.getInactivePersonidenter() - val oldBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(oldIdenter.first()) - val oldIdentUpdatedAt = oldBehandlerArbeidstaker.first().updatedAt + populateDatabase(oldIdenter.first(), database) - runBlocking { - identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) - } + val oldBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(oldIdenter.first()) + val oldIdentUpdatedAt = oldBehandlerArbeidstaker.first().updatedAt - val newIdentOccurrences = database.getIdentCount(listOf(newIdent)) - newIdentOccurrences shouldBeEqualTo 2 - val newBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(newIdent) - newBehandlerArbeidstaker.first().updatedAt shouldBeGreaterThan oldIdentUpdatedAt + runBlocking { + identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) } - it("Skal oppdatere gamle identer når person har fått ny ident, men kun tabeller som har en forekomst av gamle identer") { - val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO(hasOldPersonident = true) - val newIdent = kafkaIdenthendelseDTO.getActivePersonident()!! - val oldIdenter = kafkaIdenthendelseDTO.getInactivePersonidenter() + val newIdentOccurrences = database.getIdentCount(listOf(newIdent)) + newIdentOccurrences shouldBeEqualTo 2 + val newBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(newIdent) + newBehandlerArbeidstaker.first().updatedAt shouldBeGreaterThan oldIdentUpdatedAt + } - populateDatabase( - oldIdent = oldIdenter.first(), - database = database, - updateInAllTables = false, - ) + it("Skal oppdatere gamle identer når person har fått ny ident, men kun tabeller som har en forekomst av gamle identer") { + val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO(hasOldPersonident = true) + val newIdent = kafkaIdenthendelseDTO.getActivePersonident()!! + val oldIdenter = kafkaIdenthendelseDTO.getInactivePersonidenter() - val oldBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(oldIdenter.first()) - val oldIdentUpdatedAt = oldBehandlerArbeidstaker.first().updatedAt + populateDatabase( + oldIdent = oldIdenter.first(), + database = database, + updateInAllTables = false, + ) - runBlocking { - identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) - } + val oldBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(oldIdenter.first()) + val oldIdentUpdatedAt = oldBehandlerArbeidstaker.first().updatedAt - val newIdentOccurrences = database.getIdentCount(listOf(newIdent)) - newIdentOccurrences shouldBeEqualTo 1 - val newBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(newIdent) - newBehandlerArbeidstaker.first().updatedAt shouldBeGreaterThan oldIdentUpdatedAt + runBlocking { + identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) } + + val newIdentOccurrences = database.getIdentCount(listOf(newIdent)) + newIdentOccurrences shouldBeEqualTo 1 + val newBehandlerArbeidstaker = database.getBehandlerArbeidstakerRelasjoner(newIdent) + newBehandlerArbeidstaker.first().updatedAt shouldBeGreaterThan oldIdentUpdatedAt } + } - describe("Unhappy path") { - it("Skal kaste feil hvis PDL ikke har oppdatert identen") { - val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO( - personident = UserConstants.TREDJE_ARBEIDSTAKER_FNR, - hasOldPersonident = true, - ) - val oldIdent = kafkaIdenthendelseDTO.getInactivePersonidenter().first() + describe("Unhappy path") { + it("Skal kaste feil hvis PDL ikke har oppdatert identen") { + val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO( + personident = UserConstants.TREDJE_ARBEIDSTAKER_FNR, + hasOldPersonident = true, + ) + val oldIdent = kafkaIdenthendelseDTO.getInactivePersonidenter().first() - populateDatabase(oldIdent, database) + populateDatabase(oldIdent, database) - assertFailsWith(IllegalStateException::class) { - identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) - } + assertFailsWith(IllegalStateException::class) { + identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) } - it("Skal kaste RuntimeException hvis PDL gir en not_found ved henting av identer") { - val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO( - personident = UserConstants.ARBEIDSTAKER_FNR_WITH_ERROR, - hasOldPersonident = true, - ) - val oldIdent = kafkaIdenthendelseDTO.getInactivePersonidenter().first() - - populateDatabase(oldIdent, database) - - assertFailsWith(RuntimeException::class) { - identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) - } + } + it("Skal kaste RuntimeException hvis PDL gir en not_found ved henting av identer") { + val kafkaIdenthendelseDTO = generateKafkaIdenthendelseDTO( + personident = UserConstants.ARBEIDSTAKER_FNR_WITH_ERROR, + hasOldPersonident = true, + ) + val oldIdent = kafkaIdenthendelseDTO.getInactivePersonidenter().first() + + populateDatabase(oldIdent, database) + + assertFailsWith(RuntimeException::class) { + identhendelseService.handleIdenthendelse(kafkaIdenthendelseDTO) } } } diff --git a/src/test/kotlin/no/nav/syfo/testhelper/TestApplicationEngineUtils.kt b/src/test/kotlin/no/nav/syfo/testhelper/TestApplicationEngineUtils.kt new file mode 100644 index 00000000..027d6cb6 --- /dev/null +++ b/src/test/kotlin/no/nav/syfo/testhelper/TestApplicationEngineUtils.kt @@ -0,0 +1,21 @@ +package no.nav.syfo.testhelper + +import io.ktor.client.* +import io.ktor.client.plugins.contentnegotiation.* +import io.ktor.serialization.jackson.* +import io.ktor.server.testing.* +import no.nav.syfo.util.configure + +fun ApplicationTestBuilder.setupApiAndClient(): HttpClient { + application { + testApiModule( + externalMockEnvironment = ExternalMockEnvironment.instance + ) + } + val client = createClient { + install(ContentNegotiation) { + jackson { configure() } + } + } + return client +} diff --git a/src/test/kotlin/no/nav/syfo/util/XMLUtilSpek.kt b/src/test/kotlin/no/nav/syfo/util/XMLUtilSpek.kt index a1a2dd92..d8ca7635 100644 --- a/src/test/kotlin/no/nav/syfo/util/XMLUtilSpek.kt +++ b/src/test/kotlin/no/nav/syfo/util/XMLUtilSpek.kt @@ -5,7 +5,7 @@ import no.nav.syfo.testhelper.UserConstants import no.nav.syfo.testhelper.generator.* import no.nav.xml.eiff._2.XMLMottakenhetBlokk import org.amshove.kluent.shouldBeEqualTo -import org.junit.Assert.assertThrows +import org.junit.jupiter.api.Assertions.assertThrows import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe