From 20dd78ead5f1e06a7bc2ddbf39bbc180a66f8d33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 07:59:44 +0100 Subject: [PATCH 1/6] Legger til dependabot --- .github/dependabot.yml | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8cc654a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,37 @@ +version: 2 +registries: + maven-github: + type: maven-repository + url: https://github-package-registry-mirror.gc.nav.no/cached/maven-release + username: x-access-token + password: no-secret-required +updates: + - package-ecosystem: "maven" + directory: "/" + registries: + - "maven-github" + schedule: + interval: "weekly" + day: "monday" + time: "06:00" + timezone: "Europe/Oslo" + commit-message: + prefix: "[dependency] " + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "06:00" + timezone: "Europe/Oslo" + commit-message: + prefix: "[docker] " + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "06:00" + timezone: "Europe/Oslo" + commit-message: + prefix: "[github-actions] " From e384a21941b32d6c7360299eee0b6f57f2f4dc57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 08:00:08 +0100 Subject: [PATCH 2/6] Setter ned cpu bruk --- .nais/nais.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.nais/nais.yaml b/.nais/nais.yaml index 16e42ef..0775f1d 100644 --- a/.nais/nais.yaml +++ b/.nais/nais.yaml @@ -48,7 +48,7 @@ spec: cpu: 1000m memory: 1024Mi requests: - cpu: 500m + cpu: 250m memory: 512Mi ingresses: {{#each ingresses as |url|}} From a5aac71a322e9abe5bc43953714df83bccc57979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 08:32:40 +0100 Subject: [PATCH 3/6] =?UTF-8?q?Versjonsbump=20p=C3=A5=20s=C3=A5=20og=20si?= =?UTF-8?q?=20alt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/pom.xml b/pom.xml index 0c01972..c80839a 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 3.1.2 + 3.2.1 @@ -20,22 +20,21 @@ - 5.2.1 - 20230427084654_4121ef0 - 20231010134706_52d8d27 - 7.13.0 + 5.3 + 2024.0111.144947 + 7.15.0 2.8.0 - 4.1.0 + 5.2.1 4.0.2 - 2.2.0 - 2.0 + 2.3.0 + 2.2 + 3.1.8 + 1.14.2 + 4.2.0 - 3.3.0 - 1.9.10 - 3.5.0 - 3.11.0 - 3.0.0 + 3.5.0 + 1.9.22 UTF-8 @@ -50,23 +49,23 @@ com.github.ben-manes.caffeine caffeine - 3.1.6 + ${caffeine.version} com.microsoft.azure msal4j - 1.13.10 + ${msal4j.version} no.nav.bidrag - bidrag-commons - ${bidrag-commons.version} + bidrag-commons-felles + ${bidrag-felles.version} no.nav.bidrag - bidrag-transport - ${bidrag-transport.version} + bidrag-transport-felles + ${bidrag-felles.version} @@ -225,7 +224,7 @@ org.awaitility awaitility-kotlin - 4.2.0 + ${awaitility-kotlin.version} @@ -280,7 +279,7 @@ org.apache.maven.plugins maven-antrun-plugin - 3.1.0 + ${maven-antrun-plugin.version} ktlint From 79ee4ca470ab45416d9b01c10ebcbb5111884a4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 08:42:07 +0100 Subject: [PATCH 4/6] Oppgraderer til ktlint 1.1.1 --- pom.xml | 7 +- .../bidrag/cucumber/BidragCucumberCloud.kt | 13 +- .../no/nav/bidrag/cucumber/Constants.kt | 1 + .../no/nav/bidrag/cucumber/Environment.kt | 3 + .../no/nav/bidrag/cucumber/ScenarioManager.kt | 8 +- .../no/nav/bidrag/cucumber/SpringConfig.kt | 30 ++-- .../cucumber/aop/ExceptionLoggerAspect.kt | 6 +- .../bidrag/cucumber/aop/TestFailedAdvice.kt | 19 +-- .../bidrag/cucumber/cloud/FellesEgenskaper.kt | 16 +- .../cucumber/cloud/FellesEgenskaperService.kt | 2 +- .../cucumber/cloud/TestDataEgenskaper.kt | 1 + .../bidrag/cucumber/cloud/TestdataManager.kt | 1 - .../arbeidsflyt/ArbeidsflytEgenskaper.kt | 25 ++-- .../cloud/arbeidsflyt/OppgaveConsumer.kt | 18 ++- .../arbeidsflyt/OppgaveOgHendelseService.kt | 48 ++++-- .../cucumber/cloud/beregn/BeregnEgenskaper.kt | 13 +- .../forsendelse/ForsendelseEgenskaper.kt | 19 ++- .../cucumber/cloud/stonad/StonadEgenskaper.kt | 4 +- .../cucumber/controller/CucumberController.kt | 8 +- .../cucumber/controller/HendelseController.kt | 4 +- .../bidrag/cucumber/dto/CucumberTestsApi.kt | 18 ++- .../no/nav/bidrag/cucumber/dto/HendelseApi.kt | 2 +- .../JournalpostKafkaHendelseProducer.kt | 17 ++- .../logback/TestMessageBeforeLayoutHolder.kt | 1 - .../model/BidragCucumberSingletons.kt | 27 ++-- .../bidrag/cucumber/model/CucumberTestRun.kt | 54 ++++--- .../cucumber/model/CucumberTestsModel.kt | 40 ++--- .../no/nav/bidrag/cucumber/model/FilePath.kt | 16 +- .../cucumber/model/GjentaOppgaveSokRequest.kt | 48 ++++-- .../cucumber/model/JournalpostHendelse.kt | 12 +- .../no/nav/bidrag/cucumber/model/Oppgave.kt | 5 +- .../no/nav/bidrag/cucumber/model/ParseJson.kt | 5 +- .../bidrag/cucumber/model/RestTjenester.kt | 103 +++++++++---- .../no/nav/bidrag/cucumber/model/RunStats.kt | 35 +++-- .../cucumber/model/SuppressStackTraceText.kt | 7 +- .../no/nav/bidrag/cucumber/model/TestData.kt | 8 +- .../cucumber/model/TestMessagesHolder.kt | 2 + .../cucumber/service/AzureTokenCache.kt | 31 +++- .../cucumber/service/AzureTokenService.kt | 49 ++++-- .../cucumber/service/CucumberService.kt | 11 +- .../bidrag/cucumber/service/TokenService.kt | 21 ++- .../sikkerhet/SecurityConfiguration.kt | 15 +- .../bidrag/BidragCucumberCloudLokalNais.kt | 5 +- .../cucumber/BidragCucumberCloudLocal.kt | 1 - .../no/nav/bidrag/cucumber/FilePathTest.kt | 2 +- .../bidrag/cucumber/NotLiveSpringConfig.kt | 1 - .../nav/bidrag/cucumber/TestConfiguration.kt | 2 +- .../kotlin/no/nav/bidrag/cucumber/TestUtil.kt | 15 +- .../cucumber/aop/ExceptionLoggerAspectTest.kt | 2 - .../OppgaveOgHendelseServiceTest.kt | 39 +++-- ...erControllerCucumberServiceMockBeanTest.kt | 139 +++++++++--------- .../CucumberControllerIntegrationTest.kt | 109 +++++++------- ...umberControllerRestTemplateMockBeanTest.kt | 43 +++--- .../controller/HendelseControllerTest.kt | 21 ++- .../cucumber/controller/JsonMappingTest.kt | 20 +-- .../JournalpostKafkaHendelseProducerTest.kt | 26 ++-- .../cucumber/model/CucumberTestsModelTest.kt | 19 +-- .../model/RestTjenesteSikkerhetTest.kt | 1 - .../bidrag/cucumber/model/RestTjenesteTest.kt | 43 +++--- .../cucumber/model/RestTjenesterTest.kt | 5 +- .../nav/bidrag/cucumber/model/RunStatsTest.kt | 33 +++-- .../model/SuppressStackTraceTextTest.kt | 3 +- 62 files changed, 784 insertions(+), 518 deletions(-) diff --git a/pom.xml b/pom.xml index c80839a..adb550c 100644 --- a/pom.xml +++ b/pom.xml @@ -31,6 +31,7 @@ 3.1.8 1.14.2 4.2.0 + 1.1.1 3.5.0 @@ -317,9 +318,9 @@ - com.pinterest - ktlint - 0.47.1 + com.pinterest.ktlint + ktlint-cli + ${ktlint.version} diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloud.kt b/src/main/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloud.kt index 57a6298..c287233 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloud.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloud.kt @@ -16,12 +16,13 @@ class BidragCucumberCloud { @JvmStatic fun main(args: Array) { - val profile = if (args.isEmpty()) { - PROFILE_LIVE - } else { - LOGGER.info("Starter med profil (argument): $args") - args[0] - } + val profile = + if (args.isEmpty()) { + PROFILE_LIVE + } else { + LOGGER.info("Starter med profil (argument): $args") + args[0] + } val app = SpringApplication(BidragCucumberCloud::class.java) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/Constants.kt b/src/main/kotlin/no/nav/bidrag/cucumber/Constants.kt index 83b1b6a..59f4ea0 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/Constants.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/Constants.kt @@ -21,4 +21,5 @@ internal const val CORRELATION_ID = "correlationId" internal const val FAGOMRADE_BIDRAG = "BID" class AzureTokenException(message: String, exception: Exception? = null) : RuntimeException(message, exception) + fun usernameNotFound(): Nothing = throw RuntimeException("Fant ikke bruker") diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/Environment.kt b/src/main/kotlin/no/nav/bidrag/cucumber/Environment.kt index 34de48b..41b666f 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/Environment.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/Environment.kt @@ -20,8 +20,11 @@ internal object Environment { val testUserAuth: String get() = fetchPropertyOrEnvironment(testAuthPropName()) ?: throw unknownState(testAuthPropName()) fun fetchPropertyOrEnvironment(key: String): String? = System.getProperty(key) ?: System.getenv(key) + private fun testAuthPropName() = TEST_AUTH + '_' + testUsername?.uppercase() + private fun unknownState(name: String) = IllegalStateException("Ukjent miljøvariabel ($name), kjente: ${listKnownVariables()}!") + private fun listKnownVariables() = ArrayList(System.getenv().keys).joinToString { it } fun initCucumberEnvironment(cucumberTestsModel: CucumberTestsModel) { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/ScenarioManager.kt b/src/main/kotlin/no/nav/bidrag/cucumber/ScenarioManager.kt index 79900ff..0eefb89 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/ScenarioManager.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/ScenarioManager.kt @@ -55,7 +55,7 @@ object ScenarioManager { -------------- =|> Starting ${scenarioMessage(scenario)} with correlationId: =|> https://logs.adeo.no/app/kibana#/discover?_g=($time)&_a=($columns,$index,interval:auto,$query,$sort) - """.trimIndent() + """.trimIndent(), ) } @@ -64,7 +64,11 @@ object ScenarioManager { } fun fetchCorrelationIdForScenario() = correlationIdForScenario ?: createCorrelationIdValue("unknown") - fun errorLog(message: String, e: Exception) { + + fun errorLog( + message: String, + e: Exception, + ) { LOGGER.error(message) CucumberTestRun.holdExceptionForTest(e) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/SpringConfig.kt b/src/main/kotlin/no/nav/bidrag/cucumber/SpringConfig.kt index 8f8beb0..6d3a248 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/SpringConfig.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/SpringConfig.kt @@ -22,20 +22,20 @@ import org.springframework.kafka.core.KafkaTemplate @Configuration @OpenAPIDefinition( - info = io.swagger.v3.oas.annotations.info.Info( - title = "bidrag-cucumber-cloud", - description = "Funksjonelle tester for nais applikasjoner som er sikret med azure ad og bruker rest/kafka", - version = "v1" - ), - security = [SecurityRequirement(name = "basicAuth")] + info = + io.swagger.v3.oas.annotations.info.Info( + title = "bidrag-cucumber-cloud", + description = "Funksjonelle tester for nais applikasjoner som er sikret med azure ad og bruker rest/kafka", + version = "v1", + ), + security = [SecurityRequirement(name = "basicAuth")], ) @SecurityScheme( name = "basicAuth", type = SecuritySchemeType.HTTP, - scheme = "basic" + scheme = "basic", ) class SpringConfig { - @Bean fun suppressStackTraceText() = SuppressStackTraceText() @@ -43,11 +43,12 @@ class SpringConfig { fun correlationIdFilter() = CorrelationIdFilter() @Bean - fun exceptionLogger() = ExceptionLogger( - BidragCucumberCloud::class.java.simpleName, - ExceptionLoggerAspect::class.java, - TestFailedAdvice::class.java - ) + fun exceptionLogger() = + ExceptionLogger( + BidragCucumberCloud::class.java.simpleName, + ExceptionLoggerAspect::class.java, + TestFailedAdvice::class.java, + ) @Bean @Scope("prototype") @@ -59,11 +60,10 @@ class SpringConfig { @Configuration @Profile(PROFILE_LIVE) class LiveSpringConfig { - @Bean fun jornalpostKafkaHendelseProducer( kafkaTemplate: KafkaTemplate, @Value("\${TOPIC_JOURNALPOST}") topic: String, - objectMapper: ObjectMapper + objectMapper: ObjectMapper, ) = JournalpostKafkaHendelseProducer(kafkaTemplate = kafkaTemplate, topic = topic, objectMapper = objectMapper) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspect.kt b/src/main/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspect.kt index e940c47..25c5b80 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspect.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspect.kt @@ -10,9 +10,11 @@ import org.springframework.stereotype.Component @Aspect @Component class ExceptionLoggerAspect(private val exceptionLogger: ExceptionLogger) { - @AfterThrowing(pointcut = "within (no.nav.bidrag.cucumber.controller..*)", throwing = "exception") - fun logException(joinPoint: JoinPoint, exception: Exception) { + fun logException( + joinPoint: JoinPoint, + exception: Exception, + ) { val logMessages = exceptionLogger.logException(exception, joinPoint.sourceLocation.withinType.toString()) CucumberTestRun.hold(logMessages) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/aop/TestFailedAdvice.kt b/src/main/kotlin/no/nav/bidrag/cucumber/aop/TestFailedAdvice.kt index 510b09a..413bebb 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/aop/TestFailedAdvice.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/aop/TestFailedAdvice.kt @@ -10,20 +10,21 @@ import org.springframework.web.bind.annotation.RestControllerAdvice @RestControllerAdvice class TestFailedAdvice { - @ResponseBody @ExceptionHandler - fun handleTestFailedException(testFailedException: TestFailedException) = ResponseEntity - .status(HttpStatus.NOT_ACCEPTABLE) - .header(HttpHeaders.WARNING, warningFrom(testFailedException)) - .body(testFailedException.suppressedStackTraceLog) + fun handleTestFailedException(testFailedException: TestFailedException) = + ResponseEntity + .status(HttpStatus.NOT_ACCEPTABLE) + .header(HttpHeaders.WARNING, warningFrom(testFailedException)) + .body(testFailedException.suppressedStackTraceLog) @ResponseBody @ExceptionHandler - fun handleUnknownExceptions(runtimeException: RuntimeException) = ResponseEntity - .status(HttpStatus.INTERNAL_SERVER_ERROR) - .header(HttpHeaders.WARNING, warningFrom(runtimeException)) - .build() + fun handleUnknownExceptions(runtimeException: RuntimeException) = + ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .header(HttpHeaders.WARNING, warningFrom(runtimeException)) + .build() private fun warningFrom(runtimeException: RuntimeException) = "${runtimeException.javaClass.simpleName}: ${runtimeException.message}" } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaper.kt index 8d1b72c..1185a21 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaper.kt @@ -9,7 +9,7 @@ import org.assertj.core.api.Assertions.assertThat import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import java.io.File -import java.util.* +import java.util.EnumSet @Suppress("unused") // brukes av cucumber class FellesEgenskaper : No { @@ -17,6 +17,7 @@ class FellesEgenskaper : No { @JvmStatic private val LOGGER = LoggerFactory.getLogger(FellesEgenskaper::class.java) } + init { Gitt("nais applikasjon {string}") { naisApplikasjon: String -> CucumberTestRun.settOppNaisAppTilTesting(naisApplikasjon) } @@ -28,7 +29,10 @@ class FellesEgenskaper : No { } Når("jeg bruker endpoint {string} med json:") { endpoint: String, json: String -> - hentRestTjenesteTilTesting().exchangePost(TestdataManager.erstattUrlMedParametereFraTestdata(endpoint), TestdataManager.erstattJsonMedParametereFraTestdata(json)) + hentRestTjenesteTilTesting().exchangePost( + TestdataManager.erstattUrlMedParametereFraTestdata(endpoint), + TestdataManager.erstattJsonMedParametereFraTestdata(json), + ) } Når("jeg kaller endepunkt {string}") { endpoint: String -> @@ -49,8 +53,8 @@ class FellesEgenskaper : No { Assertion( "HttpStatus for ${hentRestTjenesteTilTesting().hentFullUrlMedEventuellWarning()}", hentRestTjenesteTilTesting().hentHttpStatus(), - HttpStatus.valueOf(enHttpStatus) - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + HttpStatus.valueOf(enHttpStatus), + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } @@ -72,7 +76,9 @@ class FellesEgenskaper : No { Så("skal http status ikke være {int} eller {int}") { enHttpStatus: Int, enAnnenHttpStatus: Int -> assertThat(hentRestTjenesteTilTesting().hentHttpStatus()) .`as`("HttpStatus for " + hentRestTjenesteTilTesting().hentFullUrlMedEventuellWarning()) - .isNotIn(EnumSet.of(HttpStatus.valueOf(enHttpStatus), HttpStatus.valueOf(enAnnenHttpStatus))) + .isNotIn( + EnumSet.of(HttpStatus.valueOf(enHttpStatus), HttpStatus.valueOf(enAnnenHttpStatus)), + ) } Og("responsen skal ikke være null") { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaperService.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaperService.kt index f952f2e..0cdfd68 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaperService.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/FellesEgenskaperService.kt @@ -12,7 +12,7 @@ object FellesEgenskaperService { LOGGER.info( "Assertion, actual: '${assertion.value}' - (${assertion.value?.javaClass}), " + "wanted: '${assertion.expectation}' (${assertion.expectation?.javaClass}), " + - "sanity check: ${CucumberTestRun.isSanityCheck}" + "sanity check: ${CucumberTestRun.isSanityCheck}", ) if (CucumberTestRun.isNotSanityCheck) { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestDataEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestDataEgenskaper.kt index c42d1c7..fbd56c9 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestDataEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestDataEgenskaper.kt @@ -10,6 +10,7 @@ class TestDataEgenskaper : No { @JvmStatic private val LOGGER = LoggerFactory.getLogger(FellesEgenskaper::class.java) } + init { Og("nøkkel for testdata {string}") { nokkel: String -> CucumberTestRun.thisRun().testData.initialiserData(nokkel) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestdataManager.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestdataManager.kt index c687092..797cdd3 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestdataManager.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/TestdataManager.kt @@ -3,7 +3,6 @@ package no.nav.bidrag.cucumber.cloud import no.nav.bidrag.cucumber.model.CucumberTestRun class TestdataManager { - companion object { fun erstattUrlMedParametereFraTestdata(url: String): String { if (url.contains("{") && url.contains("}")) { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/ArbeidsflytEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/ArbeidsflytEgenskaper.kt index 7578c43..ad20a59 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/ArbeidsflytEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/ArbeidsflytEgenskaper.kt @@ -20,11 +20,12 @@ class ArbeidsflytEgenskaper : No { init { Og("en journalpostHendelse med journalpostId {long} og fagområde {string}") { journalpostId: Long, fagomrade: String -> - journalpostHendelse = JournalpostHendelse( - journalpostId = "$fagomrade-$journalpostId", - enhet = "4812", - fagomrade = fagomrade - ) + journalpostHendelse = + JournalpostHendelse( + journalpostId = "$fagomrade-$journalpostId", + enhet = "4812", + fagomrade = fagomrade, + ) } Og("at det finnes en oppgave under behandling") { @@ -49,7 +50,7 @@ class ArbeidsflytEgenskaper : No { OppgaveOgHendelseService.sokOppgaverEtterBehandlingAvHendelse( hendelse = journalpostHendelse, tema = journalpostHendelse.fagomrade ?: throw IllegalStateException("Cucumber test må sørge for at fagområde er satt!"), - sleepInMilliseconds = 4000 + sleepInMilliseconds = 4000, ) } @@ -62,7 +63,7 @@ class ArbeidsflytEgenskaper : No { OppgaveOgHendelseService.sokOppgaverEtterBehandlingAvHendelse( hendelse = journalpostHendelse, tema = fagomrade, - sleepInMilliseconds = 4000 + sleepInMilliseconds = 4000, ) } @@ -70,7 +71,7 @@ class ArbeidsflytEgenskaper : No { OppgaveOgHendelseService.sokOpprettetOppgaveForHendelse( journalpostId = journalpostHendelse.hentJournalpostIdUtenPrefix(), tema = fagomrade, - antallGjentakelser = 1 + antallGjentakelser = 1, ) } @@ -78,7 +79,7 @@ class ArbeidsflytEgenskaper : No { OppgaveOgHendelseService.sokOpprettetOppgaveForHendelse( journalpostId = journalpostHendelse.hentJournalpostIdUtenPrefix(), tema = fagomrade, - antallGjentakelser = antallGanger + antallGjentakelser = antallGanger, ) } @@ -107,8 +108,8 @@ class ArbeidsflytEgenskaper : No { Assertion( message = "Forventet ikke å finne oppgaven", value = CucumberTestRun.hentRestTjenesteTilTesting().hentResponseSomMap()["antallTreffTotalt"], - expectation = 0 - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = 0, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } @@ -116,7 +117,7 @@ class ArbeidsflytEgenskaper : No { OppgaveOgHendelseService.ferdigstillEventuellOppgave( journalpostIdMedPrefix = journalpostHendelse.journalpostId, journalpostId = journalpostHendelse.hentJournalpostIdUtenPrefix(), - tema = journalpostHendelse.fagomrade!! + tema = journalpostHendelse.fagomrade!!, ) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveConsumer.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveConsumer.kt index 6dc0086..50540bf 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveConsumer.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveConsumer.kt @@ -17,9 +17,12 @@ object OppgaveConsumer { hentRestTjenesteTilTesting().exchangePost("/api/v1/oppgaver", oppgave) } - fun sokOppgaver(journalpostId: Long, tema: String): OppgaveSokResponse { + fun sokOppgaver( + journalpostId: Long, + tema: String, + ): OppgaveSokResponse { hentRestTjenesteTilTesting().exchangeGet( - "/api/v1/oppgaver?journalpostId=$journalpostId&journalpostId=$tema-$journalpostId&statuskategori=AAPEN&tema=$tema" + "/api/v1/oppgaver?journalpostId=$journalpostId&journalpostId=$tema-$journalpostId&statuskategori=AAPEN&tema=$tema", ) try { @@ -31,11 +34,12 @@ object OppgaveConsumer { BidragCucumberSingletons.readValue(response, OppgaveSokResponse::class.java) } } finally { - val oppgaveSokResponse = if (hentRestTjenesteTilTesting().responseEntity != null) { - "Har OppgaveSokResponse (${hentRestTjenesteTilTesting().hentResponse()})" - } else { - "Mangler OppgaveSokResponse ${if (CucumberTestRun.isSanityCheck) "og det er" else "og det er ikke"} sanity check!" - } + val oppgaveSokResponse = + if (hentRestTjenesteTilTesting().responseEntity != null) { + "Har OppgaveSokResponse (${hentRestTjenesteTilTesting().hentResponse()})" + } else { + "Mangler OppgaveSokResponse ${if (CucumberTestRun.isSanityCheck) "og det er" else "og det er ikke"} sanity check!" + } LOGGER.info("$oppgaveSokResponse med http status: ${hentRestTjenesteTilTesting().hentHttpStatus()}") } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseService.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseService.kt index fce3066..f41944b 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseService.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseService.kt @@ -12,13 +12,14 @@ import no.nav.bidrag.transport.dokument.JournalpostStatus /** * Service class in order to loosely couple logic from cucumber infrastructure */ -@Suppress("UNCHECKED_CAST") object OppgaveOgHendelseService { - @JvmStatic internal val GJENTA_OPPGAVE_SOK_REQUEST = ThreadLocal() - fun tilbyOppgave(journalpostHendelse: JournalpostHendelse, oppgavetype: String? = null) { + fun tilbyOppgave( + journalpostHendelse: JournalpostHendelse, + oppgavetype: String? = null, + ) { val sokResponse = OppgaveConsumer.sokOppgaver(journalpostHendelse.hentJournalpostIdUtenPrefix(), journalpostHendelse.fagomrade!!) val fagomrade: String = journalpostHendelse.fagomrade ?: FAGOMRADE_BIDRAG val enhetsnummer: String = journalpostHendelse.enhet ?: "4812" @@ -29,8 +30,8 @@ object OppgaveOgHendelseService { journalpostId = journalpostHendelse.hentJournalpostIdStrengUtenPrefix(), tema = fagomrade, tildeltEnhetsnr = enhetsnummer, - oppgavetype = oppgavetype ?: "JFR" - ) + oppgavetype = oppgavetype ?: "JFR", + ), ) } else if (sokResponse.oppgaver.isNotEmpty()) { val oppgave = sokResponse.oppgaver.first() @@ -44,8 +45,8 @@ object OppgaveOgHendelseService { tema = fagomrade, versjon = versjon.toInt(), tildeltEnhetsnr = enhetsnummer, - oppgavetype = oppgave.oppgavetype - ) + oppgavetype = oppgave.oppgavetype, + ), ) } else { throw IllegalStateException("Antall treff: ${sokResponse.antallTreffTotalt}, men liste i response er tom!!!") @@ -56,23 +57,36 @@ object OppgaveOgHendelseService { BidragCucumberSingletons.publiserHendelse(journalpostHendelse = journalpostHendelse) } - fun sokOppgaverEtterBehandlingAvHendelse(hendelse: JournalpostHendelse, tema: String, sleepInMilliseconds: Long) { + fun sokOppgaverEtterBehandlingAvHendelse( + hendelse: JournalpostHendelse, + tema: String, + sleepInMilliseconds: Long, + ) { CucumberTestRun.sleepWhenNotSanityCheck(sleepInMilliseconds) OppgaveConsumer.sokOppgaver(journalpostId = hendelse.hentJournalpostIdUtenPrefix(), tema = tema) } - fun sokOpprettetOppgaveForHendelse(journalpostId: Long, tema: String, antallGjentakelser: Int, sleepInMilleseconds: Long = 1500) { + fun sokOpprettetOppgaveForHendelse( + journalpostId: Long, + tema: String, + antallGjentakelser: Int, + sleepInMilleseconds: Long = 1500, + ) { GJENTA_OPPGAVE_SOK_REQUEST.set( GjentaOppgaveSokRequest( antallGjentakelser = antallGjentakelser, journalpostId = journalpostId, tema = tema, - sleepInMilleseconds = sleepInMilleseconds - ) + sleepInMilleseconds = sleepInMilleseconds, + ), ) } - fun ferdigstillEventuellOppgave(journalpostIdMedPrefix: String, journalpostId: Long, tema: String) { + fun ferdigstillEventuellOppgave( + journalpostIdMedPrefix: String, + journalpostId: Long, + tema: String, + ) { val sokResponse = OppgaveConsumer.sokOppgaver(journalpostId, tema) if (sokResponse.antallTreffTotalt > 0) { @@ -82,8 +96,8 @@ object OppgaveOgHendelseService { journalpostId = journalpostIdMedPrefix, status = JournalpostStatus.JOURNALFØRT, fagomrade = "BID", - enhet = "4812" - ) + enhet = "4812", + ), ) } } @@ -92,7 +106,11 @@ object OppgaveOgHendelseService { Thread.sleep(2000) } - fun assertThatOppgaveHar(enhet: String? = null, oppgavetype: String? = null, aktorId: String? = null) { + fun assertThatOppgaveHar( + enhet: String? = null, + oppgavetype: String? = null, + aktorId: String? = null, + ) { GJENTA_OPPGAVE_SOK_REQUEST.get().assertThatOppgaveHar(enhet, oppgavetype, aktorId) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/beregn/BeregnEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/beregn/BeregnEgenskaper.kt index e2769f1..25341a1 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/beregn/BeregnEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/beregn/BeregnEgenskaper.kt @@ -29,8 +29,8 @@ class BeregnEgenskaper : No { Assertion( message = "Resultatbeløp", value = resultatBelop, - expectation = belop - ) { assertThat(it.expectation).`as`(it.message).isEqualTo(it.value) } + expectation = belop, + ) { assertThat(it.expectation).`as`(it.message).isEqualTo(it.value) }, ) } @@ -42,13 +42,16 @@ class BeregnEgenskaper : No { Assertion( message = "Resultatkode", value = resultatkode, - expectation = kode - ) { assertThat(it.expectation).`as`(it.message).isEqualTo(it.value) } + expectation = kode, + ) { assertThat(it.expectation).`as`(it.message).isEqualTo(it.value) }, ) } } - private fun parseJson(response: String?, sti: String): String? { + private fun parseJson( + response: String?, + sti: String, + ): String? { if (response == null) { return null } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/forsendelse/ForsendelseEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/forsendelse/ForsendelseEgenskaper.kt index 6f96eb6..d7cc88d 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/forsendelse/ForsendelseEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/forsendelse/ForsendelseEgenskaper.kt @@ -53,8 +53,8 @@ class ForsendelseEgenskaper : No { Assertion( message = "Dokument", value = dokument?.get("status")?.asText(), - expectation = status - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = status, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } } @@ -71,8 +71,8 @@ class ForsendelseEgenskaper : No { Assertion( message = "Dokument", value = dokumenter.size, - expectation = antall - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = antall, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } Og("forsendelse inneholder joark journalpostid") { @@ -86,15 +86,20 @@ class ForsendelseEgenskaper : No { Assertion( message = "Dokument", value = journalpostId, - expectation = journalpostId - ) { assertThat(it.value).`as`(it.message).isNotNull() } + expectation = journalpostId, + ) { assertThat(it.value).`as`(it.message).isNotNull() }, ) } } private fun lagreDokumentreferanserFraRespons(journalpost: JsonNode) { val dokumenter = journalpost.get("dokumenter").toList() - dokumenter.forEachIndexed { i, it -> CucumberTestRun.thisRun().testData.lagreData("dokumentreferanse${i + 1}" to it.get("dokumentreferanse").asText()) } + dokumenter.forEachIndexed { + i, + it, + -> + CucumberTestRun.thisRun().testData.lagreData("dokumentreferanse${i + 1}" to it.get("dokumentreferanse").asText()) + } } private fun parseJson(response: String?): JsonNode? { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/stonad/StonadEgenskaper.kt b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/stonad/StonadEgenskaper.kt index d1abdd4..ec348af 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/cloud/stonad/StonadEgenskaper.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/cloud/stonad/StonadEgenskaper.kt @@ -24,7 +24,9 @@ class StonadEgenskaper : No { } Og("responsen under stien {string} skal være maks {long} sekunder gammel") { sti: String, antallSekunder: Long -> - LOGGER.info("Sjekker at vedtak-hendelsen har oppdatert endretTidspunkt på stønaden og at denne er maks $antallSekunder sekunder gammel") + LOGGER.info( + "Sjekker at vedtak-hendelsen har oppdatert endretTidspunkt på stønaden og at denne er maks $antallSekunder sekunder gammel", + ) val response = hentRestTjenesteTilTesting().hentResponse() val endretTidspunkt = LocalDateTime.parse(parseJson(response, sti)) ?: LocalDateTime.MIN val naaTidspunkt = LocalDateTime.now() diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/controller/CucumberController.kt b/src/main/kotlin/no/nav/bidrag/cucumber/controller/CucumberController.kt index aa292e8..b7b1846 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/controller/CucumberController.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/controller/CucumberController.kt @@ -27,10 +27,12 @@ class CucumberController(private val cucumberService: CucumberService) { @ApiResponses( value = [ ApiResponse(responseCode = "200", description = "Angitte tester kjørt uten feil"), - ApiResponse(responseCode = "406", description = "Testkjøring med cucumber feilet") - ] + ApiResponse(responseCode = "406", description = "Testkjøring med cucumber feilet"), + ], ) - fun run(@RequestBody cucumberTestsApi: CucumberTestsApi): ResponseEntity { + fun run( + @RequestBody cucumberTestsApi: CucumberTestsApi, + ): ResponseEntity { LOGGER.info("Running cucumber tests with $cucumberTestsApi!") val cucumberTestRun = CucumberTestRun(cucumberTestsApi).initEnvironment() return ResponseEntity(cucumberService.run(cucumberTestRun), HttpStatus.OK) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/controller/HendelseController.kt b/src/main/kotlin/no/nav/bidrag/cucumber/controller/HendelseController.kt index 4d01c57..bf54e79 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/controller/HendelseController.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/controller/HendelseController.kt @@ -21,7 +21,9 @@ class HendelseController(private val hendelseProducer: HendelseProducer) { @PostMapping("/hendelse/opprett") @Operation(summary = "Opprett en journalpost-hendelse") @ApiResponse(responseCode = "200", description = "ny journalpost-hendelse er publisert") - fun opprett(@RequestBody hendelseApi: HendelseApi): ResponseEntity { + fun opprett( + @RequestBody hendelseApi: HendelseApi, + ): ResponseEntity { LOGGER.info("publiserer $hendelseApi") hendelseProducer.publish(JournalpostHendelse(hendelseApi)) return ResponseEntity.ok().build() diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/dto/CucumberTestsApi.kt b/src/main/kotlin/no/nav/bidrag/cucumber/dto/CucumberTestsApi.kt index 3089bc6..8e03601 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/dto/CucumberTestsApi.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/dto/CucumberTestsApi.kt @@ -4,17 +4,25 @@ import io.swagger.v3.oas.annotations.media.Schema @Schema(description = "Dto med data for en testkjøring (som gjøres av `io.cucumber.core.cli.Main`)") data class CucumberTestsApi( - @Schema(description = "liste med ingress@nais-app (kan også være en tag i en test, ingress som brukes for en gitt nais applikasjon)") var ingressesForApps: List = emptyList(), - @Schema(description = "Nais applikasjoner som ikke skal bruke applikasjonsnavnet som \"context path\" etter ingressen") var noContextPathForApps: List = emptyList(), - @Schema(description = "Om testkjøringen er en sanity check av *.feature-filer. Feiler ikke ved assertions, bare feil ved I/O") var sanityCheck: Boolean? = false, + @Schema( + description = "liste med ingress@nais-app (kan også være en tag i en test, ingress som brukes for en gitt nais applikasjon)", + ) var ingressesForApps: List = emptyList(), + @Schema( + description = "Nais applikasjoner som ikke skal bruke applikasjonsnavnet som \"context path\" etter ingressen", + ) var noContextPathForApps: List = emptyList(), + @Schema( + description = "Om testkjøringen er en sanity check av *.feature-filer. Feiler ikke ved assertions, bare feil ved I/O", + ) var sanityCheck: Boolean? = false, @Schema(description = "Security (azure) token som skal brukes ved lokal kjøring") var securityToken: String? = null, @Schema(description = "liste med tags som skal testes uten å oppgi ingress") var tags: List = emptyList(), @Schema(description = "Brukernavn (test ident) for testkjøring, eks: z123456") var testUsername: String? = null, @Schema(description = "Om autentisering skal brukes ved kall mot API") var skipAuth: Boolean? = false, - @Schema(description = "Hvilken type saksbehandler som skal brukes ved autentiseringen") var medSaksbehandlerType: SaksbehandlerType? = null + @Schema( + description = "Hvilken type saksbehandler som skal brukes ved autentiseringen", + ) var medSaksbehandlerType: SaksbehandlerType? = null, ) enum class SaksbehandlerType { BIDRAG_BASIS, - BIDRAG_VIKAFOSSEN + BIDRAG_VIKAFOSSEN, } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/dto/HendelseApi.kt b/src/main/kotlin/no/nav/bidrag/cucumber/dto/HendelseApi.kt index 41fa6a9..f7ba67e 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/dto/HendelseApi.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/dto/HendelseApi.kt @@ -10,5 +10,5 @@ data class HendelseApi( @Schema(description = "Brukerident som kan brukes til sporing av hendelsen") val brukerident: String? = null, @Schema(description = "Fagområdet som journalposten tilhører") var fagomrade: String? = null, @Schema(description = "Enheten som journalposten tilhører") var enhet: String? = null, - @Schema(description = "Journalposten journalstatus") var journalstatus: JournalpostStatus? = null + @Schema(description = "Journalposten journalstatus") var journalstatus: JournalpostStatus? = null, ) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducer.kt b/src/main/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducer.kt index 805736b..7347061 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducer.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducer.kt @@ -14,9 +14,8 @@ class JournalpostKafkaHendelseProducer( private val kafkaTemplate: KafkaTemplate, private val topic: String, private val objectMapper: ObjectMapper, - private val timeoutAfterSeconds: Long = 15 + private val timeoutAfterSeconds: Long = 15, ) : HendelseProducer { - companion object { @JvmStatic private val LOGGER = LoggerFactory.getLogger(JournalpostKafkaHendelseProducer::class.java) @@ -28,7 +27,7 @@ class JournalpostKafkaHendelseProducer( LOGGER.info("Publish $journalpostHendelse til topic $topic") publishWithTimeout( publish = Publish(journalpostHendelse.journalpostId, objectMapper.writeValueAsString(journalpostHendelse)), - doSend = this::sendKafkaMelding + doSend = this::sendKafkaMelding, ) } else { LOGGER.info("SanityCheck - Hendelse publiseres ikke: $journalpostHendelse") @@ -43,12 +42,16 @@ class JournalpostKafkaHendelseProducer( kafkaTemplate.send(topic, publish.journalpostId, publish.json) } - private fun publishWithTimeout(publish: Publish, doSend: (input: Publish) -> Unit) { + private fun publishWithTimeout( + publish: Publish, + doSend: (input: Publish) -> Unit, + ) { val start = LocalDateTime.now() val timeout = LocalDateTime.now().plusSeconds(timeoutAfterSeconds) - val future = CompletableFuture.runAsync { - doSend(publish) - } + val future = + CompletableFuture.runAsync { + doSend(publish) + } while (!future.isDone) { if (LocalDateTime.now().isBefore(timeout)) { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/logback/TestMessageBeforeLayoutHolder.kt b/src/main/kotlin/no/nav/bidrag/cucumber/logback/TestMessageBeforeLayoutHolder.kt index 5de048e..cd07ca9 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/logback/TestMessageBeforeLayoutHolder.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/logback/TestMessageBeforeLayoutHolder.kt @@ -6,7 +6,6 @@ import no.nav.bidrag.cucumber.ScenarioManager import no.nav.bidrag.cucumber.model.CucumberTestRun class TestMessageBeforeLayoutHolder : LoggingEventCompositeJsonEncoder() { - override fun encode(event: ILoggingEvent?): ByteArray { if (CucumberTestRun.isTestRunStarted) { val message = event?.message ?: throw IllegalStateException("ILoggingEvent should not be null!") diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/BidragCucumberSingletons.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/BidragCucumberSingletons.kt index e9b6c82..25f79c3 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/BidragCucumberSingletons.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/BidragCucumberSingletons.kt @@ -24,7 +24,9 @@ internal object BidragCucumberSingletons { @Suppress("UNCHECKED_CAST") fun hentEllerInit(kClass: KClass<*>): T = applicationContext?.getBean(kClass.java) as T? ?: init(kClass) + fun hentPrototypeFraApplicationContext() = applicationContext?.getBean(HttpHeaderRestTemplate::class.java) ?: doManualInit() + private fun fetchObjectMapper() = objectMapper ?: ObjectMapper() @Suppress("UNCHECKED_CAST") @@ -42,7 +44,7 @@ internal object BidragCucumberSingletons { fun publiserHendelse(journalpostHendelse: JournalpostHendelse) { hendelseProducer?.publish(journalpostHendelse) ?: LOGGER.warn( - "Cannot publish $journalpostHendelse when spring context is not initialized, sanity check: ${CucumberTestRun.isSanityCheck}" + "Cannot publish $journalpostHendelse when spring context is not initialized, sanity check: ${CucumberTestRun.isSanityCheck}", ) } @@ -55,16 +57,21 @@ internal object BidragCucumberSingletons { } @Suppress("UNCHECKED_CAST") - private fun mapResponseSomMap(body: String): Map = try { - fetchObjectMapper().readValue(body, Map::class.java) as Map - } catch (e: Exception) { - CucumberTestRun.holdExceptionForTest(e) - throw e - } + private fun mapResponseSomMap(body: String): Map = + try { + fetchObjectMapper().readValue(body, Map::class.java) as Map + } catch (e: Exception) { + CucumberTestRun.holdExceptionForTest(e) + throw e + } - fun readValue(value: String, mapClass: Class): T = objectMapper?.readValue(value, mapClass) ?: throw IllegalStateException( - "Kunne ikke mappe: $value" - ) + fun readValue( + value: String, + mapClass: Class, + ): T = + objectMapper?.readValue(value, mapClass) ?: throw IllegalStateException( + "Kunne ikke mappe: $value", + ) fun toJson(body: Any): String = objectMapper?.writeValueAsString(body) ?: """{ "noMappingAvailable":"$body" }""" diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestRun.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestRun.kt index 84ae976..152c716 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestRun.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestRun.kt @@ -45,7 +45,6 @@ class CucumberTestRun(private val cucumberTestsModel: CucumberTestsModel) { } companion object { - @JvmStatic private val CUCUMBER_TEST_RUN = ThreadLocal() @@ -54,15 +53,16 @@ class CucumberTestRun(private val cucumberTestsModel: CucumberTestsModel) { @JvmStatic private fun initFromEnvironment(): CucumberTestRun { - val cucumberTestRun = CucumberTestRun( - CucumberTestsModel( - ingressesForApps = Environment.asList(INGRESSES_FOR_APPS), - noContextPathForApps = Environment.asList(NO_CONTEXT_PATH_FOR_APPS), - sanityCheck = fetchPropertyOrEnvironment(SANITY_CHECK)?.toBoolean(), - securityToken = fetchPropertyOrEnvironment(SECURITY_TOKEN), - tags = Environment.asList(TAGS) + val cucumberTestRun = + CucumberTestRun( + CucumberTestsModel( + ingressesForApps = Environment.asList(INGRESSES_FOR_APPS), + noContextPathForApps = Environment.asList(NO_CONTEXT_PATH_FOR_APPS), + sanityCheck = fetchPropertyOrEnvironment(SANITY_CHECK)?.toBoolean(), + securityToken = fetchPropertyOrEnvironment(SECURITY_TOKEN), + tags = Environment.asList(TAGS), + ), ) - ) CUCUMBER_TEST_RUN.set(cucumberTestRun) @@ -72,7 +72,10 @@ class CucumberTestRun(private val cucumberTestsModel: CucumberTestsModel) { val isNotSanityCheck: Boolean get() = !isSanityCheck val isSanityCheck: Boolean get() = Environment.isSanityCheck ?: thisRun().cucumberTestsModel.sanityCheck ?: false val isTestRunStarted: Boolean get() = CUCUMBER_TEST_RUN.get() != null - val isTestUserPresent: Boolean get() = fetchPropertyOrEnvironment(TEST_USER) != null || thisRun().cucumberTestsModel.testUsername != null + val isTestUserPresent: Boolean get() = + fetchPropertyOrEnvironment( + TEST_USER, + ) != null || thisRun().cucumberTestsModel.testUsername != null val securityToken: String? get() = thisRun().cucumberTestsModel.securityToken val testUsername: String? get() = thisRun().cucumberTestsModel.testUsername val skipAuth: Boolean get() = thisRun().cucumberTestsModel.skipAuth @@ -81,17 +84,29 @@ class CucumberTestRun(private val cucumberTestsModel: CucumberTestsModel) { private var exceptionLogger: ExceptionLogger? = null fun addToRunStats(scenario: Scenario) = thisRun().runStats.add(scenario) + fun fetchIngress(applicationName: String) = thisRun().cucumberTestsModel.fetchIngress(applicationName) + fun fetchTestMessagesWithRunStats() = thisRun().testMessagesHolder.fetchTestMessages() + "\n\n" + thisRun().runStats.get() + fun hentRestTjenste(applicationName: String) = thisRun().restTjenester.hentRestTjeneste(applicationName) + fun hentRestTjenesteTilTesting() = thisRun().restTjenester.hentRestTjenesteTilTesting() + fun hold(logMessages: List) = thisRun().testMessagesHolder.hold(logMessages) + fun holdTestMessage(message: String) = thisRun().testMessagesHolder.hold(message) + fun isApplicationConfigured(applicationName: String) = thisRun().restTjenester.isApplicationConfigured(applicationName) + fun isNoContextPathForApp(applicationName: String) = thisRun().cucumberTestsModel.noContextPathForApps.contains(applicationName) + fun settOppNaisApp(naisApplikasjon: String) = thisRun().restTjenester.settOppNaisApp(naisApplikasjon) + fun settOppNaisAppTilTesting(naisApplikasjon: String) = thisRun().restTjenester.settOppNaisAppTilTesting(naisApplikasjon) + fun sleepWhenNotSanityCheck(milliseconds: Long) = if (isNotSanityCheck) Thread.sleep(milliseconds) else Unit + fun updateSecurityToken(securityToken: String?) = thisRun().cucumberTestsModel.updateSecurityToken(securityToken) fun holdExceptionForTest(throwable: Throwable) { @@ -99,15 +114,16 @@ class CucumberTestRun(private val cucumberTestsModel: CucumberTestsModel) { exceptionLogger = BidragCucumberSingletons.hentEllerInit(ExceptionLogger::class) } - val exceptionLog = exceptionLogger!!.logException( - throwable, - throwable.stackTrace.first { - (it.className.contains("no.nav") || it?.fileName?.contains("feature") ?: false) && - !it.className.contains(CucumberTestRun::class.simpleName!!) && - !it.className.contains(FellesEgenskaper::class.simpleName!!) && - !it.className.contains(ScenarioManager::class.simpleName!!) - }.className - ) + val exceptionLog = + exceptionLogger!!.logException( + throwable, + throwable.stackTrace.first { + (it.className.contains("no.nav") || it?.fileName?.contains("feature") ?: false) && + !it.className.contains(CucumberTestRun::class.simpleName!!) && + !it.className.contains(FellesEgenskaper::class.simpleName!!) && + !it.className.contains(ScenarioManager::class.simpleName!!) + }.className, + ) val exceptionMessage = exceptionLog[0] val cucumberTestRun = thisRun() diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModel.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModel.kt index 39e3687..decf969 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModel.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModel.kt @@ -16,16 +16,20 @@ data class CucumberTestsModel(internal val cucumberTestsApi: CucumberTestsApi) { private val LOGGER = LoggerFactory.getLogger(CucumberTestsModel::class.java) @JvmStatic - private val FEATURE_FILES = File(ABSOLUTE_CLOUD_PATH) - .walkBottomUp() - .filter { it.isFile } - .filter { it.name.endsWith(".feature") } - .toList() + private val FEATURE_FILES = + File(ABSOLUTE_CLOUD_PATH) + .walkBottomUp() + .filter { it.isFile } + .filter { it.name.endsWith(".feature") } + .toList() @JvmStatic private val NAMES_OF_FEATURE_FILES = FEATURE_FILES.joinToString(separator = ", ") { it.name } - private fun isTagPresent(file: File, tag: String): Boolean { + private fun isTagPresent( + file: File, + tag: String, + ): Boolean { val inputStream: InputStream = file.inputStream() return inputStream.bufferedReader().use { it.readText() } .contains(tag) @@ -47,7 +51,7 @@ data class CucumberTestsModel(internal val cucumberTestsApi: CucumberTestsApi) { sanityCheck: Boolean? = false, securityToken: String? = null, tags: List = emptyList(), - testUsername: String? = null + testUsername: String? = null, ) : this( CucumberTestsApi( ingressesForApps = ingressesForApps, @@ -55,24 +59,25 @@ data class CucumberTestsModel(internal val cucumberTestsApi: CucumberTestsApi) { sanityCheck = sanityCheck, securityToken = securityToken, tags = tags, - testUsername = testUsername - ) + testUsername = testUsername, + ), ) fun getSanityCheck() = sanityCheck?.toString() ?: "false" fun fetchTags(): String { - val collectTags = ingressesForApps - .filter { it.contains("@tag:") } - .map { it.split("@tag:")[1] } - .map { "@$it" } as MutableList + val collectTags = + ingressesForApps + .filter { it.contains("@tag:") } + .map { it.split("@tag:")[1] } + .map { "@$it" } as MutableList collectTags.addAll(tags) val tagsAsStrings = transformAssertedTagsToString(collectTags) if (tagsAsStrings.isEmpty()) { throw IllegalStateException( - "Ingen tags er oppgitt. Bruk liste med tags eller liste med ingresser som har prefiksen 'tag:' etter @" + "Ingen tags er oppgitt. Bruk liste med tags eller liste med ingresser som har prefiksen 'tag:' etter @", ) } @@ -115,9 +120,10 @@ data class CucumberTestsModel(internal val cucumberTestsApi: CucumberTestsApi) { } } - private fun isNotTagPresentInFeatureFile(tag: String) = FEATURE_FILES.stream() - .filter { file: File -> isTagPresent(file, tag) } - .findFirst().isEmpty + private fun isNotTagPresentInFeatureFile(tag: String) = + FEATURE_FILES.stream() + .filter { file: File -> isTagPresent(file, tag) } + .findFirst().isEmpty internal fun initCucumberEnvironment(): CucumberTestsModel { Environment.initCucumberEnvironment(this) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/FilePath.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/FilePath.kt index e1c6cc7..905dd2e 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/FilePath.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/FilePath.kt @@ -9,11 +9,12 @@ data class FilePath(val fileName: String) { private val LOGGER = LoggerFactory.getLogger(FilePath::class.java) } - internal fun findFile() = File(".") - .walkBottomUp() - .filterNot { it.absolutePath.contains("/target/") } - .filter { it.name.endsWith(".path") } - .find { isFileName(it) } ?: throw IllegalStateException("Cannot find $fileName located in ${File(".").absolutePath}") + internal fun findFile() = + File(".") + .walkBottomUp() + .filterNot { it.absolutePath.contains("/target/") } + .filter { it.name.endsWith(".path") } + .find { isFileName(it) } ?: throw IllegalStateException("Cannot find $fileName located in ${File(".").absolutePath}") private fun isFileName(file: File): Boolean { LOGGER.info("is $fileName?: $file") @@ -21,6 +22,7 @@ data class FilePath(val fileName: String) { return fileName == file.name } - fun findFolderPath() = File(findFile().parent) - .absolutePath.replace("/./", "/") + fun findFolderPath() = + File(findFile().parent) + .absolutePath.replace("/./", "/") } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/GjentaOppgaveSokRequest.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/GjentaOppgaveSokRequest.kt index 5bc3a59..ac76d93 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/GjentaOppgaveSokRequest.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/GjentaOppgaveSokRequest.kt @@ -8,13 +8,17 @@ class GjentaOppgaveSokRequest( private val antallGjentakelser: Int, private val journalpostId: Long, private val tema: String, - private val sleepInMilleseconds: Long = 750 + private val sleepInMilleseconds: Long = 750, ) { fun assertThatOppgaveFinnes() { finnOppgaveResponseMedMaksGjentakelser() } - fun assertThatOppgaveHar(enhet: String?, oppgavetype: String?, aktorId: String?) { + fun assertThatOppgaveHar( + enhet: String?, + oppgavetype: String?, + aktorId: String?, + ) { val responseSomMap = finnOppgaveResponseMedMaksGjentakelser() if (enhet != null) { @@ -65,12 +69,15 @@ class GjentaOppgaveSokRequest( Assertion( message = "Forventet å finne oppgaven", value = responseSomMap["antallTreffTotalt"], - expectation = 1 - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = 1, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } - private fun assertTildeltEnhetsnummer(responseSomMap: Map, enhet: String) { + private fun assertTildeltEnhetsnummer( + responseSomMap: Map, + enhet: String, + ) { @Suppress("UNCHECKED_CAST") val tildeltEnhetsnr = (responseSomMap["oppgaver"] as List>?)?.first()?.get("tildeltEnhetsnr") @@ -78,12 +85,15 @@ class GjentaOppgaveSokRequest( Assertion( message = "Oppgaven er tildelt enhet", value = tildeltEnhetsnr, - expectation = enhet - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = enhet, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } - private fun assertAktorid(responseSomMap: Map, aktoerId: String) { + private fun assertAktorid( + responseSomMap: Map, + aktoerId: String, + ) { @Suppress("UNCHECKED_CAST") val oppgavetypeFraMap = (responseSomMap["oppgaver"] as List>?)?.first()?.get("aktoerId") @@ -91,12 +101,15 @@ class GjentaOppgaveSokRequest( Assertion( message = "Oppgaven har riktig aktoerId", value = oppgavetypeFraMap, - expectation = aktoerId - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = aktoerId, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } - private fun assertOppgavetype(responseSomMap: Map, oppgavetype: String) { + private fun assertOppgavetype( + responseSomMap: Map, + oppgavetype: String, + ) { @Suppress("UNCHECKED_CAST") val oppgavetypeFraMap = (responseSomMap["oppgaver"] as List>?)?.firstOrNull()?.get("oppgavetype") @@ -104,18 +117,21 @@ class GjentaOppgaveSokRequest( Assertion( message = "Oppgaven har riktig oppgavetype", value = oppgavetypeFraMap, - expectation = oppgavetype - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = oppgavetype, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } - private fun assertThatOppgaveSokHarEtTotaltAntallTreff(responseSomMap: Map, antallForventet: Int) { + private fun assertThatOppgaveSokHarEtTotaltAntallTreff( + responseSomMap: Map, + antallForventet: Int, + ) { FellesEgenskaperService.assertWhenNotSanityCheck( Assertion( message = "Forventet å finne oppgaver", value = responseSomMap["antallTreffTotalt"], - expectation = antallForventet - ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) } + expectation = antallForventet, + ) { assertThat(it.value).`as`(it.message).isEqualTo(it.expectation) }, ) } } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/JournalpostHendelse.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/JournalpostHendelse.kt index 1c359c1..5a59607 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/JournalpostHendelse.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/JournalpostHendelse.kt @@ -12,7 +12,7 @@ data class JournalpostHendelse( var fnr: String? = null, var fagomrade: String? = null, var enhet: String? = null, - var status: JournalpostStatus? = null + var status: JournalpostStatus? = null, ) { @Suppress("unused") // brukes for sporing av data som publiseres var sporing: Sporingsdata = Sporingsdata(brukerident = CucumberTestRun.testUsername) @@ -22,15 +22,16 @@ data class JournalpostHendelse( aktorId = hendelseApi.aktorId, fagomrade = hendelseApi.fagomrade, enhet = hendelseApi.enhet, - status = hendelseApi.journalstatus + status = hendelseApi.journalstatus, ) internal fun hentJournalpostIdUtenPrefix() = hentJournalpostIdStrengUtenPrefix().toLong() + fun hentJournalpostIdStrengUtenPrefix() = journalpostId.split('-')[1] } data class Sporingsdata( - var brukerident: String? = null + var brukerident: String? = null, ) { var correlationId: String = System.currentTimeMillis().toString() @@ -41,12 +42,13 @@ data class Sporingsdata( if (fromThread != null) { correlationId = fromThread } - } catch (_: Exception) {} + } catch (_: Exception) { + } } } class HendelseTimeoutException(start: LocalDateTime, timeout: LocalDateTime) : RuntimeException( - "Hendelse med timeout! Started: ${onlyTime(start)}, timed out: ${onlyTime(timeout)}" + "Hendelse med timeout! Started: ${onlyTime(start)}, timed out: ${onlyTime(timeout)}", ) private fun onlyTime(dateTime: LocalDateTime): String = dateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss,SSS")) diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/Oppgave.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/Oppgave.kt index fba3ce9..f85686d 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/Oppgave.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/Oppgave.kt @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties import java.time.LocalDate data class OppgaveSokResponse(var antallTreffTotalt: Int = 0, var oppgaver: List = emptyList()) + data class Oppgave(var id: Long = -1, var versjon: String = "na", var tildeltEnhetsnr: String = "na", val oppgavetype: String? = null) @JsonIgnoreProperties(ignoreUnknown = true) @@ -13,7 +14,7 @@ data class PatchStatusOppgaveRequest( var tema: String, var versjon: Int, var tildeltEnhetsnr: String, - var oppgavetype: String? = null + var oppgavetype: String? = null, ) : MedOppgaveId data class PostOppgaveRequest( @@ -22,7 +23,7 @@ data class PostOppgaveRequest( var oppgavetype: String = "JFR", var prioritet: String = "HOY", var aktivDato: LocalDate = LocalDate.now().minusDays(1), - var tildeltEnhetsnr: String = "1001" + var tildeltEnhetsnr: String = "1001", ) interface MedOppgaveId { diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/ParseJson.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/ParseJson.kt index ffbf411..2521eb7 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/ParseJson.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/ParseJson.kt @@ -2,7 +2,10 @@ package no.nav.bidrag.cucumber.model import com.jayway.jsonpath.JsonPath -fun parseJson(response: String?, sti: String): String? { +fun parseJson( + response: String?, + sti: String, +): String? { if (response == null) { return null } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/RestTjenester.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/RestTjenester.kt index 2ac2b90..368b703 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/RestTjenester.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/RestTjenester.kt @@ -40,10 +40,13 @@ internal class RestTjenester { private var restTjenesteTilTesting: RestTjeneste? = null fun isApplicationConfigured(applicationName: String) = restTjenesteForNavn.contains(applicationName) + fun hentRestTjenesteTilTesting() = restTjenesteTilTesting ?: throw IllegalStateException("RestTjeneste til testing er null!") - fun hentRestTjeneste(applicationName: String) = restTjenesteForNavn[applicationName] ?: throw IllegalStateException( - "RestTjeneste $applicationName er ikke funnet!" - ) + + fun hentRestTjeneste(applicationName: String) = + restTjenesteForNavn[applicationName] ?: throw IllegalStateException( + "RestTjeneste $applicationName er ikke funnet!", + ) fun settOppNaisApp(naisApplikasjon: String): RestTjeneste { LOGGER.info("Setter opp $naisApplikasjon") @@ -66,7 +69,10 @@ internal class RestTjenester { } internal class BaseUrlTemplateHandler(private val baseUrl: String) : UriTemplateHandler { - override fun expand(uriTemplate: String, uriVariables: MutableMap): URI { + override fun expand( + uriTemplate: String, + uriVariables: MutableMap, + ): URI { if (uriVariables.isNotEmpty()) { val queryString = StringBuilder() uriVariables.forEach { if (queryString.length == 1) queryString.append("$it") else queryString.append("?$it") } @@ -77,7 +83,10 @@ internal class BaseUrlTemplateHandler(private val baseUrl: String) : UriTemplate return URI.create(baseUrl + uriTemplate) } - override fun expand(uriTemplate: String, vararg uriVariables: Any?): URI { + override fun expand( + uriTemplate: String, + vararg uriVariables: Any?, + ): URI { if (uriVariables.isNotEmpty() && (uriVariables.size != 1 && uriVariables.first() != null)) { val queryString = StringBuilder("&") uriVariables.forEach { @@ -96,7 +105,7 @@ internal class BaseUrlTemplateHandler(private val baseUrl: String) : UriTemplate } class RestTjeneste( - internal val rest: ResttjenesteMedBaseUrl + internal val rest: ResttjenesteMedBaseUrl, ) { companion object { @JvmStatic @@ -125,7 +134,10 @@ class RestTjeneste( } } - private fun hentToken(applicationName: String, saksbehandlerType: SaksbehandlerType? = null): TokenValue { + private fun hentToken( + applicationName: String, + saksbehandlerType: SaksbehandlerType? = null, + ): TokenValue { val tokenService: TokenService = BidragCucumberSingletons.hentEllerInit(AzureTokenService::class) ?: throw notNullTokenService() return TokenValue(tokenService.getToken(applicationName, saksbehandlerType)) @@ -138,9 +150,11 @@ class RestTjeneste( internal var responseEntity: ResponseEntity? = null fun hentFullUrlMedEventuellWarning() = "$fullUrl${appendWarningWhenExists()}" - fun hentHttpStatus(): HttpStatus = - HttpStatus.valueOf(responseEntity?.statusCode?.value() ?: HttpStatus.I_AM_A_TEAPOT.value()) + + fun hentHttpStatus(): HttpStatus = HttpStatus.valueOf(responseEntity?.statusCode?.value() ?: HttpStatus.I_AM_A_TEAPOT.value()) + fun hentResponse(): String? = responseEntity?.body + fun hentResponseSomMap() = BidragCucumberSingletons.mapResponseSomMap(responseEntity) private fun appendWarningWhenExists(): String { @@ -149,20 +163,27 @@ class RestTjeneste( return if (warnings.isNotEmpty()) " - ${warnings[0]}" else "" } - fun exchangeGet(endpointUrl: String, failOnNotFound: Boolean = true): ResponseEntity { + fun exchangeGet( + endpointUrl: String, + failOnNotFound: Boolean = true, + ): ResponseEntity { val header = initHttpHeadersWithCorrelationIdAndEnhet() exchange( jsonEntity = HttpEntity(null, header), endpointUrl = endpointUrl, httpMethod = HttpMethod.GET, - failOnNotFound = failOnNotFound + failOnNotFound = failOnNotFound, ) LOGGER.info( if (responseEntity?.body != null) { "response with body and status ${responseEntity!!.statusCode}" - } else if (responseEntity == null) "no response entity (${sanityCheck()})" else "no response body with status ${responseEntity!!.statusCode}" + } else if (responseEntity == null) { + "no response entity (${sanityCheck()})" + } else { + "no response body with status ${responseEntity!!.statusCode}" + }, ) return responseEntity ?: ResponseEntity.status(HttpStatus.I_AM_A_TEAPOT).build() @@ -180,12 +201,18 @@ class RestTjeneste( return headers } - fun exchangePost(endpointUrl: String, body: Any) { + fun exchangePost( + endpointUrl: String, + body: Any, + ) { val jsonEntity = httpEntity(BidragCucumberSingletons.toJson(body)) exchange(jsonEntity, endpointUrl, HttpMethod.POST) } - fun exchangePost(endpointUrl: String, body: String) { + fun exchangePost( + endpointUrl: String, + body: String, + ) { val jsonEntity = httpEntity(body) exchange(jsonEntity, endpointUrl, HttpMethod.POST) } @@ -194,12 +221,18 @@ class RestTjeneste( exchange(httpEntity("{}"), endpointUrl, HttpMethod.POST) } - fun exchangeDelete(endpointUrl: String, body: String) { + fun exchangeDelete( + endpointUrl: String, + body: String, + ) { val jsonEntity = httpEntity(body) exchange(jsonEntity, endpointUrl, HttpMethod.DELETE) } - fun exchangePatch(endpointUrl: String, body: Any) { + fun exchangePatch( + endpointUrl: String, + body: Any, + ) { val jsonEntity = httpEntity(BidragCucumberSingletons.toJson(body)) exchange(jsonEntity, endpointUrl, HttpMethod.PATCH) } @@ -210,18 +243,24 @@ class RestTjeneste( return HttpEntity(body, headers) } - private fun exchange(jsonEntity: HttpEntity<*>, endpointUrl: String, httpMethod: HttpMethod, failOnNotFound: Boolean = true) { + private fun exchange( + jsonEntity: HttpEntity<*>, + endpointUrl: String, + httpMethod: HttpMethod, + failOnNotFound: Boolean = true, + ) { fullUrl = FullUrl(rest.baseUrl, endpointUrl) LOGGER.info("$httpMethod: $fullUrl") try { responseEntity = rest.template.exchange(endpointUrl, httpMethod, jsonEntity, String::class.java) } catch (e: Exception) { - responseEntity = if (e is HttpStatusCodeException) { - ResponseEntity.status(e.statusCode).body(failure(jsonEntity.body, e)) - } else { - ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failure(jsonEntity.body, e)) - } + responseEntity = + if (e is HttpStatusCodeException) { + ResponseEntity.status(e.statusCode).body(failure(jsonEntity.body, e)) + } else { + ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failure(jsonEntity.body, e)) + } if (isError(e, failOnNotFound)) { ScenarioManager.errorLog(">>> $httpMethod FEILET! ($fullUrl) ${failure(jsonEntity.body, e)}", e) @@ -233,15 +272,25 @@ class RestTjeneste( } } - private fun isError(e: Exception, failOn404: Boolean) = if (isNotFound(e)) failOn404 else true + private fun isError( + e: Exception, + failOn404: Boolean, + ) = if (isNotFound(e)) failOn404 else true + private fun isNotFound(e: Exception) = e is HttpStatusCodeException && e.statusCode == HttpStatus.NOT_FOUND - private fun failure(body: Any?, e: Exception) = """- - - input body: $body - - exception : "${e::class.simpleName}: ${e.message}" - """.trimIndent() + + private fun failure( + body: Any?, + e: Exception, + ) = """ + - + - input body: $body + - exception : "${e::class.simpleName}: ${e.message}" + """.trimIndent() } class ResttjenesteMedBaseUrl(val template: RestTemplate, val baseUrl: String) + class TokenValue(private val token: String) { fun initBearerToken() = "Bearer $token" } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/RunStats.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/RunStats.kt index 5fa9e9b..e219b2c 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/RunStats.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/RunStats.kt @@ -31,22 +31,31 @@ class RunStats { Failed : $noOfFailed $failedScenariosAsString $failureDetailsAsString""" } - private fun createStringOfFailedScenarios() = if (failedScenarios.isEmpty()) { - "" - } else { - "\n\nFailed scenarios:\n${ - failedScenarios.joinToString(prefix = "- ", separator = "\n- ") - }" - } + private fun createStringOfFailedScenarios() = + if (failedScenarios.isEmpty()) { + "" + } else { + "\n\nFailed scenarios:\n${ + failedScenarios.joinToString(prefix = "- ", separator = "\n- ") + }" + } - internal fun createStringOfFailureDetails() = if (exceptionMessages.isEmpty()) { - "" - } else { - "\n\nFailure details:\n${exceptionMessages.joinToString(separator = "\n")}" - } + internal fun createStringOfFailureDetails() = + if (exceptionMessages.isEmpty()) { + "" + } else { + "\n\nFailure details:\n${exceptionMessages.joinToString(separator = "\n")}" + } fun addExceptionLogging(messages: List) { - exceptionMessages.addAll(messages.mapIndexed { idx, message -> if (idx == 0) "- ${indentLines(message)}" else " ${indentLines(message)}" }) + exceptionMessages.addAll( + messages.mapIndexed { + idx, + message, + -> + if (idx == 0) "- ${indentLines(message)}" else " ${indentLines(message)}" + }, + ) } private fun indentLines(message: String) = message.replace("\n", "\n ") diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceText.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceText.kt index a719373..c9811ee 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceText.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceText.kt @@ -2,9 +2,10 @@ package no.nav.bidrag.cucumber.model class SuppressStackTraceText { fun suppress(text: String): String { - val lines = text - .split('\n') - .filter { doNotSuppress(it) } + val lines = + text + .split('\n') + .filter { doNotSuppress(it) } return lines.joinToString(separator = "\n") } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/TestData.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/TestData.kt index 4f65f83..d2def87 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/TestData.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/TestData.kt @@ -4,11 +4,17 @@ internal class TestData { val dataForNokkel: MutableMap = HashMap() var nokkel: String? = null - fun hentData(nokkel: String? = null) = dataForNokkel[nokkel ?: this.nokkel] ?: throw IllegalArgumentException("Fant ingen data for nøkkel") + fun hentData(nokkel: String? = null) = + dataForNokkel[nokkel ?: this.nokkel] ?: throw IllegalArgumentException( + "Fant ingen data for nøkkel", + ) + fun hentDataMedNøkkel(dataNøkkel: String? = null) = hentData()[dataNøkkel] + fun lagreData(data: Pair) { hentData()?.put(data.first, data.second) } + fun initialiserData(nokkel: String) { if (!dataForNokkel.contains(nokkel)) { this.nokkel = nokkel diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/model/TestMessagesHolder.kt b/src/main/kotlin/no/nav/bidrag/cucumber/model/TestMessagesHolder.kt index 0391c28..79a8a2a 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/model/TestMessagesHolder.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/model/TestMessagesHolder.kt @@ -4,6 +4,8 @@ internal class TestMessagesHolder { private val testMessages: MutableList = ArrayList() fun fetchTestMessages() = testMessages.joinToString(separator = "\n") + fun hold(testMessage: String) = testMessages.add(testMessage) + fun hold(messages: List) = messages.forEach { hold(it) } } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenCache.kt b/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenCache.kt index cd942e0..a1132e3 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenCache.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenCache.kt @@ -7,7 +7,10 @@ import com.nimbusds.oauth2.sdk.token.Tokens import java.util.concurrent.TimeUnit object AzureTokenCache { - fun accessTokenResponseCache(maximumSize: Long, skewInSeconds: Long): Cache { + fun accessTokenResponseCache( + maximumSize: Long, + skewInSeconds: Long, + ): Cache { // Evict based on a varying expiration policy return Caffeine.newBuilder() .maximumSize(maximumSize) @@ -17,17 +20,35 @@ object AzureTokenCache { private fun evictOnResponseExpiresIn(skewInSeconds: Long): Expiry { return object : Expiry { - override fun expireAfterCreate(p0: T, response: Tokens, p2: Long): Long { + override fun expireAfterCreate( + p0: T, + response: Tokens, + p2: Long, + ): Long { val seconds = - if (response.accessToken.lifetime > skewInSeconds) response.accessToken.lifetime - skewInSeconds else response.accessToken.lifetime + if (response.accessToken.lifetime > skewInSeconds) { + response.accessToken.lifetime - skewInSeconds + } else { + response.accessToken.lifetime + } return TimeUnit.SECONDS.toNanos(seconds) } - override fun expireAfterUpdate(p0: T, p1: Tokens?, p2: Long, currentDuration: Long): Long { + override fun expireAfterUpdate( + p0: T, + p1: Tokens?, + p2: Long, + currentDuration: Long, + ): Long { return currentDuration } - override fun expireAfterRead(p0: T, p1: Tokens?, p2: Long, currentDuration: Long): Long { + override fun expireAfterRead( + p0: T, + p1: Tokens?, + p2: Long, + currentDuration: Long, + ): Long { return currentDuration } } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenService.kt b/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenService.kt index 428ca30..a9f68b2 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenService.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/service/AzureTokenService.kt @@ -26,7 +26,7 @@ import java.net.URI data class AzureTokenRequest( val app: String, - val saksbehandlerType: SaksbehandlerType? = null + val saksbehandlerType: SaksbehandlerType? = null, ) @Component @@ -48,9 +48,8 @@ class AzureTokenService( val scopes: AppScopes, @Value("\${AZURE_OPENID_CONFIG_TOKEN_ENDPOINT}") val tokenUri: String, @Value("\${AZURE_APP_CLIENT_ID}") val clientId: String, - @Value("\${AZURE_APP_CLIENT_SECRET}") val clientSecret: String + @Value("\${AZURE_APP_CLIENT_SECRET}") val clientSecret: String, ) : TokenService() { - private lateinit var tokenCache: Cache private lateinit var clientAuth: ClientSecretPost @@ -61,7 +60,10 @@ class AzureTokenService( tokenCache = AzureTokenCache.accessTokenResponseCache(1000, 10) } - override fun generateToken(application: String, saksbehandlerType: SaksbehandlerType?): String { + override fun generateToken( + application: String, + saksbehandlerType: SaksbehandlerType?, + ): String { val request = AzureTokenRequest(application, saksbehandlerType) return tokenCache.get(request) { s: AzureTokenRequest? -> generateToken(request) }!!.accessToken.value } @@ -72,7 +74,11 @@ class AzureTokenService( } return generateClientCredentialsToken(request.app) } - private fun generateOnBehalfOfToken(appName: String, saksbehandlerType: SaksbehandlerType): Tokens { + + private fun generateOnBehalfOfToken( + appName: String, + saksbehandlerType: SaksbehandlerType, + ): Tokens { val appScope = scopes.clients[appName] val userId = testusers.identer[saksbehandlerType] ?: usernameNotFound() val usertoken = getUserToken(userId) @@ -83,7 +89,15 @@ class AzureTokenService( val customParams: MutableMap> = HashMap() customParams["requested_token_use"] = listOf("on_behalf_of") customParams["client_assertion_type"] = listOf("urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - val request = TokenRequest(tokenEndpoint, clientAuth, JWTBearerGrant(SignedJWT.parse(usertoken.accessToken.value)), scope, null, customParams) + val request = + TokenRequest( + tokenEndpoint, + clientAuth, + JWTBearerGrant(SignedJWT.parse(usertoken.accessToken.value)), + scope, + null, + customParams, + ) doTokenRequest(request) } catch (e: Exception) { LOGGER.error("Det skjedde en feil ved henting av on-behalf-of token fra Azure", e) @@ -109,7 +123,13 @@ class AzureTokenService( return try { val scope = Scope("openid offline_access $clientId/.default") val tokenEndpoint = URI(tokenUri) - val request = TokenRequest(tokenEndpoint, clientAuth, ResourceOwnerPasswordCredentialsGrant("f_$userId.e_$userId@trygdeetaten.no", Secret(user_password)), scope) + val request = + TokenRequest( + tokenEndpoint, + clientAuth, + ResourceOwnerPasswordCredentialsGrant("f_$userId.e_$userId@trygdeetaten.no", Secret(user_password)), + scope, + ) doTokenRequest(request) } catch (e: Exception) { LOGGER.error("Det skjedde en feil ved henting av client-credentials token fra Azure", e) @@ -124,13 +144,14 @@ class AzureTokenService( if (!response.indicatesSuccess()) { // We got an error response... val errorObject: ErrorObject = response.toErrorResponse().errorObject - val errorMessage = String.format( - "Det skjedde en feil ved henting av token fra Azure - code: %s, description: %s, uri: %s, statusCode: %s", - errorObject.code, - errorObject.description, - errorObject.uri, - errorObject.httpStatusCode - ) + val errorMessage = + String.format( + "Det skjedde en feil ved henting av token fra Azure - code: %s, description: %s, uri: %s, statusCode: %s", + errorObject.code, + errorObject.description, + errorObject.uri, + errorObject.httpStatusCode, + ) LOGGER.error(errorMessage) throw AzureTokenException(errorMessage) } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/service/CucumberService.kt b/src/main/kotlin/no/nav/bidrag/cucumber/service/CucumberService.kt index 2092e93..937b1d3 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/service/CucumberService.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/service/CucumberService.kt @@ -18,7 +18,7 @@ class CucumberService( applicationContext: ApplicationContext, exceptionLogger: ExceptionLogger, hendelseProducer: HendelseProducer, - objectMapper: ObjectMapper + objectMapper: ObjectMapper, ) { init { BidragCucumberSingletons.setApplicationContext(applicationContext) @@ -30,9 +30,10 @@ class CucumberService( internal fun run(cucumberTestRun: CucumberTestRun): String { val result = runCucumberTests(cucumberTestRun.tags) - val suppressedStackTraceLog = suppressStackTraceText.suppress( - CucumberTestRun.fetchTestMessagesWithRunStats() - ) + val suppressedStackTraceLog = + suppressStackTraceText.suppress( + CucumberTestRun.fetchTestMessagesWithRunStats(), + ) CucumberTestRun.endRun() @@ -51,7 +52,7 @@ class CucumberService( "--glue", "no.nav.bidrag.cucumber.cloud", "--tags", - tags + tags, ) } } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/service/TokenService.kt b/src/main/kotlin/no/nav/bidrag/cucumber/service/TokenService.kt index 405e3eb..0f6c10d 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/service/TokenService.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/service/TokenService.kt @@ -4,14 +4,21 @@ import no.nav.bidrag.cucumber.dto.SaksbehandlerType import no.nav.bidrag.cucumber.model.CucumberTestRun abstract class TokenService { - abstract fun generateToken(application: String, saksbehandlerType: SaksbehandlerType? = null): String + abstract fun generateToken( + application: String, + saksbehandlerType: SaksbehandlerType? = null, + ): String - fun getToken(application: String, saksbehandlerType: SaksbehandlerType? = null): String { - val token = if (CucumberTestRun.isNotSanityCheck) { - generateToken(application, saksbehandlerType) - } else { - "sanity check: no token" - } + fun getToken( + application: String, + saksbehandlerType: SaksbehandlerType? = null, + ): String { + val token = + if (CucumberTestRun.isNotSanityCheck) { + generateToken(application, saksbehandlerType) + } else { + "sanity check: no token" + } return token } } diff --git a/src/main/kotlin/no/nav/bidrag/cucumber/sikkerhet/SecurityConfiguration.kt b/src/main/kotlin/no/nav/bidrag/cucumber/sikkerhet/SecurityConfiguration.kt index 5038584..ca5f573 100644 --- a/src/main/kotlin/no/nav/bidrag/cucumber/sikkerhet/SecurityConfiguration.kt +++ b/src/main/kotlin/no/nav/bidrag/cucumber/sikkerhet/SecurityConfiguration.kt @@ -5,7 +5,6 @@ import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity -import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService @@ -13,26 +12,24 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint - @Configuration @EnableWebSecurity class SecurityConfiguration( @Value("\${REST_AUTH_BRUKERNAVN}") val authBrukernavn: String, - @Value("\${REST_AUTH_PASSORD}") val authPassord: String + @Value("\${REST_AUTH_PASSORD}") val authPassord: String, ) { - @Bean fun userDetailsService(): UserDetailsService { - val user: UserDetails = User - .withUsername(authBrukernavn) - .password("{noop}$authPassord").roles("USER") - .build() + val user: UserDetails = + User + .withUsername(authBrukernavn) + .password("{noop}$authPassord").roles("USER") + .build() return InMemoryUserDetailsManager(user) } @Bean fun filterChain(http: HttpSecurity): SecurityFilterChain { - http .authorizeHttpRequests { auth -> auth.requestMatchers("/actuator/**", "/swagger-ui/**", "/v3/api-docs", "/v3/api-docs/**").permitAll() diff --git a/src/test/kotlin/no/nav/bidrag/BidragCucumberCloudLokalNais.kt b/src/test/kotlin/no/nav/bidrag/BidragCucumberCloudLokalNais.kt index 89de774..480d287 100644 --- a/src/test/kotlin/no/nav/bidrag/BidragCucumberCloudLokalNais.kt +++ b/src/test/kotlin/no/nav/bidrag/BidragCucumberCloudLokalNais.kt @@ -6,10 +6,11 @@ import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.FilterType @SpringBootApplication -@ComponentScan(excludeFilters = [ComponentScan.Filter(pattern = ["no.nav.bidrag.commons..*", "no.nav.security..*"], type = FilterType.ASPECTJ)]) +@ComponentScan( + excludeFilters = [ComponentScan.Filter(pattern = ["no.nav.bidrag.commons..*", "no.nav.security..*"], type = FilterType.ASPECTJ)], +) class BidragCucumberCloudLokalNais { companion object { - @JvmStatic fun main(args: Array) { val app = SpringApplication(BidragCucumberCloudLokalNais::class.java) diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloudLocal.kt b/src/test/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloudLocal.kt index 5a0fab6..e54e265 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloudLocal.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/BidragCucumberCloudLocal.kt @@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class BidragCucumberCloudLocal { companion object { - @JvmStatic fun main(args: Array) { BidragCucumberCloud.main(args) diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/FilePathTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/FilePathTest.kt index b20bd80..07e0790 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/FilePathTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/FilePathTest.kt @@ -17,7 +17,7 @@ internal class FilePathTest { { assertThat(filePath.findFolderPath()).`as`("folder path") .isEqualTo(File("src/main/resources/no/nav/bidrag/cucumber/cloud").absolutePath) - } + }, ) } } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/NotLiveSpringConfig.kt b/src/test/kotlin/no/nav/bidrag/cucumber/NotLiveSpringConfig.kt index 091ccde..42729db 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/NotLiveSpringConfig.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/NotLiveSpringConfig.kt @@ -11,7 +11,6 @@ import org.springframework.kafka.core.ProducerFactory @Configuration @Profile("!$PROFILE_LIVE") class NotLiveSpringConfig { - @Bean fun hendelseProducer() = mock(HendelseProducer::class.java)!! diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/TestConfiguration.kt b/src/test/kotlin/no/nav/bidrag/cucumber/TestConfiguration.kt index 4f4b5d2..832974b 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/TestConfiguration.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/TestConfiguration.kt @@ -10,7 +10,7 @@ class TestConfiguration { @Bean fun restTemplateBuilder( @Value("\${REST_AUTH_BRUKERNAVN}") authBrukernavn: String, - @Value("\${REST_AUTH_PASSORD}") authPassord: String + @Value("\${REST_AUTH_PASSORD}") authPassord: String, ): RestTemplateBuilder { return RestTemplateBuilder().basicAuthentication(authBrukernavn, authPassord) } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/TestUtil.kt b/src/test/kotlin/no/nav/bidrag/cucumber/TestUtil.kt index ffe1a4f..1980bb3 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/TestUtil.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/TestUtil.kt @@ -7,14 +7,17 @@ import java.time.LocalDateTime import java.util.concurrent.CompletableFuture object TestUtil { - - fun assumeThatActuatorHealthIsRunning(ingress: String, contextPath: String) { + fun assumeThatActuatorHealthIsRunning( + ingress: String, + contextPath: String, + ) { val start = LocalDateTime.now() - val future = CompletableFuture.runAsync { - val response = RestTemplate().getForEntity("$ingress/$contextPath/actuator/health", String::class.java) + val future = + CompletableFuture.runAsync { + val response = RestTemplate().getForEntity("$ingress/$contextPath/actuator/health", String::class.java) - assumeThat(response.statusCode).isEqualTo(HttpStatus.OK) - } + assumeThat(response.statusCode).isEqualTo(HttpStatus.OK) + } while (!future.isDone) { if (start.plusSeconds(1).isAfter(LocalDateTime.now())) { diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspectTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspectTest.kt index 5d66ce9..f0064ea 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspectTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspectTest.kt @@ -21,9 +21,7 @@ import org.springframework.test.context.ActiveProfiles @SpringBootTest(classes = [BidragCucumberCloudLocal::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") internal class ExceptionLoggerAspectTest { - @Autowired - @Suppress("SpringJavaInjectionPointsAutowiringInspection") private lateinit var testRestTemplate: TestRestTemplate @MockkBean diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseServiceTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseServiceTest.kt index 0f561d3..058e973 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseServiceTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/cloud/arbeidsflyt/OppgaveOgHendelseServiceTest.kt @@ -29,12 +29,12 @@ import org.springframework.test.context.ActiveProfiles @SpringBootTest(classes = [BidragCucumberCloud::class]) @ActiveProfiles("test") internal class OppgaveOgHendelseServiceTest { - private val baseUrl = "https://base" - private val journalpostHendelse = JournalpostHendelse( - journalpostId = "BID-1010101010", - fagomrade = FAGOMRADE_BIDRAG - ) + private val journalpostHendelse = + JournalpostHendelse( + journalpostId = "BID-1010101010", + fagomrade = FAGOMRADE_BIDRAG, + ) @MockkBean(relaxed = true) private lateinit var azureTokenService: AzureTokenService @@ -61,17 +61,19 @@ internal class OppgaveOgHendelseServiceTest { verify { hendelseProducerMock.publish( - JournalpostHendelse(journalpostId = "BID-${journalpostHendelse.hentJournalpostIdUtenPrefix()}", fagomrade = "BID") + JournalpostHendelse(journalpostId = "BID-${journalpostHendelse.hentJournalpostIdUtenPrefix()}", fagomrade = "BID"), ) } } @Test fun `skal opprette oppgave`() { - every { httpHeaderRestTemplateMock.exchange(any(), eq(HttpMethod.POST), any(), eq(String::class.java)) } returns ResponseEntity.ok() - .build() - every { httpHeaderRestTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) } returns ResponseEntity.ok() - .body("""{"antallTreffTotalt":"0"}""") + every { httpHeaderRestTemplateMock.exchange(any(), eq(HttpMethod.POST), any(), eq(String::class.java)) } returns + ResponseEntity.ok() + .build() + every { httpHeaderRestTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) } returns + ResponseEntity.ok() + .body("""{"antallTreffTotalt":"0"}""") OppgaveOgHendelseService.tilbyOppgave(journalpostHendelse) @@ -99,7 +101,6 @@ internal class OppgaveOgHendelseServiceTest { OppgaveOgHendelseService.tilbyOppgave(journalpostHendelse) - @Suppress("UNCHECKED_CAST") val httpEntityCaptor = slot>() verify { @@ -107,14 +108,20 @@ internal class OppgaveOgHendelseServiceTest { "/api/v1/oppgaver/1001", HttpMethod.PATCH, capture(httpEntityCaptor), - String::class.java + String::class.java, ) } assertThat(httpEntityCaptor.captured.body).isEqualTo( BidragCucumberSingletons.toJson( - PatchStatusOppgaveRequest(id = 1001, status = "UNDER_BEHANDLING", tema = FAGOMRADE_BIDRAG, versjon = 1, tildeltEnhetsnr = "4812") - ) + PatchStatusOppgaveRequest( + id = 1001, + status = "UNDER_BEHANDLING", + tema = FAGOMRADE_BIDRAG, + versjon = 1, + tildeltEnhetsnr = "4812", + ), + ), ) } @@ -123,7 +130,9 @@ internal class OppgaveOgHendelseServiceTest { every { httpHeaderRestTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) } .returns(ResponseEntity.ok().body("""{"antallTreffTotalt":"0","oppgaver":[]}""")) .andThen(ResponseEntity.ok().body("""{"antallTreffTotalt":"0","oppgaver":[]}""")) - .andThen(ResponseEntity.ok().body("""{"antallTreffTotalt":"1","oppgaver":[{"id":"1001","versjon":"1","tildeltEnhetsnr":"123"}]}""")) + .andThen( + ResponseEntity.ok().body("""{"antallTreffTotalt":"1","oppgaver":[{"id":"1001","versjon":"1","tildeltEnhetsnr":"123"}]}"""), + ) OppgaveOgHendelseService.sokOpprettetOppgaveForHendelse(123, "BID", antallGjentakelser = 3) OppgaveOgHendelseService.assertThatOppgaveHar("123") diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerCucumberServiceMockBeanTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerCucumberServiceMockBeanTest.kt index f7227e5..060e4ba 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerCucumberServiceMockBeanTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerCucumberServiceMockBeanTest.kt @@ -27,9 +27,7 @@ import org.springframework.test.context.ActiveProfiles @DisplayName("CucumberController (mocked bean: CucumberService)") @ActiveProfiles("test") internal class CucumberControllerCucumberServiceMockBeanTest { - @Autowired - @Suppress("SpringJavaInjectionPointsAutowiringInspection") private lateinit var testRestTemplate: TestRestTemplate @MockBean @@ -47,18 +45,19 @@ internal class CucumberControllerCucumberServiceMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["ingress@tag"] } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) @@ -70,18 +69,19 @@ internal class CucumberControllerCucumberServiceMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "sanityCheck":true } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) @@ -93,18 +93,19 @@ internal class CucumberControllerCucumberServiceMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "securityToken":"xyz..." } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) @@ -118,18 +119,19 @@ internal class CucumberControllerCucumberServiceMockBeanTest { whenever(cucumberServiceMock.run(any())).thenThrow(TestFailedException("not ok", "test failed")) - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity("{}", headers), - Void::class.java - ) + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity("{}", headers), + Void::class.java, + ) assertAll( { assertThat(testResponse.statusCode).`as`("status code").isEqualTo(HttpStatus.NOT_ACCEPTABLE) }, { val warning = testResponse.headers[HttpHeaders.WARNING]?.first() ?: fail("fant ingen feilmelding fra WARNING-header") assertThat(warning).`as`("warning").isEqualTo("TestFailedException: not ok") - } + }, ) } @@ -140,18 +142,19 @@ internal class CucumberControllerCucumberServiceMockBeanTest { whenever(cucumberServiceMock.run(any())).thenThrow(IllegalStateException("something fishy happened")) - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity("{}", headers), - Void::class.java - ) + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity("{}", headers), + Void::class.java, + ) assertAll( { assertThat(testResponse.statusCode).`as`("status code").isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) }, { val warning = testResponse.headers[HttpHeaders.WARNING]?.first() ?: fail("fant ingen feilmelding fra WARNING-header") assertThat(warning).`as`("warning").isEqualTo("IllegalStateException: something fishy happened") - } + }, ) } @@ -160,20 +163,21 @@ internal class CucumberControllerCucumberServiceMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-sak.intern.dev.nav.no@bidrag-sak"], "testUsername":"z993902", "sanityCheck":true } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertAll( { assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) }, @@ -183,11 +187,11 @@ internal class CucumberControllerCucumberServiceMockBeanTest { CucumberTestsModel( sanityCheck = true, testUsername = "z993902", - ingressesForApps = listOf("https://bidrag-sak.intern.dev.nav.no@bidrag-sak") - ) - ) + ingressesForApps = listOf("https://bidrag-sak.intern.dev.nav.no@bidrag-sak"), + ), + ), ) - } + }, ) } @@ -196,19 +200,20 @@ internal class CucumberControllerCucumberServiceMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://some-ingress@some-app"], "tags":["@some-tag"] } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertAll( { assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) }, @@ -217,11 +222,11 @@ internal class CucumberControllerCucumberServiceMockBeanTest { CucumberTestRun( CucumberTestsModel( ingressesForApps = listOf("https://some-ingress@some-app"), - tags = listOf("@some-tag") - ) - ) + tags = listOf("@some-tag"), + ), + ), ) - } + }, ) } } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerIntegrationTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerIntegrationTest.kt index 7675d33..9dfdec4 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerIntegrationTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerIntegrationTest.kt @@ -22,14 +22,15 @@ import org.springframework.test.context.ActiveProfiles @DisplayName("CucumberController (integration test)") @ActiveProfiles("test") internal class CucumberControllerIntegrationTest { - @Autowired - @Suppress("SpringJavaInjectionPointsAutowiringInspection") private lateinit var testRestTemplate: TestRestTemplate private val ingressIsUp: MutableMap = HashMap() - private fun assumeThatActuatorHealthIsRunningCachedException(ingress: String, app: String) { + private fun assumeThatActuatorHealthIsRunningCachedException( + ingress: String, + app: String, + ) { if (!ingressIsUp.contains(ingress)) { try { assumeThatActuatorHealthIsRunning(ingress, app) @@ -48,18 +49,19 @@ internal class CucumberControllerIntegrationTest { fun `skal feile ved testing av applikasjon med azure ad`() { assumeThatActuatorHealthIsRunningCachedException("https://bidrag-grunnlag.intern.dev.nav.no", "bidrag-grunnlag") - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-sak.intern.dev.nav.no@tag:bidrag-grunnlag"] } - """.trimMargin().trim(), - initJsonAsMediaType() - ), - Void::class.java - ) + """.trimMargin().trim(), + initJsonAsMediaType(), + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.NOT_ACCEPTABLE) } @@ -69,40 +71,45 @@ internal class CucumberControllerIntegrationTest { fun `skal ikke feile ved testing av applikasjon med azure ad når det er snakk om en sanity check`() { assumeThatActuatorHealthIsRunningCachedException("https://bidrag-grunnlag.intern.dev.nav.no", "bidrag-grunnlag") - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-grunnlag.intern.dev.nav.no@tag:bidrag-grunnlag"], "sanityCheck":true } - """.trimMargin().trim(), - initJsonAsMediaType() - ), - Void::class.java - ) + """.trimMargin().trim(), + initJsonAsMediaType(), + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) } @Test fun `skal hente ut cucumber tekst fra kjøring`() { - assumeThatActuatorHealthIsRunningCachedException("https://bidrag-cucumber-cloud-feature.ekstern.dev.nav.no", "bidrag-cucumber-cloud") + assumeThatActuatorHealthIsRunningCachedException( + "https://bidrag-cucumber-cloud-feature.ekstern.dev.nav.no", + "bidrag-cucumber-cloud", + ) - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-cucumber-cloud.ekstern.dev.nav.no@tag:bidrag-cucumber-cloud"], "sanityCheck":true } - """.trimMargin().trim(), - initJsonAsMediaType() - ), - String::class.java - ) + """.trimMargin().trim(), + initJsonAsMediaType(), + ), + String::class.java, + ) val softly = SoftAssertions() softly.assertThat(testResponse.body).`as`("body").contains("Scenarios") @@ -116,42 +123,44 @@ internal class CucumberControllerIntegrationTest { fun `skal ikke feile når det er sanity check`() { assumeThatActuatorHealthIsRunningCachedException("https://bidrag-grunnlag.intern.dev.nav.no", "bidrag-grunnlag") - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-sak.intern.dev.nav.no@tag:bidrag-grunnlag"], "sanityCheck":true } - """.trimMargin().trim(), - initJsonAsMediaType() - ), - String::class.java - ) + """.trimMargin().trim(), + initJsonAsMediaType(), + ), + String::class.java, + ) assertThat(testResponse.statusCode).`as`("status code").isEqualTo(HttpStatus.OK) } @Test fun `skal logge eventuelle exception når det feiler under testing`() { - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "ingressesForApps":["https://bidrag-sak.intern.dev.nav.no@bidrag-sak"], "testUsername":"ukjent","tags":["@bidrag-cucumber-cloud"] } - """.trimMargin().trim(), - initJsonAsMediaType() - ), - String::class.java - ) + """.trimMargin().trim(), + initJsonAsMediaType(), + ), + String::class.java, + ) assertAll( { assertThat(testResponse.statusCode).`as`("status code").isEqualTo(HttpStatus.NOT_ACCEPTABLE) }, - { assertThat(testResponse.body).`as`("body").contains("Failure details:") } + { assertThat(testResponse.body).`as`("body").contains("Failure details:") }, ) } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerRestTemplateMockBeanTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerRestTemplateMockBeanTest.kt index 039ef3d..39ce94b 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerRestTemplateMockBeanTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/controller/CucumberControllerRestTemplateMockBeanTest.kt @@ -28,7 +28,6 @@ import org.springframework.test.context.ActiveProfiles @DisplayName("CucumberController (mocked bean: RestTemplate)") @ActiveProfiles("test") class CucumberControllerRestTemplateMockBeanTest { - @Autowired private lateinit var testRestTemplate: TestRestTemplate @@ -41,20 +40,21 @@ class CucumberControllerRestTemplateMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "testUsername":"z992903","ingressesForApps":[ "https://bidrag-sak-feature.dev-fss-pub.nais.io@bidrag-sak" ] } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) val urlCaptor = ArgumentCaptor.forClass(String::class.java) @@ -62,12 +62,12 @@ class CucumberControllerRestTemplateMockBeanTest { urlCaptor.capture(), eq(HttpMethod.GET), any(), - eq(String::class.java) + eq(String::class.java), ) assertAll( { assertThat(testResponse.statusCode).`as`("status code").isEqualTo(HttpStatus.NOT_ACCEPTABLE) }, - { assertThat(urlCaptor.value).`as`("endpoint url").isEqualTo("/sak/1900000") } + { assertThat(urlCaptor.value).`as`("endpoint url").isEqualTo("/sak/1900000") }, ) } @@ -77,20 +77,21 @@ class CucumberControllerRestTemplateMockBeanTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/run", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/run", + HttpEntity( + """ { "testUsername":"z992903","ingressesForApps":[ "https://bidrag-sak-feature.dev-fss-pub.nais.io@bidrag-sak" ] } - """.trimMargin().trim(), - headers - ), - String::class.java - ) + """.trimMargin().trim(), + headers, + ), + String::class.java, + ) val testMessages = testResponse.body ?: "Ingen body i response: $testResponse" diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/controller/HendelseControllerTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/controller/HendelseControllerTest.kt index 4f2c8e2..064c539 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/controller/HendelseControllerTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/controller/HendelseControllerTest.kt @@ -23,9 +23,7 @@ import org.springframework.test.context.ActiveProfiles @DisplayName("HendelseController (mocked HendelseProducer)") @ActiveProfiles("test") internal class HendelseControllerTest { - @Autowired - @Suppress("SpringJavaInjectionPointsAutowiringInspection") private lateinit var testRestTemplate: TestRestTemplate @MockBean @@ -41,19 +39,20 @@ internal class HendelseControllerTest { val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON - val testResponse = testRestTemplate.postForEntity( - "/hendelse/opprett", - HttpEntity( - """ + val testResponse = + testRestTemplate.postForEntity( + "/hendelse/opprett", + HttpEntity( + """ { "journalpostId":"1001", "brukerident":"jumbo" } - """.trimMargin().trim(), - headers - ), - Void::class.java - ) + """.trimMargin().trim(), + headers, + ), + Void::class.java, + ) assertThat(testResponse.statusCode).isEqualTo(HttpStatus.OK) diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/controller/JsonMappingTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/controller/JsonMappingTest.kt index 1e2b490..302af27 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/controller/JsonMappingTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/controller/JsonMappingTest.kt @@ -16,20 +16,20 @@ import org.springframework.test.context.ActiveProfiles @DisplayName("Test of mapping dto from json") @ActiveProfiles("test") class JsonMappingTest { - @Autowired private lateinit var objectMapper: ObjectMapper @Test fun `skal mappe en kjøring av bidrag-arberdsflyt`() { - val json = """ - { - "tags":["@arbeidsflyt-endre-fagomrade"], - "testUsername":"z992903", - "noContextPathForApps":["oppgave"], - "ingressesForApps":["https://oppgave-q1.dev-fss-pub.nais.io@oppgave"] - } - """.trimIndent() + val json = + """ + { + "tags":["@arbeidsflyt-endre-fagomrade"], + "testUsername":"z992903", + "noContextPathForApps":["oppgave"], + "ingressesForApps":["https://oppgave-q1.dev-fss-pub.nais.io@oppgave"] + } + """.trimIndent() val cucumberTestsModel = objectMapper.readValue(json, CucumberTestsModel::class.java) @@ -41,7 +41,7 @@ class JsonMappingTest { { assertThat(cucumberTestsModel.ingressesForApps).`as`("ingressesForApps") .isEqualTo(listOf("https://oppgave-q1.dev-fss-pub.nais.io@oppgave")) - } + }, ) } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducerTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducerTest.kt index 75a18e4..9ccaea1 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducerTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/hendelse/JournalpostKafkaHendelseProducerTest.kt @@ -52,12 +52,13 @@ internal class JournalpostKafkaHendelseProducerTest { whenever(objectMapperMock.writeValueAsString(journalpostHendelse)).thenReturn("{}") lenient().`when`(kafkaTemplateMock.send(eq("test.topic"), anyString(), anyString())).then { Thread.sleep(5000) } - val journalpostKafkaHendelseProducer = JournalpostKafkaHendelseProducer( - kafkaTemplate = kafkaTemplateMock, - objectMapper = objectMapperMock, - timeoutAfterSeconds = 1, - topic = "test.topic" - ) + val journalpostKafkaHendelseProducer = + JournalpostKafkaHendelseProducer( + kafkaTemplate = kafkaTemplateMock, + objectMapper = objectMapperMock, + timeoutAfterSeconds = 1, + topic = "test.topic", + ) assertThatExceptionOfType(HendelseTimeoutException::class.java) .isThrownBy { journalpostKafkaHendelseProducer.publish(journalpostHendelse) } @@ -72,12 +73,13 @@ internal class JournalpostKafkaHendelseProducerTest { whenever(objectMapperMock.writeValueAsString(journalpostHendelse)).thenReturn("{}") lenient().`when`(kafkaTemplateMock.send(eq("test.topic"), anyString(), anyString())).then { LOGGER.info("publiserer hendelse...") } - val journalpostKafkaHendelseProducer = JournalpostKafkaHendelseProducer( - kafkaTemplate = kafkaTemplateMock, - objectMapper = objectMapperMock, - timeoutAfterSeconds = 10, - topic = "test.topic" - ) + val journalpostKafkaHendelseProducer = + JournalpostKafkaHendelseProducer( + kafkaTemplate = kafkaTemplateMock, + objectMapper = objectMapperMock, + timeoutAfterSeconds = 10, + topic = "test.topic", + ) journalpostKafkaHendelseProducer.publish(journalpostHendelse) diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModelTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModelTest.kt index cb19733..f3b1891 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModelTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/CucumberTestsModelTest.kt @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test @DisplayName("CucumberTestsDto") internal class CucumberTestsModelTest { - @Test fun `skal ha verdien false som streng når sanityCheck er null`() { val cucumberTestsModel = CucumberTestsModel(sanityCheck = null) @@ -24,10 +23,11 @@ internal class CucumberTestsModelTest { @Test fun `skal også bruke tags som ikke er oppgitt i ingressesForApps`() { - val cucumberTestsModel = CucumberTestsModel( - ingressesForApps = listOf("https://somewhere.out.there@tag:bidrag-grunnlag"), - tags = listOf("@arbeidsflyt-endre-fagomrade") - ) + val cucumberTestsModel = + CucumberTestsModel( + ingressesForApps = listOf("https://somewhere.out.there@tag:bidrag-grunnlag"), + tags = listOf("@arbeidsflyt-endre-fagomrade"), + ) assertThat(cucumberTestsModel.fetchTags()).`as`("cucumberTests.fetchTags") .isEqualTo("(@bidrag-grunnlag or @arbeidsflyt-endre-fagomrade) and not @ignored") @@ -60,10 +60,11 @@ internal class CucumberTestsModelTest { @Test fun `skal ikke hente ut tags dobbelt opp`() { - val cucumberTestsModel = CucumberTestsModel( - ingressesForApps = listOf("https://somewhere.out.there@tag:bidrag-grunnlag"), - tags = listOf("@bidrag-grunnlag") - ) + val cucumberTestsModel = + CucumberTestsModel( + ingressesForApps = listOf("https://somewhere.out.there@tag:bidrag-grunnlag"), + tags = listOf("@bidrag-grunnlag"), + ) assertThat(cucumberTestsModel.fetchTags()).`as`("cucumberTests.fetchTags").isEqualTo("@bidrag-grunnlag and not @ignored") } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteSikkerhetTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteSikkerhetTest.kt index 1ab500b..3b61efb 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteSikkerhetTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteSikkerhetTest.kt @@ -16,7 +16,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken @SpringBootTest(classes = [BidragCucumberCloudLocal::class]) internal class RestTjenesteSikkerhetTest { - @MockBean private lateinit var azureTokenServiceMock: AzureTokenService diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteTest.kt index 0fc55df..52bdd5f 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesteTest.kt @@ -12,7 +12,6 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.context.SpringBootTest -import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.ResponseEntity @@ -27,7 +26,6 @@ import org.springframework.web.client.RestTemplate @ActiveProfiles("test") @ExtendWith(SpringExtension::class) internal class RestTjenesteTest { - @MockkBean private lateinit var azureTokenService: AzureTokenService @@ -41,19 +39,20 @@ internal class RestTjenesteTest { val oaut2AuthorizedClientMock: OAuth2AuthorizedClient = mockk("OAuth2AuthorizedClient") val oauth2AccessTokenMock: OAuth2AccessToken = mockk("OAuth2AccessToken") - every { azureTokenService.generateToken(any(), any())} returns "token" + every { azureTokenService.generateToken(any(), any()) } returns "token" every { azureTokenService.generateToken(any(), isNull()) } returns "" every { azureTokenService.getToken(any(), isNull()) } returns "" - every {oaut2AuthorizedClientMock.accessToken } returns oauth2AccessTokenMock - every {oauth2AccessTokenMock.tokenValue } returns "my secured token" + every { oaut2AuthorizedClientMock.accessToken } returns oauth2AccessTokenMock + every { oauth2AccessTokenMock.tokenValue } returns "my secured token" } @Test fun `gitt INGRESSES_FOR_APPS med verdi for applikasjon, skal RestTjeneste konfigureres med denne verdien`() { - val cucumberTestsModel = CucumberTestsModel( - ingressesForApps = listOf("https://somewhere.com/@nais-app", "https://somewhere.else.com@annen-nais-app"), - testUsername = "James Bond" - ) + val cucumberTestsModel = + CucumberTestsModel( + ingressesForApps = listOf("https://somewhere.com/@nais-app", "https://somewhere.else.com@annen-nais-app"), + testUsername = "James Bond", + ) cucumberTestsModel.initCucumberEnvironment() @@ -62,16 +61,17 @@ internal class RestTjenesteTest { assertAll( { assertThat(restTjeneste.rest.baseUrl).`as`("tjeneste-app").isEqualTo("https://somewhere.com/nais-app") }, - { assertThat(annenRestTjeneste.rest.baseUrl).`as`("annen-tjeneste").isEqualTo("https://somewhere.else.com/annen-nais-app") } + { assertThat(annenRestTjeneste.rest.baseUrl).`as`("annen-tjeneste").isEqualTo("https://somewhere.else.com/annen-nais-app") }, ) } @Test fun `gitt INGRESSES_FOR_APPS med verdi for applikasjon (konfigurert som er en tag), skal RestTjeneste konfigureres med tag-navnet`() { - val cucumberTestsModel = CucumberTestsModel( - ingressesForApps = listOf("https://somewhere.com/@nais-tag", "https://somewhere.else.com@annen-nais-tag"), - testUsername = "James Bond" - ) + val cucumberTestsModel = + CucumberTestsModel( + ingressesForApps = listOf("https://somewhere.com/@nais-tag", "https://somewhere.else.com@annen-nais-tag"), + testUsername = "James Bond", + ) cucumberTestsModel.initCucumberEnvironment() @@ -80,7 +80,7 @@ internal class RestTjenesteTest { assertAll( { assertThat(restTjeneste.rest.baseUrl).`as`("tjeneste-app").isEqualTo("https://somewhere.com/nais-tag") }, - { assertThat(annenRestTjeneste.rest.baseUrl).`as`("annen-tjeneste").isEqualTo("https://somewhere.else.com/annen-nais-tag") } + { assertThat(annenRestTjeneste.rest.baseUrl).`as`("annen-tjeneste").isEqualTo("https://somewhere.else.com/annen-nais-tag") }, ) } @@ -89,7 +89,14 @@ internal class RestTjenesteTest { val restTemplateMock: RestTemplate = mockk("RestTemplate") val restTjeneste = RestTjeneste(ResttjenesteMedBaseUrl(restTemplateMock, "https://somewhere")) - every { restTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) } returns ResponseEntity.ok().build() + every { + restTemplateMock.exchange( + any(), + eq(HttpMethod.GET), + any(), + eq(String::class.java), + ) + } returns ResponseEntity.ok().build() restTjeneste.exchangeGet("/out/there") @@ -103,7 +110,9 @@ internal class RestTjenesteTest { val restTemplateMock: RestTemplate = mockk("RestTemplate") val restTjeneste = RestTjeneste(ResttjenesteMedBaseUrl(restTemplateMock, "https://somewhere")) val headers = HttpHeaders(LinkedMultiValueMap(mapOf(HttpHeaders.WARNING to listOf("the truth will emerge!")))) - every { restTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) } returns ResponseEntity.internalServerError().headers(headers).build() + every { + restTemplateMock.exchange(any(), eq(HttpMethod.GET), any(), eq(String::class.java)) + } returns ResponseEntity.internalServerError().headers(headers).build() restTjeneste.exchangeGet("/out/there") diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesterTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesterTest.kt index ddaca01..4b99753 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesterTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/RestTjenesterTest.kt @@ -5,12 +5,11 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll internal class RestTjenesterTest { - @Test fun `skal ikke bruke app navn som del av ingress, når applikasjon konfigureres og det spesifikt oppgies at denne ikke skal bli med`() { CucumberTestsModel( ingressesForApps = listOf("https://outside@this", "https://blow@that", "https://love@you"), - noContextPathForApps = listOf("this", "that") + noContextPathForApps = listOf("this", "that"), ).initCucumberEnvironment() val thisUrl = RestTjenester.konfigurerApplikasjonUrlFor("this") @@ -20,7 +19,7 @@ internal class RestTjenesterTest { assertAll( { assertThat(thisUrl).`as`("this url").isEqualTo("https://outside") }, { assertThat(thatUrl).`as`("that url").isEqualTo("https://blow") }, - { assertThat(youUel).`as`("you url").isEqualTo("https://love/you") } + { assertThat(youUel).`as`("you url").isEqualTo("https://love/you") }, ) } } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/RunStatsTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/RunStatsTest.kt index 6eb2381..8f575a1 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/RunStatsTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/RunStatsTest.kt @@ -6,28 +6,29 @@ import org.junit.jupiter.api.Test @DisplayName("RunStats") internal class RunStatsTest { - private val runStats = RunStats() @Test fun `skal lage feilmeldinger med riktige innrykk`() { - val feilmeldinger = listOf( - "en feil oppstod:", - """ - det var noe skit... - det skal ikke skje igjen - """.trimIndent() - ) + val feilmeldinger = + listOf( + "en feil oppstod:", + """ + det var noe skit... + det skal ikke skje igjen + """.trimIndent(), + ) runStats.addExceptionLogging(feilmeldinger) - val nyeFeilmeldinger = listOf( - """ - svarte... - det skjedde igjen... - """.trimIndent(), - "men nå er det slutt!" - ) + val nyeFeilmeldinger = + listOf( + """ + svarte... + det skjedde igjen... + """.trimIndent(), + "men nå er det slutt!", + ) runStats.addExceptionLogging(nyeFeilmeldinger) val failureDetails = runStats.createStringOfFailureDetails().trim() @@ -40,7 +41,7 @@ internal class RunStatsTest { - svarte... det skjedde igjen... men nå er det slutt! - """.trimIndent().trim() + """.trimIndent().trim(), ) } } diff --git a/src/test/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceTextTest.kt b/src/test/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceTextTest.kt index f3e468e..83c569c 100644 --- a/src/test/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceTextTest.kt +++ b/src/test/kotlin/no/nav/bidrag/cucumber/model/SuppressStackTraceTextTest.kt @@ -4,7 +4,6 @@ import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test internal class SuppressStackTraceTextTest { - private val suppressStackTraceText = SuppressStackTraceText() @Test @@ -29,7 +28,7 @@ ${"\t"}at no.nav.bidrag.cucumber.cloud.FellesEgenskaper._init_(FellesEgenskaper. assertThat(stackedText).isEqualTo( """com.fasterxml.jackson.core.JsonParseException: ${"\t"}at no.nav.bidrag.cucumber.model.RestTjeneste.hentResponseSomMap(RestTjeneste.kt:32) -${"\t"}at no.nav.bidrag.cucumber.cloud.FellesEgenskaper._init_(FellesEgenskaper.kt:41)""" +${"\t"}at no.nav.bidrag.cucumber.cloud.FellesEgenskaper._init_(FellesEgenskaper.kt:41)""", ) } From bedf96ca3e09429be34b3ae1a518dbd3a12d376e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 08:49:39 +0100 Subject: [PATCH 5/6] Endrer til java 21 --- .github/workflows/build-and-deploy.yaml | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-deploy.yaml b/.github/workflows/build-and-deploy.yaml index a57539c..dfe91bd 100644 --- a/.github/workflows/build-and-deploy.yaml +++ b/.github/workflows/build-and-deploy.yaml @@ -21,7 +21,7 @@ jobs: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: - java-version: '17' + java-version: '21' distribution: 'temurin' - uses: actions/cache@v3 with: diff --git a/Dockerfile b/Dockerfile index 899fcf2..a4a0b54 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM navikt/java:17 +FROM ghcr.io/navikt/baseimages/temurin:21 LABEL maintainer="Team Bidrag" \ email="nav.ikt.prosjekt.og.forvaltning.bidrag@nav.no" From 7afb198db58fcca78041c28ce51786f32e7d2c88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simen=20H=C3=B8ston?= Date: Fri, 12 Jan 2024 11:56:17 +0100 Subject: [PATCH 6/6] Fjerner at beregn-barnebidrag og saertilskuff bruker feature --- .github/workflows/build-and-deploy.yaml | 2 -- .nais/feature.yaml | 8 ++++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build-and-deploy.yaml b/.github/workflows/build-and-deploy.yaml index dfe91bd..d358aba 100644 --- a/.github/workflows/build-and-deploy.yaml +++ b/.github/workflows/build-and-deploy.yaml @@ -190,7 +190,6 @@ jobs: - name: feature ingresses if: github.ref != 'refs/heads/main' run: | - echo "INGRESS_BEREGN_SAERTILSKUDD=https://bidrag-beregn-saertilskudd-rest-feature.intern.dev.nav.no" >> $GITHUB_ENV echo "INGRESS_CUCUMBER=https://bidrag-cucumber-cloud-feature.ekstern.dev.nav.no" >> $GITHUB_ENV - run: | curl -H "Content-Type: application/json" -i \ @@ -237,7 +236,6 @@ jobs: - name: feature ingresses if: github.ref != 'refs/heads/main' run: | - echo "INGRESS_BEREGN_BARNEBIDRAG=https://bidrag-beregn-barnebidrag-rest-feature.intern.dev.nav.no" >> $GITHUB_ENV echo "INGRESS_CUCUMBER=https://bidrag-cucumber-cloud-feature.ekstern.dev.nav.no" >> $GITHUB_ENV - run: | curl -H "Content-Type: application/json" -i \ diff --git a/.nais/feature.yaml b/.nais/feature.yaml index c0cd90d..f6bb414 100644 --- a/.nais/feature.yaml +++ b/.nais/feature.yaml @@ -12,16 +12,16 @@ access: grunnlag: bidrag-grunnlag-feature.intern.dev.nav.no vedtak: bidrag-vedtak-feature.intern.dev.nav.no stonad: bidrag-stonad-feature.intern.dev.nav.no - barnebidrag: bidrag-beregn-barnebidrag-feature.intern.dev.nav.no + barnebidrag: bidrag-beregn-barnebidrag.intern.dev.nav.no forskudd: bidrag-beregn-forskudd.intern.dev.nav.no - saertilskudd: bidrag-beregn-saertilskudd-feature.intern.dev.nav.no + saertilskudd: bidrag-beregn-saertilskudd.intern.dev.nav.no kafka-topic-journalpost: bidrag.journalpost-feature scope: oppgave: dev-fss.oppgavehandtering.oppgave-q1 sak: dev-fss.bidrag.bidrag-sak-feature - beregn_saertilskudd: dev-gcp.bidrag.bidrag-beregn-saertilskudd-rest-feature + beregn_saertilskudd: dev-gcp.bidrag.bidrag-beregn-saertilskudd-rest beregn_forskudd: dev-gcp.bidrag.bidrag-beregn-forskudd-rest - beregn_barnebidrag: dev-gcp.bidrag.bidrag-beregn-barnebidrag-rest-feature + beregn_barnebidrag: dev-gcp.bidrag.bidrag-beregn-barnebidrag-rest dokument_forsendelse: dev-gcp.bidrag.bidrag-dokument-forsendelse-feature bidrag_vedtak: dev-gcp.bidrag.bidrag-vedtak-feature bidrag_grunnlag: dev-gcp.bidrag.bidrag-grunnlag-feature