From aa808e4f45262ba98d2d08ab4eb6395be13c4762 Mon Sep 17 00:00:00 2001 From: Craig Atkinson Date: Fri, 12 Apr 2024 08:34:48 -0500 Subject: [PATCH] Updating to Projektor Gradle plugin 9.0.0 and ktlint 1.2.1 --- .editorconfig | 5 + build.gradle | 4 +- gradle/kotlin.gradle | 3 +- .../notification/badge/BuildLabel.kt | 3 +- .../notification/badge/CoverageLevel.kt | 3 +- .../badge/SvgCoverageBadgeCreator.kt | 16 +- .../badge/SvgTestRunBadgeCreator.kt | 27 +- .../badge/SvgCoverageBadgeCreatorSpec.kt | 6 +- .../github/auth/JwtTokenConfig.kt | 2 +- .../github/auth/PrivateKeyEncoder.kt | 6 +- .../github/comment/GitHubCommentClient.kt | 68 +- .../github/comment/GitHubCommentCreator.kt | 71 +- .../github/comment/GitHubCommentService.kt | 42 +- .../github/comment/PullRequest.kt | 2 +- .../github/comment/ReportCommentData.kt | 2 +- .../github/comment/ReportCommentGitData.kt | 2 +- .../comment/ReportCommentPerformanceData.kt | 2 +- .../comment/ReportCoverageCommentData.kt | 2 +- .../github/WireMockTestListener.kt | 5 +- .../github/auth/JwtProviderSpec.kt | 20 +- .../github/auth/PrivateKeyEncoderSpec.kt | 5 +- .../comment/GitHubCommentClientLiveSpec.kt | 29 +- .../github/comment/GitHubCommentClientSpec.kt | 28 +- .../comment/GitHubCommentCreatorSpec.kt | 303 +++--- .../comment/GitHubCommentServiceLiveSpec.kt | 109 ++- .../comment/GitHubCommentServiceSpec.kt | 305 +++--- .../github/GitHubWireMockStubber.kt | 899 ++++++++++-------- .../coverage/CloverCoverageReportParser.kt | 48 +- .../coverage/CoberturaCoverageReportParser.kt | 71 +- .../parser/coverage/CoverageParser.kt | 5 +- .../parser/coverage/CoverageReportParser.kt | 5 +- .../coverage/JacocoCoverageReportParser.kt | 51 +- .../projektor/parser/coverage/MathUtil.kt | 5 +- .../parser/coverage/model/CoverageReport.kt | 2 +- .../coverage/model/CoverageReportFile.kt | 2 +- .../coverage/model/CoverageReportStats.kt | 2 +- .../coverage/model/CoverageReportType.kt | 2 +- .../coverage/payload/CoverageFilePayload.kt | 2 +- .../coverage/payload/CoveragePayloadParser.kt | 13 +- .../parser/coverage/CoverageParserFileSpec.kt | 2 +- .../coverage/model/CoverageReportStatSpec.kt | 4 +- .../performance/PerformanceResultsParser.kt | 20 +- .../k6/K6PerformanceResultsParser.kt | 10 +- .../performance/k6/model/DurationStats.kt | 2 +- .../parser/performance/k6/model/K6Results.kt | 4 +- .../parser/performance/k6/model/Metrics.kt | 2 +- .../performance/k6/model/RequestCounts.kt | 2 +- .../model/PerformanceResultsReport.kt | 2 +- .../performance/model/PerformanceStats.kt | 2 +- .../results/processor/ResultsXmlMerger.kt | 34 +- .../TestResultsCypressProcessorSpec.kt | 10 +- .../processor/TestResultsProcessorSpec.kt | 8 +- .../objectstore/ObjectStoreClient.kt | 45 +- .../objectstore/ObjectCleanupListener.kt | 7 +- .../ObjectStoreClientObjectSpec.kt | 4 +- .../kotlin/projektor/server/api/MathUtil.kt | 5 +- .../kotlin/projektor/server/api/PublicId.kt | 1 - .../projektor/server/api/TestFailure.kt | 2 +- .../projektor/server/api/TestRunSummary.kt | 2 +- .../kotlin/projektor/server/api/TestSuite.kt | 2 +- .../api/attachments/AddAttachmentResponse.kt | 4 +- .../server/api/attachments/Attachment.kt | 11 +- .../server/api/attachments/AttachmentType.kt | 2 +- .../projektor/server/api/coverage/Coverage.kt | 2 +- .../server/api/coverage/CoverageFile.kt | 2 +- .../server/api/coverage/CoverageGroup.kt | 2 +- .../server/api/coverage/CoverageStat.kt | 2 +- .../server/api/coverage/CoverageStats.kt | 2 +- .../server/api/error/FailureBodyType.kt | 2 +- .../api/error/ResultsProcessingFailure.kt | 2 +- .../server/api/metadata/TestRunGitMetadata.kt | 2 +- .../api/organization/RepositoryCoverage.kt | 2 +- .../api/performance/PerformanceResult.kt | 2 +- .../server/api/quality/CodeQualityReport.kt | 2 +- .../server/api/repository/BranchType.kt | 2 +- .../api/repository/RepositoryFlakyTests.kt | 2 +- .../RepositoryTestRunTimelineEntry.kt | 2 +- .../RepositoryCoverageTimelineEntry.kt | 2 +- .../coverage/RepositoryCurrentCoverage.kt | 2 +- .../RepositoryPerformanceTestTimeline.kt | 2 +- .../RepositoryPerformanceTestTimelineEntry.kt | 2 +- .../server/api/results/ResultsProcessing.kt | 2 +- .../api/results/ResultsProcessingStatus.kt | 2 +- .../projektor/server/api/util/DurationUtil.kt | 5 +- .../src/main/kotlin/projektor/AppModule.kt | 2 +- .../src/main/kotlin/projektor/Application.kt | 56 +- .../attachment/AddAttachmentResult.kt | 1 + .../projektor/attachment/AttachmentConfig.kt | 19 +- .../AttachmentDatabaseRepository.kt | 12 +- .../attachment/AttachmentRepository.kt | 10 +- .../projektor/attachment/AttachmentService.kt | 24 +- .../main/kotlin/projektor/auth/AuthConfig.kt | 9 +- .../main/kotlin/projektor/auth/AuthService.kt | 3 +- .../projektor/badge/CoverageBadgeService.kt | 34 +- .../projektor/badge/TestRunBadgeService.kt | 16 +- .../cleanup/AttachmentCleanupService.kt | 14 +- .../kotlin/projektor/cleanup/CleanupConfig.kt | 4 +- .../projektor/cleanup/CleanupScheduledJob.kt | 17 +- .../cleanup/TestRunCleanupService.kt | 14 +- .../PreviousTestRunDatabaseRepository.kt | 118 +-- .../compare/PreviousTestRunRepository.kt | 12 +- .../compare/PreviousTestRunService.kt | 14 +- .../kotlin/projektor/compare/RecentTestRun.kt | 2 +- .../coverage/CoverageDatabaseRepository.kt | 311 +++--- .../coverage/CoverageFileCombiner.kt | 51 +- .../projektor/coverage/CoverageGroupStatus.kt | 2 +- .../projektor/coverage/CoverageMapper.kt | 8 +- .../projektor/coverage/CoverageRepository.kt | 13 +- .../projektor/coverage/CoverageService.kt | 91 +- .../projektor/database/DataSourceConfig.kt | 58 +- .../ProcessingFailureDatabaseRepository.kt | 9 +- .../error/ProcessingFailureRepository.kt | 7 +- .../error/ProcessingFailureService.kt | 10 +- .../AppendTestResultsService.kt | 19 +- .../GroupedResultsConverter.kt | 132 +-- .../GroupedTestResultsService.kt | 78 +- .../PersistTestResultsException.kt | 5 +- .../TestResultsProcessingService.kt | 18 +- .../incomingresults/TestResultsService.kt | 7 +- .../mapper/ParsedResultsToApiMapper.kt | 40 +- .../mapper/ParsedResultsToDBMapper.kt | 23 +- .../incomingresults/model/GitMetadata.kt | 2 +- .../incomingresults/model/GroupedResults.kt | 2 +- .../model/GroupedTestSuites.kt | 2 +- .../model/PerformanceResult.kt | 5 +- .../incomingresults/model/ResultsMetadata.kt | 2 +- .../ResultsProcessingDatabaseRepository.kt | 52 +- .../processing/ResultsProcessingRepository.kt | 11 +- .../logging/TimeMillisJsonLoggingProvider.kt | 5 +- .../kotlin/projektor/message/MessageConfig.kt | 1 - .../projektor/message/MessageService.kt | 1 - .../TestRunMetadataDatabaseRepository.kt | 6 +- .../metadata/TestRunMetadataRepository.kt | 6 +- .../metadata/TestRunMetadataService.kt | 6 +- .../kotlin/projektor/metrics/InfluxMetrics.kt | 37 +- .../projektor/metrics/InfluxMetricsConfig.kt | 23 +- .../projektor/metrics/MetricsService.kt | 7 + .../github/GitHubNotificationConfig.kt | 4 +- .../github/GitHubPullRequestCommentService.kt | 74 +- .../OrganizationCoverageDatabaseRepository.kt | 57 +- .../coverage/OrganizationCoverageService.kt | 46 +- .../PerformanceResultsDatabaseRepository.kt | 2 +- .../PerformanceResultsRepository.kt | 2 +- .../performance/PerformanceResultsService.kt | 3 +- .../projektor/processing/ProcessingConfig.kt | 5 +- .../CodeQualityReportDatabaseRepository.kt | 28 +- .../quality/CodeQualityReportRepository.kt | 6 +- .../RepositoryCoverageDatabaseRepository.kt | 89 +- .../coverage/RepositoryCoverageRepository.kt | 11 +- .../coverage/RepositoryCoverageService.kt | 34 +- ...RepositoryPerformanceDatabaseRepository.kt | 58 +- .../RepositoryPerformanceRepository.kt | 5 +- .../RepositoryPerformanceService.kt | 12 +- .../repository/testrun/FlakyTestCalculator.kt | 38 +- .../RepositoryTestRunDatabaseRepository.kt | 164 ++-- .../testrun/RepositoryTestRunRepository.kt | 29 +- .../testrun/RepositoryTestRunService.kt | 15 +- .../main/kotlin/projektor/route/ApiRoutes.kt | 43 +- .../projektor/route/AttachmentRoutes.kt | 25 +- .../projektor/route/CodeQualityRoutes.kt | 4 +- .../projektor/route/CompressionRequest.kt | 11 +- .../kotlin/projektor/route/ConfigRoutes.kt | 6 +- .../kotlin/projektor/route/CoverageRoutes.kt | 9 +- .../kotlin/projektor/route/MetadataRoutes.kt | 2 +- .../route/RepositoryCoverageRoutes.kt | 19 +- .../projektor/route/RepositoryRoutes.kt | 49 +- .../kotlin/projektor/route/ResultsRoutes.kt | 6 +- .../kotlin/projektor/route/SvgRouteUtils.kt | 5 +- .../kotlin/projektor/schedule/Scheduler.kt | 7 +- .../projektor/schedule/SchedulerLock.kt | 5 +- .../projektor/telemetry/OpenTelemetryRoute.kt | 6 +- .../CypressScreenshotAttachmentMatcher.kt | 5 +- .../testcase/CypressVideoAttachmentMatcher.kt | 5 +- .../testcase/TestCaseAttachmentMatcher.kt | 5 +- .../testcase/TestCaseDatabaseRepository.kt | 102 +- .../projektor/testcase/TestCaseRepository.kt | 24 +- .../projektor/testcase/TestCaseService.kt | 58 +- .../testrun/TestRunDatabaseRepository.kt | 203 ++-- .../projektor/testrun/TestRunRepository.kt | 33 +- .../projektor/testrun/TestRunService.kt | 7 +- ...stRunSystemAttributesDatabaseRepository.kt | 12 +- .../testsuite/TestSuiteDatabaseRepository.kt | 96 +- .../testsuite/TestSuiteRepository.kt | 21 +- .../projektor/testsuite/TestSuiteService.kt | 24 +- .../main/kotlin/projektor/util/GzipUtil.kt | 3 +- .../main/kotlin/projektor/util/MathUtil.kt | 1 - .../versioncontrol/VersionControlConfig.kt | 4 +- .../kotlin/projektor/ApplicationTestCase.kt | 61 +- .../projektor/DatabaseRepositoryTestCase.kt | 91 +- .../kotlin/projektor/TestRunDBGenerator.kt | 212 +++-- .../api/ApiOrganizationApplicationTest.kt | 19 +- .../api/ApiRepositoryApplicationTest.kt | 40 +- .../ApiRepositoryFlakyTestsApplicationTest.kt | 178 ++-- .../AddAttachmentApplicationTest.kt | 8 +- .../AddAttachmentMaxSizeApplicationTest.kt | 12 +- .../AddAttachmentTokenApplicationTest.kt | 17 +- .../AttachmentDatabaseRepositoryTest.kt | 1 - .../ListAttachmentsApplicationTest.kt | 6 +- .../RepositoryCoverageBadgeApplicationTest.kt | 12 +- ...toryTestRunPassFailBadgeApplicationTest.kt | 12 +- .../TestRunCoverageBadgeApplicationTest.kt | 2 +- .../cleanup/AttachmentCleanupServiceTest.kt | 23 +- .../projektor/cleanup/CleanupJobTest.kt | 15 +- .../CleanupSchedulerApplicationTest.kt | 6 +- .../cleanup/TestRunCleanupServiceTest.kt | 179 ++-- .../compare/PreviousTestRunServiceTest.kt | 121 ++- ...ddCoverageFileCompressedApplicationTest.kt | 13 +- .../ComparePreviousCoverageApplicationTest.kt | 9 +- .../CoverageDatabaseRepositoryTest.kt | 199 ++-- .../coverage/CoverageExistsApplicationTest.kt | 1 - .../coverage/CoverageFileCombinerTest.kt | 78 +- .../projektor/coverage/CoverageServiceTest.kt | 33 +- .../GetCoverageReportStatsApplicationTest.kt | 1 - .../SaveCoberturaCoverageApplicationTest.kt | 19 +- .../error/ProcessingFailureApplicationTest.kt | 5 +- ...ProcessingFailureDatabaseRepositoryTest.kt | 18 +- .../AppendCoverageApplicationTest.kt | 38 +- .../AppendGroupedResultsApplicationTest.kt | 1 - .../CypressResultsApplicationTest.kt | 11 +- ...pressResultsWithFileNameApplicationTest.kt | 11 +- .../GroupedTestResultsServiceTest.kt | 1 - .../SaveGroupedResultsApplicationTest.kt | 1 - ...roupedResultsCodeQualityApplicationTest.kt | 14 +- .../SaveGroupedResultsGitRepositoryTest.kt | 1 - ...aveGroupedResultsMetricsApplicationTest.kt | 1 - ...eGroupedResultsTelemetryApplicationTest.kt | 1 - ...oupedResultsWithCoverageApplicationTest.kt | 1 - ...thCoveragePartialFailureApplicationTest.kt | 6 +- ...oupedResultsWithMetadataApplicationTest.kt | 1 - ...tadataPullRequestCommentApplicationTest.kt | 9 +- ...ultsWithMultipleCoverageApplicationTest.kt | 24 +- .../SaveResultsApplicationTest.kt | 1 - .../SaveGroupedResultsTokenApplicationTest.kt | 4 +- .../auth/SaveResultsTokenApplicationTest.kt | 4 +- .../mapper/PackageClassNameParserSpec.kt | 14 +- ...ResultsProcessingDatabaseRepositoryTest.kt | 21 +- .../message/MessageApplicationTest.kt | 1 - .../metrics/MetricsApplicationTest.kt | 5 +- .../projektor/metrics/MetricsStubber.kt | 19 +- ...GitHubPullRequestCommentApplicationTest.kt | 7 +- .../OrganizationCoverageApplicationTest.kt | 22 +- .../GetPerformanceResultsApplicationTest.kt | 34 +- ...erformanceResultsDatabaseRepositoryTest.kt | 20 +- .../SavePerformanceResultsApplicationTest.kt | 9 +- .../CodeQualityReportApplicationTest.kt | 22 +- ...epositoryCoverageCurrentApplicationTest.kt | 30 +- ...RepositoryCoverageExistsApplicationTest.kt | 24 +- ...positoryCoverageTimelineApplicationTest.kt | 53 +- ...sitoryPerformanceDatabaseRepositoryTest.kt | 18 +- ...itoryPerformanceTimelineApplicationTest.kt | 159 ++-- .../testrun/FlakyTestCalculatorTest.kt | 166 ++-- .../RepositoryFlakyTestApplicationTest.kt | 333 ++++--- ...stRunDatabaseRepositoryFailingCasesTest.kt | 298 +++--- ...TestRunDatabaseRepositoryRecentRunsTest.kt | 1 - ...ryTestRunDatabaseRepositoryTimelineTest.kt | 1 - .../projektor/schedule/SchedulerTest.kt | 17 +- .../telemetry/OpenTelemetryApplicationTest.kt | 7 +- .../GetFailedTestCasesApplicationTest.kt | 10 +- ...iledTestCasesAttachmentsApplicationTest.kt | 9 +- .../GetSlowTestCasesApplicationTest.kt | 2 +- .../testcase/GetTestCaseApplicationTest.kt | 8 +- .../TestCaseDatabaseRepositoryTest.kt | 10 +- .../testrun/GetTestRunApplicationTest.kt | 46 +- .../GetTestRunCompressionApplicationTest.kt | 4 +- .../GetTestRunSummaryApplicationTest.kt | 23 +- .../TestRunSystemAttributesApplicationTest.kt | 6 +- ...nSystemAttributesDatabaseRepositoryTest.kt | 1 - .../TestRunDatabaseRepositoryAppendTest.kt | 75 +- .../TestRunDatabaseRepositoryDeleteTest.kt | 35 +- .../TestRunDatabaseRepositoryFetchRunTest.kt | 9 +- ...stRunDatabaseRepositoryFetchSummaryTest.kt | 1 - ...atabaseRepositorySaveGroupedResultsTest.kt | 40 +- ...estRunDatabaseRepositorySaveResultsTest.kt | 1 - .../testsuite/GetTestSuiteApplicationTest.kt | 48 +- .../GetTestSuiteSystemErrApplicationTest.kt | 6 +- .../GetTestSuiteSystemOutApplicationTest.kt | 6 +- .../TestSuiteDatabaseRepositoryAppendTest.kt | 9 +- ...atabaseRepositoryFetchGroupedSuitesTest.kt | 32 +- ...tSuiteDatabaseRepositoryFetchOutputTest.kt | 15 +- ...stSuiteDatabaseRepositoryFetchSuiteTest.kt | 39 +- ...tSuiteDatabaseRepositoryFetchSuitesTest.kt | 34 +- .../server/client/ProjektorAttachmentsApi.kt | 9 +- .../server/client/ProjektorClientBuilder.kt | 17 +- .../server/client/ProjektorTestRunApi.kt | 55 +- .../client/ProjektorTestRunMetadataApi.kt | 4 +- .../example/coverage/CloverXmlLoader.kt | 6 + .../example/coverage/CoberturaXmlLoader.kt | 2 +- .../example/coverage/CoverageFileWrapper.kt | 9 +- .../example/coverage/CoverageXmlLoader.kt | 9 +- .../example/coverage/JacocoXmlLoader.kt | 6 + .../performance/PerformanceResultsLoader.kt | 9 +- .../projektor/server/example/ExampleLoader.kt | 390 +++++--- .../parser/GroupedResultsXmlLoader.kt | 55 +- .../projektor/parser/ResultsXmlLoader.kt | 48 +- 294 files changed, 5245 insertions(+), 3967 deletions(-) create mode 100644 .editorconfig delete mode 100644 server/server-app/src/main/kotlin/projektor/util/MathUtil.kt diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..0a4416202 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,5 @@ +[*.{kt,kts}] +ktlint_code_style = ktlint_official +ktlint_standard_no-wildcard-imports = disabled +ktlint_standard_max-line-length = disabled + diff --git a/build.gradle b/build.gradle index 7a9d4623f..7758e85dc 100644 --- a/build.gradle +++ b/build.gradle @@ -6,12 +6,12 @@ buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath "org.jlleitschuh.gradle:ktlint-gradle:11.6.1" + classpath "org.jlleitschuh.gradle:ktlint-gradle:12.1.0" } } plugins { - id "dev.projektor.publish" version "8.7.0" + id "dev.projektor.publish" version "9.0.0" id "com.atkinsondev.opentelemetry-build" version "1.10.0" id 'com.github.psxpaul.execfork' version '0.2.2' apply false } diff --git a/gradle/kotlin.gradle b/gradle/kotlin.gradle index 2573ccd4e..f2198f9ef 100644 --- a/gradle/kotlin.gradle +++ b/gradle/kotlin.gradle @@ -24,8 +24,7 @@ test { } ktlint { - version = "0.42.1" - disabledRules = ["no-wildcard-imports"] + version = "1.2.1" reporters { reporter "plain?group_by_file" } diff --git a/server/notification/badge/src/main/kotlin/projektor/notification/badge/BuildLabel.kt b/server/notification/badge/src/main/kotlin/projektor/notification/badge/BuildLabel.kt index 6615d3fce..8ed66c8a5 100644 --- a/server/notification/badge/src/main/kotlin/projektor/notification/badge/BuildLabel.kt +++ b/server/notification/badge/src/main/kotlin/projektor/notification/badge/BuildLabel.kt @@ -2,7 +2,8 @@ package projektor.notification.badge enum class BuildLabel(val fillColor: String) { PASS("#4c1"), - FAIL("#e05d44"); + FAIL("#e05d44"), + ; companion object { fun of(testRunPassed: Boolean): BuildLabel = diff --git a/server/notification/badge/src/main/kotlin/projektor/notification/badge/CoverageLevel.kt b/server/notification/badge/src/main/kotlin/projektor/notification/badge/CoverageLevel.kt index 77386e6c7..0567438ce 100644 --- a/server/notification/badge/src/main/kotlin/projektor/notification/badge/CoverageLevel.kt +++ b/server/notification/badge/src/main/kotlin/projektor/notification/badge/CoverageLevel.kt @@ -6,7 +6,8 @@ enum class CoverageLevel(val fillColor: String) { GOOD("#4c1"), OK("#dfb317"), POOR("#fe7d37"), - TERRIBLE("#e05d44"); + TERRIBLE("#e05d44"), + ; companion object { fun of(coveredPercentage: BigDecimal): CoverageLevel = diff --git a/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgCoverageBadgeCreator.kt b/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgCoverageBadgeCreator.kt index 00a9e1b91..4261c7573 100644 --- a/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgCoverageBadgeCreator.kt +++ b/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgCoverageBadgeCreator.kt @@ -16,15 +16,17 @@ class SvgCoverageBadgeCreator(templateFileName: String = "coverage.template.svg" val fillColor = coverageLevel.fillColor val roundedCoveredPercentage = coveredPercentage.setScale(0, RoundingMode.HALF_UP) - val svgText = svgTemplate - .replace("{coveredPercentage}", roundedCoveredPercentage.toPlainString()) - .replace("{fillColor}", fillColor) + val svgText = + svgTemplate + .replace("{coveredPercentage}", roundedCoveredPercentage.toPlainString()) + .replace("{fillColor}", fillColor) return svgText } - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgTestRunBadgeCreator.kt b/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgTestRunBadgeCreator.kt index 4057f074a..abeed0e2b 100644 --- a/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgTestRunBadgeCreator.kt +++ b/server/notification/badge/src/main/kotlin/projektor/notification/badge/SvgTestRunBadgeCreator.kt @@ -11,21 +11,24 @@ class SvgTestRunBadgeCreator(templateFileName: String = "test_run.template.svg") val buildLabel = BuildLabel.of(testRunPassed) val fillColor = buildLabel.fillColor - val displayText = if (testRunPassed) { - "passing" - } else { - "failing" - } + val displayText = + if (testRunPassed) { + "passing" + } else { + "failing" + } - val svgText = svgTemplate - .replace("{displayText}", displayText) - .replace("{fillColor}", fillColor) + val svgText = + svgTemplate + .replace("{displayText}", displayText) + .replace("{fillColor}", fillColor) return svgText } - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/notification/badge/src/test/kotlin/projektor/notification/badge/SvgCoverageBadgeCreatorSpec.kt b/server/notification/badge/src/test/kotlin/projektor/notification/badge/SvgCoverageBadgeCreatorSpec.kt index 744cafbcb..682bceb0f 100644 --- a/server/notification/badge/src/test/kotlin/projektor/notification/badge/SvgCoverageBadgeCreatorSpec.kt +++ b/server/notification/badge/src/test/kotlin/projektor/notification/badge/SvgCoverageBadgeCreatorSpec.kt @@ -13,14 +13,16 @@ class SvgCoverageBadgeCreatorSpec : StringSpec() { row(BigDecimal("90.25"), "90%", CoverageLevel.GOOD.fillColor), row(BigDecimal("95.75"), "96%", CoverageLevel.GOOD.fillColor), row(BigDecimal("100.00"), "100%", CoverageLevel.GOOD.fillColor), - row(BigDecimal("0.00"), "0%", CoverageLevel.TERRIBLE.fillColor) + row(BigDecimal("0.00"), "0%", CoverageLevel.TERRIBLE.fillColor), ) { coveredPercentage, expectedBadgePercentage, expectedFillColor -> "should create coverage badge for covered percentage $coveredPercentage" { val svgCoverageBadgeCreator = SvgCoverageBadgeCreator("coverage.template.test") val badge = svgCoverageBadgeCreator.createBadge(coveredPercentage) - expectThat(badge).isEqualTo("$expectedBadgePercentage$expectedFillColor") + expectThat( + badge, + ).isEqualTo("$expectedBadgePercentage$expectedFillColor") } } } diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/auth/JwtTokenConfig.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/auth/JwtTokenConfig.kt index 30b6f5902..7f2614354 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/auth/JwtTokenConfig.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/auth/JwtTokenConfig.kt @@ -3,5 +3,5 @@ package projektor.notification.github.auth data class JwtTokenConfig( val gitHubAppId: String, val pemContents: String, - val ttlMillis: Long + val ttlMillis: Long, ) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/auth/PrivateKeyEncoder.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/auth/PrivateKeyEncoder.kt index fd0bc7b48..f1300d30f 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/auth/PrivateKeyEncoder.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/auth/PrivateKeyEncoder.kt @@ -3,9 +3,7 @@ package projektor.notification.github.auth import java.util.Base64 object PrivateKeyEncoder { - fun base64Encode(keyContents: String): String = - Base64.getEncoder().encodeToString(keyContents.toByteArray()) + fun base64Encode(keyContents: String): String = Base64.getEncoder().encodeToString(keyContents.toByteArray()) - fun base64Decode(encodedKeyContents: String): String = - String(Base64.getDecoder().decode(encodedKeyContents)) + fun base64Decode(encodedKeyContents: String): String = String(Base64.getDecoder().decode(encodedKeyContents)) } diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentClient.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentClient.kt index 8bf47844e..bf6671bc5 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentClient.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentClient.kt @@ -11,16 +11,24 @@ import projektor.notification.github.auth.JwtProvider class GitHubCommentClient( private val clientConfig: GitHubClientConfig, - private val jwtProvider: JwtProvider + private val jwtProvider: JwtProvider, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) - fun addComment(repository: GHRepository, issueId: Int, commentText: String) { + fun addComment( + repository: GHRepository, + issueId: Int, + commentText: String, + ) { val ghIssue = repository.getIssue(issueId) ghIssue.comment(commentText) } - fun findCommentWithText(repository: GHRepository, issueId: Int, commentText: String): GHIssueComment? { + fun findCommentWithText( + repository: GHRepository, + issueId: Int, + commentText: String, + ): GHIssueComment? { val ghIssue = repository.getIssue(issueId) val comments = ghIssue.listComments().toList() @@ -28,21 +36,30 @@ class GitHubCommentClient( return comments.find { it.body.contains(commentText) } } - fun updateComment(comment: GHIssueComment, newText: String) { + fun updateComment( + comment: GHIssueComment, + newText: String, + ) { comment.update(newText) } - fun findOpenPullRequests(repository: GHRepository, branchName: String?, commitSha: String?): Int? { - val pullRequestsResults = repository - .queryPullRequests() - .state(GHIssueState.OPEN) - .list() - .toList() + fun findOpenPullRequests( + repository: GHRepository, + branchName: String?, + commitSha: String?, + ): Int? { + val pullRequestsResults = + repository + .queryPullRequests() + .state(GHIssueState.OPEN) + .list() + .toList() - val pullRequestForBranch = branchName?.let { - pullRequestsResults - .firstOrNull { it.head.ref.endsWith(branchName) } - } + val pullRequestForBranch = + branchName?.let { + pullRequestsResults + .firstOrNull { it.head.ref.endsWith(branchName) } + } return if (pullRequestForBranch != null) { pullRequestForBranch.number @@ -53,21 +70,26 @@ class GitHubCommentClient( } } - fun getRepository(orgName: String, repoName: String): GHRepository? { + fun getRepository( + orgName: String, + repoName: String, + ): GHRepository? { val jwtToken = jwtProvider.createJWT() - val gitHub = GitHubBuilder() - .withJwtToken(jwtToken) - .withEndpoint(this.clientConfig.gitHubApiUrl) - .build() + val gitHub = + GitHubBuilder() + .withJwtToken(jwtToken) + .withEndpoint(this.clientConfig.gitHubApiUrl) + .build() val gitHubApp = gitHub.app return try { val appInstallation = gitHubApp.getInstallationByRepository(orgName, repoName) val appInstallationToken = appInstallation.createToken().create() - val githubAuthAsInst = GitHubBuilder() - .withAppInstallationToken(appInstallationToken.token) - .withEndpoint(this.clientConfig.gitHubApiUrl) - .build() + val githubAuthAsInst = + GitHubBuilder() + .withAppInstallationToken(appInstallationToken.token) + .withEndpoint(this.clientConfig.gitHubApiUrl) + .build() val repository = githubAuthAsInst.getRepository("$orgName/$repoName") repository diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentCreator.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentCreator.kt index 05a84df5c..a675fed00 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentCreator.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentCreator.kt @@ -5,11 +5,14 @@ import java.math.RoundingMode import java.time.format.DateTimeFormatter object GitHubCommentCreator { - const val headerText = "Projektor reports" + const val HEADER_TEXT = "Projektor reports" private val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm a") - fun appendComment(existingComment: String, report: ReportCommentData): String { + fun appendComment( + existingComment: String, + report: ReportCommentData, + ): String { return existingComment + "\n" + createReportTableRow(report) } @@ -19,21 +22,37 @@ object GitHubCommentCreator { private fun createReportTableHeader(): String { return """ -**$headerText** +**$HEADER_TEXT** | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | - """.trimIndent().trim() + """.trimIndent().trim() } private fun createReportTableRow(report: ReportCommentData): String { val resultText = if (report.passed) "Passed" else "Failed" - return "| [Projektor report](${createReportLink(report, "")}) | $resultText | ${createTestsCellValue(report)} | ${createCoverageCellValue(report)} | ${report.project ?: ""} | ${dateFormatter.format(report.createdDate)} UTC |" + return "| [Projektor report](${createReportLink( + report, + "", + )}) | $resultText | ${createTestsCellValue( + report, + )} | ${createCoverageCellValue(report)} | ${report.project ?: ""} | ${dateFormatter.format(report.createdDate)} UTC |" } - private fun createReportLink(report: ReportCommentData, uri: String): String { - val baseUrl = if (report.projektorServerBaseUrl.endsWith("/")) report.projektorServerBaseUrl else "${report.projektorServerBaseUrl}/" + private fun createReportLink( + report: ReportCommentData, + uri: String, + ): String { + val baseUrl = + if (report.projektorServerBaseUrl.endsWith( + "/", + ) + ) { + report.projektorServerBaseUrl + } else { + "${report.projektorServerBaseUrl}/" + } return "${baseUrl}tests/${report.publicId}/$uri" } @@ -44,7 +63,10 @@ object GitHubCommentCreator { return when { !performanceData.isNullOrEmpty() -> "[${createPerformanceCellValue(performanceData)}](${createReportLink(report, "")})" report.passed -> "[${report.totalTestCount} total](${createReportLink(report, "all")})" - else -> "[${report.failedTestCount} failed](${createReportLink(report, "failed")}) / [${report.totalTestCount} total](${createReportLink(report, "all")})" + else -> "[${report.failedTestCount} failed](${createReportLink( + report, + "failed", + )}) / [${report.totalTestCount} total](${createReportLink(report, "all")})" } } @@ -58,7 +80,10 @@ object GitHubCommentCreator { } private fun createPerformanceRow(performanceData: ReportCommentPerformanceData) = - "p95: ${performanceData.p95.setScale(0, RoundingMode.HALF_UP)} ms, RPS: ${performanceData.requestsPerSecond.setScale(0, RoundingMode.HALF_UP)}" + "p95: ${performanceData.p95.setScale( + 0, + RoundingMode.HALF_UP, + )} ms, RPS: ${performanceData.requestsPerSecond.setScale(0, RoundingMode.HALF_UP)}" private fun createCoverageCellValue(report: ReportCommentData): String { val coverage = report.coverage @@ -66,21 +91,23 @@ object GitHubCommentCreator { return if (coverage != null) { val (lineCoveredPercentage, lineCoverageDelta) = report.coverage - val deltaString = if (lineCoverageDelta != null) { - when { - lineCoverageDelta > BigDecimal.ZERO -> "(+$lineCoverageDelta%)" - lineCoverageDelta < BigDecimal.ZERO -> "($lineCoverageDelta%)" - else -> null + val deltaString = + if (lineCoverageDelta != null) { + when { + lineCoverageDelta > BigDecimal.ZERO -> "(+$lineCoverageDelta%)" + lineCoverageDelta < BigDecimal.ZERO -> "($lineCoverageDelta%)" + else -> null + } + } else { + null } - } else { - null - } - val displayValue = if (deltaString != null) { - "$lineCoveredPercentage% $deltaString" - } else { - "$lineCoveredPercentage%" - } + val displayValue = + if (deltaString != null) { + "$lineCoveredPercentage% $deltaString" + } else { + "$lineCoveredPercentage%" + } "[$displayValue](${createReportLink(report, "coverage")})" } else { diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentService.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentService.kt index 412d7ab2e..0227ca96e 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentService.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/GitHubCommentService.kt @@ -8,32 +8,42 @@ import projektor.notification.github.comment.GitHubCommentCreator.createComment class GitHubCommentService(private val commentClient: GitHubCommentClient) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) - fun upsertReportComment(commentData: ReportCommentData, publicId: String): PullRequest? { + fun upsertReportComment( + commentData: ReportCommentData, + publicId: String, + ): PullRequest? { val (orgName, repoName, branchName, commitSha, pullRequestNumber) = commentData.git val repository = commentClient.getRepository(orgName, repoName) return if (repository != null) { - logger.info("Searching for pull request with pull request number $pullRequestNumber branch name $branchName or Git commit SHA $commitSha in repo $orgName/$repoName for public ID $publicId") + logger.info( + "Searching for pull request with pull request number $pullRequestNumber branch name $branchName or Git commit SHA $commitSha in repo $orgName/$repoName for public ID $publicId", + ) - val prNumber = if (pullRequestNumber != null) { - pullRequestNumber - } else if (branchName != null || commitSha != null) { - commentClient.findOpenPullRequests(repository, branchName, commitSha) - } else { - logger.info("Need branch name or pull request number to find pull request in repo $orgName/$repoName for public ID $publicId") - null - } + val prNumber = + if (pullRequestNumber != null) { + pullRequestNumber + } else if (branchName != null || commitSha != null) { + commentClient.findOpenPullRequests(repository, branchName, commitSha) + } else { + logger.info( + "Need branch name or pull request number to find pull request in repo $orgName/$repoName for public ID $publicId", + ) + null + } if (prNumber != null) { upsertComment(repository, prNumber, commentData) PullRequest( orgName = orgName, repoName = repoName, - number = prNumber + number = prNumber, ) } else { - logger.info("Could not find pull request for branch $branchName or commit SHA $commitSha in repo $orgName/$repoName for public ID $publicId") + logger.info( + "Could not find pull request for branch $branchName or commit SHA $commitSha in repo $orgName/$repoName for public ID $publicId", + ) null } } else { @@ -41,8 +51,12 @@ class GitHubCommentService(private val commentClient: GitHubCommentClient) { } } - private fun upsertComment(repository: GHRepository, pullRequestNumber: Int, commentData: ReportCommentData) { - val existingComment = commentClient.findCommentWithText(repository, pullRequestNumber, GitHubCommentCreator.headerText) + private fun upsertComment( + repository: GHRepository, + pullRequestNumber: Int, + commentData: ReportCommentData, + ) { + val existingComment = commentClient.findCommentWithText(repository, pullRequestNumber, GitHubCommentCreator.HEADER_TEXT) if (existingComment != null) { val updatedCommentText = appendComment(existingComment.body, commentData) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/PullRequest.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/PullRequest.kt index e8622ee76..d30409173 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/PullRequest.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/PullRequest.kt @@ -3,5 +3,5 @@ package projektor.notification.github.comment data class PullRequest( val orgName: String, val repoName: String, - val number: Int + val number: Int, ) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentData.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentData.kt index b27d200f3..deef78e7d 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentData.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentData.kt @@ -12,5 +12,5 @@ data class ReportCommentData( val totalTestCount: Int, val coverage: ReportCoverageCommentData?, val performance: List?, - val project: String? + val project: String?, ) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentGitData.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentGitData.kt index fa4f4e008..5a5e8eed8 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentGitData.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentGitData.kt @@ -5,5 +5,5 @@ data class ReportCommentGitData( val repoName: String, val branchName: String?, val commitSha: String? = null, - val pullRequestNumber: Int? = null + val pullRequestNumber: Int? = null, ) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentPerformanceData.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentPerformanceData.kt index dba693a46..3d95a71a6 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentPerformanceData.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCommentPerformanceData.kt @@ -5,5 +5,5 @@ import java.math.BigDecimal data class ReportCommentPerformanceData( val name: String, val requestsPerSecond: BigDecimal, - val p95: BigDecimal + val p95: BigDecimal, ) diff --git a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCoverageCommentData.kt b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCoverageCommentData.kt index 578be2a85..daa56fce8 100644 --- a/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCoverageCommentData.kt +++ b/server/notification/github/src/main/kotlin/projektor/notification/github/comment/ReportCoverageCommentData.kt @@ -4,5 +4,5 @@ import java.math.BigDecimal data class ReportCoverageCommentData( val lineCoveredPercentage: BigDecimal, - val lineCoverageDelta: BigDecimal? + val lineCoverageDelta: BigDecimal?, ) diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/WireMockTestListener.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/WireMockTestListener.kt index 76961dc3c..f8ce00adc 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/WireMockTestListener.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/WireMockTestListener.kt @@ -14,7 +14,10 @@ class WireMockTestListener(private val wireMockServer: WireMockServer) : TestLis wireMockServer.resetAll() } - override suspend fun afterTest(testCase: TestCase, result: TestResult) { + override suspend fun afterTest( + testCase: TestCase, + result: TestResult, + ) { wireMockServer.stop() } } diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/auth/JwtProviderSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/auth/JwtProviderSpec.kt index b009a8914..08e144bfc 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/auth/JwtProviderSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/auth/JwtProviderSpec.kt @@ -8,11 +8,12 @@ import strikt.assertions.isNotNull class JwtProviderSpec : StringSpec() { init { "should create JWT from private key" { - val jwtTokenConfig = JwtTokenConfig( - gitHubAppId = "12345", - pemContents = loadTextFromFile("fake_private_key.txt"), - ttlMillis = 60_000 - ) + val jwtTokenConfig = + JwtTokenConfig( + gitHubAppId = "12345", + pemContents = loadTextFromFile("fake_private_key.txt"), + ttlMillis = 60_000, + ) val jwtProvider = JwtProvider(jwtTokenConfig) @@ -23,8 +24,9 @@ class JwtProviderSpec : StringSpec() { } } - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/auth/PrivateKeyEncoderSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/auth/PrivateKeyEncoderSpec.kt index f6621c937..eac9672b3 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/auth/PrivateKeyEncoderSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/auth/PrivateKeyEncoderSpec.kt @@ -7,12 +7,13 @@ import strikt.assertions.isEqualTo class PrivateKeyEncoderSpec : StringSpec() { init { "should encode and decode back to the same value" { - val keyContents = """ + val keyContents = + """ -----BEGIN RSA PRIVATE KEY----- 12345 67890 -----END RSA PRIVATE KEY----- - """.trimIndent() + """.trimIndent() val encodedKey = PrivateKeyEncoder.base64Encode(keyContents) val decodedKey = PrivateKeyEncoder.base64Decode(encodedKey) diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientLiveSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientLiveSpec.kt index c7722b829..cb05fb825 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientLiveSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientLiveSpec.kt @@ -18,15 +18,17 @@ class GitHubCommentClientLiveSpec : StringSpec() { private val gitHubAppId = "91621" private val gitHubApiUrl = "https://api.github.com" - private val clientConfig = GitHubClientConfig( - gitHubApiUrl = gitHubApiUrl - ) - - private val jwtTokenConfig = JwtTokenConfig( - gitHubAppId = gitHubAppId, - pemContents = keyContents, - ttlMillis = ttl - ) + private val clientConfig = + GitHubClientConfig( + gitHubApiUrl = gitHubApiUrl, + ) + + private val jwtTokenConfig = + JwtTokenConfig( + gitHubAppId = gitHubAppId, + pemContents = keyContents, + ttlMillis = ttl, + ) private val jwtCreator = JwtProvider(jwtTokenConfig) @@ -104,8 +106,9 @@ class GitHubCommentClientLiveSpec : StringSpec() { } } - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientSpec.kt index 501b66ff6..5ffec978c 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentClientSpec.kt @@ -27,9 +27,10 @@ class GitHubCommentClientSpec : StringSpec() { init { "should create comment on issue" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val gitHubCommentClient = GitHubCommentClient(clientConfig, jwtProvider) val orgName = "my-org" @@ -55,9 +56,10 @@ class GitHubCommentClientSpec : StringSpec() { "should return null when trying to get repository that does not have app enabled" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val gitHubCommentClient = GitHubCommentClient(clientConfig, jwtProvider) val orgName = "my-org" @@ -72,9 +74,10 @@ class GitHubCommentClientSpec : StringSpec() { "when open PR exists for branch should find the PR number" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val gitHubCommentClient = GitHubCommentClient(clientConfig, jwtProvider) val orgName = "my-org" @@ -93,9 +96,10 @@ class GitHubCommentClientSpec : StringSpec() { "when no open PR for branch should return null for PR number" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val gitHubCommentClient = GitHubCommentClient(clientConfig, jwtProvider) val orgName = "my-org" diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentCreatorSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentCreatorSpec.kt index 10ab27384..a3a4e64cf 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentCreatorSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentCreatorSpec.kt @@ -16,25 +16,28 @@ class GitHubCommentCreatorSpec : StringSpec() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")) "should create comment for passing build without project or coverage" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) val commentText = GitHubCommentCreator.createComment(report) @@ -45,30 +48,33 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Passed | [25 total](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/all) | | | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } "should create comment for passing build with project" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = "my-project" - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = "my-project", + ) val commentText = GitHubCommentCreator.createComment(report) @@ -79,30 +85,33 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Passed | [25 total](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/all) | | my-project | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } "should create comment for failing build" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = false, - failedTestCount = 5, - totalTestCount = 30, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = false, + failedTestCount = 5, + totalTestCount = 30, + coverage = null, + performance = null, + project = null, + ) val commentText = GitHubCommentCreator.createComment(report) @@ -113,38 +122,42 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Failed | [5 failed](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/failed) / [30 total](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/all) | | | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } forAll( row(BigDecimal("91.05"), BigDecimal("2.41"), "91.05% (+2.41%)"), row(BigDecimal("82.15"), BigDecimal("-5.25"), "82.15% (-5.25%)"), - row(BigDecimal("83.43"), null, "83.43%") + row(BigDecimal("83.43"), null, "83.43%"), ) { coveredPercentage, coverageDelta, expectedCoverageCell -> "should create comment for build with coverage $coveredPercentage and delta $coverageDelta" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = ReportCoverageCommentData( - lineCoveredPercentage = coveredPercentage, - lineCoverageDelta = coverageDelta - ), - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = + ReportCoverageCommentData( + lineCoveredPercentage = coveredPercentage, + lineCoverageDelta = coverageDelta, + ), + performance = null, + project = null, + ) val commentText = GitHubCommentCreator.createComment(report) @@ -155,37 +168,41 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Passed | [25 total](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/all) | [$expectedCoverageCell](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/coverage) | | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } } "should create comment with one performance result" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 0, - coverage = null, - performance = listOf( - ReportCommentPerformanceData( - name = "performance.json", - p95 = BigDecimal("59.13"), - requestsPerSecond = BigDecimal("1941.79") - ) - ), - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 0, + coverage = null, + performance = + listOf( + ReportCommentPerformanceData( + name = "performance.json", + p95 = BigDecimal("59.13"), + requestsPerSecond = BigDecimal("1941.79"), + ), + ), + project = null, + ) val commentText = GitHubCommentCreator.createComment(report) @@ -196,41 +213,45 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Passed | [p95: 59 ms, RPS: 1942](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | | | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } "should create comment with two performance results" { - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "my-org", - repoName = "my-repo", - branchName = "my-branch" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 0, - coverage = null, - performance = listOf( - ReportCommentPerformanceData( - name = "performance1.json", - p95 = BigDecimal("59.13"), - requestsPerSecond = BigDecimal("1941.79") - ), - ReportCommentPerformanceData( - name = "performance2.json", - p95 = BigDecimal("79.13"), - requestsPerSecond = BigDecimal("1945.79") - ) - ), - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "my-org", + repoName = "my-repo", + branchName = "my-branch", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 0, + coverage = null, + performance = + listOf( + ReportCommentPerformanceData( + name = "performance1.json", + p95 = BigDecimal("59.13"), + requestsPerSecond = BigDecimal("1941.79"), + ), + ReportCommentPerformanceData( + name = "performance2.json", + p95 = BigDecimal("79.13"), + requestsPerSecond = BigDecimal("1945.79"), + ), + ), + project = null, + ) val commentText = GitHubCommentCreator.createComment(report) @@ -241,7 +262,7 @@ class GitHubCommentCreatorSpec : StringSpec() { | Projektor report | Result | Tests executed | Coverage | Project | Date | | ---------------- | ------ | -------------- | -------- | ------- | ---- | | [Projektor report](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | Passed | [performance1.json - p95: 59 ms, RPS: 1942
performance2.json - p95: 79 ms, RPS: 1946](https://projektorlive.herokuapp.com/tests/V1BMYK93MTNR/) | | | 2020-12-16 02:30 PM UTC | - """.trimIndent().trim() + """.trimIndent().trim(), ) } } diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceLiveSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceLiveSpec.kt index 1883dba79..c4dc659a5 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceLiveSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceLiveSpec.kt @@ -16,15 +16,17 @@ class GitHubCommentServiceLiveSpec : StringSpec() { private val gitHubAppId = "91621" private val gitHubApiUrl = "https://api.github.com" - private val clientConfig = GitHubClientConfig( - gitHubApiUrl = gitHubApiUrl - ) + private val clientConfig = + GitHubClientConfig( + gitHubApiUrl = gitHubApiUrl, + ) - private val jwtTokenConfig = JwtTokenConfig( - gitHubAppId = gitHubAppId, - pemContents = keyContents, - ttlMillis = ttl - ) + private val jwtTokenConfig = + JwtTokenConfig( + gitHubAppId = gitHubAppId, + pemContents = keyContents, + ttlMillis = ttl, + ) private val jwtProvider = JwtProvider(jwtTokenConfig) @@ -32,25 +34,28 @@ class GitHubCommentServiceLiveSpec : StringSpec() { "should create comment when one does not exist" { val commentService = GitHubCommentService(GitHubCommentClient(clientConfig, jwtProvider)) - val commentData = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "craigatk", - repoName = "projektor", - branchName = "test-pr" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val commentData = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "craigatk", + repoName = "projektor", + branchName = "test-pr", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) commentService.upsertReportComment(commentData, "12345") } @@ -58,32 +63,36 @@ class GitHubCommentServiceLiveSpec : StringSpec() { "should update comment when one already exists" { val commentService = GitHubCommentService(GitHubCommentClient(clientConfig, jwtProvider)) - val newCommentData = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = "craigatk", - repoName = "projektor", - branchName = "test-pr" - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 17), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 30, - coverage = null, - performance = null, - project = null - ) + val newCommentData = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = "craigatk", + repoName = "projektor", + branchName = "test-pr", + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 17), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 30, + coverage = null, + performance = null, + project = null, + ) commentService.upsertReportComment(newCommentData, "12345") } } - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceSpec.kt b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceSpec.kt index f0ba855ac..300b59f78 100644 --- a/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceSpec.kt +++ b/server/notification/github/src/test/kotlin/projektor/notification/github/comment/GitHubCommentServiceSpec.kt @@ -29,9 +29,10 @@ class GitHubCommentServiceSpec : StringSpec() { init { "should add new comment when one does not exist" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -39,25 +40,28 @@ class GitHubCommentServiceSpec : StringSpec() { val repoName = "my-repo" val branchName = "my-branch" val pullRequestNumber = 2 - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", branchName)) @@ -81,9 +85,10 @@ class GitHubCommentServiceSpec : StringSpec() { "should update comment when one exists" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -91,32 +96,40 @@ class GitHubCommentServiceSpec : StringSpec() { val repoName = "my-repo" val branchName = "my-branch" val pullRequestNumber = 2 - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", branchName)) gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber) val commentId = 3 - gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("A comment", "Another comment", GitHubCommentCreator.headerText)) - gitHubWireMockStubber.stubGetComment(orgName, repoName, pullRequestNumber, commentId, GitHubCommentCreator.headerText) + gitHubWireMockStubber.stubListComments( + orgName, + repoName, + pullRequestNumber, + listOf("A comment", "Another comment", GitHubCommentCreator.HEADER_TEXT), + ) + gitHubWireMockStubber.stubGetComment(orgName, repoName, pullRequestNumber, commentId, GitHubCommentCreator.HEADER_TEXT) gitHubWireMockStubber.stubUpdateComment(orgName, repoName, pullRequestNumber, commentId) val pullRequest = commentService.upsertReportComment(report, "12345") @@ -135,9 +148,10 @@ class GitHubCommentServiceSpec : StringSpec() { "should return null when no pull request with branch name" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -145,25 +159,28 @@ class GitHubCommentServiceSpec : StringSpec() { val repoName = "my-repo" val branchName = "my-branch" val pullRequestNumber = 2 - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", "yet-another-branch")) @@ -183,9 +200,10 @@ class GitHubCommentServiceSpec : StringSpec() { "should find pull request by commit SHA" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -194,26 +212,29 @@ class GitHubCommentServiceSpec : StringSpec() { val branchName = "my-branch" val pullRequestNumber = 2 val sha = "123456789" - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName, - commitSha = sha - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + commitSha = sha, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("branch-1", "branch-2"), listOf("sha1", sha)) @@ -237,9 +258,10 @@ class GitHubCommentServiceSpec : StringSpec() { "should find pull request by commit SHA when no branch included" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -248,26 +270,29 @@ class GitHubCommentServiceSpec : StringSpec() { val branchName = null val pullRequestNumber = 2 val sha = "123456789" - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName, - commitSha = sha - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + commitSha = sha, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("branch-1", "branch-2"), listOf("sha1", sha)) @@ -291,9 +316,10 @@ class GitHubCommentServiceSpec : StringSpec() { "when pull request number passed in should use that" { val gitHubApiUrl = "http://localhost:${wireMockServer.port()}/" - val clientConfig = GitHubClientConfig( - gitHubApiUrl - ) + val clientConfig = + GitHubClientConfig( + gitHubApiUrl, + ) val commentClient = GitHubCommentClient(clientConfig, jwtProvider) val commentService = GitHubCommentService(commentClient) @@ -302,27 +328,30 @@ class GitHubCommentServiceSpec : StringSpec() { val branchName = "my-branch" val pullRequestNumber = 2 val sha = "123456789" - val report = ReportCommentData( - projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName, - commitSha = sha, - pullRequestNumber = pullRequestNumber - ), - publicId = "V1BMYK93MTNR", - createdDate = LocalDateTime.of( - LocalDate.of(2020, 12, 16), - LocalTime.of(14, 30) - ), - passed = true, - failedTestCount = 0, - totalTestCount = 25, - coverage = null, - performance = null, - project = null - ) + val report = + ReportCommentData( + projektorServerBaseUrl = "https://projektorlive.herokuapp.com/", + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + commitSha = sha, + pullRequestNumber = pullRequestNumber, + ), + publicId = "V1BMYK93MTNR", + createdDate = + LocalDateTime.of( + LocalDate.of(2020, 12, 16), + LocalTime.of(14, 30), + ), + passed = true, + failedTestCount = 0, + totalTestCount = 25, + coverage = null, + performance = null, + project = null, + ) gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName) gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber) diff --git a/server/notification/github/src/testFixtures/kotlin/projektor/notification/github/GitHubWireMockStubber.kt b/server/notification/github/src/testFixtures/kotlin/projektor/notification/github/GitHubWireMockStubber.kt index 77bc9b9be..6877b71da 100644 --- a/server/notification/github/src/testFixtures/kotlin/projektor/notification/github/GitHubWireMockStubber.kt +++ b/server/notification/github/src/testFixtures/kotlin/projektor/notification/github/GitHubWireMockStubber.kt @@ -10,7 +10,10 @@ import com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { - fun stubRepositoryRequests(orgName: String, repoName: String) { + fun stubRepositoryRequests( + orgName: String, + repoName: String, + ) { val installationId = 1 val accessToken = "v1.1f699f1069f60xxx" val repositoryId = 2 @@ -28,43 +31,47 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { .willReturn( aResponse().withBody( """ - { - "id": 1, - "slug": "octoapp", - "node_id": "MDExOkludGVncmF0aW9uMQ==", - "owner": { - "login": "craigatk", - "id": 1, - "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", - "url": "https://api.github.com/orgs/github", - "gravatar_id": "", - "type": "User", - "site_admin": true - }, - "name": "Octocat App", - "description": "", - "external_url": "https://example.com", - "html_url": "https://github.com/apps/octoapp", - "created_at": "2017-07-08T16:18:44-04:00", - "updated_at": "2017-07-08T16:18:44-04:00", - "permissions": { - "metadata": "read", - "contents": "read", - "issues": "write", - "single_file": "write" - }, - "events": [ - "push", - "pull_request" - ] - } - """.trimIndent() - ) - ) + { + "id": 1, + "slug": "octoapp", + "node_id": "MDExOkludGVncmF0aW9uMQ==", + "owner": { + "login": "craigatk", + "id": 1, + "node_id": "MDEyOk9yZ2FuaXphdGlvbjE=", + "url": "https://api.github.com/orgs/github", + "gravatar_id": "", + "type": "User", + "site_admin": true + }, + "name": "Octocat App", + "description": "", + "external_url": "https://example.com", + "html_url": "https://github.com/apps/octoapp", + "created_at": "2017-07-08T16:18:44-04:00", + "updated_at": "2017-07-08T16:18:44-04:00", + "permissions": { + "metadata": "read", + "contents": "read", + "issues": "write", + "single_file": "write" + }, + "events": [ + "push", + "pull_request" + ] + } + """.trimIndent(), + ), + ), ) } - fun stubGetRepoInstallation(orgName: String, repoName: String, installationId: Int) { + fun stubGetRepoInstallation( + orgName: String, + repoName: String, + installationId: Int, + ) { wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/installation")) .willReturn( @@ -108,22 +115,29 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { "updated_at": "2017-07-08T16:18:44-04:00", "app_slug": "github-actions" } -""" - ) - ) +""", + ), + ), ) } - fun stubGetRepoInstallationNotFound(orgName: String, repoName: String) { + fun stubGetRepoInstallationNotFound( + orgName: String, + repoName: String, + ) { wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/installation")) .willReturn( - aResponse().withStatus(404) - ) + aResponse().withStatus(404), + ), ) } - fun stubCreateInstallationAccessToken(installationId: Int, token: String, repositoryId: Int) { + fun stubCreateInstallationAccessToken( + installationId: Int, + token: String, + repositoryId: Int, + ) { wireMockServer.stubFor( post(urlEqualTo("/app/installations/$installationId/access_tokens")) .willReturn( @@ -211,13 +225,17 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { } ] } -""" - ) - ) +""", + ), + ), ) } - fun stubGetRepository(orgName: String, repoName: String, repositoryId: Int) { + fun stubGetRepository( + orgName: String, + repoName: String, + repositoryId: Int, + ) { wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName")) .willReturn( @@ -443,13 +461,17 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { "watchers": 1 } } -""" - ) - ) +""", + ), + ), ) } - fun stubGetIssue(orgName: String, repoName: String, issueId: Int) { + fun stubGetIssue( + orgName: String, + repoName: String, + issueId: Int, + ) { wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/issues/$issueId")) .willReturn( @@ -564,13 +586,17 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { }, "author_association": "collaborator" } -""" - ) - ) +""", + ), + ), ) } - fun stubAddComment(orgName: String, repoName: String, issueId: Int) { + fun stubAddComment( + orgName: String, + repoName: String, + issueId: Int, + ) { wireMockServer.stubFor( post(urlEqualTo("/repos/$orgName/$repoName/issues/$issueId/comments")) .willReturn( @@ -598,377 +624,396 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "author_association": "collaborator" } -""" - ) - ) +""", + ), + ), ) } - fun stubListPullRequests(orgName: String, repoName: String, branchNames: List, commitShas: List = listOf()) { + fun stubListPullRequests( + orgName: String, + repoName: String, + branchNames: List, + commitShas: List = listOf(), + ) { val shas = if (commitShas.isEmpty()) branchNames.map { "$it-sha" } else commitShas - val responseBody = branchNames.mapIndexed { idx, branchName -> - """ - { - "url": "https://api.github.com/repos/$orgName/$repoName/pulls/${idx + 1}", - "id": 1, - "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==", - "number": ${idx + 1}, - "state": "open", - "locked": true, - "title": "Amazing new feature", - "user": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - "body": "Please pull these awesome changes in!", - "labels": [ - { - "id": 208045946, - "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", - "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", - "name": "bug", - "description": "Something isn't working", - "color": "f29513", - "default": true - } - ], - "milestone": { - "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", - "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", - "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", - "id": 1002604, - "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", - "number": 1, - "state": "open", - "title": "v1.0", - "description": "Tracking milestone for version 1.0", - "creator": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - "open_issues": 4, - "closed_issues": 8, - "created_at": "2011-04-10T20:09:31Z", - "updated_at": "2014-03-03T18:58:10Z", - "closed_at": "2013-02-12T13:22:01Z", - "due_on": "2012-10-09T23:39:01Z" - }, - "active_lock_reason": "too heated", - "created_at": "2011-01-26T19:01:12Z", - "updated_at": "2011-01-26T19:01:12Z", - "closed_at": "2011-01-26T19:01:12Z", - "merged_at": "2011-01-26T19:01:12Z", - "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6", - "assignee": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - "assignees": [ - { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - { - "login": "hubot", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/hubot_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/hubot", - "type": "User", - "site_admin": true - } - ], - "requested_reviewers": [ - { - "login": "other_user", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/other_user_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/other_user", - "type": "User", - "site_admin": false - } - ], - "requested_teams": [ - { - "id": 1, - "node_id": "MDQ6VGVhbTE=", - "url": "https://api.github.com/teams/1", - "html_url": "https://api.github.com/teams/justice-league", - "name": "Justice League", - "slug": "justice-league", - "description": "A great team.", - "privacy": "closed", - "permission": "admin", - "members_url": "https://api.github.com/teams/1/members{/member}", - "repositories_url": "https://api.github.com/teams/1/repos" - } - ], - "head": { - "label": "$orgName:$branchName", - "ref": "$branchName", - "sha": "${shas[idx]}", - "user": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - "repo": { - "id": 1296269, - "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", - "name": "Hello-World", - "full_name": "octocat/Hello-World", - "owner": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "type": "User", - "site_admin": false - }, - "private": false, - "html_url": "https://github.com/octocat/Hello-World", - "description": "This your first repo!", - "fork": false, - "homepage": "https://github.com", - "language": null, - "forks_count": 9, - "stargazers_count": 80, - "watchers_count": 80, - "size": 108, - "default_branch": "master", - "open_issues_count": 0, - "is_template": true, - "topics": [ - "octocat", - "atom", - "electron", - "api" - ], - "has_issues": true, - "has_projects": true, - "has_wiki": true, - "has_pages": false, - "has_downloads": true, - "archived": false, - "disabled": false, - "visibility": "public", - "pushed_at": "2011-01-26T19:06:43Z", - "created_at": "2011-01-26T19:01:12Z", - "updated_at": "2011-01-26T19:14:43Z", - "permissions": { - "admin": false, - "push": false, - "pull": true - }, - "allow_rebase_merge": true, - "template_repository": null, - "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", - "allow_squash_merge": true, - "delete_branch_on_merge": true, - "allow_merge_commit": true, - "subscribers_count": 42, - "network_count": 0, - "license": { - "key": "mit", - "name": "MIT License", - "url": "https://api.github.com/licenses/mit", - "spdx_id": "MIT", - "node_id": "MDc6TGljZW5zZW1pdA==", - "html_url": "https://github.com/licenses/mit" - }, - "forks": 1, - "open_issues": 1, - "watchers": 1 - } - }, - "base": { - "label": "octocat:master", - "ref": "master", - "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", - "user": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "type": "User", - "site_admin": false - }, - "repo": { - "id": 1296269, - "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", - "name": "Hello-World", - "full_name": "octocat/Hello-World", - "owner": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "type": "User", - "site_admin": false - }, - "private": false, - "html_url": "https://github.com/octocat/Hello-World", - "description": "This your first repo!", - "fork": false, - "homepage": "https://github.com", - "language": null, - "forks_count": 9, - "stargazers_count": 80, - "watchers_count": 80, - "size": 108, - "default_branch": "master", - "open_issues_count": 0, - "is_template": true, - "topics": [ - "octocat", - "atom", - "electron", - "api" - ], - "has_issues": true, - "has_projects": true, - "has_wiki": true, - "has_pages": false, - "has_downloads": true, - "archived": false, - "disabled": false, - "visibility": "public", - "pushed_at": "2011-01-26T19:06:43Z", - "created_at": "2011-01-26T19:01:12Z", - "updated_at": "2011-01-26T19:14:43Z", - "permissions": { - "admin": false, - "push": false, - "pull": true - }, - "allow_rebase_merge": true, - "template_repository": null, - "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", - "allow_squash_merge": true, - "delete_branch_on_merge": true, - "allow_merge_commit": true, - "subscribers_count": 42, - "network_count": 0, - "license": { - "key": "mit", - "name": "MIT License", - "url": "https://api.github.com/licenses/mit", - "spdx_id": "MIT", - "node_id": "MDc6TGljZW5zZW1pdA==", - "html_url": "https://github.com/licenses/mit" - }, - "forks": 1, - "open_issues": 1, - "watchers": 1 - } - }, - "_links": { - "self": { - "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" - }, - "html": { - "href": "https://github.com/octocat/Hello-World/pull/1347" - }, - "issue": { - "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347" - }, - "comments": { - "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" - }, - "review_comments": { - "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" - }, - "review_comment": { - "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" - }, - "commits": { - "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" - }, - "statuses": { - "href": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" - } - }, - "author_association": "OWNER", - "draft": false - } - """.trimIndent() - }.joinToString(",") + val responseBody = + branchNames.mapIndexed { idx, branchName -> + """ + { + "url": "https://api.github.com/repos/$orgName/$repoName/pulls/${idx + 1}", + "id": 1, + "node_id": "MDExOlB1bGxSZXF1ZXN0MQ==", + "number": ${idx + 1}, + "state": "open", + "locked": true, + "title": "Amazing new feature", + "user": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + "body": "Please pull these awesome changes in!", + "labels": [ + { + "id": 208045946, + "node_id": "MDU6TGFiZWwyMDgwNDU5NDY=", + "url": "https://api.github.com/repos/octocat/Hello-World/labels/bug", + "name": "bug", + "description": "Something isn't working", + "color": "f29513", + "default": true + } + ], + "milestone": { + "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", + "html_url": "https://github.com/octocat/Hello-World/milestones/v1.0", + "labels_url": "https://api.github.com/repos/octocat/Hello-World/milestones/1/labels", + "id": 1002604, + "node_id": "MDk6TWlsZXN0b25lMTAwMjYwNA==", + "number": 1, + "state": "open", + "title": "v1.0", + "description": "Tracking milestone for version 1.0", + "creator": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + "open_issues": 4, + "closed_issues": 8, + "created_at": "2011-04-10T20:09:31Z", + "updated_at": "2014-03-03T18:58:10Z", + "closed_at": "2013-02-12T13:22:01Z", + "due_on": "2012-10-09T23:39:01Z" + }, + "active_lock_reason": "too heated", + "created_at": "2011-01-26T19:01:12Z", + "updated_at": "2011-01-26T19:01:12Z", + "closed_at": "2011-01-26T19:01:12Z", + "merged_at": "2011-01-26T19:01:12Z", + "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6", + "assignee": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + "assignees": [ + { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + { + "login": "hubot", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/hubot_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/hubot", + "type": "User", + "site_admin": true + } + ], + "requested_reviewers": [ + { + "login": "other_user", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/other_user_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/other_user", + "type": "User", + "site_admin": false + } + ], + "requested_teams": [ + { + "id": 1, + "node_id": "MDQ6VGVhbTE=", + "url": "https://api.github.com/teams/1", + "html_url": "https://api.github.com/teams/justice-league", + "name": "Justice League", + "slug": "justice-league", + "description": "A great team.", + "privacy": "closed", + "permission": "admin", + "members_url": "https://api.github.com/teams/1/members{/member}", + "repositories_url": "https://api.github.com/teams/1/repos" + } + ], + "head": { + "label": "$orgName:$branchName", + "ref": "$branchName", + "sha": "${shas[idx]}", + "user": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + "repo": { + "id": 1296269, + "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", + "name": "Hello-World", + "full_name": "octocat/Hello-World", + "owner": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "type": "User", + "site_admin": false + }, + "private": false, + "html_url": "https://github.com/octocat/Hello-World", + "description": "This your first repo!", + "fork": false, + "homepage": "https://github.com", + "language": null, + "forks_count": 9, + "stargazers_count": 80, + "watchers_count": 80, + "size": 108, + "default_branch": "master", + "open_issues_count": 0, + "is_template": true, + "topics": [ + "octocat", + "atom", + "electron", + "api" + ], + "has_issues": true, + "has_projects": true, + "has_wiki": true, + "has_pages": false, + "has_downloads": true, + "archived": false, + "disabled": false, + "visibility": "public", + "pushed_at": "2011-01-26T19:06:43Z", + "created_at": "2011-01-26T19:01:12Z", + "updated_at": "2011-01-26T19:14:43Z", + "permissions": { + "admin": false, + "push": false, + "pull": true + }, + "allow_rebase_merge": true, + "template_repository": null, + "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", + "allow_squash_merge": true, + "delete_branch_on_merge": true, + "allow_merge_commit": true, + "subscribers_count": 42, + "network_count": 0, + "license": { + "key": "mit", + "name": "MIT License", + "url": "https://api.github.com/licenses/mit", + "spdx_id": "MIT", + "node_id": "MDc6TGljZW5zZW1pdA==", + "html_url": "https://github.com/licenses/mit" + }, + "forks": 1, + "open_issues": 1, + "watchers": 1 + } + }, + "base": { + "label": "octocat:master", + "ref": "master", + "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", + "user": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "type": "User", + "site_admin": false + }, + "repo": { + "id": 1296269, + "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", + "name": "Hello-World", + "full_name": "octocat/Hello-World", + "owner": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "type": "User", + "site_admin": false + }, + "private": false, + "html_url": "https://github.com/octocat/Hello-World", + "description": "This your first repo!", + "fork": false, + "homepage": "https://github.com", + "language": null, + "forks_count": 9, + "stargazers_count": 80, + "watchers_count": 80, + "size": 108, + "default_branch": "master", + "open_issues_count": 0, + "is_template": true, + "topics": [ + "octocat", + "atom", + "electron", + "api" + ], + "has_issues": true, + "has_projects": true, + "has_wiki": true, + "has_pages": false, + "has_downloads": true, + "archived": false, + "disabled": false, + "visibility": "public", + "pushed_at": "2011-01-26T19:06:43Z", + "created_at": "2011-01-26T19:01:12Z", + "updated_at": "2011-01-26T19:14:43Z", + "permissions": { + "admin": false, + "push": false, + "pull": true + }, + "allow_rebase_merge": true, + "template_repository": null, + "temp_clone_token": "ABTLWHOULUVAXGTRYU7OC2876QJ2O", + "allow_squash_merge": true, + "delete_branch_on_merge": true, + "allow_merge_commit": true, + "subscribers_count": 42, + "network_count": 0, + "license": { + "key": "mit", + "name": "MIT License", + "url": "https://api.github.com/licenses/mit", + "spdx_id": "MIT", + "node_id": "MDc6TGljZW5zZW1pdA==", + "html_url": "https://github.com/licenses/mit" + }, + "forks": 1, + "open_issues": 1, + "watchers": 1 + } + }, + "_links": { + "self": { + "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347" + }, + "html": { + "href": "https://github.com/octocat/Hello-World/pull/1347" + }, + "issue": { + "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347" + }, + "comments": { + "href": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments" + }, + "review_comments": { + "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments" + }, + "review_comment": { + "href": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}" + }, + "commits": { + "href": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/commits" + }, + "statuses": { + "href": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e" + } + }, + "author_association": "OWNER", + "draft": false + } + """.trimIndent() + }.joinToString(",") wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/pulls?state=open")) .willReturn( - aResponse().withBody("[$responseBody]") - ) + aResponse().withBody("[$responseBody]"), + ), ) } - fun stubListComments(orgName: String, repoName: String, issueId: Int, commentBodies: List) { - val responseBodies = commentBodies.mapIndexed { idx, commentBody -> + fun stubListComments( + orgName: String, + repoName: String, + issueId: Int, + commentBodies: List, + ) { + val responseBodies = + commentBodies.mapIndexed { idx, commentBody -> """ - { - "id": ${idx + 1}, - "node_id": "MDEyOklzc3VlQ29tbWVudDE=", - "url": "https://api.github.com/repos/$orgName/$repoName/issues/comments/${idx + 1}", - "html_url": "https://github.com/$orgName/$repoName/issues/$issueId#issuecomment-${idx + 1}", - "body": "$commentBody", - "user": { - "login": "octocat", - "id": 1, - "node_id": "MDQ6VXNlcjE=", - "avatar_url": "https://github.com/images/error/octocat_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/octocat", - "type": "User", - "site_admin": false - }, - "created_at": "2011-04-14T16:00:49Z", - "updated_at": "2011-04-14T16:00:49Z", - "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", - "author_association": "collaborator" - } - """.trimIndent() - } + { + "id": ${idx + 1}, + "node_id": "MDEyOklzc3VlQ29tbWVudDE=", + "url": "https://api.github.com/repos/$orgName/$repoName/issues/comments/${idx + 1}", + "html_url": "https://github.com/$orgName/$repoName/issues/$issueId#issuecomment-${idx + 1}", + "body": "$commentBody", + "user": { + "login": "octocat", + "id": 1, + "node_id": "MDQ6VXNlcjE=", + "avatar_url": "https://github.com/images/error/octocat_happy.gif", + "gravatar_id": "", + "url": "https://api.github.com/users/octocat", + "type": "User", + "site_admin": false + }, + "created_at": "2011-04-14T16:00:49Z", + "updated_at": "2011-04-14T16:00:49Z", + "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", + "author_association": "collaborator" +} +""".trimIndent() + } wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/issues/$issueId/comments")) .willReturn( - aResponse().withBody("""[${responseBodies.joinToString(",")}]""") - ) + aResponse().withBody("""[${responseBodies.joinToString(",")}]"""), + ), ) } - fun stubGetComment(orgName: String, repoName: String, issueId: Int, commentId: Int, commentBody: String) { - val responseBody = """ + fun stubGetComment( + orgName: String, + repoName: String, + issueId: Int, + commentId: Int, + commentBody: String, + ) { + val responseBody = + """ { "id": $commentId, "node_id": "MDEyOklzc3VlQ29tbWVudDE=", @@ -989,18 +1034,24 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { "issue_url": "https://api.github.com/repos/$orgName/$repoName/issues/$issueId", "author_association": "collaborator" } - """.trimIndent() + """.trimIndent() wireMockServer.stubFor( get(urlEqualTo("/repos/$orgName/$repoName/issues/comments/$commentId")) .willReturn( - aResponse().withBody(responseBody) - ) + aResponse().withBody(responseBody), + ), ) } - fun stubUpdateComment(orgName: String, repoName: String, issueId: Int, commentId: Int) { - val responseBody = """ + fun stubUpdateComment( + orgName: String, + repoName: String, + issueId: Int, + commentId: Int, + ) { + val responseBody = + """ { "id": 1, "node_id": "MDEyOklzc3VlQ29tbWVudDE=", @@ -1021,23 +1072,29 @@ class GitHubWireMockStubber(private val wireMockServer: WireMockServer) { "issue_url": "https://api.github.com/repos/$orgName/$repoName/issues/$issueId", "author_association": "collaborator" } - """.trimIndent() + """.trimIndent() wireMockServer.stubFor( patch(urlEqualTo("/repos/$orgName/$repoName/issues/comments/$commentId")) .willReturn( - aResponse().withBody(responseBody) - ) + aResponse().withBody(responseBody), + ), ) } - fun findAddCommentRequestBodies(orgName: String, repoName: String, issueId: Int) = - wireMockServer.findRequestsMatching( - postRequestedFor(urlEqualTo("/repos/$orgName/$repoName/issues/$issueId/comments")).build() - ).requests.map { it.bodyAsString } + fun findAddCommentRequestBodies( + orgName: String, + repoName: String, + issueId: Int, + ) = wireMockServer.findRequestsMatching( + postRequestedFor(urlEqualTo("/repos/$orgName/$repoName/issues/$issueId/comments")).build(), + ).requests.map { it.bodyAsString } - fun findUpdateCommentRequestBodies(orgName: String, repoName: String, commentId: Int) = - wireMockServer.findRequestsMatching( - patchRequestedFor(urlEqualTo("/repos/$orgName/$repoName/issues/comments/$commentId")).build() - ).requests.map { it.bodyAsString } + fun findUpdateCommentRequestBodies( + orgName: String, + repoName: String, + commentId: Int, + ) = wireMockServer.findRequestsMatching( + patchRequestedFor(urlEqualTo("/repos/$orgName/$repoName/issues/comments/$commentId")).build(), + ).requests.map { it.bodyAsString } } diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CloverCoverageReportParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CloverCoverageReportParser.kt index f59036714..8a6329bea 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CloverCoverageReportParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CloverCoverageReportParser.kt @@ -11,39 +11,49 @@ import projektor.parser.coverage.model.CoverageReportStat import projektor.parser.coverage.model.CoverageReportStats class CloverCoverageReportParser : CoverageReportParser { - override fun parseReport(reportXml: String, baseDirectoryPath: String?): CoverageReport { + override fun parseReport( + reportXml: String, + baseDirectoryPath: String?, + ): CoverageReport { val parsedReport = CloverXmlReportParser().parseReport(reportXml) - val files = if (parsedReport.project.packages != null) { - parsedReport.project.packages.flatMap { pkg -> - pkg.files.map { sourceFile -> createCoverageReportFile(sourceFile, pkg, baseDirectoryPath) } + val files = + if (parsedReport.project.packages != null) { + parsedReport.project.packages.flatMap { pkg -> + pkg.files.map { sourceFile -> createCoverageReportFile(sourceFile, pkg, baseDirectoryPath) } + } + } else { + parsedReport.project.files.map { sourceFile -> createCoverageReportFile(sourceFile, null, baseDirectoryPath) } } - } else { - parsedReport.project.files.map { sourceFile -> createCoverageReportFile(sourceFile, null, baseDirectoryPath) } - } return CoverageReport( name = parsedReport.project.name, totalStats = createStats(parsedReport.project.metrics), - files = files + files = files, ) } companion object { private fun createStats(metrics: Metrics): CoverageReportStats = CoverageReportStats( - lineStat = CoverageReportStat( - covered = metrics.coveredStatements, - missed = metrics.statements - metrics.coveredStatements - ), - branchStat = CoverageReportStat( - covered = metrics.coveredConditionals, - missed = metrics.conditionals - metrics.coveredConditionals - ), - statementStat = CoverageReportStat(covered = 0, missed = 0) + lineStat = + CoverageReportStat( + covered = metrics.coveredStatements, + missed = metrics.statements - metrics.coveredStatements, + ), + branchStat = + CoverageReportStat( + covered = metrics.coveredConditionals, + missed = metrics.conditionals - metrics.coveredConditionals, + ), + statementStat = CoverageReportStat(covered = 0, missed = 0), ) - private fun createCoverageReportFile(sourceFile: CoverageFile, pkg: CoveragePackage?, baseDirectoryPath: String?): CoverageReportFile { + private fun createCoverageReportFile( + sourceFile: CoverageFile, + pkg: CoveragePackage?, + baseDirectoryPath: String?, + ): CoverageReportFile { val directoryName = pkg?.name?.replace(".", "/") ?: "" val fileName = sourceFile.name val filePath = if (baseDirectoryPath != null) "$baseDirectoryPath/$directoryName/$fileName" else "$directoryName/$fileName" @@ -54,7 +64,7 @@ class CloverCoverageReportParser : CoverageReportParser { filePath = filePath, missedLines = sourceFile.lines?.filter { it.lineCoverageType() == LineType.MISSED }?.map { it.number } ?: listOf(), partialLines = listOf(), // Clover partial lines from Jest coverage reports is not accurate so don't show anything rather than inaccurate data - stats = createStats(sourceFile.metrics) + stats = createStats(sourceFile.metrics), ) } } diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoberturaCoverageReportParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoberturaCoverageReportParser.kt index bd1673076..d2ef87615 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoberturaCoverageReportParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoberturaCoverageReportParser.kt @@ -7,47 +7,56 @@ import projektor.parser.coverage.model.CoverageReportStat import projektor.parser.coverage.model.CoverageReportStats class CoberturaCoverageReportParser : CoverageReportParser { - override fun parseReport(reportXml: String, baseDirectoryPath: String?): CoverageReport { + override fun parseReport( + reportXml: String, + baseDirectoryPath: String?, + ): CoverageReport { val parsedReport = CoberturaXmlReportParser().parseReport(reportXml) - val files: List = parsedReport.packages.packages.flatMap { pkg -> - val classes = pkg.classes.clazz + val files: List = + parsedReport.packages.packages.flatMap { pkg -> + val classes = pkg.classes.clazz - classes.map { clazz -> - val lines = clazz.lines.lines ?: listOf() + classes.map { clazz -> + val lines = clazz.lines.lines ?: listOf() - CoverageReportFile( - directoryName = clazz.fileName.substringBeforeLast(clazz.name).removeSuffix("/"), - fileName = clazz.name, - filePath = clazz.fileName, - missedLines = lines.filter { !it.isCovered }.map { it.number }, - partialLines = lines.filter { it.isPartial }.map { it.number }, - stats = CoverageReportStats( - lineStat = CoverageReportStat( - covered = lines.count { it.isCovered }, - missed = lines.count { !it.isCovered } - ), - branchStat = CoverageReportStat(0, 0), - statementStat = CoverageReportStat(0, 0) + CoverageReportFile( + directoryName = clazz.fileName.substringBeforeLast(clazz.name).removeSuffix("/"), + fileName = clazz.name, + filePath = clazz.fileName, + missedLines = lines.filter { !it.isCovered }.map { it.number }, + partialLines = lines.filter { it.isPartial }.map { it.number }, + stats = + CoverageReportStats( + lineStat = + CoverageReportStat( + covered = lines.count { it.isCovered }, + missed = lines.count { !it.isCovered }, + ), + branchStat = CoverageReportStat(0, 0), + statementStat = CoverageReportStat(0, 0), + ), ) - ) + } } - } return CoverageReport( name = "Coverage", - totalStats = CoverageReportStats( - lineStat = CoverageReportStat( - covered = parsedReport.linesCovered, - missed = parsedReport.linesValid - parsedReport.linesCovered - ), - branchStat = CoverageReportStat( - covered = parsedReport.branchesCovered, - missed = parsedReport.branchesValid - parsedReport.branchesCovered + totalStats = + CoverageReportStats( + lineStat = + CoverageReportStat( + covered = parsedReport.linesCovered, + missed = parsedReport.linesValid - parsedReport.linesCovered, + ), + branchStat = + CoverageReportStat( + covered = parsedReport.branchesCovered, + missed = parsedReport.branchesValid - parsedReport.branchesCovered, + ), + statementStat = CoverageReportStat(0, 0), ), - statementStat = CoverageReportStat(0, 0) - ), - files = files + files = files, ) } } diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageParser.kt index 31d4e9161..92b0de413 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageParser.kt @@ -7,7 +7,10 @@ import projektor.parser.coverage.model.CoverageReportType import projektor.parser.jacoco.JacocoXmlReportParser object CoverageParser { - fun parseReport(reportXml: String, baseDirectoryPath: String?): CoverageReport? { + fun parseReport( + reportXml: String, + baseDirectoryPath: String?, + ): CoverageReport? { val reportType = findReportType(reportXml) return when (reportType) { diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageReportParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageReportParser.kt index 8524c90f7..6c995c8b6 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageReportParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/CoverageReportParser.kt @@ -3,5 +3,8 @@ package projektor.parser.coverage import projektor.parser.coverage.model.CoverageReport interface CoverageReportParser { - fun parseReport(reportXml: String, baseDirectoryPath: String?): CoverageReport + fun parseReport( + reportXml: String, + baseDirectoryPath: String?, + ): CoverageReport } diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/JacocoCoverageReportParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/JacocoCoverageReportParser.kt index 61eee9bf8..996b73112 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/JacocoCoverageReportParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/JacocoCoverageReportParser.kt @@ -10,34 +10,40 @@ import projektor.parser.jacoco.model.CounterType import projektor.parser.jacoco.model.LineType class JacocoCoverageReportParser : CoverageReportParser { - override fun parseReport(reportXml: String, baseDirectoryPath: String?): CoverageReport = + override fun parseReport( + reportXml: String, + baseDirectoryPath: String?, + ): CoverageReport = try { val parsedReport = JacocoXmlReportParser().parseReport(reportXml) - val files = parsedReport.packages?.flatMap { pkg -> - pkg.sourceFiles.map { sourceFile -> - val directoryName = pkg.name.replace(".", "/") - val fileName = sourceFile.name - val filePath = - if (baseDirectoryPath != null) "$baseDirectoryPath/$directoryName/$fileName" else null + val files = + parsedReport.packages?.flatMap { pkg -> + pkg.sourceFiles.map { sourceFile -> + val directoryName = pkg.name.replace(".", "/") + val fileName = sourceFile.name + val filePath = + if (baseDirectoryPath != null) "$baseDirectoryPath/$directoryName/$fileName" else null - CoverageReportFile( - directoryName = directoryName, - fileName = fileName, - missedLines = sourceFile.lines?.filter { it.lineType() == LineType.MISSED }?.map { it.number } - ?: listOf(), - partialLines = sourceFile.lines?.filter { it.lineType() == LineType.PARTIAL }?.map { it.number } - ?: listOf(), - stats = createStats(sourceFile.counters), - filePath = filePath - ) + CoverageReportFile( + directoryName = directoryName, + fileName = fileName, + missedLines = + sourceFile.lines?.filter { it.lineType() == LineType.MISSED }?.map { it.number } + ?: listOf(), + partialLines = + sourceFile.lines?.filter { it.lineType() == LineType.PARTIAL }?.map { it.number } + ?: listOf(), + stats = createStats(sourceFile.counters), + filePath = filePath, + ) + } } - } CoverageReport( parsedReport.name, createStats(parsedReport.counters), - files + files, ) } catch (e: Exception) { throw CoverageParseException(e) @@ -52,11 +58,14 @@ class JacocoCoverageReportParser : CoverageReportParser { return CoverageReportStats( statementStat = statementStat, lineStat = lineStat, - branchStat = branchStat + branchStat = branchStat, ) } - private fun createStat(counters: List?, counterType: CounterType): CoverageReportStat { + private fun createStat( + counters: List?, + counterType: CounterType, + ): CoverageReportStat { val counter = counters?.find { it.type == counterType } return if (counter != null) { diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/MathUtil.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/MathUtil.kt index 4067b6e77..80f3537b0 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/MathUtil.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/MathUtil.kt @@ -5,7 +5,10 @@ import java.math.MathContext import java.math.RoundingMode object MathUtil { - fun calculatePercentage(value: BigDecimal, total: BigDecimal): BigDecimal = + fun calculatePercentage( + value: BigDecimal, + total: BigDecimal, + ): BigDecimal = if (value > BigDecimal.ZERO && total > BigDecimal.ZERO) { value.divide(total, MathContext(4, RoundingMode.HALF_DOWN)) .times(BigDecimal(100.00)).setScale(2, RoundingMode.HALF_DOWN) diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReport.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReport.kt index f402e3475..5257f6a0e 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReport.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReport.kt @@ -3,5 +3,5 @@ package projektor.parser.coverage.model data class CoverageReport( val name: String, val totalStats: CoverageReportStats, - val files: List? + val files: List?, ) diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportFile.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportFile.kt index 8888e23fd..5c770c9dc 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportFile.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportFile.kt @@ -6,5 +6,5 @@ data class CoverageReportFile( val stats: CoverageReportStats, val missedLines: List, val partialLines: List, - val filePath: String? = null + val filePath: String? = null, ) diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportStats.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportStats.kt index 1cc31b46e..243719d45 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportStats.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportStats.kt @@ -3,5 +3,5 @@ package projektor.parser.coverage.model data class CoverageReportStats( val statementStat: CoverageReportStat, val lineStat: CoverageReportStat, - val branchStat: CoverageReportStat + val branchStat: CoverageReportStat, ) diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportType.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportType.kt index 2be3b3418..22e79e7a2 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportType.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/model/CoverageReportType.kt @@ -3,5 +3,5 @@ package projektor.parser.coverage.model enum class CoverageReportType { JACOCO, CLOVER, - COBERTURA + COBERTURA, } diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoverageFilePayload.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoverageFilePayload.kt index 854db13f6..cb97c6e8f 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoverageFilePayload.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoverageFilePayload.kt @@ -2,5 +2,5 @@ package projektor.parser.coverage.payload data class CoverageFilePayload( val reportContents: String, - val baseDirectoryPath: String? = null + val baseDirectoryPath: String? = null, ) diff --git a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoveragePayloadParser.kt b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoveragePayloadParser.kt index 38c7b0cc9..430e77c6d 100644 --- a/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoveragePayloadParser.kt +++ b/server/parsing/coverage-parser/src/main/kotlin/projektor/parser/coverage/payload/CoveragePayloadParser.kt @@ -5,13 +5,12 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule class CoveragePayloadParser { - private val objectMapper = ObjectMapper() - .registerKotlinModule() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + private val objectMapper = + ObjectMapper() + .registerKotlinModule() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - fun parseCoverageFilePayload(payload: String): CoverageFilePayload = - objectMapper.readValue(payload, CoverageFilePayload::class.java) + fun parseCoverageFilePayload(payload: String): CoverageFilePayload = objectMapper.readValue(payload, CoverageFilePayload::class.java) - fun serializeCoverageFilePayload(payload: CoverageFilePayload): String = - objectMapper.writeValueAsString(payload) + fun serializeCoverageFilePayload(payload: CoverageFilePayload): String = objectMapper.writeValueAsString(payload) } diff --git a/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/CoverageParserFileSpec.kt b/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/CoverageParserFileSpec.kt index 3ca847aa4..a9db0079d 100644 --- a/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/CoverageParserFileSpec.kt +++ b/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/CoverageParserFileSpec.kt @@ -48,7 +48,7 @@ class CoverageParserFileSpec : StringSpec({ } } - "should include full file path for Jacoco results when base directory set"() { + "should include full file path for Jacoco results when base directory set" { val jacocoReportXml = JacocoXmlLoader().serverApp() val coverageReport = CoverageParser.parseReport(jacocoReportXml, "server/server-app/src/main/kotlin") diff --git a/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/model/CoverageReportStatSpec.kt b/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/model/CoverageReportStatSpec.kt index 8acd63722..0c6dacec5 100644 --- a/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/model/CoverageReportStatSpec.kt +++ b/server/parsing/coverage-parser/src/test/kotlin/projektor/parser/coverage/model/CoverageReportStatSpec.kt @@ -8,12 +8,12 @@ import strikt.assertions.isEqualTo import java.math.BigDecimal class CoverageReportStatSpec : StringSpec({ - "should calculate total and percent covered"() { + "should calculate total and percent covered" { forAll( row(50, 50, 100, BigDecimal("50.00")), row(33, 66, 99, BigDecimal("33.33")), row(60, 0, 60, BigDecimal("100.00")), - row(0, 0, 0, BigDecimal.ZERO) + row(0, 0, 0, BigDecimal.ZERO), ) { covered, missed, expectedTotal, expectedPercentCovered -> val coverageStat = CoverageReportStat(covered = covered, missed = missed) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/PerformanceResultsParser.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/PerformanceResultsParser.kt index a2fd829af..313099638 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/PerformanceResultsParser.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/PerformanceResultsParser.kt @@ -16,15 +16,17 @@ class PerformanceResultsParser { val k6Results = k6PerformanceResultsParser.parseResults(resultsStr) PerformanceResultsReport( - requestStats = RequestStats( - ratePerSecond = k6Results.metrics.iterations.rate, - count = k6Results.metrics.iterations.count - ), - performanceStats = PerformanceStats( - average = k6Results.metrics.requestDurationStats.average, - maximum = k6Results.metrics.requestDurationStats.maximum, - p95 = k6Results.metrics.requestDurationStats.p95 - ) + requestStats = + RequestStats( + ratePerSecond = k6Results.metrics.iterations.rate, + count = k6Results.metrics.iterations.count, + ), + performanceStats = + PerformanceStats( + average = k6Results.metrics.requestDurationStats.average, + maximum = k6Results.metrics.requestDurationStats.maximum, + p95 = k6Results.metrics.requestDurationStats.p95, + ), ) } catch (e: Exception) { logger.warn("Error parsing performance results", e) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/K6PerformanceResultsParser.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/K6PerformanceResultsParser.kt index 4047ae6c3..e4c8fb411 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/K6PerformanceResultsParser.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/K6PerformanceResultsParser.kt @@ -6,10 +6,10 @@ import com.fasterxml.jackson.module.kotlin.registerKotlinModule import projektor.parser.performance.k6.model.K6Results class K6PerformanceResultsParser { - private val mapper = ObjectMapper() - .registerKotlinModule() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + private val mapper = + ObjectMapper() + .registerKotlinModule() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - fun parseResults(k6Results: String): K6Results = - mapper.readValue(k6Results, K6Results::class.java) + fun parseResults(k6Results: String): K6Results = mapper.readValue(k6Results, K6Results::class.java) } diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/DurationStats.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/DurationStats.kt index 9d5bbf2d8..1350f37f2 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/DurationStats.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/DurationStats.kt @@ -9,5 +9,5 @@ class DurationStats( @JsonProperty("med") val median: BigDecimal, @JsonProperty("min") val minimum: BigDecimal, @JsonProperty("p(90)") val p90: BigDecimal, - @JsonProperty("p(95)") val p95: BigDecimal + @JsonProperty("p(95)") val p95: BigDecimal, ) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/K6Results.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/K6Results.kt index 2dda0b84c..9060de4c5 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/K6Results.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/K6Results.kt @@ -2,4 +2,6 @@ package projektor.parser.performance.k6.model import com.fasterxml.jackson.annotation.JsonProperty -class K6Results(@JsonProperty("metrics") val metrics: Metrics) +class K6Results( + @JsonProperty("metrics") val metrics: Metrics, +) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/Metrics.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/Metrics.kt index 494349d5a..5fe7cd8a8 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/Metrics.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/Metrics.kt @@ -4,5 +4,5 @@ import com.fasterxml.jackson.annotation.JsonProperty class Metrics( @JsonProperty("http_req_duration") val requestDurationStats: DurationStats, - @JsonProperty("iterations") val iterations: RequestCounts + @JsonProperty("iterations") val iterations: RequestCounts, ) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/RequestCounts.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/RequestCounts.kt index d91ffb30b..fd4c64557 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/RequestCounts.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/k6/model/RequestCounts.kt @@ -4,5 +4,5 @@ import java.math.BigDecimal class RequestCounts( val count: Long, - val rate: BigDecimal + val rate: BigDecimal, ) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceResultsReport.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceResultsReport.kt index 1323250bd..cf9fe7465 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceResultsReport.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceResultsReport.kt @@ -2,5 +2,5 @@ package projektor.parser.performance.model class PerformanceResultsReport( val requestStats: RequestStats, - val performanceStats: PerformanceStats + val performanceStats: PerformanceStats, ) diff --git a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceStats.kt b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceStats.kt index 992929df3..22ffe1bbb 100644 --- a/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceStats.kt +++ b/server/parsing/performance-results-parser/src/main/kotlin/projektor/parser/performance/model/PerformanceStats.kt @@ -5,5 +5,5 @@ import java.math.BigDecimal data class PerformanceStats( val average: BigDecimal, val maximum: BigDecimal, - val p95: BigDecimal + val p95: BigDecimal, ) diff --git a/server/parsing/test-results-parser/src/main/kotlin/projektor/results/processor/ResultsXmlMerger.kt b/server/parsing/test-results-parser/src/main/kotlin/projektor/results/processor/ResultsXmlMerger.kt index d8f490016..c4a032ac0 100644 --- a/server/parsing/test-results-parser/src/main/kotlin/projektor/results/processor/ResultsXmlMerger.kt +++ b/server/parsing/test-results-parser/src/main/kotlin/projektor/results/processor/ResultsXmlMerger.kt @@ -1,28 +1,32 @@ package projektor.results.processor object ResultsXmlMerger { - fun cleanAndMergeBlob(resultsBlob: String): String = resultsBlob - .let(ResultsXmlMerger::removeXmlHeader) - .let(ResultsXmlMerger::conditionallyWrapInTestSuitesXml) - .let(ResultsXmlMerger::wrappedInTestSuitesWrapperXml) + fun cleanAndMergeBlob(resultsBlob: String): String = + resultsBlob + .let(ResultsXmlMerger::removeXmlHeader) + .let(ResultsXmlMerger::conditionallyWrapInTestSuitesXml) + .let(ResultsXmlMerger::wrappedInTestSuitesWrapperXml) fun conditionallyWrapInTestSuitesXml(resultsXml: String): String = if (!resultsXml.contains(" - $resultsXml - - """.trimIndent() + + $resultsXml + + """.trimIndent().trim() } else { resultsXml } - private fun removeXmlHeader(resultXml: String) = resultXml - .replace(Regex("""<\?xml.*\?>"""), "") + private fun removeXmlHeader(resultXml: String) = + resultXml + .replace(Regex("""<\?xml.*\?>"""), "") - private fun wrappedInTestSuitesWrapperXml(resultsXml: String) = """ - - $resultsXml - - """.trimIndent() + private fun wrappedInTestSuitesWrapperXml(resultsXml: String) = + """ + + + $resultsXml + + """.trimIndent().trim() } diff --git a/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsCypressProcessorSpec.kt b/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsCypressProcessorSpec.kt index 0ba65dee2..85924a2f4 100644 --- a/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsCypressProcessorSpec.kt +++ b/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsCypressProcessorSpec.kt @@ -25,8 +25,9 @@ class TestResultsCypressProcessorSpec : StringSpec({ "should parse multiple Cypress test results with file name in separate suite" { val testResultsProcessor = TestResultsProcessor() val resultsXmlLoader = ResultsXmlLoader() - val blob = resultsXmlLoader.cypressAttachmentsSpecWithFilePath() + - resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath() + val blob = + resultsXmlLoader.cypressAttachmentsSpecWithFilePath() + + resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath() val testSuiteList = testResultsProcessor.parseResultsBlob(blob) expectThat(testSuiteList).hasSize(4).any { @@ -56,8 +57,9 @@ class TestResultsCypressProcessorSpec : StringSpec({ "should filter out empty Cypress test suites" { val testResultsProcessor = TestResultsProcessor() val resultsXmlLoader = ResultsXmlLoader() - val blob = resultsXmlLoader.cypressEmptyTestSuites() + - resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath() + val blob = + resultsXmlLoader.cypressEmptyTestSuites() + + resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath() val testSuiteList = testResultsProcessor.parseResultsBlob(blob) expectThat(testSuiteList).hasSize(2).any { diff --git a/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsProcessorSpec.kt b/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsProcessorSpec.kt index 30e314964..fc2e33fa9 100644 --- a/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsProcessorSpec.kt +++ b/server/parsing/test-results-parser/src/test/kotlin/projektor/results/processor/TestResultsProcessorSpec.kt @@ -22,7 +22,7 @@ class TestResultsProcessorSpec : StringSpec({ .map(TestSuite::name) .contains( "test suite", - "test run with failed test cases" + "test run with failed test cases", ) } @@ -38,7 +38,7 @@ class TestResultsProcessorSpec : StringSpec({ .map(TestSuite::name) .contains( "projektor.example.spock.PassingSpec", - "projektor.example.spock.FailingSpec" + "projektor.example.spock.FailingSpec", ) } @@ -53,7 +53,7 @@ class TestResultsProcessorSpec : StringSpec({ .hasSize(1) .map(TestSuite::name) .contains( - "projektor.example.spock.PassingSpec" + "projektor.example.spock.PassingSpec", ) } @@ -68,7 +68,7 @@ class TestResultsProcessorSpec : StringSpec({ .hasSize(1) .map(TestSuite::name) .contains( - "pytest" + "pytest", ) } diff --git a/server/persistence/object-store/src/main/kotlin/projektor/objectstore/ObjectStoreClient.kt b/server/persistence/object-store/src/main/kotlin/projektor/objectstore/ObjectStoreClient.kt index 4b018edec..8e5a45ff2 100644 --- a/server/persistence/object-store/src/main/kotlin/projektor/objectstore/ObjectStoreClient.kt +++ b/server/persistence/object-store/src/main/kotlin/projektor/objectstore/ObjectStoreClient.kt @@ -13,10 +13,11 @@ import projektor.objectstore.bucket.BucketCreationException import java.io.InputStream class ObjectStoreClient(config: ObjectStoreConfig) { - private val minioClient = MinioClient.builder() - .endpoint(config.url) - .credentials(config.accessKey, config.secretKey) - .build() + private val minioClient = + MinioClient.builder() + .endpoint(config.url) + .credentials(config.accessKey, config.secretKey) + .build() fun createBucketIfNotExists(bucketName: String) { try { @@ -28,11 +29,16 @@ class ObjectStoreClient(config: ObjectStoreConfig) { } } - fun bucketExists(bucketName: String) = minioClient.bucketExists( - BucketExistsArgs.builder().bucket(bucketName).build() - ) + fun bucketExists(bucketName: String) = + minioClient.bucketExists( + BucketExistsArgs.builder().bucket(bucketName).build(), + ) - fun putObject(bucketName: String, objectName: String, stream: InputStream) { + fun putObject( + bucketName: String, + objectName: String, + stream: InputStream, + ) { minioClient.putObject( PutObjectArgs .builder() @@ -40,41 +46,50 @@ class ObjectStoreClient(config: ObjectStoreConfig) { .`object`(objectName) .stream(stream, -1, 10485760) .contentType("application/octet-stream") - .build() + .build(), ) } - fun getObject(bucketName: String, objectName: String): InputStream? = + fun getObject( + bucketName: String, + objectName: String, + ): InputStream? = try { minioClient.getObject( GetObjectArgs .builder() .bucket(bucketName) .`object`(objectName) - .build() + .build(), ) } catch (e: ErrorResponseException) { null } - fun removeObject(bucketName: String, objectName: String) { + fun removeObject( + bucketName: String, + objectName: String, + ) { minioClient.removeObject( RemoveObjectArgs .builder() .bucket(bucketName) .`object`(objectName) - .build() + .build(), ) } - fun removeObjects(bucketName: String, objectNames: List) { + fun removeObjects( + bucketName: String, + objectNames: List, + ) { val objects = objectNames.map { DeleteObject(it) } minioClient.removeObjects( RemoveObjectsArgs .builder() .bucket(bucketName) .objects(objects) - .build() + .build(), ) } } diff --git a/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectCleanupListener.kt b/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectCleanupListener.kt index 3ed4dddf8..b3a8c1d50 100644 --- a/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectCleanupListener.kt +++ b/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectCleanupListener.kt @@ -7,13 +7,16 @@ import io.kotest.core.test.TestResult class ObjectCleanupListener( private val objectStoreClient: ObjectStoreClient, private val bucketName: String, - private val objectName: String + private val objectName: String, ) : TestListener { override suspend fun beforeTest(testCase: TestCase) { objectStoreClient.createBucketIfNotExists(bucketName) } - override suspend fun afterTest(testCase: TestCase, result: TestResult) { + override suspend fun afterTest( + testCase: TestCase, + result: TestResult, + ) { objectStoreClient.removeObject(bucketName, objectName) } } diff --git a/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectStoreClientObjectSpec.kt b/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectStoreClientObjectSpec.kt index 259703272..2593ae747 100644 --- a/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectStoreClientObjectSpec.kt +++ b/server/persistence/object-store/src/test/kotlin/projektor/objectstore/ObjectStoreClientObjectSpec.kt @@ -26,12 +26,12 @@ class ObjectStoreClientObjectSpec : StringSpec() { .and { get { readBytes().decodeToString() }.isEqualTo("Here is a test file") } } - "when trying to get object that does not exist should return null"() { + "when trying to get object that does not exist should return null" { expectThat(client.getObject(bucketName, "objectDoesNotExist")) .isNull() } - "should delete object"() { + "should delete object" { client.putObject(bucketName, objectName, File("src/test/resources/test_file.txt").inputStream()) client.removeObject(bucketName, objectName) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/MathUtil.kt b/server/server-api/src/main/kotlin/projektor/server/api/MathUtil.kt index 299f2375d..0caa09cec 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/MathUtil.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/MathUtil.kt @@ -5,7 +5,10 @@ import java.math.MathContext import java.math.RoundingMode object MathUtil { - fun calculatePercentage(value: BigDecimal, total: BigDecimal): BigDecimal = + fun calculatePercentage( + value: BigDecimal, + total: BigDecimal, + ): BigDecimal = if (value > BigDecimal.ZERO && total > BigDecimal.ZERO) { value.divide(total, MathContext(4, RoundingMode.HALF_DOWN)) .times(BigDecimal(100.00)).setScale(2, RoundingMode.HALF_DOWN) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/PublicId.kt b/server/server-api/src/main/kotlin/projektor/server/api/PublicId.kt index 27e0af7ea..b4aefd95f 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/PublicId.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/PublicId.kt @@ -1,6 +1,5 @@ package projektor.server.api data class PublicId(val id: String) { - override fun toString() = id } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/TestFailure.kt b/server/server-api/src/main/kotlin/projektor/server/api/TestFailure.kt index 33416a994..3d20472d6 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/TestFailure.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/TestFailure.kt @@ -3,5 +3,5 @@ package projektor.server.api data class TestFailure( val failureMessage: String?, val failureType: String?, - val failureText: String? + val failureText: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/TestRunSummary.kt b/server/server-api/src/main/kotlin/projektor/server/api/TestRunSummary.kt index b5352953e..bc6e6cf9c 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/TestRunSummary.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/TestRunSummary.kt @@ -14,5 +14,5 @@ data class TestRunSummary( val averageDuration: BigDecimal, val slowestTestCaseDuration: BigDecimal, val createdTimestamp: Instant, - val wallClockDuration: BigDecimal? + val wallClockDuration: BigDecimal?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/TestSuite.kt b/server/server-api/src/main/kotlin/projektor/server/api/TestSuite.kt index 49406b50d..2104ebd39 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/TestSuite.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/TestSuite.kt @@ -19,5 +19,5 @@ data class TestSuite( val hasSystemErr: Boolean, val groupName: String?, val groupLabel: String?, - val testCases: List? + val testCases: List?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/attachments/AddAttachmentResponse.kt b/server/server-api/src/main/kotlin/projektor/server/api/attachments/AddAttachmentResponse.kt index d092ddda8..b4de8516d 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/attachments/AddAttachmentResponse.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/attachments/AddAttachmentResponse.kt @@ -2,11 +2,11 @@ package projektor.server.api.attachments data class AddAttachmentResponse( val name: String?, - val error: AddAttachmentError? + val error: AddAttachmentError?, ) enum class AddAttachmentError { ATTACHMENTS_DISABLED, ATTACHMENT_TOO_LARGE, - ATTACHMENT_FAILED + ATTACHMENT_FAILED, } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/attachments/Attachment.kt b/server/server-api/src/main/kotlin/projektor/server/api/attachments/Attachment.kt index 158deccf7..a65a6c027 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/attachments/Attachment.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/attachments/Attachment.kt @@ -2,9 +2,10 @@ package projektor.server.api.attachments data class Attachment(val fileName: String, val objectName: String, val fileSize: Long?) { val attachmentType: AttachmentType - get() = when { - fileName.endsWith(".png") || fileName.endsWith(".jpg") -> AttachmentType.IMAGE - fileName.endsWith(".mp4") -> AttachmentType.VIDEO - else -> AttachmentType.OTHER - } + get() = + when { + fileName.endsWith(".png") || fileName.endsWith(".jpg") -> AttachmentType.IMAGE + fileName.endsWith(".mp4") -> AttachmentType.VIDEO + else -> AttachmentType.OTHER + } } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/attachments/AttachmentType.kt b/server/server-api/src/main/kotlin/projektor/server/api/attachments/AttachmentType.kt index 9642c64ad..2c7229d40 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/attachments/AttachmentType.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/attachments/AttachmentType.kt @@ -3,5 +3,5 @@ package projektor.server.api.attachments enum class AttachmentType { IMAGE, VIDEO, - OTHER + OTHER, } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/coverage/Coverage.kt b/server/server-api/src/main/kotlin/projektor/server/api/coverage/Coverage.kt index d4346223c..63faf7c37 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/coverage/Coverage.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/coverage/Coverage.kt @@ -3,7 +3,7 @@ package projektor.server.api.coverage data class Coverage( val groups: List, val overallStats: CoverageStats, - val previousTestRunId: String? + val previousTestRunId: String?, ) { fun findCoverageGroup(name: String): CoverageGroup? = groups.find { it.name == name } } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageFile.kt b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageFile.kt index d07271541..1d783c736 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageFile.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageFile.kt @@ -6,5 +6,5 @@ data class CoverageFile( val missedLines: Array, val partialLines: Array, val stats: CoverageStats, - val filePath: String? + val filePath: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageGroup.kt b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageGroup.kt index 9a6e8f6c2..097a42243 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageGroup.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageGroup.kt @@ -2,5 +2,5 @@ package projektor.server.api.coverage class CoverageGroup( val name: String, - val stats: CoverageStats + val stats: CoverageStats, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStat.kt b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStat.kt index 73377a7ec..781cf43a8 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStat.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStat.kt @@ -6,7 +6,7 @@ import java.math.BigDecimal data class CoverageStat( val covered: Int, val missed: Int, - val coveredPercentageDelta: BigDecimal? = null + val coveredPercentageDelta: BigDecimal? = null, ) { var total: Int = 0 get() = covered + missed diff --git a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStats.kt b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStats.kt index 0f7cc94be..80f5f4d74 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStats.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/coverage/CoverageStats.kt @@ -3,5 +3,5 @@ package projektor.server.api.coverage data class CoverageStats( val statementStat: CoverageStat, val lineStat: CoverageStat, - val branchStat: CoverageStat + val branchStat: CoverageStat, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/error/FailureBodyType.kt b/server/server-api/src/main/kotlin/projektor/server/api/error/FailureBodyType.kt index 408519c25..9e9b03544 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/error/FailureBodyType.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/error/FailureBodyType.kt @@ -2,5 +2,5 @@ package projektor.server.api.error enum class FailureBodyType { COVERAGE, - TEST_RESULTS + TEST_RESULTS, } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/error/ResultsProcessingFailure.kt b/server/server-api/src/main/kotlin/projektor/server/api/error/ResultsProcessingFailure.kt index 81e89de48..35ec89646 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/error/ResultsProcessingFailure.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/error/ResultsProcessingFailure.kt @@ -7,5 +7,5 @@ data class ResultsProcessingFailure( val body: String, val bodyType: FailureBodyType, val createdTimestamp: Instant, - val failureMessage: String? + val failureMessage: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/metadata/TestRunGitMetadata.kt b/server/server-api/src/main/kotlin/projektor/server/api/metadata/TestRunGitMetadata.kt index c35a06463..76d9f9467 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/metadata/TestRunGitMetadata.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/metadata/TestRunGitMetadata.kt @@ -7,7 +7,7 @@ data class TestRunGitMetadata( val projectName: String?, val isMainBranch: Boolean, val pullRequestNumber: Int?, - val commitSha: String? + val commitSha: String?, ) { var gitHubBaseUrl: String? = null } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/organization/RepositoryCoverage.kt b/server/server-api/src/main/kotlin/projektor/server/api/organization/RepositoryCoverage.kt index 2af4de9d9..7de95967e 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/organization/RepositoryCoverage.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/organization/RepositoryCoverage.kt @@ -6,5 +6,5 @@ data class RepositoryCoverage( val publicId: String, val repoName: String, val projectName: String?, - val coverage: Coverage? + val coverage: Coverage?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/performance/PerformanceResult.kt b/server/server-api/src/main/kotlin/projektor/server/api/performance/PerformanceResult.kt index cf9953b6f..bba2f72d7 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/performance/PerformanceResult.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/performance/PerformanceResult.kt @@ -8,5 +8,5 @@ data class PerformanceResult( val requestCount: Long, val average: BigDecimal, val maximum: BigDecimal, - val p95: BigDecimal + val p95: BigDecimal, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/quality/CodeQualityReport.kt b/server/server-api/src/main/kotlin/projektor/server/api/quality/CodeQualityReport.kt index 9ab9ec17e..d4c32be96 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/quality/CodeQualityReport.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/quality/CodeQualityReport.kt @@ -4,5 +4,5 @@ data class CodeQualityReport( val idx: Int, val contents: String, val fileName: String, - val groupName: String? + val groupName: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/BranchType.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/BranchType.kt index 0690ff6d6..5a840d081 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/BranchType.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/BranchType.kt @@ -2,5 +2,5 @@ package projektor.server.api.repository enum class BranchType { MAINLINE, - ALL + ALL, } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryFlakyTests.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryFlakyTests.kt index 4723b2500..35dacf869 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryFlakyTests.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryFlakyTests.kt @@ -3,5 +3,5 @@ package projektor.server.api.repository data class RepositoryFlakyTests( val tests: List, val maxRuns: Int, - val failureCountThreshold: Int + val failureCountThreshold: Int, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryTestRunTimelineEntry.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryTestRunTimelineEntry.kt index e1faabe71..d6bb38e76 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryTestRunTimelineEntry.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/RepositoryTestRunTimelineEntry.kt @@ -10,7 +10,7 @@ data class RepositoryTestRunTimelineEntry( val cumulativeDuration: BigDecimal, val wallClockDuration: BigDecimal?, val totalTestCount: Int, - val passed: Boolean + val passed: Boolean, ) { val testAverageDuration: BigDecimal get() = calculateAverageDuration(cumulativeDuration, totalTestCount) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCoverageTimelineEntry.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCoverageTimelineEntry.kt index 7d193384c..2280169ef 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCoverageTimelineEntry.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCoverageTimelineEntry.kt @@ -6,5 +6,5 @@ import java.time.Instant data class RepositoryCoverageTimelineEntry( val publicId: String, val createdTimestamp: Instant, - val coverageStats: CoverageStats + val coverageStats: CoverageStats, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCurrentCoverage.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCurrentCoverage.kt index 63ddc579a..e4cdf4f6c 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCurrentCoverage.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/coverage/RepositoryCurrentCoverage.kt @@ -9,5 +9,5 @@ data class RepositoryCurrentCoverage( val coveredPercentage: BigDecimal?, val repo: String, val project: String?, - val branch: String? + val branch: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimeline.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimeline.kt index 9fa6776e7..690588af6 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimeline.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimeline.kt @@ -2,5 +2,5 @@ package projektor.server.api.repository.performance data class RepositoryPerformanceTestTimeline( val name: String, - val entries: List + val entries: List, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimelineEntry.kt b/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimelineEntry.kt index d578e4dc8..4eb50e1b5 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimelineEntry.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/repository/performance/RepositoryPerformanceTestTimelineEntry.kt @@ -6,5 +6,5 @@ import java.time.Instant data class RepositoryPerformanceTestTimelineEntry( val publicId: String, val createdTimestamp: Instant, - val performanceResult: PerformanceResult + val performanceResult: PerformanceResult, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessing.kt b/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessing.kt index c7c9e0765..97bf248c1 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessing.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessing.kt @@ -6,5 +6,5 @@ data class ResultsProcessing( val id: String, val status: ResultsProcessingStatus, val createdTimestamp: LocalDateTime?, - val errorMessage: String? + val errorMessage: String?, ) diff --git a/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessingStatus.kt b/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessingStatus.kt index 84bcdbc7e..bfa0d23bd 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessingStatus.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/results/ResultsProcessingStatus.kt @@ -5,5 +5,5 @@ enum class ResultsProcessingStatus { PROCESSING, SUCCESS, DELETED, - ERROR + ERROR, } diff --git a/server/server-api/src/main/kotlin/projektor/server/api/util/DurationUtil.kt b/server/server-api/src/main/kotlin/projektor/server/api/util/DurationUtil.kt index 6a863db1d..48051694f 100644 --- a/server/server-api/src/main/kotlin/projektor/server/api/util/DurationUtil.kt +++ b/server/server-api/src/main/kotlin/projektor/server/api/util/DurationUtil.kt @@ -6,7 +6,10 @@ import java.math.RoundingMode private val roundingMathContext = MathContext(3, RoundingMode.HALF_UP) -fun calculateAverageDuration(cumulativeDuration: BigDecimal, totalTestCount: Int): BigDecimal { +fun calculateAverageDuration( + cumulativeDuration: BigDecimal, + totalTestCount: Int, +): BigDecimal { return if (cumulativeDuration > BigDecimal.ZERO && totalTestCount > 0) { cumulativeDuration.divide(totalTestCount.toBigDecimal(), roundingMathContext) } else { diff --git a/server/server-app/src/main/kotlin/projektor/AppModule.kt b/server/server-app/src/main/kotlin/projektor/AppModule.kt index 27ba41b6d..0752b8d25 100644 --- a/server/server-app/src/main/kotlin/projektor/AppModule.kt +++ b/server/server-app/src/main/kotlin/projektor/AppModule.kt @@ -83,7 +83,7 @@ fun createAppModule( notificationConfig: NotificationConfig, processingConfig: ProcessingConfig, gitHubCommentService: GitHubCommentService?, - attachmentService: AttachmentService? + attachmentService: AttachmentService?, ) = module { single { dataSource } single { TestResultsProcessor() } diff --git a/server/server-app/src/main/kotlin/projektor/Application.kt b/server/server-app/src/main/kotlin/projektor/Application.kt index e51a1bf58..f08610984 100644 --- a/server/server-app/src/main/kotlin/projektor/Application.kt +++ b/server/server-app/src/main/kotlin/projektor/Application.kt @@ -103,17 +103,18 @@ fun Application.main(meterRegistry: MeterRegistry? = null) { val attachmentService = conditionallyCreateAttachmentService(applicationConfig, attachmentRepository) attachmentService?.conditionallyCreateBucketIfNotExists() - val appModule = createAppModule( - dataSource = dataSource, - authConfig = authConfig, - dslContext = dslContext, - metricRegistry = metricRegistry, - messageConfig = messageConfig, - notificationConfig = notificationConfig, - processingConfig = processingConfig, - gitHubCommentService = gitHubCommentService, - attachmentService = attachmentService - ) + val appModule = + createAppModule( + dataSource = dataSource, + authConfig = authConfig, + dslContext = dslContext, + metricRegistry = metricRegistry, + messageConfig = messageConfig, + notificationConfig = notificationConfig, + processingConfig = processingConfig, + gitHubCommentService = gitHubCommentService, + attachmentService = attachmentService, + ) install(CORS) { anyHost() @@ -173,7 +174,8 @@ fun Application.main(meterRegistry: MeterRegistry? = null) { val coverageService: CoverageService by inject() - val testRunCleanupService = TestRunCleanupService(cleanupConfig, testRunRepository, resultsProcessingRepository, coverageService, attachmentService) + val testRunCleanupService = + TestRunCleanupService(cleanupConfig, testRunRepository, resultsProcessingRepository, coverageService, attachmentService) val attachmentCleanupService = attachmentService?.let { AttachmentCleanupService(cleanupConfig, testRunRepository, attachmentService) } val scheduler: Scheduler by inject() CleanupScheduledJob.conditionallyStartCleanupScheduledJob(cleanupConfig, testRunCleanupService, attachmentCleanupService, scheduler) @@ -225,30 +227,36 @@ fun Application.main(meterRegistry: MeterRegistry? = null) { } } -private fun conditionallyCreateAttachmentService(applicationConfig: ApplicationConfig, attachmentRepository: AttachmentRepository): AttachmentService? = - if (AttachmentConfig.attachmentsEnabled(applicationConfig)) +private fun conditionallyCreateAttachmentService( + applicationConfig: ApplicationConfig, + attachmentRepository: AttachmentRepository, +): AttachmentService? = + if (AttachmentConfig.attachmentsEnabled(applicationConfig)) { AttachmentService(AttachmentConfig.createAttachmentConfig(applicationConfig), attachmentRepository) - else + } else { null + } private fun conditionallyCreateGitHubCommentService(applicationConfig: ApplicationConfig): GitHubCommentService? { val gitHubNotificationConfig = GitHubNotificationConfig.createGitHubNotificationConfig(applicationConfig) val (gitHubApiUrl, gitHubAppId, privateKey) = gitHubNotificationConfig return if (gitHubApiUrl != null && gitHubAppId != null && privateKey != null) { - val jwtTokenConfig = JwtTokenConfig( - gitHubAppId = gitHubAppId, - pemContents = privateKey, - ttlMillis = 60_000 - ) + val jwtTokenConfig = + JwtTokenConfig( + gitHubAppId = gitHubAppId, + pemContents = privateKey, + ttlMillis = 60_000, + ) val jwtProvider = JwtProvider(jwtTokenConfig) val gitHubClientConfig = GitHubClientConfig(gitHubApiUrl = gitHubApiUrl) - val gitHubCommentClient = GitHubCommentClient( - clientConfig = gitHubClientConfig, - jwtProvider = jwtProvider - ) + val gitHubCommentClient = + GitHubCommentClient( + clientConfig = gitHubClientConfig, + jwtProvider = jwtProvider, + ) GitHubCommentService(gitHubCommentClient) } else { diff --git a/server/server-app/src/main/kotlin/projektor/attachment/AddAttachmentResult.kt b/server/server-app/src/main/kotlin/projektor/attachment/AddAttachmentResult.kt index 6f086b6dd..8ce10ba06 100644 --- a/server/server-app/src/main/kotlin/projektor/attachment/AddAttachmentResult.kt +++ b/server/server-app/src/main/kotlin/projektor/attachment/AddAttachmentResult.kt @@ -2,5 +2,6 @@ package projektor.attachment sealed class AddAttachmentResult { object Success : AddAttachmentResult() + class Failure(val errorMessage: String?) : AddAttachmentResult() } diff --git a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentConfig.kt b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentConfig.kt index f2186df45..a2166460f 100644 --- a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentConfig.kt @@ -9,19 +9,20 @@ data class AttachmentConfig( val autoCreateBucket: Boolean, val accessKey: String, val secretKey: String, - val maxSizeMB: BigDecimal? + val maxSizeMB: BigDecimal?, ) { companion object { fun attachmentsEnabled(applicationConfig: ApplicationConfig): Boolean = applicationConfig.propertyOrNull("ktor.attachment.url")?.getString()?.isNotEmpty() ?: false - fun createAttachmentConfig(applicationConfig: ApplicationConfig) = AttachmentConfig( - applicationConfig.property("ktor.attachment.url").getString(), - applicationConfig.property("ktor.attachment.bucketName").getString(), - applicationConfig.propertyOrNull("ktor.attachment.autoCreateBucket")?.getString()?.toBoolean() ?: false, - applicationConfig.property("ktor.attachment.accessKey").getString(), - applicationConfig.property("ktor.attachment.secretKey").getString(), - applicationConfig.propertyOrNull("ktor.attachment.maxSizeMB")?.getString()?.toBigDecimal() - ) + fun createAttachmentConfig(applicationConfig: ApplicationConfig) = + AttachmentConfig( + applicationConfig.property("ktor.attachment.url").getString(), + applicationConfig.property("ktor.attachment.bucketName").getString(), + applicationConfig.propertyOrNull("ktor.attachment.autoCreateBucket")?.getString()?.toBoolean() ?: false, + applicationConfig.property("ktor.attachment.accessKey").getString(), + applicationConfig.property("ktor.attachment.secretKey").getString(), + applicationConfig.propertyOrNull("ktor.attachment.maxSizeMB")?.getString()?.toBigDecimal(), + ) } } diff --git a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentDatabaseRepository.kt index 445df5f2f..7503efb10 100644 --- a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentDatabaseRepository.kt @@ -12,7 +12,10 @@ import projektor.server.api.attachments.Attachment class AttachmentDatabaseRepository(private val dslContext: DSLContext) : AttachmentRepository { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) - override suspend fun addAttachment(publicId: PublicId, attachment: Attachment) { + override suspend fun addAttachment( + publicId: PublicId, + attachment: Attachment, + ) { withContext(Dispatchers.IO) { dslContext.transaction { configuration -> val attachmentDao = TestRunAttachmentDao(configuration) @@ -30,13 +33,16 @@ class AttachmentDatabaseRepository(private val dslContext: DSLContext) : Attachm .fetchInto(Attachment::class.java) } - override suspend fun deleteAttachment(publicId: PublicId, objectName: String) { + override suspend fun deleteAttachment( + publicId: PublicId, + objectName: String, + ) { withContext(Dispatchers.IO) { dslContext .deleteFrom(Tables.TEST_RUN_ATTACHMENT) .where( Tables.TEST_RUN_ATTACHMENT.TEST_RUN_PUBLIC_ID.eq(publicId.id) - .and(Tables.TEST_RUN_ATTACHMENT.OBJECT_NAME.eq(objectName)) + .and(Tables.TEST_RUN_ATTACHMENT.OBJECT_NAME.eq(objectName)), ) .execute() } diff --git a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentRepository.kt b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentRepository.kt index 5fe4938b6..37003857f 100644 --- a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentRepository.kt @@ -4,9 +4,15 @@ import projektor.server.api.PublicId import projektor.server.api.attachments.Attachment interface AttachmentRepository { - suspend fun addAttachment(publicId: PublicId, attachment: Attachment) + suspend fun addAttachment( + publicId: PublicId, + attachment: Attachment, + ) suspend fun listAttachments(publicId: PublicId): List - suspend fun deleteAttachment(publicId: PublicId, objectName: String) + suspend fun deleteAttachment( + publicId: PublicId, + objectName: String, + ) } diff --git a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentService.kt b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentService.kt index e13a39871..5b6bb7d81 100644 --- a/server/server-app/src/main/kotlin/projektor/attachment/AttachmentService.kt +++ b/server/server-app/src/main/kotlin/projektor/attachment/AttachmentService.kt @@ -13,7 +13,7 @@ import java.math.BigDecimal class AttachmentService( private val config: AttachmentConfig, - private val attachmentRepository: AttachmentRepository + private val attachmentRepository: AttachmentRepository, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -37,7 +37,12 @@ class AttachmentService( attachmentSizeInBytes.toBigDecimal() <= maxSizeInBytes } - suspend fun addAttachment(publicId: PublicId, fileName: String, attachmentStream: InputStream, attachmentSize: Long?): AddAttachmentResult { + suspend fun addAttachment( + publicId: PublicId, + fileName: String, + attachmentStream: InputStream, + attachmentSize: Long?, + ): AddAttachmentResult { val objectName = attachmentObjectName(publicId, fileName) return try { @@ -45,7 +50,10 @@ class AttachmentService( objectStoreClient.putObject(config.bucketName, objectName, attachmentStream) } - attachmentRepository.addAttachment(publicId, Attachment(fileName = fileName, objectName = objectName, fileSize = attachmentSize)) + attachmentRepository.addAttachment( + publicId, + Attachment(fileName = fileName, objectName = objectName, fileSize = attachmentSize), + ) AddAttachmentResult.Success } catch (e: Exception) { @@ -54,7 +62,10 @@ class AttachmentService( } } - suspend fun getAttachment(publicId: PublicId, attachmentFileName: String) = withContext(Dispatchers.IO) { + suspend fun getAttachment( + publicId: PublicId, + attachmentFileName: String, + ) = withContext(Dispatchers.IO) { objectStoreClient.getObject(config.bucketName, attachmentObjectName(publicId, attachmentFileName)) } @@ -71,6 +82,9 @@ class AttachmentService( } companion object { - fun attachmentObjectName(publicId: PublicId, attachmentFileName: String) = "${publicId.id}-$attachmentFileName" + fun attachmentObjectName( + publicId: PublicId, + attachmentFileName: String, + ) = "${publicId.id}-$attachmentFileName" } } diff --git a/server/server-app/src/main/kotlin/projektor/auth/AuthConfig.kt b/server/server-app/src/main/kotlin/projektor/auth/AuthConfig.kt index d9142041b..d3956d92f 100644 --- a/server/server-app/src/main/kotlin/projektor/auth/AuthConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/auth/AuthConfig.kt @@ -4,10 +4,11 @@ import io.ktor.server.config.ApplicationConfig data class AuthConfig(val publishToken: String?) { companion object { - const val PublishToken = "X-PROJEKTOR-TOKEN" + const val PUBLISH_TOKEN = "X-PROJEKTOR-TOKEN" - fun createAuthConfig(applicationConfig: ApplicationConfig) = AuthConfig( - applicationConfig.propertyOrNull("ktor.auth.publishToken")?.getString() - ) + fun createAuthConfig(applicationConfig: ApplicationConfig) = + AuthConfig( + applicationConfig.propertyOrNull("ktor.auth.publishToken")?.getString(), + ) } } diff --git a/server/server-app/src/main/kotlin/projektor/auth/AuthService.kt b/server/server-app/src/main/kotlin/projektor/auth/AuthService.kt index 22312edc6..962e8ca45 100644 --- a/server/server-app/src/main/kotlin/projektor/auth/AuthService.kt +++ b/server/server-app/src/main/kotlin/projektor/auth/AuthService.kt @@ -1,6 +1,5 @@ package projektor.auth class AuthService(private val authConfig: AuthConfig) { - fun isAuthValid(tokenFromRequest: String?) = - authConfig.publishToken.isNullOrEmpty() || authConfig.publishToken == tokenFromRequest + fun isAuthValid(tokenFromRequest: String?) = authConfig.publishToken.isNullOrEmpty() || authConfig.publishToken == tokenFromRequest } diff --git a/server/server-app/src/main/kotlin/projektor/badge/CoverageBadgeService.kt b/server/server-app/src/main/kotlin/projektor/badge/CoverageBadgeService.kt index 550446bd6..a5f93713e 100644 --- a/server/server-app/src/main/kotlin/projektor/badge/CoverageBadgeService.kt +++ b/server/server-app/src/main/kotlin/projektor/badge/CoverageBadgeService.kt @@ -10,23 +10,27 @@ import projektor.server.api.repository.BranchType class CoverageBadgeService( private val coverageService: CoverageService, private val previousTestRunService: PreviousTestRunService, - private val svgCoverageBadgeCreator: SvgCoverageBadgeCreator + private val svgCoverageBadgeCreator: SvgCoverageBadgeCreator, ) { - suspend fun createCoverageBadge(fullRepoName: String, projectName: String?): String? { + suspend fun createCoverageBadge( + fullRepoName: String, + projectName: String?, + ): String? { + val mostRecentRunWithCoverage = + previousTestRunService.findMostRecentRunWithCoverage( + fullRepoName, + projectName, + BranchSearch(branchType = BranchType.MAINLINE), + ) ?: previousTestRunService.findMostRecentRunWithCoverage( + fullRepoName, + projectName, + BranchSearch(branchType = BranchType.ALL), + ) - val mostRecentRunWithCoverage = previousTestRunService.findMostRecentRunWithCoverage( - fullRepoName, - projectName, - BranchSearch(branchType = BranchType.MAINLINE) - ) ?: previousTestRunService.findMostRecentRunWithCoverage( - fullRepoName, - projectName, - BranchSearch(branchType = BranchType.ALL) - ) - - val coveredPercentage = mostRecentRunWithCoverage?.publicId?.let { publicId -> - coverageService.getCoveredLinePercentage(publicId) - } + val coveredPercentage = + mostRecentRunWithCoverage?.publicId?.let { publicId -> + coverageService.getCoveredLinePercentage(publicId) + } return coveredPercentage?.let { svgCoverageBadgeCreator.createBadge(it) } } diff --git a/server/server-app/src/main/kotlin/projektor/badge/TestRunBadgeService.kt b/server/server-app/src/main/kotlin/projektor/badge/TestRunBadgeService.kt index 62da10731..045567666 100644 --- a/server/server-app/src/main/kotlin/projektor/badge/TestRunBadgeService.kt +++ b/server/server-app/src/main/kotlin/projektor/badge/TestRunBadgeService.kt @@ -22,12 +22,16 @@ class TestRunBadgeService( } } - suspend fun createTestsBadge(repoName: String, projectName: String?): String? { - val previousTestRun = previousTestRunService.findMostRecentRun( - repoName, - projectName, - BranchSearch(branchType = BranchType.MAINLINE) - ) + suspend fun createTestsBadge( + repoName: String, + projectName: String?, + ): String? { + val previousTestRun = + previousTestRunService.findMostRecentRun( + repoName, + projectName, + BranchSearch(branchType = BranchType.MAINLINE), + ) return if (previousTestRun != null) { testRunBadgeCreator.createBadge(previousTestRun.passed) diff --git a/server/server-app/src/main/kotlin/projektor/cleanup/AttachmentCleanupService.kt b/server/server-app/src/main/kotlin/projektor/cleanup/AttachmentCleanupService.kt index 75ce9267b..8cbcd0733 100644 --- a/server/server-app/src/main/kotlin/projektor/cleanup/AttachmentCleanupService.kt +++ b/server/server-app/src/main/kotlin/projektor/cleanup/AttachmentCleanupService.kt @@ -9,7 +9,7 @@ import java.time.LocalDate class AttachmentCleanupService( private val cleanupConfig: CleanupConfig, private val testRunRepository: TestRunRepository, - private val attachmentService: AttachmentService + private val attachmentService: AttachmentService, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -20,9 +20,10 @@ class AttachmentCleanupService( val createdBefore = LocalDate.now().minusDays(maxAttachmentAgeDays) val testRunsWithAttachmentsToDelete = testRunRepository.findTestRunsCreatedBeforeAndNotPinnedWithAttachments(createdBefore) - val testRunsWithAttachmentsDeleted = testRunsWithAttachmentsToDelete.mapNotNull { - conditionallyRemoveAttachments(it, cleanupConfig) - } + val testRunsWithAttachmentsDeleted = + testRunsWithAttachmentsToDelete.mapNotNull { + conditionallyRemoveAttachments(it, cleanupConfig) + } logger.info("Removed attachments from ${testRunsWithAttachmentsDeleted.size} test runs created before $createdBefore") @@ -33,7 +34,10 @@ class AttachmentCleanupService( listOf() } - private suspend fun conditionallyRemoveAttachments(publicId: PublicId, cleanupConfig: CleanupConfig): PublicId? = + private suspend fun conditionallyRemoveAttachments( + publicId: PublicId, + cleanupConfig: CleanupConfig, + ): PublicId? = try { if (!cleanupConfig.dryRun) { attachmentService.deleteAttachments(publicId) diff --git a/server/server-app/src/main/kotlin/projektor/cleanup/CleanupConfig.kt b/server/server-app/src/main/kotlin/projektor/cleanup/CleanupConfig.kt index 0121fb458..580b366fd 100644 --- a/server/server-app/src/main/kotlin/projektor/cleanup/CleanupConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/cleanup/CleanupConfig.kt @@ -5,7 +5,7 @@ import io.ktor.server.config.ApplicationConfig data class CleanupConfig( val maxReportAgeDays: Int?, val maxAttachmentAgeDays: Int?, - val dryRun: Boolean + val dryRun: Boolean, ) { val enabled: Boolean get() = reportCleanupEnabled || attachmentCleanupEnabled @@ -25,7 +25,7 @@ data class CleanupConfig( return CleanupConfig( maxReportAgeDays, maxAttachmentAgeDays, - dryRun + dryRun, ) } } diff --git a/server/server-app/src/main/kotlin/projektor/cleanup/CleanupScheduledJob.kt b/server/server-app/src/main/kotlin/projektor/cleanup/CleanupScheduledJob.kt index 78965d9ea..892f10e8e 100644 --- a/server/server-app/src/main/kotlin/projektor/cleanup/CleanupScheduledJob.kt +++ b/server/server-app/src/main/kotlin/projektor/cleanup/CleanupScheduledJob.kt @@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit class CleanupScheduledJob( private val testRunCleanupService: TestRunCleanupService, - private val attachmentCleanupService: AttachmentCleanupService? + private val attachmentCleanupService: AttachmentCleanupService?, ) : Runnable { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -24,21 +24,22 @@ class CleanupScheduledJob( } companion object { - const val cleanupJobName = "cleanup_old_test_runs" + const val CLEANUP_JOB_NAME = "cleanup_old_test_runs" fun conditionallyStartCleanupScheduledJob( cleanupConfig: CleanupConfig, testRunCleanupService: TestRunCleanupService, attachmentCleanupService: AttachmentCleanupService?, - scheduler: Scheduler + scheduler: Scheduler, ) { if (cleanupConfig.enabled) { val cleanupScheduledJob = CleanupScheduledJob(testRunCleanupService, attachmentCleanupService) - val job = ScheduledJob( - cleanupJobName, - cleanupScheduledJob, - ScheduleDelay(1, TimeUnit.DAYS) - ) + val job = + ScheduledJob( + CLEANUP_JOB_NAME, + cleanupScheduledJob, + ScheduleDelay(1, TimeUnit.DAYS), + ) scheduler.scheduleJob(job) } diff --git a/server/server-app/src/main/kotlin/projektor/cleanup/TestRunCleanupService.kt b/server/server-app/src/main/kotlin/projektor/cleanup/TestRunCleanupService.kt index 070362016..3c66ed9c1 100644 --- a/server/server-app/src/main/kotlin/projektor/cleanup/TestRunCleanupService.kt +++ b/server/server-app/src/main/kotlin/projektor/cleanup/TestRunCleanupService.kt @@ -14,7 +14,7 @@ class TestRunCleanupService( private val testRunRepository: TestRunRepository, private val resultsProcessingRepository: ResultsProcessingRepository, private val coverageService: CoverageService, - private val attachmentService: AttachmentService? + private val attachmentService: AttachmentService?, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -25,9 +25,10 @@ class TestRunCleanupService( val createdBefore = LocalDate.now().minusDays(maxReportAgeDays) val testRunsToCleanUp = testRunRepository.findTestRunsCreatedBeforeAndNotPinned(createdBefore) - val cleanedUpTestRunIds = testRunsToCleanUp.mapNotNull { - conditionallyCleanupTestRun(it, cleanupConfig) - } + val cleanedUpTestRunIds = + testRunsToCleanUp.mapNotNull { + conditionallyCleanupTestRun(it, cleanupConfig) + } logger.info("Removed ${cleanedUpTestRunIds.size} test runs created before $createdBefore") @@ -48,7 +49,10 @@ class TestRunCleanupService( resultsProcessingRepository.updateResultsProcessingStatus(publicId, ResultsProcessingStatus.DELETED) } - private suspend fun conditionallyCleanupTestRun(publicId: PublicId, cleanupConfig: CleanupConfig): PublicId? = + private suspend fun conditionallyCleanupTestRun( + publicId: PublicId, + cleanupConfig: CleanupConfig, + ): PublicId? = try { if (!cleanupConfig.dryRun) { cleanupTestRun(publicId) diff --git a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunDatabaseRepository.kt index 5d690a95f..994d7cd44 100644 --- a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunDatabaseRepository.kt @@ -17,32 +17,34 @@ import java.time.ZoneOffset class PreviousTestRunDatabaseRepository(private val dslContext: DSLContext) : PreviousTestRunRepository { override suspend fun findPreviousMainBranchRunWithCoverage(publicId: PublicId): PublicId? = withContext(Dispatchers.IO) { - val currentRunInfo = dslContext.select( - GIT_METADATA.REPO_NAME, - TEST_RUN.CREATED_TIMESTAMP, - GIT_METADATA.PROJECT_NAME - ) - .from(GIT_METADATA) - .innerJoin(TEST_RUN).on(GIT_METADATA.TEST_RUN_ID.eq(TEST_RUN.ID)) - .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) - .limit(1) - .fetchOneInto(CurrentRunInfo::class.java) + val currentRunInfo = + dslContext.select( + GIT_METADATA.REPO_NAME, + TEST_RUN.CREATED_TIMESTAMP, + GIT_METADATA.PROJECT_NAME, + ) + .from(GIT_METADATA) + .innerJoin(TEST_RUN).on(GIT_METADATA.TEST_RUN_ID.eq(TEST_RUN.ID)) + .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) + .limit(1) + .fetchOneInto(CurrentRunInfo::class.java) if (currentRunInfo != null) { - val previousPublicId = dslContext.select(TEST_RUN.PUBLIC_ID) - .from(TEST_RUN) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) - .where( - GIT_METADATA.IS_MAIN_BRANCH.eq(true) - .and(TEST_RUN.PUBLIC_ID.ne(publicId.id)) - .and(GIT_METADATA.REPO_NAME.eq(currentRunInfo.repoName)) - .and(withProjectName(currentRunInfo.projectName)) - .and(TEST_RUN.CREATED_TIMESTAMP.lessThan(currentRunInfo.createdTimestamp)) - ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) - .limit(1) - .fetchOne(TEST_RUN.PUBLIC_ID) + val previousPublicId = + dslContext.select(TEST_RUN.PUBLIC_ID) + .from(TEST_RUN) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) + .where( + GIT_METADATA.IS_MAIN_BRANCH.eq(true) + .and(TEST_RUN.PUBLIC_ID.ne(publicId.id)) + .and(GIT_METADATA.REPO_NAME.eq(currentRunInfo.repoName)) + .and(withProjectName(currentRunInfo.projectName)) + .and(TEST_RUN.CREATED_TIMESTAMP.lessThan(currentRunInfo.createdTimestamp)), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) + .limit(1) + .fetchOne(TEST_RUN.PUBLIC_ID) previousPublicId?.let { PublicId(it) } } else { @@ -50,53 +52,63 @@ class PreviousTestRunDatabaseRepository(private val dslContext: DSLContext) : Pr } } - override suspend fun findMostRecentRunWithCoverage(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? = + override suspend fun findMostRecentRunWithCoverage( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? = withContext(Dispatchers.IO) { - val recentTestRun = dslContext.select(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP, TEST_RUN.PASSED, GIT_METADATA.BRANCH_NAME) - .from(TEST_RUN) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) - .where( - GIT_METADATA.REPO_NAME.eq(repoName) - .and(withBranchType(branch?.branchType)) - .and(withBranchName(branch?.branchName)) - .and(withProjectName(projectName)) - ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) - .limit(1) - .fetchOne() + val recentTestRun = + dslContext.select(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP, TEST_RUN.PASSED, GIT_METADATA.BRANCH_NAME) + .from(TEST_RUN) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) + .where( + GIT_METADATA.REPO_NAME.eq(repoName) + .and(withBranchType(branch?.branchType)) + .and(withBranchName(branch?.branchName)) + .and(withProjectName(projectName)), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) + .limit(1) + .fetchOne() recentTestRun?.let { RecentTestRun( publicId = PublicId(it.component1()), createdTimestamp = it.component2().toInstant(ZoneOffset.UTC), passed = it.component3(), - branch = it.component4() + branch = it.component4(), ) } } - override suspend fun findMostRecentRun(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? = + override suspend fun findMostRecentRun( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? = withContext(Dispatchers.IO) { - val recentTestRun = dslContext.select(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP, TEST_RUN.PASSED, GIT_METADATA.BRANCH_NAME) - .from(TEST_RUN) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .where( - GIT_METADATA.REPO_NAME.eq(repoName) - .and(withBranchType(branch?.branchType)) - .and(withBranchName(branch?.branchName)) - .and(withProjectName(projectName)) - ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) - .limit(1) - .fetchOne() + val recentTestRun = + dslContext.select(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP, TEST_RUN.PASSED, GIT_METADATA.BRANCH_NAME) + .from(TEST_RUN) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .where( + GIT_METADATA.REPO_NAME.eq(repoName) + .and(withBranchType(branch?.branchType)) + .and(withBranchName(branch?.branchName)) + .and(withProjectName(projectName)), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) + .limit(1) + .fetchOne() recentTestRun?.let { RecentTestRun( publicId = PublicId(it.component1()), createdTimestamp = it.component2().toInstant(ZoneOffset.UTC), passed = it.component3(), - branch = it.component4() + branch = it.component4(), ) } } diff --git a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunRepository.kt b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunRepository.kt index 9dce294d2..6ab383b4f 100644 --- a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunRepository.kt @@ -6,7 +6,15 @@ import projektor.server.api.repository.BranchSearch interface PreviousTestRunRepository { suspend fun findPreviousMainBranchRunWithCoverage(publicId: PublicId): PublicId? - suspend fun findMostRecentRunWithCoverage(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? + suspend fun findMostRecentRunWithCoverage( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? - suspend fun findMostRecentRun(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? + suspend fun findMostRecentRun( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? } diff --git a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunService.kt b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunService.kt index 0a640aacc..e382545ab 100644 --- a/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunService.kt +++ b/server/server-app/src/main/kotlin/projektor/compare/PreviousTestRunService.kt @@ -7,9 +7,15 @@ class PreviousTestRunService(private val previousTestRunRepository: PreviousTest suspend fun findPreviousMainBranchRunWithCoverage(publicId: PublicId): PublicId? = previousTestRunRepository.findPreviousMainBranchRunWithCoverage(publicId) - suspend fun findMostRecentRunWithCoverage(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? = - previousTestRunRepository.findMostRecentRunWithCoverage(repoName, projectName, branch) + suspend fun findMostRecentRunWithCoverage( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? = previousTestRunRepository.findMostRecentRunWithCoverage(repoName, projectName, branch) - suspend fun findMostRecentRun(repoName: String, projectName: String?, branch: BranchSearch?): RecentTestRun? = - previousTestRunRepository.findMostRecentRun(repoName, projectName, branch) + suspend fun findMostRecentRun( + repoName: String, + projectName: String?, + branch: BranchSearch?, + ): RecentTestRun? = previousTestRunRepository.findMostRecentRun(repoName, projectName, branch) } diff --git a/server/server-app/src/main/kotlin/projektor/compare/RecentTestRun.kt b/server/server-app/src/main/kotlin/projektor/compare/RecentTestRun.kt index 08ee8e388..718c2b1a4 100644 --- a/server/server-app/src/main/kotlin/projektor/compare/RecentTestRun.kt +++ b/server/server-app/src/main/kotlin/projektor/compare/RecentTestRun.kt @@ -7,5 +7,5 @@ data class RecentTestRun( val publicId: PublicId, val createdTimestamp: Instant, val passed: Boolean, - val branch: String? + val branch: String?, ) diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageDatabaseRepository.kt index ffe57d2f6..8bc846995 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageDatabaseRepository.kt @@ -27,20 +27,23 @@ import kotlin.streams.toList class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageRepository { private val codeCoverageRunDao = CodeCoverageRunDao(dslContext.configuration()) - private val coverageReportMapper = JdbcMapperFactory.newInstance() - .addKeys("id") - .ignorePropertyNotFound() - .newMapper(CoverageReport::class.java) - - private val overallStatsMapper = JdbcMapperFactory.newInstance() - .addKeys("id") - .ignorePropertyNotFound() - .newMapper(CoverageReportStats::class.java) - - private val coverageFileMapper = JdbcMapperFactory.newInstance() - .addKeys("id") - .ignorePropertyNotFound() - .newMapper(CoverageFile::class.java) + private val coverageReportMapper = + JdbcMapperFactory.newInstance() + .addKeys("id") + .ignorePropertyNotFound() + .newMapper(CoverageReport::class.java) + + private val overallStatsMapper = + JdbcMapperFactory.newInstance() + .addKeys("id") + .ignorePropertyNotFound() + .newMapper(CoverageReportStats::class.java) + + private val coverageFileMapper = + JdbcMapperFactory.newInstance() + .addKeys("id") + .ignorePropertyNotFound() + .newMapper(CoverageFile::class.java) override suspend fun createOrGetCoverageRun(publicId: PublicId): CodeCoverageRun = withContext(Dispatchers.IO) { @@ -59,7 +62,7 @@ class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageR override suspend fun addCoverageReport( coverageRun: CodeCoverageRun, - coverageReport: CoverageReport + coverageReport: CoverageReport, ): CodeCoverageGroup = withContext(Dispatchers.IO) { val codeCoverageGroup = CodeCoverageGroup() @@ -91,83 +94,85 @@ class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageR override suspend fun upsertCoverageGroup( coverageRun: CodeCoverageRun, coverageReport: CoverageReport, - newLineStat: CoverageStat - ): Pair = withContext(Dispatchers.IO) { - val existingCoverageGroup = dslContext - .selectFrom(CODE_COVERAGE_GROUP) - .where( - CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID.eq(coverageRun.id) - .and(CODE_COVERAGE_GROUP.NAME.eq(coverageReport.name)) - ) - .fetchOneInto(CodeCoverageGroup::class.java) - - if (existingCoverageGroup == null) { - Pair(addCoverageReport(coverageRun, coverageReport), CoverageGroupStatus.NEW) - } else { - val codeCoverageStatsDao = CodeCoverageStatsDao(dslContext.configuration()) - val existingGroupStats = codeCoverageStatsDao.fetchOneById(existingCoverageGroup.statsId) - - existingGroupStats.lineCovered = newLineStat.covered - existingGroupStats.lineMissed = newLineStat.missed - existingGroupStats.branchCovered = 0 - existingGroupStats.branchMissed = 0 - existingGroupStats.statementCovered = 0 - existingGroupStats.statementMissed = 0 - codeCoverageStatsDao.update(existingGroupStats) - - Pair(existingCoverageGroup, CoverageGroupStatus.EXISTING) + newLineStat: CoverageStat, + ): Pair = + withContext(Dispatchers.IO) { + val existingCoverageGroup = + dslContext + .selectFrom(CODE_COVERAGE_GROUP) + .where( + CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID.eq(coverageRun.id) + .and(CODE_COVERAGE_GROUP.NAME.eq(coverageReport.name)), + ) + .fetchOneInto(CodeCoverageGroup::class.java) + + if (existingCoverageGroup == null) { + Pair(addCoverageReport(coverageRun, coverageReport), CoverageGroupStatus.NEW) + } else { + val codeCoverageStatsDao = CodeCoverageStatsDao(dslContext.configuration()) + val existingGroupStats = codeCoverageStatsDao.fetchOneById(existingCoverageGroup.statsId) + + existingGroupStats.lineCovered = newLineStat.covered + existingGroupStats.lineMissed = newLineStat.missed + existingGroupStats.branchCovered = 0 + existingGroupStats.branchMissed = 0 + existingGroupStats.statementCovered = 0 + existingGroupStats.statementMissed = 0 + codeCoverageStatsDao.update(existingGroupStats) + + Pair(existingCoverageGroup, CoverageGroupStatus.EXISTING) + } } - } override suspend fun insertCoverageFiles( coverageReportFiles: List, coverageRun: CodeCoverageRun, - coverageGroup: CodeCoverageGroup - ) = - withContext(Dispatchers.IO) { - dslContext.transaction { configuration -> - val codeCoverageFileDao = CodeCoverageFileDao(configuration) - val codeCoverageStatsDao = CodeCoverageStatsDao(configuration) + coverageGroup: CodeCoverageGroup, + ) = withContext(Dispatchers.IO) { + dslContext.transaction { configuration -> + val codeCoverageFileDao = CodeCoverageFileDao(configuration) + val codeCoverageStatsDao = CodeCoverageStatsDao(configuration) + + coverageReportFiles.forEach { reportFile -> + val reportFileStats = reportFile.stats + + val fileStats = CodeCoverageStats() + fileStats.codeCoverageRunId = coverageRun.id + fileStats.statementCovered = reportFileStats.statementStat.covered + fileStats.statementMissed = reportFileStats.statementStat.missed + fileStats.lineCovered = reportFileStats.lineStat.covered + fileStats.lineMissed = reportFileStats.lineStat.missed + fileStats.branchCovered = reportFileStats.branchStat.covered + fileStats.branchMissed = reportFileStats.branchStat.missed + fileStats.scope = "FILE" + codeCoverageStatsDao.insert(fileStats) + + val codeCoverageFile = CodeCoverageFile() + codeCoverageFile.codeCoverageRunId = coverageRun.id + codeCoverageFile.codeCoverageGroupId = coverageGroup.id + codeCoverageFile.statsId = fileStats.id + codeCoverageFile.fileName = reportFile.fileName + codeCoverageFile.directoryName = reportFile.directoryName + codeCoverageFile.filePath = reportFile.filePath + codeCoverageFile.missedLines = reportFile.missedLines + codeCoverageFile.partialLines = reportFile.partialLines - coverageReportFiles.forEach { reportFile -> - val reportFileStats = reportFile.stats - - val fileStats = CodeCoverageStats() - fileStats.codeCoverageRunId = coverageRun.id - fileStats.statementCovered = reportFileStats.statementStat.covered - fileStats.statementMissed = reportFileStats.statementStat.missed - fileStats.lineCovered = reportFileStats.lineStat.covered - fileStats.lineMissed = reportFileStats.lineStat.missed - fileStats.branchCovered = reportFileStats.branchStat.covered - fileStats.branchMissed = reportFileStats.branchStat.missed - fileStats.scope = "FILE" - codeCoverageStatsDao.insert(fileStats) - - val codeCoverageFile = CodeCoverageFile() - codeCoverageFile.codeCoverageRunId = coverageRun.id - codeCoverageFile.codeCoverageGroupId = coverageGroup.id - codeCoverageFile.statsId = fileStats.id - codeCoverageFile.fileName = reportFile.fileName - codeCoverageFile.directoryName = reportFile.directoryName - codeCoverageFile.filePath = reportFile.filePath - codeCoverageFile.missedLines = reportFile.missedLines - codeCoverageFile.partialLines = reportFile.partialLines - - codeCoverageFileDao.insert(codeCoverageFile) - } + codeCoverageFileDao.insert(codeCoverageFile) } } + } override suspend fun upsertCoverageFiles( coverageReportFiles: List, coverageRun: CodeCoverageRun, - coverageGroup: CodeCoverageGroup + coverageGroup: CodeCoverageGroup, ) = withContext(Dispatchers.IO) { - val currentCoverageFilePaths: List = dslContext - .select(CODE_COVERAGE_FILE.FILE_PATH) - .from(CODE_COVERAGE_FILE) - .where(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(coverageGroup.id)) - .fetchInto(String::class.java) + val currentCoverageFilePaths: List = + dslContext + .select(CODE_COVERAGE_FILE.FILE_PATH) + .from(CODE_COVERAGE_FILE) + .where(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(coverageGroup.id)) + .fetchInto(String::class.java) val existingCoverageFiles = coverageReportFiles.filter { currentCoverageFilePaths.contains(it.filePath) } val newCoverageFiles = coverageReportFiles.filter { !currentCoverageFilePaths.contains(it.filePath) } @@ -180,19 +185,20 @@ class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageR private suspend fun updateCoverageFiles( coverageReportFiles: List, coverageRun: CodeCoverageRun, - coverageGroup: CodeCoverageGroup + coverageGroup: CodeCoverageGroup, ) = withContext(Dispatchers.IO) { val codeCoverageFileDao = CodeCoverageFileDao(dslContext.configuration()) coverageReportFiles.forEach { reportFile -> - val codeCoverageFile = dslContext - .selectFrom(CODE_COVERAGE_FILE) - .where( - CODE_COVERAGE_FILE.FILE_PATH.eq(reportFile.filePath) - .and(CODE_COVERAGE_FILE.CODE_COVERAGE_RUN_ID.eq(coverageRun.id)) - .and(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(coverageGroup.id)) - ) - .fetchOneInto(CodeCoverageFile::class.java) + val codeCoverageFile = + dslContext + .selectFrom(CODE_COVERAGE_FILE) + .where( + CODE_COVERAGE_FILE.FILE_PATH.eq(reportFile.filePath) + .and(CODE_COVERAGE_FILE.CODE_COVERAGE_RUN_ID.eq(coverageRun.id)) + .and(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(coverageGroup.id)), + ) + .fetchOneInto(CodeCoverageFile::class.java) if (codeCoverageFile != null) { codeCoverageFile.missedLines = reportFile.missedLines @@ -214,23 +220,25 @@ class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageR override suspend fun fetchOverallStats(publicId: PublicId): CoverageReportStats = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - sum(CODE_COVERAGE_STATS.BRANCH_COVERED).`as`("branch_stat_covered"), - sum(CODE_COVERAGE_STATS.BRANCH_MISSED).`as`("branch_stat_missed"), - sum(CODE_COVERAGE_STATS.STATEMENT_COVERED).`as`("statement_stat_covered"), - sum(CODE_COVERAGE_STATS.STATEMENT_MISSED).`as`("statement_stat_missed"), - sum(CODE_COVERAGE_STATS.LINE_COVERED).`as`("line_stat_covered"), - sum(CODE_COVERAGE_STATS.LINE_MISSED).`as`("line_stat_missed") - ) - .from(CODE_COVERAGE_STATS) - .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_STATS.ID.eq(CODE_COVERAGE_GROUP.STATS_ID)) - .innerJoin(CODE_COVERAGE_RUN).on(CODE_COVERAGE_RUN.ID.eq(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID)) - .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP"))) - .fetchResultSet() - - val overallStatus: CoverageReportStats = resultSet.use { - overallStatsMapper.stream(resultSet).findFirst().orElse(null) - } + val resultSet = + dslContext.select( + sum(CODE_COVERAGE_STATS.BRANCH_COVERED).`as`("branch_stat_covered"), + sum(CODE_COVERAGE_STATS.BRANCH_MISSED).`as`("branch_stat_missed"), + sum(CODE_COVERAGE_STATS.STATEMENT_COVERED).`as`("statement_stat_covered"), + sum(CODE_COVERAGE_STATS.STATEMENT_MISSED).`as`("statement_stat_missed"), + sum(CODE_COVERAGE_STATS.LINE_COVERED).`as`("line_stat_covered"), + sum(CODE_COVERAGE_STATS.LINE_MISSED).`as`("line_stat_missed"), + ) + .from(CODE_COVERAGE_STATS) + .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_STATS.ID.eq(CODE_COVERAGE_GROUP.STATS_ID)) + .innerJoin(CODE_COVERAGE_RUN).on(CODE_COVERAGE_RUN.ID.eq(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID)) + .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP"))) + .fetchResultSet() + + val overallStatus: CoverageReportStats = + resultSet.use { + overallStatsMapper.stream(resultSet).findFirst().orElse(null) + } overallStatus } @@ -241,59 +249,66 @@ class CoverageDatabaseRepository(private val dslContext: DSLContext) : CoverageR dslContext.select(CODE_COVERAGE_RUN.ID) .from(CODE_COVERAGE_RUN) .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_RUN.ID.eq(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID)) - .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id)) + .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id)), ) } - override suspend fun fetchCoverageFiles(publicId: PublicId, groupName: String): List = + override suspend fun fetchCoverageFiles( + publicId: PublicId, + groupName: String, + ): List = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - CODE_COVERAGE_FILE.DIRECTORY_NAME, - CODE_COVERAGE_FILE.FILE_NAME, - CODE_COVERAGE_FILE.FILE_PATH, - CODE_COVERAGE_FILE.MISSED_LINES, - CODE_COVERAGE_FILE.PARTIAL_LINES, - CODE_COVERAGE_STATS.BRANCH_COVERED.`as`("stats_branch_stat_covered"), - CODE_COVERAGE_STATS.BRANCH_MISSED.`as`("stats_branch_stat_missed"), - CODE_COVERAGE_STATS.STATEMENT_COVERED.`as`("stats_statement_stat_covered"), - CODE_COVERAGE_STATS.STATEMENT_MISSED.`as`("stats_statement_stat_missed"), - CODE_COVERAGE_STATS.LINE_COVERED.`as`("stats_line_stat_covered"), - CODE_COVERAGE_STATS.LINE_MISSED.`as`("stats_line_stat_missed") - ) - .from(CODE_COVERAGE_FILE) - .innerJoin(CODE_COVERAGE_RUN).on(CODE_COVERAGE_FILE.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) - .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(CODE_COVERAGE_GROUP.ID)) - .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_FILE.STATS_ID.eq(CODE_COVERAGE_STATS.ID)) - .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_GROUP.NAME.eq(groupName))) - .fetchResultSet() - - val coverageFiles: List = resultSet.use { - coverageFileMapper.stream(resultSet).toList() - } + val resultSet = + dslContext.select( + CODE_COVERAGE_FILE.DIRECTORY_NAME, + CODE_COVERAGE_FILE.FILE_NAME, + CODE_COVERAGE_FILE.FILE_PATH, + CODE_COVERAGE_FILE.MISSED_LINES, + CODE_COVERAGE_FILE.PARTIAL_LINES, + CODE_COVERAGE_STATS.BRANCH_COVERED.`as`("stats_branch_stat_covered"), + CODE_COVERAGE_STATS.BRANCH_MISSED.`as`("stats_branch_stat_missed"), + CODE_COVERAGE_STATS.STATEMENT_COVERED.`as`("stats_statement_stat_covered"), + CODE_COVERAGE_STATS.STATEMENT_MISSED.`as`("stats_statement_stat_missed"), + CODE_COVERAGE_STATS.LINE_COVERED.`as`("stats_line_stat_covered"), + CODE_COVERAGE_STATS.LINE_MISSED.`as`("stats_line_stat_missed"), + ) + .from(CODE_COVERAGE_FILE) + .innerJoin(CODE_COVERAGE_RUN).on(CODE_COVERAGE_FILE.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) + .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_FILE.CODE_COVERAGE_GROUP_ID.eq(CODE_COVERAGE_GROUP.ID)) + .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_FILE.STATS_ID.eq(CODE_COVERAGE_STATS.ID)) + .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_GROUP.NAME.eq(groupName))) + .fetchResultSet() + + val coverageFiles: List = + resultSet.use { + coverageFileMapper.stream(resultSet).toList() + } coverageFiles } override suspend fun fetchCoverageList(publicId: PublicId): List = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - CODE_COVERAGE_GROUP.NAME.`as`("name"), - CODE_COVERAGE_STATS.BRANCH_COVERED.`as`("total_stats_branch_stat_covered"), - CODE_COVERAGE_STATS.BRANCH_MISSED.`as`("total_stats_branch_stat_missed"), - CODE_COVERAGE_STATS.STATEMENT_COVERED.`as`("total_stats_statement_stat_covered"), - CODE_COVERAGE_STATS.STATEMENT_MISSED.`as`("total_stats_statement_stat_missed"), - CODE_COVERAGE_STATS.LINE_COVERED.`as`("total_stats_line_stat_covered"), - CODE_COVERAGE_STATS.LINE_MISSED.`as`("total_stats_line_stat_missed") - ) - .from(CODE_COVERAGE_RUN) - .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_RUN.ID.eq(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID)) - .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_GROUP.STATS_ID.eq(CODE_COVERAGE_STATS.ID)) - .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP"))) - .fetchResultSet() - - val coverageReports: List = resultSet.use { - coverageReportMapper.stream(resultSet).toList() - } + val resultSet = + dslContext.select( + CODE_COVERAGE_GROUP.NAME.`as`("name"), + CODE_COVERAGE_STATS.BRANCH_COVERED.`as`("total_stats_branch_stat_covered"), + CODE_COVERAGE_STATS.BRANCH_MISSED.`as`("total_stats_branch_stat_missed"), + CODE_COVERAGE_STATS.STATEMENT_COVERED.`as`("total_stats_statement_stat_covered"), + CODE_COVERAGE_STATS.STATEMENT_MISSED.`as`("total_stats_statement_stat_missed"), + CODE_COVERAGE_STATS.LINE_COVERED.`as`("total_stats_line_stat_covered"), + CODE_COVERAGE_STATS.LINE_MISSED.`as`("total_stats_line_stat_missed"), + ) + .from(CODE_COVERAGE_RUN) + .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_RUN.ID.eq(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID)) + .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_GROUP.STATS_ID.eq(CODE_COVERAGE_STATS.ID)) + .where(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID.eq(publicId.id).and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP"))) + .fetchResultSet() + + val coverageReports: List = + resultSet.use { + coverageReportMapper.stream(resultSet).toList() + } coverageReports } diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageFileCombiner.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageFileCombiner.kt index 2e4c649b6..766317856 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageFileCombiner.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageFileCombiner.kt @@ -3,33 +3,42 @@ package projektor.coverage import projektor.server.api.coverage.CoverageFile import projektor.server.api.coverage.CoverageStat -fun combineCoverageFiles(existingCoverageFiles: List, incomingCoverageFiles: List): List { +fun combineCoverageFiles( + existingCoverageFiles: List, + incomingCoverageFiles: List, +): List { val existingFilePaths = existingCoverageFiles.mapNotNull { it.filePath } val coverageFilesToAdd = incomingCoverageFiles.filter { !existingFilePaths.contains(it.filePath) } - val updatedCoverageFiles = existingCoverageFiles.map { existingCoverageFile -> - val matchedIncomingCoverageFile = incomingCoverageFiles.find { it.filePath == existingCoverageFile.filePath } - - if (matchedIncomingCoverageFile != null) { - val totalLines = existingCoverageFile.stats.lineStat.total - val missedLines: Array = existingCoverageFile.missedLines.intersect(matchedIncomingCoverageFile.missedLines.toList()).toTypedArray() - - val newLineStat = CoverageStat( - covered = totalLines - missedLines.size, - missed = missedLines.size - ) - - existingCoverageFile.copy( - missedLines = missedLines, - stats = existingCoverageFile.stats.copy( - lineStat = newLineStat + val updatedCoverageFiles = + existingCoverageFiles.map { existingCoverageFile -> + val matchedIncomingCoverageFile = incomingCoverageFiles.find { it.filePath == existingCoverageFile.filePath } + + if (matchedIncomingCoverageFile != null) { + val totalLines = existingCoverageFile.stats.lineStat.total + val missedLines: Array = + existingCoverageFile.missedLines.intersect( + matchedIncomingCoverageFile.missedLines.toList(), + ).toTypedArray() + + val newLineStat = + CoverageStat( + covered = totalLines - missedLines.size, + missed = missedLines.size, + ) + + existingCoverageFile.copy( + missedLines = missedLines, + stats = + existingCoverageFile.stats.copy( + lineStat = newLineStat, + ), ) - ) - } else { - existingCoverageFile + } else { + existingCoverageFile + } } - } return updatedCoverageFiles + coverageFilesToAdd } diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageGroupStatus.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageGroupStatus.kt index cb4df3864..e6c8745d2 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageGroupStatus.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageGroupStatus.kt @@ -2,5 +2,5 @@ package projektor.coverage enum class CoverageGroupStatus { NEW, - EXISTING + EXISTING, } diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageMapper.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageMapper.kt index f605feac7..27343f342 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageMapper.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageMapper.kt @@ -14,20 +14,20 @@ fun CoverageReportStat.toCoverageStat(previousCoverageStats: CoverageStat?): Cov CoverageStat( covered = this.covered, missed = this.missed, - coveredPercentageDelta = previousCoverageStats?.let { this.percentCovered - it.coveredPercentage } + coveredPercentageDelta = previousCoverageStats?.let { this.percentCovered - it.coveredPercentage }, ) fun CoverageReportStats.toCoverageStats(previousCoverageStats: CoverageStats?): CoverageStats = CoverageStats( statementStat = this.statementStat.toCoverageStat(previousCoverageStats?.statementStat), lineStat = this.lineStat.toCoverageStat(previousCoverageStats?.lineStat), - branchStat = this.branchStat.toCoverageStat(previousCoverageStats?.branchStat) + branchStat = this.branchStat.toCoverageStat(previousCoverageStats?.branchStat), ) fun CoverageReport.toCoverageGroup(previousCoverage: Coverage?): CoverageGroup = CoverageGroup( name = name, - stats = totalStats.toCoverageStats(previousCoverage?.findCoverageGroup(name)?.stats) + stats = totalStats.toCoverageStats(previousCoverage?.findCoverageGroup(name)?.stats), ) fun CoverageReportFile.toCoverageFile(): CoverageFile = @@ -37,5 +37,5 @@ fun CoverageReportFile.toCoverageFile(): CoverageFile = missedLines = missedLines.toTypedArray(), partialLines = partialLines.toTypedArray(), stats = stats.toCoverageStats(null), - filePath = filePath + filePath = filePath, ) diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageRepository.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageRepository.kt index d3eeb7ef5..a6f77f18c 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageRepository.kt @@ -13,25 +13,25 @@ interface CoverageRepository { suspend fun addCoverageReport( coverageRun: CodeCoverageRun, - coverageReport: CoverageReport + coverageReport: CoverageReport, ): CodeCoverageGroup suspend fun upsertCoverageGroup( coverageRun: CodeCoverageRun, coverageReport: CoverageReport, - newLineStat: CoverageStat + newLineStat: CoverageStat, ): Pair suspend fun insertCoverageFiles( coverageReportFiles: List, coverageRun: CodeCoverageRun, - coverageGroup: CodeCoverageGroup + coverageGroup: CodeCoverageGroup, ) suspend fun upsertCoverageFiles( coverageReportFiles: List, coverageRun: CodeCoverageRun, - coverageGroup: CodeCoverageGroup + coverageGroup: CodeCoverageGroup, ) suspend fun fetchOverallStats(publicId: PublicId): CoverageReportStats @@ -40,7 +40,10 @@ interface CoverageRepository { suspend fun coverageGroupExists(publicId: PublicId): Boolean - suspend fun fetchCoverageFiles(publicId: PublicId, groupName: String): List + suspend fun fetchCoverageFiles( + publicId: PublicId, + groupName: String, + ): List suspend fun deleteCoverage(publicId: PublicId): Boolean } diff --git a/server/server-app/src/main/kotlin/projektor/coverage/CoverageService.kt b/server/server-app/src/main/kotlin/projektor/coverage/CoverageService.kt index 9962c307a..d8e8a67b1 100644 --- a/server/server-app/src/main/kotlin/projektor/coverage/CoverageService.kt +++ b/server/server-app/src/main/kotlin/projektor/coverage/CoverageService.kt @@ -24,12 +24,15 @@ class CoverageService( private val coverageRepository: CoverageRepository, private val metricsService: MetricsService, private val previousTestRunService: PreviousTestRunService, - private val processingFailureService: ProcessingFailureService + private val processingFailureService: ProcessingFailureService, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) private val coveragePayloadParser = CoveragePayloadParser() - suspend fun parseAndSaveReport(payload: String, publicId: PublicId): CoverageReport? = + suspend fun parseAndSaveReport( + payload: String, + publicId: PublicId, + ): CoverageReport? = try { val coverageFilePayload = coveragePayloadParser.parseCoverageFilePayload(payload) @@ -40,12 +43,15 @@ class CoverageService( publicId = publicId, body = payload, bodyType = FailureBodyType.COVERAGE, - e = e + e = e, ) throw e } - suspend fun saveReport(coverageFilePayload: CoverageFilePayload, publicId: PublicId): CoverageReport? = + suspend fun saveReport( + coverageFilePayload: CoverageFilePayload, + publicId: PublicId, + ): CoverageReport? = try { saveReportInternal(coverageFilePayload, publicId) } catch (e: Exception) { @@ -64,12 +70,15 @@ class CoverageService( publicId = publicId, body = coverageFilePayload.reportContents, bodyType = FailureBodyType.COVERAGE, - e = e + e = e, ) throw e } - private suspend fun saveReportInternal(coverageFilePayload: CoverageFilePayload, publicId: PublicId): CoverageReport? { + private suspend fun saveReportInternal( + coverageFilePayload: CoverageFilePayload, + publicId: PublicId, + ): CoverageReport? { metricsService.incrementCoverageProcessStartCounter() val coverageRun = coverageRepository.createOrGetCoverageRun(publicId) val coverageReport = CoverageParser.parseReport(coverageFilePayload.reportContents, coverageFilePayload.baseDirectoryPath) @@ -103,7 +112,7 @@ class CoverageService( Coverage( groups = coverageReports.map { it.toCoverageGroup(null) }, overallStats = overallStats.toCoverageStats(null), - previousTestRunId = null + previousTestRunId = null, ) } else { null @@ -123,7 +132,7 @@ class CoverageService( Coverage( groups = coverageReports.map { it.toCoverageGroup(previousCoverage) }, overallStats = overallStats.toCoverageStats(previousCoverage?.overallStats), - previousTestRunId = previousTestRun?.id + previousTestRunId = previousTestRun?.id, ) } else { null @@ -148,46 +157,51 @@ class CoverageService( } } - suspend fun coverageExists(publicId: PublicId): Boolean = - coverageRepository.coverageGroupExists(publicId) + suspend fun coverageExists(publicId: PublicId): Boolean = coverageRepository.coverageGroupExists(publicId) - suspend fun deleteCoverage(publicId: PublicId) = - coverageRepository.deleteCoverage(publicId) + suspend fun deleteCoverage(publicId: PublicId) = coverageRepository.deleteCoverage(publicId) - suspend fun getCoverageGroupFiles(publicId: PublicId, groupName: String): List = - coverageRepository.fetchCoverageFiles(publicId, groupName) + suspend fun getCoverageGroupFiles( + publicId: PublicId, + groupName: String, + ): List = coverageRepository.fetchCoverageFiles(publicId, groupName) suspend fun parseReport(coverageFilePayload: CoverageFilePayload): Pair>? = withContext(Dispatchers.IO) { val coverageReport = CoverageParser.parseReport(coverageFilePayload.reportContents, coverageFilePayload.baseDirectoryPath) coverageReport?.let { report -> - val coverageFiles = report.files?.let { fileList -> - fileList.map { it.toCoverageFile() } - } ?: listOf() + val coverageFiles = + report.files?.let { fileList -> + fileList.map { it.toCoverageFile() } + } ?: listOf() Pair(coverageReport, coverageFiles) } } - suspend fun appendCoverage(publicId: PublicId, coverageFiles: List) { + suspend fun appendCoverage( + publicId: PublicId, + coverageFiles: List, + ) { val coverageRun = coverageRepository.createOrGetCoverageRun(publicId) coverageFiles.forEach { coverageFilePayload -> - val parsedReport = try { - parseReport(coverageFilePayload) - } catch (e: Exception) { - logger.info("Problem parsing coverage report", e) - metricsService.incrementCoverageParseFailureCounter() - - processingFailureService.recordProcessingFailure( - publicId = publicId, - body = coverageFilePayload.reportContents, - bodyType = FailureBodyType.COVERAGE, - e = e - ) - null - } + val parsedReport = + try { + parseReport(coverageFilePayload) + } catch (e: Exception) { + logger.info("Problem parsing coverage report", e) + metricsService.incrementCoverageParseFailureCounter() + + processingFailureService.recordProcessingFailure( + publicId = publicId, + body = coverageFilePayload.reportContents, + bodyType = FailureBodyType.COVERAGE, + e = e, + ) + null + } if (parsedReport != null) { val (incomingCoverageReport, incomingCoverageFiles) = parsedReport @@ -203,11 +217,12 @@ class CoverageService( val newLineStat = CoverageStat(covered = coveredLines, missed = missedLines, coveredPercentageDelta = null) - val (coverageGroup, coverageGroupStatus) = coverageRepository.upsertCoverageGroup( - coverageRun, - incomingCoverageReport, - newLineStat - ) + val (coverageGroup, coverageGroupStatus) = + coverageRepository.upsertCoverageGroup( + coverageRun, + incomingCoverageReport, + newLineStat, + ) if (coverageGroupStatus == CoverageGroupStatus.NEW) { coverageRepository.insertCoverageFiles( @@ -226,7 +241,7 @@ class CoverageService( publicId = publicId, body = coverageFilePayload.reportContents, bodyType = FailureBodyType.COVERAGE, - e = e + e = e, ) } } diff --git a/server/server-app/src/main/kotlin/projektor/database/DataSourceConfig.kt b/server/server-app/src/main/kotlin/projektor/database/DataSourceConfig.kt index 1db8cdac8..603d524d7 100644 --- a/server/server-app/src/main/kotlin/projektor/database/DataSourceConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/database/DataSourceConfig.kt @@ -18,18 +18,22 @@ data class DataSourceConfig( val username: String, val password: String, val schema: String, - val maximumPoolSize: Int + val maximumPoolSize: Int, ) { companion object { - fun createDataSourceConfig(applicationConfig: ApplicationConfig) = DataSourceConfig( - applicationConfig.property("ktor.datasource.jdbcUrl").getString(), - applicationConfig.property("ktor.datasource.username").getString(), - applicationConfig.property("ktor.datasource.password").getString(), - applicationConfig.property("ktor.datasource.schema").getString(), - applicationConfig.property("ktor.datasource.maximumPoolSize").getString().toInt() - ) + fun createDataSourceConfig(applicationConfig: ApplicationConfig) = + DataSourceConfig( + applicationConfig.property("ktor.datasource.jdbcUrl").getString(), + applicationConfig.property("ktor.datasource.username").getString(), + applicationConfig.property("ktor.datasource.password").getString(), + applicationConfig.property("ktor.datasource.schema").getString(), + applicationConfig.property("ktor.datasource.maximumPoolSize").getString().toInt(), + ) - fun createDataSource(dataSourceConfig: DataSourceConfig, metricRegistry: MeterRegistry): HikariDataSource { + fun createDataSource( + dataSourceConfig: DataSourceConfig, + metricRegistry: MeterRegistry, + ): HikariDataSource { val hikariConfig = HikariConfig() hikariConfig.username = dataSourceConfig.username hikariConfig.password = dataSourceConfig.password @@ -43,24 +47,32 @@ data class DataSourceConfig( return dataSource } - fun flywayMigrate(dataSource: DataSource, dataSourceConfig: DataSourceConfig) { - val flyway = Flyway.configure() - .dataSource(dataSource) - .schemas(dataSourceConfig.schema) - .load() + fun flywayMigrate( + dataSource: DataSource, + dataSourceConfig: DataSourceConfig, + ) { + val flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(dataSourceConfig.schema) + .load() flyway.migrate() } - fun createDSLContext(dataSource: DataSource, dataSourceConfig: DataSourceConfig): DSLContext { - val settings = Settings() - .withRenderMapping( - RenderMapping() - .withSchemata( - MappedSchema().withInput("public") - .withOutput(dataSourceConfig.schema) - ) - ) + fun createDSLContext( + dataSource: DataSource, + dataSourceConfig: DataSourceConfig, + ): DSLContext { + val settings = + Settings() + .withRenderMapping( + RenderMapping() + .withSchemata( + MappedSchema().withInput("public") + .withOutput(dataSourceConfig.schema), + ), + ) return DSL.using(dataSource, SQLDialect.POSTGRES, settings) } diff --git a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureDatabaseRepository.kt index 0f2ce41dd..b0aa53280 100644 --- a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureDatabaseRepository.kt @@ -15,7 +15,12 @@ import projektor.database.generated.tables.pojos.ResultsProcessingFailure as Res class ProcessingFailureDatabaseRepository(private val dslContext: DSLContext) : ProcessingFailureRepository { private val resultsProcessingFailureDao = ResultsProcessingFailureDao(dslContext.configuration()) - override suspend fun recordProcessingFailure(publicId: PublicId, body: String, bodyType: FailureBodyType, failureMessage: String?): ResultsProcessingFailure { + override suspend fun recordProcessingFailure( + publicId: PublicId, + body: String, + bodyType: FailureBodyType, + failureMessage: String?, + ): ResultsProcessingFailure { val resultsProcessingFailureDB = ResultsProcessingFailureDB() resultsProcessingFailureDB.publicId = publicId.id resultsProcessingFailureDB.body = body @@ -29,7 +34,7 @@ class ProcessingFailureDatabaseRepository(private val dslContext: DSLContext) : body = body, bodyType = bodyType, failureMessage = failureMessage, - createdTimestamp = resultsProcessingFailureDB.createdTimestamp.toInstant(ZoneOffset.UTC) + createdTimestamp = resultsProcessingFailureDB.createdTimestamp.toInstant(ZoneOffset.UTC), ) } diff --git a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureRepository.kt b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureRepository.kt index bebd36905..1c0f5177e 100644 --- a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureRepository.kt @@ -5,7 +5,12 @@ import projektor.server.api.error.FailureBodyType import projektor.server.api.error.ResultsProcessingFailure interface ProcessingFailureRepository { - suspend fun recordProcessingFailure(publicId: PublicId, body: String, bodyType: FailureBodyType, failureMessage: String?): ResultsProcessingFailure + suspend fun recordProcessingFailure( + publicId: PublicId, + body: String, + bodyType: FailureBodyType, + failureMessage: String?, + ): ResultsProcessingFailure suspend fun fetchRecentProcessingFailures(failureCount: Int): List } diff --git a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureService.kt b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureService.kt index 2a9e454d9..7dfab3fa8 100644 --- a/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureService.kt +++ b/server/server-app/src/main/kotlin/projektor/error/ProcessingFailureService.kt @@ -5,13 +5,17 @@ import projektor.server.api.error.FailureBodyType import projektor.server.api.error.ResultsProcessingFailure class ProcessingFailureService(private val processingFailureRepository: ProcessingFailureRepository) { - - suspend fun recordProcessingFailure(publicId: PublicId, body: String, bodyType: FailureBodyType, e: Exception) { + suspend fun recordProcessingFailure( + publicId: PublicId, + body: String, + bodyType: FailureBodyType, + e: Exception, + ) { processingFailureRepository.recordProcessingFailure( publicId = publicId, body = body, bodyType = bodyType, - failureMessage = e.message + failureMessage = e.message, ) } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/AppendTestResultsService.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/AppendTestResultsService.kt index 9472c37bd..05514b9bd 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/AppendTestResultsService.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/AppendTestResultsService.kt @@ -10,22 +10,33 @@ import projektor.testsuite.TestSuiteRepository class AppendTestResultsService( private val testRunRepository: TestRunRepository, - private val testSuiteRepository: TestSuiteRepository + private val testSuiteRepository: TestSuiteRepository, ) { - suspend fun findExistingTestRunWithGroup(group: String?, repoName: String?): PublicId? = + suspend fun findExistingTestRunWithGroup( + group: String?, + repoName: String?, + ): PublicId? = if (group != null && repoName != null) { testRunRepository.findTestRunWithGroup(group, repoName) } else { null } - suspend fun appendGroupedTestRun(existingPublicId: PublicId, groupedResults: GroupedResults): Pair = + suspend fun appendGroupedTestRun( + existingPublicId: PublicId, + groupedResults: GroupedResults, + ): Pair = withContext(Dispatchers.IO) { // Find the highest test suite index for the existing public ID val highestExistingTestSuiteIdx = testSuiteRepository.fetchHighestTestSuiteIndex(existingPublicId) ?: 0 // Save the test suites, starting with that highest index - val testRunId = testRunRepository.appendTestSuites(existingPublicId, highestExistingTestSuiteIdx + 1, groupedResults.groupedTestSuites) + val testRunId = + testRunRepository.appendTestSuites( + existingPublicId, + highestExistingTestSuiteIdx + 1, + groupedResults.groupedTestSuites, + ) // Fetch back all the test suites val allTestSuites = testSuiteRepository.fetchTestSuitesWithCases(existingPublicId) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedResultsConverter.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedResultsConverter.kt index 41ebf11c5..6c7465ea9 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedResultsConverter.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedResultsConverter.kt @@ -16,72 +16,84 @@ import projektor.server.api.quality.CodeQualityReport class GroupedResultsConverter( private val groupedResultsParser: GroupedResultsParser, private val performanceResultsParser: PerformanceResultsParser, - private val testResultsProcessor: TestResultsProcessor + private val testResultsProcessor: TestResultsProcessor, ) { - suspend fun parseAndConvertGroupedResults(groupedResultsBlob: String): GroupedResults = withContext(Dispatchers.IO) { - val incomingGroupedResults = groupedResultsParser.parseGroupedResults(groupedResultsBlob) + suspend fun parseAndConvertGroupedResults(groupedResultsBlob: String): GroupedResults = + withContext(Dispatchers.IO) { + val incomingGroupedResults = groupedResultsParser.parseGroupedResults(groupedResultsBlob) - val groupedTestSuites = incomingGroupedResults.groupedTestSuites?.map { - val nonEmptyTestSuites = testResultsProcessor.parseResultsBlob(it.testSuitesBlob) - .filter { testSuite -> !testSuite.testCases.isNullOrEmpty() } + val groupedTestSuites = + incomingGroupedResults.groupedTestSuites?.map { + val nonEmptyTestSuites = + testResultsProcessor.parseResultsBlob(it.testSuitesBlob) + .filter { testSuite -> !testSuite.testCases.isNullOrEmpty() } - GroupedTestSuites( - groupName = it.groupName, - groupLabel = it.groupLabel, - directory = it.directory, - testSuites = nonEmptyTestSuites - ) - } ?: listOf() + GroupedTestSuites( + groupName = it.groupName, + groupLabel = it.groupLabel, + directory = it.directory, + testSuites = nonEmptyTestSuites, + ) + } ?: listOf() - val metadata = incomingGroupedResults.metadata?.let { metadata -> - ResultsMetadata( - git = metadata.git?.let { gitMetadata -> - GitMetadata( - repoName = gitMetadata.repoName, - projectName = gitMetadata.projectName, - branchName = gitMetadata.branchName, - isMainBranch = gitMetadata.isMainBranch, - commitSha = gitMetadata.commitSha, - pullRequestNumber = gitMetadata.pullRequestNumber + val metadata = + incomingGroupedResults.metadata?.let { metadata -> + ResultsMetadata( + git = + metadata.git?.let { gitMetadata -> + GitMetadata( + repoName = gitMetadata.repoName, + projectName = gitMetadata.projectName, + branchName = gitMetadata.branchName, + isMainBranch = gitMetadata.isMainBranch, + commitSha = gitMetadata.commitSha, + pullRequestNumber = gitMetadata.pullRequestNumber, + ) + }, + ci = metadata.ci, + group = metadata.group, ) - }, - ci = metadata.ci, - group = metadata.group - ) - } + } - val performanceResults = incomingGroupedResults.performanceResults?.mapNotNull { perfResults -> - val parsedResults = performanceResultsParser.parseResults(perfResults.resultsBlob) + val performanceResults = + incomingGroupedResults.performanceResults?.mapNotNull { perfResults -> + val parsedResults = performanceResultsParser.parseResults(perfResults.resultsBlob) - if (parsedResults != null) PerformanceResult( - name = perfResults.name, - requestCount = parsedResults.requestStats.count, - requestsPerSecond = parsedResults.requestStats.ratePerSecond, - average = parsedResults.performanceStats.average, - maximum = parsedResults.performanceStats.maximum, - p95 = parsedResults.performanceStats.p95 - ) else null - } ?: listOf() + if (parsedResults != null) { + PerformanceResult( + name = perfResults.name, + requestCount = parsedResults.requestStats.count, + requestsPerSecond = parsedResults.requestStats.ratePerSecond, + average = parsedResults.performanceStats.average, + maximum = parsedResults.performanceStats.maximum, + p95 = parsedResults.performanceStats.p95, + ) + } else { + null + } + } ?: listOf() - GroupedResults( - groupedTestSuites = groupedTestSuites, - performanceResults = performanceResults, - metadata = metadata, - wallClockDuration = incomingGroupedResults.wallClockDuration, - coverageFiles = incomingGroupedResults.coverageFiles?.map { incomingCoverageFile -> - CoverageFilePayload( - reportContents = incomingCoverageFile.reportContents, - baseDirectoryPath = incomingCoverageFile.baseDirectoryPath - ) - }, - codeQualityReports = incomingGroupedResults.codeQualityFiles?.mapIndexed { idx, codeQualityReport -> - CodeQualityReport( - idx = idx + 1, - contents = codeQualityReport.contents, - fileName = codeQualityReport.fileName, - groupName = codeQualityReport.groupName - ) - } - ) - } + GroupedResults( + groupedTestSuites = groupedTestSuites, + performanceResults = performanceResults, + metadata = metadata, + wallClockDuration = incomingGroupedResults.wallClockDuration, + coverageFiles = + incomingGroupedResults.coverageFiles?.map { incomingCoverageFile -> + CoverageFilePayload( + reportContents = incomingCoverageFile.reportContents, + baseDirectoryPath = incomingCoverageFile.baseDirectoryPath, + ) + }, + codeQualityReports = + incomingGroupedResults.codeQualityFiles?.mapIndexed { idx, codeQualityReport -> + CodeQualityReport( + idx = idx + 1, + contents = codeQualityReport.contents, + fileName = codeQualityReport.fileName, + groupName = codeQualityReport.groupName, + ) + }, + ) + } } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedTestResultsService.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedTestResultsService.kt index 90e8c48b5..90121ea0a 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedTestResultsService.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/GroupedTestResultsService.kt @@ -34,7 +34,7 @@ class GroupedTestResultsService( private val gitHubPullRequestCommentService: GitHubPullRequestCommentService, private val coverageService: CoverageService, private val appendTestResultsService: AppendTestResultsService, - private val codeQualityReportRepository: CodeQualityReportRepository + private val codeQualityReportRepository: CodeQualityReportRepository, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -49,23 +49,24 @@ class GroupedTestResultsService( val span = tracer.startSpanWithParent("projektor.parseGroupedResults") - val groupedResults = try { - groupedResultsConverter.parseAndConvertGroupedResults(groupedResultsBlob) - } catch (e: JsonProcessingException) { - val errorMessage = "Problem parsing test results: ${e.message}" - logger.info(errorMessage, e) - metricsService.incrementResultsParseFailureCounter() - testResultsProcessingService.recordResultsProcessingError(publicId, groupedResultsBlob, errorMessage) - throw PersistTestResultsException(publicId, errorMessage, e) - } catch (e: Exception) { - val errorMessage = "Error persisting test results: ${e.message}" - logger.error(errorMessage, e) - metricsService.incrementResultsProcessFailureCounter() - testResultsProcessingService.recordResultsProcessingError(publicId, groupedResultsBlob, errorMessage) - throw PersistTestResultsException(publicId, errorMessage, e) - } finally { - span.end() - } + val groupedResults = + try { + groupedResultsConverter.parseAndConvertGroupedResults(groupedResultsBlob) + } catch (e: JsonProcessingException) { + val errorMessage = "Problem parsing test results: ${e.message}" + logger.info(errorMessage, e) + metricsService.incrementResultsParseFailureCounter() + testResultsProcessingService.recordResultsProcessingError(publicId, groupedResultsBlob, errorMessage) + throw PersistTestResultsException(publicId, errorMessage, e) + } catch (e: Exception) { + val errorMessage = "Error persisting test results: ${e.message}" + logger.error(errorMessage, e) + metricsService.incrementResultsProcessFailureCounter() + testResultsProcessingService.recordResultsProcessingError(publicId, groupedResultsBlob, errorMessage) + throw PersistTestResultsException(publicId, errorMessage, e) + } finally { + span.end() + } val group = groupedResults.metadata?.group val repoAndOrgName = groupedResults.metadata?.git?.repoName @@ -84,13 +85,18 @@ class GroupedTestResultsService( return existingPublicIdWithGroup ?: publicId } - suspend fun doPersistTestResults(publicId: PublicId, groupedResults: GroupedResults, groupedResultsBlob: String) { + suspend fun doPersistTestResults( + publicId: PublicId, + groupedResults: GroupedResults, + groupedResultsBlob: String, + ) { try { val (testRunId, testRunSummary) = testRunRepository.saveGroupedTestRun(publicId, groupedResults) - val performanceResults = groupedResults.performanceResults.map { performanceResult -> - performanceResultsRepository.savePerformanceResults(testRunId, publicId, performanceResult) - } + val performanceResults = + groupedResults.performanceResults.map { performanceResult -> + performanceResultsRepository.savePerformanceResults(testRunId, publicId, performanceResult) + } testResultsProcessingService.updateResultsProcessingStatus(publicId, ResultsProcessingStatus.SUCCESS) @@ -110,7 +116,7 @@ class GroupedTestResultsService( testRunMetadataRepository.updateGitMetadata( testRunId = testRunId, pullRequestNumber = pullRequestNumber, - commitSha = groupedResults.metadata.git.commitSha + commitSha = groupedResults.metadata.git.commitSha, ) } } catch (e: Exception) { @@ -121,17 +127,22 @@ class GroupedTestResultsService( } } - private suspend fun doAppendTestResults(publicId: PublicId, groupedResults: GroupedResults, groupedResultsBlob: String) { + private suspend fun doAppendTestResults( + publicId: PublicId, + groupedResults: GroupedResults, + groupedResultsBlob: String, + ) { try { val (testRunId, testRunSummary) = appendTestResultsService.appendGroupedTestRun(publicId, groupedResults) metricsService.incrementResultsProcessSuccessCounter() - val coverage = groupedResults.coverageFiles?.let { - coverageService.appendCoverage(publicId, it) + val coverage = + groupedResults.coverageFiles?.let { + coverageService.appendCoverage(publicId, it) - coverageService.getCoverage(publicId) - } + coverageService.getCoverage(publicId) + } groupedResults.codeQualityReports?.let { codeQualityReportRepository.insertCodeQualityReports(testRunId, it) @@ -146,7 +157,10 @@ class GroupedTestResultsService( } } - private suspend fun saveCoverage(publicId: PublicId, coverageFiles: List): Coverage? { + private suspend fun saveCoverage( + publicId: PublicId, + coverageFiles: List, + ): Coverage? { coverageService.appendCoverage(publicId, coverageFiles) return coverageService.getCoverageWithPreviousRunComparison(publicId) @@ -156,13 +170,15 @@ class GroupedTestResultsService( testRunSummary: TestRunSummary, gitMetadata: GitMetadata?, coverage: Coverage?, - performanceResults: List? + performanceResults: List?, ): PullRequest? = try { val pullRequest = gitHubPullRequestCommentService.upsertComment(testRunSummary, gitMetadata, coverage, performanceResults) if (pullRequest != null) { - logger.info("Successfully commented on pull request ${pullRequest.number} in ${pullRequest.orgName}/${pullRequest.repoName}") + logger.info( + "Successfully commented on pull request ${pullRequest.number} in ${pullRequest.orgName}/${pullRequest.repoName}", + ) metricsService.incrementPullRequestCommentSuccessCounter() } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/PersistTestResultsException.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/PersistTestResultsException.kt index 6f0586a5e..9e6cde612 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/PersistTestResultsException.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/PersistTestResultsException.kt @@ -2,4 +2,7 @@ package projektor.incomingresults import projektor.server.api.PublicId -data class PersistTestResultsException(val publicId: PublicId, val errorMessage: String, override val cause: Throwable) : RuntimeException(errorMessage, cause) +data class PersistTestResultsException(val publicId: PublicId, val errorMessage: String, override val cause: Throwable) : RuntimeException( + errorMessage, + cause, +) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsProcessingService.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsProcessingService.kt index 0dcd1cc2a..5742fb153 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsProcessingService.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsProcessingService.kt @@ -6,17 +6,21 @@ import projektor.server.api.results.ResultsProcessing import projektor.server.api.results.ResultsProcessingStatus class TestResultsProcessingService( - private val resultsProcessingRepository: ResultsProcessingRepository + private val resultsProcessingRepository: ResultsProcessingRepository, ) { - suspend fun createResultsProcessing(publicId: PublicId) = - resultsProcessingRepository.createResultsProcessing(publicId) + suspend fun createResultsProcessing(publicId: PublicId) = resultsProcessingRepository.createResultsProcessing(publicId) suspend fun fetchResultsProcessing(publicId: PublicId): ResultsProcessing? = resultsProcessingRepository.fetchResultsProcessing(publicId) - suspend fun updateResultsProcessingStatus(publicId: PublicId, newStatus: ResultsProcessingStatus) = - resultsProcessingRepository.updateResultsProcessingStatus(publicId, newStatus) + suspend fun updateResultsProcessingStatus( + publicId: PublicId, + newStatus: ResultsProcessingStatus, + ) = resultsProcessingRepository.updateResultsProcessingStatus(publicId, newStatus) - suspend fun recordResultsProcessingError(publicId: PublicId, resultsBody: String, errorMessage: String?) = - resultsProcessingRepository.recordResultsProcessingError(publicId, resultsBody, errorMessage) + suspend fun recordResultsProcessingError( + publicId: PublicId, + resultsBody: String, + errorMessage: String?, + ) = resultsProcessingRepository.recordResultsProcessingError(publicId, resultsBody, errorMessage) } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsService.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsService.kt index a9dcdb973..30870c748 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsService.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/TestResultsService.kt @@ -16,7 +16,7 @@ class TestResultsService( private val testResultsProcessor: TestResultsProcessor, private val testRunRepository: TestRunRepository, private val testResultsProcessingService: TestResultsProcessingService, - private val metricsService: MetricsService + private val metricsService: MetricsService, ) { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) @@ -33,7 +33,10 @@ class TestResultsService( return publicId } - suspend fun doPersistTestResults(publicId: PublicId, resultsBlob: String) { + suspend fun doPersistTestResults( + publicId: PublicId, + resultsBlob: String, + ) { try { testResultsProcessingService.updateResultsProcessingStatus(publicId, ResultsProcessingStatus.PROCESSING) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToApiMapper.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToApiMapper.kt index 7897ab0f3..22f55722d 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToApiMapper.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToApiMapper.kt @@ -11,20 +11,22 @@ import projektor.server.api.TestSuite as TestSuiteApi fun toTestRunSummary( publicId: PublicId, testSuites: List, - wallClockDuration: BigDecimal? + wallClockDuration: BigDecimal?, ): TestRunSummary { val totalTestCount = testSuites.sumOf { it.tests } val totalFailureCount = testSuites.sumOf { it.failures } val allTestCases = testSuites.flatMap { it.testCases } - val cumulativeDuration = allTestCases - .mapNotNull { it.time } - .fold(BigDecimal.ZERO, BigDecimal::add) + val cumulativeDuration = + allTestCases + .mapNotNull { it.time } + .fold(BigDecimal.ZERO, BigDecimal::add) val averageDuration = calculateAverageDuration(cumulativeDuration, totalTestCount) - val slowestTestCaseDuration = allTestCases - .mapNotNull { it.time } - .maxOrNull() - ?: BigDecimal.ZERO + val slowestTestCaseDuration = + allTestCases + .mapNotNull { it.time } + .maxOrNull() + ?: BigDecimal.ZERO return TestRunSummary( publicId.id, @@ -37,27 +39,29 @@ fun toTestRunSummary( averageDuration, slowestTestCaseDuration, Instant.now(), - wallClockDuration + wallClockDuration, ) } fun toTestRunSummaryFromApi( publicId: PublicId, testSuites: List, - wallClockDuration: BigDecimal? + wallClockDuration: BigDecimal?, ): TestRunSummary { val totalTestCount = testSuites.sumOf { it.testCount } val totalFailureCount = testSuites.sumOf { it.failureCount } val allTestCases = testSuites.mapNotNull { it.testCases }.flatten() - val cumulativeDuration = allTestCases - .mapNotNull { it.duration } - .fold(BigDecimal.ZERO, BigDecimal::add) + val cumulativeDuration = + allTestCases + .mapNotNull { it.duration } + .fold(BigDecimal.ZERO, BigDecimal::add) val averageDuration = calculateAverageDuration(cumulativeDuration, totalTestCount) - val slowestTestCaseDuration = allTestCases - .mapNotNull { it.duration } - .maxOrNull() - ?: BigDecimal.ZERO + val slowestTestCaseDuration = + allTestCases + .mapNotNull { it.duration } + .maxOrNull() + ?: BigDecimal.ZERO return TestRunSummary( publicId.id, @@ -70,6 +74,6 @@ fun toTestRunSummaryFromApi( averageDuration, slowestTestCaseDuration, Instant.now(), - wallClockDuration + wallClockDuration, ) } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToDBMapper.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToDBMapper.kt index c19eb8df5..acc7dbb19 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToDBMapper.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/mapper/ParsedResultsToDBMapper.kt @@ -26,7 +26,11 @@ fun GroupedTestSuites.toDB(testRunId: Long): TestSuiteGroupDB { return testSuiteGroupDB } -fun TestSuite.toDB(testRunId: Long, testGroupId: Long?, testSuiteIdx: Int): TestSuiteDB { +fun TestSuite.toDB( + testRunId: Long, + testGroupId: Long?, + testSuiteIdx: Int, +): TestSuiteDB { val packageAndClassName = parsePackageAndClassName(name) val testSuiteDB = TestSuiteDB() @@ -51,7 +55,10 @@ fun TestSuite.toDB(testRunId: Long, testGroupId: Long?, testSuiteIdx: Int): Test return testSuiteDB } -fun TestCase.toDB(testSuiteId: Long, testCaseIdx: Int): TestCaseDB { +fun TestCase.toDB( + testSuiteId: Long, + testCaseIdx: Int, +): TestCaseDB { val packageAndClassName = parsePackageAndClassName(className) val testCaseDB = TestCaseDB() @@ -86,12 +93,14 @@ fun parsePackageAndClassName(classNameWithPackage: String?): Pair?, - val codeQualityReports: List? + val codeQualityReports: List?, ) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/model/GroupedTestSuites.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/model/GroupedTestSuites.kt index 90c3eeb23..76fc1dfc4 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/model/GroupedTestSuites.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/model/GroupedTestSuites.kt @@ -6,5 +6,5 @@ data class GroupedTestSuites( val testSuites: List, val groupName: String?, val groupLabel: String?, - val directory: String? + val directory: String?, ) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/model/PerformanceResult.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/model/PerformanceResult.kt index 271a48d6b..81dfc293f 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/model/PerformanceResult.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/model/PerformanceResult.kt @@ -9,9 +9,8 @@ data class PerformanceResult( val requestCount: Long, val average: BigDecimal, val maximum: BigDecimal, - val p95: BigDecimal + val p95: BigDecimal, ) { - fun toApi(): PerformanceResultApi = PerformanceResultApi( name = name, @@ -19,6 +18,6 @@ data class PerformanceResult( requestCount = requestCount, average = average, maximum = maximum, - p95 = p95 + p95 = p95, ) } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/model/ResultsMetadata.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/model/ResultsMetadata.kt index fa524aa39..fd2f184fd 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/model/ResultsMetadata.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/model/ResultsMetadata.kt @@ -3,5 +3,5 @@ package projektor.incomingresults.model data class ResultsMetadata( val git: GitMetadata?, val ci: Boolean?, - val group: String? + val group: String?, ) diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt index d3eb30e5a..5b124e1ea 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt @@ -16,23 +16,25 @@ import projektor.database.generated.tables.pojos.ResultsProcessing as ResultsPro class ResultsProcessingDatabaseRepository( private val dslContext: DSLContext, - private val processingFailureRepository: ProcessingFailureRepository + private val processingFailureRepository: ProcessingFailureRepository, ) : ResultsProcessingRepository { private val resultsProcessingDao = ResultsProcessingDao(dslContext.configuration()) - private val resultsProcessingMapper = JdbcMapperFactory.newInstance() - .addKeys("public_id") - .ignorePropertyNotFound() - .newMapper(ResultsProcessing::class.java) + private val resultsProcessingMapper = + JdbcMapperFactory.newInstance() + .addKeys("public_id") + .ignorePropertyNotFound() + .newMapper(ResultsProcessing::class.java) override suspend fun createResultsProcessing(publicId: PublicId): ResultsProcessing = withContext(Dispatchers.IO) { val createdTimestamp = LocalDateTime.now() - val resultsProcessingDB = ResultsProcessingDB() - .setPublicId(publicId.id) - .setStatus(ResultsProcessingStatus.RECEIVED.name) - .setCreatedTimestamp(createdTimestamp) + val resultsProcessingDB = + ResultsProcessingDB() + .setPublicId(publicId.id) + .setStatus(ResultsProcessingStatus.RECEIVED.name) + .setCreatedTimestamp(createdTimestamp) resultsProcessingDao.insert(resultsProcessingDB) ResultsProcessing(publicId.id, ResultsProcessingStatus.RECEIVED, createdTimestamp, null) @@ -40,7 +42,7 @@ class ResultsProcessingDatabaseRepository( override suspend fun updateResultsProcessingStatus( publicId: PublicId, - newStatus: ResultsProcessingStatus + newStatus: ResultsProcessingStatus, ): Boolean = withContext(Dispatchers.IO) { dslContext.update(Tables.RESULTS_PROCESSING) @@ -52,20 +54,21 @@ class ResultsProcessingDatabaseRepository( override suspend fun recordResultsProcessingError( publicId: PublicId, resultsBody: String, - errorMessage: String? + errorMessage: String?, ): Boolean = withContext(Dispatchers.IO) { - val updateProcessingStatus = dslContext.update(Tables.RESULTS_PROCESSING) - .set(Tables.RESULTS_PROCESSING.STATUS, ResultsProcessingStatus.ERROR.name) - .set(Tables.RESULTS_PROCESSING.ERROR_MESSAGE, errorMessage) - .where(Tables.RESULTS_PROCESSING.PUBLIC_ID.eq(publicId.id)) - .execute() > 0 + val updateProcessingStatus = + dslContext.update(Tables.RESULTS_PROCESSING) + .set(Tables.RESULTS_PROCESSING.STATUS, ResultsProcessingStatus.ERROR.name) + .set(Tables.RESULTS_PROCESSING.ERROR_MESSAGE, errorMessage) + .where(Tables.RESULTS_PROCESSING.PUBLIC_ID.eq(publicId.id)) + .execute() > 0 processingFailureRepository.recordProcessingFailure( publicId = publicId, body = resultsBody, bodyType = FailureBodyType.TEST_RESULTS, - failureMessage = errorMessage + failureMessage = errorMessage, ) updateProcessingStatus @@ -73,13 +76,14 @@ class ResultsProcessingDatabaseRepository( override suspend fun fetchResultsProcessing(publicId: PublicId): ResultsProcessing? = withContext(Dispatchers.IO) { - val resultSet = dslContext - .select(Tables.RESULTS_PROCESSING.fields().toList()) - .select(Tables.RESULTS_PROCESSING.PUBLIC_ID.`as`("id")) - .from(Tables.RESULTS_PROCESSING) - .where(Tables.RESULTS_PROCESSING.PUBLIC_ID.eq(publicId.id)) - .limit(1) - .fetchResultSet() + val resultSet = + dslContext + .select(Tables.RESULTS_PROCESSING.fields().toList()) + .select(Tables.RESULTS_PROCESSING.PUBLIC_ID.`as`("id")) + .from(Tables.RESULTS_PROCESSING) + .where(Tables.RESULTS_PROCESSING.PUBLIC_ID.eq(publicId.id)) + .limit(1) + .fetchResultSet() resultSet.use { resultsProcessingMapper.stream(it).findFirst().orElse(null) } } diff --git a/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingRepository.kt b/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingRepository.kt index 8a3e23356..aba3c8c99 100644 --- a/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingRepository.kt @@ -7,9 +7,16 @@ import projektor.server.api.results.ResultsProcessingStatus interface ResultsProcessingRepository { suspend fun createResultsProcessing(publicId: PublicId): ResultsProcessing - suspend fun updateResultsProcessingStatus(publicId: PublicId, newStatus: ResultsProcessingStatus): Boolean + suspend fun updateResultsProcessingStatus( + publicId: PublicId, + newStatus: ResultsProcessingStatus, + ): Boolean - suspend fun recordResultsProcessingError(publicId: PublicId, resultsBody: String, errorMessage: String?): Boolean + suspend fun recordResultsProcessingError( + publicId: PublicId, + resultsBody: String, + errorMessage: String?, + ): Boolean suspend fun fetchResultsProcessing(publicId: PublicId): ResultsProcessing? } diff --git a/server/server-app/src/main/kotlin/projektor/logging/TimeMillisJsonLoggingProvider.kt b/server/server-app/src/main/kotlin/projektor/logging/TimeMillisJsonLoggingProvider.kt index 7acfa1806..33b443c1a 100644 --- a/server/server-app/src/main/kotlin/projektor/logging/TimeMillisJsonLoggingProvider.kt +++ b/server/server-app/src/main/kotlin/projektor/logging/TimeMillisJsonLoggingProvider.kt @@ -10,7 +10,10 @@ class TimeMillisJsonLoggingProvider : AbstractFieldJsonProvider { fieldName = FIELD_NAME } - override fun writeTo(generator: JsonGenerator, event: ILoggingEvent) { + override fun writeTo( + generator: JsonGenerator, + event: ILoggingEvent, + ) { JsonWritingUtils.writeNumberField(generator, fieldName, event.timeStamp / 1000) } diff --git a/server/server-app/src/main/kotlin/projektor/message/MessageConfig.kt b/server/server-app/src/main/kotlin/projektor/message/MessageConfig.kt index c8d16da83..39d48f2b0 100644 --- a/server/server-app/src/main/kotlin/projektor/message/MessageConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/message/MessageConfig.kt @@ -3,7 +3,6 @@ package projektor.message import io.ktor.server.config.ApplicationConfig data class MessageConfig(val globalMessages: List) { - companion object { fun createMessageConfig(applicationConfig: ApplicationConfig): MessageConfig { val messageString = applicationConfig.propertyOrNull("ktor.message.global")?.getString() diff --git a/server/server-app/src/main/kotlin/projektor/message/MessageService.kt b/server/server-app/src/main/kotlin/projektor/message/MessageService.kt index dd8d99cf6..0fd345abd 100644 --- a/server/server-app/src/main/kotlin/projektor/message/MessageService.kt +++ b/server/server-app/src/main/kotlin/projektor/message/MessageService.kt @@ -4,7 +4,6 @@ import projektor.server.api.PublicId import projektor.server.api.messages.Messages class MessageService(private val messageConfig: MessageConfig) { - fun getTestRunMessages(publicId: PublicId): Messages { return Messages(messageConfig.globalMessages) } diff --git a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataDatabaseRepository.kt index 10dd78ff6..7627da1e2 100644 --- a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataDatabaseRepository.kt @@ -29,7 +29,11 @@ class TestRunMetadataDatabaseRepository(private val dslContext: DSLContext) : Te .fetchOneInto(TestRunMetadata::class.java) } - override suspend fun updateGitMetadata(testRunId: Long, pullRequestNumber: Int?, commitSha: String?) { + override suspend fun updateGitMetadata( + testRunId: Long, + pullRequestNumber: Int?, + commitSha: String?, + ) { withContext(Dispatchers.IO) { dslContext.update(GIT_METADATA) .set(GIT_METADATA.PULL_REQUEST_NUMBER, pullRequestNumber) diff --git a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataRepository.kt b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataRepository.kt index 8e13e7ead..635129a15 100644 --- a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataRepository.kt @@ -9,5 +9,9 @@ interface TestRunMetadataRepository { suspend fun fetchResultsMetadata(publicId: PublicId): TestRunMetadata? - suspend fun updateGitMetadata(testRunId: Long, pullRequestNumber: Int?, commitSha: String?) + suspend fun updateGitMetadata( + testRunId: Long, + pullRequestNumber: Int?, + commitSha: String?, + ) } diff --git a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataService.kt b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataService.kt index ad6fd1a90..b0598eba3 100644 --- a/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataService.kt +++ b/server/server-app/src/main/kotlin/projektor/metadata/TestRunMetadataService.kt @@ -5,9 +5,7 @@ import projektor.server.api.metadata.TestRunGitMetadata import projektor.server.api.metadata.TestRunMetadata class TestRunMetadataService(private val testRunMetadataRepository: TestRunMetadataRepository) { - suspend fun fetchGitMetadata(publicId: PublicId): TestRunGitMetadata? = - testRunMetadataRepository.fetchGitMetadata(publicId) + suspend fun fetchGitMetadata(publicId: PublicId): TestRunGitMetadata? = testRunMetadataRepository.fetchGitMetadata(publicId) - suspend fun fetchResultsMetadata(publicId: PublicId): TestRunMetadata? = - testRunMetadataRepository.fetchResultsMetadata(publicId) + suspend fun fetchResultsMetadata(publicId: PublicId): TestRunMetadata? = testRunMetadataRepository.fetchResultsMetadata(publicId) } diff --git a/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetrics.kt b/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetrics.kt index 6f62991cf..abcfebf4e 100644 --- a/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetrics.kt +++ b/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetrics.kt @@ -6,29 +6,30 @@ import io.micrometer.influx.InfluxMeterRegistry import java.time.Duration fun createRegistry(config: InfluxMetricsConfig): InfluxMeterRegistry { + val registryConfig: InfluxConfig = + object : InfluxConfig { + override fun step(): Duration { + return Duration.ofSeconds(config.interval) + } - val registryConfig: InfluxConfig = object : InfluxConfig { - override fun step(): Duration { - return Duration.ofSeconds(config.interval) - } + override fun db(): String { + return config.dbName + } - override fun db(): String { - return config.dbName - } + override fun get(k: String): String? { + val value = + when (k) { + "influx.autoCreateDb" -> config.autoCreateDb.toString() + "influx.enabled" -> config.enabled.toString() + "influx.uri" -> config.uri + "influx.userName" -> config.username + "influx.password" -> config.password + else -> null + } - override fun get(k: String): String? { - val value = when (k) { - "influx.autoCreateDb" -> config.autoCreateDb.toString() - "influx.enabled" -> config.enabled.toString() - "influx.uri" -> config.uri - "influx.userName" -> config.username - "influx.password" -> config.password - else -> null + return value } - - return value } - } return InfluxMeterRegistry(registryConfig, Clock.SYSTEM) } diff --git a/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetricsConfig.kt b/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetricsConfig.kt index d9d31c490..e3753349d 100644 --- a/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetricsConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/metrics/InfluxMetricsConfig.kt @@ -10,18 +10,19 @@ data class InfluxMetricsConfig( val password: String?, val autoCreateDb: Boolean, val interval: Long, - val environment: String? + val environment: String?, ) { companion object { - fun createInfluxMetricsConfig(applicationConfig: ApplicationConfig) = InfluxMetricsConfig( - applicationConfig.propertyOrNull("ktor.metrics.influxdb.enabled")?.getString()?.toBoolean() ?: false, - applicationConfig.propertyOrNull("ktor.metrics.influxdb.dbName")?.getString() ?: "default", - applicationConfig.propertyOrNull("ktor.metrics.influxdb.uri")?.getString() ?: "http://localhost:8086", - applicationConfig.propertyOrNull("ktor.metrics.influxdb.username")?.getString(), - applicationConfig.propertyOrNull("ktor.metrics.influxdb.password")?.getString(), - applicationConfig.propertyOrNull("ktor.metrics.influxdb.autoCreateDb")?.getString()?.toBoolean() ?: false, - applicationConfig.propertyOrNull("ktor.metrics.influxdb.interval")?.getString()?.toLong() ?: 10, - applicationConfig.propertyOrNull("ktor.metrics.influxdb.environment")?.getString() - ) + fun createInfluxMetricsConfig(applicationConfig: ApplicationConfig) = + InfluxMetricsConfig( + applicationConfig.propertyOrNull("ktor.metrics.influxdb.enabled")?.getString()?.toBoolean() ?: false, + applicationConfig.propertyOrNull("ktor.metrics.influxdb.dbName")?.getString() ?: "default", + applicationConfig.propertyOrNull("ktor.metrics.influxdb.uri")?.getString() ?: "http://localhost:8086", + applicationConfig.propertyOrNull("ktor.metrics.influxdb.username")?.getString(), + applicationConfig.propertyOrNull("ktor.metrics.influxdb.password")?.getString(), + applicationConfig.propertyOrNull("ktor.metrics.influxdb.autoCreateDb")?.getString()?.toBoolean() ?: false, + applicationConfig.propertyOrNull("ktor.metrics.influxdb.interval")?.getString()?.toLong() ?: 10, + applicationConfig.propertyOrNull("ktor.metrics.influxdb.environment")?.getString(), + ) } } diff --git a/server/server-app/src/main/kotlin/projektor/metrics/MetricsService.kt b/server/server-app/src/main/kotlin/projektor/metrics/MetricsService.kt index 5cac99224..c7b478984 100644 --- a/server/server-app/src/main/kotlin/projektor/metrics/MetricsService.kt +++ b/server/server-app/src/main/kotlin/projektor/metrics/MetricsService.kt @@ -18,16 +18,23 @@ class MetricsService(private val metricRegistry: MeterRegistry) { private val resultsParseFailureCounter = metricRegistry.counter("results_parse_failure") fun incrementCoverageParseFailureCounter() = coverageParseFailureCounter.increment() + fun incrementCoverageProcessFailureCounter() = coverageProcessFailureCounter.increment() + fun incrementCoverageProcessSuccessCounter() = coverageProcessSuccessCounter.increment() + fun incrementCoverageProcessStartCounter() = coverageProcessStartCounter.increment() fun incrementPullRequestCommentSuccessCounter() = pullRequestCommentSuccessCounter.increment() + fun incrementPullRequestCommentFailureCounter() = pullRequestCommentFailureCounter.increment() fun incrementResultsProcessStartCounter() = resultsProcessStartCounter.increment() + fun incrementResultsProcessSuccessCounter() = resultsProcessSuccessCounter.increment() + fun incrementResultsProcessFailureCounter() = resultsProcessFailureCounter.increment() + fun incrementResultsParseFailureCounter() = resultsParseFailureCounter.increment() fun createTimer(name: String): Pair { diff --git a/server/server-app/src/main/kotlin/projektor/notification/github/GitHubNotificationConfig.kt b/server/server-app/src/main/kotlin/projektor/notification/github/GitHubNotificationConfig.kt index 8b22ef173..de552de22 100644 --- a/server/server-app/src/main/kotlin/projektor/notification/github/GitHubNotificationConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/notification/github/GitHubNotificationConfig.kt @@ -6,7 +6,7 @@ import projektor.notification.github.auth.PrivateKeyEncoder data class GitHubNotificationConfig( val gitHubApiUrl: String?, val gitHubAppId: String?, - val privateKey: String? + val privateKey: String?, ) { companion object { fun createGitHubNotificationConfig(applicationConfig: ApplicationConfig): GitHubNotificationConfig { @@ -19,7 +19,7 @@ data class GitHubNotificationConfig( return GitHubNotificationConfig( gitHubApiUrl = gitHubApiUrl, gitHubAppId = gitHubAppId, - privateKey = privateKey + privateKey = privateKey, ) } } diff --git a/server/server-app/src/main/kotlin/projektor/notification/github/GitHubPullRequestCommentService.kt b/server/server-app/src/main/kotlin/projektor/notification/github/GitHubPullRequestCommentService.kt index 28507c49e..97a51aaa1 100644 --- a/server/server-app/src/main/kotlin/projektor/notification/github/GitHubPullRequestCommentService.kt +++ b/server/server-app/src/main/kotlin/projektor/notification/github/GitHubPullRequestCommentService.kt @@ -16,13 +16,13 @@ import java.time.ZoneId class GitHubPullRequestCommentService( private val notificationConfig: NotificationConfig, - private val gitHubCommentService: GitHubCommentService? + private val gitHubCommentService: GitHubCommentService?, ) { fun upsertComment( testRunSummary: TestRunSummary, gitMetadata: GitMetadata?, coverage: Coverage?, - performanceResults: List? + performanceResults: List?, ): PullRequest? { val (serverBaseUrl) = notificationConfig @@ -36,41 +36,45 @@ class GitHubPullRequestCommentService( val orgName = repoParts[0] val repoName = repoParts[1] - val coverageData = if (coverage != null) { - ReportCoverageCommentData( - lineCoveredPercentage = coverage.overallStats.lineStat.coveredPercentage, - lineCoverageDelta = coverage.overallStats.lineStat.coveredPercentageDelta - ) - } else { - null - } + val coverageData = + if (coverage != null) { + ReportCoverageCommentData( + lineCoveredPercentage = coverage.overallStats.lineStat.coveredPercentage, + lineCoverageDelta = coverage.overallStats.lineStat.coveredPercentageDelta, + ) + } else { + null + } - val performanceData = performanceResults?.map { performanceResult -> - ReportCommentPerformanceData( - name = performanceResult.name, - requestsPerSecond = performanceResult.requestsPerSecond, - p95 = performanceResult.p95 - ) - } + val performanceData = + performanceResults?.map { performanceResult -> + ReportCommentPerformanceData( + name = performanceResult.name, + requestsPerSecond = performanceResult.requestsPerSecond, + p95 = performanceResult.p95, + ) + } - val commentData = ReportCommentData( - projektorServerBaseUrl = serverBaseUrl, - git = ReportCommentGitData( - orgName = orgName, - repoName = repoName, - branchName = branchName, - commitSha = commitSha, - pullRequestNumber = pullRequestNumber - ), - publicId = testRunSummary.id, - createdDate = LocalDateTime.ofInstant(testRunSummary.createdTimestamp, ZoneId.of("Z")), - passed = testRunSummary.passed, - totalTestCount = testRunSummary.totalTestCount, - failedTestCount = testRunSummary.totalFailureCount, - performance = performanceData, - coverage = coverageData, - project = gitMetadata.projectName - ) + val commentData = + ReportCommentData( + projektorServerBaseUrl = serverBaseUrl, + git = + ReportCommentGitData( + orgName = orgName, + repoName = repoName, + branchName = branchName, + commitSha = commitSha, + pullRequestNumber = pullRequestNumber, + ), + publicId = testRunSummary.id, + createdDate = LocalDateTime.ofInstant(testRunSummary.createdTimestamp, ZoneId.of("Z")), + passed = testRunSummary.passed, + totalTestCount = testRunSummary.totalTestCount, + failedTestCount = testRunSummary.totalFailureCount, + performance = performanceData, + coverage = coverageData, + project = gitMetadata.projectName, + ) gitHubCommentService.upsertReportComment(commentData, testRunSummary.id) } else { diff --git a/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageDatabaseRepository.kt index 63021276d..656718229 100644 --- a/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageDatabaseRepository.kt @@ -9,36 +9,43 @@ import projektor.database.generated.Tables.* import kotlin.streams.toList class OrganizationCoverageDatabaseRepository(private val dslContext: DSLContext) : OrganizationCoverageRepository { - - private val repositoryTestRunMapper = JdbcMapperFactory.newInstance() - .addKeys("public_id") - .ignorePropertyNotFound() - .newMapper(RepositoryTestRun::class.java) + private val repositoryTestRunMapper = + JdbcMapperFactory.newInstance() + .addKeys("public_id") + .ignorePropertyNotFound() + .newMapper(RepositoryTestRun::class.java) override suspend fun findReposWithCoverage(orgName: String): List = withContext(Dispatchers.IO) { - val resultSet = dslContext.selectDistinct( - firstValue(TEST_RUN.PUBLIC_ID).over().partitionBy(GIT_METADATA.REPO_NAME, GIT_METADATA.PROJECT_NAME).orderBy(TEST_RUN.CREATED_TIMESTAMP.desc()).`as`("public_id"), - GIT_METADATA.REPO_NAME, - GIT_METADATA.PROJECT_NAME, - GIT_METADATA.BRANCH_NAME, - TEST_RUN.CREATED_TIMESTAMP, - ) - .from(GIT_METADATA) - .innerJoin(TEST_RUN).on(GIT_METADATA.TEST_RUN_ID.eq(TEST_RUN.ID)) - .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) - .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) - .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_STATS.ID.eq(CODE_COVERAGE_GROUP.STATS_ID)) - .where( - GIT_METADATA.ORG_NAME.eq(orgName) - .and(GIT_METADATA.IS_MAIN_BRANCH.eq(true)) - .and(CODE_COVERAGE_STATS.LINE_COVERED.isNotNull) + val resultSet = + dslContext.selectDistinct( + firstValue( + TEST_RUN.PUBLIC_ID, + ).over().partitionBy( + GIT_METADATA.REPO_NAME, + GIT_METADATA.PROJECT_NAME, + ).orderBy(TEST_RUN.CREATED_TIMESTAMP.desc()).`as`("public_id"), + GIT_METADATA.REPO_NAME, + GIT_METADATA.PROJECT_NAME, + GIT_METADATA.BRANCH_NAME, + TEST_RUN.CREATED_TIMESTAMP, ) - .fetchResultSet() + .from(GIT_METADATA) + .innerJoin(TEST_RUN).on(GIT_METADATA.TEST_RUN_ID.eq(TEST_RUN.ID)) + .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) + .innerJoin(CODE_COVERAGE_GROUP).on(CODE_COVERAGE_GROUP.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) + .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_STATS.ID.eq(CODE_COVERAGE_GROUP.STATS_ID)) + .where( + GIT_METADATA.ORG_NAME.eq(orgName) + .and(GIT_METADATA.IS_MAIN_BRANCH.eq(true)) + .and(CODE_COVERAGE_STATS.LINE_COVERED.isNotNull), + ) + .fetchResultSet() - val repositoryTestRuns: List = resultSet.use { - repositoryTestRunMapper.stream(resultSet).toList() - } + val repositoryTestRuns: List = + resultSet.use { + repositoryTestRunMapper.stream(resultSet).toList() + } repositoryTestRuns } diff --git a/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageService.kt b/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageService.kt index 3c28a6de2..60950e6ae 100644 --- a/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageService.kt +++ b/server/server-app/src/main/kotlin/projektor/organization/coverage/OrganizationCoverageService.kt @@ -8,21 +8,22 @@ import projektor.server.api.repository.coverage.RepositoryCurrentCoverage class OrganizationCoverageService( private val organizationCoverageRepository: OrganizationCoverageRepository, - private val coverageService: CoverageService + private val coverageService: CoverageService, ) { suspend fun getCoverage(orgName: String): OrganizationCoverage { val repositoryTestRuns = findReposWithCoverage(orgName) - val repositories = repositoryTestRuns.map { repositoryTestRun -> - val coverage = coverageService.getCoverage(repositoryTestRun.publicId) + val repositories = + repositoryTestRuns.map { repositoryTestRun -> + val coverage = coverageService.getCoverage(repositoryTestRun.publicId) - RepositoryCoverage( - publicId = repositoryTestRun.publicId.id, - repoName = repositoryTestRun.repoName, - projectName = repositoryTestRun.projectName, - coverage = coverage - ) - } + RepositoryCoverage( + publicId = repositoryTestRun.publicId.id, + repoName = repositoryTestRun.repoName, + projectName = repositoryTestRun.projectName, + coverage = coverage, + ) + } return OrganizationCoverage(repositories) } @@ -30,18 +31,19 @@ class OrganizationCoverageService( suspend fun getCurrentCoverage(orgName: String): OrganizationCurrentCoverage { val repositoryTestRuns = findReposWithCoverage(orgName) - val repositories = repositoryTestRuns.map { repositoryTestRun -> - val coveredPercentage = coverageService.getCoveredLinePercentage(repositoryTestRun.publicId) - - RepositoryCurrentCoverage( - id = repositoryTestRun.publicId.id, - createdTimestamp = repositoryTestRun.createdTimestamp, - coveredPercentage = coveredPercentage, - repo = repositoryTestRun.repoName, - project = repositoryTestRun.projectName, - branch = repositoryTestRun.branchName - ) - } + val repositories = + repositoryTestRuns.map { repositoryTestRun -> + val coveredPercentage = coverageService.getCoveredLinePercentage(repositoryTestRun.publicId) + + RepositoryCurrentCoverage( + id = repositoryTestRun.publicId.id, + createdTimestamp = repositoryTestRun.createdTimestamp, + coveredPercentage = coveredPercentage, + repo = repositoryTestRun.repoName, + project = repositoryTestRun.projectName, + branch = repositoryTestRun.branchName, + ) + } return OrganizationCurrentCoverage(repositories) } diff --git a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsDatabaseRepository.kt index f3da6a8ef..c67855d95 100644 --- a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsDatabaseRepository.kt @@ -19,7 +19,7 @@ class PerformanceResultsDatabaseRepository(private val dslContext: DSLContext) : override suspend fun savePerformanceResults( testRunId: Long, publicId: PublicId, - results: IncomingPerformanceResult + results: IncomingPerformanceResult, ): PerformanceResult = withContext(Dispatchers.IO) { val performanceResults = PerformanceResults() diff --git a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsRepository.kt b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsRepository.kt index 295f3c26a..66db5fb18 100644 --- a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsRepository.kt @@ -8,7 +8,7 @@ interface PerformanceResultsRepository { suspend fun savePerformanceResults( testRunId: Long, publicId: PublicId, - results: IncomingPerformanceResult + results: IncomingPerformanceResult, ): PerformanceResult suspend fun fetchResults(publicId: PublicId): List diff --git a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsService.kt b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsService.kt index c9ca01a71..76a08ffc0 100644 --- a/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsService.kt +++ b/server/server-app/src/main/kotlin/projektor/performance/PerformanceResultsService.kt @@ -4,6 +4,5 @@ import projektor.server.api.PublicId import projektor.server.api.performance.PerformanceResult class PerformanceResultsService(private val performanceResultsRepository: PerformanceResultsRepository) { - suspend fun fetchResults(publicId: PublicId): List = - performanceResultsRepository.fetchResults(publicId) + suspend fun fetchResults(publicId: PublicId): List = performanceResultsRepository.fetchResults(publicId) } diff --git a/server/server-app/src/main/kotlin/projektor/processing/ProcessingConfig.kt b/server/server-app/src/main/kotlin/projektor/processing/ProcessingConfig.kt index 3aa2aba9c..f95ce11ab 100644 --- a/server/server-app/src/main/kotlin/projektor/processing/ProcessingConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/processing/ProcessingConfig.kt @@ -6,7 +6,10 @@ import projektor.parser.grouped.GroupedResultsParser data class ProcessingConfig(val maxPayloadSize: Int) { companion object { fun createProcessingConfig(applicationConfig: ApplicationConfig): ProcessingConfig { - val maxPayloadSize: Int = applicationConfig.propertyOrNull("ktor.processing.maxPayloadSize")?.toString()?.toInt() ?: GroupedResultsParser.DEFAULT_MAX_PAYLOAD_SIZE + val maxPayloadSize: Int = + applicationConfig.propertyOrNull( + "ktor.processing.maxPayloadSize", + )?.toString()?.toInt() ?: GroupedResultsParser.DEFAULT_MAX_PAYLOAD_SIZE return ProcessingConfig(maxPayloadSize) } diff --git a/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportDatabaseRepository.kt index 057c80d7b..9cd1ba505 100644 --- a/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportDatabaseRepository.kt @@ -13,15 +13,18 @@ import kotlin.streams.toList import projektor.database.generated.tables.pojos.CodeQualityReport as CodeQualityReportDB class CodeQualityReportDatabaseRepository(private val dslContext: DSLContext) : CodeQualityReportRepository { - private val codeQualityReportDao = CodeQualityReportDao(dslContext.configuration()) - private val codeQualityMapper = JdbcMapperFactory.newInstance() - .addKeys("id") - .ignorePropertyNotFound() - .newMapper(CodeQualityReport::class.java) + private val codeQualityMapper = + JdbcMapperFactory.newInstance() + .addKeys("id") + .ignorePropertyNotFound() + .newMapper(CodeQualityReport::class.java) - override suspend fun insertCodeQualityReports(testRunId: Long, codeQualityReports: List) { + override suspend fun insertCodeQualityReports( + testRunId: Long, + codeQualityReports: List, + ) { codeQualityReports.forEach { codeQualityReport -> val codeQualityReportDB = CodeQualityReportDB() codeQualityReportDB.testRunId = testRunId @@ -36,12 +39,13 @@ class CodeQualityReportDatabaseRepository(private val dslContext: DSLContext) : override suspend fun fetchCodeQualityReports(publicId: PublicId): List = withContext(Dispatchers.IO) { - val resultSet = dslContext - .select(CODE_QUALITY_REPORT.fields().toList()) - .from(CODE_QUALITY_REPORT) - .innerJoin(TEST_RUN).on(CODE_QUALITY_REPORT.TEST_RUN_ID.eq(TEST_RUN.ID)) - .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) - .fetchResultSet() + val resultSet = + dslContext + .select(CODE_QUALITY_REPORT.fields().toList()) + .from(CODE_QUALITY_REPORT) + .innerJoin(TEST_RUN).on(CODE_QUALITY_REPORT.TEST_RUN_ID.eq(TEST_RUN.ID)) + .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) + .fetchResultSet() resultSet.use { codeQualityMapper.stream(it).toList() } } diff --git a/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportRepository.kt b/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportRepository.kt index a85e923c0..b4589a8f3 100644 --- a/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/quality/CodeQualityReportRepository.kt @@ -4,8 +4,10 @@ import projektor.server.api.PublicId import projektor.server.api.quality.CodeQualityReport interface CodeQualityReportRepository { - - suspend fun insertCodeQualityReports(testRunId: Long, codeQualityReports: List) + suspend fun insertCodeQualityReports( + testRunId: Long, + codeQualityReports: List, + ) suspend fun fetchCodeQualityReports(publicId: PublicId): List } diff --git a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageDatabaseRepository.kt index c5562bd45..1f2cc78a2 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageDatabaseRepository.kt @@ -20,45 +20,55 @@ import java.time.Instant import kotlin.streams.toList class RepositoryCoverageDatabaseRepository(private val dslContext: DSLContext) : RepositoryCoverageRepository { - private val repositoryCoverageTimelineEntryMapper = JdbcMapperFactory.newInstance() - .addKeys("public_id") - .ignorePropertyNotFound() - .newMapper(ReportTimelineEntry::class.java) + private val repositoryCoverageTimelineEntryMapper = + JdbcMapperFactory.newInstance() + .addKeys("public_id") + .ignorePropertyNotFound() + .newMapper(ReportTimelineEntry::class.java) - override suspend fun fetchRepositoryCoverageTimeline(branchType: BranchType, repoName: String, projectName: String?): RepositoryCoverageTimeline? = + override suspend fun fetchRepositoryCoverageTimeline( + branchType: BranchType, + repoName: String, + projectName: String?, + ): RepositoryCoverageTimeline? = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - TEST_RUN.PUBLIC_ID, - TEST_RUN.CREATED_TIMESTAMP, - DSL.sum(CODE_COVERAGE_STATS.BRANCH_COVERED).`as`("coverage_stats_branch_stat_covered"), - DSL.sum(CODE_COVERAGE_STATS.BRANCH_MISSED).`as`("coverage_stats_branch_stat_missed"), - DSL.sum(CODE_COVERAGE_STATS.STATEMENT_COVERED).`as`("coverage_stats_statement_stat_covered"), - DSL.sum(CODE_COVERAGE_STATS.STATEMENT_MISSED).`as`("coverage_stats_statement_stat_missed"), - DSL.sum(CODE_COVERAGE_STATS.LINE_COVERED).`as`("coverage_stats_line_stat_covered"), - DSL.sum(CODE_COVERAGE_STATS.LINE_MISSED).`as`("coverage_stats_line_stat_missed") - ) - .from(GIT_METADATA) - .innerJoin(TEST_RUN).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) - .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_STATS.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) - .where( - GIT_METADATA.REPO_NAME.eq(repoName) - .and(withBranchType(branchType)) - .and(withProjectName(projectName)) - .and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP")) + val resultSet = + dslContext.select( + TEST_RUN.PUBLIC_ID, + TEST_RUN.CREATED_TIMESTAMP, + DSL.sum(CODE_COVERAGE_STATS.BRANCH_COVERED).`as`("coverage_stats_branch_stat_covered"), + DSL.sum(CODE_COVERAGE_STATS.BRANCH_MISSED).`as`("coverage_stats_branch_stat_missed"), + DSL.sum(CODE_COVERAGE_STATS.STATEMENT_COVERED).`as`("coverage_stats_statement_stat_covered"), + DSL.sum(CODE_COVERAGE_STATS.STATEMENT_MISSED).`as`("coverage_stats_statement_stat_missed"), + DSL.sum(CODE_COVERAGE_STATS.LINE_COVERED).`as`("coverage_stats_line_stat_covered"), + DSL.sum(CODE_COVERAGE_STATS.LINE_MISSED).`as`("coverage_stats_line_stat_missed"), ) - .groupBy(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) - .fetchResultSet() + .from(GIT_METADATA) + .innerJoin(TEST_RUN).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(CODE_COVERAGE_RUN).on(TEST_RUN.PUBLIC_ID.eq(CODE_COVERAGE_RUN.TEST_RUN_PUBLIC_ID)) + .innerJoin(CODE_COVERAGE_STATS).on(CODE_COVERAGE_STATS.CODE_COVERAGE_RUN_ID.eq(CODE_COVERAGE_RUN.ID)) + .where( + GIT_METADATA.REPO_NAME.eq(repoName) + .and(withBranchType(branchType)) + .and(withProjectName(projectName)) + .and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP")), + ) + .groupBy(TEST_RUN.PUBLIC_ID, TEST_RUN.CREATED_TIMESTAMP) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) + .fetchResultSet() - val timelineEntries: List = resultSet.use { - repositoryCoverageTimelineEntryMapper.stream(resultSet).toList() - } + val timelineEntries: List = + resultSet.use { + repositoryCoverageTimelineEntryMapper.stream(resultSet).toList() + } if (timelineEntries.isNotEmpty()) RepositoryCoverageTimeline(timelineEntries.map { it.toFullEntry() }) else null } - override suspend fun coverageExists(repoName: String, projectName: String?): Boolean = + override suspend fun coverageExists( + repoName: String, + projectName: String?, + ): Boolean = withContext(Dispatchers.IO) { dslContext.fetchExists( dslContext.select(CODE_COVERAGE_RUN.ID) @@ -69,20 +79,21 @@ class RepositoryCoverageDatabaseRepository(private val dslContext: DSLContext) : .where( GIT_METADATA.REPO_NAME.eq(repoName) .and(withProjectName(projectName)) - .and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP")) - ) + .and(CODE_COVERAGE_STATS.SCOPE.eq("GROUP")), + ), ) } data class ReportTimelineEntry( val publicId: String, val createdTimestamp: Instant, - val coverageStats: CoverageReportStats + val coverageStats: CoverageReportStats, ) { - fun toFullEntry() = RepositoryCoverageTimelineEntry( - publicId = publicId, - createdTimestamp = createdTimestamp, - coverageStats = coverageStats.toCoverageStats(null) - ) + fun toFullEntry() = + RepositoryCoverageTimelineEntry( + publicId = publicId, + createdTimestamp = createdTimestamp, + coverageStats = coverageStats.toCoverageStats(null), + ) } } diff --git a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageRepository.kt index 3d6fa8626..8703d2abe 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageRepository.kt @@ -4,7 +4,14 @@ import projektor.server.api.repository.BranchType import projektor.server.api.repository.coverage.RepositoryCoverageTimeline interface RepositoryCoverageRepository { - suspend fun fetchRepositoryCoverageTimeline(branchType: BranchType, repoName: String, projectName: String?): RepositoryCoverageTimeline? + suspend fun fetchRepositoryCoverageTimeline( + branchType: BranchType, + repoName: String, + projectName: String?, + ): RepositoryCoverageTimeline? - suspend fun coverageExists(repoName: String, projectName: String?): Boolean + suspend fun coverageExists( + repoName: String, + projectName: String?, + ): Boolean } diff --git a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageService.kt b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageService.kt index c14608fd5..20380a02c 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageService.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/coverage/RepositoryCoverageService.kt @@ -10,17 +10,25 @@ import projektor.server.api.repository.coverage.RepositoryCurrentCoverage class RepositoryCoverageService( private val coverageService: CoverageService, private val previousTestRunService: PreviousTestRunService, - private val repositoryCoverageRepository: RepositoryCoverageRepository + private val repositoryCoverageRepository: RepositoryCoverageRepository, ) { - suspend fun fetchRepositoryCoverageTimeline(branchType: BranchType, repoName: String, projectName: String?): RepositoryCoverageTimeline? = - repositoryCoverageRepository.fetchRepositoryCoverageTimeline(branchType, repoName, projectName) + suspend fun fetchRepositoryCoverageTimeline( + branchType: BranchType, + repoName: String, + projectName: String?, + ): RepositoryCoverageTimeline? = repositoryCoverageRepository.fetchRepositoryCoverageTimeline(branchType, repoName, projectName) - suspend fun fetchRepositoryCurrentCoverage(repoName: String, projectName: String?, branchSearch: BranchSearch?): RepositoryCurrentCoverage? { - val mostRecentRunWithCoverage = previousTestRunService.findMostRecentRunWithCoverage( - repoName, - projectName, - branchSearch - ) + suspend fun fetchRepositoryCurrentCoverage( + repoName: String, + projectName: String?, + branchSearch: BranchSearch?, + ): RepositoryCurrentCoverage? { + val mostRecentRunWithCoverage = + previousTestRunService.findMostRecentRunWithCoverage( + repoName, + projectName, + branchSearch, + ) val coveredPercentage = mostRecentRunWithCoverage?.publicId?.let { publicId -> coverageService.getCoveredLinePercentage(publicId) } @@ -31,13 +39,15 @@ class RepositoryCoverageService( createdTimestamp = mostRecentRunWithCoverage.createdTimestamp, repo = repoName, branch = mostRecentRunWithCoverage.branch, - project = projectName + project = projectName, ) } else { null } } - suspend fun coverageExists(repoName: String, projectName: String?): Boolean = - repositoryCoverageRepository.coverageExists(repoName, projectName) + suspend fun coverageExists( + repoName: String, + projectName: String?, + ): Boolean = repositoryCoverageRepository.coverageExists(repoName, projectName) } diff --git a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepository.kt index f7f847502..d9a53e257 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepository.kt @@ -12,36 +12,42 @@ import projektor.server.api.repository.performance.RepositoryPerformanceTestTime import kotlin.streams.toList class RepositoryPerformanceDatabaseRepository(private val dslContext: DSLContext) : RepositoryPerformanceRepository { - private val repositoryPerformanceTimelineEntryMapper = JdbcMapperFactory.newInstance() - .addKeys("public_id") - .ignorePropertyNotFound() - .newMapper(RepositoryPerformanceTestTimelineEntry::class.java) + private val repositoryPerformanceTimelineEntryMapper = + JdbcMapperFactory.newInstance() + .addKeys("public_id") + .ignorePropertyNotFound() + .newMapper(RepositoryPerformanceTestTimelineEntry::class.java) - override suspend fun fetchTestTimelineEntries(repoName: String, projectName: String?): List = + override suspend fun fetchTestTimelineEntries( + repoName: String, + projectName: String?, + ): List = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - TEST_RUN.PUBLIC_ID, - TEST_RUN.CREATED_TIMESTAMP, - PERFORMANCE_RESULTS.NAME.`as`("performance_result.name"), - PERFORMANCE_RESULTS.REQUESTS_PER_SECOND.`as`("performance_result.requests_per_second"), - PERFORMANCE_RESULTS.REQUEST_COUNT.`as`("performance_result.request_count"), - PERFORMANCE_RESULTS.AVERAGE.`as`("performance_result.average"), - PERFORMANCE_RESULTS.P95.`as`("performance_result.p95"), - PERFORMANCE_RESULTS.MAXIMUM.`as`("performance_result.maximum"), - ) - .from(PERFORMANCE_RESULTS) - .innerJoin(TEST_RUN).on(PERFORMANCE_RESULTS.TEST_RUN_ID.eq(TEST_RUN.ID)) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .where( - GIT_METADATA.REPO_NAME.eq(repoName) - .and(withProjectName(projectName)) + val resultSet = + dslContext.select( + TEST_RUN.PUBLIC_ID, + TEST_RUN.CREATED_TIMESTAMP, + PERFORMANCE_RESULTS.NAME.`as`("performance_result.name"), + PERFORMANCE_RESULTS.REQUESTS_PER_SECOND.`as`("performance_result.requests_per_second"), + PERFORMANCE_RESULTS.REQUEST_COUNT.`as`("performance_result.request_count"), + PERFORMANCE_RESULTS.AVERAGE.`as`("performance_result.average"), + PERFORMANCE_RESULTS.P95.`as`("performance_result.p95"), + PERFORMANCE_RESULTS.MAXIMUM.`as`("performance_result.maximum"), ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) - .fetchResultSet() + .from(PERFORMANCE_RESULTS) + .innerJoin(TEST_RUN).on(PERFORMANCE_RESULTS.TEST_RUN_ID.eq(TEST_RUN.ID)) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .where( + GIT_METADATA.REPO_NAME.eq(repoName) + .and(withProjectName(projectName)), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) + .fetchResultSet() - val timelineEntries: List = resultSet.use { - repositoryPerformanceTimelineEntryMapper.stream(resultSet).toList() - } + val timelineEntries: List = + resultSet.use { + repositoryPerformanceTimelineEntryMapper.stream(resultSet).toList() + } timelineEntries } diff --git a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceRepository.kt index c4061450e..f40b08a64 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceRepository.kt @@ -3,5 +3,8 @@ package projektor.repository.performance import projektor.server.api.repository.performance.RepositoryPerformanceTestTimelineEntry interface RepositoryPerformanceRepository { - suspend fun fetchTestTimelineEntries(repoName: String, projectName: String?): List + suspend fun fetchTestTimelineEntries( + repoName: String, + projectName: String?, + ): List } diff --git a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceService.kt b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceService.kt index 00c8c493e..4787d1a9c 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceService.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/performance/RepositoryPerformanceService.kt @@ -4,14 +4,18 @@ import projektor.server.api.repository.performance.RepositoryPerformanceTestTime import projektor.server.api.repository.performance.RepositoryPerformanceTimeline class RepositoryPerformanceService(private val repositoryPerformanceRepository: RepositoryPerformanceRepository) { - suspend fun fetchPerformanceTimeline(repoName: String, projectName: String?): RepositoryPerformanceTimeline? { + suspend fun fetchPerformanceTimeline( + repoName: String, + projectName: String?, + ): RepositoryPerformanceTimeline? { val entries = repositoryPerformanceRepository.fetchTestTimelineEntries(repoName, projectName) return if (entries.isNotEmpty()) { val entriesByName = entries.groupBy { it.performanceResult.name } - val testTimelines: List = entriesByName.toList().map { (name, entries) -> - RepositoryPerformanceTestTimeline(name, entries) - } + val testTimelines: List = + entriesByName.toList().map { (name, entries) -> + RepositoryPerformanceTestTimeline(name, entries) + } RepositoryPerformanceTimeline(testTimelines) } else { diff --git a/server/server-app/src/main/kotlin/projektor/repository/testrun/FlakyTestCalculator.kt b/server/server-app/src/main/kotlin/projektor/repository/testrun/FlakyTestCalculator.kt index 434769cf5..d5de5c3b3 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/testrun/FlakyTestCalculator.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/testrun/FlakyTestCalculator.kt @@ -5,28 +5,34 @@ import projektor.server.api.TestCase import projektor.server.api.repository.RepositoryFlakyTest class FlakyTestCalculator { - fun calculateFlakyTests(failingTestCases: List, flakyFailureThreshold: Int, testRunCount: Long): List { + fun calculateFlakyTests( + failingTestCases: List, + flakyFailureThreshold: Int, + testRunCount: Long, + ): List { val testCaseGroups = failingTestCases.groupBy { it.fullName } val flakyTestCaseGroups = testCaseGroups.filter { it.value.size >= flakyFailureThreshold } - val flakyTestCases = flakyTestCaseGroups.map { flakyTestCaseGroup -> - val firstTestCase = flakyTestCaseGroup.value.minByOrNull { it.createdTimestamp }!! - val latestTestCase = flakyTestCaseGroup.value.maxByOrNull { it.createdTimestamp }!! + val flakyTestCases = + flakyTestCaseGroups.map { flakyTestCaseGroup -> + val firstTestCase = flakyTestCaseGroup.value.minByOrNull { it.createdTimestamp }!! + val latestTestCase = flakyTestCaseGroup.value.maxByOrNull { it.createdTimestamp }!! - val failurePercentage = calculatePercentage( - flakyTestCaseGroup.value.size.toBigDecimal(), - testRunCount.toBigDecimal() - ) + val failurePercentage = + calculatePercentage( + flakyTestCaseGroup.value.size.toBigDecimal(), + testRunCount.toBigDecimal(), + ) - RepositoryFlakyTest( - testCase = flakyTestCaseGroup.value.first(), - failureCount = flakyTestCaseGroup.value.size, - failurePercentage = failurePercentage, - firstTestCase = firstTestCase, - latestTestCase = latestTestCase - ) - } + RepositoryFlakyTest( + testCase = flakyTestCaseGroup.value.first(), + failureCount = flakyTestCaseGroup.value.size, + failurePercentage = failurePercentage, + firstTestCase = firstTestCase, + latestTestCase = latestTestCase, + ) + } return flakyTestCases } diff --git a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepository.kt index e4326548c..156da9125 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepository.kt @@ -27,52 +27,63 @@ import kotlin.streams.toList class RepositoryTestRunDatabaseRepository(private val dslContext: DSLContext) : RepositoryTestRunRepository { private val tracer = GlobalOpenTelemetry.getTracer("projektor.RepositoryTestRunDatabaseRepository") - private val timelineEntryMapper = JdbcMapperFactory.newInstance() - .addKeys("public_id") - .ignorePropertyNotFound() - .newMapper(RepositoryTestRunTimelineEntry::class.java) + private val timelineEntryMapper = + JdbcMapperFactory.newInstance() + .addKeys("public_id") + .ignorePropertyNotFound() + .newMapper(RepositoryTestRunTimelineEntry::class.java) - override suspend fun fetchRepositoryTestRunTimeline(repoName: String, projectName: String?): RepositoryTestRunTimeline? = + override suspend fun fetchRepositoryTestRunTimeline( + repoName: String, + projectName: String?, + ): RepositoryTestRunTimeline? = withContext(Dispatchers.IO) { - val resultSet = dslContext.select( - TEST_RUN.PUBLIC_ID, - TEST_RUN.CREATED_TIMESTAMP, - TEST_RUN.CUMULATIVE_DURATION, - TEST_RUN.WALL_CLOCK_DURATION, - TEST_RUN.PASSED, - TEST_RUN.TOTAL_TEST_COUNT - ) - .from(TEST_RUN) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) - .where(runInCIFromRepo(repoName, projectName)) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) - .fetchResultSet() - - val timelineEntries: List = resultSet.use { - timelineEntryMapper.stream(resultSet).toList() - } + val resultSet = + dslContext.select( + TEST_RUN.PUBLIC_ID, + TEST_RUN.CREATED_TIMESTAMP, + TEST_RUN.CUMULATIVE_DURATION, + TEST_RUN.WALL_CLOCK_DURATION, + TEST_RUN.PASSED, + TEST_RUN.TOTAL_TEST_COUNT, + ) + .from(TEST_RUN) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) + .where(runInCIFromRepo(repoName, projectName)) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.asc()) + .fetchResultSet() + + val timelineEntries: List = + resultSet.use { + timelineEntryMapper.stream(resultSet).toList() + } if (timelineEntries.isNotEmpty()) RepositoryTestRunTimeline(timelineEntries) else null } - override suspend fun fetchRepositoryTestRunSummaries(repoName: String, projectName: String?, limit: Int): List = + override suspend fun fetchRepositoryTestRunSummaries( + repoName: String, + projectName: String?, + limit: Int, + ): List = withContext(Dispatchers.IO) { val span = tracer.startSpanWithParent("projektor.fetchRepositoryTestRunSummaries") - val testRunSummaries = dslContext - .select(TEST_RUN.PUBLIC_ID.`as`("id")) - .select(TEST_RUN.fields().filterNot { it.name == "id" }.toList()) - .from(TEST_RUN) - .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .where( - runInCIFromRepo(repoName, projectName) - .and(withBranchType(BranchType.MAINLINE)) - ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc()) - .limit(limit) - .fetchInto(TestRunSummary::class.java) + val testRunSummaries = + dslContext + .select(TEST_RUN.PUBLIC_ID.`as`("id")) + .select(TEST_RUN.fields().filterNot { it.name == "id" }.toList()) + .from(TEST_RUN) + .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .where( + runInCIFromRepo(repoName, projectName) + .and(withBranchType(BranchType.MAINLINE)), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc()) + .limit(limit) + .fetchInto(TestRunSummary::class.java) span.end() @@ -83,44 +94,48 @@ class RepositoryTestRunDatabaseRepository(private val dslContext: DSLContext) : repoName: String, projectName: String?, maxRuns: Int, - branchType: BranchType + branchType: BranchType, ): List = withContext(Dispatchers.IO) { - - val resultSet = selectTestCase(dslContext) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) - .where( - runInCIFromRepo(repoName, projectName) - .and(TEST_CASE.PASSED.eq(false)) - .and(withBranchType(branchType)) - .and( - TEST_RUN.CREATED_TIMESTAMP.ge( - dslContext - .select(min(TEST_RUN.`as`("x").CREATED_TIMESTAMP)) - .from( - ( - dslContext.select(TEST_RUN.CREATED_TIMESTAMP) - .from(TEST_RUN) - .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) - .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) - .where(runInCIFromRepo(repoName, projectName).and(withBranchType(branchType))) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) - .limit(maxRuns) - ).asTable("x") - ) - ) - ) - ) - .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) - .fetchResultSet() + val resultSet = + selectTestCase(dslContext) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) + .where( + runInCIFromRepo(repoName, projectName) + .and(TEST_CASE.PASSED.eq(false)) + .and(withBranchType(branchType)) + .and( + TEST_RUN.CREATED_TIMESTAMP.ge( + dslContext + .select(min(TEST_RUN.`as`("x").CREATED_TIMESTAMP)) + .from( + ( + dslContext.select(TEST_RUN.CREATED_TIMESTAMP) + .from(TEST_RUN) + .innerJoin(GIT_METADATA).on(TEST_RUN.ID.eq(GIT_METADATA.TEST_RUN_ID)) + .innerJoin(RESULTS_METADATA).on(TEST_RUN.ID.eq(RESULTS_METADATA.TEST_RUN_ID)) + .where(runInCIFromRepo(repoName, projectName).and(withBranchType(branchType))) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) + .limit(maxRuns) + ).asTable("x"), + ), + ), + ), + ) + .orderBy(TEST_RUN.CREATED_TIMESTAMP.desc().nullsLast()) + .fetchResultSet() val testCases = resultSet.use { TestCaseDatabaseRepository.testCaseMapper.stream(it).toList() } testCases } - override suspend fun fetchRecentTestRunPublicIds(repoName: String, projectName: String?, maxRuns: Int): List = + override suspend fun fetchRecentTestRunPublicIds( + repoName: String, + projectName: String?, + maxRuns: Int, + ): List = withContext(Dispatchers.IO) { dslContext .select(TEST_RUN.PUBLIC_ID) @@ -134,7 +149,10 @@ class RepositoryTestRunDatabaseRepository(private val dslContext: DSLContext) : .map { PublicId(it) } } - override suspend fun fetchTestRunCount(repoName: String, projectName: String?): Long = + override suspend fun fetchTestRunCount( + repoName: String, + projectName: String?, + ): Long = withContext(Dispatchers.IO) { dslContext .select(count(TEST_RUN.ID)) @@ -146,7 +164,10 @@ class RepositoryTestRunDatabaseRepository(private val dslContext: DSLContext) : } companion object { - fun runInCIFromRepo(repoName: String, projectName: String?): Condition = + fun runInCIFromRepo( + repoName: String, + projectName: String?, + ): Condition = GIT_METADATA.REPO_NAME.eq(repoName) .and(withProjectName(projectName)) .and(RESULTS_METADATA.CI.eq(true)) @@ -165,9 +186,10 @@ class RepositoryTestRunDatabaseRepository(private val dslContext: DSLContext) : } fun withProjectName(projectName: String?): Condition = - if (projectName == null) + if (projectName == null) { GIT_METADATA.PROJECT_NAME.isNull - else + } else { GIT_METADATA.PROJECT_NAME.eq(projectName) + } } } diff --git a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunRepository.kt b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunRepository.kt index 685086903..246d2482c 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunRepository.kt @@ -7,13 +7,32 @@ import projektor.server.api.repository.BranchType import projektor.server.api.repository.RepositoryTestRunTimeline interface RepositoryTestRunRepository { - suspend fun fetchRepositoryTestRunTimeline(repoName: String, projectName: String?): RepositoryTestRunTimeline? + suspend fun fetchRepositoryTestRunTimeline( + repoName: String, + projectName: String?, + ): RepositoryTestRunTimeline? - suspend fun fetchRepositoryTestRunSummaries(repoName: String, projectName: String?, limit: Int): List + suspend fun fetchRepositoryTestRunSummaries( + repoName: String, + projectName: String?, + limit: Int, + ): List - suspend fun fetchRepositoryFailingTestCases(repoName: String, projectName: String?, maxRuns: Int, branchType: BranchType): List + suspend fun fetchRepositoryFailingTestCases( + repoName: String, + projectName: String?, + maxRuns: Int, + branchType: BranchType, + ): List - suspend fun fetchRecentTestRunPublicIds(repoName: String, projectName: String?, maxRuns: Int): List + suspend fun fetchRecentTestRunPublicIds( + repoName: String, + projectName: String?, + maxRuns: Int, + ): List - suspend fun fetchTestRunCount(repoName: String, projectName: String?): Long + suspend fun fetchTestRunCount( + repoName: String, + projectName: String?, + ): Long } diff --git a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunService.kt b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunService.kt index 354c26899..cd087efd4 100644 --- a/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunService.kt +++ b/server/server-app/src/main/kotlin/projektor/repository/testrun/RepositoryTestRunService.kt @@ -8,15 +8,17 @@ import kotlin.math.min class RepositoryTestRunService(private val repositoryTestRunRepository: RepositoryTestRunRepository) { private val flakyTestCalculator = FlakyTestCalculator() - suspend fun fetchRepositoryTestRunTimeline(repoName: String, projectName: String?) = - repositoryTestRunRepository.fetchRepositoryTestRunTimeline(repoName, projectName) + suspend fun fetchRepositoryTestRunTimeline( + repoName: String, + projectName: String?, + ) = repositoryTestRunRepository.fetchRepositoryTestRunTimeline(repoName, projectName) suspend fun fetchFlakyTests( repoName: String, projectName: String?, maxRuns: Int, flakyFailureThreshold: Int, - branchType: BranchType + branchType: BranchType, ): List { val failingTestCases = repositoryTestRunRepository.fetchRepositoryFailingTestCases(repoName, projectName, maxRuns, branchType) val totalTestRunCount = repositoryTestRunRepository.fetchTestRunCount(repoName, projectName) @@ -25,6 +27,9 @@ class RepositoryTestRunService(private val repositoryTestRunRepository: Reposito return flakyTestCalculator.calculateFlakyTests(failingTestCases, flakyFailureThreshold, testRunCount) } - suspend fun fetchRepositoryTestRunSummaries(repoName: String, projectName: String?, limit: Int): List = - repositoryTestRunRepository.fetchRepositoryTestRunSummaries(repoName, projectName, limit) + suspend fun fetchRepositoryTestRunSummaries( + repoName: String, + projectName: String?, + limit: Int, + ): List = repositoryTestRunRepository.fetchRepositoryTestRunSummaries(repoName, projectName, limit) } diff --git a/server/server-app/src/main/kotlin/projektor/route/ApiRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/ApiRoutes.kt index 5f6a3e3ab..843a75068 100644 --- a/server/server-app/src/main/kotlin/projektor/route/ApiRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/ApiRoutes.kt @@ -39,17 +39,19 @@ fun Route.api( val projectName = call.request.queryParameters["project"] val branchName = call.request.queryParameters["branch"] - val branchSearch = if (branchName != null) { - BranchSearch(branchName = branchName) - } else { - BranchSearch(branchType = BranchType.MAINLINE) - } - - val repositoryCurrentCoverage = repositoryCoverageService.fetchRepositoryCurrentCoverage( - fullRepoName, - projectName, - branchSearch - ) + val branchSearch = + if (branchName != null) { + BranchSearch(branchName = branchName) + } else { + BranchSearch(branchType = BranchType.MAINLINE) + } + + val repositoryCurrentCoverage = + repositoryCoverageService.fetchRepositoryCurrentCoverage( + fullRepoName, + projectName, + branchSearch, + ) repositoryCurrentCoverage?.let { call.respond(HttpStatusCode.OK, it) } ?: call.respond(HttpStatusCode.NoContent) @@ -65,13 +67,14 @@ fun Route.api( val fullRepoName = "$orgPart/$repoPart" - val flakyTests = repositoryTestRunService.fetchFlakyTests( - repoName = fullRepoName, - projectName = projectName, - maxRuns = maxRuns, - flakyFailureThreshold = flakyThreshold, - branchType = branchType - ) + val flakyTests = + repositoryTestRunService.fetchFlakyTests( + repoName = fullRepoName, + projectName = projectName, + maxRuns = maxRuns, + flakyFailureThreshold = flakyThreshold, + branchType = branchType, + ) if (flakyTests.isNotEmpty()) { call.respond( @@ -79,8 +82,8 @@ fun Route.api( RepositoryFlakyTests( tests = flakyTests, maxRuns = maxRuns, - failureCountThreshold = flakyThreshold - ) + failureCountThreshold = flakyThreshold, + ), ) } else { call.respond(HttpStatusCode.NoContent) diff --git a/server/server-app/src/main/kotlin/projektor/route/AttachmentRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/AttachmentRoutes.kt index 0308efe52..70d0e235d 100644 --- a/server/server-app/src/main/kotlin/projektor/route/AttachmentRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/AttachmentRoutes.kt @@ -23,26 +23,37 @@ import projektor.server.api.attachments.Attachments fun Route.attachments( attachmentService: AttachmentService?, - authService: AuthService + authService: AuthService, ) { post("/run/{publicId}/attachments/{attachmentName}") { val publicId = call.parameters.getOrFail("publicId") val attachmentName = call.parameters.getOrFail("attachmentName") - val attachmentStream = withContext(Dispatchers.IO) { - call.receiveStream() - } + val attachmentStream = + withContext(Dispatchers.IO) { + call.receiveStream() + } val contentLengthInBytes = call.request.header("content-length")?.toLong() - if (!authService.isAuthValid(call.request.header(AuthConfig.PublishToken))) { + if (!authService.isAuthValid(call.request.header(AuthConfig.PUBLISH_TOKEN))) { call.respond(HttpStatusCode.Unauthorized) } else if (attachmentService != null) { if (attachmentService.attachmentSizeValid(contentLengthInBytes)) { - val addAttachmentResult = attachmentService.addAttachment(PublicId(publicId), attachmentName, attachmentStream, contentLengthInBytes) + val addAttachmentResult = + attachmentService.addAttachment( + PublicId(publicId), + attachmentName, + attachmentStream, + contentLengthInBytes, + ) when (addAttachmentResult) { AddAttachmentResult.Success -> call.respond(HttpStatusCode.OK, AddAttachmentResponse(attachmentName, null)) - is AddAttachmentResult.Failure -> call.respond(HttpStatusCode.BadRequest, AddAttachmentResponse(attachmentName, AddAttachmentError.ATTACHMENT_FAILED)) + is AddAttachmentResult.Failure -> + call.respond( + HttpStatusCode.BadRequest, + AddAttachmentResponse(attachmentName, AddAttachmentError.ATTACHMENT_FAILED), + ) } } else { call.respond(HttpStatusCode.BadRequest, AddAttachmentResponse(null, AddAttachmentError.ATTACHMENT_TOO_LARGE)) diff --git a/server/server-app/src/main/kotlin/projektor/route/CodeQualityRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/CodeQualityRoutes.kt index b65e59dda..2cf410e4b 100644 --- a/server/server-app/src/main/kotlin/projektor/route/CodeQualityRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/CodeQualityRoutes.kt @@ -10,9 +10,7 @@ import projektor.quality.CodeQualityReportRepository import projektor.server.api.PublicId import projektor.server.api.quality.CodeQualityReports -fun Route.codeQuality( - codeQualityReportRepository: CodeQualityReportRepository -) { +fun Route.codeQuality(codeQualityReportRepository: CodeQualityReportRepository) { get("/run/{publicId}/quality") { val publicId = call.parameters.getOrFail("publicId") diff --git a/server/server-app/src/main/kotlin/projektor/route/CompressionRequest.kt b/server/server-app/src/main/kotlin/projektor/route/CompressionRequest.kt index 4482a0165..9c5a7e9f0 100644 --- a/server/server-app/src/main/kotlin/projektor/route/CompressionRequest.kt +++ b/server/server-app/src/main/kotlin/projektor/route/CompressionRequest.kt @@ -8,11 +8,12 @@ import projektor.util.ungzip object CompressionRequest { suspend fun receiveCompressedOrPlainTextPayload(call: ApplicationCall): String { - val payload = if (call.request.header(HttpHeaders.ContentEncoding) == "gzip") { - ungzip(call.receive()) - } else { - call.receive() - } + val payload = + if (call.request.header(HttpHeaders.ContentEncoding) == "gzip") { + ungzip(call.receive()) + } else { + call.receive() + } return payload } diff --git a/server/server-app/src/main/kotlin/projektor/route/ConfigRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/ConfigRoutes.kt index 201c240ef..bfb3112b3 100644 --- a/server/server-app/src/main/kotlin/projektor/route/ConfigRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/ConfigRoutes.kt @@ -16,9 +16,9 @@ fun Route.config(cleanupConfig: CleanupConfig) { ServerConfig( ServerCleanupConfig( cleanupConfig.enabled, - cleanupConfig.maxReportAgeDays - ) - ) + cleanupConfig.maxReportAgeDays, + ), + ), ) } } diff --git a/server/server-app/src/main/kotlin/projektor/route/CoverageRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/CoverageRoutes.kt index ce114d1c7..87eacd736 100644 --- a/server/server-app/src/main/kotlin/projektor/route/CoverageRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/CoverageRoutes.kt @@ -18,11 +18,14 @@ import projektor.server.api.coverage.CoverageExists import projektor.server.api.coverage.CoverageFiles import projektor.server.api.coverage.SaveCoverageError -fun Route.coverage(authService: AuthService, coverageService: CoverageService) { +fun Route.coverage( + authService: AuthService, + coverageService: CoverageService, +) { post("/run/{publicId}/coverage") { val publicId = call.parameters.getOrFail("publicId") - if (!authService.isAuthValid(call.request.header(AuthConfig.PublishToken))) { + if (!authService.isAuthValid(call.request.header(AuthConfig.PUBLISH_TOKEN))) { call.respond(HttpStatusCode.Unauthorized) } else { val reportXml = receiveCompressedOrPlainTextPayload(call) @@ -40,7 +43,7 @@ fun Route.coverage(authService: AuthService, coverageService: CoverageService) { post("/run/{publicId}/coverageFile") { val publicId = call.parameters.getOrFail("publicId") - if (!authService.isAuthValid(call.request.header(AuthConfig.PublishToken))) { + if (!authService.isAuthValid(call.request.header(AuthConfig.PUBLISH_TOKEN))) { call.respond(HttpStatusCode.Unauthorized) } else { val incomingPayload = receiveCompressedOrPlainTextPayload(call) diff --git a/server/server-app/src/main/kotlin/projektor/route/MetadataRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/MetadataRoutes.kt index 4b53bf19a..f7a40a18c 100644 --- a/server/server-app/src/main/kotlin/projektor/route/MetadataRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/MetadataRoutes.kt @@ -12,7 +12,7 @@ import projektor.versioncontrol.VersionControlConfig fun Route.metadata( testRunMetadataService: TestRunMetadataService, - versionControlConfig: VersionControlConfig + versionControlConfig: VersionControlConfig, ) { get("/run/{publicId}/metadata") { val publicId = call.parameters.getOrFail("publicId") diff --git a/server/server-app/src/main/kotlin/projektor/route/RepositoryCoverageRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/RepositoryCoverageRoutes.kt index a3873f46e..aa0b57592 100644 --- a/server/server-app/src/main/kotlin/projektor/route/RepositoryCoverageRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/RepositoryCoverageRoutes.kt @@ -12,9 +12,7 @@ import projektor.server.api.coverage.CoverageExists import projektor.server.api.repository.BranchSearch import projektor.server.api.repository.BranchType -fun Route.repositoryCoverage( - repositoryCoverageService: RepositoryCoverageService, -) { +fun Route.repositoryCoverage(repositoryCoverageService: RepositoryCoverageService) { fun findBranchType(call: ApplicationCall): BranchType { val branchTypeString = (call.request.queryParameters["branch"] ?: "MAINLINE").uppercase() return BranchType.valueOf(branchTypeString) @@ -70,20 +68,21 @@ fun Route.repositoryCoverage( orgPart: String, repoPart: String, projectName: String?, - call: ApplicationCall + call: ApplicationCall, ) { val fullRepoName = "$orgPart/$repoPart" - val repositoryCurrentCoverage = repositoryCoverageService.fetchRepositoryCurrentCoverage( - fullRepoName, - projectName, - BranchSearch(branchType = BranchType.MAINLINE) - ) + val repositoryCurrentCoverage = + repositoryCoverageService.fetchRepositoryCurrentCoverage( + fullRepoName, + projectName, + BranchSearch(branchType = BranchType.MAINLINE), + ) if (repositoryCurrentCoverage != null) { call.respond( HttpStatusCode.OK, - repositoryCurrentCoverage + repositoryCurrentCoverage, ) } else { call.respond(HttpStatusCode.NoContent) diff --git a/server/server-app/src/main/kotlin/projektor/route/RepositoryRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/RepositoryRoutes.kt index 78d8e3698..b6524b68e 100644 --- a/server/server-app/src/main/kotlin/projektor/route/RepositoryRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/RepositoryRoutes.kt @@ -15,7 +15,7 @@ import projektor.server.api.repository.RepositoryFlakyTests fun Route.repository( previousTestRunService: PreviousTestRunService, - repositoryTestRunService: RepositoryTestRunService + repositoryTestRunService: RepositoryTestRunService, ) { get("/repo/{orgPart}/{repoPart}/timeline") { val orgPart = call.parameters.getOrFail("orgPart") @@ -47,17 +47,18 @@ fun Route.repository( maxRuns: Int, flakyThreshold: Int, branchType: BranchType, - call: ApplicationCall + call: ApplicationCall, ) { val fullRepoName = "$orgPart/$repoPart" - val flakyTests = repositoryTestRunService.fetchFlakyTests( - repoName = fullRepoName, - projectName = projectName, - maxRuns = maxRuns, - flakyFailureThreshold = flakyThreshold, - branchType = branchType - ) + val flakyTests = + repositoryTestRunService.fetchFlakyTests( + repoName = fullRepoName, + projectName = projectName, + maxRuns = maxRuns, + flakyFailureThreshold = flakyThreshold, + branchType = branchType, + ) if (flakyTests.isNotEmpty()) { call.respond( @@ -65,8 +66,8 @@ fun Route.repository( RepositoryFlakyTests( tests = flakyTests, maxRuns = maxRuns, - failureCountThreshold = flakyThreshold - ) + failureCountThreshold = flakyThreshold, + ), ) } else { call.respond(HttpStatusCode.NoContent) @@ -87,7 +88,7 @@ fun Route.repository( maxRuns = maxRuns, flakyThreshold = flakyThreshold, branchType = branchType, - call + call, ) } @@ -106,7 +107,7 @@ fun Route.repository( maxRuns = maxRuns, flakyThreshold = flakyThreshold, branchType = branchType, - call + call, ) } @@ -115,11 +116,12 @@ fun Route.repository( val repoPart = call.parameters.getOrFail("repoPart") val fullRepoName = "$orgPart/$repoPart" - val latestTestRun = previousTestRunService.findMostRecentRun( - fullRepoName, - null, - BranchSearch(branchType = BranchType.MAINLINE) - ) + val latestTestRun = + previousTestRunService.findMostRecentRun( + fullRepoName, + null, + BranchSearch(branchType = BranchType.MAINLINE), + ) latestTestRun?.let { call.respondRedirect("/tests/${latestTestRun.publicId.id}", permanent = false) } ?: call.respond(HttpStatusCode.NoContent) @@ -131,11 +133,12 @@ fun Route.repository( val projectName = call.parameters.getOrFail("projectName") val fullRepoName = "$orgPart/$repoPart" - val latestTestRun = previousTestRunService.findMostRecentRun( - fullRepoName, - projectName, - BranchSearch(branchType = BranchType.MAINLINE) - ) + val latestTestRun = + previousTestRunService.findMostRecentRun( + fullRepoName, + projectName, + BranchSearch(branchType = BranchType.MAINLINE), + ) latestTestRun?.let { call.respondRedirect("/tests/${latestTestRun.publicId.id}", permanent = false) } ?: call.respond(HttpStatusCode.NoContent) diff --git a/server/server-app/src/main/kotlin/projektor/route/ResultsRoutes.kt b/server/server-app/src/main/kotlin/projektor/route/ResultsRoutes.kt index 815b26998..663c94130 100644 --- a/server/server-app/src/main/kotlin/projektor/route/ResultsRoutes.kt +++ b/server/server-app/src/main/kotlin/projektor/route/ResultsRoutes.kt @@ -28,10 +28,10 @@ fun Route.results( testResultsProcessingService: TestResultsProcessingService, authService: AuthService, metricRegistry: MeterRegistry, - metricsService: MetricsService + metricsService: MetricsService, ) { post("/results") { - if (!authService.isAuthValid(call.request.header(AuthConfig.PublishToken))) { + if (!authService.isAuthValid(call.request.header(AuthConfig.PUBLISH_TOKEN))) { call.respond(HttpStatusCode.Unauthorized) } else { metricsService.incrementResultsProcessStartCounter() @@ -48,7 +48,7 @@ fun Route.results( } } post("/groupedResults") { - if (!authService.isAuthValid(call.request.header(AuthConfig.PublishToken))) { + if (!authService.isAuthValid(call.request.header(AuthConfig.PUBLISH_TOKEN))) { call.respond(HttpStatusCode.Unauthorized) } else { metricsService.incrementResultsProcessStartCounter() diff --git a/server/server-app/src/main/kotlin/projektor/route/SvgRouteUtils.kt b/server/server-app/src/main/kotlin/projektor/route/SvgRouteUtils.kt index bd3db80a3..fff2bc91e 100644 --- a/server/server-app/src/main/kotlin/projektor/route/SvgRouteUtils.kt +++ b/server/server-app/src/main/kotlin/projektor/route/SvgRouteUtils.kt @@ -4,7 +4,10 @@ import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* -suspend fun respondWithSvg(svgBadge: String?, call: ApplicationCall) { +suspend fun respondWithSvg( + svgBadge: String?, + call: ApplicationCall, +) { svgBadge?.let { svg -> call.respondText( svg, diff --git a/server/server-app/src/main/kotlin/projektor/schedule/Scheduler.kt b/server/server-app/src/main/kotlin/projektor/schedule/Scheduler.kt index bc7ec9356..986dfef0e 100644 --- a/server/server-app/src/main/kotlin/projektor/schedule/Scheduler.kt +++ b/server/server-app/src/main/kotlin/projektor/schedule/Scheduler.kt @@ -10,9 +10,10 @@ class Scheduler(private val schedulerLock: SchedulerLock) { private val scheduledJobs = ConcurrentHashMap() fun scheduleJob(job: ScheduledJob) { - val runnableWithLock = Runnable { - schedulerLock.executeWithLock(job.runnable, SchedulerLockConfig(60, job.name)) - } + val runnableWithLock = + Runnable { + schedulerLock.executeWithLock(job.runnable, SchedulerLockConfig(60, job.name)) + } executor.scheduleWithFixedDelay(runnableWithLock, job.scheduleDelay.value, job.scheduleDelay.value, job.scheduleDelay.unit) diff --git a/server/server-app/src/main/kotlin/projektor/schedule/SchedulerLock.kt b/server/server-app/src/main/kotlin/projektor/schedule/SchedulerLock.kt index 31f79d9b4..77378a117 100644 --- a/server/server-app/src/main/kotlin/projektor/schedule/SchedulerLock.kt +++ b/server/server-app/src/main/kotlin/projektor/schedule/SchedulerLock.kt @@ -11,7 +11,10 @@ class SchedulerLock(dataSource: DataSource) { private val lockProvider = JdbcTemplateLockProvider(dataSource) private val executor = DefaultLockingTaskExecutor(lockProvider) - fun executeWithLock(runnable: Runnable, lockConfig: SchedulerLockConfig) { + fun executeWithLock( + runnable: Runnable, + lockConfig: SchedulerLockConfig, + ) { val lockAtMostFor: Duration = Duration.ofMinutes(lockConfig.lockMinutes) val lockAtLeastFor: Duration = Duration.ofSeconds(15) executor.executeWithLock(runnable, LockConfiguration(Instant.now(), lockConfig.lockName, lockAtMostFor, lockAtLeastFor)) diff --git a/server/server-app/src/main/kotlin/projektor/telemetry/OpenTelemetryRoute.kt b/server/server-app/src/main/kotlin/projektor/telemetry/OpenTelemetryRoute.kt index a15db1e50..421ea4ee7 100644 --- a/server/server-app/src/main/kotlin/projektor/telemetry/OpenTelemetryRoute.kt +++ b/server/server-app/src/main/kotlin/projektor/telemetry/OpenTelemetryRoute.kt @@ -7,7 +7,6 @@ import io.ktor.util.AttributeKey import io.opentelemetry.api.trace.Span class OpenTelemetryRoute { - class Configuration { var includeHttpMethod: Boolean = false } @@ -15,7 +14,10 @@ class OpenTelemetryRoute { companion object Feature : BaseApplicationPlugin { override val key: AttributeKey = AttributeKey("OpenTelemetryRoute") - override fun install(pipeline: Application, configure: Configuration.() -> Unit): OpenTelemetryRoute { + override fun install( + pipeline: Application, + configure: Configuration.() -> Unit, + ): OpenTelemetryRoute { val configuration = Configuration().apply(configure) pipeline.environment.monitor.subscribe(Routing.RoutingCallStarted) { call -> diff --git a/server/server-app/src/main/kotlin/projektor/testcase/CypressScreenshotAttachmentMatcher.kt b/server/server-app/src/main/kotlin/projektor/testcase/CypressScreenshotAttachmentMatcher.kt index e0c98599c..56400d418 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/CypressScreenshotAttachmentMatcher.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/CypressScreenshotAttachmentMatcher.kt @@ -4,7 +4,10 @@ import projektor.server.api.TestCase import projektor.server.api.attachments.Attachment class CypressScreenshotAttachmentMatcher : TestCaseAttachmentMatcher { - override fun findAttachment(testCase: TestCase, attachments: List?): Attachment? = + override fun findAttachment( + testCase: TestCase, + attachments: List?, + ): Attachment? = attachments?.find { attachment -> val testCaseNameWords = testCase.name.split(" ") diff --git a/server/server-app/src/main/kotlin/projektor/testcase/CypressVideoAttachmentMatcher.kt b/server/server-app/src/main/kotlin/projektor/testcase/CypressVideoAttachmentMatcher.kt index ba1696447..7e0c6af23 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/CypressVideoAttachmentMatcher.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/CypressVideoAttachmentMatcher.kt @@ -4,7 +4,10 @@ import projektor.server.api.TestCase import projektor.server.api.attachments.Attachment class CypressVideoAttachmentMatcher : TestCaseAttachmentMatcher { - override fun findAttachment(testCase: TestCase, attachments: List?): Attachment? = + override fun findAttachment( + testCase: TestCase, + attachments: List?, + ): Attachment? = attachments?.find { attachment -> val testCaseFilePathParts = testCase.fileName?.split("/") diff --git a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseAttachmentMatcher.kt b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseAttachmentMatcher.kt index 65e5f0e3d..0600055f4 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseAttachmentMatcher.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseAttachmentMatcher.kt @@ -4,5 +4,8 @@ import projektor.server.api.TestCase import projektor.server.api.attachments.Attachment interface TestCaseAttachmentMatcher { - fun findAttachment(testCase: TestCase, attachments: List?): Attachment? + fun findAttachment( + testCase: TestCase, + attachments: List?, + ): Attachment? } diff --git a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseDatabaseRepository.kt index 0db258b7f..e0ceb856b 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseDatabaseRepository.kt @@ -19,54 +19,65 @@ import projektor.util.addPrefixToFields import kotlin.streams.toList class TestCaseDatabaseRepository(private val dslContext: DSLContext) : TestCaseRepository { - override suspend fun fetchFailedTestCases(testRunPublicId: PublicId): List = withContext(Dispatchers.IO) { - val resultSet = selectTestCase(dslContext) - .where( - TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id) - .and(TEST_CASE.PASSED.eq(false)) - ) - .orderBy(TEST_CASE.ID) - .fetchResultSet() + val resultSet = + selectTestCase(dslContext) + .where( + TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id) + .and(TEST_CASE.PASSED.eq(false)), + ) + .orderBy(TEST_CASE.ID) + .fetchResultSet() resultSet.use { testCaseMapper.stream(it).toList() } } - override suspend fun fetchSlowTestCases(testRunPublicId: PublicId, limit: Int): List = + override suspend fun fetchSlowTestCases( + testRunPublicId: PublicId, + limit: Int, + ): List = withContext(Dispatchers.IO) { - val resultSet = selectTestCase(dslContext) - .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id)) - .orderBy(TEST_CASE.DURATION.desc()) - .limit(limit) - .fetchResultSet() + val resultSet = + selectTestCase(dslContext) + .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id)) + .orderBy(TEST_CASE.DURATION.desc()) + .limit(limit) + .fetchResultSet() resultSet.use { testCaseMapper.stream(it).toList() } } - override suspend fun fetchTestCase(testRunPublicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestCase? = + override suspend fun fetchTestCase( + testRunPublicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestCase? = withContext(Dispatchers.IO) { - val resultSet = selectTestCase(dslContext) - .where( - TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id) - .and(TEST_SUITE.IDX.eq(testSuiteIdx)) - .and(TEST_CASE.IDX.eq(testCaseIdx)) - ) - .orderBy(TEST_CASE.ID) - .fetchResultSet() + val resultSet = + selectTestCase(dslContext) + .where( + TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id) + .and(TEST_SUITE.IDX.eq(testSuiteIdx)) + .and(TEST_CASE.IDX.eq(testCaseIdx)), + ) + .orderBy(TEST_CASE.ID) + .fetchResultSet() - val testCase: TestCase? = resultSet.use { - testCaseMapper.stream(resultSet).findFirst().orElse(null) - } + val testCase: TestCase? = + resultSet.use { + testCaseMapper.stream(resultSet).findFirst().orElse(null) + } testCase } companion object { - val testCaseMapper = JdbcMapperFactory.newInstance() - .addKeys("id", "failure_id") - .ignorePropertyNotFound() - .newMapper(TestCase::class.java) + val testCaseMapper = + JdbcMapperFactory.newInstance() + .addKeys("id", "failure_id") + .ignorePropertyNotFound() + .newMapper(TestCase::class.java) fun selectTestCase(dslContext: DSLContext): SelectOnConditionStep = dslContext @@ -88,15 +99,26 @@ class TestCaseDatabaseRepository(private val dslContext: DSLContext) : TestCaseR .leftOuterJoin(TEST_FAILURE).on(TEST_FAILURE.TEST_CASE_ID.eq(TEST_CASE.ID)) } - override suspend fun fetchTestCaseSystemErr(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput = - fetchTestCaseOutputField(publicId, testSuiteIdx, testCaseIdx, TEST_CASE.SYSTEM_ERR) + override suspend fun fetchTestCaseSystemErr( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput = fetchTestCaseOutputField(publicId, testSuiteIdx, testCaseIdx, TEST_CASE.SYSTEM_ERR) - override suspend fun fetchTestCaseSystemOut(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput = - fetchTestCaseOutputField(publicId, testSuiteIdx, testCaseIdx, TEST_CASE.SYSTEM_OUT) + override suspend fun fetchTestCaseSystemOut( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput = fetchTestCaseOutputField(publicId, testSuiteIdx, testCaseIdx, TEST_CASE.SYSTEM_OUT) - private suspend fun fetchTestCaseOutputField(testRunPublicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int, field: TableField) = - withContext(Dispatchers.IO) { - val outputValue = dslContext + private suspend fun fetchTestCaseOutputField( + testRunPublicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + field: TableField, + ) = withContext(Dispatchers.IO) { + val outputValue = + dslContext .select(field) .from(TEST_CASE) .innerJoin(TEST_SUITE).on(TEST_CASE.TEST_SUITE_ID.eq(TEST_SUITE.ID)) @@ -104,10 +126,10 @@ class TestCaseDatabaseRepository(private val dslContext: DSLContext) : TestCaseR .where( TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id) .and(TEST_SUITE.IDX.eq(testSuiteIdx)) - .and(TEST_CASE.IDX.eq(testCaseIdx)) + .and(TEST_CASE.IDX.eq(testCaseIdx)), ) .fetchOne(field) - TestOutput(outputValue) - } + TestOutput(outputValue) + } } diff --git a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseRepository.kt b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseRepository.kt index cf7466db0..c72337b5b 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseRepository.kt @@ -5,14 +5,28 @@ import projektor.server.api.TestCase import projektor.server.api.TestOutput interface TestCaseRepository { - suspend fun fetchFailedTestCases(testRunPublicId: PublicId): List - suspend fun fetchSlowTestCases(testRunPublicId: PublicId, limit: Int): List + suspend fun fetchSlowTestCases( + testRunPublicId: PublicId, + limit: Int, + ): List - suspend fun fetchTestCase(testRunPublicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestCase? + suspend fun fetchTestCase( + testRunPublicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestCase? - suspend fun fetchTestCaseSystemErr(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput + suspend fun fetchTestCaseSystemErr( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput - suspend fun fetchTestCaseSystemOut(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput + suspend fun fetchTestCaseSystemOut( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput } diff --git a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseService.kt b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseService.kt index 254e85f2f..bbdcc6d2f 100644 --- a/server/server-app/src/main/kotlin/projektor/testcase/TestCaseService.kt +++ b/server/server-app/src/main/kotlin/projektor/testcase/TestCaseService.kt @@ -7,23 +7,28 @@ import projektor.server.api.TestOutput class TestCaseService( private val testCaseRepository: TestCaseRepository, - private val attachmentService: AttachmentService? + private val attachmentService: AttachmentService?, ) { - - private val attachmentMatchers = listOf( - CypressScreenshotAttachmentMatcher(), - CypressVideoAttachmentMatcher() - ) - - suspend fun fetchTestCase(testRunPublicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestCase? { + private val attachmentMatchers = + listOf( + CypressScreenshotAttachmentMatcher(), + CypressVideoAttachmentMatcher(), + ) + + suspend fun fetchTestCase( + testRunPublicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestCase? { val testCase = testCaseRepository.fetchTestCase(testRunPublicId, testSuiteIdx, testCaseIdx) if (testCase?.passed == false) { val attachments = attachmentService?.listAttachments(testRunPublicId) - val testCaseAttachments = attachmentMatchers.mapNotNull { attachmentMatcher -> - attachmentMatcher.findAttachment(testCase, attachments) - } + val testCaseAttachments = + attachmentMatchers.mapNotNull { attachmentMatcher -> + attachmentMatcher.findAttachment(testCase, attachments) + } testCase.attachments = testCaseAttachments } @@ -38,9 +43,10 @@ class TestCaseService( val attachments = attachmentService?.listAttachments(publicId) failedTestCases.forEach { testCase -> - val testCaseAttachments = attachmentMatchers.mapNotNull { attachmentMatcher -> - attachmentMatcher.findAttachment(testCase, attachments) - } + val testCaseAttachments = + attachmentMatchers.mapNotNull { attachmentMatcher -> + attachmentMatcher.findAttachment(testCase, attachments) + } testCase.attachments = testCaseAttachments } @@ -49,12 +55,20 @@ class TestCaseService( return failedTestCases } - suspend fun fetchSlowTestCases(publicId: PublicId, limit: Int): List = - testCaseRepository.fetchSlowTestCases(publicId, limit) - - suspend fun fetchTestCaseSystemErr(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput = - testCaseRepository.fetchTestCaseSystemErr(publicId, testSuiteIdx, testCaseIdx) - - suspend fun fetchTestCaseSystemOut(publicId: PublicId, testSuiteIdx: Int, testCaseIdx: Int): TestOutput = - testCaseRepository.fetchTestCaseSystemOut(publicId, testSuiteIdx, testCaseIdx) + suspend fun fetchSlowTestCases( + publicId: PublicId, + limit: Int, + ): List = testCaseRepository.fetchSlowTestCases(publicId, limit) + + suspend fun fetchTestCaseSystemErr( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput = testCaseRepository.fetchTestCaseSystemErr(publicId, testSuiteIdx, testCaseIdx) + + suspend fun fetchTestCaseSystemOut( + publicId: PublicId, + testSuiteIdx: Int, + testCaseIdx: Int, + ): TestOutput = testCaseRepository.fetchTestCaseSystemOut(publicId, testSuiteIdx, testCaseIdx) } diff --git a/server/server-app/src/main/kotlin/projektor/testrun/TestRunDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/testrun/TestRunDatabaseRepository.kt index 9a3b4eaa5..174592902 100644 --- a/server/server-app/src/main/kotlin/projektor/testrun/TestRunDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testrun/TestRunDatabaseRepository.kt @@ -45,68 +45,77 @@ import projektor.parser.model.TestSuite as ParsedTestSuite class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRepository { private val logger = LoggerFactory.getLogger(javaClass.canonicalName) - private val testRunMapper = JdbcMapperFactory.newInstance() - .addKeys("id", "test_suites_id") - .ignorePropertyNotFound() - .newMapper(TestRun::class.java) + private val testRunMapper = + JdbcMapperFactory.newInstance() + .addKeys("id", "test_suites_id") + .ignorePropertyNotFound() + .newMapper(TestRun::class.java) private val tracer = GlobalOpenTelemetry.getTracer("projektor.TestRunDatabaseRepository") - override suspend fun saveTestRun(publicId: PublicId, testSuites: List) = - withContext(Dispatchers.IO) { - val testRunSummary = toTestRunSummary(publicId, testSuites, null) - val testRunDB = testRunSummary.toDB() - - dslContext.transaction { configuration -> - val testRunDao = TestRunDao(configuration) + override suspend fun saveTestRun( + publicId: PublicId, + testSuites: List, + ) = withContext(Dispatchers.IO) { + val testRunSummary = toTestRunSummary(publicId, testSuites, null) + val testRunDB = testRunSummary.toDB() - testRunDao.insert(testRunDB) + dslContext.transaction { configuration -> + val testRunDao = TestRunDao(configuration) - saveTestSuites(testSuites, testRunDB.id, null, 0, configuration) + testRunDao.insert(testRunDB) - logger.info("Finished inserting test run $publicId") - } + saveTestSuites(testSuites, testRunDB.id, null, 0, configuration) - testRunSummary + logger.info("Finished inserting test run $publicId") } - override suspend fun saveGroupedTestRun(publicId: PublicId, groupedResults: GroupedResults) = - withContext(Dispatchers.IO) { - val testSuites = groupedResults.groupedTestSuites.flatMap { it.testSuites } - val testRunSummary = toTestRunSummary(publicId, testSuites, groupedResults.wallClockDuration) - val testRunDB = testRunSummary.toDB() + testRunSummary + } - logger.info("Starting inserting test run $publicId") + override suspend fun saveGroupedTestRun( + publicId: PublicId, + groupedResults: GroupedResults, + ) = withContext(Dispatchers.IO) { + val testSuites = groupedResults.groupedTestSuites.flatMap { it.testSuites } + val testRunSummary = toTestRunSummary(publicId, testSuites, groupedResults.wallClockDuration) + val testRunDB = testRunSummary.toDB() - dslContext.transaction { configuration -> - val testRunDao = TestRunDao(configuration) - val testSuiteGroupDao = TestSuiteGroupDao(configuration) + logger.info("Starting inserting test run $publicId") - testRunDao.insert(testRunDB) + dslContext.transaction { configuration -> + val testRunDao = TestRunDao(configuration) + val testSuiteGroupDao = TestSuiteGroupDao(configuration) - var testSuiteStartingIndex = 0 + testRunDao.insert(testRunDB) - groupedResults.groupedTestSuites.forEach { groupedTestSuites -> - val testSuiteGroupDB = groupedTestSuites.toDB(testRunDB.id) - testSuiteGroupDao.insert(testSuiteGroupDB) + var testSuiteStartingIndex = 0 - saveTestSuites(groupedTestSuites.testSuites, testRunDB.id, testSuiteGroupDB.id, testSuiteStartingIndex, configuration) + groupedResults.groupedTestSuites.forEach { groupedTestSuites -> + val testSuiteGroupDB = groupedTestSuites.toDB(testRunDB.id) + testSuiteGroupDao.insert(testSuiteGroupDB) - testSuiteStartingIndex += groupedTestSuites.testSuites.size - } + saveTestSuites(groupedTestSuites.testSuites, testRunDB.id, testSuiteGroupDB.id, testSuiteStartingIndex, configuration) - saveResultsMetadata(testRunDB.id, groupedResults.metadata, configuration) - saveGitMetadata(testRunDB.id, groupedResults.metadata?.git, configuration) + testSuiteStartingIndex += groupedTestSuites.testSuites.size } - saveGitRepository(groupedResults.metadata?.git) + saveResultsMetadata(testRunDB.id, groupedResults.metadata, configuration) + saveGitMetadata(testRunDB.id, groupedResults.metadata?.git, configuration) + } - logger.info("Finished inserting test run $publicId") + saveGitRepository(groupedResults.metadata?.git) - Pair(testRunDB.id, testRunSummary) - } + logger.info("Finished inserting test run $publicId") - override suspend fun appendTestSuites(publicId: PublicId, startingIdx: Int, groupedTestSuites: List): Long = + Pair(testRunDB.id, testRunSummary) + } + + override suspend fun appendTestSuites( + publicId: PublicId, + startingIdx: Int, + groupedTestSuites: List, + ): Long = withContext(Dispatchers.IO) { var testRunId: Long = 0 logger.info("Starting appending test suites to $publicId") @@ -122,13 +131,14 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep groupedTestSuites.forEach { groupedTestSuites -> val existingTestSuiteDB = fetchTestSuiteGroup(testRunDB.id, groupedTestSuites.groupName) - val testSuiteGroupDB = if (existingTestSuiteDB != null) { - existingTestSuiteDB - } else { - val newTestSuiteGroupDB = groupedTestSuites.toDB(testRunDB.id) - testSuiteGroupDao.insert(newTestSuiteGroupDB) - newTestSuiteGroupDB - } + val testSuiteGroupDB = + if (existingTestSuiteDB != null) { + existingTestSuiteDB + } else { + val newTestSuiteGroupDB = groupedTestSuites.toDB(testRunDB.id) + testSuiteGroupDao.insert(newTestSuiteGroupDB) + newTestSuiteGroupDB + } saveTestSuites(groupedTestSuites.testSuites, testRunDB.id, testSuiteGroupDB.id, testSuiteStartingIndex, configuration) @@ -141,7 +151,11 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep testRunId } - override suspend fun updateTestRunSummary(testRunId: Long, testSuites: List, wallClockDuration: BigDecimal?): TestRunSummary = + override suspend fun updateTestRunSummary( + testRunId: Long, + testSuites: List, + wallClockDuration: BigDecimal?, + ): TestRunSummary = withContext(Dispatchers.IO) { val testRunDao = TestRunDao(dslContext.configuration()) val existingTestRun = testRunDao.fetchOneById(testRunId) @@ -169,7 +183,7 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep testRunId: Long, testGroupId: Long?, testSuiteStartingIndex: Int, - configuration: Configuration + configuration: Configuration, ) { val testSuiteDao = TestSuiteDao(configuration) val testCaseDao = TestCaseDao(configuration) @@ -194,7 +208,7 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep private fun saveResultsMetadata( testRunId: Long, resultsMetadata: ResultsMetadata?, - configuration: Configuration + configuration: Configuration, ) { val resultsMetadataDao = ResultsMetadataDao(configuration) @@ -206,7 +220,7 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep private fun saveGitMetadata( testRunId: Long, git: GitMetadata?, - configuration: Configuration + configuration: Configuration, ) { val gitMetadataDao = GitMetadataDao(configuration) @@ -237,7 +251,10 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep } } - private fun fetchTestSuiteGroup(testRunId: Long, groupName: String?): TestSuiteGroupDB? = + private fun fetchTestSuiteGroup( + testRunId: Long, + groupName: String?, + ): TestSuiteGroupDB? = dslContext .select(TEST_SUITE_GROUP.fields().toList()) .from(TEST_SUITE_GROUP) @@ -248,24 +265,26 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep withContext(Dispatchers.IO) { val span = tracer.startSpanWithParent("projektor.fetchTestRun") - val resultSet = dslContext - .select(TEST_RUN.PUBLIC_ID.`as`("id")) - .select(TEST_RUN.addPrefixToFields("summary")) - .select(TEST_SUITE.addPrefixToFields("test_suites_")) - .select(TEST_SUITE_GROUP.GROUP_LABEL.`as`("test_suites_group_label")) - .select(TEST_SUITE_GROUP.GROUP_NAME.`as`("test_suites_group_name")) - .from(TEST_RUN) - .leftOuterJoin(TEST_SUITE).on(TEST_SUITE.TEST_RUN_ID.eq(TEST_RUN.ID)) - .leftOuterJoin(TEST_SUITE_GROUP).on(TEST_SUITE.TEST_SUITE_GROUP_ID.eq(TEST_SUITE_GROUP.ID)) - .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) - .orderBy(TEST_RUN.ID) - .fetchResultSet() + val resultSet = + dslContext + .select(TEST_RUN.PUBLIC_ID.`as`("id")) + .select(TEST_RUN.addPrefixToFields("summary")) + .select(TEST_SUITE.addPrefixToFields("test_suites_")) + .select(TEST_SUITE_GROUP.GROUP_LABEL.`as`("test_suites_group_label")) + .select(TEST_SUITE_GROUP.GROUP_NAME.`as`("test_suites_group_name")) + .from(TEST_RUN) + .leftOuterJoin(TEST_SUITE).on(TEST_SUITE.TEST_RUN_ID.eq(TEST_RUN.ID)) + .leftOuterJoin(TEST_SUITE_GROUP).on(TEST_SUITE.TEST_SUITE_GROUP_ID.eq(TEST_SUITE_GROUP.ID)) + .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) + .orderBy(TEST_RUN.ID) + .fetchResultSet() val mapperSpan = tracer.startSpanWithParent("projektor.fetchTestRun.mapper") - val testRun: TestRun? = resultSet.use { - testRunMapper.stream(resultSet).findFirst().orElse(null) - } + val testRun: TestRun? = + resultSet.use { + testRunMapper.stream(resultSet).findFirst().orElse(null) + } mapperSpan.end() @@ -278,12 +297,13 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep withContext(Dispatchers.IO) { val span = tracer.startSpanWithParent("projektor.fetchTestRunSummary") - val testRunSummary = dslContext - .select(TEST_RUN.PUBLIC_ID.`as`("id")) - .select(TEST_RUN.fields().filterNot { it.name == "id" }.toList()) - .from(TEST_RUN) - .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) - .fetchOneInto(TestRunSummary::class.java) + val testRunSummary = + dslContext + .select(TEST_RUN.PUBLIC_ID.`as`("id")) + .select(TEST_RUN.fields().filterNot { it.name == "id" }.toList()) + .from(TEST_RUN) + .where(TEST_RUN.PUBLIC_ID.eq(publicId.id)) + .fetchOneInto(TestRunSummary::class.java) span.end() @@ -310,7 +330,10 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep override suspend fun findTestRunsCreatedBeforeAndNotPinnedWithAttachments(createdBefore: LocalDate): List = findTestRunsCreatedBeforeAndNotPinned(createdBefore, true) - override suspend fun findTestRunWithGroup(group: String, repoName: String): PublicId? = + override suspend fun findTestRunWithGroup( + group: String, + repoName: String, + ): PublicId? = withContext(Dispatchers.IO) { dslContext .select(TEST_RUN.PUBLIC_ID) @@ -323,27 +346,31 @@ class TestRunDatabaseRepository(private val dslContext: DSLContext) : TestRunRep ?.let { PublicId(it) } } - private suspend fun findTestRunsCreatedBeforeAndNotPinned(createdBefore: LocalDate, withAttachmentsOnly: Boolean): List = + private suspend fun findTestRunsCreatedBeforeAndNotPinned( + createdBefore: LocalDate, + withAttachmentsOnly: Boolean, + ): List = withContext(Dispatchers.IO) { val createdBeforeTimestamp = LocalDateTime.of(createdBefore, LocalTime.MIDNIGHT) - val query = if (withAttachmentsOnly) { - dslContext - .select(TEST_RUN.PUBLIC_ID) - .from(TEST_RUN) - .leftOuterJoin(TEST_RUN_SYSTEM_ATTRIBUTES).on(TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID.eq(TEST_RUN.PUBLIC_ID)) - .innerJoin(TEST_RUN_ATTACHMENT).on(TEST_RUN.PUBLIC_ID.eq(TEST_RUN_ATTACHMENT.TEST_RUN_PUBLIC_ID)) - } else { - dslContext - .select(TEST_RUN.PUBLIC_ID) - .from(TEST_RUN) - .leftOuterJoin(TEST_RUN_SYSTEM_ATTRIBUTES).on(TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID.eq(TEST_RUN.PUBLIC_ID)) - } + val query = + if (withAttachmentsOnly) { + dslContext + .select(TEST_RUN.PUBLIC_ID) + .from(TEST_RUN) + .leftOuterJoin(TEST_RUN_SYSTEM_ATTRIBUTES).on(TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID.eq(TEST_RUN.PUBLIC_ID)) + .innerJoin(TEST_RUN_ATTACHMENT).on(TEST_RUN.PUBLIC_ID.eq(TEST_RUN_ATTACHMENT.TEST_RUN_PUBLIC_ID)) + } else { + dslContext + .select(TEST_RUN.PUBLIC_ID) + .from(TEST_RUN) + .leftOuterJoin(TEST_RUN_SYSTEM_ATTRIBUTES).on(TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID.eq(TEST_RUN.PUBLIC_ID)) + } query.where( TEST_RUN_SYSTEM_ATTRIBUTES.PINNED.isNull .or(TEST_RUN_SYSTEM_ATTRIBUTES.PINNED.isFalse) - .and(TEST_RUN.CREATED_TIMESTAMP.lessOrEqual(createdBeforeTimestamp)) + .and(TEST_RUN.CREATED_TIMESTAMP.lessOrEqual(createdBeforeTimestamp)), ) .fetchInto(String::class.java) .map { PublicId(it) } diff --git a/server/server-app/src/main/kotlin/projektor/testrun/TestRunRepository.kt b/server/server-app/src/main/kotlin/projektor/testrun/TestRunRepository.kt index f95198ea5..41512d009 100644 --- a/server/server-app/src/main/kotlin/projektor/testrun/TestRunRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testrun/TestRunRepository.kt @@ -11,13 +11,27 @@ import java.time.LocalDate import projektor.server.api.TestSuite as TestSuiteApi interface TestRunRepository { - suspend fun saveTestRun(publicId: PublicId, testSuites: List): TestRunSummary - - suspend fun saveGroupedTestRun(publicId: PublicId, groupedResults: GroupedResults): Pair - - suspend fun appendTestSuites(publicId: PublicId, startingIdx: Int, groupedTestSuites: List): Long - - suspend fun updateTestRunSummary(testRunId: Long, testSuites: List, wallClockDuration: BigDecimal?): TestRunSummary + suspend fun saveTestRun( + publicId: PublicId, + testSuites: List, + ): TestRunSummary + + suspend fun saveGroupedTestRun( + publicId: PublicId, + groupedResults: GroupedResults, + ): Pair + + suspend fun appendTestSuites( + publicId: PublicId, + startingIdx: Int, + groupedTestSuites: List, + ): Long + + suspend fun updateTestRunSummary( + testRunId: Long, + testSuites: List, + wallClockDuration: BigDecimal?, + ): TestRunSummary suspend fun fetchTestRun(publicId: PublicId): TestRun? @@ -29,5 +43,8 @@ interface TestRunRepository { suspend fun findTestRunsCreatedBeforeAndNotPinnedWithAttachments(createdBefore: LocalDate): List - suspend fun findTestRunWithGroup(group: String, repoName: String): PublicId? + suspend fun findTestRunWithGroup( + group: String, + repoName: String, + ): PublicId? } diff --git a/server/server-app/src/main/kotlin/projektor/testrun/TestRunService.kt b/server/server-app/src/main/kotlin/projektor/testrun/TestRunService.kt index 3320c784e..215e1f413 100644 --- a/server/server-app/src/main/kotlin/projektor/testrun/TestRunService.kt +++ b/server/server-app/src/main/kotlin/projektor/testrun/TestRunService.kt @@ -6,12 +6,9 @@ import projektor.server.api.TestRun import projektor.server.api.TestRunSummary class TestRunService(private val testRunRepository: TestRunRepository) { + suspend fun fetchTestRun(publicId: PublicId): TestRun? = testRunRepository.fetchTestRun(publicId) - suspend fun fetchTestRun(publicId: PublicId): TestRun? = - testRunRepository.fetchTestRun(publicId) - - suspend fun fetchTestRunSummary(publicId: PublicId): TestRunSummary? = - testRunRepository.fetchTestRunSummary(publicId) + suspend fun fetchTestRunSummary(publicId: PublicId): TestRunSummary? = testRunRepository.fetchTestRunSummary(publicId) fun addTestRunSummaryToSpan(testRunSummary: TestRunSummary) { val span = Span.current() diff --git a/server/server-app/src/main/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepository.kt index a1a1d9bd9..179816004 100644 --- a/server/server-app/src/main/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepository.kt @@ -9,7 +9,6 @@ import projektor.server.api.PublicId import projektor.server.api.attributes.TestRunSystemAttributes class TestRunSystemAttributesDatabaseRepository(private val dslContext: DSLContext) : TestRunSystemAttributesRepository { - override suspend fun fetchAttributes(publicId: PublicId): TestRunSystemAttributes? = withContext(Dispatchers.IO) { dslContext @@ -23,11 +22,18 @@ class TestRunSystemAttributesDatabaseRepository(private val dslContext: DSLConte override suspend fun unpin(publicId: PublicId) = upsertPinned(publicId, false) - private suspend fun upsertPinned(publicId: PublicId, newPinnedValue: Boolean): Int = + private suspend fun upsertPinned( + publicId: PublicId, + newPinnedValue: Boolean, + ): Int = withContext(Dispatchers.IO) { try { dslContext - .insertInto(TEST_RUN_SYSTEM_ATTRIBUTES, TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID, TEST_RUN_SYSTEM_ATTRIBUTES.PINNED) + .insertInto( + TEST_RUN_SYSTEM_ATTRIBUTES, + TEST_RUN_SYSTEM_ATTRIBUTES.TEST_RUN_PUBLIC_ID, + TEST_RUN_SYSTEM_ATTRIBUTES.PINNED, + ) .values(publicId.id, newPinnedValue) .onDuplicateKeyUpdate() .set(TEST_RUN_SYSTEM_ATTRIBUTES.PINNED, newPinnedValue) diff --git a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteDatabaseRepository.kt b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteDatabaseRepository.kt index 400fe0202..e1baa11c0 100644 --- a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteDatabaseRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteDatabaseRepository.kt @@ -19,26 +19,35 @@ import projektor.util.addPrefixToFields import kotlin.streams.toList class TestSuiteDatabaseRepository(private val dslContext: DSLContext) : TestSuiteRepository { - private val testSuiteMapper = JdbcMapperFactory.newInstance() - .addKeys("id", "test_cases_id", "test_cases_failure_id") - .ignorePropertyNotFound() - .newMapper(TestSuite::class.java) - - override suspend fun fetchTestSuite(testRunPublicId: PublicId, testSuiteIdx: Int): TestSuite? = + private val testSuiteMapper = + JdbcMapperFactory.newInstance() + .addKeys("id", "test_cases_id", "test_cases_failure_id") + .ignorePropertyNotFound() + .newMapper(TestSuite::class.java) + + override suspend fun fetchTestSuite( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestSuite? = withContext(Dispatchers.IO) { - val resultSet = selectTestSuite(dslContext) - .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id).and(TEST_SUITE.IDX.eq(testSuiteIdx))) - .orderBy(TEST_SUITE.ID) - .fetchResultSet() + val resultSet = + selectTestSuite(dslContext) + .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id).and(TEST_SUITE.IDX.eq(testSuiteIdx))) + .orderBy(TEST_SUITE.ID) + .fetchResultSet() - val testSuite: TestSuite? = resultSet.use { - testSuiteMapper.stream(resultSet).findFirst().orElse(null) - } + val testSuite: TestSuite? = + resultSet.use { + testSuiteMapper.stream(resultSet).findFirst().orElse(null) + } testSuite } - override suspend fun fetchTestSuites(testRunPublicId: PublicId, searchCriteria: TestSuiteSearchCriteria): List = + override suspend fun fetchTestSuites( + testRunPublicId: PublicId, + searchCriteria: TestSuiteSearchCriteria, + ): List = withContext(Dispatchers.IO) { val conditions = mutableListOf(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id)) @@ -50,47 +59,58 @@ class TestSuiteDatabaseRepository(private val dslContext: DSLContext) : TestSuit conditions.add(TEST_SUITE.FAILURE_COUNT.ge(1)) } - val testSuites = dslContext - .select(TEST_SUITE.fields().toList()) - .from(TEST_SUITE) - .innerJoin(TEST_RUN).on(TEST_SUITE.TEST_RUN_ID.eq(TEST_RUN.ID)) - .where(conditions) - .fetchInto(TestSuite::class.java) + val testSuites = + dslContext + .select(TEST_SUITE.fields().toList()) + .from(TEST_SUITE) + .innerJoin(TEST_RUN).on(TEST_SUITE.TEST_RUN_ID.eq(TEST_RUN.ID)) + .where(conditions) + .fetchInto(TestSuite::class.java) testSuites } override suspend fun fetchTestSuitesWithCases(testRunPublicId: PublicId): List = withContext(Dispatchers.IO) { - val resultSet = selectTestSuite(dslContext) - .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id)) - .orderBy(TEST_SUITE.ID) - .fetchResultSet() + val resultSet = + selectTestSuite(dslContext) + .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id)) + .orderBy(TEST_SUITE.ID) + .fetchResultSet() - val testSuites = resultSet.use { - testSuiteMapper.stream(resultSet).toList() - } + val testSuites = + resultSet.use { + testSuiteMapper.stream(resultSet).toList() + } testSuites } - override suspend fun fetchTestSuiteSystemErr(testRunPublicId: PublicId, testSuiteIdx: Int): TestOutput = - fetchTestSuiteOutputField(testRunPublicId, testSuiteIdx, TEST_SUITE.SYSTEM_ERR) - - override suspend fun fetchTestSuiteSystemOut(testRunPublicId: PublicId, testSuiteIdx: Int): TestOutput = - fetchTestSuiteOutputField(testRunPublicId, testSuiteIdx, TEST_SUITE.SYSTEM_OUT) - - private suspend fun fetchTestSuiteOutputField(testRunPublicId: PublicId, testSuiteIdx: Int, field: TableField) = - withContext(Dispatchers.IO) { - val outputValue = dslContext + override suspend fun fetchTestSuiteSystemErr( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestOutput = fetchTestSuiteOutputField(testRunPublicId, testSuiteIdx, TEST_SUITE.SYSTEM_ERR) + + override suspend fun fetchTestSuiteSystemOut( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestOutput = fetchTestSuiteOutputField(testRunPublicId, testSuiteIdx, TEST_SUITE.SYSTEM_OUT) + + private suspend fun fetchTestSuiteOutputField( + testRunPublicId: PublicId, + testSuiteIdx: Int, + field: TableField, + ) = withContext(Dispatchers.IO) { + val outputValue = + dslContext .select(field) .from(TEST_SUITE) .innerJoin(TEST_RUN).on(TEST_SUITE.TEST_RUN_ID.eq(TEST_RUN.ID)) .where(TEST_RUN.PUBLIC_ID.eq(testRunPublicId.id).and(TEST_SUITE.IDX.eq(testSuiteIdx))) .fetchOne(field) - TestOutput(outputValue) - } + TestOutput(outputValue) + } override suspend fun fetchHighestTestSuiteIndex(testRunPublicId: PublicId): Int? = withContext(Dispatchers.IO) { diff --git a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteRepository.kt b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteRepository.kt index 906ce3649..0e29f3911 100644 --- a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteRepository.kt +++ b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteRepository.kt @@ -5,16 +5,27 @@ import projektor.server.api.TestOutput import projektor.server.api.TestSuite interface TestSuiteRepository { + suspend fun fetchTestSuite( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestSuite? - suspend fun fetchTestSuite(testRunPublicId: PublicId, testSuiteIdx: Int): TestSuite? - - suspend fun fetchTestSuites(testRunPublicId: PublicId, searchCriteria: TestSuiteSearchCriteria): List + suspend fun fetchTestSuites( + testRunPublicId: PublicId, + searchCriteria: TestSuiteSearchCriteria, + ): List suspend fun fetchTestSuitesWithCases(testRunPublicId: PublicId): List - suspend fun fetchTestSuiteSystemErr(testRunPublicId: PublicId, testSuiteIdx: Int): TestOutput + suspend fun fetchTestSuiteSystemErr( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestOutput - suspend fun fetchTestSuiteSystemOut(testRunPublicId: PublicId, testSuiteIdx: Int): TestOutput + suspend fun fetchTestSuiteSystemOut( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestOutput suspend fun fetchHighestTestSuiteIndex(testRunPublicId: PublicId): Int? } diff --git a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteService.kt b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteService.kt index 9beacd5e4..07a60cca7 100644 --- a/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteService.kt +++ b/server/server-app/src/main/kotlin/projektor/testsuite/TestSuiteService.kt @@ -5,15 +5,23 @@ import projektor.server.api.TestOutput import projektor.server.api.TestSuite class TestSuiteService(private val testSuiteRepository: TestSuiteRepository) { - suspend fun fetchTestSuite(testRunPublicId: PublicId, testSuiteIdx: Int): TestSuite? = - testSuiteRepository.fetchTestSuite(testRunPublicId, testSuiteIdx) + suspend fun fetchTestSuite( + testRunPublicId: PublicId, + testSuiteIdx: Int, + ): TestSuite? = testSuiteRepository.fetchTestSuite(testRunPublicId, testSuiteIdx) - suspend fun fetchTestSuites(publicId: PublicId, testSuiteSearchCriteria: TestSuiteSearchCriteria): List = - testSuiteRepository.fetchTestSuites(publicId, testSuiteSearchCriteria) + suspend fun fetchTestSuites( + publicId: PublicId, + testSuiteSearchCriteria: TestSuiteSearchCriteria, + ): List = testSuiteRepository.fetchTestSuites(publicId, testSuiteSearchCriteria) - suspend fun fetchTestSuiteSystemErr(publicId: PublicId, testSuiteIdx: Int): TestOutput = - testSuiteRepository.fetchTestSuiteSystemErr(publicId, testSuiteIdx) + suspend fun fetchTestSuiteSystemErr( + publicId: PublicId, + testSuiteIdx: Int, + ): TestOutput = testSuiteRepository.fetchTestSuiteSystemErr(publicId, testSuiteIdx) - suspend fun fetchTestSuiteSystemOut(publicId: PublicId, testSuiteIdx: Int): TestOutput = - testSuiteRepository.fetchTestSuiteSystemOut(publicId, testSuiteIdx) + suspend fun fetchTestSuiteSystemOut( + publicId: PublicId, + testSuiteIdx: Int, + ): TestOutput = testSuiteRepository.fetchTestSuiteSystemOut(publicId, testSuiteIdx) } diff --git a/server/server-app/src/main/kotlin/projektor/util/GzipUtil.kt b/server/server-app/src/main/kotlin/projektor/util/GzipUtil.kt index 783cd38cd..264fad183 100644 --- a/server/server-app/src/main/kotlin/projektor/util/GzipUtil.kt +++ b/server/server-app/src/main/kotlin/projektor/util/GzipUtil.kt @@ -10,5 +10,4 @@ fun gzip(content: String): ByteArray { return bos.toByteArray() } -fun ungzip(content: ByteArray): String = - GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() } +fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() } diff --git a/server/server-app/src/main/kotlin/projektor/util/MathUtil.kt b/server/server-app/src/main/kotlin/projektor/util/MathUtil.kt deleted file mode 100644 index 94fd3c7fc..000000000 --- a/server/server-app/src/main/kotlin/projektor/util/MathUtil.kt +++ /dev/null @@ -1 +0,0 @@ -package projektor.util diff --git a/server/server-app/src/main/kotlin/projektor/versioncontrol/VersionControlConfig.kt b/server/server-app/src/main/kotlin/projektor/versioncontrol/VersionControlConfig.kt index d971f623a..b6697004c 100644 --- a/server/server-app/src/main/kotlin/projektor/versioncontrol/VersionControlConfig.kt +++ b/server/server-app/src/main/kotlin/projektor/versioncontrol/VersionControlConfig.kt @@ -3,14 +3,14 @@ package projektor.versioncontrol import io.ktor.server.config.ApplicationConfig data class VersionControlConfig( - val gitHubBaseUrl: String? + val gitHubBaseUrl: String?, ) { companion object { fun createVersionControlConfig(applicationConfig: ApplicationConfig): VersionControlConfig { val gitHubBaseUrl = applicationConfig.propertyOrNull("ktor.versionControl.gitHubBaseUrl")?.getString() return VersionControlConfig( - gitHubBaseUrl = gitHubBaseUrl + gitHubBaseUrl = gitHubBaseUrl, ) } } diff --git a/server/server-app/src/test/kotlin/projektor/ApplicationTestCase.kt b/server/server-app/src/test/kotlin/projektor/ApplicationTestCase.kt index ad4f51480..8aea049e0 100644 --- a/server/server-app/src/test/kotlin/projektor/ApplicationTestCase.kt +++ b/server/server-app/src/test/kotlin/projektor/ApplicationTestCase.kt @@ -68,18 +68,20 @@ open class ApplicationTestCase { val cloverXmlLoader = CloverXmlLoader() val resultsXmlLoader = ResultsXmlLoader() - val objectMapper: ObjectMapper = ObjectMapper() - .registerKotlinModule() - .registerModule(JavaTimeModule()) - .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + val objectMapper: ObjectMapper = + ObjectMapper() + .registerKotlinModule() + .registerModule(JavaTimeModule()) + .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) val exporter = InMemorySpanExporter.create() - val tracerProvider = SdkTracerProvider - .builder() - .addSpanProcessor(SimpleSpanProcessor.create(exporter)) - .build() + val tracerProvider = + SdkTracerProvider + .builder() + .addSpanProcessor(SimpleSpanProcessor.create(exporter)) + .build() lateinit var dataSource: HikariDataSource lateinit var dslContext: DSLContext @@ -231,23 +233,27 @@ open class ApplicationTestCase { codeQualityReportDao = CodeQualityReportDao(dslContext.configuration()) - testRunDBGenerator = TestRunDBGenerator( - testRunDao, - testSuiteGroupDao, - testSuiteDao, - testCaseDao, - testFailureDao, - testRunSystemAttributesDao, - gitMetadataDao, - resultsMetadataDao, - coverageService, - attachmentDao - ) + testRunDBGenerator = + TestRunDBGenerator( + testRunDao, + testSuiteGroupDao, + testSuiteDao, + testCaseDao, + testFailureDao, + testRunSystemAttributesDao, + gitMetadataDao, + resultsMetadataDao, + coverageService, + attachmentDao, + ) this.application = application } - fun waitUntilTestRunHasAttachments(publicId: PublicId, attachmentCount: Int) { + fun waitUntilTestRunHasAttachments( + publicId: PublicId, + attachmentCount: Int, + ) { await until { attachmentDao.fetchByTestRunPublicId(publicId.id).size == attachmentCount } } @@ -275,10 +281,11 @@ open class ApplicationTestCase { return Pair(PublicId(publicId), testRun) } - protected fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + protected fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() @AfterEach fun closeDataSource() { diff --git a/server/server-app/src/test/kotlin/projektor/DatabaseRepositoryTestCase.kt b/server/server-app/src/test/kotlin/projektor/DatabaseRepositoryTestCase.kt index bf241fab3..59f59405d 100644 --- a/server/server-app/src/test/kotlin/projektor/DatabaseRepositoryTestCase.kt +++ b/server/server-app/src/test/kotlin/projektor/DatabaseRepositoryTestCase.kt @@ -68,14 +68,15 @@ open class DatabaseRepositoryTestCase : KoinTest { lateinit var coverageStatsDao: CodeCoverageStatsDao lateinit var coverageService: CoverageService - val attachmentConfig = AttachmentConfig( - url = "http://localhost:9000", - bucketName = "attachmentstesting", - autoCreateBucket = true, - accessKey = "minio_access_key", - secretKey = "minio_secret_key", - maxSizeMB = null - ) + val attachmentConfig = + AttachmentConfig( + url = "http://localhost:9000", + bucketName = "attachmentstesting", + autoCreateBucket = true, + accessKey = "minio_access_key", + secretKey = "minio_secret_key", + maxSizeMB = null, + ) var attachmentsEnabled = false lateinit var attachmentService: AttachmentService @@ -83,13 +84,14 @@ open class DatabaseRepositoryTestCase : KoinTest { fun setup() { val hikariConfig = HikariConfig() - val dataSourceConfig = DataSourceConfig( - System.getenv("DB_URL") ?: "jdbc:postgresql://localhost:5433/projektordb", - System.getenv("DB_USERNAME") ?: "testuser", - System.getenv("DB_PASSWORD") ?: "testpass", - "public", - 3 - ) + val dataSourceConfig = + DataSourceConfig( + System.getenv("DB_URL") ?: "jdbc:postgresql://localhost:5433/projektordb", + System.getenv("DB_USERNAME") ?: "testuser", + System.getenv("DB_PASSWORD") ?: "testpass", + "public", + 3, + ) hikariConfig.username = dataSourceConfig.username hikariConfig.password = dataSourceConfig.password @@ -102,16 +104,17 @@ open class DatabaseRepositoryTestCase : KoinTest { dslContext = DSL.using(dataSource, SQLDialect.POSTGRES) - val metricsConfig = InfluxMetricsConfig( - false, - "fakedb", - "http://localhost", - null, - null, - false, - 10, - "test" - ) + val metricsConfig = + InfluxMetricsConfig( + false, + "fakedb", + "http://localhost", + null, + null, + false, + 10, + "test", + ) startKoin { modules( @@ -124,8 +127,8 @@ open class DatabaseRepositoryTestCase : KoinTest { NotificationConfig(null), ProcessingConfig(GroupedResultsParser.DEFAULT_MAX_PAYLOAD_SIZE), null, - null - ) + null, + ), ) } @@ -151,24 +154,26 @@ open class DatabaseRepositoryTestCase : KoinTest { val metricsService: MetricsService by inject() coverageService = CoverageService(coverageRepository, metricsService, previousTestRunService, processingFailureService) - testRunDBGenerator = TestRunDBGenerator( - testRunDao, - testSuiteGroupDao, - testSuiteDao, - testCaseDao, - testFailureDao, - testRunSystemAttributesDao, - gitMetadataDao, - resultsMetadataDao, - coverageService, - attachmentDao - ) + testRunDBGenerator = + TestRunDBGenerator( + testRunDao, + testSuiteGroupDao, + testSuiteDao, + testCaseDao, + testFailureDao, + testRunSystemAttributesDao, + gitMetadataDao, + resultsMetadataDao, + coverageService, + attachmentDao, + ) if (attachmentsEnabled) { - attachmentService = AttachmentService( - attachmentConfig, - get() - ) + attachmentService = + AttachmentService( + attachmentConfig, + get(), + ) attachmentService.conditionallyCreateBucketIfNotExists() } } diff --git a/server/server-app/src/test/kotlin/projektor/TestRunDBGenerator.kt b/server/server-app/src/test/kotlin/projektor/TestRunDBGenerator.kt index 8a2ad44e7..6ab0229b3 100644 --- a/server/server-app/src/test/kotlin/projektor/TestRunDBGenerator.kt +++ b/server/server-app/src/test/kotlin/projektor/TestRunDBGenerator.kt @@ -38,9 +38,12 @@ class TestRunDBGenerator( private val gitMetadataDao: GitMetadataDao, private val resultsMetadataDao: ResultsMetadataDao, private val coverageService: CoverageService, - private val attachmentDao: TestRunAttachmentDao + private val attachmentDao: TestRunAttachmentDao, ) { - fun createTestRun(publicId: PublicId, testSuiteDataList: List): TestRunDB { + fun createTestRun( + publicId: PublicId, + testSuiteDataList: List, + ): TestRunDB { val testRun = createTestRun(publicId, testSuiteDataList.size, testSuiteDataList.count { it.failingTestCaseNames.isNotEmpty() }) testRunDao.insert(testRun) println("Inserted test run ${testRun.publicId}") @@ -90,7 +93,7 @@ class TestRunDBGenerator( repoName: String, ci: Boolean, projectName: String?, - branchName: String = "main" + branchName: String = "main", ): TestRunDB { val testRunDB = createTestRun(publicId, testSuiteDataList) addResultsMetadata(testRunDB, ci) @@ -105,7 +108,7 @@ class TestRunDBGenerator( branchName: String?, projectName: String?, pullRequestNumber: Int?, - commitSha: String? + commitSha: String?, ): GitMetadataDB { val gitMetadata = GitMetadataDB() gitMetadata.testRunId = testRunDB.id @@ -123,7 +126,7 @@ class TestRunDBGenerator( fun addResultsMetadata( testRunDB: TestRunDB, - ci: Boolean + ci: Boolean, ): ResultsMetadataDB { val resultsMetadata = ResultsMetadataDB() resultsMetadata.testRunId = testRunDB.id @@ -141,9 +144,9 @@ class TestRunDBGenerator( "testSuite1", listOf("testSuite1TestCase1"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) fun createSimpleFailingTestRun(publicId: PublicId): TestRunDB = @@ -154,42 +157,62 @@ class TestRunDBGenerator( "testSuite1", listOf("testSuite1TestCase1"), listOf("failingTestSuite1TestCase1"), - listOf() - ) - ) + listOf(), + ), + ), ) fun createEmptyTestRun(publicId: PublicId): TestRunDB = createTestRun( publicId, - listOf() + listOf(), ) - fun createEmptyTestRunInRepo(publicId: PublicId, repoName: String, ci: Boolean, projectName: String?): TestRunDB { - val testRunDB = createTestRun( - publicId, - listOf() - ) + fun createEmptyTestRunInRepo( + publicId: PublicId, + repoName: String, + ci: Boolean, + projectName: String?, + ): TestRunDB { + val testRunDB = + createTestRun( + publicId, + listOf(), + ) addResultsMetadata(testRunDB, ci) addGitMetadata(testRunDB, repoName, true, "main", projectName, null, null) return testRunDB } - fun createSimpleTestRunInRepo(publicId: PublicId, repoName: String, ci: Boolean, projectName: String?): TestRunDB { + fun createSimpleTestRunInRepo( + publicId: PublicId, + repoName: String, + ci: Boolean, + projectName: String?, + ): TestRunDB { val testRunDB = createSimpleTestRun(publicId) addResultsMetadata(testRunDB, ci) addGitMetadata(testRunDB, repoName, true, "main", projectName, null, null) return testRunDB } - fun createSimpleFailingTestRunInRepo(publicId: PublicId, repoName: String, ci: Boolean, projectName: String?): TestRunDB { + fun createSimpleFailingTestRunInRepo( + publicId: PublicId, + repoName: String, + ci: Boolean, + projectName: String?, + ): TestRunDB { val testRunDB = createSimpleFailingTestRun(publicId) addResultsMetadata(testRunDB, ci) addGitMetadata(testRunDB, repoName, true, "main", projectName, null, null) return testRunDB } - fun createTestRun(publicId: PublicId, createdOn: LocalDate, pinned: Boolean): TestRunDB { + fun createTestRun( + publicId: PublicId, + createdOn: LocalDate, + pinned: Boolean, + ): TestRunDB { val testRun = createTestRun(publicId, listOf()) testRun.createdTimestamp = createdOn.atStartOfDay() testRunDao.update(testRun) @@ -205,21 +228,22 @@ class TestRunDBGenerator( coverageText: String, repoName: String, branchName: String = "main", - projectName: String? = null - ): TestRunDB = createTestRunWithCoverageAndGitMetadata( - publicId, - CoverageFilePayload(coverageText), - repoName, - branchName, - projectName - ) + projectName: String? = null, + ): TestRunDB = + createTestRunWithCoverageAndGitMetadata( + publicId, + CoverageFilePayload(coverageText), + repoName, + branchName, + projectName, + ) fun createTestRunWithCoverageAndGitMetadata( publicId: PublicId, coverageFilePayload: CoverageFilePayload, repoName: String, branchName: String = "main", - projectName: String? = null + projectName: String? = null, ): TestRunDB { val testRunDB = createSimpleTestRun(publicId) addGitMetadata(testRunDB, repoName, branchName == "main", branchName, projectName, null, null) @@ -228,7 +252,11 @@ class TestRunDBGenerator( return testRunDB } - fun addTestSuiteGroupToTestRun(testSuiteGroup: TestSuiteGroupDB, testRun: TestRunDB, testSuiteClassNames: List) { + fun addTestSuiteGroupToTestRun( + testSuiteGroup: TestSuiteGroupDB, + testRun: TestRunDB, + testSuiteClassNames: List, + ) { val testSuiteDBs = testSuiteDao.fetchByTestRunId(testRun.id).filter { it.className in testSuiteClassNames } testSuiteDBs.forEach { testSuiteDB -> @@ -237,7 +265,11 @@ class TestRunDBGenerator( } } - fun addTestSuiteGroupToTestRun(groupName: String, testRun: TestRunDB, testSuiteClassNames: List): TestSuiteGroupDB { + fun addTestSuiteGroupToTestRun( + groupName: String, + testRun: TestRunDB, + testSuiteClassNames: List, + ): TestSuiteGroupDB { val testSuiteGroup = TestSuiteGroupDB() testSuiteGroup.testRunId = testRun.id testSuiteGroup.groupName = groupName @@ -248,7 +280,11 @@ class TestRunDBGenerator( return testSuiteGroup } - fun addAttachment(publicId: PublicId, objectName: String, fileName: String): TestRunAttachment { + fun addAttachment( + publicId: PublicId, + objectName: String, + fileName: String, + ): TestRunAttachment { val attachment = TestRunAttachment() attachment.testRunPublicId = publicId.id attachment.objectName = objectName @@ -264,50 +300,72 @@ data class TestSuiteData( val passingTestCaseNames: List, val failingTestCaseNames: List, val skippedTestCaseNames: List, - val fileName: String? = null + val fileName: String? = null, ) -fun createTestRun(publicId: PublicId, totalTestCount: Int, failingTestCount: Int = 0, cumulativeDuration: BigDecimal = BigDecimal("30.000")): TestRunDB = TestRunDB() - .setPublicId(publicId.id) - .setTotalTestCount(totalTestCount) - .setTotalPassingCount(totalTestCount) - .setTotalFailureCount(failingTestCount) - .setTotalSkippedCount(0) - .setCumulativeDuration(cumulativeDuration) - .setAverageDuration( - if (totalTestCount > 0) - calculateAverageDuration(cumulativeDuration, totalTestCount) - else - cumulativeDuration - ) - .setSlowestTestCaseDuration(BigDecimal("10.000")) - .setPassed(failingTestCount == 0) - .setCreatedTimestamp(LocalDateTime.now()) - -fun createTestSuite(testRunId: Long, packageAndClassName: String, idx: Int): TestSuiteDB = TestSuiteDB() - .setTestRunId(testRunId) - .setPackageName(parsePackageAndClassName(packageAndClassName).first) - .setClassName(parsePackageAndClassName(packageAndClassName).second) - .setIdx(idx) - .setTestCount(6) - .setPassingCount(3) - .setFailureCount(2) - .setSkippedCount(1) - .setDuration(BigDecimal.TEN) - .setStartTs(LocalDateTime.now()) - .setHostname("hostname") - -fun createTestCase(testSuiteId: Long, name: String, idx: Int, passed: Boolean): TestCaseDB = TestCaseDB() - .setTestSuiteId(testSuiteId) - .setName(name) - .setIdx(idx) - .setClassName("${name}ClassName") - .setDuration(BigDecimal("2.5")) - .setPassed(passed) - .setSkipped(false) - -fun createTestFailure(testCaseId: Long, testCaseName: String): TestFailureDB = TestFailureDB() - .setTestCaseId(testCaseId) - .setFailureMessage("$testCaseName failure message") - .setFailureText("$testCaseName failure text") - .setFailureType("$testCaseName failure type") +fun createTestRun( + publicId: PublicId, + totalTestCount: Int, + failingTestCount: Int = 0, + cumulativeDuration: BigDecimal = BigDecimal("30.000"), +): TestRunDB = + TestRunDB() + .setPublicId(publicId.id) + .setTotalTestCount(totalTestCount) + .setTotalPassingCount(totalTestCount) + .setTotalFailureCount(failingTestCount) + .setTotalSkippedCount(0) + .setCumulativeDuration(cumulativeDuration) + .setAverageDuration( + if (totalTestCount > 0) { + calculateAverageDuration(cumulativeDuration, totalTestCount) + } else { + cumulativeDuration + }, + ) + .setSlowestTestCaseDuration(BigDecimal("10.000")) + .setPassed(failingTestCount == 0) + .setCreatedTimestamp(LocalDateTime.now()) + +fun createTestSuite( + testRunId: Long, + packageAndClassName: String, + idx: Int, +): TestSuiteDB = + TestSuiteDB() + .setTestRunId(testRunId) + .setPackageName(parsePackageAndClassName(packageAndClassName).first) + .setClassName(parsePackageAndClassName(packageAndClassName).second) + .setIdx(idx) + .setTestCount(6) + .setPassingCount(3) + .setFailureCount(2) + .setSkippedCount(1) + .setDuration(BigDecimal.TEN) + .setStartTs(LocalDateTime.now()) + .setHostname("hostname") + +fun createTestCase( + testSuiteId: Long, + name: String, + idx: Int, + passed: Boolean, +): TestCaseDB = + TestCaseDB() + .setTestSuiteId(testSuiteId) + .setName(name) + .setIdx(idx) + .setClassName("${name}ClassName") + .setDuration(BigDecimal("2.5")) + .setPassed(passed) + .setSkipped(false) + +fun createTestFailure( + testCaseId: Long, + testCaseName: String, +): TestFailureDB = + TestFailureDB() + .setTestCaseId(testCaseId) + .setFailureMessage("$testCaseName failure message") + .setFailureText("$testCaseName failure text") + .setFailureType("$testCaseName failure type") diff --git a/server/server-app/src/test/kotlin/projektor/api/ApiOrganizationApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/api/ApiOrganizationApplicationTest.kt index 0dd1ebda4..aaf26aa3a 100644 --- a/server/server-app/src/test/kotlin/projektor/api/ApiOrganizationApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/api/ApiOrganizationApplicationTest.kt @@ -40,59 +40,58 @@ class ApiOrganizationApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/org/$orgName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo1, coverageText = JacocoXmlLoader().serverApp(), repoName = repo1, - projectName = "proj1" + projectName = "proj1", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId1, coverageText = JacocoXmlLoader().serverApp(), repoName = repo1, - projectName = "proj1" + projectName = "proj1", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = otherProjectRepo1, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repo1, - projectName = "proj2" + projectName = "proj2", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo2, coverageText = JacocoXmlLoader().jacocoXmlParser(), - repoName = repo2 + repoName = repo2, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId2, coverageText = JacocoXmlLoader().jacocoXmlParser(), - repoName = repo2 + repoName = repo2, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo3, coverageText = JacocoXmlLoader().junitResultsParser(), - repoName = repo3 + repoName = repo3, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId3, coverageText = JacocoXmlLoader().junitResultsParser(), - repoName = repo3 + repoName = repo3, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = anotherPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = anotherRepo + repoName = anotherRepo, ) testRunDBGenerator.createSimpleTestRunInRepo( publicId = noCodeCoveragePublicId, repoName = noCodeCoverageRepo, ci = true, - projectName = null + projectName = null, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryApplicationTest.kt index 8959a39b6..9424ada1c 100644 --- a/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryApplicationTest.kt @@ -28,26 +28,25 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -55,14 +54,14 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -95,26 +94,25 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/coverage/current?project=other-project") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -122,14 +120,14 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -163,26 +161,25 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/coverage/current?branch=my-branch") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "my-branch" + branchName = "my-branch", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -190,14 +187,14 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -229,26 +226,25 @@ class ApiRepositoryApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = otherBranchRunPublicId1, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "other" + branchName = "other", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = mainRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = otherBranchRunPublicId2, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "other" + branchName = "other", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryFlakyTestsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryFlakyTestsApplicationTest.kt index 4707c9852..cef6e7251 100644 --- a/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryFlakyTestsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/api/ApiRepositoryFlakyTestsApplicationTest.kt @@ -23,20 +23,21 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/tests/flaky") { @@ -63,30 +64,32 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { val projectName = null val failingPublicIds = (1..3).map { randomPublicId() } - val failingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val failingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/tests/flaky?max_runs=10&threshold=3") { @@ -114,20 +117,21 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/tests/flaky?project=$projectName") { @@ -154,46 +158,49 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { val projectName = null val failingMainlinePublicIds = (1..3).map { randomPublicId() } - val failingMainlineTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingMainlineTestSuite1", - listOf("passing1"), - listOf("failingMainline1"), - listOf() - ), - TestSuiteData( - "projektor.failingMainlineTestSuite2", - listOf("passing2"), - listOf("failingMainline2"), - listOf() + val failingMainlineTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingMainlineTestSuite1", + listOf("passing1"), + listOf("failingMainline1"), + listOf(), + ), + TestSuiteData( + "projektor.failingMainlineTestSuite2", + listOf("passing2"), + listOf("failingMainline2"), + listOf(), + ), ) - ) val failingBranchPublicIds = (1..3).map { randomPublicId() } - val failingBranchTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingBranchTestSuite1", - listOf("passing1"), - listOf("failingBranch1"), - listOf() - ), - TestSuiteData( - "projektor.failingBranchTestSuite2", - listOf("passing2"), - listOf("failingBranch2"), - listOf() + val failingBranchTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingBranchTestSuite1", + listOf("passing1"), + listOf("failingBranch1"), + listOf(), + ), + TestSuiteData( + "projektor.failingBranchTestSuite2", + listOf("passing2"), + listOf("failingBranch2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/api/v1/repo/$repoName/tests/flaky?max_runs=20&threshold=3&branch_type=MAINLINE") { @@ -201,7 +208,14 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { testRunDBGenerator.createTestRunInRepo(publicId, failingMainlineTestSuiteDataList, repoName, true, projectName, "main") } failingBranchPublicIds.forEach { publicId -> - testRunDBGenerator.createTestRunInRepo(publicId, failingBranchTestSuiteDataList, repoName, true, projectName, "my-branch") + testRunDBGenerator.createTestRunInRepo( + publicId, + failingBranchTestSuiteDataList, + repoName, + true, + projectName, + "my-branch", + ) } passingPublicIds.forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, passingTestSuiteDataList, repoName, true, projectName) @@ -219,11 +233,11 @@ class ApiRepositoryFlakyTestsApplicationTest : ApplicationTestCase() { expectThat(flakyTestCaseNames) .contains( "projektor.failingMainline1ClassName.failingMainline1", - "projektor.failingMainline2ClassName.failingMainline2" + "projektor.failingMainline2ClassName.failingMainline2", ) .not().contains( "projektor.failingBranch1ClassName.failingBranch1", - "projektor.failingBranch2ClassName.failingBranch2" + "projektor.failingBranch2ClassName.failingBranch2", ) } } diff --git a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentApplicationTest.kt index 46a71e7df..10e7a2907 100644 --- a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentApplicationTest.kt @@ -31,9 +31,9 @@ class AddAttachmentApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) addHeader("content-length", attachmentBytes.size.toString()) @@ -62,7 +62,6 @@ class AddAttachmentApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/run/$publicId/attachments/test-attachment.txt") { - addHeader("content-length", attachmentBytes.size.toString()) setBody(attachmentBytes) }.apply { @@ -92,7 +91,6 @@ class AddAttachmentApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/run/$publicId/attachments/test-attachment.txt") { - addHeader("content-length", attachmentBytes.size.toString()) setBody(attachmentBytes) }.apply { diff --git a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentMaxSizeApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentMaxSizeApplicationTest.kt index 54bff2697..d5b9d9522 100644 --- a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentMaxSizeApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentMaxSizeApplicationTest.kt @@ -33,9 +33,9 @@ class AddAttachmentMaxSizeApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) addHeader("content-length", "23342") @@ -64,9 +64,9 @@ class AddAttachmentMaxSizeApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) addHeader("content-length", "23342") diff --git a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentTokenApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentTokenApplicationTest.kt index b55ed1765..fd4455ad0 100644 --- a/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentTokenApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/attachment/AddAttachmentTokenApplicationTest.kt @@ -16,7 +16,6 @@ import java.io.File @ExperimentalStdlibApi class AddAttachmentTokenApplicationTest : ApplicationTestCase() { - @Test fun `when token required and valid token included in header should add attachment`() { val validPublishToken = "publish12345" @@ -34,12 +33,12 @@ class AddAttachmentTokenApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) - addHeader(AuthConfig.PublishToken, validPublishToken) + addHeader(AuthConfig.PUBLISH_TOKEN, validPublishToken) setBody(File("src/test/resources/test-attachment.txt").readBytes()) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -73,12 +72,12 @@ class AddAttachmentTokenApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) - addHeader(AuthConfig.PublishToken, "invalidPublishTOken") + addHeader(AuthConfig.PUBLISH_TOKEN, "invalidPublishTOken") setBody(File("src/test/resources/test-attachment.txt").readBytes()) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.Unauthorized) diff --git a/server/server-app/src/test/kotlin/projektor/attachment/AttachmentDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/attachment/AttachmentDatabaseRepositoryTest.kt index 56d37bfb9..5d950f9c4 100644 --- a/server/server-app/src/test/kotlin/projektor/attachment/AttachmentDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/attachment/AttachmentDatabaseRepositoryTest.kt @@ -11,7 +11,6 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class AttachmentDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `when test run has two attachments should return them`() { val publicId = randomPublicId() diff --git a/server/server-app/src/test/kotlin/projektor/attachment/ListAttachmentsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/attachment/ListAttachmentsApplicationTest.kt index 09ffdd943..96f11ab59 100644 --- a/server/server-app/src/test/kotlin/projektor/attachment/ListAttachmentsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/attachment/ListAttachmentsApplicationTest.kt @@ -39,9 +39,9 @@ class ListAttachmentsApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) addHeader("content-length", attachment1Bytes.size.toString()) setBody(attachment1Bytes) diff --git a/server/server-app/src/test/kotlin/projektor/badge/RepositoryCoverageBadgeApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/badge/RepositoryCoverageBadgeApplicationTest.kt index 59f3c983a..a02cee318 100644 --- a/server/server-app/src/test/kotlin/projektor/badge/RepositoryCoverageBadgeApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/badge/RepositoryCoverageBadgeApplicationTest.kt @@ -30,14 +30,14 @@ class RepositoryCoverageBadgeApplicationTest : ApplicationTestCase() { publicId = mainlinePublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = featureBranchPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -60,7 +60,7 @@ class RepositoryCoverageBadgeApplicationTest : ApplicationTestCase() { publicId = featureBranchPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -83,7 +83,7 @@ class RepositoryCoverageBadgeApplicationTest : ApplicationTestCase() { publicId = thisPublicId, repoName = repoName, ci = true, - projectName = null + projectName = null, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.NotFound) @@ -105,7 +105,7 @@ class RepositoryCoverageBadgeApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -129,7 +129,7 @@ class RepositoryCoverageBadgeApplicationTest : ApplicationTestCase() { publicId = thisPublicId, repoName = repoName, ci = true, - projectName = projectName + projectName = projectName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.NotFound) diff --git a/server/server-app/src/test/kotlin/projektor/badge/RepositoryTestRunPassFailBadgeApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/badge/RepositoryTestRunPassFailBadgeApplicationTest.kt index cff453914..a0c58fcfb 100644 --- a/server/server-app/src/test/kotlin/projektor/badge/RepositoryTestRunPassFailBadgeApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/badge/RepositoryTestRunPassFailBadgeApplicationTest.kt @@ -26,14 +26,14 @@ class RepositoryTestRunPassFailBadgeApplicationTest : ApplicationTestCase() { publicId = mainlinePublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = featureBranchPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -57,14 +57,14 @@ class RepositoryTestRunPassFailBadgeApplicationTest : ApplicationTestCase() { publicId = passingPublicId, repoName = repoName, ci = true, - projectName = null + projectName = null, ) testRunDBGenerator.createSimpleFailingTestRunInRepo( publicId = failingPublicId, repoName = repoName, ci = true, - projectName = null + projectName = null, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -90,7 +90,7 @@ class RepositoryTestRunPassFailBadgeApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -98,7 +98,7 @@ class RepositoryTestRunPassFailBadgeApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "feature/dev", - projectName = projectName + projectName = projectName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/badge/TestRunCoverageBadgeApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/badge/TestRunCoverageBadgeApplicationTest.kt index b5894e621..62799f08e 100644 --- a/server/server-app/src/test/kotlin/projektor/badge/TestRunCoverageBadgeApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/badge/TestRunCoverageBadgeApplicationTest.kt @@ -27,7 +27,7 @@ class TestRunCoverageBadgeApplicationTest : ApplicationTestCase() { testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId, coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = repoName + repoName = repoName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/cleanup/AttachmentCleanupServiceTest.kt b/server/server-app/src/test/kotlin/projektor/cleanup/AttachmentCleanupServiceTest.kt index b07069263..b02915813 100644 --- a/server/server-app/src/test/kotlin/projektor/cleanup/AttachmentCleanupServiceTest.kt +++ b/server/server-app/src/test/kotlin/projektor/cleanup/AttachmentCleanupServiceTest.kt @@ -13,18 +13,18 @@ import strikt.assertions.isNotNull import java.time.LocalDate class AttachmentCleanupServiceTest : DatabaseRepositoryTestCase() { - init { attachmentsEnabled = true } @Test fun `should delete attachments from test runs older than specified day`() { - val attachmentCleanupService = AttachmentCleanupService( - CleanupConfig(null, 21, false), - get(), - attachmentService - ) + val attachmentCleanupService = + AttachmentCleanupService( + CleanupConfig(null, 21, false), + get(), + attachmentService, + ) val cleanupPublicId = randomPublicId() testRunDBGenerator.createTestRun(cleanupPublicId, LocalDate.now().minusDays(23), false) @@ -51,11 +51,12 @@ class AttachmentCleanupServiceTest : DatabaseRepositoryTestCase() { @Test fun `when dry run enabled should not delete any attachments`() { - val attachmentCleanupService = AttachmentCleanupService( - CleanupConfig(null, 14, true), - get(), - attachmentService - ) + val attachmentCleanupService = + AttachmentCleanupService( + CleanupConfig(null, 14, true), + get(), + attachmentService, + ) val cleanupPublicId = randomPublicId() testRunDBGenerator.createTestRun(cleanupPublicId, LocalDate.now().minusDays(16), false) diff --git a/server/server-app/src/test/kotlin/projektor/cleanup/CleanupJobTest.kt b/server/server-app/src/test/kotlin/projektor/cleanup/CleanupJobTest.kt index d56a97da8..247d8a775 100644 --- a/server/server-app/src/test/kotlin/projektor/cleanup/CleanupJobTest.kt +++ b/server/server-app/src/test/kotlin/projektor/cleanup/CleanupJobTest.kt @@ -12,13 +12,14 @@ import java.time.LocalDate class CleanupJobTest : DatabaseRepositoryTestCase() { @Test fun `should execute test report cleanup`() { - val cleanupService = TestRunCleanupService( - CleanupConfig(30, null, false), - get(), - get(), - get(), - null - ) + val cleanupService = + TestRunCleanupService( + CleanupConfig(30, null, false), + get(), + get(), + get(), + null, + ) val cleanupScheduledJob = CleanupScheduledJob(cleanupService, null) val publicIdToDelete = randomPublicId() diff --git a/server/server-app/src/test/kotlin/projektor/cleanup/CleanupSchedulerApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/cleanup/CleanupSchedulerApplicationTest.kt index 576d3be7c..9a8059efa 100644 --- a/server/server-app/src/test/kotlin/projektor/cleanup/CleanupSchedulerApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/cleanup/CleanupSchedulerApplicationTest.kt @@ -24,7 +24,7 @@ class CleanupSchedulerApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { val scheduler: Scheduler = application.get() - val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.cleanupJobName) + val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.CLEANUP_JOB_NAME) expectThat(cleanupJob) .isNotNull() .and { @@ -49,7 +49,7 @@ class CleanupSchedulerApplicationTest : ApplicationTestCase() { val scheduler: Scheduler = application.get() - val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.cleanupJobName) + val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.CLEANUP_JOB_NAME) assertNotNull(cleanupJob) cleanupJob.runnable.run() @@ -69,7 +69,7 @@ class CleanupSchedulerApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { val scheduler: Scheduler = application.get() - val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.cleanupJobName) + val cleanupJob = scheduler.findScheduledJob(CleanupScheduledJob.CLEANUP_JOB_NAME) expectThat(cleanupJob).isNull() } } diff --git a/server/server-app/src/test/kotlin/projektor/cleanup/TestRunCleanupServiceTest.kt b/server/server-app/src/test/kotlin/projektor/cleanup/TestRunCleanupServiceTest.kt index b7e17ad54..11bfd185b 100644 --- a/server/server-app/src/test/kotlin/projektor/cleanup/TestRunCleanupServiceTest.kt +++ b/server/server-app/src/test/kotlin/projektor/cleanup/TestRunCleanupServiceTest.kt @@ -28,36 +28,37 @@ import java.time.LocalDate import java.time.LocalDateTime class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { - @Test fun `should delete non-grouped test run without attachments`() { - val cleanupService = TestRunCleanupService( - CleanupConfig(30, null, false), - get(), - get(), - get(), - null - ) + val cleanupService = + TestRunCleanupService( + CleanupConfig(30, null, false), + get(), + get(), + get(), + null, + ) val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() - ) ) - ) val testSuiteIds = testSuiteDao.fetchByTestRunId(testRun.id).map { it.id } val testCaseIds = testSuiteIds.flatMap { testCaseDao.fetchByTestSuiteId(it) }.map { it.id } @@ -77,33 +78,35 @@ class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { @Test fun `should delete grouped test run without attachments`() { - val cleanupService = TestRunCleanupService( - CleanupConfig(30, null, false), - get(), - get(), - get(), - null - ) + val cleanupService = + TestRunCleanupService( + CleanupConfig(30, null, false), + get(), + get(), + get(), + null, + ) val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() - ) ) - ) val testGroup1 = testRunDBGenerator.addTestSuiteGroupToTestRun("group1", testRun, listOf("testSuite1")) val testGroup2 = testRunDBGenerator.addTestSuiteGroupToTestRun("group2", testRun, listOf("testSuite2")) @@ -129,13 +132,14 @@ class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { @Test fun `should update processing status to 'deleted'`() { - val cleanupService = TestRunCleanupService( - CleanupConfig(30, null, false), - get(), - get(), - get(), - null - ) + val cleanupService = + TestRunCleanupService( + CleanupConfig(30, null, false), + get(), + get(), + get(), + null, + ) val publicId = randomPublicId() @@ -143,7 +147,7 @@ class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { ResultsProcessing() .setPublicId(publicId.id) .setCreatedTimestamp(LocalDateTime.now()) - .setStatus(ResultsProcessingStatus.SUCCESS.name) + .setStatus(ResultsProcessingStatus.SUCCESS.name), ) testRunDBGenerator.createTestRun( @@ -153,9 +157,9 @@ class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) runBlocking { cleanupService.cleanupTestRun(publicId) } @@ -169,45 +173,48 @@ class TestRunCleanupServiceTest : DatabaseRepositoryTestCase() { @Test fun `should delete test run with attachments`() { - val attachmentsConfig = AttachmentConfig( - "http://localhost:9000", - "attachmentsremoving", - true, - "minio_access_key", - "minio_secret_key", - null - ) + val attachmentsConfig = + AttachmentConfig( + "http://localhost:9000", + "attachmentsremoving", + true, + "minio_access_key", + "minio_secret_key", + null, + ) val attachmentService = AttachmentService(attachmentsConfig, AttachmentDatabaseRepository(dslContext)) attachmentService.conditionallyCreateBucketIfNotExists() - val cleanupService = TestRunCleanupService( - CleanupConfig(30, null, false), - get(), - get(), - get(), - attachmentService - ) + val cleanupService = + TestRunCleanupService( + CleanupConfig(30, null, false), + get(), + get(), + get(), + attachmentService, + ) val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() - ) ) - ) val attachmentInputStream = File("src/test/resources/test-attachment.txt").inputStream() val attachmentFileNames = listOf("attachment1.txt", "attachment2.txt", "attachment3.txt") diff --git a/server/server-app/src/test/kotlin/projektor/compare/PreviousTestRunServiceTest.kt b/server/server-app/src/test/kotlin/projektor/compare/PreviousTestRunServiceTest.kt index 2f3d241ae..14a151101 100644 --- a/server/server-app/src/test/kotlin/projektor/compare/PreviousTestRunServiceTest.kt +++ b/server/server-app/src/test/kotlin/projektor/compare/PreviousTestRunServiceTest.kt @@ -18,7 +18,6 @@ import java.time.ZoneOffset import java.time.temporal.ChronoUnit class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { - @Test fun `should exclude test run that is newer than specified test run`() { val previousTestRunService by inject() @@ -33,7 +32,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( previousPublicId, JacocoXmlLoader().serverApp(), - repoName + repoName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -41,19 +40,19 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( thisPublicId, JacocoXmlLoader().serverApp(), - repoName + repoName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( newerPublicId, JacocoXmlLoader().serverApp(), - repoName + repoName, ) val returnedId = runBlocking { previousTestRunService.findPreviousMainBranchRunWithCoverage(thisPublicId) } @@ -78,7 +77,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "project" + projectName = "project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -86,7 +85,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -94,7 +93,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "project" + projectName = "project", ) val returnedId = runBlocking { previousTestRunService.findPreviousMainBranchRunWithCoverage(thisPublicId) } @@ -117,7 +116,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { publicId, JacocoXmlLoader().serverApp(), repoName, - branchName = "main" + branchName = "main", ) } @@ -125,7 +124,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { newerFeatureBranchWithCoveragePublicId, JacocoXmlLoader().serverApp(), repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) val newerWithoutCoveragePublicId = randomPublicId() @@ -133,10 +132,17 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { newerWithoutCoveragePublicId, repoName, true, - null + null, ) - val mostRecentTestRun = runBlocking { previousTestRunService.findMostRecentRunWithCoverage(repoName, null, BranchSearch(branchType = BranchType.MAINLINE)) } + val mostRecentTestRun = + runBlocking { + previousTestRunService.findMostRecentRunWithCoverage( + repoName, + null, + BranchSearch(branchType = BranchType.MAINLINE), + ) + } expectThat(mostRecentTestRun).isNotNull().and { get { publicId }.isEqualTo(newestMainlineWithCoveragePublicId) @@ -159,7 +165,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { publicId, JacocoXmlLoader().serverApp(), repoName, - branchName = "main" + branchName = "main", ) } @@ -167,7 +173,7 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { newerFeatureBranchWithCoveragePublicId, JacocoXmlLoader().serverApp(), repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) val newerWithoutCoveragePublicId = randomPublicId() @@ -175,10 +181,11 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { newerWithoutCoveragePublicId, repoName, true, - null + null, ) - val mostRecentTestRun = runBlocking { previousTestRunService.findMostRecentRunWithCoverage(repoName, null, BranchSearch(branchType = BranchType.ALL)) } + val mostRecentTestRun = + runBlocking { previousTestRunService.findMostRecentRunWithCoverage(repoName, null, BranchSearch(branchType = BranchType.ALL)) } expectThat(mostRecentTestRun).isNotNull().and { get { publicId }.isEqualTo(newerFeatureBranchWithCoveragePublicId) @@ -201,29 +208,39 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) - val newTestRun = testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( - publicId = newPublicId, - coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = repoName, - branchName = "main", - projectName = projectName - ) + val newTestRun = + testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( + publicId = newPublicId, + coverageText = JacocoXmlLoader().serverAppReduced(), + repoName = repoName, + branchName = "main", + projectName = projectName, + ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = newerWithDifferentProjectName, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) - val recentTestRun = runBlocking { previousTestRunService.findMostRecentRunWithCoverage(repoName, projectName, BranchSearch(branchType = BranchType.MAINLINE)) } + val recentTestRun = + runBlocking { + previousTestRunService.findMostRecentRunWithCoverage( + repoName, + projectName, + BranchSearch(branchType = BranchType.MAINLINE), + ) + } expectThat(recentTestRun).isNotNull().and { get { publicId }.isEqualTo(newPublicId) - get { createdTimestamp.truncatedTo(ChronoUnit.MILLIS) }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) + get { + createdTimestamp.truncatedTo(ChronoUnit.MILLIS) + }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) get { branch }.isEqualTo("main") } } @@ -243,28 +260,32 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = null + projectName = null, ) - val newTestRun = testRunDBGenerator.createSimpleTestRunInRepo( - publicId = newPublicId, - repoName = repoName, - ci = true, - projectName = null - ) + val newTestRun = + testRunDBGenerator.createSimpleTestRunInRepo( + publicId = newPublicId, + repoName = repoName, + ci = true, + projectName = null, + ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = newerWithDifferentProjectName, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) - val recentTestRun = runBlocking { previousTestRunService.findMostRecentRun(repoName, null, BranchSearch(branchType = BranchType.MAINLINE)) } + val recentTestRun = + runBlocking { previousTestRunService.findMostRecentRun(repoName, null, BranchSearch(branchType = BranchType.MAINLINE)) } expectThat(recentTestRun).isNotNull().and { get { publicId }.isEqualTo(newPublicId) - get { createdTimestamp.truncatedTo(ChronoUnit.MILLIS) }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) + get { + createdTimestamp.truncatedTo(ChronoUnit.MILLIS) + }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) get { branch }.isEqualTo("main") } } @@ -285,29 +306,33 @@ class PreviousTestRunServiceTest : DatabaseRepositoryTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) - val newTestRun = testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( - publicId = newPublicId, - coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = repoName, - branchName = "main", - projectName = projectName - ) + val newTestRun = + testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( + publicId = newPublicId, + coverageText = JacocoXmlLoader().serverAppReduced(), + repoName = repoName, + branchName = "main", + projectName = projectName, + ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = newerWithDifferentProjectName, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) - val recentTestRun = runBlocking { previousTestRunService.findMostRecentRun(repoName, projectName, BranchSearch(branchType = BranchType.MAINLINE)) } + val recentTestRun = + runBlocking { previousTestRunService.findMostRecentRun(repoName, projectName, BranchSearch(branchType = BranchType.MAINLINE)) } expectThat(recentTestRun).isNotNull().and { get { publicId }.isEqualTo(newPublicId) - get { createdTimestamp.truncatedTo(ChronoUnit.MILLIS) }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) + get { + createdTimestamp.truncatedTo(ChronoUnit.MILLIS) + }.isEqualTo(newTestRun.createdTimestamp.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)) get { branch }.isEqualTo("main") get { passed }.isTrue() } diff --git a/server/server-app/src/test/kotlin/projektor/coverage/AddCoverageFileCompressedApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/AddCoverageFileCompressedApplicationTest.kt index 45edc3fd4..a4e128b10 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/AddCoverageFileCompressedApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/AddCoverageFileCompressedApplicationTest.kt @@ -29,10 +29,11 @@ class AddCoverageFileCompressedApplicationTest : ApplicationTestCase() { val coverageGroup = "server-app" val coverageXmlReport = JacocoXmlLoader().serverApp() - val coverageFilePayload = CoverageFilePayload( - reportContents = coverageXmlReport, - baseDirectoryPath = "server/server-app/src/main/kotlin" - ) + val coverageFilePayload = + CoverageFilePayload( + reportContents = coverageXmlReport, + baseDirectoryPath = "server/server-app/src/main/kotlin", + ) val compressedBody = gzip(coveragePayloadParser.serializeCoverageFilePayload(coverageFilePayload)) withTestApplication(::createTestApplication) { @@ -62,7 +63,9 @@ class AddCoverageFileCompressedApplicationTest : ApplicationTestCase() { expectThat(resultsProcessingDatabaseRepositoryFile) .isNotNull().and { get { directoryName }.isEqualTo("projektor/incomingresults/processing") - get { filePath }.isEqualTo("server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt") + get { filePath }.isEqualTo( + "server/server-app/src/main/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepository.kt", + ) } } } diff --git a/server/server-app/src/test/kotlin/projektor/coverage/ComparePreviousCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/ComparePreviousCoverageApplicationTest.kt index 3c3fe12f0..090abfb07 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/ComparePreviousCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/ComparePreviousCoverageApplicationTest.kt @@ -29,13 +29,13 @@ class ComparePreviousCoverageApplicationTest : ApplicationTestCase() { testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = previousPublicId, coverageText = JacocoXmlLoader().serverApp(), - repoName = repoName + repoName = repoName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thisPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = repoName + repoName = repoName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -86,17 +86,16 @@ class ComparePreviousCoverageApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$thisPublicId/coverage") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = previousPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = repoName + repoName = repoName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thisPublicId, coverageText = JacocoXmlLoader().serverApp(), - repoName = repoName + repoName = repoName, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/coverage/CoverageDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/CoverageDatabaseRepositoryTest.kt index bda533a6c..396d0fa45 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/CoverageDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/CoverageDatabaseRepositoryTest.kt @@ -23,7 +23,6 @@ import java.math.BigDecimal import kotlin.test.assertNotNull class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `when one coverage report should fetch its overall stats`() { val coverageDatabaseRepository = CoverageDatabaseRepository(dslContext) @@ -33,15 +32,16 @@ class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val coverageRun = runBlocking { coverageDatabaseRepository.createOrGetCoverageRun(publicId) } - val coverageReport = CoverageReport( - "my-report", - CoverageReportStats( - statementStat = CoverageReportStat(75, 25), - lineStat = CoverageReportStat(60, 0), - branchStat = CoverageReportStat(33, 66) - ), - null - ) + val coverageReport = + CoverageReport( + "my-report", + CoverageReportStats( + statementStat = CoverageReportStat(75, 25), + lineStat = CoverageReportStat(60, 0), + branchStat = CoverageReportStat(33, 66), + ), + null, + ) runBlocking { coverageDatabaseRepository.addCoverageReport(coverageRun, coverageReport) } val overallStats = runBlocking { coverageDatabaseRepository.fetchOverallStats(publicId) } @@ -74,43 +74,47 @@ class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val coverageRun = runBlocking { coverageDatabaseRepository.createOrGetCoverageRun(publicId) } - val coverageReport = CoverageReport( - "my-report", - CoverageReportStats( - statementStat = CoverageReportStat(75, 25), - lineStat = CoverageReportStat(60, 0), - branchStat = CoverageReportStat(33, 66) - ), - null - ) + val coverageReport = + CoverageReport( + "my-report", + CoverageReportStats( + statementStat = CoverageReportStat(75, 25), + lineStat = CoverageReportStat(60, 0), + branchStat = CoverageReportStat(33, 66), + ), + null, + ) val coverageGroup = runBlocking { coverageDatabaseRepository.addCoverageReport(coverageRun, coverageReport) } - val coverageReportFiles = listOf( - CoverageFile( - directoryName = "dir-1", - fileName = "File1.kt", - stats = CoverageStats( - statementStat = CoverageStat(75, 25), - lineStat = CoverageStat(60, 0), - branchStat = CoverageStat(33, 66) + val coverageReportFiles = + listOf( + CoverageFile( + directoryName = "dir-1", + fileName = "File1.kt", + stats = + CoverageStats( + statementStat = CoverageStat(75, 25), + lineStat = CoverageStat(60, 0), + branchStat = CoverageStat(33, 66), + ), + missedLines = arrayOf(12, 13), + partialLines = arrayOf(14, 15), + filePath = null, ), - missedLines = arrayOf(12, 13), - partialLines = arrayOf(14, 15), - filePath = null - ), - CoverageFile( - directoryName = "dir-2", - fileName = "File2.kt", - stats = CoverageStats( - statementStat = CoverageStat(80, 20), - lineStat = CoverageStat(55, 10), - branchStat = CoverageStat(12, 1) + CoverageFile( + directoryName = "dir-2", + fileName = "File2.kt", + stats = + CoverageStats( + statementStat = CoverageStat(80, 20), + lineStat = CoverageStat(55, 10), + branchStat = CoverageStat(12, 1), + ), + missedLines = arrayOf(18, 19, 20), + partialLines = arrayOf(21), + filePath = null, ), - missedLines = arrayOf(18, 19, 20), - partialLines = arrayOf(21), - filePath = null ) - ) runBlocking { coverageDatabaseRepository.insertCoverageFiles(coverageReportFiles, coverageRun, coverageGroup) } @@ -143,43 +147,47 @@ class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val coverageRun = runBlocking { coverageDatabaseRepository.createOrGetCoverageRun(publicId) } - val coverageReport = CoverageReport( - "my-report", - CoverageReportStats( - statementStat = CoverageReportStat(75, 25), - lineStat = CoverageReportStat(60, 0), - branchStat = CoverageReportStat(33, 66) - ), - null - ) + val coverageReport = + CoverageReport( + "my-report", + CoverageReportStats( + statementStat = CoverageReportStat(75, 25), + lineStat = CoverageReportStat(60, 0), + branchStat = CoverageReportStat(33, 66), + ), + null, + ) val coverageGroup = runBlocking { coverageDatabaseRepository.addCoverageReport(coverageRun, coverageReport) } - val coverageReportFiles = listOf( - CoverageFile( - directoryName = "dir-1", - fileName = "File1.kt", - stats = CoverageStats( - statementStat = CoverageStat(75, 25, null), - lineStat = CoverageStat(60, 0, null), - branchStat = CoverageStat(33, 66, null) + val coverageReportFiles = + listOf( + CoverageFile( + directoryName = "dir-1", + fileName = "File1.kt", + stats = + CoverageStats( + statementStat = CoverageStat(75, 25, null), + lineStat = CoverageStat(60, 0, null), + branchStat = CoverageStat(33, 66, null), + ), + missedLines = arrayOf(12), + partialLines = arrayOf(14, 15), + filePath = null, ), - missedLines = arrayOf(12), - partialLines = arrayOf(14, 15), - filePath = null - ), - CoverageFile( - directoryName = "dir-2", - fileName = "File2.kt", - stats = CoverageStats( - statementStat = CoverageStat(80, 20, null), - lineStat = CoverageStat(55, 10, null), - branchStat = CoverageStat(12, 1, null) + CoverageFile( + directoryName = "dir-2", + fileName = "File2.kt", + stats = + CoverageStats( + statementStat = CoverageStat(80, 20, null), + lineStat = CoverageStat(55, 10, null), + branchStat = CoverageStat(12, 1, null), + ), + missedLines = arrayOf(18, 19, 20), + partialLines = arrayOf(21), + filePath = null, ), - missedLines = arrayOf(18, 19, 20), - partialLines = arrayOf(21), - filePath = null ) - ) runBlocking { coverageDatabaseRepository.insertCoverageFiles(coverageReportFiles, coverageRun, coverageGroup) } @@ -218,15 +226,16 @@ class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val coverageRun = runBlocking { coverageDatabaseRepository.createOrGetCoverageRun(publicId) } - val coverageReport = CoverageReport( - "my-report", - CoverageReportStats( - statementStat = CoverageReportStat(75, 25), - lineStat = CoverageReportStat(60, 0), - branchStat = CoverageReportStat(33, 66) - ), - null - ) + val coverageReport = + CoverageReport( + "my-report", + CoverageReportStats( + statementStat = CoverageReportStat(75, 25), + lineStat = CoverageReportStat(60, 0), + branchStat = CoverageReportStat(33, 66), + ), + null, + ) runBlocking { coverageDatabaseRepository.addCoverageReport(coverageRun, coverageReport) } val hasCoverageData = runBlocking { coverageDatabaseRepository.coverageGroupExists(publicId) } @@ -269,19 +278,23 @@ class CoverageDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val coverageRun = runBlocking { coverageDatabaseRepository.createOrGetCoverageRun(publicId) } - val coverageReport = CoverageReport( - "my-report", - CoverageReportStats( - statementStat = CoverageReportStat(75, 25), - lineStat = CoverageReportStat(60, 0), - branchStat = CoverageReportStat(33, 66) - ), - null - ) + val coverageReport = + CoverageReport( + "my-report", + CoverageReportStats( + statementStat = CoverageReportStat(75, 25), + lineStat = CoverageReportStat(60, 0), + branchStat = CoverageReportStat(33, 66), + ), + null, + ) val newLineStat = CoverageStat(covered = 8, missed = 1) - val (newCoverageGroup, coverageGroupStatus) = runBlocking { coverageDatabaseRepository.upsertCoverageGroup(coverageRun, coverageReport, newLineStat) } + val (newCoverageGroup, coverageGroupStatus) = + runBlocking { + coverageDatabaseRepository.upsertCoverageGroup(coverageRun, coverageReport, newLineStat) + } expectThat(newCoverageGroup) { get { name }.isEqualTo("my-report") } diff --git a/server/server-app/src/test/kotlin/projektor/coverage/CoverageExistsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/CoverageExistsApplicationTest.kt index ea042a898..1d0983ec8 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/CoverageExistsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/CoverageExistsApplicationTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertNotNull @ExperimentalStdlibApi class CoverageExistsApplicationTest : ApplicationTestCase() { - @Test fun `when report has coverage data should return true`() { val publicId = randomPublicId() diff --git a/server/server-app/src/test/kotlin/projektor/coverage/CoverageFileCombinerTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/CoverageFileCombinerTest.kt index eb8d73811..c8dad20b2 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/CoverageFileCombinerTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/CoverageFileCombinerTest.kt @@ -12,16 +12,18 @@ import strikt.assertions.isNotNull class CoverageFileCombinerTest { @Test fun `should add new files that do not currently exist`() { - val existingCoverageFiles = listOf( - createCoverageFile("src/File1.tsx", arrayOf(2), CoverageStat(covered = 5, missed = 1)), - createCoverageFile("src/File2.tsx", arrayOf(), CoverageStat(covered = 6, missed = 0)), - createCoverageFile("src/File3.tsx", arrayOf(), CoverageStat(covered = 7, missed = 0)) - ) + val existingCoverageFiles = + listOf( + createCoverageFile("src/File1.tsx", arrayOf(2), CoverageStat(covered = 5, missed = 1)), + createCoverageFile("src/File2.tsx", arrayOf(), CoverageStat(covered = 6, missed = 0)), + createCoverageFile("src/File3.tsx", arrayOf(), CoverageStat(covered = 7, missed = 0)), + ) - val incomingCoverageFiles = listOf( - createCoverageFile("src/File8.tsx", arrayOf(2, 6), CoverageStat(covered = 5, missed = 2)), - createCoverageFile("src/File9.tsx", arrayOf(), CoverageStat(covered = 9, missed = 0)) - ) + val incomingCoverageFiles = + listOf( + createCoverageFile("src/File8.tsx", arrayOf(2, 6), CoverageStat(covered = 5, missed = 2)), + createCoverageFile("src/File9.tsx", arrayOf(), CoverageStat(covered = 9, missed = 0)), + ) val combinedCoverageFiles = combineCoverageFiles(existingCoverageFiles, incomingCoverageFiles) expectThat(combinedCoverageFiles).hasSize(5) @@ -55,15 +57,17 @@ class CoverageFileCombinerTest { @Test fun `should combine existing file and add new one`() { - val existingCoverageFiles = listOf( - createCoverageFile("src/File1.tsx", arrayOf(2), CoverageStat(covered = 5, missed = 1)), - createCoverageFile("src/File2.tsx", arrayOf(3), CoverageStat(covered = 6, missed = 1)), - ) + val existingCoverageFiles = + listOf( + createCoverageFile("src/File1.tsx", arrayOf(2), CoverageStat(covered = 5, missed = 1)), + createCoverageFile("src/File2.tsx", arrayOf(3), CoverageStat(covered = 6, missed = 1)), + ) - val incomingCoverageFiles = listOf( - createCoverageFile("src/File1.tsx", arrayOf(6), CoverageStat(covered = 5, missed = 1)), - createCoverageFile("src/File3.tsx", arrayOf(), CoverageStat(covered = 9, missed = 0)) - ) + val incomingCoverageFiles = + listOf( + createCoverageFile("src/File1.tsx", arrayOf(6), CoverageStat(covered = 5, missed = 1)), + createCoverageFile("src/File3.tsx", arrayOf(), CoverageStat(covered = 9, missed = 0)), + ) val combinedCoverageFiles = combineCoverageFiles(existingCoverageFiles, incomingCoverageFiles) expectThat(combinedCoverageFiles).hasSize(3) @@ -87,13 +91,15 @@ class CoverageFileCombinerTest { @Test fun `should use the intersection of missed lines as the result`() { - val existingCoverageFiles = listOf( - createCoverageFile("src/File1.tsx", arrayOf(2, 6, 8, 9), CoverageStat(covered = 5, missed = 4)), - ) + val existingCoverageFiles = + listOf( + createCoverageFile("src/File1.tsx", arrayOf(2, 6, 8, 9), CoverageStat(covered = 5, missed = 4)), + ) - val incomingCoverageFiles = listOf( - createCoverageFile("src/File1.tsx", arrayOf(1, 6, 8, 10), CoverageStat(covered = 5, missed = 4)), - ) + val incomingCoverageFiles = + listOf( + createCoverageFile("src/File1.tsx", arrayOf(1, 6, 8, 10), CoverageStat(covered = 5, missed = 4)), + ) val combinedCoverageFiles = combineCoverageFiles(existingCoverageFiles, incomingCoverageFiles) expectThat(combinedCoverageFiles).hasSize(1) @@ -105,17 +111,21 @@ class CoverageFileCombinerTest { } } - private fun createCoverageFile(filePath: String, missedLines: Array, lineStat: CoverageStat) = - CoverageFile( - filePath = filePath, - fileName = "fileName", - directoryName = "dir", - missedLines = missedLines, - partialLines = arrayOf(), - stats = CoverageStats( + private fun createCoverageFile( + filePath: String, + missedLines: Array, + lineStat: CoverageStat, + ) = CoverageFile( + filePath = filePath, + fileName = "fileName", + directoryName = "dir", + missedLines = missedLines, + partialLines = arrayOf(), + stats = + CoverageStats( lineStat = lineStat, branchStat = CoverageStat(0, 0), - statementStat = CoverageStat(0, 0) - ) - ) + statementStat = CoverageStat(0, 0), + ), + ) } diff --git a/server/server-app/src/test/kotlin/projektor/coverage/CoverageServiceTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/CoverageServiceTest.kt index 6f679768e..c1bae42ed 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/CoverageServiceTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/CoverageServiceTest.kt @@ -31,12 +31,13 @@ class CoverageServiceTest : DatabaseRepositoryTestCase() { val metricsService = MetricsService(meterRegistry) val previousTestRunService: PreviousTestRunService by inject() val processingFailureService: ProcessingFailureService by inject() - val coverageService = CoverageService( - coverageRepository, - metricsService, - previousTestRunService, - processingFailureService - ) + val coverageService = + CoverageService( + coverageRepository, + metricsService, + previousTestRunService, + processingFailureService, + ) val coverageFilePayload = CoverageFilePayload(reportContents = JacocoXmlLoader().junitResultsParser()) val publicId = PublicId("this-is-too-long-for-an-id") @@ -56,17 +57,19 @@ class CoverageServiceTest : DatabaseRepositoryTestCase() { val metricsService = MetricsService(meterRegistry) val previousTestRunService: PreviousTestRunService by inject() val processingFailureService: ProcessingFailureService by inject() - val coverageService = CoverageService( - coverageRepository, - metricsService, - previousTestRunService, - processingFailureService - ) + val coverageService = + CoverageService( + coverageRepository, + metricsService, + previousTestRunService, + processingFailureService, + ) val reportContents = CloverXmlLoader().coverageFilesTable() - val coverageFilePayload = CoverageFilePayload( - reportContents = reportContents - ) + val coverageFilePayload = + CoverageFilePayload( + reportContents = reportContents, + ) val parsedReportPair = runBlocking { coverageService.parseReport(coverageFilePayload) } assertNotNull(parsedReportPair) diff --git a/server/server-app/src/test/kotlin/projektor/coverage/GetCoverageReportStatsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/GetCoverageReportStatsApplicationTest.kt index 58691f3f6..c0d95ea8a 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/GetCoverageReportStatsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/GetCoverageReportStatsApplicationTest.kt @@ -18,7 +18,6 @@ import kotlin.test.assertNotNull @ExperimentalStdlibApi class GetCoverageReportStatsApplicationTest : ApplicationTestCase() { - @Test fun `when one coverage report should get its stats`() { val publicId = randomPublicId() diff --git a/server/server-app/src/test/kotlin/projektor/coverage/SaveCoberturaCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/coverage/SaveCoberturaCoverageApplicationTest.kt index cb8462c1e..6ae45ee00 100644 --- a/server/server-app/src/test/kotlin/projektor/coverage/SaveCoberturaCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/coverage/SaveCoberturaCoverageApplicationTest.kt @@ -21,13 +21,13 @@ import java.math.BigDecimal import kotlin.test.assertNotNull class SaveCoberturaCoverageApplicationTest : ApplicationTestCase() { - @Test fun `should save Cobertura coverage and test results`() { - val requestBody = GroupedResultsXmlLoader().resultsWithCoverage( - resultsXmls = listOf(ResultsXmlLoader().jestUi()), - coverageXmls = listOf(CoberturaXmlLoader().uiCobertura()) - ) + val requestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + resultsXmls = listOf(ResultsXmlLoader().jestUi()), + coverageXmls = listOf(CoberturaXmlLoader().uiCobertura()), + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { @@ -76,10 +76,11 @@ class SaveCoberturaCoverageApplicationTest : ApplicationTestCase() { @Test fun `should save Cobertura coverage without branch field on line and test results`() { - val requestBody = GroupedResultsXmlLoader().resultsWithCoverage( - resultsXmls = listOf(ResultsXmlLoader().jestUi()), - coverageXmls = listOf(CoberturaXmlLoader().noBranchCobertura()) - ) + val requestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + resultsXmls = listOf(ResultsXmlLoader().jestUi()), + coverageXmls = listOf(CoberturaXmlLoader().noBranchCobertura()), + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureApplicationTest.kt index 43f37596d..0323f00c8 100644 --- a/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureApplicationTest.kt @@ -19,7 +19,6 @@ import strikt.assertions.isEqualTo import kotlin.test.assertNotNull class ProcessingFailureApplicationTest : ApplicationTestCase() { - @Test fun `should fetch processing failures`() { val tooOldPublicIds = (1..5).map { randomPublicId() } @@ -35,7 +34,7 @@ class ProcessingFailureApplicationTest : ApplicationTestCase() { publicId = publicId, body = "too-old", bodyType = FailureBodyType.COVERAGE, - e = IllegalArgumentException("too-old") + e = IllegalArgumentException("too-old"), ) } } @@ -46,7 +45,7 @@ class ProcessingFailureApplicationTest : ApplicationTestCase() { publicId = publicId, body = "recent-body-$publicId", bodyType = FailureBodyType.COVERAGE, - e = IllegalArgumentException("recent-failure-$publicId") + e = IllegalArgumentException("recent-failure-$publicId"), ) } } diff --git a/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureDatabaseRepositoryTest.kt index 3a0924570..795c6c5fa 100644 --- a/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/error/ProcessingFailureDatabaseRepositoryTest.kt @@ -12,7 +12,6 @@ import strikt.assertions.isEqualTo import java.time.temporal.ChronoUnit class ProcessingFailureDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch most recent failure`() { val processingFailureRepository: ProcessingFailureRepository by inject() @@ -22,14 +21,15 @@ class ProcessingFailureDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val bodyType = FailureBodyType.TEST_RESULTS val failureMessage = "the failure" - val failureDB = runBlocking { - processingFailureRepository.recordProcessingFailure( - publicId, - body, - bodyType, - failureMessage - ) - } + val failureDB = + runBlocking { + processingFailureRepository.recordProcessingFailure( + publicId, + body, + bodyType, + failureMessage, + ) + } val failures = runBlocking { processingFailureRepository.fetchRecentProcessingFailures(1) } expectThat(failures).hasSize(1) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/AppendCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/AppendCoverageApplicationTest.kt index 7d242d466..006593557 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/AppendCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/AppendCoverageApplicationTest.kt @@ -38,21 +38,24 @@ class AppendCoverageApplicationTest : ApplicationTestCase() { metadata.git = gitMetadata metadata.group = "B12" - val coverageFilesTableRequestBody = GroupedResultsXmlLoader().resultsWithCoverage( - listOf(resultsXmlLoader.jestCoverageFilesTable()), - listOf(cloverXmlLoader.coverageFilesTable()), - metadata - ) - val coverageGraphRequestBody = GroupedResultsXmlLoader().resultsWithCoverage( - listOf(resultsXmlLoader.jestCoverageGraph()), - listOf(cloverXmlLoader.coverageGraph()), - metadata - ) - val coverageTableRequestBody = GroupedResultsXmlLoader().resultsWithCoverage( - listOf(resultsXmlLoader.jestCoverageTable()), - listOf(cloverXmlLoader.coverageTable()), - metadata - ) + val coverageFilesTableRequestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + listOf(resultsXmlLoader.jestCoverageFilesTable()), + listOf(cloverXmlLoader.coverageFilesTable()), + metadata, + ) + val coverageGraphRequestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + listOf(resultsXmlLoader.jestCoverageGraph()), + listOf(cloverXmlLoader.coverageGraph()), + metadata, + ) + val coverageTableRequestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + listOf(resultsXmlLoader.jestCoverageTable()), + listOf(cloverXmlLoader.coverageTable()), + metadata, + ) lateinit var publicId: PublicId lateinit var testRun: TestRun @@ -229,8 +232,9 @@ class AppendCoverageApplicationTest : ApplicationTestCase() { } await untilAsserted { - val coverageTableFile = runBlocking { coverageService.getCoverageGroupFiles(publicId, coverageGroup.name) } - .find { it.fileName == "CoverageTable.tsx" } + val coverageTableFile = + runBlocking { coverageService.getCoverageGroupFiles(publicId, coverageGroup.name) } + .find { it.fileName == "CoverageTable.tsx" } expectThat(coverageTableFile) .isNotNull() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/AppendGroupedResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/AppendGroupedResultsApplicationTest.kt index 7ae7bc9f6..1d4983b5e 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/AppendGroupedResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/AppendGroupedResultsApplicationTest.kt @@ -27,7 +27,6 @@ import strikt.assertions.isTrue import kotlin.test.assertNotNull class AppendGroupedResultsApplicationTest : ApplicationTestCase() { - @Test fun `should append second grouped test results run`() { val repoPart = RandomStringUtils.randomAlphabetic(12) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsApplicationTest.kt index 87e2085d1..bef0a6c20 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsApplicationTest.kt @@ -57,12 +57,13 @@ class CypressResultsApplicationTest : ApplicationTestCase() { @Test fun `when one Cypress test suite is empty should save other one`() { - val requestBody = GroupedResultsXmlLoader().wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.cypressEmptyTestSuites(), - resultsXmlLoader.cypressAttachmentsSpecWithFilePath() + val requestBody = + GroupedResultsXmlLoader().wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.cypressEmptyTestSuites(), + resultsXmlLoader.cypressAttachmentsSpecWithFilePath(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsWithFileNameApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsWithFileNameApplicationTest.kt index 7de100b44..22afaed66 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsWithFileNameApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/CypressResultsWithFileNameApplicationTest.kt @@ -25,12 +25,13 @@ import kotlin.test.assertNotNull class CypressResultsWithFileNameApplicationTest : ApplicationTestCase() { @Test fun `should save Cypress file path as package name`() { - val resultsBody = GroupedResultsXmlLoader().wrapResultsXmlsInGroup( - listOf( - ResultsXmlLoader().cypressAttachmentsSpecWithFilePath(), - ResultsXmlLoader().cypressRepositoryTimelineSpecWithFilePath() + val resultsBody = + GroupedResultsXmlLoader().wrapResultsXmlsInGroup( + listOf( + ResultsXmlLoader().cypressAttachmentsSpecWithFilePath(), + ResultsXmlLoader().cypressRepositoryTimelineSpecWithFilePath(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/GroupedTestResultsServiceTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/GroupedTestResultsServiceTest.kt index 32ada8f69..b3d8729ff 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/GroupedTestResultsServiceTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/GroupedTestResultsServiceTest.kt @@ -13,7 +13,6 @@ import strikt.assertions.isNotEmpty import kotlin.test.assertNotNull class GroupedTestResultsServiceTest : DatabaseRepositoryTestCase() { - @Test fun `should filter out test suites that have no test cases`() { val groupedTestResultsService: GroupedTestResultsService by inject() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsApplicationTest.kt index 4c82db83d..2e8f72d9e 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsApplicationTest.kt @@ -17,7 +17,6 @@ import strikt.assertions.isNotNull import kotlin.test.assertNotNull class SaveGroupedResultsApplicationTest : ApplicationTestCase() { - @Test fun `should save grouped test results`() { val requestBody = GroupedResultsXmlLoader().passingGroupedResults() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsCodeQualityApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsCodeQualityApplicationTest.kt index 7211c835c..126c7a68d 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsCodeQualityApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsCodeQualityApplicationTest.kt @@ -15,15 +15,15 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class SaveGroupedResultsCodeQualityApplicationTest : ApplicationTestCase() { - @Test fun `should save results with code quality files`() { - val codeQualityReports = (1..2).map { idx -> - val codeQualityReport = projektor.parser.grouped.model.CodeQualityReport() - codeQualityReport.contents = "Report contents $idx" - codeQualityReport.fileName = "quality_$idx.txt" - codeQualityReport - } + val codeQualityReports = + (1..2).map { idx -> + val codeQualityReport = projektor.parser.grouped.model.CodeQualityReport() + codeQualityReport.contents = "Report contents $idx" + codeQualityReport.fileName = "quality_$idx.txt" + codeQualityReport + } val requestBody = GroupedResultsXmlLoader().codeQualityResults(codeQualityReports) val compressedBody = gzip(requestBody) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsGitRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsGitRepositoryTest.kt index 1b90963bb..29b6777d4 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsGitRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsGitRepositoryTest.kt @@ -15,7 +15,6 @@ import strikt.assertions.isEqualTo import strikt.assertions.isNotNull class SaveGroupedResultsGitRepositoryTest : ApplicationTestCase() { - @Test fun `should set Git repository table with Git org and repo`() { val gitMetadata = GitMetadata() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsMetricsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsMetricsApplicationTest.kt index 44a85fe84..e2499f9b2 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsMetricsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsMetricsApplicationTest.kt @@ -19,7 +19,6 @@ import strikt.assertions.isEqualTo import kotlin.test.assertNotNull class SaveGroupedResultsMetricsApplicationTest : ApplicationTestCase() { - @Test fun `should record success metric when saving grouped test results succeeds`() { val requestBody = GroupedResultsXmlLoader().passingGroupedResults() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsTelemetryApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsTelemetryApplicationTest.kt index bce206cd0..c45e9caed 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsTelemetryApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsTelemetryApplicationTest.kt @@ -13,7 +13,6 @@ import strikt.assertions.any import strikt.assertions.isEqualTo class SaveGroupedResultsTelemetryApplicationTest : ApplicationTestCase() { - @Test fun `should record telemetry when saving grouped test results`() { val requestBody = GroupedResultsXmlLoader().passingGroupedResults() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoverageApplicationTest.kt index b8b9f3caf..222a3ee13 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoverageApplicationTest.kt @@ -23,7 +23,6 @@ import strikt.assertions.isNotNull import java.math.BigDecimal class SaveGroupedResultsWithCoverageApplicationTest : ApplicationTestCase() { - @Test fun `should save grouped results with coverage`() { val incomingCoverageFile = CoverageFile() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoveragePartialFailureApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoveragePartialFailureApplicationTest.kt index 702e81a74..1bad39375 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoveragePartialFailureApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithCoveragePartialFailureApplicationTest.kt @@ -18,7 +18,6 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class SaveGroupedResultsWithCoveragePartialFailureApplicationTest : ApplicationTestCase() { - @Test fun `when one invalid coverage file should save the others and record parsing failed metric`() { val invalidCoverageFile = CoverageFile() @@ -30,7 +29,10 @@ class SaveGroupedResultsWithCoveragePartialFailureApplicationTest : ApplicationT val validCoverageFile2 = CoverageFile() validCoverageFile2.reportContents = JacocoXmlLoader().junitResultsParser() - val requestBody = GroupedResultsXmlLoader().passingResultsWithCoverage(listOf(validCoverageFile1, invalidCoverageFile, validCoverageFile2)) + val requestBody = + GroupedResultsXmlLoader().passingResultsWithCoverage( + listOf(validCoverageFile1, invalidCoverageFile, validCoverageFile2), + ) val compressedBody = gzip(requestBody) withTestApplication(::createTestApplication) { diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataApplicationTest.kt index fc611d860..dcbabcce5 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataApplicationTest.kt @@ -16,7 +16,6 @@ import strikt.assertions.isEqualTo import strikt.assertions.isTrue class SaveGroupedResultsWithMetadataApplicationTest : ApplicationTestCase() { - @Test fun `should save grouped test results with Git metadata`() { val gitMetadata = GitMetadata() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest.kt index 331993f85..67df07dad 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest.kt @@ -26,7 +26,6 @@ import strikt.assertions.isEqualTo import strikt.assertions.isTrue class SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest : ApplicationTestCase() { - @BeforeEach fun reset() { wireMockServer.resetAll() @@ -70,7 +69,13 @@ class SaveGroupedResultsWithMetadataPullRequestCommentApplicationTest : Applicat }.apply { val (_, testRun) = waitForTestRunSaveToComplete(response) - await until { gitHubWireMockStubber.findAddCommentRequestBodies(incomingOrgName, incomingRepoName, gitHubPullRequestNumber).size == 1 } + await until { + gitHubWireMockStubber.findAddCommentRequestBodies( + incomingOrgName, + incomingRepoName, + gitHubPullRequestNumber, + ).size == 1 + } val gitMetadatas = gitMetadataDao.fetchByTestRunId(testRun.id) expectThat(gitMetadatas).hasSize(1) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMultipleCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMultipleCoverageApplicationTest.kt index 8c8e1f318..246946a61 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMultipleCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveGroupedResultsWithMultipleCoverageApplicationTest.kt @@ -19,21 +19,21 @@ import strikt.assertions.isNotNull import java.math.BigDecimal class SaveGroupedResultsWithMultipleCoverageApplicationTest : ApplicationTestCase() { - @Test fun `should save grouped results with multiple coverage reports`() { - val requestBody = GroupedResultsXmlLoader().resultsWithCoverage( - listOf( - resultsXmlLoader.jestCoverageFilesTable(), - resultsXmlLoader.jestCoverageGraph(), - resultsXmlLoader.jestCoverageTable() - ), - listOf( - cloverXmlLoader.coverageFilesTable(), - cloverXmlLoader.coverageGraph(), - cloverXmlLoader.coverageTable() + val requestBody = + GroupedResultsXmlLoader().resultsWithCoverage( + listOf( + resultsXmlLoader.jestCoverageFilesTable(), + resultsXmlLoader.jestCoverageGraph(), + resultsXmlLoader.jestCoverageTable(), + ), + listOf( + cloverXmlLoader.coverageFilesTable(), + cloverXmlLoader.coverageGraph(), + cloverXmlLoader.coverageTable(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveResultsApplicationTest.kt index c9d9ddfee..07584e5eb 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/SaveResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/SaveResultsApplicationTest.kt @@ -24,7 +24,6 @@ import java.math.BigDecimal import kotlin.test.assertNotNull class SaveResultsApplicationTest : ApplicationTestCase() { - @Test fun `should parse request and save results for passing test`() { val requestBody = resultsXmlLoader.passing() diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveGroupedResultsTokenApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveGroupedResultsTokenApplicationTest.kt index ddd007b63..c3cb32d5b 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveGroupedResultsTokenApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveGroupedResultsTokenApplicationTest.kt @@ -26,7 +26,7 @@ class SaveGroupedResultsTokenApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { addHeader(HttpHeaders.ContentType, "text/plain") - addHeader(AuthConfig.PublishToken, validPublishToken) + addHeader(AuthConfig.PUBLISH_TOKEN, validPublishToken) setBody(requestBody) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -50,7 +50,7 @@ class SaveGroupedResultsTokenApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { addHeader(HttpHeaders.ContentType, "text/plain") - addHeader(AuthConfig.PublishToken, "notPublish12345") + addHeader(AuthConfig.PUBLISH_TOKEN, "notPublish12345") setBody(requestBody) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.Unauthorized) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveResultsTokenApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveResultsTokenApplicationTest.kt index f913ece93..016ceb9f8 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveResultsTokenApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/auth/SaveResultsTokenApplicationTest.kt @@ -25,7 +25,7 @@ class SaveResultsTokenApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/results") { addHeader(HttpHeaders.ContentType, "text/plain") - addHeader(AuthConfig.PublishToken, validPublishToken) + addHeader(AuthConfig.PUBLISH_TOKEN, validPublishToken) setBody(requestBody) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -49,7 +49,7 @@ class SaveResultsTokenApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/results") { addHeader(HttpHeaders.ContentType, "text/plain") - addHeader(AuthConfig.PublishToken, "notPublish12345") + addHeader(AuthConfig.PUBLISH_TOKEN, "notPublish12345") setBody(requestBody) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.Unauthorized) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/mapper/PackageClassNameParserSpec.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/mapper/PackageClassNameParserSpec.kt index 3da43f3a0..ab15e8da2 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/mapper/PackageClassNameParserSpec.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/mapper/PackageClassNameParserSpec.kt @@ -13,10 +13,18 @@ class PackageClassNameParserSpec : StringSpec({ row("com.example.sub.package.MyTestSpec", "com.example.sub.package", "MyTestSpec"), row("Spec", null, "Spec"), row("/k6/test.js", "k6/test.js", "test"), - row("src\\TestOutput\\__tests__\\TestSuiteSystemErr.spec.tsx", "src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", "TestSuiteSystemErr"), - row("src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", "src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", "TestSuiteSystemErr"), + row( + "src\\TestOutput\\__tests__\\TestSuiteSystemErr.spec.tsx", + "src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", + "TestSuiteSystemErr", + ), + row( + "src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", + "src/TestOutput/__tests__/TestSuiteSystemErr.spec.tsx", + "TestSuiteSystemErr", + ), row("Text description / with period . and another slash /", null, "Text description / with period . and another slash /"), - row("No_spaces/but./_dots/", null, "No_spaces/but./_dots/") + row("No_spaces/but./_dots/", null, "No_spaces/but./_dots/"), ) { classAndPackage, expectedPackage, expectedClass -> val packageAndClass = parsePackageAndClassName(classAndPackage) diff --git a/server/server-app/src/test/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepositoryTest.kt index c5d5b8f2f..80c18cdd0 100644 --- a/server/server-app/src/test/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/incomingresults/processing/ResultsProcessingDatabaseRepositoryTest.kt @@ -44,9 +44,10 @@ class ResultsProcessingDatabaseRepositoryTest : DatabaseRepositoryTestCase() { fun `should update results processing status`() { val publicId = randomPublicId() - val resultsProcessingDB = ResultsProcessing() - .setPublicId(publicId.id) - .setStatus(ResultsProcessingStatus.RECEIVED.name) + val resultsProcessingDB = + ResultsProcessing() + .setPublicId(publicId.id) + .setStatus(ResultsProcessingStatus.RECEIVED.name) resultsProcessingDao.insert(resultsProcessingDB) runBlocking { resultsProcessingDatabaseRepository.updateResultsProcessingStatus(publicId, ResultsProcessingStatus.PROCESSING) } @@ -61,9 +62,10 @@ class ResultsProcessingDatabaseRepositoryTest : DatabaseRepositoryTestCase() { fun `should set status to error and record error message`() { val publicId = randomPublicId() - val resultsProcessingDB = ResultsProcessing() - .setPublicId(publicId.id) - .setStatus(ResultsProcessingStatus.RECEIVED.name) + val resultsProcessingDB = + ResultsProcessing() + .setPublicId(publicId.id) + .setStatus(ResultsProcessingStatus.RECEIVED.name) resultsProcessingDao.insert(resultsProcessingDB) val newErrorMessage = "An error occurred" @@ -94,9 +96,10 @@ class ResultsProcessingDatabaseRepositoryTest : DatabaseRepositoryTestCase() { fun `should fetch results processing record`() { val publicId = randomPublicId() - val resultsProcessingDB = ResultsProcessing() - .setPublicId(publicId.id) - .setStatus(ResultsProcessingStatus.RECEIVED.name) + val resultsProcessingDB = + ResultsProcessing() + .setPublicId(publicId.id) + .setStatus(ResultsProcessingStatus.RECEIVED.name) resultsProcessingDao.insert(resultsProcessingDB) val resultsProcessing = runBlocking { resultsProcessingDatabaseRepository.fetchResultsProcessing(publicId) } diff --git a/server/server-app/src/test/kotlin/projektor/message/MessageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/message/MessageApplicationTest.kt index 4d0e3ce8c..d584a98a4 100644 --- a/server/server-app/src/test/kotlin/projektor/message/MessageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/message/MessageApplicationTest.kt @@ -15,7 +15,6 @@ import strikt.assertions.isEqualTo import kotlin.test.assertNotNull class MessageApplicationTest : ApplicationTestCase() { - @Test fun `when single global message should return it`() { val publicId = randomPublicId() diff --git a/server/server-app/src/test/kotlin/projektor/metrics/MetricsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/metrics/MetricsApplicationTest.kt index 0613e8131..b4a245f08 100644 --- a/server/server-app/src/test/kotlin/projektor/metrics/MetricsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/metrics/MetricsApplicationTest.kt @@ -13,7 +13,6 @@ import projektor.ApplicationTestCase import projektor.incomingresults.randomPublicId class MetricsApplicationTest : ApplicationTestCase() { - @BeforeEach fun reset() { metricsStubber.reset() @@ -30,7 +29,7 @@ class MetricsApplicationTest : ApplicationTestCase() { handleRequest(HttpMethod.Get, "/run/$publicId") { testRunDBGenerator.createTestRun( publicId, - listOf() + listOf(), ) }.apply { await until { metricsStubber.findCreateMetricsDatabaseRequests().isNotEmpty() } @@ -52,7 +51,7 @@ class MetricsApplicationTest : ApplicationTestCase() { handleRequest(HttpMethod.Get, "/run/$publicId") { testRunDBGenerator.createTestRun( publicId, - listOf() + listOf(), ) }.apply { await until { metricsStubber.findCreateMetricsDatabaseRequests().isNotEmpty() } diff --git a/server/server-app/src/test/kotlin/projektor/metrics/MetricsStubber.kt b/server/server-app/src/test/kotlin/projektor/metrics/MetricsStubber.kt index 65dafd7c2..9709c3aa5 100644 --- a/server/server-app/src/test/kotlin/projektor/metrics/MetricsStubber.kt +++ b/server/server-app/src/test/kotlin/projektor/metrics/MetricsStubber.kt @@ -34,17 +34,24 @@ class MetricsStubber { fun findWriteMetricsRequestsForMetric(metricContents: String) = findWriteMetricsRequests().filter { it.bodyAsString.contains(metricContents) } - fun findWriteMetricsRequestForCounterMetric(metricName: String) = - findWriteMetricsRequestsForMetric("$metricName,metric_type=counter") + fun findWriteMetricsRequestForCounterMetric(metricName: String) = findWriteMetricsRequestsForMetric("$metricName,metric_type=counter") - fun verifyWriteMetricsRequestForCounterMetric(metricName: String, expectedCount: Int): Boolean { + fun verifyWriteMetricsRequestForCounterMetric( + metricName: String, + expectedCount: Int, + ): Boolean { val metricWriteRequests = findWriteMetricsRequestsForMetric(metricName) - val metricCounts = metricWriteRequests.map { it.bodyAsString.substringAfter("$metricName,metric_type=counter value=").substring(0, 1).toInt() } + val metricCounts = + metricWriteRequests.map { + it.bodyAsString.substringAfter("$metricName,metric_type=counter value=").substring(0, 1).toInt() + } return metricCounts.any { it >= expectedCount } } - fun findWriteMetricsRequestForCounterMetric(metricName: String, expectedCount: Int) = - findWriteMetricsRequestsForMetric("$metricName,metric_type=counter value=$expectedCount") + fun findWriteMetricsRequestForCounterMetric( + metricName: String, + expectedCount: Int, + ) = findWriteMetricsRequestsForMetric("$metricName,metric_type=counter value=$expectedCount") } diff --git a/server/server-app/src/test/kotlin/projektor/notification/github/GitHubPullRequestCommentApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/notification/github/GitHubPullRequestCommentApplicationTest.kt index aa103a38c..bca935756 100644 --- a/server/server-app/src/test/kotlin/projektor/notification/github/GitHubPullRequestCommentApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/notification/github/GitHubPullRequestCommentApplicationTest.kt @@ -195,7 +195,12 @@ class GitHubPullRequestCommentApplicationTest : ApplicationTestCase() { gitMetadata.isMainBranch = true val metadata = ResultsMetadata() metadata.git = gitMetadata - val requestBody = GroupedResultsXmlLoader().wrapPerformanceResultsInGroup("performance.json", PerformanceResultsLoader().k6GetRun(), metadata) + val requestBody = + GroupedResultsXmlLoader().wrapPerformanceResultsInGroup( + "performance.json", + PerformanceResultsLoader().k6GetRun(), + metadata, + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/organization/OrganizationCoverageApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/organization/OrganizationCoverageApplicationTest.kt index 37d3e56f3..fbe86c875 100644 --- a/server/server-app/src/test/kotlin/projektor/organization/OrganizationCoverageApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/organization/OrganizationCoverageApplicationTest.kt @@ -43,52 +43,51 @@ class OrganizationCoverageApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/org/$orgName/coverage") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo1, coverageText = JacocoXmlLoader().serverApp(), repoName = repo1, - projectName = "proj1" + projectName = "proj1", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId1, coverageText = JacocoXmlLoader().serverApp(), repoName = repo1, - projectName = "proj1" + projectName = "proj1", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = otherProjectRepo1, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repo1, - projectName = "proj2" + projectName = "proj2", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo2, coverageText = JacocoXmlLoader().jacocoXmlParser(), - repoName = repo2 + repoName = repo2, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId2, coverageText = JacocoXmlLoader().jacocoXmlParser(), - repoName = repo2 + repoName = repo2, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = olderRunRepo3, coverageText = JacocoXmlLoader().junitResultsParser(), - repoName = repo3 + repoName = repo3, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = publicId3, coverageText = JacocoXmlLoader().junitResultsParser(), - repoName = repo3 + repoName = repo3, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = anotherPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), - repoName = anotherRepo + repoName = anotherRepo, ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -146,19 +145,18 @@ class OrganizationCoverageApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/org/$orgName/coverage") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = mainBranchId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = featureBranchId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "feature/branch" + branchName = "feature/branch", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/performance/GetPerformanceResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/performance/GetPerformanceResultsApplicationTest.kt index 0065c776e..b452a73d9 100644 --- a/server/server-app/src/test/kotlin/projektor/performance/GetPerformanceResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/performance/GetPerformanceResultsApplicationTest.kt @@ -23,23 +23,25 @@ class GetPerformanceResultsApplicationTest : ApplicationTestCase() { fun `when performance results should return them`() { val publicId = randomPublicId() - val savedPerfResult1 = IncomingPerformanceResult( - name = "perf1", - requestsPerSecond = BigDecimal("80.00"), - requestCount = 4000, - average = BigDecimal("25.66"), - maximum = BigDecimal("45.99"), - p95 = BigDecimal("40.78") - ) + val savedPerfResult1 = + IncomingPerformanceResult( + name = "perf1", + requestsPerSecond = BigDecimal("80.00"), + requestCount = 4000, + average = BigDecimal("25.66"), + maximum = BigDecimal("45.99"), + p95 = BigDecimal("40.78"), + ) - val savedPerfResult2 = IncomingPerformanceResult( - name = "perf2", - requestsPerSecond = BigDecimal("90.00"), - requestCount = 6000, - average = BigDecimal("20.67"), - maximum = BigDecimal("42.88"), - p95 = BigDecimal("30.48") - ) + val savedPerfResult2 = + IncomingPerformanceResult( + name = "perf2", + requestsPerSecond = BigDecimal("90.00"), + requestCount = 6000, + average = BigDecimal("20.67"), + maximum = BigDecimal("42.88"), + p95 = BigDecimal("30.48"), + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/performance") { diff --git a/server/server-app/src/test/kotlin/projektor/performance/PerformanceResultsDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/performance/PerformanceResultsDatabaseRepositoryTest.kt index e8b3a818e..7393d4a2d 100644 --- a/server/server-app/src/test/kotlin/projektor/performance/PerformanceResultsDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/performance/PerformanceResultsDatabaseRepositoryTest.kt @@ -12,7 +12,6 @@ import strikt.assertions.isEqualTo import java.math.BigDecimal class PerformanceResultsDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `should insert performance test results`() { val performanceResultsDatabaseRepository = PerformanceResultsDatabaseRepository(dslContext) @@ -22,20 +21,21 @@ class PerformanceResultsDatabaseRepositoryTest : DatabaseRepositoryTestCase() { val testRun = testRunDBGenerator.createEmptyTestRun(publicId) - val result = PerformanceResult( - name = "perf.json", - requestsPerSecond = BigDecimal("50.00"), - requestCount = 4000, - average = BigDecimal("18.022342"), - maximum = BigDecimal("56.29193"), - p95 = BigDecimal("45.02142") - ) + val result = + PerformanceResult( + name = "perf.json", + requestsPerSecond = BigDecimal("50.00"), + requestCount = 4000, + average = BigDecimal("18.022342"), + maximum = BigDecimal("56.29193"), + p95 = BigDecimal("45.02142"), + ) runBlocking { performanceResultsDatabaseRepository.savePerformanceResults( testRun.id, publicId, - result + result, ) } diff --git a/server/server-app/src/test/kotlin/projektor/performance/SavePerformanceResultsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/performance/SavePerformanceResultsApplicationTest.kt index 77b1a52a6..cf4c31ab3 100644 --- a/server/server-app/src/test/kotlin/projektor/performance/SavePerformanceResultsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/performance/SavePerformanceResultsApplicationTest.kt @@ -37,10 +37,11 @@ class SavePerformanceResultsApplicationTest : ApplicationTestCase() { perfResult2.name = "perf-2" perfResult2.resultsBlob = PerformanceResultsLoader().k6GetRun() - val requestBody = GroupedResultsXmlLoader().wrapPerformanceResultsInGroup( - listOf(perfResult1, perfResult2), - metadata - ) + val requestBody = + GroupedResultsXmlLoader().wrapPerformanceResultsInGroup( + listOf(perfResult1, perfResult2), + metadata, + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Post, "/groupedResults") { diff --git a/server/server-app/src/test/kotlin/projektor/quality/CodeQualityReportApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/quality/CodeQualityReportApplicationTest.kt index 3dad02b92..3fd834457 100644 --- a/server/server-app/src/test/kotlin/projektor/quality/CodeQualityReportApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/quality/CodeQualityReportApplicationTest.kt @@ -17,27 +17,26 @@ import strikt.assertions.isEqualTo import kotlin.test.assertNotNull class CodeQualityReportApplicationTest : ApplicationTestCase() { - @Test fun `when code quality reports for test run should get them`() { val publicId = randomPublicId() withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/quality") { - val testRun = testRunDBGenerator.createEmptyTestRun(publicId) - val codeQualityReports = (1..3).map { idx -> - val codeQualityReport = CodeQualityReport() + val codeQualityReports = + (1..3).map { idx -> + val codeQualityReport = CodeQualityReport() - codeQualityReport.testRunId = testRun.id - codeQualityReport.contents = "Report contents $idx" - codeQualityReport.fileName = "code_quality_$idx.txt" - codeQualityReport.groupName = "group_$idx" - codeQualityReport.idx = idx + codeQualityReport.testRunId = testRun.id + codeQualityReport.contents = "Report contents $idx" + codeQualityReport.fileName = "code_quality_$idx.txt" + codeQualityReport.groupName = "group_$idx" + codeQualityReport.idx = idx - codeQualityReport - } + codeQualityReport + } codeQualityReportDao.insert(codeQualityReports) } @@ -76,7 +75,6 @@ class CodeQualityReportApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/quality") { - val testRun = testRunDBGenerator.createEmptyTestRun(publicId) val otherTestRun = testRunDBGenerator.createEmptyTestRun(otherPublicId) diff --git a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageCurrentApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageCurrentApplicationTest.kt index 1103d8efc..0c6682e63 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageCurrentApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageCurrentApplicationTest.kt @@ -19,7 +19,6 @@ import java.time.ZoneOffset import kotlin.test.assertNotNull class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { - @Test fun `should fetch current coverage for repository without project name`() { val orgName = RandomStringUtils.randomAlphabetic(12) @@ -34,26 +33,25 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -61,14 +59,14 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -102,13 +100,12 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -116,7 +113,7 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -124,7 +121,7 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = null + projectName = null, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -132,14 +129,14 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -169,12 +166,11 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/current") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInRepoFeatureBranch, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "another-branch" + branchName = "another-branch", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -182,14 +178,14 @@ class RepositoryCoverageCurrentApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.NoContent) diff --git a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageExistsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageExistsApplicationTest.kt index 8fd10002e..1fad871c4 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageExistsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageExistsApplicationTest.kt @@ -27,12 +27,11 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/exists") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInRepoPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -40,14 +39,14 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -70,20 +69,19 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/exists") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentProjectPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -109,12 +107,11 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/coverage/exists") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInRepoPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -122,14 +119,14 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -154,19 +151,18 @@ class RepositoryCoverageExistsApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/coverage/exists") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInRepoPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageTimelineApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageTimelineApplicationTest.kt index b9b28812f..d5e3b2d4e 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageTimelineApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/coverage/RepositoryCoverageTimelineApplicationTest.kt @@ -21,7 +21,6 @@ import java.time.ZoneOffset import kotlin.test.assertNotNull class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { - @Test fun `should fetch coverage timeline in mainline for repository without project name`() { val orgName = RandomStringUtils.randomAlphabetic(12) @@ -37,33 +36,32 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/timeline") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentBranchPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -71,14 +69,14 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -133,33 +131,32 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/coverage/timeline?branch=ALL") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = secondRunPublicId, coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = thirdRunPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "main" + branchName = "main", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentBranchPublicId, coverageText = JacocoXmlLoader().jacocoXmlParser(), repoName = repoName, - branchName = "feature/dev" + branchName = "feature/dev", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -167,14 +164,14 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -216,13 +213,12 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/coverage/timeline") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -230,7 +226,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -238,7 +234,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "feature/dev", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -246,7 +242,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = null + projectName = null, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -254,14 +250,14 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -308,13 +304,12 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/coverage/timeline?branch=ALL") { - testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = firstRunPublicId, coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -322,7 +317,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "main", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -330,7 +325,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverApp(), repoName = repoName, branchName = "feature/dev", - projectName = projectName + projectName = projectName, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -338,7 +333,7 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().serverAppReduced(), repoName = repoName, branchName = "main", - projectName = null + projectName = null, ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( @@ -346,14 +341,14 @@ class RepositoryCoverageTimelineApplicationTest : ApplicationTestCase() { coverageText = JacocoXmlLoader().junitResultsParser(), repoName = repoName, branchName = "main", - projectName = "other-project" + projectName = "other-project", ) testRunDBGenerator.createTestRunWithCoverageAndGitMetadata( publicId = runInDifferentRepoPublicId, coverageText = JacocoXmlLoader().junitResultsParser(), repoName = "other/repo", - branchName = "main" + branchName = "main", ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepositoryTest.kt index 8ec8b6424..c71bd1a95 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceDatabaseRepositoryTest.kt @@ -13,7 +13,6 @@ import strikt.assertions.hasSize import java.math.BigDecimal class RepositoryPerformanceDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch from any branch, not just the main one`() { val repositoryPerformanceRepository: RepositoryPerformanceRepository by inject() @@ -27,14 +26,15 @@ class RepositoryPerformanceDatabaseRepositoryTest : DatabaseRepositoryTestCase() testRunDBGenerator.addResultsMetadata(testRunDB, false) testRunDBGenerator.addGitMetadata(testRunDB, repoName, false, null, null, null, null) - val savedPerfResult1 = PerformanceResult( - name = "perf1", - requestsPerSecond = BigDecimal("90.00"), - requestCount = 6000, - average = BigDecimal("20.67"), - maximum = BigDecimal("42.88"), - p95 = BigDecimal("30.48") - ) + val savedPerfResult1 = + PerformanceResult( + name = "perf1", + requestsPerSecond = BigDecimal("90.00"), + requestCount = 6000, + average = BigDecimal("20.67"), + maximum = BigDecimal("42.88"), + p95 = BigDecimal("30.48"), + ) val performanceResultsRepository: PerformanceResultsRepository by inject() runBlocking { performanceResultsRepository.savePerformanceResults(testRunDB.id, publicId, savedPerfResult1) } diff --git a/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceTimelineApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceTimelineApplicationTest.kt index 2dd85f0c0..20290770b 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceTimelineApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/performance/RepositoryPerformanceTimelineApplicationTest.kt @@ -21,7 +21,6 @@ import java.math.BigDecimal import kotlin.test.assertNotNull class RepositoryPerformanceTimelineApplicationTest : ApplicationTestCase() { - @Test fun `should fetch performance timeline for repository without project name`() { val orgName = RandomStringUtils.randomAlphabetic(12) @@ -33,45 +32,66 @@ class RepositoryPerformanceTimelineApplicationTest : ApplicationTestCase() { val testName = "perf-test" - val firstPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("80.000"), - requestCount = 4000, - average = BigDecimal("25.664"), - p95 = BigDecimal("40.783"), - maximum = BigDecimal("45.991") - ) - - val secondPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("90.000"), - requestCount = 6000, - average = BigDecimal("20.670"), - p95 = BigDecimal("30.483"), - maximum = BigDecimal("42.889") - ) - - val thirdPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("100.000"), - requestCount = 7000, - average = BigDecimal("22.672"), - p95 = BigDecimal("35.482"), - maximum = BigDecimal("44.881") - ) + val firstPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("80.000"), + requestCount = 4000, + average = BigDecimal("25.664"), + p95 = BigDecimal("40.783"), + maximum = BigDecimal("45.991"), + ) + + val secondPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("90.000"), + requestCount = 6000, + average = BigDecimal("20.670"), + p95 = BigDecimal("30.483"), + maximum = BigDecimal("42.889"), + ) + + val thirdPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("100.000"), + requestCount = 7000, + average = BigDecimal("22.672"), + p95 = BigDecimal("35.482"), + maximum = BigDecimal("44.881"), + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/performance/timeline") { val performanceResultsRepository: PerformanceResultsRepository = application.get() val firstTestRun = testRunDBGenerator.createEmptyTestRunInRepo(firstRunPublicId, repoName, true, null) - runBlocking { performanceResultsRepository.savePerformanceResults(firstTestRun.id, firstRunPublicId, firstPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + firstTestRun.id, + firstRunPublicId, + firstPerfResultToSave, + ) + } val secondTestRun = testRunDBGenerator.createEmptyTestRunInRepo(secondRunPublicId, repoName, true, null) - runBlocking { performanceResultsRepository.savePerformanceResults(secondTestRun.id, secondRunPublicId, secondPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + secondTestRun.id, + secondRunPublicId, + secondPerfResultToSave, + ) + } val thirdTestRun = testRunDBGenerator.createEmptyTestRunInRepo(thirdRunPublicId, repoName, true, null) - runBlocking { performanceResultsRepository.savePerformanceResults(thirdTestRun.id, thirdRunPublicId, thirdPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + thirdTestRun.id, + thirdRunPublicId, + thirdPerfResultToSave, + ) + } }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -128,45 +148,66 @@ class RepositoryPerformanceTimelineApplicationTest : ApplicationTestCase() { val testName = "perf-test" - val firstPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("80.000"), - requestCount = 4000, - average = BigDecimal("25.664"), - p95 = BigDecimal("40.783"), - maximum = BigDecimal("45.991") - ) - - val secondPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("90.000"), - requestCount = 6000, - average = BigDecimal("20.670"), - p95 = BigDecimal("30.483"), - maximum = BigDecimal("42.889") - ) - - val thirdPerfResultToSave = PerformanceResult( - name = testName, - requestsPerSecond = BigDecimal("100.000"), - requestCount = 7000, - average = BigDecimal("22.672"), - p95 = BigDecimal("35.482"), - maximum = BigDecimal("44.881") - ) + val firstPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("80.000"), + requestCount = 4000, + average = BigDecimal("25.664"), + p95 = BigDecimal("40.783"), + maximum = BigDecimal("45.991"), + ) + + val secondPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("90.000"), + requestCount = 6000, + average = BigDecimal("20.670"), + p95 = BigDecimal("30.483"), + maximum = BigDecimal("42.889"), + ) + + val thirdPerfResultToSave = + PerformanceResult( + name = testName, + requestsPerSecond = BigDecimal("100.000"), + requestCount = 7000, + average = BigDecimal("22.672"), + p95 = BigDecimal("35.482"), + maximum = BigDecimal("44.881"), + ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/performance/timeline") { val performanceResultsRepository: PerformanceResultsRepository = application.get() val firstTestRun = testRunDBGenerator.createEmptyTestRunInRepo(firstRunPublicId, repoName, true, projectName) - runBlocking { performanceResultsRepository.savePerformanceResults(firstTestRun.id, firstRunPublicId, firstPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + firstTestRun.id, + firstRunPublicId, + firstPerfResultToSave, + ) + } val secondTestRun = testRunDBGenerator.createEmptyTestRunInRepo(secondRunPublicId, repoName, true, projectName) - runBlocking { performanceResultsRepository.savePerformanceResults(secondTestRun.id, secondRunPublicId, secondPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + secondTestRun.id, + secondRunPublicId, + secondPerfResultToSave, + ) + } val thirdTestRun = testRunDBGenerator.createEmptyTestRunInRepo(thirdRunPublicId, repoName, true, projectName) - runBlocking { performanceResultsRepository.savePerformanceResults(thirdTestRun.id, thirdRunPublicId, thirdPerfResultToSave) } + runBlocking { + performanceResultsRepository.savePerformanceResults( + thirdTestRun.id, + thirdRunPublicId, + thirdPerfResultToSave, + ) + } }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/repository/testrun/FlakyTestCalculatorTest.kt b/server/server-app/src/test/kotlin/projektor/repository/testrun/FlakyTestCalculatorTest.kt index 04838ca14..b99b6922e 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/testrun/FlakyTestCalculatorTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/testrun/FlakyTestCalculatorTest.kt @@ -15,33 +15,37 @@ class FlakyTestCalculatorTest { val packageName = "dev.projektor" val className = "MyFlakyTests" val testCaseName = "shouldSometimesPass" - val oldestTestCase = createTestCase( - packageName, - className, - testCaseName, - "oldest-public-id", - LocalDateTime.now().minusDays(2) - ) - val middleTestCase = createTestCase( - packageName, - className, - testCaseName, - "middle-public-id", - LocalDateTime.now().minusDays(1) - ) - val newestTestCase = createTestCase( - packageName, - className, - testCaseName, - "newest-public-id", - LocalDateTime.now() - ) - - val flakyTests = FlakyTestCalculator().calculateFlakyTests( - listOf(oldestTestCase, middleTestCase, newestTestCase), - 3, - 6 - ) + val oldestTestCase = + createTestCase( + packageName, + className, + testCaseName, + "oldest-public-id", + LocalDateTime.now().minusDays(2), + ) + val middleTestCase = + createTestCase( + packageName, + className, + testCaseName, + "middle-public-id", + LocalDateTime.now().minusDays(1), + ) + val newestTestCase = + createTestCase( + packageName, + className, + testCaseName, + "newest-public-id", + LocalDateTime.now(), + ) + + val flakyTests = + FlakyTestCalculator().calculateFlakyTests( + listOf(oldestTestCase, middleTestCase, newestTestCase), + 3, + 6, + ) expectThat(flakyTests).hasSize(1) @@ -60,31 +64,34 @@ class FlakyTestCalculatorTest { val packageName = "dev.projektor" val className = "MyFlakyTests" - val notFlakyEnoughTestCases = (1..2).map { idx -> - createTestCase( - packageName, - className, - "notFlakyEnough", - "public-id-$idx", - LocalDateTime.now() - ) - } + val notFlakyEnoughTestCases = + (1..2).map { idx -> + createTestCase( + packageName, + className, + "notFlakyEnough", + "public-id-$idx", + LocalDateTime.now(), + ) + } - val flakyTestCases = (1..3).map { idx -> - createTestCase( - packageName, - className, - "soFlaky", - "public-id-$idx", - LocalDateTime.now() - ) - } + val flakyTestCases = + (1..3).map { idx -> + createTestCase( + packageName, + className, + "soFlaky", + "public-id-$idx", + LocalDateTime.now(), + ) + } - val flakyTests = FlakyTestCalculator().calculateFlakyTests( - notFlakyEnoughTestCases + flakyTestCases, - 3, - 3 - ) + val flakyTests = + FlakyTestCalculator().calculateFlakyTests( + notFlakyEnoughTestCases + flakyTestCases, + 3, + 3, + ) expectThat(flakyTests).hasSize(1) @@ -99,31 +106,34 @@ class FlakyTestCalculatorTest { val packageName = "dev.projektor" val className = "MyFlakyTests" - val flakyTestCases1 = (1..4).map { idx -> - createTestCase( - packageName, - className, - "flaky-1", - "public-id-$idx", - LocalDateTime.now().plusDays(idx.toLong()) - ) - } + val flakyTestCases1 = + (1..4).map { idx -> + createTestCase( + packageName, + className, + "flaky-1", + "public-id-$idx", + LocalDateTime.now().plusDays(idx.toLong()), + ) + } - val flakyTestCases2 = (1..3).map { idx -> - createTestCase( - packageName, - className, - "soFlaky", - "public-id-$idx", - LocalDateTime.now().plusDays(idx.toLong()) - ) - } + val flakyTestCases2 = + (1..3).map { idx -> + createTestCase( + packageName, + className, + "soFlaky", + "public-id-$idx", + LocalDateTime.now().plusDays(idx.toLong()), + ) + } - val flakyTests = FlakyTestCalculator().calculateFlakyTests( - flakyTestCases1 + flakyTestCases2, - 3, - 6 - ) + val flakyTests = + FlakyTestCalculator().calculateFlakyTests( + flakyTestCases1 + flakyTestCases2, + 3, + 6, + ) expectThat(flakyTests) { any { @@ -137,7 +147,13 @@ class FlakyTestCalculatorTest { } } - private fun createTestCase(packageName: String, className: String, testCaseName: String, publicId: String, createdTimeStamp: LocalDateTime) = TestCase( + private fun createTestCase( + packageName: String, + className: String, + testCaseName: String, + publicId: String, + createdTimeStamp: LocalDateTime, + ) = TestCase( idx = 1, testSuiteIdx = 1, name = testCaseName, @@ -154,6 +170,6 @@ class FlakyTestCalculatorTest { hasSystemErrTestSuite = false, publicId = publicId, createdTimestamp = createdTimeStamp, - failure = null + failure = null, ) } diff --git a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryFlakyTestApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryFlakyTestApplicationTest.kt index 028563072..6ed3c765c 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryFlakyTestApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryFlakyTestApplicationTest.kt @@ -18,7 +18,6 @@ import strikt.assertions.isEqualTo import kotlin.test.assertNotNull class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { - @Test fun `when flaky tests without a project name should return them`() { val orgName = RandomStringUtils.randomAlphabetic(12) @@ -27,20 +26,21 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky") { @@ -68,30 +68,32 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val projectName = null val failingPublicIds = (1..3).map { randomPublicId() } - val failingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val failingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky?max_runs=10&threshold=3") { @@ -119,30 +121,32 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val projectName = null val failingPublicIds = (1..3).map { randomPublicId() } - val failingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val failingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) val passingPublicIds = (1..8).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky?max_runs=10&threshold=3") { @@ -166,14 +170,15 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing"), - listOf(), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky") { @@ -194,20 +199,21 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing2"), - listOf("failing2"), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing2"), + listOf("failing2"), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/tests/flaky") { @@ -235,46 +241,49 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val projectName = null val failingMainlinePublicIds = (1..3).map { randomPublicId() } - val failingMainlineTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingMainlineTestSuite1", - listOf("passing1"), - listOf("failingMainline1"), - listOf() - ), - TestSuiteData( - "projektor.failingMainlineTestSuite2", - listOf("passing2"), - listOf("failingMainline2"), - listOf() + val failingMainlineTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingMainlineTestSuite1", + listOf("passing1"), + listOf("failingMainline1"), + listOf(), + ), + TestSuiteData( + "projektor.failingMainlineTestSuite2", + listOf("passing2"), + listOf("failingMainline2"), + listOf(), + ), ) - ) val failingBranchPublicIds = (1..3).map { randomPublicId() } - val failingBranchTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingBranchTestSuite1", - listOf("passing1"), - listOf("failingBranch1"), - listOf() - ), - TestSuiteData( - "projektor.failingBranchTestSuite2", - listOf("passing2"), - listOf("failingBranch2"), - listOf() + val failingBranchTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingBranchTestSuite1", + listOf("passing1"), + listOf("failingBranch1"), + listOf(), + ), + TestSuiteData( + "projektor.failingBranchTestSuite2", + listOf("passing2"), + listOf("failingBranch2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky?max_runs=20&threshold=3&branch_type=MAINLINE") { @@ -282,7 +291,14 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { testRunDBGenerator.createTestRunInRepo(publicId, failingMainlineTestSuiteDataList, repoName, true, projectName, "main") } failingBranchPublicIds.forEach { publicId -> - testRunDBGenerator.createTestRunInRepo(publicId, failingBranchTestSuiteDataList, repoName, true, projectName, "my-branch") + testRunDBGenerator.createTestRunInRepo( + publicId, + failingBranchTestSuiteDataList, + repoName, + true, + projectName, + "my-branch", + ) } passingPublicIds.forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, passingTestSuiteDataList, repoName, true, projectName) @@ -300,11 +316,11 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { expectThat(flakyTestCaseNames) .contains( "projektor.failingMainline1ClassName.failingMainline1", - "projektor.failingMainline2ClassName.failingMainline2" + "projektor.failingMainline2ClassName.failingMainline2", ) .not().contains( "projektor.failingBranch1ClassName.failingBranch1", - "projektor.failingBranch2ClassName.failingBranch2" + "projektor.failingBranch2ClassName.failingBranch2", ) } } @@ -317,46 +333,49 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val projectName = null val failingMainlinePublicIds = (1..3).map { randomPublicId() } - val failingMainlineTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingMainlineTestSuite1", - listOf("passing1"), - listOf("failingMainline1"), - listOf() - ), - TestSuiteData( - "projektor.failingMainlineTestSuite2", - listOf("passing2"), - listOf("failingMainline2"), - listOf() + val failingMainlineTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingMainlineTestSuite1", + listOf("passing1"), + listOf("failingMainline1"), + listOf(), + ), + TestSuiteData( + "projektor.failingMainlineTestSuite2", + listOf("passing2"), + listOf("failingMainline2"), + listOf(), + ), ) - ) val failingBranchPublicIds = (1..3).map { randomPublicId() } - val failingBranchTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingBranchTestSuite1", - listOf("passing1"), - listOf("failingBranch1"), - listOf() - ), - TestSuiteData( - "projektor.failingBranchTestSuite2", - listOf("passing2"), - listOf("failingBranch2"), - listOf() + val failingBranchTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingBranchTestSuite1", + listOf("passing1"), + listOf("failingBranch1"), + listOf(), + ), + TestSuiteData( + "projektor.failingBranchTestSuite2", + listOf("passing2"), + listOf("failingBranch2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/tests/flaky?max_runs=20&threshold=3&branch_type=ALL") { @@ -364,7 +383,14 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { testRunDBGenerator.createTestRunInRepo(publicId, failingMainlineTestSuiteDataList, repoName, true, projectName, "main") } failingBranchPublicIds.forEach { publicId -> - testRunDBGenerator.createTestRunInRepo(publicId, failingBranchTestSuiteDataList, repoName, true, projectName, "my-branch") + testRunDBGenerator.createTestRunInRepo( + publicId, + failingBranchTestSuiteDataList, + repoName, + true, + projectName, + "my-branch", + ) } passingPublicIds.forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, passingTestSuiteDataList, repoName, true, projectName) @@ -382,11 +408,11 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { expectThat(flakyTestCaseNames) .contains( "projektor.failingMainline1ClassName.failingMainline1", - "projektor.failingMainline2ClassName.failingMainline2" + "projektor.failingMainline2ClassName.failingMainline2", ) .contains( "projektor.failingBranch1ClassName.failingBranch1", - "projektor.failingBranch2ClassName.failingBranch2" + "projektor.failingBranch2ClassName.failingBranch2", ) } } @@ -400,14 +426,15 @@ class RepositoryFlakyTestApplicationTest : ApplicationTestCase() { val publicIds = (1..5).map { randomPublicId() } - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing"), - listOf(), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing"), + listOf(), + listOf(), + ), ) - ) withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/repo/$repoName/project/$projectName/tests/flaky") { diff --git a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryFailingCasesTest.kt b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryFailingCasesTest.kt index 479159f02..2a49de7ce 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryFailingCasesTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryFailingCasesTest.kt @@ -15,7 +15,6 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTestCase() { - @Test fun `should find failing test cases in repo and CI without project name`() { val repositoryTestRunDatabaseRepository = RepositoryTestRunDatabaseRepository(dslContext) @@ -31,26 +30,27 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe val ciInOtherRepoPublicId = randomPublicId() - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1", "failing2"), - listOf() - ), - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing2"), - listOf(), - listOf() - ), - TestSuiteData( - "projektor.failingTestSuite2", - listOf("passing3"), - listOf("failing3", "failing4"), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1", "failing2"), + listOf(), + ), + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing2"), + listOf(), + listOf(), + ), + TestSuiteData( + "projektor.failingTestSuite2", + listOf("passing3"), + listOf("failing3", "failing4"), + listOf(), + ), ) - ) val maxRuns = 4 @@ -59,14 +59,15 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe testRunDBGenerator.createTestRunInRepo(nonCIPublicId, testSuiteDataList, repoName, false, projectName) testRunDBGenerator.createTestRunInRepo(ciInOtherRepoPublicId, testSuiteDataList, "$orgName/another-project", true, projectName) - val failingTestCases = runBlocking { - repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( - repoName, - projectName, - maxRuns, - BranchType.ALL - ) - } + val failingTestCases = + runBlocking { + repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( + repoName, + projectName, + maxRuns, + BranchType.ALL, + ) + } val failingTestCaseNames = failingTestCases.map(TestCase::fullName) @@ -125,47 +126,50 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe val secondRunCITruePublicId = randomPublicId() val thirdRunCITruePublicId = randomPublicId() - val testSuiteDataList = listOf( - TestSuiteData( - "projektor.failingTestSuite1", - listOf("passing1"), - listOf("failing1"), - listOf() - ), - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing2"), - listOf(), - listOf() + val testSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingTestSuite1", + listOf("passing1"), + listOf("failing1"), + listOf(), + ), + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing2"), + listOf(), + listOf(), + ), ) - ) listOf(firstRunCITruePublicId, secondRunCITruePublicId, thirdRunCITruePublicId).forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, testSuiteDataList, repoName, true, projectName) } - val failingTestCasesMax1 = runBlocking { - repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( - repoName, - projectName, - 1, - BranchType.ALL - ) - } + val failingTestCasesMax1 = + runBlocking { + repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( + repoName, + projectName, + 1, + BranchType.ALL, + ) + } expectThat(failingTestCasesMax1) .hasSize(1) expectThat(failingTestCasesMax1[0].publicId).isEqualTo(thirdRunCITruePublicId.id) - val failingTestCasesMax2 = runBlocking { - repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( - repoName, - projectName, - 2, - BranchType.ALL - ) - } + val failingTestCasesMax2 = + runBlocking { + repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( + repoName, + projectName, + 2, + BranchType.ALL, + ) + } expectThat(failingTestCasesMax2) .hasSize(2) @@ -183,46 +187,49 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe val projectName = null val failingMainlinePublicIds = (1..3).map { randomPublicId() } - val failingMainlineTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingMainlineTestSuite1", - listOf("passing1"), - listOf("failingMainline1"), - listOf() - ), - TestSuiteData( - "projektor.failingMainlineTestSuite2", - listOf("passing2"), - listOf("failingMainline2"), - listOf() + val failingMainlineTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingMainlineTestSuite1", + listOf("passing1"), + listOf("failingMainline1"), + listOf(), + ), + TestSuiteData( + "projektor.failingMainlineTestSuite2", + listOf("passing2"), + listOf("failingMainline2"), + listOf(), + ), ) - ) val failingBranchPublicIds = (1..3).map { randomPublicId() } - val failingBranchTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingBranchTestSuite1", - listOf("passing1"), - listOf("failingBranch1"), - listOf() - ), - TestSuiteData( - "projektor.failingBranchTestSuite2", - listOf("passing2"), - listOf("failingBranch2"), - listOf() + val failingBranchTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingBranchTestSuite1", + listOf("passing1"), + listOf("failingBranch1"), + listOf(), + ), + TestSuiteData( + "projektor.failingBranchTestSuite2", + listOf("passing2"), + listOf("failingBranch2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) failingMainlinePublicIds.forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, failingMainlineTestSuiteDataList, repoName, true, projectName, "main") @@ -234,25 +241,26 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe testRunDBGenerator.createTestRunInRepo(publicId, passingTestSuiteDataList, repoName, true, projectName) } - val failingTestCases = runBlocking { - repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( - repoName, - projectName, - 100, - BranchType.MAINLINE - ) - } + val failingTestCases = + runBlocking { + repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( + repoName, + projectName, + 100, + BranchType.MAINLINE, + ) + } val failingTestCaseNames = failingTestCases.map(TestCase::fullName) expectThat(failingTestCaseNames) .contains( "projektor.failingMainline1ClassName.failingMainline1", - "projektor.failingMainline2ClassName.failingMainline2" + "projektor.failingMainline2ClassName.failingMainline2", ) .not().contains( "projektor.failingBranch1ClassName.failingBranch1", - "projektor.failingBranch2ClassName.failingBranch2" + "projektor.failingBranch2ClassName.failingBranch2", ) } @@ -265,46 +273,49 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe val projectName = null val failingMainlinePublicIds = (1..3).map { randomPublicId() } - val failingMainlineTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingMainlineTestSuite1", - listOf("passing1"), - listOf("failingMainline1"), - listOf() - ), - TestSuiteData( - "projektor.failingMainlineTestSuite2", - listOf("passing2"), - listOf("failingMainline2"), - listOf() + val failingMainlineTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingMainlineTestSuite1", + listOf("passing1"), + listOf("failingMainline1"), + listOf(), + ), + TestSuiteData( + "projektor.failingMainlineTestSuite2", + listOf("passing2"), + listOf("failingMainline2"), + listOf(), + ), ) - ) val failingBranchPublicIds = (1..3).map { randomPublicId() } - val failingBranchTestSuiteDataList = listOf( - TestSuiteData( - "projektor.failingBranchTestSuite1", - listOf("passing1"), - listOf("failingBranch1"), - listOf() - ), - TestSuiteData( - "projektor.failingBranchTestSuite2", - listOf("passing2"), - listOf("failingBranch2"), - listOf() + val failingBranchTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.failingBranchTestSuite1", + listOf("passing1"), + listOf("failingBranch1"), + listOf(), + ), + TestSuiteData( + "projektor.failingBranchTestSuite2", + listOf("passing2"), + listOf("failingBranch2"), + listOf(), + ), ) - ) val passingPublicIds = (1..7).map { randomPublicId() } - val passingTestSuiteDataList = listOf( - TestSuiteData( - "projektor.passingTestSuite", - listOf("passing1", "passing2"), - listOf(), - listOf() + val passingTestSuiteDataList = + listOf( + TestSuiteData( + "projektor.passingTestSuite", + listOf("passing1", "passing2"), + listOf(), + listOf(), + ), ) - ) failingMainlinePublicIds.forEach { publicId -> testRunDBGenerator.createTestRunInRepo(publicId, failingMainlineTestSuiteDataList, repoName, true, projectName, "main") @@ -316,25 +327,26 @@ class RepositoryTestRunDatabaseRepositoryFailingCasesTest : DatabaseRepositoryTe testRunDBGenerator.createTestRunInRepo(publicId, passingTestSuiteDataList, repoName, true, projectName) } - val failingTestCases = runBlocking { - repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( - repoName, - projectName, - 100, - BranchType.ALL - ) - } + val failingTestCases = + runBlocking { + repositoryTestRunDatabaseRepository.fetchRepositoryFailingTestCases( + repoName, + projectName, + 100, + BranchType.ALL, + ) + } val failingTestCaseNames = failingTestCases.map(TestCase::fullName) expectThat(failingTestCaseNames) .contains( "projektor.failingMainline1ClassName.failingMainline1", - "projektor.failingMainline2ClassName.failingMainline2" + "projektor.failingMainline2ClassName.failingMainline2", ) .contains( "projektor.failingBranch1ClassName.failingBranch1", - "projektor.failingBranch2ClassName.failingBranch2" + "projektor.failingBranch2ClassName.failingBranch2", ) } } diff --git a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryRecentRunsTest.kt b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryRecentRunsTest.kt index 20259510c..46541540f 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryRecentRunsTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryRecentRunsTest.kt @@ -10,7 +10,6 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class RepositoryTestRunDatabaseRepositoryRecentRunsTest : DatabaseRepositoryTestCase() { - @Test fun `should find recent test run public IDs`() { val repositoryTestRunDatabaseRepository = RepositoryTestRunDatabaseRepository(dslContext) diff --git a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryTimelineTest.kt b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryTimelineTest.kt index 78ecf796d..9e6f58220 100644 --- a/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryTimelineTest.kt +++ b/server/server-app/src/test/kotlin/projektor/repository/testrun/RepositoryTestRunDatabaseRepositoryTimelineTest.kt @@ -13,7 +13,6 @@ import java.math.BigDecimal import kotlin.test.assertNotNull class RepositoryTestRunDatabaseRepositoryTimelineTest : DatabaseRepositoryTestCase() { - @Test fun `should find entries without project name for CI builds`() { val repositoryTestRunDatabaseRepository = RepositoryTestRunDatabaseRepository(dslContext) diff --git a/server/server-app/src/test/kotlin/projektor/schedule/SchedulerTest.kt b/server/server-app/src/test/kotlin/projektor/schedule/SchedulerTest.kt index d0d4c00eb..47252d120 100644 --- a/server/server-app/src/test/kotlin/projektor/schedule/SchedulerTest.kt +++ b/server/server-app/src/test/kotlin/projektor/schedule/SchedulerTest.kt @@ -13,24 +13,25 @@ import kotlin.time.ExperimentalTime import kotlin.time.measureTime @ExperimentalTime - class SchedulerTest : DatabaseRepositoryTestCase() { @Test fun `should run scheduled job`() { var schedulerCalled = false - val scheduledJob = Runnable { - schedulerCalled = true - } + val scheduledJob = + Runnable { + schedulerCalled = true + } val schedulerLock = SchedulerLock(dataSource) val scheduler = Scheduler(schedulerLock) - val scheduleDuration = measureTime { - scheduler.scheduleJob(ScheduledJob("my_job", scheduledJob, ScheduleDelay(4, TimeUnit.SECONDS))) + val scheduleDuration = + measureTime { + scheduler.scheduleJob(ScheduledJob("my_job", scheduledJob, ScheduleDelay(4, TimeUnit.SECONDS))) - await until { schedulerCalled } - } + await until { schedulerCalled } + } expectThat(scheduleDuration.inWholeSeconds).isGreaterThanOrEqualTo(4) diff --git a/server/server-app/src/test/kotlin/projektor/telemetry/OpenTelemetryApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/telemetry/OpenTelemetryApplicationTest.kt index 8158e734a..3c6aa6d80 100644 --- a/server/server-app/src/test/kotlin/projektor/telemetry/OpenTelemetryApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/telemetry/OpenTelemetryApplicationTest.kt @@ -14,7 +14,6 @@ import strikt.assertions.hasSize import strikt.assertions.isEqualTo class OpenTelemetryApplicationTest : ApplicationTestCase() { - @Test fun `should add custom spans when fetching test run`() { val publicId = randomPublicId() @@ -28,9 +27,9 @@ class OpenTelemetryApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) diff --git a/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesApplicationTest.kt index 1d59a0fdc..443d2d3ff 100644 --- a/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesApplicationTest.kt @@ -33,15 +33,15 @@ class GetFailedTestCasesApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), listOf("testSuite2FailedTestCase1"), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -56,7 +56,7 @@ class GetFailedTestCasesApplicationTest : ApplicationTestCase() { .contains( "testSuite1FailedTestCase1", "testSuite1FailedTestCase2", - "testSuite2FailedTestCase1" + "testSuite2FailedTestCase1", ) expectThat(failedTestCases) diff --git a/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesAttachmentsApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesAttachmentsApplicationTest.kt index eb215e8e7..08877e5c7 100644 --- a/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesAttachmentsApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testcase/GetFailedTestCasesAttachmentsApplicationTest.kt @@ -19,7 +19,6 @@ import strikt.assertions.isNotNull import kotlin.test.assertNotNull class GetFailedTestCasesAttachmentsApplicationTest : ApplicationTestCase() { - @Test fun `should include screenshot attachment when test case has one`() { val publicId = randomPublicId() @@ -35,9 +34,9 @@ class GetFailedTestCasesAttachmentsApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), listOf("testSuite1 FailedTestCase 1", "testSuite1 FailedTestCase 2"), - listOf() + listOf(), ), - ) + ), ) testRunDBGenerator.addAttachment(publicId, "object-1", "testSuite1 FailedTestCase 1.png") @@ -92,9 +91,9 @@ class GetFailedTestCasesAttachmentsApplicationTest : ApplicationTestCase() { listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), listOf("testSuite1 FailedTestCase 1", "testSuite1 FailedTestCase 2"), listOf(), - "testSuite1.spec.js" + "testSuite1.spec.js", ), - ) + ), ) testRunDBGenerator.addAttachment(publicId, "screenshot-1", "testSuite1 FailedTestCase 1.png") diff --git a/server/server-app/src/test/kotlin/projektor/testcase/GetSlowTestCasesApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testcase/GetSlowTestCasesApplicationTest.kt index 1ec4f92ec..70b28c17c 100644 --- a/server/server-app/src/test/kotlin/projektor/testcase/GetSlowTestCasesApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testcase/GetSlowTestCasesApplicationTest.kt @@ -56,7 +56,7 @@ class GetSlowTestCasesApplicationTest : ApplicationTestCase() { BigDecimal("19.000"), BigDecimal("18.000"), BigDecimal("17.000"), - BigDecimal("16.000") + BigDecimal("16.000"), ) } } diff --git a/server/server-app/src/test/kotlin/projektor/testcase/GetTestCaseApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testcase/GetTestCaseApplicationTest.kt index 21065ae8b..ecd27f00a 100644 --- a/server/server-app/src/test/kotlin/projektor/testcase/GetTestCaseApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testcase/GetTestCaseApplicationTest.kt @@ -33,15 +33,15 @@ class GetTestCaseApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1"), listOf("testSuite1TestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2TestCase1", "testSuite2TestCase2", "testSuite2TestCase3"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { val responseTestCase = objectMapper.readValue(response.content, TestCase::class.java) diff --git a/server/server-app/src/test/kotlin/projektor/testcase/repository/TestCaseDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/testcase/repository/TestCaseDatabaseRepositoryTest.kt index 8c6c00dff..0ed5b6615 100644 --- a/server/server-app/src/test/kotlin/projektor/testcase/repository/TestCaseDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testcase/repository/TestCaseDatabaseRepositoryTest.kt @@ -33,15 +33,15 @@ class TestCaseDatabaseRepositoryTest : DatabaseRepositoryTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), listOf("testSuite2FailedTestCase1"), - listOf() - ) - ) + listOf(), + ), + ), ) val testCaseDatabaseRepository = TestCaseDatabaseRepository(dslContext) @@ -86,7 +86,7 @@ class TestCaseDatabaseRepositoryTest : DatabaseRepositoryTestCase() { BigDecimal("24.000"), BigDecimal("23.000"), BigDecimal("22.000"), - BigDecimal("21.000") + BigDecimal("21.000"), ) } diff --git a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunApplicationTest.kt index bb99d8291..c3e393431 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunApplicationTest.kt @@ -17,7 +17,6 @@ import strikt.assertions.isNotNull import kotlin.test.assertNotNull class GetTestRunApplicationTest : ApplicationTestCase() { - @Test fun `should fetch test run from database`() { val publicId = randomPublicId() @@ -31,15 +30,15 @@ class GetTestRunApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2TestCase1", "testSuite2TestCase2", "testSuite2TestCase3"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -75,9 +74,9 @@ class GetTestRunApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1", "testSuite1TestCase2"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { expectThat(response.status()).isEqualTo(HttpStatusCode.OK) @@ -100,23 +99,24 @@ class GetTestRunApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId") { - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "projektor.TestSuite1", - listOf("testCase1"), - listOf(), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "projektor.TestSuite1", + listOf("testCase1"), + listOf(), + listOf(), + ), + TestSuiteData( + "projektor.TestSuite2", + listOf("testCase2"), + listOf(), + listOf(), + ), ), - TestSuiteData( - "projektor.TestSuite2", - listOf("testCase2"), - listOf(), - listOf() - ) ) - ) val testSuiteGroup1 = TestSuiteGroup() testSuiteGroup1.testRunId = testRun.id diff --git a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunCompressionApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunCompressionApplicationTest.kt index abfbc588b..0686d9d5c 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunCompressionApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunCompressionApplicationTest.kt @@ -33,9 +33,9 @@ class GetTestRunCompressionApplicationTest : ApplicationTestCase() { "reallyLongNameForTestSuite$it", listOf("testSuite${it}TestCase1", "testSuite${it}TestCase2"), listOf(), - listOf() + listOf(), ) - } + }, ) addHeader(HttpHeaders.AcceptEncoding, "gzip") diff --git a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunSummaryApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunSummaryApplicationTest.kt index 514ee8153..2087b36aa 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunSummaryApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/GetTestRunSummaryApplicationTest.kt @@ -23,17 +23,18 @@ class GetTestRunSummaryApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/summary") { - val testRun = TestRunDB() - .setPublicId(publicId.id) - .setTotalTestCount(6) - .setTotalPassingCount(4) - .setTotalFailureCount(2) - .setTotalSkippedCount(1) - .setCumulativeDuration(BigDecimal("30.000")) - .setAverageDuration(BigDecimal("5.000")) - .setSlowestTestCaseDuration(BigDecimal("10.000")) - .setPassed(false) - .setCreatedTimestamp(LocalDateTime.now()) + val testRun = + TestRunDB() + .setPublicId(publicId.id) + .setTotalTestCount(6) + .setTotalPassingCount(4) + .setTotalFailureCount(2) + .setTotalSkippedCount(1) + .setCumulativeDuration(BigDecimal("30.000")) + .setAverageDuration(BigDecimal("5.000")) + .setSlowestTestCaseDuration(BigDecimal("10.000")) + .setPassed(false) + .setCreatedTimestamp(LocalDateTime.now()) testRunDao.insert(testRun) }.apply { diff --git a/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesApplicationTest.kt index 357605905..5500fbf31 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesApplicationTest.kt @@ -24,7 +24,7 @@ class TestRunSystemAttributesApplicationTest : ApplicationTestCase() { handleRequest(HttpMethod.Get, "/run/$publicId/attributes") { testRunDBGenerator.createTestRun( publicId, - listOf() + listOf(), ) testRunSystemAttributesDao.insert(TestRunSystemAttributes(publicId.id, true)) @@ -57,7 +57,7 @@ class TestRunSystemAttributesApplicationTest : ApplicationTestCase() { handleRequest(HttpMethod.Post, "/run/$publicId/attributes/pin") { testRunDBGenerator.createTestRun( publicId, - listOf() + listOf(), ) testRunSystemAttributesDao.insert(TestRunSystemAttributes(publicId.id, false)) @@ -89,7 +89,7 @@ class TestRunSystemAttributesApplicationTest : ApplicationTestCase() { handleRequest(HttpMethod.Post, "/run/$publicId/attributes/unpin") { testRunDBGenerator.createTestRun( publicId, - listOf() + listOf(), ) testRunSystemAttributesDao.insert(TestRunSystemAttributes(publicId.id, true)) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepositoryTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepositoryTest.kt index 9b5b5afe2..615f3c55a 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepositoryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/attributes/TestRunSystemAttributesDatabaseRepositoryTest.kt @@ -12,7 +12,6 @@ import strikt.assertions.isNull import strikt.assertions.isTrue class TestRunSystemAttributesDatabaseRepositoryTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch pinned when it is true`() { val repository = TestRunSystemAttributesDatabaseRepository(dslContext) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryAppendTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryAppendTest.kt index e233c8d85..5cacacdb9 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryAppendTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryAppendTest.kt @@ -19,7 +19,6 @@ import strikt.assertions.isNotNull import strikt.assertions.map class TestRunDatabaseRepositoryAppendTest : DatabaseRepositoryTestCase() { - @Test fun `should append new test group of test suites`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) @@ -29,23 +28,24 @@ class TestRunDatabaseRepositoryAppendTest : DatabaseRepositoryTestCase() { val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() - ) ) - ) testRunDBGenerator.addTestSuiteGroupToTestRun("SomeGroup1", testRun, listOf("testSuite1")) testRunDBGenerator.addTestSuiteGroupToTestRun("SomeGroup2", testRun, listOf("testSuite2")) @@ -74,29 +74,30 @@ class TestRunDatabaseRepositoryAppendTest : DatabaseRepositoryTestCase() { val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() - ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), + TestSuiteData( + "testSuite3", + listOf("testSuite3PassedTestCase1", "testSuite3PassedTestCase2"), + listOf("testSuite3FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite3", - listOf("testSuite3PassedTestCase1", "testSuite3PassedTestCase2"), - listOf("testSuite3FailedTestCase1"), - listOf() - ) ) - ) testRunDBGenerator.addTestSuiteGroupToTestRun("Group1", testRun, listOf("testSuite1")) testRunDBGenerator.addTestSuiteGroupToTestRun("Group2", testRun, listOf("testSuite2", "testSuite3")) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryDeleteTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryDeleteTest.kt index d619cbac2..7b93eddf9 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryDeleteTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryDeleteTest.kt @@ -13,30 +13,30 @@ import strikt.assertions.isNull import java.time.LocalDate class TestRunDatabaseRepositoryDeleteTest : DatabaseRepositoryTestCase() { - @Test fun `should delete test run`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), - listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1", "testSuite1PassedTestCase2"), + listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), + listOf(), + ), + TestSuiteData( + "testSuite2", + listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), + listOf("testSuite2FailedTestCase1"), + listOf(), + ), ), - TestSuiteData( - "testSuite2", - listOf("testSuite2PassedTestCase1", "testSuite2PassedTestCase2"), - listOf("testSuite2FailedTestCase1"), - listOf() - ) ) - ) val testSuiteIds = testSuiteDao.fetchByTestRunId(testRun.id).map { it.id } val testCaseIds = testSuiteIds.flatMap { testCaseDao.fetchByTestSuiteId(it) }.map { it.id } @@ -100,7 +100,8 @@ class TestRunDatabaseRepositoryDeleteTest : DatabaseRepositoryTestCase() { val noAttachmentsPublicId = randomPublicId() testRunDBGenerator.createTestRun(noAttachmentsPublicId, LocalDate.of(2020, 2, 1), false) - val fetchedTestRuns = runBlocking { testRunDatabaseRepository.findTestRunsCreatedBeforeAndNotPinnedWithAttachments(LocalDate.of(2020, 2, 2)) } + val fetchedTestRuns = + runBlocking { testRunDatabaseRepository.findTestRunsCreatedBeforeAndNotPinnedWithAttachments(LocalDate.of(2020, 2, 2)) } expectThat(fetchedTestRuns) .contains(shouldFetch1PublicId, shouldFetch2PublicId) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchRunTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchRunTest.kt index d1f4b7569..f74c4719e 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchRunTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchRunTest.kt @@ -19,7 +19,6 @@ import java.time.LocalDateTime import kotlin.test.assertNotNull class TestRunDatabaseRepositoryFetchRunTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch all fields in test run and test suite`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) @@ -134,15 +133,15 @@ class TestRunDatabaseRepositoryFetchRunTest : DatabaseRepositoryTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1", "testSuitePassed1TestCase2"), listOf("testSuite1FailedTestCase1"), - listOf("testSuite1SkippedTestCase1", "testSuite1SkippedTestCase2") + listOf("testSuite1SkippedTestCase1", "testSuite1SkippedTestCase2"), ), TestSuiteData( "testSuite2", listOf("testSuite2PassedTestCase1"), listOf("testSuite2FailedTestCase1", "testSuite2FailedTestCase2", "testSuite2FailedTestCase3"), - listOf() - ) - ) + listOf(), + ), + ), ) val testRun = runBlocking { testRunDatabaseRepository.fetchTestRun(publicId) } diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchSummaryTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchSummaryTest.kt index a1345e8f4..247eee15b 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchSummaryTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositoryFetchSummaryTest.kt @@ -13,7 +13,6 @@ import java.math.BigDecimal import java.time.LocalDateTime class TestRunDatabaseRepositoryFetchSummaryTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch all fields in the test run summary`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveGroupedResultsTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveGroupedResultsTest.kt index 5fdc489c3..ef96497d0 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveGroupedResultsTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveGroupedResultsTest.kt @@ -16,7 +16,6 @@ import projektor.parser.model.TestCase as ParsedTestCase import projektor.parser.model.TestSuite as ParsedTestSuite class TestRunDatabaseRepositorySaveGroupedResultsTest : DatabaseRepositoryTestCase() { - @Test fun `should save grouped results with two groups with two test suites each`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) @@ -26,22 +25,24 @@ class TestRunDatabaseRepositorySaveGroupedResultsTest : DatabaseRepositoryTestCa val testGroup1TestSuite1 = createTestSuite("testGroup1TestSuite1") val testGroup1TestSuite2 = createTestSuite("testGroup1TestSuite2") - val testGroup1 = GroupedTestSuites( - listOf(testGroup1TestSuite1, testGroup1TestSuite2), - "Group1", - "Label1", - "directory-1" - ) + val testGroup1 = + GroupedTestSuites( + listOf(testGroup1TestSuite1, testGroup1TestSuite2), + "Group1", + "Label1", + "directory-1", + ) val testGroup2TestSuite1 = createTestSuite("testGroup2TestSuite1") val testGroup2TestSuite2 = createTestSuite("testGroup2TestSuite2") - val testGroup2 = GroupedTestSuites( - listOf(testGroup2TestSuite1, testGroup2TestSuite2), - "Group2", - "Label2", - "directory-2" - ) + val testGroup2 = + GroupedTestSuites( + listOf(testGroup2TestSuite1, testGroup2TestSuite2), + "Group2", + "Label2", + "directory-2", + ) val groupedResults = GroupedResults(listOf(testGroup1, testGroup2), listOf(), null, null, null, null) @@ -86,12 +87,13 @@ class TestRunDatabaseRepositorySaveGroupedResultsTest : DatabaseRepositoryTestCa val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) val publicId = randomPublicId() - val testGroup = GroupedTestSuites( - listOf(), - "Group", - "Label", - "directory" - ) + val testGroup = + GroupedTestSuites( + listOf(), + "Group", + "Label", + "directory", + ) val groupedResults = GroupedResults(listOf(testGroup), listOf(), null, null, null, null) diff --git a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveResultsTest.kt b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveResultsTest.kt index 713a9b0d8..b51f1c9b9 100644 --- a/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveResultsTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testrun/repository/TestRunDatabaseRepositorySaveResultsTest.kt @@ -15,7 +15,6 @@ import projektor.parser.model.TestCase as ParsedTestCase import projektor.parser.model.TestSuite as ParsedTestSuite class TestRunDatabaseRepositorySaveResultsTest : DatabaseRepositoryTestCase() { - @Test fun `should save test run with two passing test cases`() { val testRunDatabaseRepository = TestRunDatabaseRepository(dslContext) diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteApplicationTest.kt index 9a3d67e34..97d2ade3c 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteApplicationTest.kt @@ -37,15 +37,15 @@ class GetTestSuiteApplicationTest : ApplicationTestCase() { "testSuite1", listOf("testSuite1TestCase1"), listOf("testSuite1TestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2TestCase1", "testSuite2TestCase2", "testSuite2TestCase3"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) }.apply { val responseContent = response.content @@ -82,23 +82,24 @@ class GetTestSuiteApplicationTest : ApplicationTestCase() { withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/suite/$testSuiteIdx") { - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "projektor.TestSuite1", - listOf("testCase1"), - listOf(), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "projektor.TestSuite1", + listOf("testCase1"), + listOf(), + listOf(), + ), + TestSuiteData( + "projektor.TestSuite2", + listOf("testCase2"), + listOf(), + listOf(), + ), ), - TestSuiteData( - "projektor.TestSuite2", - listOf("testCase2"), - listOf(), - listOf() - ) ) - ) val testSuiteGroup = TestSuiteGroupDB() testSuiteGroup.testRunId = testRun.id @@ -124,11 +125,12 @@ class GetTestSuiteApplicationTest : ApplicationTestCase() { @Test fun `should get test suite with file name`() { - val resultsBody = GroupedResultsXmlLoader().wrapResultsXmlsInGroup( - listOf( - ResultsXmlLoader().cypressWithFilePathAndRootSuiteNameSet() + val resultsBody = + GroupedResultsXmlLoader().wrapResultsXmlsInGroup( + listOf( + ResultsXmlLoader().cypressWithFilePathAndRootSuiteNameSet(), + ), ) - ) val testSuiteIdx = 1 diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemErrApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemErrApplicationTest.kt index 00f2650e2..75c38a8e7 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemErrApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemErrApplicationTest.kt @@ -19,10 +19,12 @@ class GetTestSuiteSystemErrApplicationTest : ApplicationTestCase() { fun shouldFetchTestSuiteSystemErrFromDatabase() { val publicId = randomPublicId() val testSuiteIdx = 1 - val systemErr = """Here is some system err + val systemErr = + """ + Here is some system err With multiple Lines - """.trimIndent() + """.trimIndent() withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/suite/$testSuiteIdx/systemErr") { diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemOutApplicationTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemOutApplicationTest.kt index 56070f6de..2fedd38a8 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemOutApplicationTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/GetTestSuiteSystemOutApplicationTest.kt @@ -19,10 +19,12 @@ class GetTestSuiteSystemOutApplicationTest : ApplicationTestCase() { fun shouldFetchTestSuiteSystemOutFromDatabase() { val publicId = randomPublicId() val testSuiteIdx = 1 - val systemOut = """Here is some system output + val systemOut = + """ + Here is some system output With multiple Lines - """.trimIndent() + """.trimIndent() withTestApplication(::createTestApplication) { handleRequest(HttpMethod.Get, "/run/$publicId/suite/$testSuiteIdx/systemOut") { diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryAppendTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryAppendTest.kt index 60eb33c09..edd12dae4 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryAppendTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryAppendTest.kt @@ -11,7 +11,6 @@ import strikt.assertions.isEqualTo import strikt.assertions.isNotNull class TestSuiteDatabaseRepositoryAppendTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch highest test suite index`() { val testSuiteDatabaseRepository = TestSuiteDatabaseRepository(dslContext) @@ -24,15 +23,15 @@ class TestSuiteDatabaseRepositoryAppendTest : DatabaseRepositoryTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1"), listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2TestCase1", "testSuite2TestCase2", "testSuite2TestCase3"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) val highestTestSuiteIdx = runBlocking { testSuiteDatabaseRepository.fetchHighestTestSuiteIndex(publicId) } diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchGroupedSuitesTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchGroupedSuitesTest.kt index 702cc3a77..c7929231f 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchGroupedSuitesTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchGroupedSuitesTest.kt @@ -12,29 +12,29 @@ import strikt.assertions.isNotNull import projektor.database.generated.tables.pojos.TestSuiteGroup as TestSuiteGroupDB class TestSuiteDatabaseRepositoryFetchGroupedSuitesTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch grouped test suites`() { val testSuiteDatabaseRepository = TestSuiteDatabaseRepository(dslContext) val publicId = randomPublicId() - val testRun = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "projektor.TestSuite1", - listOf("testCase1"), - listOf(), - listOf() + val testRun = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "projektor.TestSuite1", + listOf("testCase1"), + listOf(), + listOf(), + ), + TestSuiteData( + "projektor.TestSuite2", + listOf("testCase2"), + listOf(), + listOf(), + ), ), - TestSuiteData( - "projektor.TestSuite2", - listOf("testCase2"), - listOf(), - listOf() - ) ) - ) val testSuiteGroup = TestSuiteGroupDB() testSuiteGroup.testRunId = testRun.id diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchOutputTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchOutputTest.kt index b4ba29a28..dfdfc0c67 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchOutputTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchOutputTest.kt @@ -12,7 +12,6 @@ import strikt.assertions.isEqualTo import strikt.assertions.isNotNull class TestSuiteDatabaseRepositoryFetchOutputTest : DatabaseRepositoryTestCase() { - @Test fun `should fetch test suite system out`() { val testSuiteDatabaseRepository = TestSuiteDatabaseRepository(dslContext) @@ -35,9 +34,10 @@ class TestSuiteDatabaseRepositoryFetchOutputTest : DatabaseRepositoryTestCase() testSuiteDB.systemErr = "My system err" testSuiteDao.insert(testSuiteDB) - val systemOut = runBlocking { - testSuiteDatabaseRepository.fetchTestSuiteSystemOut(publicId, 1) - } + val systemOut = + runBlocking { + testSuiteDatabaseRepository.fetchTestSuiteSystemOut(publicId, 1) + } expectThat(systemOut) .get { value }.isNotNull().isEqualTo("My system out") @@ -65,9 +65,10 @@ class TestSuiteDatabaseRepositoryFetchOutputTest : DatabaseRepositoryTestCase() testSuiteDB.systemErr = "My system err" testSuiteDao.insert(testSuiteDB) - val systemErr = runBlocking { - testSuiteDatabaseRepository.fetchTestSuiteSystemErr(publicId, 1) - } + val systemErr = + runBlocking { + testSuiteDatabaseRepository.fetchTestSuiteSystemErr(publicId, 1) + } expectThat(systemErr) .get { value }.isNotNull().isEqualTo("My system err") diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuiteTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuiteTest.kt index fa064feab..0cb6b4bc0 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuiteTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuiteTest.kt @@ -16,7 +16,6 @@ import strikt.assertions.isNotNull import strikt.assertions.isNull class TestSuiteDatabaseRepositoryFetchSuiteTest : DatabaseRepositoryTestCase() { - @Test fun `when test suite failed should fetch test suite along with test cases and failures`() { val testSuiteDatabaseRepository = TestSuiteDatabaseRepository(dslContext) @@ -29,15 +28,15 @@ class TestSuiteDatabaseRepositoryFetchSuiteTest : DatabaseRepositoryTestCase() { "testSuite1", listOf("testSuite1PassedTestCase1"), listOf("testSuite1FailedTestCase1", "testSuite1FailedTestCase2"), - listOf() + listOf(), ), TestSuiteData( "testSuite2", listOf("testSuite2TestCase1", "testSuite2TestCase2", "testSuite2TestCase3"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) val testSuite = runBlocking { testSuiteDatabaseRepository.fetchTestSuite(publicId, 1) } @@ -96,17 +95,18 @@ class TestSuiteDatabaseRepositoryFetchSuiteTest : DatabaseRepositoryTestCase() { fun `should not fetch system out and err columns when fetching individual test suite`() { val publicId = randomPublicId() - val testRunDB = testRunDBGenerator.createTestRun( - publicId, - listOf( - TestSuiteData( - "testSuite1", - listOf("testSuite1PassedTestCase1"), - listOf(), - listOf() - ) + val testRunDB = + testRunDBGenerator.createTestRun( + publicId, + listOf( + TestSuiteData( + "testSuite1", + listOf("testSuite1PassedTestCase1"), + listOf(), + listOf(), + ), + ), ) - ) val testSuiteIdx = 1 @@ -116,10 +116,11 @@ class TestSuiteDatabaseRepositoryFetchSuiteTest : DatabaseRepositoryTestCase() { .where(Tables.TEST_SUITE.TEST_RUN_ID.eq(testRunDB.id).and(Tables.TEST_SUITE.IDX.eq(testSuiteIdx))) .execute() - val testSuites = TestSuiteDatabaseRepository.selectTestSuite(dslContext) - .where(Tables.TEST_RUN.PUBLIC_ID.eq(publicId.id).and(Tables.TEST_SUITE.IDX.eq(testSuiteIdx))) - .orderBy(Tables.TEST_SUITE.ID) - .fetchInto(TestSuite::class.java) + val testSuites = + TestSuiteDatabaseRepository.selectTestSuite(dslContext) + .where(Tables.TEST_RUN.PUBLIC_ID.eq(publicId.id).and(Tables.TEST_SUITE.IDX.eq(testSuiteIdx))) + .orderBy(Tables.TEST_SUITE.ID) + .fetchInto(TestSuite::class.java) expectThat(testSuites).hasSize(1) diff --git a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuitesTest.kt b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuitesTest.kt index 26883910e..f332f80e4 100644 --- a/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuitesTest.kt +++ b/server/server-app/src/test/kotlin/projektor/testsuite/repository/TestSuiteDatabaseRepositoryFetchSuitesTest.kt @@ -27,26 +27,27 @@ class TestSuiteDatabaseRepositoryFetchSuitesTest : DatabaseRepositoryTestCase() "projektor.TestSuite1", listOf("testCase1"), listOf(), - listOf() + listOf(), ), TestSuiteData( "projektor.TestSuite2", listOf("testCase1"), listOf(), - listOf() + listOf(), ), TestSuiteData( "something.else.testSuite2", listOf("testCase1"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) - val testSuites = runBlocking { - testSuiteDatabaseRepository.fetchTestSuites(publicId, TestSuiteSearchCriteria("projektor", false)) - } + val testSuites = + runBlocking { + testSuiteDatabaseRepository.fetchTestSuites(publicId, TestSuiteSearchCriteria("projektor", false)) + } expectThat(testSuites) .hasSize(2) @@ -72,26 +73,27 @@ class TestSuiteDatabaseRepositoryFetchSuitesTest : DatabaseRepositoryTestCase() "projektor.TestSuite1", listOf("testCase1"), listOf(), - listOf() + listOf(), ), TestSuiteData( "projektor.TestSuite2", listOf("testCase1"), listOf(), - listOf() + listOf(), ), TestSuiteData( "something.else.testSuite2", listOf("testCase1"), listOf(), - listOf() - ) - ) + listOf(), + ), + ), ) - val testSuites = runBlocking { - testSuiteDatabaseRepository.fetchTestSuites(publicId, TestSuiteSearchCriteria("should.find.nothing", false)) - } + val testSuites = + runBlocking { + testSuiteDatabaseRepository.fetchTestSuites(publicId, TestSuiteSearchCriteria("should.find.nothing", false)) + } expectThat(testSuites).isEmpty() } diff --git a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorAttachmentsApi.kt b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorAttachmentsApi.kt index e1def8616..8804ea978 100644 --- a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorAttachmentsApi.kt +++ b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorAttachmentsApi.kt @@ -8,8 +8,13 @@ import retrofit2.http.Path interface ProjektorAttachmentsApi { @GET("/run/{publicId}/attachments") - fun listAttachments(@Path("publicId") publicId: String): Call + fun listAttachments( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/attachments/{fileName}") - fun getAttachments(@Path("publicId") publicId: String, @Path("fileName") fileName: String): Call + fun getAttachments( + @Path("publicId") publicId: String, + @Path("fileName") fileName: String, + ): Call } diff --git a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorClientBuilder.kt b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorClientBuilder.kt index 06253cd84..703b9e3ec 100644 --- a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorClientBuilder.kt +++ b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorClientBuilder.kt @@ -10,13 +10,18 @@ import retrofit2.Retrofit import retrofit2.converter.jackson.JacksonConverterFactory object ProjektorClientBuilder { - private val objectMapper = ObjectMapper() - .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .registerKotlinModule() - .registerModule(JavaTimeModule()) + private val objectMapper = + ObjectMapper() + .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .registerKotlinModule() + .registerModule(JavaTimeModule()) - fun createApi(baseUrl: String, okHttpClient: OkHttpClient, apiClass: Class): T { + fun createApi( + baseUrl: String, + okHttpClient: OkHttpClient, + apiClass: Class, + ): T { return Retrofit.Builder() .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .baseUrl(baseUrl) diff --git a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunApi.kt b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunApi.kt index 397c33b5c..c8621dc22 100644 --- a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunApi.kt +++ b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunApi.kt @@ -15,38 +15,69 @@ import retrofit2.http.Path interface ProjektorTestRunApi { @GET("/run/{publicId}") - fun testRun(@Path("publicId") publicId: String): Call + fun testRun( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/suites") - fun testSuites(@Path("publicId") publicId: String): Call> + fun testSuites( + @Path("publicId") publicId: String, + ): Call> @GET("/run/{publicId}/suite/{testSuiteIdx}") - fun testSuite(@Path("publicId") publicId: String, @Path("testSuiteIdx") testSuiteIdx: Int): Call + fun testSuite( + @Path("publicId") publicId: String, + @Path("testSuiteIdx") testSuiteIdx: Int, + ): Call @GET("/run/{publicId}/suite/{testSuiteIdx}/systemOut") - fun testSuiteSystemOut(@Path("publicId") publicId: String, @Path("testSuiteIdx") testSuiteIdx: Int): Call + fun testSuiteSystemOut( + @Path("publicId") publicId: String, + @Path("testSuiteIdx") testSuiteIdx: Int, + ): Call @GET("/run/{publicId}/suite/{testSuiteIdx}/systemErr") - fun testSuiteSystemErr(@Path("publicId") publicId: String, @Path("testSuiteIdx") testSuiteIdx: Int): Call + fun testSuiteSystemErr( + @Path("publicId") publicId: String, + @Path("testSuiteIdx") testSuiteIdx: Int, + ): Call @GET("/run/{publicId}/suite/{testSuiteIdx}/case/{testCaseIdx}") - fun testCase(@Path("publicId") publicId: String, @Path("testSuiteIdx") testSuiteIdx: Int, @Path("testCaseIdx") testCaseIdx: Int): Call + fun testCase( + @Path("publicId") publicId: String, + @Path("testSuiteIdx") testSuiteIdx: Int, + @Path("testCaseIdx") testCaseIdx: Int, + ): Call @GET("/run/{publicId}/suite/{testSuiteIdx}/case/{testCaseIdx}/systemOut") - fun testCaseSystemOut(@Path("publicId") publicId: String, @Path("testSuiteIdx") testSuiteIdx: Int, @Path("testCaseIdx") testCaseIdx: Int): Call + fun testCaseSystemOut( + @Path("publicId") publicId: String, + @Path("testSuiteIdx") testSuiteIdx: Int, + @Path("testCaseIdx") testCaseIdx: Int, + ): Call @GET("/run/{publicId}/coverage") - fun coverage(@Path("publicId") publicId: String): Call + fun coverage( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/coverage/overall") - fun coverageOverallStats(@Path("publicId") publicId: String): Call + fun coverageOverallStats( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/coverage/exists") - fun coverageExists(@Path("publicId") publicId: String): Call + fun coverageExists( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/previous") - fun previousTestRun(@Path("publicId") publicId: String): Call + fun previousTestRun( + @Path("publicId") publicId: String, + ): Call @GET("/run/{publicId}/quality") - fun codeQualityReports(@Path("publicId") publicId: String): Call + fun codeQualityReports( + @Path("publicId") publicId: String, + ): Call } diff --git a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunMetadataApi.kt b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunMetadataApi.kt index 53fc0e6b1..495039459 100644 --- a/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunMetadataApi.kt +++ b/server/server-client/src/main/kotlin/projektor/server/client/ProjektorTestRunMetadataApi.kt @@ -7,5 +7,7 @@ import retrofit2.http.Path interface ProjektorTestRunMetadataApi { @GET("/run/{publicId}/metadata") - fun testRunMetadata(@Path("publicId") publicId: String): Call + fun testRunMetadata( + @Path("publicId") publicId: String, + ): Call } diff --git a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CloverXmlLoader.kt b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CloverXmlLoader.kt index b8c3f7723..6a8f134d1 100644 --- a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CloverXmlLoader.kt +++ b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CloverXmlLoader.kt @@ -2,12 +2,18 @@ package projektor.server.example.coverage class CloverXmlLoader : CoverageXmlLoader() { fun uiClover() = loadTextFromFile("ui-clover.xml") + fun uiClover2() = loadTextFromFile("ui-clover-2.xml") + fun uiCloverLarge() = loadTextFromFile("ui-clover-large.xml") + fun uiCloverManyMissedLines() = loadTextFromFile("ui-clover-many-missed-lines.xml") + fun noPackage() = loadTextFromFile("clover-no-package.xml") fun coverageFilesTable() = loadTextFromFile("clover-append/CoverageFilesTable-clover.xml") + fun coverageGraph() = loadTextFromFile("clover-append/CoverageGraph-clover.xml") + fun coverageTable() = loadTextFromFile("clover-append/CoverageTable-clover.xml") } diff --git a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoberturaXmlLoader.kt b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoberturaXmlLoader.kt index 829c7a90f..ba08c5e93 100644 --- a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoberturaXmlLoader.kt +++ b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoberturaXmlLoader.kt @@ -1,8 +1,8 @@ package projektor.server.example.coverage class CoberturaXmlLoader : CoverageXmlLoader() { - fun nodeScriptCobertura() = loadTextFromFile("cobertura/node-script-cobertura.xml") + fun uiCobertura() = loadTextFromFile("cobertura/ui-cobertura.xml") fun noBranchCobertura() = loadTextFromFile("cobertura/no-branch-cobertura.xml") diff --git a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageFileWrapper.kt b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageFileWrapper.kt index 415d6312e..f1e493ee5 100644 --- a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageFileWrapper.kt +++ b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageFileWrapper.kt @@ -6,11 +6,14 @@ import projektor.parser.coverage.payload.CoveragePayloadParser object CoverageFileWrapper { private val coveragePayloadParser = CoveragePayloadParser() - fun createCoverageFilePayload(payload: String, baseDirectoryPath: String?): String = + fun createCoverageFilePayload( + payload: String, + baseDirectoryPath: String?, + ): String = coveragePayloadParser.serializeCoverageFilePayload( CoverageFilePayload( reportContents = payload, - baseDirectoryPath = baseDirectoryPath - ) + baseDirectoryPath = baseDirectoryPath, + ), ) } diff --git a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageXmlLoader.kt b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageXmlLoader.kt index c223f83e4..d4fd54103 100644 --- a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageXmlLoader.kt +++ b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/CoverageXmlLoader.kt @@ -1,8 +1,9 @@ package projektor.server.example.coverage abstract class CoverageXmlLoader { - fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/JacocoXmlLoader.kt b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/JacocoXmlLoader.kt index bdade0d18..574a34b51 100644 --- a/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/JacocoXmlLoader.kt +++ b/server/test/coverage-fixtures/src/main/kotlin/projektor/server/example/coverage/JacocoXmlLoader.kt @@ -4,15 +4,21 @@ import java.math.BigDecimal class JacocoXmlLoader : CoverageXmlLoader() { fun jacocoXmlParser() = loadTextFromFile("jacoco-xml-parser-jacocoTestReport.xml") + fun jacocoXmlParserReduced() = loadTextFromFile("jacoco-xml-parser-reduced-jacocoTestReport.xml") + fun jacocoXmlParser75() = loadTextFromFile("jacoco-xml-parser-75-jacocoTestReport.xml") + fun jacocoXmlParser85() = loadTextFromFile("jacoco-xml-parser-85-jacocoTestReport.xml") fun junitResultsParser() = loadTextFromFile("junit-results-parser-jacocoTestReport.xml") + fun junitResultsParserReduced() = loadTextFromFile("junit-results-parser-reduced-jacocoTestReport.xml") fun serverApp() = loadTextFromFile("server-app-jacocoTestReport.xml") + fun serverAppReduced() = loadTextFromFile("server-app-reduced-jacocoTestReport.xml") + fun serverAppInvalid() = loadTextFromFile("server-app-jacocoTestReport-invalid.xml") fun emptyReport() = loadTextFromFile("jacoco-empty.xml") diff --git a/server/test/performance-fixtures/src/main/kotlin/projektor/server/example/performance/PerformanceResultsLoader.kt b/server/test/performance-fixtures/src/main/kotlin/projektor/server/example/performance/PerformanceResultsLoader.kt index 3dba2d554..fc0a93bd3 100644 --- a/server/test/performance-fixtures/src/main/kotlin/projektor/server/example/performance/PerformanceResultsLoader.kt +++ b/server/test/performance-fixtures/src/main/kotlin/projektor/server/example/performance/PerformanceResultsLoader.kt @@ -5,8 +5,9 @@ class PerformanceResultsLoader { fun k6GetRun() = loadTextFromFile("k6/getRun.json") - fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() } diff --git a/server/test/server-example-loader/src/main/kotlin/projektor/server/example/ExampleLoader.kt b/server/test/server-example-loader/src/main/kotlin/projektor/server/example/ExampleLoader.kt index f3e580515..215c963bf 100644 --- a/server/test/server-example-loader/src/main/kotlin/projektor/server/example/ExampleLoader.kt +++ b/server/test/server-example-loader/src/main/kotlin/projektor/server/example/ExampleLoader.kt @@ -35,30 +35,32 @@ fun loadPassingExample() { } fun loadAllExamples() { - val testResults = listOf( - resultsXmlLoader.passing(), - resultsXmlLoader.failing(), - resultsXmlLoader.failingLongFailureMessage(), - resultsXmlLoader.longOutput(), - resultsXmlLoader.output(), - resultsXmlLoader.reallyLongOutput(), - resultsXmlLoader.reallyLongOutput5000(), - resultsXmlLoader.reallyLongOutput10000(), - resultsXmlLoader.someIgnored(), - resultsXmlLoader.someIgnoredSomeFailing() - ) + val testResults = + listOf( + resultsXmlLoader.passing(), + resultsXmlLoader.failing(), + resultsXmlLoader.failingLongFailureMessage(), + resultsXmlLoader.longOutput(), + resultsXmlLoader.output(), + resultsXmlLoader.reallyLongOutput(), + resultsXmlLoader.reallyLongOutput5000(), + resultsXmlLoader.reallyLongOutput10000(), + resultsXmlLoader.someIgnored(), + resultsXmlLoader.someIgnoredSomeFailing(), + ) val saveResultsResponse = sendResultsToServer(testResults) println("View run with all tests at $uiBaseUrl${saveResultsResponse.uri}") } fun loadLargeOutputExamples() { - val testResults = listOf( - resultsXmlLoader.reallyLongOutput(), - resultsXmlLoader.reallyLongOutput5000(), - resultsXmlLoader.reallyLongOutput10000(), - resultsXmlLoader.reallyLongOutput100k(), - ) + val testResults = + listOf( + resultsXmlLoader.reallyLongOutput(), + resultsXmlLoader.reallyLongOutput5000(), + resultsXmlLoader.reallyLongOutput10000(), + resultsXmlLoader.reallyLongOutput100k(), + ) val saveResultsResponse = sendResultsToServer(testResults) println("View run with large output at $uiBaseUrl${saveResultsResponse.uri}") @@ -75,73 +77,96 @@ fun loadCypressExamplesWithFilePaths() { } fun loadCypressAndJestExamplesWithFilePaths() { - val groupedResults = groupedResultsXmlLoader.wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.cypressAttachmentsSpecWithFilePath(), - resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath(), - resultsXmlLoader.cypressWithFilePathAndRootSuiteNameSet(), - resultsXmlLoader.jestUiFilePath() + val groupedResults = + groupedResultsXmlLoader.wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.cypressAttachmentsSpecWithFilePath(), + resultsXmlLoader.cypressRepositoryTimelineSpecWithFilePath(), + resultsXmlLoader.cypressWithFilePathAndRootSuiteNameSet(), + resultsXmlLoader.jestUiFilePath(), + ), ) - ) val saveResultsResponse = sendGroupedResultsToServer(groupedResults) println("View run with Cypress and Jest tests with file paths at $uiBaseUrl${saveResultsResponse.uri}") } fun loadCypressWithFilePathAndRootSuiteNameSet() { - val groupedResults = groupedResultsXmlLoader.wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.cypressWithFilePathAndRootSuiteNameSet() + val groupedResults = + groupedResultsXmlLoader.wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.cypressWithFilePathAndRootSuiteNameSet(), + ), ) - ) val saveResultsResponse = sendGroupedResultsToServer(groupedResults) println("View run with Cypress tests with file path and root suite name set at $uiBaseUrl${saveResultsResponse.uri}") } fun loadFailingCypressTestWithAttachment() { - val resultsBody = groupedResultsXmlLoader.wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.cypressFailingAttachmentsTestWithScreenshot(), - resultsXmlLoader.cypressFailingDashboardTestWithScreenshots() + val resultsBody = + groupedResultsXmlLoader.wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.cypressFailingAttachmentsTestWithScreenshot(), + resultsXmlLoader.cypressFailingDashboardTestWithScreenshots(), + ), ) - ) val saveResultsResponse = sendGroupedResultsToServer(resultsBody) - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/dashboard -- should show failed test case summaries on dashboard page (failed).png") - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/dashboard -- should show test run summary data on dashboard page (failed).png") - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/test run with attachments -- should list attachments on attachments page (failed).png") + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/dashboard -- should show failed test case summaries on dashboard page (failed).png", + ) + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/dashboard -- should show test run summary data on dashboard page (failed).png", + ) + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/test run with attachments -- should list attachments on attachments page (failed).png", + ) println("View run with failing Cypress test with attachment screenshot at $uiBaseUrl${saveResultsResponse.uri}") } fun loadFailingCypressTestWithScreenshotAndVideoAttachments() { - val resultsBody = groupedResultsXmlLoader.wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.cypressFailingAttachmentsTestWithScreenshot(), - resultsXmlLoader.cypressFailingDashboardTestWithScreenshots() + val resultsBody = + groupedResultsXmlLoader.wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.cypressFailingAttachmentsTestWithScreenshot(), + resultsXmlLoader.cypressFailingDashboardTestWithScreenshots(), + ), ) - ) val saveResultsResponse = sendGroupedResultsToServer(resultsBody) - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/dashboard -- should show failed test case summaries on dashboard page (failed).png") - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/dashboard -- should show test run summary data on dashboard page (failed).png") - sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/test run with attachments -- should list attachments on attachments page (failed).png") + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/dashboard -- should show failed test case summaries on dashboard page (failed).png", + ) + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/dashboard -- should show test run summary data on dashboard page (failed).png", + ) + sendAttachmentToServer( + saveResultsResponse.id, + "src/main/resources/test run with attachments -- should list attachments on attachments page (failed).png", + ) sendAttachmentToServer(saveResultsResponse.id, "src/main/resources/attachments.spec.js.mp4") println("View run with failing Cypress test with screenshot and video attachments at $uiBaseUrl${saveResultsResponse.uri}") } fun loadSixFailingTests() { - val resultsBody = groupedResultsXmlLoader.wrapResultsXmlsInGroup( - listOf( - resultsXmlLoader.failing(), - resultsXmlLoader.failingLongFailureMessage(), - resultsXmlLoader.someIgnoredSomeFailing(), - resultsXmlLoader.gradleSingleTestCaseSystemOutFail(), - resultsXmlLoader.failingAnother() + val resultsBody = + groupedResultsXmlLoader.wrapResultsXmlsInGroup( + listOf( + resultsXmlLoader.failing(), + resultsXmlLoader.failingLongFailureMessage(), + resultsXmlLoader.someIgnoredSomeFailing(), + resultsXmlLoader.gradleSingleTestCaseSystemOutFail(), + resultsXmlLoader.failingAnother(), + ), ) - ) val saveResultsResponse = sendGroupedResultsToServer(resultsBody) @@ -149,7 +174,10 @@ fun loadSixFailingTests() { } fun loadPassingGroupedExample() { - val saveResultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.resultsWithCoverage(resultsXmls = listOf(resultsXmlLoader.passing()), coverageXmls = listOf())) + val saveResultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.resultsWithCoverage(resultsXmls = listOf(resultsXmlLoader.passing()), coverageXmls = listOf()), + ) println("View run with passing grouped tests at at $uiBaseUrl${saveResultsResponse.uri}") } @@ -175,7 +203,8 @@ fun loadK6Examples() { val k6ExampleResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXmlLoader.k6Example())) println("View run with k6 example results at at $uiBaseUrl${k6ExampleResponse.uri}") - val k6GetFailedTestCasesLargeResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXmlLoader.k6GetFailedTestCasesLarge())) + val k6GetFailedTestCasesLargeResponse = + sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXmlLoader.k6GetFailedTestCasesLarge())) println("View run with k6 getFailedTestCasesLarge results at at $uiBaseUrl${k6GetFailedTestCasesLargeResponse.uri}") } @@ -217,13 +246,25 @@ fun loadMultipleCoverageWithPreviousRunExample() { } fun loadCoberturaCoverageUi() { - val currentResultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.resultsWithCoverage(resultsXmls = listOf(resultsXmlLoader.jestUi()), coverageXmls = listOf(CoberturaXmlLoader().uiCobertura()))) + val currentResultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.resultsWithCoverage( + resultsXmls = listOf(resultsXmlLoader.jestUi()), + coverageXmls = listOf(CoberturaXmlLoader().uiCobertura()), + ), + ) println("View run with Cobertura coverage and UI results at $uiBaseUrl${currentResultsResponse.uri}") } fun loadCoberturaCoverageNoDocType() { - val currentResultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.resultsWithCoverage(resultsXmls = listOf(), coverageXmls = listOf(CoberturaXmlLoader().noDoctypeCobertura()))) + val currentResultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.resultsWithCoverage( + resultsXmls = listOf(), + coverageXmls = listOf(CoberturaXmlLoader().noDoctypeCobertura()), + ), + ) println("View run with Cobertura coverage without DocType at $uiBaseUrl${currentResultsResponse.uri}") } @@ -239,18 +280,22 @@ fun loadCloverCoverageLarge() { resultsMetadata.git = gitMetadata resultsMetadata.ci = true - val currentResultsResponse = sendGroupedResultsToServer( - groupedResultsXmlLoader.resultsWithCoverage( - resultsXmls = listOf(resultsXmlLoader.jestUi()), - coverageXmls = listOf(CloverXmlLoader().uiCloverLarge()), - metadata = resultsMetadata + val currentResultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.resultsWithCoverage( + resultsXmls = listOf(resultsXmlLoader.jestUi()), + coverageXmls = listOf(CloverXmlLoader().uiCloverLarge()), + metadata = resultsMetadata, + ), ) - ) println("View run with large Clover coverage and UI results at $uiBaseUrl${currentResultsResponse.uri}") } -fun loadMultipleTestRunsFromSameRepoForTimeline(repoName: String = "timeline-org/timeline-repo", printLink: Boolean = true) { +fun loadMultipleTestRunsFromSameRepoForTimeline( + repoName: String = "timeline-org/timeline-repo", + printLink: Boolean = true, +) { val branchName = "main" val gitMetadata = GitMetadata() gitMetadata.repoName = repoName @@ -261,9 +306,15 @@ fun loadMultipleTestRunsFromSameRepoForTimeline(repoName: String = "timeline-org resultsMetadata.ci = true sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUi(), metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.longOutput(), metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.someIgnored(), metadata = resultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUi(), metadata = resultsMetadata), + ) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.longOutput(), metadata = resultsMetadata), + ) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.someIgnored(), metadata = resultsMetadata), + ) if (printLink) { println("View repository test run timeline at $uiBaseUrl/repository/$repoName") @@ -291,8 +342,12 @@ fun loadMultipleShortTestRunsFromSameRepoForTimeline() { resultsMetadata.ci = true sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.longOutput(), metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.someIgnored(), metadata = resultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.longOutput(), metadata = resultsMetadata), + ) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.someIgnored(), metadata = resultsMetadata), + ) println("View repository short test run timeline at $uiBaseUrl/repository/$repoName") } @@ -308,9 +363,15 @@ fun slowTimeline() { resultsMetadata.git = gitMetadata resultsMetadata.ci = true - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slow(), metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slower(), metadata = resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slow(), metadata = resultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slow(), metadata = resultsMetadata), + ) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slower(), metadata = resultsMetadata), + ) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.slow(), metadata = resultsMetadata), + ) println("View repository slow tests run timeline at $uiBaseUrl/repository/$repoName") } @@ -380,12 +441,13 @@ fun loadCoverage75WithGit() { val coverageFile = CoverageFile() coverageFile.reportContents = JacocoXmlLoader().jacocoXmlParser75() - val resultsResponse = sendGroupedResultsToServer( - groupedResultsXmlLoader.passingResultsWithCoverage( - coverageFiles = listOf(coverageFile), - metadata = resultsMetadata + val resultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.passingResultsWithCoverage( + coverageFiles = listOf(coverageFile), + metadata = resultsMetadata, + ), ) - ) println("View run 75% coverage and Git metadata at $uiBaseUrl${resultsResponse.uri}") } @@ -403,12 +465,13 @@ fun loadCoverage85WithGit() { val coverageFile = CoverageFile() coverageFile.reportContents = JacocoXmlLoader().jacocoXmlParser85() - val resultsResponse = sendGroupedResultsToServer( - groupedResultsXmlLoader.passingResultsWithCoverage( - coverageFiles = listOf(coverageFile), - metadata = resultsMetadata + val resultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.passingResultsWithCoverage( + coverageFiles = listOf(coverageFile), + metadata = resultsMetadata, + ), ) - ) println("View run 85% coverage and Git metadata at $uiBaseUrl${resultsResponse.uri}") } @@ -448,15 +511,24 @@ fun repositoryFlakyTests() { branchResultsMetadata.ci = true repeat(5) { - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.failing(), metadata = mainResultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.failing(), metadata = mainResultsMetadata), + ) } repeat(6) { - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.failingLongFailureMessage(), metadata = branchResultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup( + resultsXml = resultsXmlLoader.failingLongFailureMessage(), + metadata = branchResultsMetadata, + ), + ) } repeat(2) { - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.passing(), metadata = mainResultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.passing(), metadata = mainResultsMetadata), + ) } println("View repository with flaky tests at $uiBaseUrl/repository/$repoName/tests/flaky") @@ -477,13 +549,15 @@ fun loadJestWithCoverageManyMissedLines() { } fun loadJestWithFilePaths() { - val resultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUiFilePath())) + val resultsResponse = + sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUiFilePath())) println("View run with Jest results with file paths at $uiBaseUrl${resultsResponse.uri}") } fun loadJestWithFailures() { - val resultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUiFailures())) + val resultsResponse = + sendGroupedResultsToServer(groupedResultsXmlLoader.wrapResultsXmlInGroup(resultsXml = resultsXmlLoader.jestUiFailures())) println("View run with Jest results with failures at $uiBaseUrl${resultsResponse.uri}") } @@ -520,13 +594,18 @@ fun performanceSingleTestTimeline() { val k6GetRunResults = PerformanceResultsLoader().k6GetRun() sendGroupedResultsToServer(groupedResultsXmlLoader.wrapPerformanceResultsInGroup(testName, k6GetRunResults, resultsMetadata)) - sendGroupedResultsToServer(groupedResultsXmlLoader.wrapPerformanceResultsInGroup(testName, k6GetFailedTestCasesLargeResults, resultsMetadata)) + sendGroupedResultsToServer( + groupedResultsXmlLoader.wrapPerformanceResultsInGroup(testName, k6GetFailedTestCasesLargeResults, resultsMetadata), + ) sendGroupedResultsToServer(groupedResultsXmlLoader.wrapPerformanceResultsInGroup(testName, k6GetRunResults, resultsMetadata)) println("View performance test timeline with single test at $uiBaseUrl/repository/$repoName") } -fun repositoryCoverageTimeline(repoName: String = "cov-org/cov-repo", printLink: Boolean = true) { +fun repositoryCoverageTimeline( + repoName: String = "cov-org/cov-repo", + printLink: Boolean = true, +) { val branchName = "main" val gitMetadata = GitMetadata() gitMetadata.repoName = repoName @@ -535,12 +614,30 @@ fun repositoryCoverageTimeline(repoName: String = "cov-org/cov-repo", printLink: val resultsMetadata = ResultsMetadata() resultsMetadata.git = gitMetadata - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().jacocoXmlParser()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().jacocoXmlParserReduced()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().serverAppReduced()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().serverApp()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().junitResultsParser()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, JacocoXmlLoader().junitResultsParserReduced()) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().jacocoXmlParser(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().jacocoXmlParserReduced(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().serverAppReduced(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().serverApp(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().junitResultsParser(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)).id, + JacocoXmlLoader().junitResultsParserReduced(), + ) if (printLink) { println("View repository coverage timeline at $uiBaseUrl/repository/$repoName") @@ -564,12 +661,30 @@ fun repositoryCoverageTimelineDifferentBranches() { val resultsMetadataBranch = ResultsMetadata() resultsMetadataBranch.git = gitMetadataBranch - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, JacocoXmlLoader().jacocoXmlParser()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, JacocoXmlLoader().jacocoXmlParserReduced()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, JacocoXmlLoader().serverAppReduced()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, JacocoXmlLoader().serverApp()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, JacocoXmlLoader().junitResultsParser()) - sendCoverageToServer(sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, JacocoXmlLoader().junitResultsParserReduced()) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, + JacocoXmlLoader().jacocoXmlParser(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, + JacocoXmlLoader().jacocoXmlParserReduced(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataMain)).id, + JacocoXmlLoader().serverAppReduced(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, + JacocoXmlLoader().serverApp(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, + JacocoXmlLoader().junitResultsParser(), + ) + sendCoverageToServer( + sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadataBranch)).id, + JacocoXmlLoader().junitResultsParserReduced(), + ) println("View repository coverage timeline with different branches at $uiBaseUrl/repository/$repoName") } @@ -586,7 +701,10 @@ fun coveragePayloadWithBaseDirectory() { val resultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.passingGroupedResults(metadata = resultsMetadata)) val publicId = resultsResponse.id - sendCoveragePayloadToServer(publicId, createCoverageFilePayload(JacocoXmlLoader().jacocoXmlParser(), "server/parsing/jacoco-xml-parser/src/main/kotlin")) + sendCoveragePayloadToServer( + publicId, + createCoverageFilePayload(JacocoXmlLoader().jacocoXmlParser(), "server/parsing/jacoco-xml-parser/src/main/kotlin"), + ) sendCoveragePayloadToServer(publicId, createCoverageFilePayload(JacocoXmlLoader().serverApp(), "server/server-app/src/main/kotlin")) println("View run with coverage base directory and Git metadata at $uiBaseUrl${resultsResponse.uri}") @@ -610,7 +728,10 @@ fun codeQualityTwoReports() { codeQualityReport2.contents = readFileContents("quality/server-app-ktlint.txt") codeQualityReport2.fileName = "server-app-ktlint.txt" - val resultsResponse = sendGroupedResultsToServer(groupedResultsXmlLoader.codeQualityResults(listOf(codeQualityReport1, codeQualityReport2), metadata = resultsMetadata)) + val resultsResponse = + sendGroupedResultsToServer( + groupedResultsXmlLoader.codeQualityResults(listOf(codeQualityReport1, codeQualityReport2), metadata = resultsMetadata), + ) println("View run with two code quality reports at $uiBaseUrl${resultsResponse.uri}") } @@ -640,8 +761,7 @@ fun invalidResults() { println("View admin page with results failures at $uiBaseUrl/admin") } -fun sendResultsToServer(resultXmlList: List): SaveResultsResponse = - resultXmlList.joinToString("\n").let(::sendResultsToServer) +fun sendResultsToServer(resultXmlList: List): SaveResultsResponse = resultXmlList.joinToString("\n").let(::sendResultsToServer) fun sendResultsToServer(resultsBlob: String): SaveResultsResponse { val client = OkHttpClient() @@ -649,10 +769,11 @@ fun sendResultsToServer(resultsBlob: String): SaveResultsResponse { val url = "$serverBaseUrl/results" val requestBody = resultsBlob.toRequestBody(plainTextMediaType) - val request = Request.Builder() - .url(url) - .post(requestBody) - .build() + val request = + Request.Builder() + .url(url) + .post(requestBody) + .build() val response = client.newCall(request).execute() val responseString = response.body?.string() @@ -664,17 +785,21 @@ fun readFileContents(resourcesRelativePath: String): String { return file.readText() } -fun sendAttachmentToServer(publicId: String, attachmentFilePath: String) { +fun sendAttachmentToServer( + publicId: String, + attachmentFilePath: String, +) { val attachmentFile = File(attachmentFilePath) val client = OkHttpClient() val mediaType = "octet/stream".toMediaType() val url = "$serverBaseUrl/run/$publicId/attachments/${attachmentFile.name}" val requestBody = attachmentFile.readBytes().toRequestBody(mediaType) - val request = Request.Builder() - .url(url) - .post(requestBody) - .build() + val request = + Request.Builder() + .url(url) + .post(requestBody) + .build() val response = client.newCall(request).execute() println("Response code ${response.code} from uploading attachment $attachmentFilePath") @@ -686,42 +811,51 @@ fun sendGroupedResultsToServer(groupedResultsJson: String): SaveResultsResponse val url = "$serverBaseUrl/groupedResults" val requestBody = groupedResultsJson.toRequestBody(mediaType) - val request = Request.Builder() - .url(url) - .post(requestBody) - .build() + val request = + Request.Builder() + .url(url) + .post(requestBody) + .build() val response = client.newCall(request).execute() val responseString = response.body?.string() return Gson().fromJson(responseString, SaveResultsResponse::class.java) } -fun sendCoverageToServer(publicId: String, reportXml: String) { +fun sendCoverageToServer( + publicId: String, + reportXml: String, +) { val client = OkHttpClient() val mediaType = "text/plain".toMediaType() val url = "$serverBaseUrl/run/$publicId/coverage" val requestBody = reportXml.toRequestBody(mediaType) - val request = Request.Builder() - .url(url) - .post(requestBody) - .build() + val request = + Request.Builder() + .url(url) + .post(requestBody) + .build() client.newCall(request).execute() } -fun sendCoveragePayloadToServer(publicId: String, reportPayload: String) { +fun sendCoveragePayloadToServer( + publicId: String, + reportPayload: String, +) { val client = OkHttpClient() val mediaType = "application/json".toMediaType() val url = "$serverBaseUrl/run/$publicId/coverageFile" val requestBody = reportPayload.toRequestBody(mediaType) - val request = Request.Builder() - .url(url) - .post(requestBody) - .build() + val request = + Request.Builder() + .url(url) + .post(requestBody) + .build() client.newCall(request).execute() } diff --git a/server/test/test-fixtures/src/main/kotlin/projektor/parser/GroupedResultsXmlLoader.kt b/server/test/test-fixtures/src/main/kotlin/projektor/parser/GroupedResultsXmlLoader.kt index 99cdc4dc3..c8362eb60 100644 --- a/server/test/test-fixtures/src/main/kotlin/projektor/parser/GroupedResultsXmlLoader.kt +++ b/server/test/test-fixtures/src/main/kotlin/projektor/parser/GroupedResultsXmlLoader.kt @@ -13,7 +13,10 @@ class GroupedResultsXmlLoader { private val groupedResultsParser = GroupedResultsParser() private val resultsXmlLoader = ResultsXmlLoader() - fun passingGroupedResults(metadata: ResultsMetadata? = null, wallClockDuration: BigDecimal? = null): String { + fun passingGroupedResults( + metadata: ResultsMetadata? = null, + wallClockDuration: BigDecimal? = null, + ): String { val groupedTestSuites1 = GroupedTestSuites() groupedTestSuites1.groupName = "Group1" groupedTestSuites1.groupLabel = "unitTest" @@ -34,7 +37,10 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun wrapResultsXmlInGroup(resultsXml: String, metadata: ResultsMetadata? = null): String { + fun wrapResultsXmlInGroup( + resultsXml: String, + metadata: ResultsMetadata? = null, + ): String { val groupedTestSuites = GroupedTestSuites() groupedTestSuites.groupName = "Group1" groupedTestSuites.groupLabel = "unitTest" @@ -48,7 +54,10 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun wrapResultsXmlsInGroup(resultsXmls: List, metadata: ResultsMetadata? = null): String { + fun wrapResultsXmlsInGroup( + resultsXmls: List, + metadata: ResultsMetadata? = null, + ): String { val groupedTestSuites = GroupedTestSuites() groupedTestSuites.groupName = "Group1" groupedTestSuites.groupLabel = "unitTest" @@ -62,7 +71,10 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun wrapPerformanceResultsInGroup(performanceResults: List, metadata: ResultsMetadata? = null): String { + fun wrapPerformanceResultsInGroup( + performanceResults: List, + metadata: ResultsMetadata? = null, + ): String { val groupedResults = GroupedResults() groupedResults.performanceResults = performanceResults groupedResults.metadata = metadata @@ -70,7 +82,11 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun wrapPerformanceResultsInGroup(name: String, performanceResultsBlob: String, metadata: ResultsMetadata? = null): String { + fun wrapPerformanceResultsInGroup( + name: String, + performanceResultsBlob: String, + metadata: ResultsMetadata? = null, + ): String { val performanceResult = PerformanceResult() performanceResult.name = name performanceResult.resultsBlob = performanceResultsBlob @@ -78,7 +94,10 @@ class GroupedResultsXmlLoader { return wrapPerformanceResultsInGroup(listOf(performanceResult), metadata) } - fun passingResultsWithCoverage(coverageFiles: List, metadata: ResultsMetadata? = null): String { + fun passingResultsWithCoverage( + coverageFiles: List, + metadata: ResultsMetadata? = null, + ): String { val groupedTestSuites1 = GroupedTestSuites() groupedTestSuites1.groupName = "Group1" groupedTestSuites1.groupLabel = "unitTest" @@ -99,7 +118,10 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun codeQualityResults(codeQualityReports: List, metadata: ResultsMetadata? = null): String { + fun codeQualityResults( + codeQualityReports: List, + metadata: ResultsMetadata? = null, + ): String { val groupedResults = GroupedResults() groupedResults.metadata = metadata groupedResults.codeQualityFiles = codeQualityReports @@ -107,7 +129,11 @@ class GroupedResultsXmlLoader { return groupedResultsParser.serializeGroupedResults(groupedResults) } - fun resultsWithCoverage(resultsXmls: List, coverageXmls: List, metadata: ResultsMetadata? = null): String { + fun resultsWithCoverage( + resultsXmls: List, + coverageXmls: List, + metadata: ResultsMetadata? = null, + ): String { val groupedTestSuites = GroupedTestSuites() groupedTestSuites.groupName = "All files" groupedTestSuites.directory = "/src" @@ -116,12 +142,13 @@ class GroupedResultsXmlLoader { val groupedResults = GroupedResults() groupedResults.groupedTestSuites = listOf(groupedTestSuites) groupedResults.metadata = metadata - groupedResults.coverageFiles = coverageXmls.map { coverageXml -> - val coverageFile = CoverageFile() - coverageFile.reportContents = coverageXml - coverageFile.baseDirectoryPath = "/src" - coverageFile - } + groupedResults.coverageFiles = + coverageXmls.map { coverageXml -> + val coverageFile = CoverageFile() + coverageFile.reportContents = coverageXml + coverageFile.baseDirectoryPath = "/src" + coverageFile + } return groupedResultsParser.serializeGroupedResults(groupedResults) } diff --git a/server/test/test-fixtures/src/main/kotlin/projektor/parser/ResultsXmlLoader.kt b/server/test/test-fixtures/src/main/kotlin/projektor/parser/ResultsXmlLoader.kt index 5763df45c..aaf428e89 100644 --- a/server/test/test-fixtures/src/main/kotlin/projektor/parser/ResultsXmlLoader.kt +++ b/server/test/test-fixtures/src/main/kotlin/projektor/parser/ResultsXmlLoader.kt @@ -6,6 +6,7 @@ class ResultsXmlLoader { fun passing() = loadTextFromFile("TEST-projektor.example.spock.PassingSpec.xml") fun failing() = loadTextFromFile("TEST-projektor.example.spock.FailingSpec.xml") + fun failingAnother() = loadTextFromFile("TEST-projektor.example.spock.AnotherFailingSpec.xml") fun failingLongFailureMessage() = loadTextFromFile("TEST-projektor.testsuite.GetTestSuiteApplicationTest-long-failure-output.xml") @@ -30,29 +31,33 @@ class ResultsXmlLoader { fun slower() = loadTextFromFile("TEST-projektor.example.spock.SlowerSpec.xml") - fun invalid() = loadTextFromFile("TEST-projektor.example.spock.PassingSpec.xml") - .replace(" { - val cypressResourceList = ClassGraph() - .whitelistPaths("cypress") - .scan() - .getResourcesWithExtension("xml") + val cypressResourceList = + ClassGraph() + .whitelistPaths("cypress") + .scan() + .getResourcesWithExtension("xml") return cypressResourceList .map { String(it.load()) } } fun cypressResultsWithFilePaths(): List { - val cypressResourceList = ClassGraph() - .whitelistPaths("cypress-file-path") - .scan() - .getResourcesWithExtension("xml") + val cypressResourceList = + ClassGraph() + .whitelistPaths("cypress-file-path") + .scan() + .getResourcesWithExtension("xml") return cypressResourceList .map { String(it.load()) } @@ -61,18 +66,27 @@ class ResultsXmlLoader { fun cypressEmptyTestSuites() = loadTextFromFile("cypress/cypress-empty-test-suites.xml") fun cypressAttachmentsSpecWithFilePath() = loadTextFromFile("cypress-file-path/cypress-attachments.xml") + fun cypressRepositoryTimelineSpecWithFilePath() = loadTextFromFile("cypress-file-path/cypress-repository-timeline.xml") + fun cypressWithFilePathAndRootSuiteNameSet() = loadTextFromFile("cypress-file-path/cypress-root-suite-name.xml") - fun cypressFailingDashboardTestWithScreenshots() = loadTextFromFile("cypress-file-path/cypress-failing-dashboard-test-with-screenshots.xml") - fun cypressFailingAttachmentsTestWithScreenshot() = loadTextFromFile("cypress-file-path/cypress-failing-attachments-test-with-screenshot.xml") + fun cypressFailingDashboardTestWithScreenshots() = + loadTextFromFile("cypress-file-path/cypress-failing-dashboard-test-with-screenshots.xml") + + fun cypressFailingAttachmentsTestWithScreenshot() = + loadTextFromFile("cypress-file-path/cypress-failing-attachments-test-with-screenshot.xml") fun jestUi() = loadTextFromFile("jest/ui-junit.xml") + fun jestUiFilePath() = loadTextFromFile("jest/ui-file-path-junit.xml") + fun jestUiFailures() = loadTextFromFile("jest/ui-junit-failures.xml") fun jestCoverageFilesTable() = loadTextFromFile("jest-append/CoverageFilesTable-junit.xml") + fun jestCoverageGraph() = loadTextFromFile("jest-append/CoverageGraph-junit.xml") + fun jestCoverageTable() = loadTextFromFile("jest-append/CoverageTable-junit.xml") fun pytestFailing() = loadTextFromFile("pytest/pytest-failing.xml") @@ -80,12 +94,14 @@ class ResultsXmlLoader { fun pytestPassing() = loadTextFromFile("pytest/pytest-passing.xml") fun k6Example() = loadTextFromFile("k6/k6-junit.xml") + fun k6GetFailedTestCasesLarge() = loadTextFromFile("k6/k6-getFailedTestCasesLarge.xml") fun singleQuoteXmlDeclaration() = loadTextFromFile("single-quote-xml-declaration.xml") - private fun loadTextFromFile(filename: String) = javaClass - .getResourceAsStream("/$filename") - .bufferedReader() - .readText() + private fun loadTextFromFile(filename: String) = + javaClass + .getResourceAsStream("/$filename") + .bufferedReader() + .readText() }