diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 2aa2ccdae1..226f80965b 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -39,3 +39,6 @@ b20f0ba57795f003fe4d90817422e14b880d6c8c # Scala Steward: Reformat with scalafmt 3.8.3 36121b1cae26cb45c8e5cbe3dcce11d15612c4ce + +# Scala Steward: Reformat with scalafmt 3.8.4 +e2300dcb3228e0e4458a1efdadde59cc1141d024 diff --git a/.scalafmt.conf b/.scalafmt.conf index 098e53052a..2ccf93145b 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,4 +1,4 @@ -version = "3.8.3" +version = "3.8.4" runner.dialect = scala213 diff --git a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/CommitInfoSpec.scala b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/CommitInfoSpec.scala index a19ab024ed..6e48f68b1d 100644 --- a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/CommitInfoSpec.scala +++ b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/CommitInfoSpec.scala @@ -33,7 +33,7 @@ class CommitInfoSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou "CommitInfo Decoder" should { - "decode valid JSON to a CommitInfo object" in { + "decode valid JSON to a CommitInfo object" in forAll { commitInfo: CommitInfo => json"""{ "id": ${commitInfo.id.value}, @@ -46,7 +46,6 @@ class CommitInfoSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou "parent_ids": ${commitInfo.parents.map(_.value)} }""".as[CommitInfo] shouldBe Right(commitInfo) } - } "decode valid JSON with blank emails to a CommitInfo object" in { val commitInfo = commitInfos.generateOne diff --git a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/commiteventsSpec.scala b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/commiteventsSpec.scala index 450402f052..8f03298e00 100644 --- a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/commiteventsSpec.scala +++ b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/commitsync/eventgeneration/commiteventsSpec.scala @@ -30,11 +30,10 @@ class AuthorSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "withEmail" should { - "instantiate a new Author with username extracted from the email" in { + "instantiate a new Author with username extracted from the email" in forAll { email: Email => Author.withEmail(email) shouldBe Author(email.extractName, email) } - } } } @@ -42,10 +41,9 @@ class CommitterSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shoul "withEmail" should { - "instantiate a new Committer with username extracted from the email" in { + "instantiate a new Committer with username extracted from the email" in forAll { email: Email => Committer.withEmail(email) shouldBe Committer(email.extractName, email) } - } } } diff --git a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/CommitToEventLogSpec.scala b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/CommitToEventLogSpec.scala index b5c3a2df27..e65ab29d4c 100644 --- a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/CommitToEventLogSpec.scala +++ b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/CommitToEventLogSpec.scala @@ -152,7 +152,8 @@ class CommitToEventLogSpec extends AnyWordSpec with MockFactory with should.Matc "body": $body, "status": ${event.status} }""" - case (event: SkippedCommitEvent, body) => json"""{ + case (event: SkippedCommitEvent, body) => + json"""{ "categoryName": "CREATION", "id": ${event.id}, "project": { diff --git a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/SynchronizationSummarySpec.scala b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/SynchronizationSummarySpec.scala index 0fd87b378e..406f3bf151 100644 --- a/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/SynchronizationSummarySpec.scala +++ b/commit-event-service/src/test/scala/io/renku/commiteventservice/events/consumers/common/SynchronizationSummarySpec.scala @@ -31,7 +31,7 @@ class SynchronizationSummarySpec extends AnyWordSpec with should.Matchers with S "get & updated" should { - "return count for the given key" in { + "return count for the given key" in forAll(resultsAndMaybeCountList) { countsAndResults => val summary = countsAndResults .foldLeft(SynchronizationSummary()) { @@ -44,12 +44,11 @@ class SynchronizationSummarySpec extends AnyWordSpec with should.Matchers with S case (None, result) => summary.get(result) shouldBe 0 } } - } } "increment" should { - "increment the count for the given key" in { + "increment the count for the given key" in forAll(summaries, updateResults.toGeneratorOfList(max = 10)) { (initialSummary, results) => val summary = results.foldLeft(initialSummary)(_.incrementCount(_)) @@ -60,7 +59,6 @@ class SynchronizationSummarySpec extends AnyWordSpec with should.Matchers with S val failed = Failed(nonEmptyStrings().generateOne, exceptions.generateOne) summary.get(failed) shouldBe initialSummary.get(failed) + results.count(_.isInstanceOf[Failed]) } - } } "show" should { diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/DatasetSearchInfoSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/DatasetSearchInfoSpec.scala index d7eabd4524..887af2e5fe 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/DatasetSearchInfoSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/DatasetSearchInfoSpec.scala @@ -40,7 +40,7 @@ class DatasetSearchInfoSpec extends AnyWordSpec with should.Matchers with ScalaC "show" should { - "return String representation of the Info" in { + "return String representation of the Info" in forAll(datasetSearchInfoObjects) { case info @ DatasetSearchInfo(topSameAs, name, @@ -76,6 +76,5 @@ class DatasetSearchInfoSpec extends AnyWordSpec with should.Matchers with ScalaC show"links = [${links.mkString_("; ")}]".some ).flatten.mkString(", ") } - } } } diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/LinkSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/LinkSpec.scala index 4ebf7180bc..64a2f9c53c 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/LinkSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/LinkSpec.scala @@ -100,11 +100,10 @@ class LinkSpec extends AnyWordSpec with should.Matchers with ScalaCheckPropertyC "show" should { - "returns String representation" in { + "returns String representation" in forAll(linkObjectsGen(datasetTopmostSameAs.generateOne)) { link => link.show shouldBe show"id = ${link.resourceId}, projectId = ${link.projectId}, datasetId = ${link.datasetId}, visibility = ${link.visibility}" } - } } } diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/ModelDatasetSearchInfoSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/ModelDatasetSearchInfoSpec.scala index 48aa42d0a7..b369a9f02c 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/ModelDatasetSearchInfoSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/ModelDatasetSearchInfoSpec.scala @@ -29,7 +29,7 @@ class ModelDatasetSearchInfoSpec extends AnyWordSpec with should.Matchers with S "show" should { - "return String representation of the Info" in { + "return String representation of the Info" in forAll(modelDatasetSearchInfoObjects) { case info @ ModelDatasetSearchInfo(topSameAs, name, @@ -65,6 +65,5 @@ class ModelDatasetSearchInfoSpec extends AnyWordSpec with should.Matchers with S show"link = $link".some ).flatten.mkString(", ") } - } } } diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/CalculatorInfoSetSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/CalculatorInfoSetSpec.scala index 8e4cbd3d2f..c876d0897f 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/CalculatorInfoSetSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/CalculatorInfoSetSpec.scala @@ -192,7 +192,7 @@ class CalculatorInfoSetSpec "show" should { - "return String containing project id and slug along with model and TS search info" in { + "return String containing project id and slug along with model and TS search info" in forAll(anyProjectEntities.map(_.to[entities.Project])) { project => val modelInfo = modelDatasetSearchInfoObjects(withLinkTo = project).generateOne @@ -209,7 +209,6 @@ class CalculatorInfoSetSpec maybeTSInfo.map(tsi => show"tsInfo = [$tsi]") ).flatten.mkString(", ") } - } } private def searchIntoToString(info: ModelDatasetSearchInfo) = List( diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/EncodersSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/EncodersSpec.scala index bef74679c8..615f5ea24d 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/EncodersSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/datasets/commands/EncodersSpec.scala @@ -66,8 +66,7 @@ class EncodersSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope "searchInfoEncoder" should { - "turn a SearchInfo object into a Set of relevant Quads" in { - + "turn a SearchInfo object into a Set of relevant Quads" in forAll(datasetSearchInfoObjects) { searchInfo => searchInfo.asQuads shouldBe Set( DatasetsQuad(searchInfo.topmostSameAs, rdf / "type", renku / "DiscoverableDataset"), @@ -88,7 +87,6 @@ class EncodersSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope maybeImagesConcatToQuad(searchInfo).toSet ++ linksToQuads(searchInfo) } - } } private def createdOrPublishedToQuad(topmostSameAs: datasets.TopmostSameAs): datasets.CreatedOrPublished => Quad = { diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/ProjectSearchInfoSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/ProjectSearchInfoSpec.scala index 6b94054d0c..ebde962296 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/ProjectSearchInfoSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/ProjectSearchInfoSpec.scala @@ -28,7 +28,7 @@ class ProjectSearchInfoSpec extends AnyWordSpec with should.Matchers with ScalaC "show" should { - "return a String representation of the Info" in { + "return a String representation of the Info" in forAll(projectSearchInfoObjects) { case info @ ProjectSearchInfo(id, name, @@ -60,6 +60,5 @@ class ProjectSearchInfoSpec extends AnyWordSpec with should.Matchers with ScalaC } ).flatten.mkString(", ") } - } } } diff --git a/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/commands/EncodersSpec.scala b/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/commands/EncodersSpec.scala index 89377e6af9..876e2e47f7 100644 --- a/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/commands/EncodersSpec.scala +++ b/entities-search/src/test/scala/io/renku/entities/searchgraphs/projects/commands/EncodersSpec.scala @@ -38,8 +38,7 @@ class EncodersSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope "searchInfoEncoder" should { - "turn a SearchInfo object into a Set of relevant Quads" in { - + "turn a SearchInfo object into a Set of relevant Quads" in forAll(projectSearchInfoObjects) { searchInfo => searchInfo.asQuads shouldBe Set( ProjectsQuad(searchInfo.id, rdf / "type", renku / "DiscoverableProject"), @@ -55,7 +54,6 @@ class EncodersSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope maybeKeywordsConcatToQuad(searchInfo).toSet ++ maybeImagesConcatToQuad(searchInfo).toSet } - } } diff --git a/event-log-api/src/test/scala/io/renku/eventlog/api/events/StatusChangeEventSpec.scala b/event-log-api/src/test/scala/io/renku/eventlog/api/events/StatusChangeEventSpec.scala index 0db77ca3b8..94ab950db1 100644 --- a/event-log-api/src/test/scala/io/renku/eventlog/api/events/StatusChangeEventSpec.scala +++ b/event-log-api/src/test/scala/io/renku/eventlog/api/events/StatusChangeEventSpec.scala @@ -82,13 +82,12 @@ class StatusChangeEventSpec extends AnyWordSpec with should.Matchers with ScalaC } } "encode" should { - "encode a discriminator value" in { + "encode a discriminator value" in forAll(StatusChangeGenerators.statusChangeEvents) { event => val json = event.asJson val subCategory = json.asObject.flatMap(_.apply("subCategory")) subCategory shouldBe Some(event.subCategoryName.asJson) } - } "encode a discriminator value when using specific codec" in { val event: RollbackToAwaitingDeletion = StatusChangeGenerators.rollbackToAwaitingDeletionEvents.generateOne diff --git a/event-log-api/src/test/scala/io/renku/eventlog/api/events/TestClient.scala b/event-log-api/src/test/scala/io/renku/eventlog/api/events/TestClient.scala index fc7823dd17..faf6b8cad7 100644 --- a/event-log-api/src/test/scala/io/renku/eventlog/api/events/TestClient.scala +++ b/event-log-api/src/test/scala/io/renku/eventlog/api/events/TestClient.scala @@ -73,6 +73,6 @@ class CollectingTestClient[F[_]: Async] extends Client[F] { } object TestClient { - def expectingMode[F[_]: Async]: ExpectingTestClient[F] = new ExpectingTestClient[F] + def expectingMode[F[_]: Async]: ExpectingTestClient[F] = new ExpectingTestClient[F] def collectingMode[F[_]: Async]: CollectingTestClient[F] = new CollectingTestClient[F] } diff --git a/event-log/src/main/scala/io/renku/eventlog/MicroserviceRoutes.scala b/event-log/src/main/scala/io/renku/eventlog/MicroserviceRoutes.scala index 7ec5187fa8..3ccb90c7c1 100644 --- a/event-log/src/main/scala/io/renku/eventlog/MicroserviceRoutes.scala +++ b/event-log/src/main/scala/io/renku/eventlog/MicroserviceRoutes.scala @@ -90,7 +90,7 @@ private class MicroserviceRoutes[F[_]: Sync]( case GET -> Root / "events" / EventId(eventId) / ProjectId(projectId) => respond503IfMigrating(getDetails(CompoundEventId(eventId, projectId))) case GET -> Root / "events" / EventId(eventId) / ProjectSlug(projectSlug) / "payload" => respond503IfMigrating(eventPayloadEndpoint.getEventPayload(eventId, projectSlug)) case GET -> Root / "ping" => Ok("pong") - case GET -> Root / "migration-status" => isMigrating.get.flatMap {isMigrating => Ok(json"""{"isMigrating": $isMigrating}""")} + case GET -> Root / "migration-status" => isMigrating.get.flatMap{isMigrating => Ok(json"""{"isMigrating": $isMigrating}""")} case GET -> Root / "status" => respond503IfMigrating(`GET /status`) case req @ POST -> Root / "subscriptions" => respond503IfMigrating(addSubscription(req)) }.withMetrics.map(_ <+> versionRoutes()) diff --git a/event-log/src/main/scala/io/renku/eventlog/events/producers/awaitinggeneration/SubscriptionCategory.scala b/event-log/src/main/scala/io/renku/eventlog/events/producers/awaitinggeneration/SubscriptionCategory.scala index 2bcb0ce613..a04ea66f7c 100644 --- a/event-log/src/main/scala/io/renku/eventlog/events/producers/awaitinggeneration/SubscriptionCategory.scala +++ b/event-log/src/main/scala/io/renku/eventlog/events/producers/awaitinggeneration/SubscriptionCategory.scala @@ -39,10 +39,11 @@ private[producers] object SubscriptionCategory { val categoryName: CategoryName = CategoryName("AWAITING_GENERATION") - def apply[F[ - _ - ]: Async: Parallel: SessionResource: DefaultSubscriberTracker: Logger: MetricsRegistry: QueriesExecutionTimes: EventStatusGauges] - : F[producers.SubscriptionCategory[F]] = for { + def apply[ + F[ + _ + ]: Async: Parallel: SessionResource: DefaultSubscriberTracker: Logger: MetricsRegistry: QueriesExecutionTimes: EventStatusGauges + ]: F[producers.SubscriptionCategory[F]] = for { implicit0(subscribers: DefaultSubscribers[F]) <- DefaultSubscribers[F](categoryName) eventFetcher <- EventFinder[F] dispatchRecovery <- DispatchRecovery[F] diff --git a/event-log/src/main/scala/io/renku/eventlog/events/producers/cleanup/SubscriptionCategory.scala b/event-log/src/main/scala/io/renku/eventlog/events/producers/cleanup/SubscriptionCategory.scala index 39f61c5cd4..aa1e8c7e57 100644 --- a/event-log/src/main/scala/io/renku/eventlog/events/producers/cleanup/SubscriptionCategory.scala +++ b/event-log/src/main/scala/io/renku/eventlog/events/producers/cleanup/SubscriptionCategory.scala @@ -33,10 +33,11 @@ import org.typelevel.log4cats.Logger private[producers] object SubscriptionCategory { - def apply[F[ - _ - ]: Async: Parallel: SessionResource: DefaultSubscriberTracker: Logger: MetricsRegistry: QueriesExecutionTimes: EventStatusGauges] - : F[SubscriptionCategory[F]] = for { + def apply[ + F[ + _ + ]: Async: Parallel: SessionResource: DefaultSubscriberTracker: Logger: MetricsRegistry: QueriesExecutionTimes: EventStatusGauges + ]: F[SubscriptionCategory[F]] = for { implicit0(subscribers: DefaultSubscribers[F]) <- DefaultSubscribers[F](categoryName) eventDelivery <- eventdelivery.EventDelivery[F, CleanUpEvent]( eventDeliveryIdExtractor = (event: CleanUpEvent) => DeletingProjectDeliverId(event.project.id) diff --git a/event-log/src/test/scala/io/renku/eventlog/TSMigrationModelSpec.scala b/event-log/src/test/scala/io/renku/eventlog/TSMigrationModelSpec.scala index 529f31e397..3f526f1c3a 100644 --- a/event-log/src/test/scala/io/renku/eventlog/TSMigrationModelSpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/TSMigrationModelSpec.scala @@ -77,19 +77,17 @@ class ChangeDateSpec extends AnyWordSpec with should.Matchers with ScalaCheckPro "instantiation" should { - "succeed for timestamps not in the future" in { + "succeed for timestamps not in the future" in forAll(timestamps(max = Instant.now())) { value => ChangeDate.from(value).map(_.value) shouldBe Right(value) } - } - "fail for timestamps from the future" in { + "fail for timestamps from the future" in forAll(timestamps(min = Instant.now().plus(1, SECONDS))) { value => val Left(exception) = ChangeDate.from(value).map(_.value) exception shouldBe an[IllegalArgumentException] exception.getMessage shouldBe s"${ChangeDate.typeName} cannot be in the future" } - } } } @@ -101,16 +99,14 @@ class MigrationMessageSpec extends AnyWordSpec with ScalaCheckPropertyChecks wit MigrationMessage shouldBe an[NonBlank[_]] } - "be instantiatable from any non-blank string" in { + "be instantiatable from any non-blank string" in forAll(nonEmptyStrings()) { body => MigrationMessage.from(body).map(_.value) shouldBe Right(body) } - } - "be instantiatable from an exception and contain the stack trace" in { + "be instantiatable from an exception and contain the stack trace" in forAll(nestedExceptions) { exception => MigrationMessage(exception).value shouldBe Message.Error.fromStackTrace(exception).show } - } } } diff --git a/event-log/src/test/scala/io/renku/eventlog/events/consumers/creation/EventSpec.scala b/event-log/src/test/scala/io/renku/eventlog/events/consumers/creation/EventSpec.scala index a31449de8b..1663b51dff 100644 --- a/event-log/src/test/scala/io/renku/eventlog/events/consumers/creation/EventSpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/events/consumers/creation/EventSpec.scala @@ -29,10 +29,9 @@ class EventSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "compoundEventId" should { - "create a CompoundEventId from the event's id and project id" in { + "create a CompoundEventId from the event's id and project id" in forAll { event: Event => event.compoundEventId shouldBe CompoundEventId(event.id, event.project.id) } - } } } diff --git a/event-log/src/test/scala/io/renku/eventlog/events/producers/TotalCapacitySpec.scala b/event-log/src/test/scala/io/renku/eventlog/events/producers/TotalCapacitySpec.scala index 5bf9e9708e..d73b7a648d 100644 --- a/event-log/src/test/scala/io/renku/eventlog/events/producers/TotalCapacitySpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/events/producers/TotalCapacitySpec.scala @@ -48,10 +48,9 @@ class TotalCapacitySpec extends AnyWordSpec with should.Matchers with ScalaCheck "*" should { - "multiple the Capacity's value by the given value" in { + "multiple the Capacity's value by the given value" in forAll { (totalCapacity: TotalCapacity, value: Double) => totalCapacity * value shouldBe totalCapacity.value * value } - } } } diff --git a/event-log/src/test/scala/io/renku/eventlog/events/producers/tsmigrationrequest/EventFinderSpec.scala b/event-log/src/test/scala/io/renku/eventlog/events/producers/tsmigrationrequest/EventFinderSpec.scala index fe875a772b..d5c49cc991 100644 --- a/event-log/src/test/scala/io/renku/eventlog/events/producers/tsmigrationrequest/EventFinderSpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/events/producers/tsmigrationrequest/EventFinderSpec.scala @@ -259,19 +259,18 @@ class EventFinderSpec "return no Event " + "- case when there are multiple rows for the same version " + "one in Sent for less than SentStatusTimeout" + - "but also one in RecoverableFailure for more than RecoverableStatusTimeout" in testDBResource.use { - implicit cfg => - for { - _ <- insertSubscriptionRecord(subscriberUrls.generateOne, version, Sent, less(than = sentStatusTimeout)) - _ <- insertSubscriptionRecord(subscriberUrls.generateOne, - version, - RecoverableFailure, - more(than = recoverableStatusTimeout) - ) - _ <- insertSubscriptionRecord(url, version, New, ChangeDate(now)) + "but also one in RecoverableFailure for more than RecoverableStatusTimeout" in testDBResource.use { implicit cfg => + for { + _ <- insertSubscriptionRecord(subscriberUrls.generateOne, version, Sent, less(than = sentStatusTimeout)) + _ <- insertSubscriptionRecord(subscriberUrls.generateOne, + version, + RecoverableFailure, + more(than = recoverableStatusTimeout) + ) + _ <- insertSubscriptionRecord(url, version, New, ChangeDate(now)) - _ <- finder.popEvent().asserting(_ shouldBe None) - } yield () + _ <- finder.popEvent().asserting(_ shouldBe None) + } yield () } "return Migration Request Event for the most recent version row with Sent " + diff --git a/event-log/src/test/scala/io/renku/eventlog/init/EventLogTableRenamerSpec.scala b/event-log/src/test/scala/io/renku/eventlog/init/EventLogTableRenamerSpec.scala index d934be66c5..d53932d6a9 100644 --- a/event-log/src/test/scala/io/renku/eventlog/init/EventLogTableRenamerSpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/init/EventLogTableRenamerSpec.scala @@ -33,18 +33,17 @@ class EventLogTableRenamerSpec extends AsyncFlatSpec with AsyncIOSpec with DbIni protected[init] override val runMigrationsUpTo: Class[_ <: DbMigrator[IO]] = classOf[EventLogTableRenamer[IO]] - it should "rename the 'event_log' table to 'event' when 'event' does not exist" in testDBResource.use { - implicit cfg => - for { - _ <- tableExists("event_log").asserting(_ shouldBe true) + it should "rename the 'event_log' table to 'event' when 'event' does not exist" in testDBResource.use { implicit cfg => + for { + _ <- tableExists("event_log").asserting(_ shouldBe true) - _ <- tableRenamer.run.assertNoException + _ <- tableRenamer.run.assertNoException - _ <- tableExists("event_log").asserting(_ shouldBe false) - _ <- tableExists("event").asserting(_ shouldBe true) + _ <- tableExists("event_log").asserting(_ shouldBe false) + _ <- tableExists("event").asserting(_ shouldBe true) - _ <- logger.loggedOnlyF(Info("'event_log' table renamed to 'event'")) - } yield Succeeded + _ <- logger.loggedOnlyF(Info("'event_log' table renamed to 'event'")) + } yield Succeeded } it should "do nothing if the 'event' table already exists and 'event_log' does not exist" in testDBResource.use { diff --git a/event-log/src/test/scala/io/renku/eventlog/modelSpec.scala b/event-log/src/test/scala/io/renku/eventlog/modelSpec.scala index 3287efcc2f..094c21f074 100644 --- a/event-log/src/test/scala/io/renku/eventlog/modelSpec.scala +++ b/event-log/src/test/scala/io/renku/eventlog/modelSpec.scala @@ -33,19 +33,17 @@ class EventDateSpec extends AnyWordSpec with should.Matchers with ScalaCheckProp "instantiation" should { - "succeed if less than a day in the future" in { + "succeed if less than a day in the future" in forAll(timestamps(max = Instant.now().plus(24, HOURS).minus(1, SECONDS))) { value => EventDate.from(value).map(_.value) shouldBe Right(value) } - } - "fail if further than a day in the future" in { + "fail if further than a day in the future" in forAll(timestamps(min = Instant.now().plus(24, HOURS).plus(1, SECONDS))) { value => val Left(exception) = EventDate.from(value).map(_.value) exception shouldBe an[IllegalArgumentException] exception.getMessage should startWith(s"${EventDate.typeName} has to be <= ") } - } } } @@ -57,11 +55,10 @@ class CreatedDateSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho CreatedDate shouldBe an[InstantNotInTheFuture[_]] } - "be instantiatable from any Instant not from the future" in { + "be instantiatable from any Instant not from the future" in forAll(timestampsNotInTheFuture) { instant => CreatedDate.from(instant).map(_.value) shouldBe Right(instant) } - } } } @@ -69,11 +66,10 @@ class ExecutionDateSpec extends AnyWordSpec with ScalaCheckPropertyChecks with s "ExecutionDate" should { - "be instantiatable from any Instant" in { + "be instantiatable from any Instant" in forAll(timestamps) { instant => ExecutionDate.from(instant).map(_.value) shouldBe Right(instant) } - } } } @@ -85,16 +81,14 @@ class EventMessageSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sh EventMessage shouldBe an[NonBlank[_]] } - "be instantiatable from any non-blank string" in { + "be instantiatable from any non-blank string" in forAll(nonEmptyStrings()) { body => EventMessage.from(body).map(_.value) shouldBe Right(body) } - } - "be instantiatable from an exception and contain the stack trace" in { + "be instantiatable from an exception and contain the stack trace" in forAll(nestedExceptions) { exception => EventMessage(exception).value shouldBe Message.Error.fromStackTrace(exception).show } - } } } diff --git a/graph-commons/src/test/scala/io/renku/config/ApiUrlSpec.scala b/graph-commons/src/test/scala/io/renku/config/ApiUrlSpec.scala index 91a4f5c607..a73360a380 100644 --- a/graph-commons/src/test/scala/io/renku/config/ApiUrlSpec.scala +++ b/graph-commons/src/test/scala/io/renku/config/ApiUrlSpec.scala @@ -35,7 +35,7 @@ class ApiUrlSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "apply" should { - "return a ResourcesUrl if there's a value for 'services.renku.resource-url'" in { + "return a ResourcesUrl if there's a value for 'services.renku.resource-url'" in forAll(httpUrls()) { url => val config = ConfigFactory.parseMap( Map( @@ -48,7 +48,6 @@ class ApiUrlSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M ) ApiUrl[Try](config) shouldBe Success(ApiUrl(url)) } - } "fail if there's no value for the 'services.renku.url'" in { val Failure(exception) = ApiUrl[Try](ConfigFactory.empty()) diff --git a/graph-commons/src/test/scala/io/renku/events/consumers/subscriptions/SubscriberUrlSpec.scala b/graph-commons/src/test/scala/io/renku/events/consumers/subscriptions/SubscriberUrlSpec.scala index e2335bd252..f6de927ad5 100644 --- a/graph-commons/src/test/scala/io/renku/events/consumers/subscriptions/SubscriberUrlSpec.scala +++ b/graph-commons/src/test/scala/io/renku/events/consumers/subscriptions/SubscriberUrlSpec.scala @@ -42,11 +42,10 @@ class SubscriberUrlSpec extends AnyWordSpec with should.Matchers with ScalaCheck "to MicroserviceBaseUrl conversion" should { - "successfully convert MicroserviceBaseUrl if well defined" in { + "successfully convert MicroserviceBaseUrl if well defined" in forAll(httpUrls(pathGenerator = ""), relativePaths(minSegments = 0, maxSegments = 2)) { (url, path) => val pathValidated = if (path.isEmpty) "" else s"/$path" SubscriberUrl(s"$url$pathValidated").toUnsafe[MicroserviceBaseUrl] shouldBe MicroserviceBaseUrl(url) } - } } } diff --git a/graph-commons/src/test/scala/io/renku/graph/config/RenkuUrlLoaderSpec.scala b/graph-commons/src/test/scala/io/renku/graph/config/RenkuUrlLoaderSpec.scala index aa24dcb9ce..cb51e224d7 100644 --- a/graph-commons/src/test/scala/io/renku/graph/config/RenkuUrlLoaderSpec.scala +++ b/graph-commons/src/test/scala/io/renku/graph/config/RenkuUrlLoaderSpec.scala @@ -37,7 +37,7 @@ class RenkuUrlLoaderSpec extends AnyWordSpec with ScalaCheckPropertyChecks with "apply" should { - "return a renkuUrl if there's a value for 'services.renku.url'" in { + "return a renkuUrl if there's a value for 'services.renku.url'" in forAll(httpUrls()) { url => val config = ConfigFactory.parseMap( Map( @@ -51,7 +51,6 @@ class RenkuUrlLoaderSpec extends AnyWordSpec with ScalaCheckPropertyChecks with RenkuUrlLoader[Try](config) shouldBe Success(RenkuUrl(url)) } - } "fail if there's no value for the 'services.renku.url'" in { val Failure(exception) = RenkuUrlLoader[Try](ConfigFactory.empty()) @@ -77,10 +76,9 @@ class RenkuUrlLoaderSpec extends AnyWordSpec with ScalaCheckPropertyChecks with "showAs[RdfResource]" should { - "URI encode and wrap the url in <>" in { + "URI encode and wrap the url in <>" in forAll { url: RenkuUrl => url.showAs[RdfResource] shouldBe s"<${URIref.encode(url.value)}>" } - } } } diff --git a/graph-commons/src/test/scala/io/renku/graph/http/server/EventIdSpec.scala b/graph-commons/src/test/scala/io/renku/graph/http/server/EventIdSpec.scala index a8abf76751..4aa298ce44 100644 --- a/graph-commons/src/test/scala/io/renku/graph/http/server/EventIdSpec.scala +++ b/graph-commons/src/test/scala/io/renku/graph/http/server/EventIdSpec.scala @@ -30,11 +30,10 @@ class EventIdSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. "unapply" should { - "convert valid eventId as string to EventId" in { + "convert valid eventId as string to EventId" in forAll { id: events.EventId => EventId.unapply(id.toString) shouldBe Some(id) } - } "return None if string value is blank" in { EventId.unapply(" ") shouldBe None diff --git a/graph-commons/src/test/scala/io/renku/graph/http/server/security/ProjectAuthRecordsFinderSpec.scala b/graph-commons/src/test/scala/io/renku/graph/http/server/security/ProjectAuthRecordsFinderSpec.scala index bb26da9327..e05aae3847 100644 --- a/graph-commons/src/test/scala/io/renku/graph/http/server/security/ProjectAuthRecordsFinderSpec.scala +++ b/graph-commons/src/test/scala/io/renku/graph/http/server/security/ProjectAuthRecordsFinderSpec.scala @@ -64,11 +64,10 @@ class ProjectAuthRecordsFinderSpec } } - it should "return empty when project is not found" in { + it should "return empty when project is not found" in withProjectAuthService.use { s => val finder = ProjectAuthRecordsFinder(s) val slug = Slug("p/c") finder(slug, None).asserting(_ shouldBe Nil) } - } } diff --git a/graph-commons/src/test/scala/io/renku/graph/model/eventsSpec.scala b/graph-commons/src/test/scala/io/renku/graph/model/eventsSpec.scala index 36be7fee4f..9aa0c59121 100644 --- a/graph-commons/src/test/scala/io/renku/graph/model/eventsSpec.scala +++ b/graph-commons/src/test/scala/io/renku/graph/model/eventsSpec.scala @@ -111,8 +111,7 @@ class EventStatusSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho class EventStatusProgressSpec extends AnyWordSpec with TableDrivenPropertyChecks with should.Matchers { import EventStatusProgress._ - "apply" should { - + "apply" should forAll { Table( ("status", "stage", "completion"), @@ -136,18 +135,16 @@ class EventStatusProgressSpec extends AnyWordSpec with TableDrivenPropertyChecks progress.completion.value shouldBe completion } } - } } class CompoundEventIdSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Matchers { "toString" should { - "be of format 'id = , projectId = '" in { + "be of format 'id = , projectId = '" in forAll { commitEventId: CompoundEventId => commitEventId.toString shouldBe s"id = ${commitEventId.id}, projectId = ${commitEventId.projectId}" } - } } } @@ -155,19 +152,17 @@ class CommittedDateSpec extends AnyWordSpec with should.Matchers with ScalaCheck "instantiation" should { - "succeed if less than a day in the future" in { + "succeed if less than a day in the future" in forAll(timestamps(max = Instant.now().plus(24, HOURS).minus(1, SECONDS))) { value => CommittedDate.from(value).map(_.value) shouldBe Right(value) } - } - "fail if further than a day in the future" in { + "fail if further than a day in the future" in forAll(timestamps(min = Instant.now().plus(24, HOURS).plus(1, SECONDS))) { value => val Left(exception) = CommittedDate.from(value).map(_.value) exception shouldBe an[IllegalArgumentException] exception.getMessage should startWith(s"${CommittedDate.typeName} has to be <= ") } - } } } @@ -182,11 +177,10 @@ class EventBodySpec extends AnyWordSpec with ScalaCheckPropertyChecks with shoul EventBody shouldBe an[NonBlank[_]] } - "be instantiatable from any non-blank string" in { + "be instantiatable from any non-blank string" in forAll(nonEmptyStrings()) { body => EventBody.from(body).map(_.value) shouldBe Right(body) } - } } "decodeAs" should { @@ -300,13 +294,12 @@ class EventProcessingTimeSpec extends AnyWordSpec with ScalaCheckPropertyChecks EventProcessingTime shouldBe an[DurationNotNegative[_]] } - "be instantiatable from any non negative finite durations" in { + "be instantiatable from any non negative finite durations" in forAll(notNegativeJavaDurations) { body => EventProcessingTime.from(body).map(_.value) shouldBe Right(body) } - } - "throw an error if it is instantiated with a negative finite duration" in { + "throw an error if it is instantiated with a negative finite duration" in forAll( javaDurations(min = -2000, max = -1) ) { duration => @@ -314,28 +307,25 @@ class EventProcessingTimeSpec extends AnyWordSpec with ScalaCheckPropertyChecks exception shouldBe an[IllegalArgumentException] exception.getMessage should startWith(s"${EventProcessingTime.typeName} cannot have a negative duration") } - } } "*" should { - "multiply the given processing time by the given value" in { + "multiply the given processing time by the given value" in forAll(eventProcessingTimes, positiveInts()) { (processingTime, multiplier) => processingTime * multiplier shouldBe EventProcessingTime( JavaDuration.ofMillis(processingTime.value.toMillis * multiplier.value) ) } - } } "/" should { - "divide the given processing time by the given value" in { + "divide the given processing time by the given value" in forAll(eventProcessingTimes, positiveInts()) { (processingTime, multiplier) => processingTime / multiplier shouldBe EventProcessingTime( JavaDuration.ofMillis(processingTime.value.toMillis / multiplier.value) ) } - } } } diff --git a/graph-commons/src/test/scala/io/renku/http/rest/linksSpec.scala b/graph-commons/src/test/scala/io/renku/http/rest/linksSpec.scala index 971e5853fa..3a0285c37c 100644 --- a/graph-commons/src/test/scala/io/renku/http/rest/linksSpec.scala +++ b/graph-commons/src/test/scala/io/renku/http/rest/linksSpec.scala @@ -32,17 +32,15 @@ class linksSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "links" should { - "be serializable to Json" in { + "be serializable to Json" in forAll { links: Links => links.asJson shouldBe Json.arr(links.links.map(_.asJson).toList: _*) } - } - "be deserializable from Json" in { + "be deserializable from Json" in forAll { links: Links => Json.arr(links.links.map(_.asJson).toList: _*).as[Links] shouldBe Right(links) } - } "be deserializable from Json with no 'method'" in { val link = linkObjects.generateOne.copy(method = Links.Method.GET) @@ -60,7 +58,7 @@ class linksSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "_links" should { - "create a Json object with '_links' property and the given Rel and Href tuples as the value" in { + "create a Json object with '_links' property and the given Rel and Href tuples as the value" in forAll { links: Links => val relHrefTuple +: relHrefTuples = links.links.map { case Link(rel, href, _) => rel -> href @@ -70,23 +68,20 @@ class linksSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "_links": ${Links(links.links.map(_.copy(method = Links.Method.GET)))} }""" } - } - "create a Json object with '_links' property and the given Links as the value" in { + "create a Json object with '_links' property and the given Links as the value" in forAll { links: Links => _links(links) shouldBe json"""{ "_links": $links }""" } - } - "create a Json object with '_links' property when links given as varargs" in { + "create a Json object with '_links' property when links given as varargs" in forAll { links: Links => _links(links.links.head, links.links.tail: _*) shouldBe json"""{ "_links": $links }""" } - } } "get" should { diff --git a/graph-commons/src/test/scala/io/renku/http/server/HttpServerSpec.scala b/graph-commons/src/test/scala/io/renku/http/server/HttpServerSpec.scala index c4aad97d2e..4af160a39e 100644 --- a/graph-commons/src/test/scala/io/renku/http/server/HttpServerSpec.scala +++ b/graph-commons/src/test/scala/io/renku/http/server/HttpServerSpec.scala @@ -41,7 +41,7 @@ class HttpServerSpec "run" should { - "create an http server to serve the given routes" in { + "create an http server to serve the given routes" in client .run(Request[IO](Method.GET, baseUri / "resource")) .use { response => @@ -50,9 +50,8 @@ class HttpServerSpec _ = response.status shouldBe Status.Ok } yield () } - } - "create an http server which responds with NOT_FOUND and JSON body for non-existing resource" in { + "create an http server which responds with NOT_FOUND and JSON body for non-existing resource" in client .run(Request[IO](Method.GET, baseUri / "non-existing")) .use { response => @@ -62,7 +61,6 @@ class HttpServerSpec _ = response.contentType shouldBe Some(`Content-Type`(MediaType.application.json)) } yield () } - } } private lazy val port = httpPorts.generateOne diff --git a/graph-commons/src/test/scala/io/renku/json/JsonOpsSpec.scala b/graph-commons/src/test/scala/io/renku/json/JsonOpsSpec.scala index af5d7db0c3..95bd0b1e79 100644 --- a/graph-commons/src/test/scala/io/renku/json/JsonOpsSpec.scala +++ b/graph-commons/src/test/scala/io/renku/json/JsonOpsSpec.scala @@ -33,7 +33,7 @@ class JsonOpsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. "addIfDefined extension method" should { - "be adding the property to the JSON being called on if the given value is defined" in { + "be adding the property to the JSON being called on if the given value is defined" in forAll(nonBlankStrings(), nonBlankStrings()) { (property, value) => val newJson = existingJson addIfDefined (property.value -> Some(value.toString())) @@ -42,7 +42,6 @@ class JsonOpsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. property.value -> value.toString().asJson ) } - } "not be adding the property to the JSON being called on if the given value is empty" in { diff --git a/graph-commons/src/test/scala/io/renku/triplesstore/DatasetConnectionConfigSpec.scala b/graph-commons/src/test/scala/io/renku/triplesstore/DatasetConnectionConfigSpec.scala index 21db1875ab..58112c005b 100644 --- a/graph-commons/src/test/scala/io/renku/triplesstore/DatasetConnectionConfigSpec.scala +++ b/graph-commons/src/test/scala/io/renku/triplesstore/DatasetConnectionConfigSpec.scala @@ -35,7 +35,7 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe "AdminConnectionConfig.apply" should { - "read 'services.fuseki.url', 'services.fuseki.admin.username' and 'services.fuseki.admin.password' to instantiate the AdminConnectionConfig" in { + "read 'services.fuseki.url', 'services.fuseki.admin.username' and 'services.fuseki.admin.password' to instantiate the AdminConnectionConfig" in forAll(adminConnectionConfigs) { storeConfig => val config = ConfigFactory.parseMap( Map( @@ -57,7 +57,6 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe actual.authCredentials.username shouldBe storeConfig.authCredentials.username actual.authCredentials.password shouldBe storeConfig.authCredentials.password } - } "fail if url invalid" in { val config = ConfigFactory.parseMap( @@ -127,7 +126,7 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe credentials <- basicAuthCredentials } yield ProjectsConnectionConfig(url, credentials) - "read 'services.fuseki.url', 'services.fuseki.renku.username' and 'services.fuseki.renku.password' to instantiate the RenkuConnectionConfig" in { + "read 'services.fuseki.url', 'services.fuseki.renku.username' and 'services.fuseki.renku.password' to instantiate the RenkuConnectionConfig" in forAll(projectsConnectionConfig) { storeConfig => val config = ConfigFactory.parseMap( Map( @@ -150,7 +149,6 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe actual.authCredentials.username shouldBe storeConfig.authCredentials.username actual.authCredentials.password shouldBe storeConfig.authCredentials.password } - } "fail if url invalid" in { val config = ConfigFactory.parseMap( @@ -220,7 +218,7 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe credentials <- basicAuthCredentials } yield MigrationsConnectionConfig(url, credentials) - "read 'services.fuseki.url', 'services.fuseki.admin.username' and 'services.fuseki.admin.password' to instantiate the RenkuConnectionConfig" in { + "read 'services.fuseki.url', 'services.fuseki.admin.username' and 'services.fuseki.admin.password' to instantiate the RenkuConnectionConfig" in forAll(migrationsConnectionConfig) { storeConfig => val config = ConfigFactory.parseMap( Map( @@ -243,6 +241,5 @@ class DatasetConnectionConfigSpec extends AnyWordSpec with ScalaCheckPropertyChe actual.authCredentials.username shouldBe storeConfig.authCredentials.username actual.authCredentials.password shouldBe storeConfig.authCredentials.password } - } } } diff --git a/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/create/MultipartRequestCodec.scala b/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/create/MultipartRequestCodec.scala index 1681f23e37..d236dabd4e 100644 --- a/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/create/MultipartRequestCodec.scala +++ b/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/create/MultipartRequestCodec.scala @@ -63,7 +63,7 @@ private trait MultipartRequestEncoder[F[_]] { } private object MultipartRequestEncoder { - def apply[F[_]: Sync]: MultipartRequestEncoder[F] = forSync(implicitly[Sync[F]]) + def apply[F[_]: Sync]: MultipartRequestEncoder[F] = forSync(implicitly[Sync[F]]) implicit def forSync[F[_]](implicit F: Sync[F]): MultipartRequestEncoder[F] = new MultipartRequestEncoderImpl[F] } @@ -96,7 +96,7 @@ private trait MultipartRequestDecoder[F[_]] { } private object MultipartRequestDecoder { - def apply[F[_]: Async]: MultipartRequestDecoder[F] = forAsync[F] + def apply[F[_]: Async]: MultipartRequestDecoder[F] = forAsync[F] implicit def forAsync[F[_]](implicit F: Async[F]): MultipartRequestDecoder[F] = new MultipartRequestDecoderImpl[F] } diff --git a/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodec.scala b/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodec.scala index 5ff9913eb6..87bbbad282 100644 --- a/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodec.scala +++ b/knowledge-graph/src/main/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodec.scala @@ -59,7 +59,7 @@ private trait MultipartRequestEncoder[F[_]] { } private object MultipartRequestEncoder { - def apply[F[_]: Sync]: MultipartRequestEncoder[F] = forSync(implicitly[Sync[F]]) + def apply[F[_]: Sync]: MultipartRequestEncoder[F] = forSync(implicitly[Sync[F]]) implicit def forSync[F[_]](implicit F: Sync[F]): MultipartRequestEncoder[F] = new MultipartRequestEncoderImpl[F] } @@ -106,7 +106,7 @@ private trait MultipartRequestDecoder[F[_]] { } private object MultipartRequestDecoder { - def apply[F[_]: Async]: MultipartRequestDecoder[F] = forAsync[F] + def apply[F[_]: Async]: MultipartRequestDecoder[F] = forAsync[F] implicit def forAsync[F[_]](implicit F: Async[F]): MultipartRequestDecoder[F] = new MultipartRequestDecoderImpl[F] } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/BaseDetailsFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/BaseDetailsFinderSpec.scala index 1adea5d60e..693cf972ad 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/BaseDetailsFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/BaseDetailsFinderSpec.scala @@ -73,7 +73,7 @@ class BaseDetailsFinderSpec extends AnyWordSpec with ScalaCheckPropertyChecks wi "modified dataset decoder" should { - "decode result-set with a blank description, url, sameAs, and images to a Dataset object" in { + "decode result-set with a blank description, url, sameAs, and images to a Dataset object" in forAll( anyRenkuProjectEntities.addDatasetAndModification(datasetEntities(provenanceNonModified)), blankStrings() @@ -90,7 +90,6 @@ class BaseDetailsFinderSpec extends AnyWordSpec with ScalaCheckPropertyChecks wi .some .asRight } - } } private def nonModifiedToResultSet(project: testentities.RenkuProject, diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/CreatorsFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/CreatorsFinderSpec.scala index 25e6c4bd32..a8f61b7f95 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/CreatorsFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/CreatorsFinderSpec.scala @@ -36,21 +36,19 @@ class CreatorsFinderSpec extends AnyWordSpec with ScalaCheckPropertyChecks with "dataset creator decoder" should { - "decode result-set with a blank affiliation to a DatasetCreator object" in { + "decode result-set with a blank affiliation to a DatasetCreator object" in forAll(personEmails, personNames, blankStrings()) { (email, name, affiliation) => resultSet(email, name, affiliation).as[NonEmptyList[DatasetCreator]] shouldBe Right { NonEmptyList.of(DatasetCreator(Some(email), name, None)) } } - } - "decode result-set with a non-blank affiliation to a DatasetCreator object" in { + "decode result-set with a non-blank affiliation to a DatasetCreator object" in forAll(personEmails, personNames, personAffiliations) { (email, name, affiliation) => resultSet(email, name, affiliation.toString).as[NonEmptyList[DatasetCreator]] shouldBe Right { NonEmptyList.of(DatasetCreator(Some(email), name, Some(affiliation))) } } - } } private def resultSet(email: Email, name: Name, blank: String) = json"""{ diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/EndpointDocsSpec.scala index c0fbaada81..2ff856c13f 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/EndpointDocsSpec.scala @@ -32,9 +32,8 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } private implicit lazy val renkuApiUrl: renku.ApiUrl = renkuApiUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/RequestedDatasetSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/RequestedDatasetSpec.scala index 0eeefb941a..4460e93ccc 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/RequestedDatasetSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/datasets/details/RequestedDatasetSpec.scala @@ -44,8 +44,7 @@ class RequestedDatasetSpec "External sameAs" -> RequestedDataset(datasetExternalSameAs.generateOne) ) - "url codec" should { - + "url codec" should forAll(idTypeScenarios) { (idType, id) => s"url encode and decode Dataset identifier of $idType type" in { @@ -54,14 +53,11 @@ class RequestedDatasetSpec RequestedDataset.unapply(encoded.encoded).value shouldBe id } } - } - - "json codec" should { + "json codec" should forAll(idTypeScenarios) { (idType, id) => s"json encode and decode Dataset identifier of $idType type" in { id.asJson.hcursor.as[RequestedDataset].value shouldBe id } } - } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/docs/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/docs/EndpointDocsSpec.scala index 4967bc0a8e..59413ed2a0 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/docs/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/docs/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/EndpointDocsSpec.scala index 9fbb985b41..6e61292b86 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/EndpointDocsSpec.scala @@ -30,9 +30,8 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } private implicit lazy val renkuUrl: renku.ApiUrl = renkuApiUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/currentuser/recentlyviewed/EndpointSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/currentuser/recentlyviewed/EndpointSpec.scala index 6c5d12f2dc..2baf67e6af 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/currentuser/recentlyviewed/EndpointSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/entities/currentuser/recentlyviewed/EndpointSpec.scala @@ -91,7 +91,7 @@ class EndpointSpec "getRecentlyViewedEntities" should { - "respond with OK and the found entities" in { + "respond with OK and the found entities" in forAll(Generators.listOf(modelEntities)) { results => val finder = makeFinderFor(IO(results)) @@ -104,7 +104,6 @@ class EndpointSpec response.as[Json].unsafeRunSync() shouldMatchTo results.asJson } - } "respond with INTERNAL_SERVER_ERROR when finding entities fails" in { val exception = new Exception("boom") diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/gitlab/UserInfoFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/gitlab/UserInfoFinderSpec.scala index b3ad4e1c0e..ecb59d1a84 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/gitlab/UserInfoFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/gitlab/UserInfoFinderSpec.scala @@ -71,10 +71,9 @@ class UserInfoFinderSpec .asserting(_ shouldBe Some(userInfo)) } - it should "return no user info if GL returns 404 NOT_FOUND" in { + it should "return no user info if GL returns 404 NOT_FOUND" in mapResponse(NotFound, Request[IO](), Response[IO](NotFound)) .asserting(_ shouldBe None) - } private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]] private lazy val finder = new UserInfoFinderImpl[IO] diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/ontology/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/ontology/EndpointDocsSpec.scala index 17ed4b8075..fd58575c52 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/ontology/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/ontology/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/EndpointDocsSpec.scala index cbe36024c3..f5a4b35aa4 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(EndpointDocs.path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/NamespaceFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/NamespaceFinderSpec.scala index 9491470c1d..9f9aa6aa2f 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/NamespaceFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/create/NamespaceFinderSpec.scala @@ -89,9 +89,8 @@ class NamespaceFinderSpec } NotFound :: Forbidden :: Nil foreach { status => - it should s"return None if GL returns $status" in { + it should s"return None if GL returns $status" in mapResponse(status, Request[IO](), Response[IO](status)).asserting(_ shouldBe None) - } } private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]] diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/EndpointDocsSpec.scala index c851054636..d7f0de2e24 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/EndpointDocsSpec.scala @@ -30,9 +30,8 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } private implicit lazy val renkuUrl: renku.ApiUrl = renkuApiUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/ProjectDatasetSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/ProjectDatasetSpec.scala index 469d9f702c..eff1245483 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/ProjectDatasetSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/ProjectDatasetSpec.scala @@ -34,11 +34,10 @@ import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class ProjectDatasetSpec extends AnyFlatSpec with should.Matchers with ScalaCheckPropertyChecks with ImageUrisEncoder { - it should "encode to JSON" in { + it should "encode to JSON" in forAll(projectDatasetGen) { datasets => datasets.asJson(ProjectDataset.encoder(projectSlug)) shouldBe toJson(datasets) } - } private lazy val toJson: ProjectDataset => Json = { case ProjectDataset(id, originalId, name, slug, createdOrPublished, _, Left(sameAs), images) => diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/tags/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/tags/EndpointDocsSpec.scala index fd3925d32b..837c6af2db 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/tags/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/datasets/tags/EndpointDocsSpec.scala @@ -30,9 +30,8 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } private implicit lazy val renkuUrl: renku.ApiUrl = renkuApiUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/delete/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/delete/EndpointDocsSpec.scala index 37c93f231c..cd98ff27ff 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/delete/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/delete/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(EndpointDocs.path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/EndpointDocsSpec.scala index 0508e6891e..5e975434d1 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/EndpointDocsSpec.scala @@ -30,10 +30,9 @@ class EndpointDocsSpec extends AnyWordSpec { implicit val gitLabUrl: GitLabUrl = EntitiesGenerators.gitLabUrl "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath( new EndpointDocsImpl(new ProjectJsonEncoderImpl(renkuApiUrls.generateOne), ProjectJsonLDEncoder).path ) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonEncoderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonEncoderSpec.scala index c315a334e3..4145cab8df 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonEncoderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonEncoderSpec.scala @@ -49,7 +49,7 @@ class ProjectJsonEncoderSpec extends AnyWordSpec with should.Matchers with Scala "encode" should { - "convert the model.Project object to Json" in { + "convert the model.Project object to Json" in forAll { project: Project => val json = encoder encode project @@ -62,7 +62,6 @@ class ProjectJsonEncoderSpec extends AnyWordSpec with should.Matchers with Scala ) } - } } private lazy val renkuApiUrl: renku.ApiUrl = renkuApiUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonLDEncoderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonLDEncoderSpec.scala index dab855afae..47c609a200 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonLDEncoderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/ProjectJsonLDEncoderSpec.scala @@ -36,11 +36,10 @@ class ProjectJsonLDEncoderSpec extends AnyWordSpec with should.Matchers with Sca "encode" should { - "convert the model.Project object to Json" in { + "convert the model.Project object to Json" in forAll { project: Project => (ProjectJsonLDEncoder encode project).cursor.as(decoder(project)) shouldBe project.asRight } - } } private def decoder(project: Project): JsonLDDecoder[Project] = JsonLDDecoder.entity(entities.Project.entityTypes) { diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/modelSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/modelSpec.scala index 5a7c4d0e34..8116649133 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/modelSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/details/modelSpec.scala @@ -33,12 +33,11 @@ class modelSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "SshUrl" should { - "instantiate for valid absolute ssh urls" in { + "instantiate for valid absolute ssh urls" in forAll(nonEmptyList(nonBlankStrings()), projectSlugs) { (hostParts, projectSlug) => val url = s"git@${hostParts.toList.mkString(".")}:$projectSlug.git" SshUrl.from(url).map(_.value) shouldBe Right(url) } - } "fail instantiation for non-ssh urls" in { val url = s"${gitLabUrls.generateOne}/${projectSlugs.generateOne}.git" diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/EndpointDocsSpec.scala index 7e61968fae..aa11dd974a 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(EndpointDocs.path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/LineageSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/LineageSpec.scala index eeee1c4a50..f20f49155a 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/LineageSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/LineageSpec.scala @@ -39,7 +39,7 @@ class LineageSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. "from" should { - "succeed if all the edges have nodes definitions" in { + "succeed if all the edges have nodes definitions" in forAll(edgesSets) { edgesSet => val nodesSet = generateNodes(edgesSet) val Right(Lineage(actualEdges, actualNodes)) = Lineage.from[EitherLineage](edgesSet, nodesSet) @@ -47,7 +47,6 @@ class LineageSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. actualEdges shouldBe edgesSet actualNodes shouldBe nodesSet } - } "fail if there are edges with no nodes definitions" in { val edgesSet = edgesSets.generateOne @@ -96,21 +95,19 @@ class LineageSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should. "getNode" should { - "return a Node if there is one with the given location" in { + "return a Node if there is one with the given location" in forAll { lineage: Lineage => val node = Random.shuffle(lineage.nodes.toList).head lineage.getNode(node.location) shouldBe node.some } - } - "return None if no node are found with the given location" in { + "return None if no node are found with the given location" in forAll { lineage: Lineage => val location = nodeLocations.generateOne lineage.getNode(location) shouldBe None } - } } private lazy val edgesSets: Gen[Set[Edge]] = for { diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/NodeIdSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/NodeIdSpec.scala index 1130f647d7..3a19dba379 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/NodeIdSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/files/lineage/NodeIdSpec.scala @@ -31,10 +31,9 @@ class NodeIdSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "showAs[RdfResource]" should { - "wrap the Node.Id in <>" in { + "wrap the Node.Id in <>" in forAll { resourceId: Node.Id => resourceId.showAs[RdfResource] shouldBe s"<${URIref.encode(resourceId.value)}>" } - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/images/ImageUrisEncoderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/images/ImageUrisEncoderSpec.scala index 771e2c14af..592cb1b8bd 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/images/ImageUrisEncoderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/images/ImageUrisEncoderSpec.scala @@ -35,11 +35,10 @@ class ImageUrisEncoderSpec with ScalaCheckPropertyChecks with ImageUrisEncoder { - it should "encode the List[ImageUri] -> slug tuples to JSON" in { + it should "encode the List[ImageUri] -> slug tuples to JSON" in forAll(imageUris.toGeneratorOfList()) { images => (images -> projectSlug).asJson shouldBe imagesEncoder(images) } - } private lazy val imagesEncoder: Encoder[List[ImageUri]] = Encoder.instance[List[ImageUri]] { images => Json.fromValues( diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/BranchProtectionCheckSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/BranchProtectionCheckSpec.scala index 7861e63e3f..d11971760f 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/BranchProtectionCheckSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/BranchProtectionCheckSpec.scala @@ -144,10 +144,9 @@ class BranchProtectionCheckSpec .asserting(_ shouldBe Nil) } - it should "return an empty list if GL returns 404 NOT_FOUND" in { + it should "return an empty list if GL returns 404 NOT_FOUND" in mapResponse(NotFound, Request[IO](), Response[IO](NotFound)) .asserting(_ shouldBe Nil) - } private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]] private lazy val finder = new BranchProtectionCheckImpl[IO] diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/EndpointDocsSpec.scala index cc537c823f..359d651385 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/EndpointDocsSpec.scala @@ -25,8 +25,7 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(EndpointDocs.path) - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodecSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodecSpec.scala index db82819675..76e3249558 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodecSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/MultipartRequestCodecSpec.scala @@ -40,9 +40,8 @@ class MultipartRequestCodecSpec private val codec: MultipartRequestCodec[IO] = MultipartRequestCodec[IO] forAll(projectUpdatesGen, countingGen) { (updates, cnt) => - it should s"decode/encode the multipart request with multiple values #$cnt" in { + it should s"decode/encode the multipart request with multiple values #$cnt" in (codec.encode(updates) >>= (MultipartRequestCodec[IO].decode(_))).asserting(_ shouldBe updates) - } } it should "decode/encode the multipart request for empty updates" in { diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectGitUrlFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectGitUrlFinderSpec.scala index b905e92d9c..e1b6e40962 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectGitUrlFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectGitUrlFinderSpec.scala @@ -73,10 +73,9 @@ class ProjectGitUrlFinderSpec .asserting(_ shouldBe Some(gitUrl)) } - it should "return no gitUrl if GL returns 404 NOT_FOUND" in { + it should "return no gitUrl if GL returns 404 NOT_FOUND" in mapResponse(NotFound, Request[IO](), Response[IO](NotFound)) .asserting(_ shouldBe None) - } private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]] private lazy val finder = new ProjectGitUrlFinderImpl[IO] diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectUpdatesSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectUpdatesSpec.scala index f9d6d9b7de..4af30b9b57 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectUpdatesSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/ProjectUpdatesSpec.scala @@ -32,61 +32,54 @@ class ProjectUpdatesSpec extends AnyWordSpec with should.Matchers with ScalaChec "onlyGLUpdateNeeded" should { - "return true if at least image and/or visibility is updated but not desc and keywords" in { + "return true if at least image and/or visibility is updated but not desc and keywords" in forAll( projectUpdatesGen .suchThat(u => (u.newImage orElse u.newVisibility).isDefined) .map(_.copy(newDescription = None, newKeywords = None)) )(_.onlyGLUpdateNeeded shouldBe true) - } - "return false otherwise" in { + "return false otherwise" in forAll( projectUpdatesGen .suchThat(u => (u.newDescription orElse u.newKeywords).isDefined) )(_.onlyGLUpdateNeeded shouldBe false) - } } "glUpdateNeeded" should { - "return true if at least image and/or visibility is updated" in { + "return true if at least image and/or visibility is updated" in forAll( projectUpdatesGen .suchThat(u => (u.newImage orElse u.newVisibility).isDefined) )(_.glUpdateNeeded shouldBe true) - } - "return false otherwise" in { + "return false otherwise" in forAll(projectUpdatesGen.map(_.copy(newImage = None, newVisibility = None)))( _.glUpdateNeeded shouldBe false ) - } } "coreUpdateNeeded" should { - "return true if at least description and/or keywords is updated" in { + "return true if at least description and/or keywords is updated" in forAll( projectUpdatesGen .suchThat(u => (u.newDescription orElse u.newKeywords).isDefined) )(_.coreUpdateNeeded shouldBe true) - } - "return false otherwise" in { + "return false otherwise" in forAll(projectUpdatesGen.map(_.copy(newDescription = None, newKeywords = None)))( _.coreUpdateNeeded shouldBe false ) - } } "JSON encode/decode" should { - "encode/decode all standard cases" in { + "encode/decode all standard cases" in forAll(projectUpdatesGen.suchThat(_.newImage.isEmpty)) { updates => updates.asJson.hcursor.as[ProjectUpdates].value shouldBe updates } - } "lack of the description property to be considered as no-op for the property" in { diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/TGUpdatesFinderSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/TGUpdatesFinderSpec.scala index 1754e22b01..9e1ddd5e7a 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/TGUpdatesFinderSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/TGUpdatesFinderSpec.scala @@ -95,23 +95,21 @@ class TGUpdatesFinderSpec extends AnyWordSpec with should.Matchers with TryValue "map the Core updatable values from the Project updates " + "if there are only Core updatable values and " + - "it's confirmed Core pushed to the default branch" in { + "it's confirmed Core pushed to the default branch" in + forAll(projectUpdatesGen.suchThat(_.coreUpdateNeeded).map(_.copy(newImage = None, newVisibility = None))) { + updates => + val branch = branches.generateOne - forAll(projectUpdatesGen.suchThat(_.coreUpdateNeeded).map(_.copy(newImage = None, newVisibility = None))) { - updates => - val branch = branches.generateOne - - findTGProjectUpdates(updates, - maybeGLUpdatedProject = None, - maybeDefaultBranch = DefaultBranch.Unprotected(branch).some, - corePushBranch = branch - ).success.value shouldBe TGProjectUpdates( - newDescription = updates.newDescription, - newImages = None, - newKeywords = updates.newKeywords, - newVisibility = None - ) - } + findTGProjectUpdates(updates, + maybeGLUpdatedProject = None, + maybeDefaultBranch = DefaultBranch.Unprotected(branch).some, + corePushBranch = branch + ).success.value shouldBe TGProjectUpdates( + newDescription = updates.newDescription, + newImages = None, + newKeywords = updates.newKeywords, + newVisibility = None + ) } "return an empty TG updates object " + diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/UpdateFailuresSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/UpdateFailuresSpec.scala index 136f6f366b..da5adaec44 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/UpdateFailuresSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/projects/update/UpdateFailuresSpec.scala @@ -35,7 +35,7 @@ class UpdateFailuresSpec extends AnyWordSpec with should.Matchers with ScalaChec "corePushedToNonDefaultBranch" should { - "return a Conflict Failure with a JSON message containing the branch Core pushed to" in { + "return a Conflict Failure with a JSON message containing the branch Core pushed to" in forAll(tgUpdatesGen, defaultBranchInfos.toGeneratorOfOptions, branches) { (tgUpdates, maybeDefaultBranch, corePushBranch) => val failure = UpdateFailures.corePushedToNonDefaultBranch(tgUpdates, maybeDefaultBranch, corePushBranch) @@ -58,6 +58,5 @@ class UpdateFailuresSpec extends AnyWordSpec with should.Matchers with ScalaChec }""" } } - } } } diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/GitLabIdSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/GitLabIdSpec.scala index 3a4fb2c31c..24d9743817 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/GitLabIdSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/GitLabIdSpec.scala @@ -30,11 +30,10 @@ class GitLabIdSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope "unapply" should { - "convert valid eventId as string to EventId" in { + "convert valid eventId as string to EventId" in forAll { id: persons.GitLabId => binders.GitLabId.unapply(id.toString) shouldBe Some(id) } - } "return None if string value is not a valid GitLabId" in { binders.GitLabId.unapply(nonEmptyStrings().generateOne) shouldBe None diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/projects/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/projects/EndpointDocsSpec.scala index bca741bcc7..72bb4c3076 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/projects/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/users/projects/EndpointDocsSpec.scala @@ -30,9 +30,8 @@ class EndpointDocsSpec extends AnyWordSpec { "path" should { - "return a valid Path object" in { + "return a valid Path object" in validatePath(new EndpointDocsImpl().path) - } } private implicit lazy val renkuUrl: RenkuUrl = renkuUrls.generateOne diff --git a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/version/EndpointDocsSpec.scala b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/version/EndpointDocsSpec.scala index 9c9f02f798..4f812b5212 100644 --- a/knowledge-graph/src/test/scala/io/renku/knowledgegraph/version/EndpointDocsSpec.scala +++ b/knowledge-graph/src/test/scala/io/renku/knowledgegraph/version/EndpointDocsSpec.scala @@ -24,7 +24,6 @@ import org.scalatest.matchers.should class EndpointDocsSpec extends AnyFlatSpec with should.Matchers { - it should "return a valid Path object" in { + it should "return a valid Path object" in validatePath(EndpointDocs.path) - } } diff --git a/project-auth/src/test/scala/io/renku/projectauth/ProjectAuthServiceSpec.scala b/project-auth/src/test/scala/io/renku/projectauth/ProjectAuthServiceSpec.scala index 42b9545891..b715230da7 100644 --- a/project-auth/src/test/scala/io/renku/projectauth/ProjectAuthServiceSpec.scala +++ b/project-auth/src/test/scala/io/renku/projectauth/ProjectAuthServiceSpec.scala @@ -118,7 +118,7 @@ class ProjectAuthServiceSpec } } - it should "search by member id" in { + it should "search by member id" in withProjectAuthServiceData(randomData(1, suchThat = _.members.nonEmpty)).use { case (s, original) => for { found <- s.getAll(QueryFilter.all.withMember(original.head.members.head.gitLabId)).compile.lastOrError @@ -134,5 +134,4 @@ class ProjectAuthServiceSpec _ = nf shouldBe None } yield () } - } } diff --git a/project-auth/src/test/scala/io/renku/projectauth/util/SparqlSnippetsSpec.scala b/project-auth/src/test/scala/io/renku/projectauth/util/SparqlSnippetsSpec.scala index 417d56e75f..1f5820c277 100644 --- a/project-auth/src/test/scala/io/renku/projectauth/util/SparqlSnippetsSpec.scala +++ b/project-auth/src/test/scala/io/renku/projectauth/util/SparqlSnippetsSpec.scala @@ -168,7 +168,7 @@ class SparqlSnippetsSpec } } - it should "update visibility on a project" in { + it should "update visibility on a project" in clientAndData.use { case (client, data) => val el = data.head val otherVis = (Visibility.all - el.visibility).head @@ -183,13 +183,12 @@ class SparqlSnippetsSpec _ = r.visibility shouldBe otherVis } yield () } - } val allVisibilities = (Visibility.all.map(Set(_)) ++ Visibility.all.toList.permutations.map(_.tail.toSet)) ++ Set(Visibility.all) allVisibilities.foreach { givenVisibility => - it should s"select projects with given visibility $givenVisibility" in { + it should s"select projects with given visibility $givenVisibility" in clientAndData.use { case (client, data) => for { existingUser <- IO(selectUserFrom(data).generateSome) @@ -201,10 +200,9 @@ class SparqlSnippetsSpec _ = found shouldBe expected } yield () } - } } - it should "select projects given a member" in { + it should "select projects given a member" in clientAndData.use { case (client, data) => for { existingUser <- IO(selectUserFrom(data).generateOne) @@ -224,7 +222,6 @@ class SparqlSnippetsSpec _ = r2 shouldBe Nil } yield () } - } def projectFilter(user: Option[persons.GitLabId], givenVisibility: Set[Visibility])(p: ProjectAuthData): Boolean = givenVisibility.contains(p.visibility) && (p.visibility match { diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliActivitySpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliActivitySpec.scala index 2fe3ed15d4..dca684b4c4 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliActivitySpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliActivitySpec.scala @@ -42,17 +42,15 @@ class CliActivitySpec private val activityGen = ActivityGenerators.activityGen(Instant.EPOCH) "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(activityGen) { cliActivity => assertCompatibleCodec(cliActivity) } - } - "work on multiple items" in { + "work on multiple items" in forAll(activityGen, activityGen) { (act1, act2) => assertCompatibleCodec(act1, act2) } - } "fail if there is no Agent entity" in { import io.renku.jsonld.syntax._ diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliAssociationSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliAssociationSpec.scala index efb0b50418..ac8b4cb5a7 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliAssociationSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliAssociationSpec.scala @@ -39,15 +39,13 @@ class CliAssociationSpec private val associationGen = AssociationGenerators.associationGen(Instant.EPOCH) "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(associationGen) { cliAssoc => assertCompatibleCodec(cliAssoc) } - } - "work on multiple items" in { + "work on multiple items" in forAll(associationGen, associationGen) { (cliAssoc1, cliAssoc2) => assertCompatibleCodec(cliAssoc1, cliAssoc2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandInputSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandInputSpec.scala index e719ba71d7..21afe3ed27 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandInputSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandInputSpec.scala @@ -37,15 +37,13 @@ class CliCommandInputSpec private val commandInputGen = CommandParameterGenerators.commandInputGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(commandInputGen) { cliParam => assertCompatibleCodec(cliParam) } - } - "work on multiple items" in { + "work on multiple items" in forAll(commandInputGen, commandInputGen) { (cliParam1, cliParam2) => assertCompatibleCodec(cliParam1, cliParam2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandOutputSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandOutputSpec.scala index 7548e44db0..2913de4903 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandOutputSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandOutputSpec.scala @@ -37,15 +37,13 @@ class CliCommandOutputSpec private val commandOutputGen = CommandParameterGenerators.commandOutputGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(commandOutputGen) { cliParam => assertCompatibleCodec(cliParam) } - } - "work on multiple items" in { + "work on multiple items" in forAll(commandOutputGen, commandOutputGen) { (cliParam1, cliParam2) => assertCompatibleCodec(cliParam1, cliParam2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandParameterSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandParameterSpec.scala index 485175106d..bded457900 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandParameterSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliCommandParameterSpec.scala @@ -34,16 +34,14 @@ class CliCommandParameterSpec val commandParameterGen = CommandParameterGenerators.commandParameterGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(commandParameterGen) { cliParam => assertCompatibleCodec(cliParam) } - } - "work on multiple items" in { + "work on multiple items" in forAll(commandParameterGen, commandParameterGen) { (cliParam1, cliParam2) => assertCompatibleCodec(cliParam1, cliParam2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetFileSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetFileSpec.scala index e8176828b4..08f0ac6d36 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetFileSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetFileSpec.scala @@ -36,15 +36,13 @@ class CliDatasetFileSpec private val datasetFileGen = DatasetFileGenerators.datasetFileGen(Instant.EPOCH) "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(datasetFileGen) { cliDatasetFile => assertCompatibleCodec(cliDatasetFile) } - } - "work on multiple items" in { + "work on multiple items" in forAll(datasetFileGen, datasetFileGen) { (cliFile1, cliFile2) => assertCompatibleCodec(cliFile1, cliFile2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetSpec.scala index 669d689e2e..b8c61e7d7b 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliDatasetSpec.scala @@ -40,32 +40,28 @@ class CliDatasetSpec private val datasetGen = DatasetGenerators.datasetGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(datasetGen) { cliDataset => assertCompatibleCodec(cliDataset) } - } - "be compatible with publication events" in { + "be compatible with publication events" in forAll(DatasetGenerators.datasetWithEventsGen) { cliDataset => implicit val jsonEncoder = CliDataset.flatJsonLDEncoder assertCompatibleCodec(cliDataset) } - } - "work on multiple items" in { + "work on multiple items" in forAll(datasetGen, datasetGen) { (cliDataset1, cliDataset2) => assertCompatibleCodec(cliDataset1, cliDataset2) } - } - "work on multiple items with publication events" in { + "work on multiple items with publication events" in forAll(DatasetGenerators.datasetWithEventsGen, DatasetGenerators.datasetWithEventsGen) { (cliDataset1, cliDataset2) => implicit val jsonEncoder = CliDataset.flatJsonLDEncoder assertCompatibleCodec(cliDataset1, cliDataset2) } - } "skip publicationEvents that belong to a different dataset" in { val dataset = DatasetGenerators.datasetWithEventsGen.generateOne diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliEntitySpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliEntitySpec.scala index 54b397b500..2796de8f1d 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliEntitySpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliEntitySpec.scala @@ -42,17 +42,15 @@ class CliEntitySpec private val collectionEntityGen = EntityGenerators.collectionEntityGen "entity decode/encode" should { - "be compatible" in { + "be compatible" in forAll(singleEntityGen) { cliEntity => assertCompatibleCodec(cliEntity) } - } - "work on multiple items" in { + "work on multiple items" in forAll(singleEntityGen, singleEntityGen) { (cliEntity1, cliEntity2) => assertCompatibleCodec(cliEntity1, cliEntity2) } - } "work for only a specific generation id" in { val entity1 :: entity2 :: _ = @@ -67,15 +65,13 @@ class CliEntitySpec } "collection decode/encode" should { - "be compatible" in { + "be compatible" in forAll(collectionEntityGen) { cliEntity => assertCompatibleCodec(cliEntity) } - } - "work on multiple items" in { + "work on multiple items" in forAll(collectionEntityGen, collectionEntityGen) { (cliColl1, cliColl2) => assertCompatibleCodec(cliColl1, cliColl2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliGenerationSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliGenerationSpec.scala index 7aaca0b3fa..77e56df481 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliGenerationSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliGenerationSpec.scala @@ -39,24 +39,21 @@ class CliGenerationSpec val generationGen = GenerationGenerators.generationGen() "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(generationGen) { cliGen => assertCompatibleCodec(cliGen) } - } - "work on multiple items" in { + "work on multiple items" in forAll(generationGen, generationGen) { (cliGen1, cliGen2) => assertCompatibleCodec(cliGen1, cliGen2) } - } - "work for a specific activity only" in { + "work for a specific activity only" in forAll(generationGen, generationGen) { (gen1, gen2) => val decoder = JsonLDDecoder.decodeList(CliGeneration.decoderForActivity(gen1.activityResourceId)) val result = List(gen1, gen2).asFlattenedJsonLD.cursor.as[List[CliGeneration]](decoder) result.value shouldMatchTo List(gen1) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterLinkSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterLinkSpec.scala index fe0feb6f09..d730769d71 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterLinkSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterLinkSpec.scala @@ -37,15 +37,13 @@ class CliParameterLinkSpec private val parameterLinkGen = CommandParameterGenerators.parameterLinkGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(parameterLinkGen) { cliParam => assertCompatibleCodec(cliParam) } - } - "work on multiple items" in { + "work on multiple items" in forAll(parameterLinkGen, parameterLinkGen) { (cliParam1, cliParam2) => assertCompatibleCodec(cliParam1, cliParam2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterMappingSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterMappingSpec.scala index 4baeb53e0d..c0d9375f50 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterMappingSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterMappingSpec.scala @@ -37,17 +37,15 @@ class CliParameterMappingSpec private val parameterMappingGen = CommandParameterGenerators.parameterMappingGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(parameterMappingGen) { cliParam => assertCompatibleCodec(allMappings _)(cliParam) } - } - "work on multiple items" in { + "work on multiple items" in forAll(parameterMappingGen, parameterMappingGen) { (cliParam1, cliParam2) => assertCompatibleCodec(allMappings _)(cliParam1, cliParam2) } - } } def allMappings(cliParam: CliParameterMapping): List[CliParameterMapping] = diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterValueSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterValueSpec.scala index 1b50474684..8bb179dff7 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterValueSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliParameterValueSpec.scala @@ -35,21 +35,19 @@ class CliParameterValueSpec val parameterValueGen = ParameterValueGenerators.parameterValueGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(parameterValueGen) { cliParameterValue => assertCompatibleCodec(cliParameterValue) } - } - "work on multiple items" in { + "work on multiple items" in forAll(parameterValueGen, parameterValueGen) { (cliParam1, cliParam2) => assertCompatibleCodec(cliParam1, cliParam2) } - } } "asString" should { - "return the plain value as a string " in { + "return the plain value as a string " in List("blabla".asJson -> "blabla", 124.asJson -> 124, true.asJson -> true, 12.04.asJson -> 12.04).foreach { case (jsonValue, plainValue) => val jsonLDString = @@ -79,6 +77,5 @@ class CliParameterValueSpec .fold(throw _, identity) result.value.asString shouldBe plainValue.toString } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliPersonSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliPersonSpec.scala index a25029593d..e31a627981 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliPersonSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliPersonSpec.scala @@ -41,19 +41,17 @@ class CliPersonSpec private val personGen = PersonGenerators.cliPersonGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(personGen) { cliPerson => assertCompatibleCodec(cliPerson) } - } - "work on multiple items" in { + "work on multiple items" in forAll(personGen, personGen) { (cliPerson1, cliPerson2) => assertCompatibleCodec(cliPerson1, cliPerson2) } - } - "fail when there is no name" in { + "fail when there is no name" in forAll(personGen) { person => val jsonLDPerson = JsonLD.entity( person.resourceId.asEntityId, @@ -65,7 +63,6 @@ class CliPersonSpec failure shouldBe a[DecodingFailure] failure.message shouldBe show"No name on Person ${person.resourceId}" } - } "support multiple names, picking any" in { val resourceId = RenkuTinyTypeGenerators.personNameResourceId.generateOne diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliProjectSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliProjectSpec.scala index 4e13bb3bd1..f9020c8334 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliProjectSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliProjectSpec.scala @@ -44,17 +44,15 @@ class CliProjectSpec private val projectGen = ProjectGenerators.projectGen(Instant.EPOCH) "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(projectGen) { cliProject => assertCompatibleCodec(cliProject) } - } - "work on multiple items" in { + "work on multiple items" in forAll(projectGen, projectGen) { (cliProject1, cliProject2) => assertCompatibleCodec(cliProject1, cliProject2) } - } "return a DecodingFailure when there's a Person entity that cannot be decoded" in { val project = projectGen.generateOne @@ -81,7 +79,7 @@ class CliProjectSpec "dateModified" should { - "be the max of Project's dateCreated, Plans' dateModified, Datasets' dateModified and Activities' startTime" in { + "be the max of Project's dateCreated, Plans' dateModified, Datasets' dateModified and Activities' startTime" in forAll(projectGen) { cliProject => cliProject.dateModified shouldBe projects.DateModified { ( @@ -94,6 +92,5 @@ class CliProjectSpec ).max } } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliPublicationEventSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliPublicationEventSpec.scala index ad7de4490c..4bbc4e1b13 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliPublicationEventSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliPublicationEventSpec.scala @@ -42,16 +42,14 @@ class CliPublicationEventSpec private implicit val decoder: JsonLDDecoder[CliPublicationEvent] = CliPublicationEvent.decoder(dataset) "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(entityGen) { entity => assertCompatibleCodec(entity) } - } - "work on multiple items" in { + "work on multiple items" in forAll(entityGen, entityGen) { (entity1, entity2) => assertCompatibleCodec(entity1, entity2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliSoftwareAgentSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliSoftwareAgentSpec.scala index 820d134c2c..2e37bb773d 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliSoftwareAgentSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliSoftwareAgentSpec.scala @@ -34,16 +34,14 @@ class CliSoftwareAgentSpec private val agentGen = SoftwareAgentGenerators.softwareAgentGen "decode/encode" should { - "be compatible" in { + "be compatible" in forAll(agentGen) { cliAgent => assertCompatibleCodec(cliAgent) } - } - "work on multiple items" in { + "work on multiple items" in forAll(agentGen, agentGen) { (cliAgent1, cliAgent2) => assertCompatibleCodec(cliAgent1, cliAgent2) } - } } } diff --git a/renku-cli-model/src/test/scala/io/renku/cli/model/CliStepPlanSpec.scala b/renku-cli-model/src/test/scala/io/renku/cli/model/CliStepPlanSpec.scala index 6677134af4..9134479ece 100644 --- a/renku-cli-model/src/test/scala/io/renku/cli/model/CliStepPlanSpec.scala +++ b/renku-cli-model/src/test/scala/io/renku/cli/model/CliStepPlanSpec.scala @@ -48,17 +48,15 @@ class CliStepPlanSpec private val workflowFileCompositePlanGen = PlanGenerators.workflowFileCompositePlanGen(Instant.EPOCH) "plan decode/encode" should { - "be compatible" in { + "be compatible" in forAll(planGen) { cliPlan => assertCompatibleCodec(cliPlan) } - } - "work on multiple items" in { + "work on multiple items" in forAll(planGen, planGen) { (cliPan1, cliPlan2) => assertCompatibleCodec(cliPan1, cliPlan2) } - } "work with additional types" in { val planDecoder = JsonLDDecoder.decodeList(CliPlan.jsonLDDecoderLenientTyped) @@ -79,43 +77,37 @@ class CliStepPlanSpec } "composite plan decode/encode" should { - "be compatible" in { + "be compatible" in forAll(compositePlanGen) { cliPlan => assertCompatibleCodec(allCompositePlans _)(cliPlan) } - } - "work on multiple items" in { + "work on multiple items" in forAll(compositePlanGen, compositePlanGen) { (cliPan1, cliPlan2) => assertCompatibleCodec(allCompositePlans _)(cliPan1, cliPlan2) } - } } "workflow file plan decode/encode" should { - "be compatible" in { + "be compatible" in forAll(workflowFilePlanGen) { cliPlan => assertCompatibleCodec(cliPlan) } - } - "work on multiple items" in { + "work on multiple items" in forAll(workflowFilePlanGen, workflowFilePlanGen) { (cliPan1, cliPlan2) => assertCompatibleCodec(cliPan1, cliPlan2) } - } } "workflow file composite plan decode/encode" should { - "be compatible" in { + "be compatible" in forAll(workflowFileCompositePlanGen) { cliPlan => assertCompatibleCodec(cliPlan) } - } - "work on multiple items" in { + "work on multiple items" in forAll(workflowFileCompositePlanGen, workflowFileCompositePlanGen) { (cliPan1, cliPlan2) => assertCompatibleCodec(cliPan1, cliPlan2) } - } } def allCompositePlans(in: CliCompositePlan): List[CliCompositePlan] = diff --git a/renku-core-client/src/test/scala/io/renku/core/client/NewProjectSpec.scala b/renku-core-client/src/test/scala/io/renku/core/client/NewProjectSpec.scala index 98ccdda348..416982a415 100644 --- a/renku-core-client/src/test/scala/io/renku/core/client/NewProjectSpec.scala +++ b/renku-core-client/src/test/scala/io/renku/core/client/NewProjectSpec.scala @@ -28,7 +28,7 @@ import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class NewProjectSpec extends AnyFlatSpec with should.Matchers with EitherValues with ScalaCheckPropertyChecks { - it should "encode to JSON" in { + it should "encode to JSON" in forAll(newProjectsGen) { newProject => newProject.asJson shouldBe json"""{ @@ -44,5 +44,4 @@ class NewProjectSpec extends AnyFlatSpec with should.Matchers with EitherValues "initial_branch": ${newProject.branch} }""".dropNullValues } - } } diff --git a/renku-core-client/src/test/scala/io/renku/core/client/ProjectMigrationCheckSpec.scala b/renku-core-client/src/test/scala/io/renku/core/client/ProjectMigrationCheckSpec.scala index 8f38096e34..5c9c0321e3 100644 --- a/renku-core-client/src/test/scala/io/renku/core/client/ProjectMigrationCheckSpec.scala +++ b/renku-core-client/src/test/scala/io/renku/core/client/ProjectMigrationCheckSpec.scala @@ -33,9 +33,8 @@ class ProjectMigrationCheckSpec with EitherValues with ScalaCheckPropertyChecks { - it should "decode from JSON" in { + it should "decode from JSON" in forAll { migrationCheck: ProjectMigrationCheck => migrationCheck.asJson.hcursor.as[ProjectMigrationCheck].value shouldBe migrationCheck } - } } diff --git a/renku-core-client/src/test/scala/io/renku/core/client/SchemaApiVersionsSpec.scala b/renku-core-client/src/test/scala/io/renku/core/client/SchemaApiVersionsSpec.scala index aef8859d21..5959aa3310 100644 --- a/renku-core-client/src/test/scala/io/renku/core/client/SchemaApiVersionsSpec.scala +++ b/renku-core-client/src/test/scala/io/renku/core/client/SchemaApiVersionsSpec.scala @@ -29,9 +29,8 @@ import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class SchemaApiVersionsSpec extends AnyFlatSpec with should.Matchers with EitherValues with ScalaCheckPropertyChecks { - it should "decode from JSON" in { + it should "decode from JSON" in forAll { apiVersions: SchemaApiVersions => apiVersions.asJson.hcursor.as[SchemaApiVersions].value shouldBe apiVersions } - } } diff --git a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/datasetsSpec.scala b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/datasetsSpec.scala index 0918c10d7d..fdc7544ae5 100644 --- a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/datasetsSpec.scala +++ b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/datasetsSpec.scala @@ -62,35 +62,31 @@ class datasetsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should "ImageUri" should { - "instantiate as ImageUri.Relative for relative paths" in { + "instantiate as ImageUri.Relative for relative paths" in forAll(relativePaths()) { path => val uri = ImageUri(path) uri shouldBe a[ImageUri.Relative] uri shouldBe a[RelativePathTinyType] ImageUri.from(path) shouldBe uri.asRight } - } - "instantiate as ImageUri.Absolute for absolute paths" in { + "instantiate as ImageUri.Absolute for absolute paths" in forAll(httpUrls()) { path => val uri = ImageUri(path) uri shouldBe a[ImageUri.Absolute] uri shouldBe an[UrlTinyType] ImageUri.from(path) shouldBe uri.asRight } - } - "provide an implicit Json encoder" in { + "provide an implicit Json encoder" in forAll(imageUris) { uri => uri.asJson shouldBe Json.fromString(uri.value) } - } - "provide an implicit Json decoder" in { + "provide an implicit Json decoder" in forAll(imageUris) { uri => Json.fromString(uri.value).as[ImageUri] shouldBe uri.asRight } - } } "SameAs" should { @@ -99,49 +95,44 @@ class datasetsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should datasetSameAs.generateOne shouldBe a[UrlTinyType] } - "allow to construct ExternalSameAs using the from factory" in { + "allow to construct ExternalSameAs using the from factory" in forAll(httpUrls()) { url => val sameAs = SameAs.from(url).value sameAs should (be(a[SameAs]) and be(a[ExternalSameAs])) sameAs.value shouldBe url } - } - "allow to construct InternalSameAs using the internal factory" in { + "allow to construct InternalSameAs using the internal factory" in forAll(renkuUrls) { url => val sameAs = SameAs.internal(url).value sameAs should (be(a[SameAs]) and be(a[InternalSameAs])) sameAs.value shouldBe url.value } - } } "SameAs.equals" should { - "return true for two SameAs having equal value regardless of the type - case of InternalSameAs" in { + "return true for two SameAs having equal value regardless of the type - case of InternalSameAs" in forAll { sameAs: InternalSameAs => SameAs.internal(RenkuUrl(sameAs.value)) shouldBe SameAs.from(sameAs.value) SameAs.from(sameAs.value) shouldBe SameAs.internal(RenkuUrl(sameAs.value)) } - } - "return true for two SameAs having equal value regardless of the type - case of ImportedSameAs" in { + "return true for two SameAs having equal value regardless of the type - case of ImportedSameAs" in forAll { sameAs: ExternalSameAs => SameAs.external(Refined.unsafeApply(sameAs.value)) shouldBe SameAs.from(sameAs.value) SameAs.from(sameAs.value) shouldBe SameAs.external(Refined.unsafeApply(sameAs.value)) } - } } "SameAs.hashCode" should { - "return same values for two SameAs having equal value regardless of the type" in { + "return same values for two SameAs having equal value regardless of the type" in forAll(datasetSameAs) { sameAs => SameAs.internal(RenkuUrl(sameAs.value)).map(_.hashCode()) shouldBe SameAs .external(Refined.unsafeApply(sameAs.value)) .map(_.hashCode()) } - } } "SameAs.internal" should { diff --git a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/personsSpec.scala b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/personsSpec.scala index 3d286146a1..8970d4d7e1 100644 --- a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/personsSpec.scala +++ b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/personsSpec.scala @@ -47,11 +47,10 @@ class EmailSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "instantiation" should { - "be successful for valid emails" in { + "be successful for valid emails" in forAll(emailStrings) { email => Email(email).value shouldBe email } - } "fail blank emails" in { val Left(exception) = Email.from(blankStrings().generateOne) @@ -76,11 +75,10 @@ class EmailSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Ma "extract username" should { - "return the username part from the email" in { + "return the username part from the email" in forAll { email: Email => email.extractName.value shouldBe email.value.substring(0, email.value.indexOf("@")) } - } } private implicit lazy val emailStrings: Gen[String] = { @@ -161,21 +159,19 @@ class PersonResourceIdSpec "showAs[RdfResource]" should { - "URI encode and wrap the ResourceId in <> if the id doesn't contain email" in { + "URI encode and wrap the ResourceId in <> if the id doesn't contain email" in forAll(Gen.oneOf(personGitLabResourceId, personOrcidResourceId, personNameResourceId).widen[persons.ResourceId]) { resourceId => resourceId.showAs[RdfResource] shouldBe s"<${URIref.encode(resourceId.show)}>" } - } - "encrypt the local part of the email ResourceId, URI encode it and wrap in <>" in { + "encrypt the local part of the email ResourceId, URI encode it and wrap in <>" in forAll { email: Email => val username = email.extractName.value val resourceId = ResourceId(email) resourceId.showAs[RdfResource] shouldBe s"<${resourceId.value.replace(username, URIref.encode(username))}>" } - } } } @@ -185,11 +181,10 @@ class PersonGitLabIdSpec extends AnyWordSpec with ScalaCheckPropertyChecks with "parse" should { - "return a GitLabId for valid id in String" in { + "return a GitLabId for valid id in String" in forAll(RenkuTinyTypeGenerators.personGitLabIds) { gitLabId => GitLabId.parse(gitLabId.toString) shouldBe Right(gitLabId) } - } "fail for invalid id in String" in { val value = nonBlankStrings().generateOne.value diff --git a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/plansSpec.scala b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/plansSpec.scala index 0c6cb01ac2..be35593cc9 100644 --- a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/plansSpec.scala +++ b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/plansSpec.scala @@ -40,12 +40,11 @@ class ResourceIdSpec "toIdentifier converted" should { - "be successful for valid ResourceIds" in { + "be successful for valid ResourceIds" in forAll(planIdentifiers) { id => val resourceId = plans.ResourceId(id) resourceId.as[Try, plans.Identifier].success.value shouldBe id } - } "fail for an unknown resourceIds" in { val resourceId = plans.ResourceId { diff --git a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/projectsSpec.scala b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/projectsSpec.scala index 24a34c5921..91ef90d334 100644 --- a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/projectsSpec.scala +++ b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/projectsSpec.scala @@ -41,11 +41,10 @@ class ProjectGitLabIdSpec extends AnyWordSpec with ScalaCheckPropertyChecks with "instantiation" should { - "be successful for non-negative values" in { + "be successful for non-negative values" in forAll(nonNegativeInts()) { id => GitLabId(id.value).value shouldBe id.value } - } "fail for negative ids" in { an[IllegalArgumentException] shouldBe thrownBy { @@ -65,11 +64,10 @@ class SlugSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Mat "instantiation" should { - "be successful for relative paths with min number of 2 segments" in { + "be successful for relative paths with min number of 2 segments" in forAll(relativePaths(minSegments = 2, maxSegments = 22, partsGenerator)) { path => Slug(path).value shouldBe path } - } "fail for relative paths of single segment" in { an[IllegalArgumentException] shouldBe thrownBy { @@ -91,28 +89,25 @@ class SlugSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Mat } "toPath" should { - "extract the very last path segment" in { + "extract the very last path segment" in forAll(projectNamespaces.toGeneratorOfNonEmptyList(), projectPaths) { (namespaces, path) => Slug(s"${namespaces.map(_.show).nonEmptyIntercalate("/")}/$path").toPath shouldBe path } - } } "toNamespaces" should { - "extract all the slug segments except the last one" in { + "extract all the slug segments except the last one" in forAll(projectNamespaces.toGeneratorOfNonEmptyList(), projectPaths) { (namespaces, path) => Slug(s"${namespaces.map(_.show).nonEmptyIntercalate("/")}/$path").toNamespaces shouldBe namespaces.toList } - } } "toNamespace" should { - "extract the namespace from the slug" in { + "extract the namespace from the slug" in forAll(projectNamespaces.toGeneratorOfNonEmptyList(), projectNames) { (namespaces, name) => val namespaceAsString = namespaces.map(_.show).nonEmptyIntercalate("/") Slug(s"$namespaceAsString/$name").toNamespace shouldBe Namespace(namespaceAsString) } - } } private lazy val partsGenerator = { @@ -152,8 +147,7 @@ class VisibilitySpec extends AnyWordSpec with should.Matchers with TableDrivenPr } } - "ordering" should { - + "ordering" should forAll { Table( ("in", "out", "result"), @@ -173,7 +167,6 @@ class VisibilitySpec extends AnyWordSpec with should.Matchers with TableDrivenPr implicitly[Ordering[Visibility]].compare(in, out) shouldBe result } } - } } class ProjectResourceIdSpec @@ -191,11 +184,10 @@ class ProjectResourceIdSpec "instantiation" should { - "be successful for URLs ending with a project slug" in { + "be successful for URLs ending with a project slug" in forAll(httpUrls(pathGenerator = pathGenerator)) { url => ResourceId(url).value shouldBe url } - } "fail for relative paths" in { an[IllegalArgumentException] shouldBe thrownBy { @@ -212,20 +204,18 @@ class ProjectResourceIdSpec "toProjectSlug converter" should { - "convert any Project Resource to ProjectSlug" in { + "convert any Project Resource to ProjectSlug" in forAll { (renkuUrl: RenkuUrl, projectSlug: Slug) => ResourceId(projectSlug)(renkuUrl).as[Try, Slug] shouldBe projectSlug.pure[Try] } - } } "showAs[RdfResource]" should { - "URI encode and wrap the ResourceId in <>" in { + "URI encode and wrap the ResourceId in <>" in forAll { resourceId: ResourceId => resourceId.showAs[RdfResource] shouldBe s"<${URIref.encode(resourceId.value)}>" } - } } private lazy val pathGenerator = projectSlugs.map(slug => s"projects/$slug") @@ -235,12 +225,11 @@ class GitHttpUrlSpec extends AnyWordSpec with should.Matchers with EitherValues "HttpUrl" should { - "instantiate for valid absolute git urls" in { + "instantiate for valid absolute git urls" in forAll(httpUrls(), projectSlugs) { (httpUrl, projectSlug) => val url = s"$httpUrl/$projectSlug.git" GitHttpUrl.from(url).map(_.value) shouldBe Right(url) } - } "fail instantiation for non-absolute urls" in { diff --git a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/versionsSpec.scala b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/versionsSpec.scala index a533694ae5..6d3cbe7dd0 100644 --- a/renku-model-tiny-types/src/test/scala/io/renku/graph/model/versionsSpec.scala +++ b/renku-model-tiny-types/src/test/scala/io/renku/graph/model/versionsSpec.scala @@ -31,22 +31,20 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should "from" should { - "return Right for a valid released version" in { + "return Right for a valid released version" in forAll(Generators.semanticVersions) { version => CliVersion.from(version).map(_.show) shouldBe version.asRight } - } - "return Right for a valid dev version" in { + "return Right for a valid dev version" in forAll(devVersions()) { version => CliVersion.from(version).map(_.show) shouldBe version.asRight } - } } "major, minor and bugfix" should { - "extract the relevant version parts from a released version" in { + "extract the relevant version parts from a released version" in forAll(Generators.semanticVersions) { version => val cli = CliVersion(version) val s"$major.$minor.$bugfix" = version @@ -54,9 +52,8 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should cli.minor shouldBe minor cli.bugfix shouldBe bugfix } - } - "extract the relevant version parts from a dev version" in { + "extract the relevant version parts from a dev version" in forAll(devVersions()) { version => val cli = CliVersion(version) val s"$major.$minor.$bugfix" = version @@ -64,12 +61,11 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should cli.minor shouldBe minor cli.bugfix shouldBe bugfix } - } } "ordering" should { - "consider the major only if different" in { + "consider the major only if different" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.major != version2.major) { val list = List(version1, version2) @@ -78,9 +74,8 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should else list.sorted shouldBe list.reverse } } - } - "consider the minor only if majors are the same" in { + "consider the minor only if majors are the same" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.minor != version2.minor) { val version2SameMajor = CliVersion(version2.show.replaceFirst(s"${version2.major}.", s"${version1.major}.")) @@ -91,9 +86,8 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should else list.sorted shouldBe list.reverse } } - } - "consider the bugfix only if majors and minors are the same" in { + "consider the bugfix only if majors and minors are the same" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.bugfix != version2.bugfix) { val version2SameMajorMinor = CliVersion( @@ -107,7 +101,6 @@ class versionsSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should else list.sorted shouldBe list.reverse } } - } "consider the dev part if all majors, minors and bugfix are the same" in { val semanticVersion = Generators.semanticVersions.generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/ActivitySpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/ActivitySpec.scala index 419afdfcd1..2139ca3516 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/ActivitySpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/ActivitySpec.scala @@ -45,7 +45,7 @@ class ActivitySpec "fromCli" should { - "turn CliActivity entity into the Activity object" in { + "turn CliActivity entity into the Activity object" in forAll( activityEntities(stepPlanEntities(planCommands, cliShapedPersons), cliShapedPersons)( projectCreatedDates().generateOne @@ -56,7 +56,6 @@ class ActivitySpec modelActivity shouldMatchToValid activity.to[entities.Activity] } - } "fail if there are Input Parameter Values for non-existing Usage Entities" in { val location = entityLocations.generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/AgentSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/AgentSpec.scala index e484994062..d189fec112 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/AgentSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/AgentSpec.scala @@ -36,10 +36,9 @@ class AgentSpec "fromCli" should { - "turn CLiSoftwareAgent entity into the Agent object" in { + "turn CLiSoftwareAgent entity into the Agent object" in forAll { agent: Agent => entities.Agent.fromCli(agent.to[CliSoftwareAgent]) shouldMatchToValid agent.to[entities.Agent] } - } } } diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/AssociationSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/AssociationSpec.scala index 246cc3dfa5..a4854cd199 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/AssociationSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/AssociationSpec.scala @@ -41,7 +41,7 @@ class AssociationSpec "fromCli" should { - "turn CliAssociation entity with Renku agent into the Association object" in { + "turn CliAssociation entity with Renku agent into the Association object" in forAll( activityEntities(stepPlanEntities(planCommands, cliShapedPersons), cliShapedPersons)( projectCreatedDates().generateOne @@ -50,7 +50,6 @@ class AssociationSpec val cliAssoc = association.to[CliAssociation] entities.Association.fromCli(cliAssoc) shouldMatchToValid association.to[entities.Association] } - } "turn CliAssociation entity with Person agent into the Association object" in { val (association, _, _) = generateAssociationWithPersonAgent diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetPartSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetPartSpec.scala index 4d37d33e65..7e0cbdce46 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetPartSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetPartSpec.scala @@ -47,7 +47,7 @@ class DatasetPartSpec } } - "turn CliDatasetFile with InvalidationTime entity into the DatasetPart object" in { + "turn CliDatasetFile with InvalidationTime entity into the DatasetPart object" in forAll(datasetEntities(provenanceNonModified(cliShapedPersons)).decoupledFromProject) { dataset => val datasetPart = datasetPartEntities(dataset.provenance.date.instant).generateOne val invalidationTime = invalidationTimes(datasetPart.dateCreated.value).generateOne @@ -61,7 +61,6 @@ class DatasetPartSpec _.to[entities.DatasetPart] ) } - } "fail if invalidationTime is older than the part" in { val datasetPart_ = datasetPartEntities(timestampsNotInTheFuture.generateOne).generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetSpec.scala index a21faa5afb..354a6d4a33 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/DatasetSpec.scala @@ -52,15 +52,13 @@ class DatasetSpec "fromCli" should { - "turn CliDataset entity into the Dataset object" in { - + "turn CliDataset entity into the Dataset object" in forAll(datasetEntities(provenanceNonModified(cliShapedPersons)).decoupledFromProject) { testDs => val modelDs = testDs.to[entities.Dataset[entities.Dataset.Provenance]] val cliDs = testDs.to[CliDataset] entities.Dataset.fromCli(cliDs) shouldMatchToValid modelDs } - } "fail if originalIdentifier on an Imported External dataset is different than its identifier" in { diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/EntitySpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/EntitySpec.scala index d92d2ab24e..3832a8e84b 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/EntitySpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/EntitySpec.scala @@ -45,16 +45,15 @@ class EntitySpec ) "fromCli" should { - "turn CliInputEntity entity into the Entity object " in { + "turn CliInputEntity entity into the Entity object " in forAll(inputEntities) { entity => val cliEntity = entity.to[CliEntity] val modelEntity = entity.to[entities.Entity.InputEntity] entities.Entity.fromCli(cliEntity) shouldMatchTo modelEntity } - } - "turn CliOutput entity into the Entity object " in { + "turn CliOutput entity into the Entity object " in forAll(locationCommandOutputObjects) { commandOutput => val activity = activityGenerator(commandOutput).generateOne val cliEntities = activity.to[CliActivity].generations.map(_.entity) @@ -65,9 +64,8 @@ class EntitySpec _.entity.to[entities.Entity.OutputEntity] ) } - } - "turn CliOutput entity with multiple Generations into the Entity object " in { + "turn CliOutput entity with multiple Generations into the Entity object " in forAll(locationCommandOutputObjects) { commandOutput => val testActivity = activityGenerator(commandOutput).generateOne val updatedActivity = testActivity.copy(generationFactories = @@ -83,6 +81,5 @@ class EntitySpec result should contain allElementsOf updatedActivity.generations.map(g => Entity.toEntity.apply(g.entity)) } - } } } diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/GenerationSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/GenerationSpec.scala index 4d2fdcc478..db1bdf8684 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/GenerationSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/GenerationSpec.scala @@ -47,7 +47,7 @@ class GenerationSpec ) } - "turn valid CliGeneration into Generation object" in { + "turn valid CliGeneration into Generation object" in forAll(locationCommandOutputObjects) { commandOutput => val testActivity = activityEntities(stepPlanEntities(planCommands, cliShapedPersons, commandOutput), cliShapedPersons)( @@ -58,6 +58,5 @@ class GenerationSpec val cliGeneration = generation.to[CliGeneration] entities.Generation.fromCli(cliGeneration) shouldMatchToValid generation.to[entities.Generation] } - } } } diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/ParameterValueSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/ParameterValueSpec.scala index 9f2ca9015a..519a1b59bd 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/ParameterValueSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/ParameterValueSpec.scala @@ -50,7 +50,7 @@ class ParameterValueSpec ) "fromCli" should { - "turn cli VariableParameterValue entity into the VariableParameterValue object " in { + "turn cli VariableParameterValue entity into the VariableParameterValue object " in forAll(nonEmptyStrings().toGeneratorOf(ParameterDefaultValue), parameterValueOverrides) { (defaultValue, valueOverride) => val activity = @@ -67,9 +67,8 @@ class ParameterValueSpec result shouldMatchToValid entitiesActivity.parameters entitiesActivity.parameters.foreach(_ shouldBe a[entities.ParameterValue.CommandParameterValue]) } - } - "turn cli InputParameterValue entity into the InputParameterValue object " in { + "turn cli InputParameterValue entity into the InputParameterValue object " in forAll(entityLocations, entityChecksums) { (location, checksum) => val activity = executionPlannerGen(CommandInput.fromLocation(location)).generateOne .planInputParameterValuesFromChecksum(location -> checksum) @@ -84,9 +83,8 @@ class ParameterValueSpec result shouldMatchToValid entitiesActivity.parameters entitiesActivity.parameters.foreach(_ shouldBe a[entities.ParameterValue.CommandInputValue]) } - } - "turn JsonLD OutputParameterValue entity into the OutputParameterValue object " in { + "turn JsonLD OutputParameterValue entity into the OutputParameterValue object " in forAll(entityLocations) { location => val activity = executionPlannerGen(CommandOutput.fromLocation(location)).generateOne .buildProvenanceUnsafe() @@ -100,7 +98,6 @@ class ParameterValueSpec result shouldMatchToValid entitiesActivity.parameters entitiesActivity.parameters.foreach(_ shouldBe a[entities.ParameterValue.CommandOutputValue]) } - } "fail if there are VariableParameterValue for non-existing CommandParameters" in { val defaultValue = nonEmptyStrings().toGeneratorOf(ParameterDefaultValue).generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/PersonSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/PersonSpec.scala index 23f73a47a6..55e4ee8f0c 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/PersonSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/PersonSpec.scala @@ -50,7 +50,7 @@ class PersonSpec "apply(Name, GitLabId)" should { - "instantiate a Person.WithGitLabId" in { + "instantiate a Person.WithGitLabId" in forAll(personNames, personGitLabIds) { (name, glId) => entities.Person(name, glId) shouldBe entities.Person.WithGitLabId(persons.ResourceId(glId), glId, @@ -60,19 +60,17 @@ class PersonSpec maybeAffiliation = None ) } - } } "fromCli" should { - "turn CliPerson entity into the Person object" in { + "turn CliPerson entity into the Person object" in forAll(cliShapedPersons) { person: Person => val cliPerson = person.to[CliPerson] entities.Person.fromCli(cliPerson) shouldMatchToValid person.to[entities.Person] } - } - "fail if person's ResourceId does not match the Email or Orcid based ResourceId if no GitLabId but Email given" in { + "fail if person's ResourceId does not match the Email or Orcid based ResourceId if no GitLabId but Email given" in forAll(Gen.oneOf(personGitLabResourceId, personNameResourceId).widen[persons.ResourceId], personEmails, personNames @@ -84,9 +82,8 @@ class PersonSpec show"orcidId = ${Option.empty[persons.OrcidId]}, email = ${email.some}, affiliation = None" ) } - } - "fail if person's ResourceId does not match the Name or Orcid based ResourceId if no GitLabId and Email given" in { + "fail if person's ResourceId does not match the Name or Orcid based ResourceId if no GitLabId and Email given" in forAll(Gen.oneOf(personGitLabResourceId, personEmailResourceId).widen[persons.ResourceId], personNames) { (invalidResourceId, name) => val cliPerson = CliPerson(CliPersonResourceId(invalidResourceId.value), name, None, None) @@ -96,7 +93,6 @@ class PersonSpec show"orcidId = ${Option.empty[persons.OrcidId]}, email = ${Option.empty[persons.Email]}, affiliation = None" ) } - } } "entityFunctions.findAllPersons" should { diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/PlanSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/PlanSpec.scala index 06954794c4..5fac1c26e2 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/PlanSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/PlanSpec.scala @@ -49,21 +49,19 @@ class PlanSpec "fromCli (StepEntity)" should { - "turn CliStepPlan of a non-modified Plan entity into the StepPlan object" in { + "turn CliStepPlan of a non-modified Plan entity into the StepPlan object" in forAll(stepPlans) { plan => val prodPlan = plan.to[entities.StepPlan] val cliPlan = plan.to[CliStepPlan] entities.StepPlan.fromCli(cliPlan) shouldMatchToValid prodPlan } - } - "turn CliStepPlan of a modified Plan entity into the StepPlan object" in { + "turn CliStepPlan of a modified Plan entity into the StepPlan object" in forAll(stepPlans.map(_.createModification())) { (plan: StepPlan) => val prodPlan = plan.to[entities.StepPlan] val cliPlan = plan.to[CliStepPlan] entities.StepPlan.fromCli(cliPlan) shouldMatchToValid prodPlan } - } "convert if invalidation after the creation date" in { @@ -115,30 +113,27 @@ class PlanSpec "fromCli (CompositePlan)" should { - "work for a non-modified composite plan" in { + "work for a non-modified composite plan" in forAll(compositePlanGen(cliShapedPersons)) { plan => val expected = plan.to[entities.CompositePlan] val cliPlan = plan.to[CliCompositePlan] entities.CompositePlan.fromCli(cliPlan) shouldMatchToValid expected } - } - "work for a modified composite plan" in { + "work for a modified composite plan" in forAll(compositePlanGen(cliShapedPersons).map(_.createModification())) { plan => val expected = plan.to[entities.CompositePlan] val cliPlan = plan.to[CliCompositePlan] entities.CompositePlan.fromCli(cliPlan) shouldMatchToValid expected } - } - "work if invalidation after the creation date" in { + "work if invalidation after the creation date" in forAll(compositePlanGen(cliShapedPersons).map(_.createModification().invalidate())) { plan => val expected = plan.to[entities.CompositePlan] val cliPlan = plan.to[CliCompositePlan] entities.CompositePlan.fromCli(cliPlan) shouldMatchToValid expected } - } "work for any Plan entity subtypes" in { val testCp = compositePlanGen(cliShapedPersons).generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/ProjectSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/ProjectSpec.scala index b557306615..0f26cdbf7c 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/ProjectSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/ProjectSpec.scala @@ -223,7 +223,7 @@ class ProjectSpec } } - "turn non-renku CliProject entity without parent into the NonRenkuProject object" in { + "turn non-renku CliProject entity without parent into the NonRenkuProject object" in forAll(gitLabProjectInfos.map(projectInfoMaybeParent.replace(None))) { projectInfo => val creator = projectMembersWithEmail.generateOne val members = gitLabProjectMembers.generateSet() @@ -242,7 +242,6 @@ class ProjectSpec maybeCreator = creator.toPerson.some ) } - } "turn non-renku CliProject entity with parent into the NonRenkuProject object" in { forAll(gitLabProjectInfos.map(projectInfoMaybeParent.replace(projectSlugs.generateSome))) { projectInfo => @@ -1010,7 +1009,7 @@ class ProjectSpec implicit val graph: GraphClass = GraphClass.Default - "produce JsonLD with all the relevant properties of a Renku Project" in { + "produce JsonLD with all the relevant properties of a Renku Project" in forAll(renkuProjectEntitiesWithDatasetsAndActivities.map(_.to[entities.RenkuProject])) { project => val maybeParentId = project match { case p: entities.RenkuProject.WithParent => p.parentResourceId.some @@ -1044,9 +1043,8 @@ class ProjectSpec ) .toJson } - } - "produce JsonLD with all the relevant properties or a non-Renku Project" in { + "produce JsonLD with all the relevant properties or a non-Renku Project" in forAll(anyNonRenkuProjectEntities.map(_.to[entities.NonRenkuProject])) { project => val maybeParentId = project match { case p: entities.NonRenkuProject.WithParent => p.parentResourceId.some @@ -1075,7 +1073,6 @@ class ProjectSpec ) .toJson } - } } "encode for the Project Graph" should { @@ -1083,7 +1080,7 @@ class ProjectSpec import persons.ResourceId.entityIdEncoder implicit val graph: GraphClass = GraphClass.Project - "produce JsonLD with all the relevant properties and only links to Person entities" in { + "produce JsonLD with all the relevant properties and only links to Person entities" in forAll( renkuProjectEntitiesWithDatasetsAndActivities .modify(replaceMembers(projectMemberEntities(withoutGitLabId).generateFixedSizeSet(ofSize = 1))) @@ -1121,9 +1118,8 @@ class ProjectSpec ) .toJson } - } - "produce JsonLD with all the relevant properties or a non-Renku Project" in { + "produce JsonLD with all the relevant properties or a non-Renku Project" in forAll( anyNonRenkuProjectEntities .modify(replaceMembers(projectMemberEntities(withoutGitLabId).generateFixedSizeSet(ofSize = 1))) @@ -1156,9 +1152,8 @@ class ProjectSpec ) .toJson } - } - "produce JsonLD with all the relevant properties without images" in { + "produce JsonLD with all the relevant properties without images" in forAll( anyNonRenkuProjectEntities .modify(replaceMembers(projectMemberEntities(withoutGitLabId).generateFixedSizeSet(ofSize = 1))) @@ -1198,7 +1193,6 @@ class ProjectSpec ) .toJson } - } } "entityFunctions.findAllPersons" should { diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/StepPlanCommandParameterSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/StepPlanCommandParameterSpec.scala index ff2cdf2acf..dbff26907a 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/StepPlanCommandParameterSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/StepPlanCommandParameterSpec.scala @@ -46,82 +46,74 @@ class StepPlanCommandParameterSpec "StepPlanCommandParameter.fromCli" should { - "turn cli data of ExplicitCommandParameter entity into the ExplicitCommandParameter object" in { + "turn cli data of ExplicitCommandParameter entity into the ExplicitCommandParameter object" in forAll(explicitCommandParameterObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliParams = plan.to[CliStepPlan].parameters val result = cliParams.traverse(entities.StepPlanCommandParameter.CommandParameter.fromCli) result shouldMatchToValid plan.parameters.map(_.to[entities.StepPlanCommandParameter.CommandParameter]) } - } - "turn cli data of ImplicitCommandParameter entity into the ExplicitCommandParameter object" in { + "turn cli data of ImplicitCommandParameter entity into the ExplicitCommandParameter object" in forAll(implicitCommandParameterObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliParams = plan.to[CliStepPlan].parameters val result = cliParams.traverse(entities.StepPlanCommandParameter.CommandParameter.fromCli) result shouldMatchToValid plan.parameters.map(_.to[entities.StepPlanCommandParameter.CommandParameter]) } - } } "CommandInput.fromCli" should { - "turn cli data of LocationCommandInput entity into the LocationCommandInput object" in { + "turn cli data of LocationCommandInput entity into the LocationCommandInput object" in forAll(locationCommandInputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliInputs = plan.to[model.CliStepPlan].inputs val result = cliInputs.traverse(entities.StepPlanCommandParameter.CommandInput.fromCli) result shouldMatchToValid plan.inputs.map(_.to[entities.StepPlanCommandParameter.CommandInput]) } - } - "turn cli data of MappedCommandInput entity into the MappedCommandInput object" in { + "turn cli data of MappedCommandInput entity into the MappedCommandInput object" in forAll(mappedCommandInputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliInputs = plan.to[model.CliStepPlan].inputs val result = cliInputs.traverse(entities.StepPlanCommandParameter.CommandInput.fromCli) result shouldMatchToValid plan.inputs.map(_.to[entities.StepPlanCommandParameter.CommandInput]) } - } - "turn cli data of ImplicitCommandInput entity into the ImplicitCommandInput object" in { + "turn cli data of ImplicitCommandInput entity into the ImplicitCommandInput object" in forAll(implicitCommandInputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliInputs = plan.to[model.CliStepPlan].inputs val result = cliInputs.traverse(entities.StepPlanCommandParameter.CommandInput.fromCli) result shouldMatchToValid plan.inputs.map(_.to[entities.StepPlanCommandParameter.CommandInput]) } - } } show"CommandOutput.fromCli" should { - "turn cli data of LocationCommandOutput entity into the LocationCommandOutput object" in { + "turn cli data of LocationCommandOutput entity into the LocationCommandOutput object" in forAll(locationCommandOutputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliOutputs = plan.to[model.CliStepPlan].outputs val result = cliOutputs.traverse(entities.StepPlanCommandParameter.CommandOutput.fromCli) result shouldMatchToValid plan.outputs.map(_.to[entities.StepPlanCommandParameter.CommandOutput]) } - } - "turn cli data of MappedCommandOutput entity into the MappedCommandOutput object" in { + "turn cli data of MappedCommandOutput entity into the MappedCommandOutput object" in forAll(mappedCommandOutputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliOutputs = plan.to[model.CliStepPlan].outputs val result = cliOutputs.traverse(entities.StepPlanCommandParameter.CommandOutput.fromCli) result shouldMatchToValid plan.outputs.map(_.to[entities.StepPlanCommandParameter.CommandOutput]) } - } - "turn cli data of ImplicitCommandOutput entity into the ImplicitCommandOutput object" in { + "turn cli data of ImplicitCommandOutput entity into the ImplicitCommandOutput object" in forAll(implicitCommandOutputObjects) { parameterFactory => val plan = planGenerator(parameterFactory).generateOne val cliOutputs = plan.to[model.CliStepPlan].outputs val result = cliOutputs.traverse(entities.StepPlanCommandParameter.CommandOutput.fromCli) result shouldMatchToValid plan.outputs.map(_.to[entities.StepPlanCommandParameter.CommandOutput]) } - } } } diff --git a/renku-model/src/test/scala/io/renku/graph/model/entities/UsageSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/entities/UsageSpec.scala index 5c73b4c91a..946c7aa692 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/entities/UsageSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/entities/UsageSpec.scala @@ -40,7 +40,7 @@ class UsageSpec "fromCli" should { implicit val renkuUrl: RenkuUrl = renkuUrls.generateOne - "turn CliUsage entity into the Usage object" in { + "turn CliUsage entity into the Usage object" in forAll(entityLocations, entityChecksums) { (location, checksum) => val activity = executionPlanners( stepPlanEntities(planCommands, cliShapedPersons, CommandInput.fromLocation(location)), @@ -55,6 +55,5 @@ class UsageSpec result shouldMatchToValid activity.usages.map(_.to[entities.Usage]) } - } } } diff --git a/renku-model/src/test/scala/io/renku/graph/model/infraSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/infraSpec.scala index a4f2f38edb..a05c162cef 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/infraSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/infraSpec.scala @@ -33,28 +33,25 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou "from" should { - "return Right for a valid released version" in { + "return Right for a valid released version" in forAll(semanticVersions) { version => CliVersion.from(version).map(_.show).value shouldBe version } - } - "return Right for a valid rc version" in { + "return Right for a valid rc version" in forAll(rcVersions()) { version => CliVersion.from(version).map(_.show).value shouldBe version } - } - "return Right for a valid dev version" in { + "return Right for a valid dev version" in forAll(devVersions()) { version => CliVersion.from(version).map(_.show).value shouldBe version } - } } "major, minor and bugfix" should { - "extract the relevant version parts from a released version" in { + "extract the relevant version parts from a released version" in forAll(semanticVersions) { version => val cli = CliVersion(version) val s"$major.$minor.$bugfix" = version @@ -62,9 +59,8 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou cli.minor shouldBe minor cli.bugfix shouldBe bugfix } - } - "extract the relevant version parts from an rc version" in { + "extract the relevant version parts from an rc version" in forAll(rcVersions()) { version => val cli = CliVersion(version) val s"$major.$minor.$bugfix" = version @@ -72,9 +68,8 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou cli.minor shouldBe minor cli.bugfix shouldBe bugfix } - } - "extract the relevant version parts from a dev version" in { + "extract the relevant version parts from a dev version" in forAll(devVersions()) { version => val cli = CliVersion(version) val s"$major.$minor.$bugfix" = version @@ -82,12 +77,11 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou cli.minor shouldBe minor cli.bugfix shouldBe bugfix } - } } "ordering" should { - "consider the major only if different" in { + "consider the major only if different" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.major != version2.major) { val list = List(version1, version2) @@ -96,9 +90,8 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou else list.sorted shouldBe list.reverse } } - } - "consider the minor only if majors are the same" in { + "consider the minor only if majors are the same" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.minor != version2.minor) { val version2SameMajor = CliVersion(version2.show.replaceFirst(s"${version2.major}.", s"${version1.major}.")) @@ -109,9 +102,8 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou else list.sorted shouldBe list.reverse } } - } - "consider the bugfix only if majors and minors are the same" in { + "consider the bugfix only if majors and minors are the same" in forAll(cliVersions, cliVersions) { (version1, version2) => whenever(version1.bugfix != version2.bugfix) { val version2SameMajorMinor = CliVersion( @@ -125,7 +117,6 @@ class CliVersionSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shou else list.sorted shouldBe list.reverse } } - } "consider the rc part if all majors, minors and bugfix are the same" in { val semanticVersion = semanticVersions.generateOne diff --git a/renku-model/src/test/scala/io/renku/graph/model/testentities/ModelOps.scala b/renku-model/src/test/scala/io/renku/graph/model/testentities/ModelOps.scala index baa8662a7d..b611fbf507 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/testentities/ModelOps.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/testentities/ModelOps.scala @@ -478,17 +478,17 @@ trait ModelOps extends Dataset.ProvenanceOps { prov.copy(creators = (creatorGen.generateOne.copy(name = userName) :: prov.creators).sortBy(_.name)) } - implicit val creatorUsernameUpdaterImportedInternalAncestorInternal - : (persons.Name, - Dataset.Provenance.ImportedInternalAncestorInternal - ) => Dataset.Provenance.ImportedInternalAncestorInternal = { case (userName, prov) => + implicit val creatorUsernameUpdaterImportedInternalAncestorInternal: ( + persons.Name, + Dataset.Provenance.ImportedInternalAncestorInternal + ) => Dataset.Provenance.ImportedInternalAncestorInternal = { case (userName, prov) => prov.copy(creators = (personEntities.generateOne.copy(name = userName) :: prov.creators).sortBy(_.name)) } - implicit val creatorUsernameUpdaterImportedInternalAncestorExternal - : (persons.Name, - Dataset.Provenance.ImportedInternalAncestorExternal - ) => Dataset.Provenance.ImportedInternalAncestorExternal = { case (userName, prov) => + implicit val creatorUsernameUpdaterImportedInternalAncestorExternal: ( + persons.Name, + Dataset.Provenance.ImportedInternalAncestorExternal + ) => Dataset.Provenance.ImportedInternalAncestorExternal = { case (userName, prov) => prov.copy(creators = (personEntities.generateOne.copy(name = userName) :: prov.creators).sortBy(_.name)) } diff --git a/renku-model/src/test/scala/io/renku/graph/model/views/SparqlLiteralEncoderSpec.scala b/renku-model/src/test/scala/io/renku/graph/model/views/SparqlLiteralEncoderSpec.scala index 85baf2e6fe..81ac05ae51 100644 --- a/renku-model/src/test/scala/io/renku/graph/model/views/SparqlLiteralEncoderSpec.scala +++ b/renku-model/src/test/scala/io/renku/graph/model/views/SparqlLiteralEncoderSpec.scala @@ -29,17 +29,15 @@ class SparqlLiteralEncoderSpec extends AnyWordSpec with ScalaCheckPropertyChecks "iriEncode" should { - "do nothing for letter chars" in { + "do nothing for letter chars" in forAll(alphaStr) { s => sparqlEncode(s) shouldBe s } - } - "do nothing for digit chars" in { + "do nothing for digit chars" in forAll(numStr) { s => sparqlEncode(s) shouldBe s } - } "escape ' with \\" in { sparqlEncode("a'b") shouldBe """a\'b""" diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/TinyTypeSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/TinyTypeSpec.scala index 8d5f5b57df..8eb85f21f7 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/TinyTypeSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/TinyTypeSpec.scala @@ -47,22 +47,20 @@ class TinyTypeSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should "stringTinyTypeConverter" should { - "url encode the given value and convert it to a single element list of PathSegment" in { + "url encode the given value and convert it to a single element list of PathSegment" in forAll(nonEmptyStrings(), Gen.oneOf("\\", " "), nonEmptyStrings()) { (part1, part2, part3) => val tinyType = new StringTinyType { val value = s"$part1$part2$part3" } StringTinyType.stringTinyTypeConverter(tinyType) shouldBe List(PathSegment(tinyType.value)) } - } } "relativePathTinyTypeConverter" should { - "do not url encode the given value and convert it to a multiple elements list of PathSegment" in { + "do not url encode the given value and convert it to a multiple elements list of PathSegment" in forAll(nonEmptyList(nonEmptyStrings())) { segments => val tinyType = new RelativePathTinyType { val value = segments.toList.mkString("/") } RelativePathTinyType.relativePathTinyTypeConverter(tinyType) shouldBe segments.toList.map(PathSegment.apply) } - } } private lazy val arbitraryValues: List[Any] = diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/BoundedInstantSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/BoundedInstantSpec.scala index 9ab1426ff6..49f0e460ba 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/BoundedInstantSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/BoundedInstantSpec.scala @@ -41,7 +41,7 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with protected[this] override def maybeMax: Option[Instant] = Some(max) } - "be instantiatable instants from within the defined boundaries" in { + "be instantiatable instants from within the defined boundaries" in forAll( timestamps( min = Instant.now().minus(24, HOURS).plus(2, SECONDS), @@ -50,9 +50,8 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with ) { value => Type.from(value).map(_.value) shouldBe Right(value) } - } - "fail if outside the left boundary" in { + "fail if outside the left boundary" in forAll( timestamps( max = Instant.now().minus(24, HOURS).minus(2, SECONDS) @@ -63,9 +62,8 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with exception shouldBe an[IllegalArgumentException] exception.getMessage shouldBe s"${Type.typeName} has to be >= ${Type.min} and <= ${Type.max}" } - } - "fail if outside the right boundary" in { + "fail if outside the right boundary" in forAll( timestamps( min = Instant.now().plus(24, HOURS).plus(2, SECONDS) @@ -76,7 +74,6 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with exception shouldBe an[IllegalArgumentException] exception.getMessage shouldBe s"${Type.typeName} has to be >= ${Type.min} and <= ${Type.max}" } - } } "BoundedInstant - with min" should { @@ -89,15 +86,14 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with protected[this] override def maybeMin: Option[Instant] = Some(min) } - "be instantiatable instants from within the defined boundaries" in { + "be instantiatable instants from within the defined boundaries" in forAll( timestamps(min = Instant.now().minus(24, HOURS).plus(2, SECONDS)) ) { value => Type.from(value).map(_.value) shouldBe Right(value) } - } - "fail if outside the boundary" in { + "fail if outside the boundary" in forAll( timestamps( max = Instant.now().minus(24, HOURS).minus(2, SECONDS) @@ -108,7 +104,6 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with exception shouldBe an[IllegalArgumentException] exception.getMessage shouldBe s"${Type.typeName} has to be >= ${Type.min}" } - } } "BoundedInstant - with max" should { @@ -121,15 +116,14 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with protected[this] override def maybeMax: Option[Instant] = Some(max) } - "be instantiatable instants from within the defined boundaries" in { + "be instantiatable instants from within the defined boundaries" in forAll( timestamps(max = Instant.now().plus(24, HOURS).minus(2, SECONDS)) ) { value => Type.from(value).map(_.value) shouldBe Right(value) } - } - "fail if outside the boundary" in { + "fail if outside the boundary" in forAll( timestamps( min = Instant.now().plus(24, HOURS).plus(2, SECONDS) @@ -140,6 +134,5 @@ class BoundedInstantSpec extends AnyWordSpec with ScalaCheckPropertyChecks with exception shouldBe an[IllegalArgumentException] exception.getMessage shouldBe s"${Type.typeName} has to be <= ${Type.max}" } - } } } diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/DurationNotNegativeSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/DurationNotNegativeSpec.scala index b64d7b525c..d760287294 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/DurationNotNegativeSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/DurationNotNegativeSpec.scala @@ -31,11 +31,10 @@ class DurationNotNegativeSpec extends AnyWordSpec with ScalaCheckPropertyChecks "DurationNotNegative" should { - "be instantiatable when values are positive durations" in { + "be instantiatable when values are positive durations" in forAll(notNegativeJavaDurations) { someValue => DurationNotNegativeType(someValue).value shouldBe someValue } - } "throw an IllegalArgumentException for negative duration" in { intercept[IllegalArgumentException] { diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/GitShaSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/GitShaSpec.scala index ea809e3b47..6fa65da45d 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/GitShaSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/GitShaSpec.scala @@ -28,11 +28,10 @@ class GitShaSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "GitSha" should { - "be instantiatable for a valid sha" in { + "be instantiatable for a valid sha" in forAll(shas) { sha => SomeGitSha(sha).toString shouldBe sha } - } "throw an IllegalArgumentException for non-sha values" in { intercept[IllegalArgumentException] { diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantInThePastSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantInThePastSpec.scala index 3eea720df3..321657e1ee 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantInThePastSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantInThePastSpec.scala @@ -30,11 +30,10 @@ class InstantInThePastSpec extends AnyWordSpec with ScalaCheckPropertyChecks wit "InstantInThePast" should { - "be instantiatable when values are Instants in the past" in { + "be instantiatable when values are Instants in the past" in forAll(timestampsNotInTheFuture) { someValue => InstantInThePastType(someValue).value shouldBe someValue } - } "throw an IllegalArgumentException for instants the future" in { intercept[IllegalArgumentException] { diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantNotInTheFutureSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantNotInTheFutureSpec.scala index 9a926801ce..a1d9da9d6c 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantNotInTheFutureSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/InstantNotInTheFutureSpec.scala @@ -30,11 +30,10 @@ class InstantNotInTheFutureSpec extends AnyWordSpec with ScalaCheckPropertyCheck "InstantNotInTheFuture" should { - "be instantiatable when values are Instants in the past" in { + "be instantiatable when values are Instants in the past" in forAll(timestampsNotInTheFuture) { someValue => InstantInThePastType(someValue).value shouldBe someValue } - } "be instantiatable when values are Instants from now" in { val systemZone = ZoneId.systemDefault diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/LocalDateNotInTheFutureSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/LocalDateNotInTheFutureSpec.scala index 42517abac5..ec4bdb85b5 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/LocalDateNotInTheFutureSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/LocalDateNotInTheFutureSpec.scala @@ -30,11 +30,10 @@ class LocalDateNotInTheFutureSpec extends AnyWordSpec with ScalaCheckPropertyChe "LocalDateNotInTheFuture" should { - "be instantiatable when values are LocalDates in the past" in { + "be instantiatable when values are LocalDates in the past" in forAll(localDatesNotInTheFuture) { someValue => LocalDateNotInTheFutureType(someValue).value shouldBe someValue } - } "be instantiatable when values are LocalDate from now" in { val fixedNow = LocalDate.now diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonBlankSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonBlankSpec.scala index f3c97b2c40..a59772397f 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonBlankSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonBlankSpec.scala @@ -28,11 +28,10 @@ class NonBlankSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should "NonBlank" should { - "be instantiatable when values are not blank" in { + "be instantiatable when values are not blank" in forAll(nonEmptyStrings()) { someValue => NonBlankString(someValue).toString shouldBe someValue } - } "throw an IllegalArgumentException for empty String values" in { intercept[IllegalArgumentException]( diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonNegativeSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonNegativeSpec.scala index c250bed955..aa770a665e 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonNegativeSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/NonNegativeSpec.scala @@ -28,11 +28,10 @@ class NonNegativeSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho "NonNegativeInt" should { - "be instantiatable when values are greater or equal zero" in { + "be instantiatable when values are greater or equal zero" in forAll(Gen.choose(0, 100000)) { someValue => TestNonNegativeInt(someValue).value shouldBe someValue } - } "throw an IllegalArgumentException for negative value" in { intercept[IllegalArgumentException]( @@ -43,11 +42,10 @@ class NonNegativeSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho "NonNegativeLong" should { - "be instantiatable when values are greater or equal zero" in { + "be instantiatable when values are greater or equal zero" in forAll(Gen.choose(0, 100000)) { someValue => TestNonNegativeLong(someValue).value shouldBe someValue } - } "throw an IllegalArgumentException for negative value" in { intercept[IllegalArgumentException]( diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PathSegmentSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PathSegmentSpec.scala index 2899275b02..f575aa9522 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PathSegmentSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PathSegmentSpec.scala @@ -42,11 +42,10 @@ class PathSegmentSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho "apply" should { - "url encode the given value and successfully instantiate" in { + "url encode the given value and successfully instantiate" in forAll(nonEmptyStrings(), Gen.oneOf("\\/", " "), nonEmptyStrings()) { (part1, part2, part3) => val raw = s"$part1$part2$part3" PathSegment(raw).value shouldBe urlEncode(raw) } - } } } diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PositiveIntSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PositiveIntSpec.scala index 3312d1d5c6..b14481e2ff 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PositiveIntSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/PositiveIntSpec.scala @@ -28,11 +28,10 @@ class PositiveIntSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho "PositiveInt" should { - "be instantiatable when values are greater than zero" in { + "be instantiatable when values are greater than zero" in forAll(Gen.choose(1, 100000)) { someValue => PositiveIntTest(someValue).value shouldBe someValue } - } "throw an IllegalArgumentException for 0" in { intercept[IllegalArgumentException]( diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/RelativePathSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/RelativePathSpec.scala index deb2e27734..17e2367db0 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/RelativePathSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/RelativePathSpec.scala @@ -34,17 +34,15 @@ class RelativePathSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sh RelativePathString shouldBe a[NonBlank[_]] } - "be instantiatable when values are not starting and ending with '/'" in { + "be instantiatable when values are not starting and ending with '/'" in forAll(nonEmptyStrings()) { someValue => RelativePathString(someValue).toString shouldBe someValue } - } - "be instantiatable when values are not starting but ending with '/' and having the '/' sign inside" in { + "be instantiatable when values are not starting but ending with '/' and having the '/' sign inside" in forAll(relativePaths().map(v => s"$v/")) { someValue => RelativePathString(someValue).toString shouldBe someValue } - } "throw an IllegalArgumentException for values starting with a protocol" in { s"http://${relativePaths().generateOne}" :: httpUrls().generateOne :: s"ftp://${relativePaths().generateOne}" :: Nil foreach { diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UUIDSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UUIDSpec.scala index 25abc5b1d9..faf67a0456 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UUIDSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UUIDSpec.scala @@ -34,27 +34,24 @@ class UUIDSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Mat UUIDString shouldBe a[NonBlank[_]] } - "be instantiatable when values are valid UUIDs" in { + "be instantiatable when values are valid UUIDs" in forAll(uuid) { expected => val Right(UUIDString(actual)) = UUIDString.from(expected.toString) actual shouldBe expected.toString } - } - "be instantiatable when values are UUIDs without dashes" in { + "be instantiatable when values are UUIDs without dashes" in forAll(noDashUuid) { expected => val Right(UUIDString(actual)) = UUIDString.from(expected) actual shouldBe expected } - } - "fail instantiation for non-UUID values" in { + "fail instantiation for non-UUID values" in forAll(nonEmptyStrings()) { value => intercept[IllegalArgumentException] { UUIDString(value) }.getMessage shouldBe s"'$value' is not a valid UUID value for io.renku.tinytypes.constraints.UUIDString" } - } } } diff --git a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UrlSpec.scala b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UrlSpec.scala index 569f34d596..ebbf2d9980 100644 --- a/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UrlSpec.scala +++ b/tiny-types/src/test/scala/io/renku/tinytypes/constraints/UrlSpec.scala @@ -31,11 +31,10 @@ class UrlSpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.Matc "Url" should { - "be instantiatable for valid urls" in { + "be instantiatable for valid urls" in forAll(httpUrls()) { url => UrlType(url).toString shouldBe url } - } "throw an IllegalArgumentException for invalid urls" in { intercept[IllegalArgumentException]( diff --git a/token-repository/src/main/scala/io/renku/tokenrepository/repository/init/ExpiryAndCreatedDatesAdder.scala b/token-repository/src/main/scala/io/renku/tokenrepository/repository/init/ExpiryAndCreatedDatesAdder.scala index a0fa901d38..4c3c582d44 100644 --- a/token-repository/src/main/scala/io/renku/tokenrepository/repository/init/ExpiryAndCreatedDatesAdder.scala +++ b/token-repository/src/main/scala/io/renku/tokenrepository/repository/init/ExpiryAndCreatedDatesAdder.scala @@ -45,12 +45,11 @@ private class ExpiryAndCreatedDatesAdder[F[_]: Spawn: Logger: SessionResource] e case false => addColumn(column, columnType) } - private def addColumn(column: String, columnType: String): Kleisli[F, Session[F], Unit] = Kleisli { - implicit session => - for { - _ <- execute(sql"ALTER TABLE projects_tokens ADD COLUMN IF NOT EXISTS #$column #$columnType".command) - _ <- execute(sql"CREATE INDEX IF NOT EXISTS idx_#$column ON projects_tokens(#$column)".command) - _ <- Logger[F].info(s"'$column' column added") - } yield () + private def addColumn(column: String, columnType: String): Kleisli[F, Session[F], Unit] = Kleisli { implicit session => + for { + _ <- execute(sql"ALTER TABLE projects_tokens ADD COLUMN IF NOT EXISTS #$column #$columnType".command) + _ <- execute(sql"CREATE INDEX IF NOT EXISTS idx_#$column ON projects_tokens(#$column)".command) + _ <- Logger[F].info(s"'$column' column added") + } yield () } } diff --git a/token-repository/src/test/scala/io/renku/tokenrepository/repository/creation/ProjectSlugFinderSpec.scala b/token-repository/src/test/scala/io/renku/tokenrepository/repository/creation/ProjectSlugFinderSpec.scala index 67202a3111..d5e9ea275f 100644 --- a/token-repository/src/test/scala/io/renku/tokenrepository/repository/creation/ProjectSlugFinderSpec.scala +++ b/token-repository/src/test/scala/io/renku/tokenrepository/repository/creation/ProjectSlugFinderSpec.scala @@ -86,9 +86,8 @@ class ProjectSlugFinderSpec } Status.Unauthorized :: Status.Forbidden :: Status.NotFound :: Nil foreach { status => - it should s"map $status response to None" in { + it should s"map $status response to None" in mapResponse(status, Request[IO](), Response[IO](status)).asserting(_ shouldBe None) - } } it should "map UNAUTHORIZED response to None" in { diff --git a/token-repository/src/test/scala/io/renku/tokenrepository/repository/modelSpec.scala b/token-repository/src/test/scala/io/renku/tokenrepository/repository/modelSpec.scala index c197d8edc1..b3ed159920 100644 --- a/token-repository/src/test/scala/io/renku/tokenrepository/repository/modelSpec.scala +++ b/token-repository/src/test/scala/io/renku/tokenrepository/repository/modelSpec.scala @@ -34,7 +34,7 @@ class ProjectTokenDuePeriodSpec extends AnyWordSpec with should.Matchers with Sc "apply" should { - "read 'project-token-due-period' as Period from the config" in { + "read 'project-token-due-period' as Period from the config" in forAll(ints(min = 1, max = 2 * 365)) { duration => val config = ConfigFactory.parseMap( Map("project-token-due-period" -> s"$duration days").asJava @@ -42,7 +42,6 @@ class ProjectTokenDuePeriodSpec extends AnyWordSpec with should.Matchers with Sc ProjectTokenDuePeriod[Try](config) shouldBe Period.ofDays(duration).pure[Try] } - } } } diff --git a/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/NewProjectSpec.scala b/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/NewProjectSpec.scala index 74a6310b97..92fd9bc033 100644 --- a/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/NewProjectSpec.scala +++ b/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/NewProjectSpec.scala @@ -32,11 +32,10 @@ class NewProjectSpec extends AnyWordSpec with should.Matchers with ScalaCheckPro "encode/decode" should { - "work for any NewProject " in { + "work for any NewProject " in forAll(newProjectsGen) { newProject => newProject.asJson.hcursor.as[NewProject].value shouldBe newProject } - } } "show" should { diff --git a/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/events/ProjectViewedEventSpec.scala b/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/events/ProjectViewedEventSpec.scala index dc9dd1f401..da9399c2ed 100644 --- a/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/events/ProjectViewedEventSpec.scala +++ b/triples-generator-api/src/test/scala/io/renku/triplesgenerator/api/events/ProjectViewedEventSpec.scala @@ -92,11 +92,10 @@ class ProjectViewedEventSpec "json codec" should { - "encode and decode" in { + "encode and decode" in forAll(projectViewedEvents) { event => event.asJson.hcursor.as[ProjectViewedEvent].value shouldBe event } - } "be able to decode json valid from the contract point of view - user GL id case" in { json"""{ diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/EventHandler.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/EventHandler.scala index 1dde6e6eb1..833f339f47 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/EventHandler.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/EventHandler.scala @@ -64,9 +64,11 @@ private object EventHandler { import eu.timepit.refined.pureconfig._ import io.renku.config.ConfigLoader.find - def apply[F[ - _ - ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: MetricsRegistry: Logger: SparqlQueryTimeRecorder]( + def apply[ + F[ + _ + ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: MetricsRegistry: Logger: SparqlQueryTimeRecorder + ]( subscriptionMechanism: SubscriptionMechanism[F], tsWriteLock: TsWriteLock[F], topSameAsLock: Lock[F, datasets.TopmostSameAs], diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/SubscriptionFactory.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/SubscriptionFactory.scala index dda0fe78cf..2e1236d8b8 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/SubscriptionFactory.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/minprojectinfo/SubscriptionFactory.scala @@ -37,9 +37,11 @@ import org.typelevel.log4cats.Logger object SubscriptionFactory { - def apply[F[ - _ - ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: MetricsRegistry: Logger: SparqlQueryTimeRecorder]( + def apply[ + F[ + _ + ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: MetricsRegistry: Logger: SparqlQueryTimeRecorder + ]( tsWriteLock: TsWriteLock[F], topSameAsLock: Lock[F, datasets.TopmostSameAs], projectSparqlClient: ProjectSparqlClient[F], diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/EventHandler.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/EventHandler.scala index abc3c64bd2..ef0192c25e 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/EventHandler.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/EventHandler.scala @@ -59,9 +59,11 @@ private class EventHandler[F[_]: MonadCancelThrow: Logger]( private object EventHandler { - def apply[F[ - _ - ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: Logger: MetricsRegistry: SparqlQueryTimeRecorder]( + def apply[ + F[ + _ + ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: Logger: MetricsRegistry: SparqlQueryTimeRecorder + ]( subscriptionMechanism: SubscriptionMechanism[F], concurrentProcessesNumber: ConcurrentProcessesNumber, tsWriteLock: TsWriteLock[F], diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/SubscriptionFactory.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/SubscriptionFactory.scala index 238001ab8a..f1b588f3b1 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/SubscriptionFactory.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/SubscriptionFactory.scala @@ -37,9 +37,11 @@ import io.renku.triplesstore.{ProjectSparqlClient, SparqlQueryTimeRecorder} import org.typelevel.log4cats.Logger object SubscriptionFactory { - def apply[F[ - _ - ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: Logger: MetricsRegistry: SparqlQueryTimeRecorder]( + def apply[ + F[ + _ + ]: Async: NonEmptyParallel: Parallel: ReProvisioningStatus: GitLabClient: Logger: MetricsRegistry: SparqlQueryTimeRecorder + ]( tsWriteLock: TsWriteLock[F], topSameAsLock: Lock[F, datasets.TopmostSameAs], projectSparqlClient: ProjectSparqlClient[F], diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/Migration.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/Migration.scala index 8ff4b923c6..d3182b7912 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/Migration.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/Migration.scala @@ -47,8 +47,8 @@ private object Migration { implicit val decoder: Decoder[Name] = stringDecoder(Name) - implicit def entityIdEncoder(implicit renkuUrl: RenkuUrl): EntityIdEncoder[Name] = EntityIdEncoder.instance { - name => EntityId.of((renkuUrl / "migration" / name.asUrlPart).toString) + implicit def entityIdEncoder(implicit renkuUrl: RenkuUrl): EntityIdEncoder[Name] = EntityIdEncoder.instance { name => + EntityId.of((renkuUrl / "migration" / name.asUrlPart).toString) } private implicit class MigrationNameOps(name: Migration.Name) { diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/BacklogCreator.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/BacklogCreator.scala index a84258b4d2..c229cdee83 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/BacklogCreator.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/BacklogCreator.scala @@ -114,8 +114,8 @@ private class BacklogCreatorImpl[F[_]: Async](recordsFinder: RecordsFinder[F], m |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } private def storeInBacklog(currentPage: Ref[F, Int]): Option[SparqlQuery] => F[Unit] = { diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/ProjectsPageFinder.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/ProjectsPageFinder.scala index ff4df96cb6..7947d6f278 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/ProjectsPageFinder.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/datemodified/ProjectsPageFinder.scala @@ -70,7 +70,7 @@ private class ProjectsPageFinderImpl[F[_]: Monad](recordsFinder: RecordsFinder[F |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } } diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/lucenereindex/ProjectsPageFinder.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/lucenereindex/ProjectsPageFinder.scala index 9d81e76686..1d3ee9795d 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/lucenereindex/ProjectsPageFinder.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/lucenereindex/ProjectsPageFinder.scala @@ -72,7 +72,7 @@ private class ProjectsPageFinderImpl[F[_]: Monad](migrationName: Migration.Name, |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } } diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/BacklogCreator.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/BacklogCreator.scala index 23ef30c2f7..feb051c83d 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/BacklogCreator.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/BacklogCreator.scala @@ -105,8 +105,8 @@ private class BacklogCreatorImpl[F[_]: Async](recordsFinder: RecordsFinder[F], m |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } private def storeInBacklog(currentPage: Ref[F, Int]): Option[SparqlQuery] => F[Unit] = { diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/ProjectsPageFinder.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/ProjectsPageFinder.scala index 2b9be6e214..afa3b29b68 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/ProjectsPageFinder.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectsgraph/ProjectsPageFinder.scala @@ -70,7 +70,7 @@ private class ProjectsPageFinderImpl[F[_]: Monad](recordsFinder: RecordsFinder[F |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } } diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/BacklogCreator.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/BacklogCreator.scala index 76397886ad..9c52b08e72 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/BacklogCreator.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/BacklogCreator.scala @@ -114,8 +114,8 @@ private class BacklogCreatorImpl[F[_]: Async](recordsFinder: RecordsFinder[F], m |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } private def storeInBacklog(currentPage: Ref[F, Int]): Option[SparqlQuery] => F[Unit] = { diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/ProjectsPageFinder.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/ProjectsPageFinder.scala index bc2b14789b..14d13878c5 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/ProjectsPageFinder.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/projectslug/ProjectsPageFinder.scala @@ -70,7 +70,7 @@ private class ProjectsPageFinderImpl[F[_]: Monad](recordsFinder: RecordsFinder[F |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } } diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/BacklogCreator.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/BacklogCreator.scala index 0659b05ae7..845c037941 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/BacklogCreator.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/BacklogCreator.scala @@ -117,8 +117,8 @@ private class BacklogCreatorImpl[F[_]: Async](startTimeFinder: MigrationStartTim |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } private def storeInBacklog(currentPage: Ref[F, Int]): Option[SparqlQuery] => F[Unit] = { diff --git a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/ProjectsPageFinder.scala b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/ProjectsPageFinder.scala index 89fe40428e..9bc0ef15f3 100644 --- a/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/ProjectsPageFinder.scala +++ b/triples-generator/src/main/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/v10migration/ProjectsPageFinder.scala @@ -70,7 +70,7 @@ private class ProjectsPageFinderImpl[F[_]: Monad](recordsFinder: RecordsFinder[F |""".stripMargin ) - private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { - implicit cur => extract[projects.Slug]("slug") + private implicit lazy val decoder: Decoder[List[projects.Slug]] = ResultsDecoder[List, projects.Slug] { implicit cur => + extract[projects.Slug]("slug") } } diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/awaitinggeneration/GenerationProcessesNumberSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/awaitinggeneration/GenerationProcessesNumberSpec.scala index 48d6722dec..57915695c6 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/awaitinggeneration/GenerationProcessesNumberSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/awaitinggeneration/GenerationProcessesNumberSpec.scala @@ -39,7 +39,7 @@ class GenerationProcessesNumberSpec "apply" should { - "return a GenerationProcessesNumber if there's a value for 'generation-processes-number' in the config" in { + "return a GenerationProcessesNumber if there's a value for 'generation-processes-number' in the config" in forAll(positiveInts()) { value => val config = ConfigFactory.parseMap( Map("generation-processes-number" -> value.value).asJava @@ -47,7 +47,6 @@ class GenerationProcessesNumberSpec GenerationProcessesNumber[Try](config).success.value shouldBe GenerationProcessesNumber(value.value) } - } "fail if there's no value for the 'generation-processes-number'" in { GenerationProcessesNumber[Try](ConfigFactory.empty()).failure.exception shouldBe an[ConfigLoadingException] diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/membersync/GLProjectVisibilityFinderSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/membersync/GLProjectVisibilityFinderSpec.scala index 03a99b3e9d..9eb480ddb8 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/membersync/GLProjectVisibilityFinderSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/membersync/GLProjectVisibilityFinderSpec.scala @@ -79,9 +79,8 @@ class GLProjectVisibilityFinderSpec } Status.Unauthorized :: Status.Forbidden :: Status.NotFound :: Nil foreach { status => - it should s"map $status response to None" in { + it should s"map $status response to None" in mapResponse(status, Request[IO](), Response[IO](status)).asserting(_ shouldBe None) - } } it should "throws a MatchError if remote responds with status different than OK, NOT_FOUND or UNAUTHORIZED" in { diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/syncrepometadata/processor/GLDataFinderSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/syncrepometadata/processor/GLDataFinderSpec.scala index 6f66a8aac1..00c9e95479 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/syncrepometadata/processor/GLDataFinderSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/syncrepometadata/processor/GLDataFinderSpec.scala @@ -97,10 +97,9 @@ class GLDataFinderSpec } Unauthorized :: Forbidden :: NotFound :: Nil foreach { status => - it should show"decode to None for $status status" in { + it should show"decode to None for $status status" in mapResponse(status, Request[IO](), Response[IO]()) .asserting(_ shouldBe None) - } } private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]] diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/ConcurrentProcessesNumberSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/ConcurrentProcessesNumberSpec.scala index 71f07fc13f..934b63f969 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/ConcurrentProcessesNumberSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/triplesgenerated/ConcurrentProcessesNumberSpec.scala @@ -39,7 +39,7 @@ class ConcurrentProcessesNumberSpec "apply" should { - "return a GenerationProcessesNumber if there's a value for 'transformation-processes-number' in the config" in { + "return a GenerationProcessesNumber if there's a value for 'transformation-processes-number' in the config" in forAll(positiveInts()) { value => val config = ConfigFactory.parseMap( Map("transformation-processes-number" -> value.value).asJava @@ -47,7 +47,6 @@ class ConcurrentProcessesNumberSpec ConcurrentProcessesNumber[Try](config).success.value shouldBe ConcurrentProcessesNumber(value.value) } - } "fail if there's no value for the 'transformation-processes-number'" in { ConcurrentProcessesNumber[Try](ConfigFactory.empty()).failure.exception shouldBe an[ConfigLoadingException] diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/tooling/RecoverableErrorsRecoverySpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/tooling/RecoverableErrorsRecoverySpec.scala index a5be40e671..49f7ce50c2 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/tooling/RecoverableErrorsRecoverySpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/events/consumers/tsmigrationrequest/migrations/tooling/RecoverableErrorsRecoverySpec.scala @@ -34,8 +34,7 @@ import scala.util.{Success, Try} private class RecoverableErrorsRecoverySpec extends AnyWordSpec with should.Matchers with TableDrivenPropertyChecks { import RecoverableErrorsRecovery._ - "maybeRecoverableError" should { - + "maybeRecoverableError" should forAll( Table( "Problem name" -> "Exception", @@ -58,5 +57,4 @@ private class RecoverableErrorsRecoverySpec extends AnyWordSpec with should.Matc failure.cause shouldBe exception.getCause } } - } } diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/projects/create/PayloadConverterSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/projects/create/PayloadConverterSpec.scala index a0d726c1db..9d585d3065 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/projects/create/PayloadConverterSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/projects/create/PayloadConverterSpec.scala @@ -32,7 +32,7 @@ class PayloadConverterSpec extends AnyFlatSpec with should.Matchers with ScalaCh private implicit val renkuUrl: RenkuUrl = renkuUrls.generateOne private val converter = new PayloadConverterImpl - it should s"turn the NewProject into a Project entity" in { + it should s"turn the NewProject into a Project entity" in forAll(newProjectsGen) { newProject => val resourceId = projects.ResourceId(newProject.slug) val creator = entities.Person(newProject.creator.name, newProject.creator.id) @@ -51,5 +51,4 @@ class PayloadConverterSpec extends AnyFlatSpec with should.Matchers with ScalaCh Image.projectImage(resourceId, newProject.images) ) } - } } diff --git a/triples-generator/src/test/scala/io/renku/triplesgenerator/tsprovisioning/transformation/namedgraphs/persons/PersonMergerSpec.scala b/triples-generator/src/test/scala/io/renku/triplesgenerator/tsprovisioning/transformation/namedgraphs/persons/PersonMergerSpec.scala index 9a5a0abae2..d530c31c1d 100644 --- a/triples-generator/src/test/scala/io/renku/triplesgenerator/tsprovisioning/transformation/namedgraphs/persons/PersonMergerSpec.scala +++ b/triples-generator/src/test/scala/io/renku/triplesgenerator/tsprovisioning/transformation/namedgraphs/persons/PersonMergerSpec.scala @@ -44,7 +44,7 @@ class PersonMergerSpec extends AnyWordSpec with should.Matchers with ScalaCheckP error.getMessage shouldBe s"Persons ${model.resourceId} and ${kg.resourceId} do not have matching identifiers" } - "prefer model values if they exist in case of Person with GitLabId" in { + "prefer model values if they exist in case of Person with GitLabId" in forAll(personEntities(withGitLabId) map (_.toMaybe[entities.Person.WithGitLabId])) { case Some(model) => val kg = model.copy( @@ -61,9 +61,8 @@ class PersonMergerSpec extends AnyWordSpec with should.Matchers with ScalaCheckP .pure[Try] case None => fail("Cannot convert to entities.person") } - } - "prefer model values if they exist in case of Person with Email but no GitLabId" in { + "prefer model values if they exist in case of Person with Email but no GitLabId" in forAll(personEntities(withoutGitLabId, withEmail) map (_.toMaybe[entities.Person.WithEmail])) { case Some(model) => val kg = model.copy( @@ -78,9 +77,8 @@ class PersonMergerSpec extends AnyWordSpec with should.Matchers with ScalaCheckP .pure[Try] case None => fail("Cannot convert to entities.person") } - } - "prefer model values if they exist in case of Person without Email and GitLabId" in { + "prefer model values if they exist in case of Person without Email and GitLabId" in forAll(personEntities(withoutGitLabId, withoutEmail) map (_.toMaybe[entities.Person.WithNameOnly])) { case Some(model) => val kg = model.copy( @@ -95,6 +93,5 @@ class PersonMergerSpec extends AnyWordSpec with should.Matchers with ScalaCheckP .pure[Try] case None => fail("Cannot convert to entities.person") } - } } } diff --git a/triples-store-client/src/test/scala/io/renku/triplesstore/client/model/TripleObjectSpec.scala b/triples-store-client/src/test/scala/io/renku/triplesstore/client/model/TripleObjectSpec.scala index 4236494070..e879284140 100644 --- a/triples-store-client/src/test/scala/io/renku/triplesstore/client/model/TripleObjectSpec.scala +++ b/triples-store-client/src/test/scala/io/renku/triplesstore/client/model/TripleObjectSpec.scala @@ -28,8 +28,7 @@ import org.scalatest.wordspec.AnyWordSpec class TripleObjectSpec extends AnyWordSpec with should.Matchers with TableDrivenPropertyChecks { - "show" should { - + "show" should forAll { Table( "type" -> "value generator", @@ -50,5 +49,4 @@ class TripleObjectSpec extends AnyWordSpec with should.Matchers with TableDriven obj.show shouldBe obj.value.toString } } - } } diff --git a/triples-store-client/src/test/scala/io/renku/triplesstore/client/sparql/SparqlEncoderSpec.scala b/triples-store-client/src/test/scala/io/renku/triplesstore/client/sparql/SparqlEncoderSpec.scala index 7cf4df1f1d..09c03b9d7c 100644 --- a/triples-store-client/src/test/scala/io/renku/triplesstore/client/sparql/SparqlEncoderSpec.scala +++ b/triples-store-client/src/test/scala/io/renku/triplesstore/client/sparql/SparqlEncoderSpec.scala @@ -85,18 +85,16 @@ class SparqlEncoderSpec extends AnyWordSpec with should.Matchers with ScalaCheck obj.asSparql.sparql shouldBe s"<${URIref.encode(obj.show)}>" } - "be able to encode a Triple as Fragment" in { + "be able to encode a Triple as Fragment" in forAll { (triple: Triple) => triple.asSparql.sparql shouldBe s"<${URIref.encode(triple.subject.show)}> <${URIref.encode(triple.predicate.show)}> ${triple.obj.asSparql.sparql}.\n" } - } - "be able to encode a Quad as Fragment" in { + "be able to encode a Quad as Fragment" in forAll { (quad: Quad) => quad.asSparql.sparql shouldBe s"GRAPH <${URIref.encode(quad.graphId.show)}> { ${quad.triple.asSparql.sparql} }" } - } } } diff --git a/utils/common/src/main/scala/io/renku/compression/Zip.scala b/utils/common/src/main/scala/io/renku/compression/Zip.scala index cc95634717..b14d996465 100644 --- a/utils/common/src/main/scala/io/renku/compression/Zip.scala +++ b/utils/common/src/main/scala/io/renku/compression/Zip.scala @@ -30,8 +30,8 @@ import scala.util.Try import scala.util.control.NonFatal trait Zip { - def zip[F[_]: Sync](content: String): F[Array[Byte]] - def unzip(bytes: Array[Byte]): Either[Exception, String] + def zip[F[_]: Sync](content: String): F[Array[Byte]] + def unzip(bytes: Array[Byte]): Either[Exception, String] } object Zip extends Zip { diff --git a/utils/common/src/test/scala/io/renku/cache/KeySpec.scala b/utils/common/src/test/scala/io/renku/cache/KeySpec.scala index 399e86f5da..a9dc494b14 100644 --- a/utils/common/src/test/scala/io/renku/cache/KeySpec.scala +++ b/utils/common/src/test/scala/io/renku/cache/KeySpec.scala @@ -40,7 +40,7 @@ class KeySpec extends AnyWordSpec with should.Matchers with IOSpec with ScalaChe key.accessedAt shouldBe key.createdAt } - "retain order based on the respective property" in { + "retain order based on the respective property" in forAll { values: List[String] => val keys = values.distinct.zipWithIndex.map { case (v, ts) => new Key(v, ts, values.size - ts) @@ -49,9 +49,8 @@ class KeySpec extends AnyWordSpec with should.Matchers with IOSpec with ScalaChe keys.sorted(Key.Order.oldest[String]) shouldBe keys.sortBy(_.createdAt) keys.sorted(Key.Order.leastRecentlyUsed[String]) shouldBe keys.sortBy(_.accessedAt) } - } - "distinguish different values with same properties" in { + "distinguish different values with same properties" in forAll { values: List[String] => val keys = values.distinct.map(v => new Key(v, 1, 1)) @@ -59,6 +58,5 @@ class KeySpec extends AnyWordSpec with should.Matchers with IOSpec with ScalaChe TreeSet.from(keys)(Key.Order.oldest[String]).size shouldBe keys.size TreeSet.from(keys)(Key.Order.leastRecentlyUsed[String]).size shouldBe keys.size } - } } } diff --git a/utils/common/src/test/scala/io/renku/compression/ZipSpec.scala b/utils/common/src/test/scala/io/renku/compression/ZipSpec.scala index 56c2b008ef..71f90442f9 100644 --- a/utils/common/src/test/scala/io/renku/compression/ZipSpec.scala +++ b/utils/common/src/test/scala/io/renku/compression/ZipSpec.scala @@ -45,12 +45,11 @@ class ZipSpec extends AsyncWordSpec with AsyncIOSpec with should.Matchers with E "zip" should { - "fail with a meaningful error if zipping fails" in { + "fail with a meaningful error if zipping fails" in Zip.zip[IO](null).assertThrowsError[Exception] { exception => exception.getMessage shouldBe "Zipping content failed" Option(exception.getCause) shouldBe a[Some[_]] } - } } "unzip" should { diff --git a/utils/common/src/test/scala/io/renku/control/RateLimitSpec.scala b/utils/common/src/test/scala/io/renku/control/RateLimitSpec.scala index 1ca4971b39..3cab8b620c 100644 --- a/utils/common/src/test/scala/io/renku/control/RateLimitSpec.scala +++ b/utils/common/src/test/scala/io/renku/control/RateLimitSpec.scala @@ -35,29 +35,25 @@ class RateLimitSpec extends AnyWordSpec with RateLimitGenerators with ScalaCheck "from" should { - "instantiate from '/seq' value" in { + "instantiate from '/seq' value" in forAll(positiveLongs(max = Integer.MAX_VALUE)) { int => RateLimit.from[EitherWithThrowable, Target](s"$int/sec") shouldBe Right(RateLimit(int, Second)) } - } - "instantiate from '/min' value" in { + "instantiate from '/min' value" in forAll(positiveLongs(max = Integer.MAX_VALUE)) { int => RateLimit.from[EitherWithThrowable, Target](s"$int/min") shouldBe Right(RateLimit(int, Minute)) } - } - "instantiate from '/hour' value" in { + "instantiate from '/hour' value" in forAll(positiveLongs(max = Integer.MAX_VALUE)) { int => RateLimit.from[EitherWithThrowable, Target](s"$int/hour") shouldBe Right(RateLimit(int, Hour)) } - } - "instantiate from '/day' value" in { + "instantiate from '/day' value" in forAll(positiveLongs(max = Integer.MAX_VALUE)) { int => RateLimit.from[EitherWithThrowable, Target](s"$int/day") shouldBe Right(RateLimit(int, Day)) } - } "return failure if 0" in { val Left(exception) = RateLimit.from[EitherWithThrowable, Target]("0/sec") @@ -90,19 +86,18 @@ class RateLimitSpec extends AnyWordSpec with RateLimitGenerators with ScalaCheck "toString" should { - "produce a string in format '/'" in { + "produce a string in format '/'" in forAll(rateLimits) { case rateLimit @ RateLimit(rate, Second) => rateLimit.toString shouldBe s"$rate/sec" case rateLimit @ RateLimit(rate, Minute) => rateLimit.toString shouldBe s"$rate/min" case rateLimit @ RateLimit(rate, Hour) => rateLimit.toString shouldBe s"$rate/hour" case rateLimit @ RateLimit(rate, Day) => rateLimit.toString shouldBe s"$rate/day" } - } } "/" should { - "make the rate limit x times slower than initially" in { + "make the rate limit x times slower than initially" in forAll(rateLimits[Target], positiveInts()) { (rateLimit, divider) => whenever { (rateLimit.items.value * (1 day).toMillis / (rateLimit.per.multiplierFor(MILLISECONDS) * divider)).toLong > 0 @@ -118,7 +113,6 @@ class RateLimitSpec extends AnyWordSpec with RateLimitGenerators with ScalaCheck } } } - } "fail if resulting RateLimit below 1/day" in { val Left(exception) = RateLimit(1L, per = Day) / 2 diff --git a/utils/config/src/test/scala/io/renku/crypto/SecretConfigReaderSpec.scala b/utils/config/src/test/scala/io/renku/crypto/SecretConfigReaderSpec.scala index 564557eccd..3da4fcf3ae 100644 --- a/utils/config/src/test/scala/io/renku/crypto/SecretConfigReaderSpec.scala +++ b/utils/config/src/test/scala/io/renku/crypto/SecretConfigReaderSpec.scala @@ -45,8 +45,7 @@ class SecretConfigReaderSpec val keyName = "secret" - "read an ASCII secret" in { - + "read an ASCII secret" in forAll(aesCryptoSecrets) { secret => val config = ConfigFactory.parseMap( Map(keyName -> secret.decodeAscii.fold(throw _, identity)).asJava @@ -54,7 +53,6 @@ class SecretConfigReaderSpec ConfigSource.fromConfig(config).at(keyName).load[Secret].value shouldBe secret } - } // we need to keep this functionality due to backward compatibility // where Base64 encoded values were coming to the reader diff --git a/utils/gitlab/src/test/scala/io/renku/http/client/AccessTokenSpec.scala b/utils/gitlab/src/test/scala/io/renku/http/client/AccessTokenSpec.scala index b2b0814a74..843f270e34 100644 --- a/utils/gitlab/src/test/scala/io/renku/http/client/AccessTokenSpec.scala +++ b/utils/gitlab/src/test/scala/io/renku/http/client/AccessTokenSpec.scala @@ -42,11 +42,10 @@ class AccessTokenSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho personalAccessTokens.generateOne shouldBe a[Sensitive] } - "be instantiatable from a non-blank String" in { + "be instantiatable from a non-blank String" in forAll(nonEmptyStrings()) { value => PersonalAccessToken.from(value).map(_.value) shouldBe Right(value) } - } "fail instantiation for a blank String" in { val Left(exception) = PersonalAccessToken.from(" ") @@ -61,11 +60,10 @@ class AccessTokenSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho userOAuthAccessTokens.generateOne shouldBe a[Sensitive] } - "be instantiatable from a non-blank String" in { + "be instantiatable from a non-blank String" in forAll(nonEmptyStrings()) { value => UserOAuthAccessToken.from(value).map(_.value) shouldBe Right(value) } - } "fail instantiation for a blank String" in { val Left(exception) = UserOAuthAccessToken.from(" ") @@ -80,11 +78,10 @@ class AccessTokenSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sho projectAccessTokens.generateOne shouldBe a[Sensitive] } - "be instantiatable from a non-blank String" in { + "be instantiatable from a non-blank String" in forAll(nonEmptyStrings()) { value => ProjectAccessToken.from(value).map(_.value) shouldBe Right(value) } - } "fail instantiation for a blank String" in { val Left(exception) = ProjectAccessToken.from(" ") diff --git a/utils/gitlab/src/test/scala/io/renku/http/client/GitLabClientSpec.scala b/utils/gitlab/src/test/scala/io/renku/http/client/GitLabClientSpec.scala index fa649dad02..c3c72d82e0 100644 --- a/utils/gitlab/src/test/scala/io/renku/http/client/GitLabClientSpec.scala +++ b/utils/gitlab/src/test/scala/io/renku/http/client/GitLabClientSpec.scala @@ -225,8 +225,7 @@ class GitLabClientSpec } } - "post(Multipart)" should { - + "post(Multipart)" should forAll(tokenScenarios) { (tokenType, accessToken: AccessToken) => s"send the given multipart request with the $tokenType to the endpoint" in new TestCase { @@ -261,10 +260,8 @@ class GitLabClientSpec .unsafeRunSync() shouldBe () } } - } - - "put" should { + "put" should forAll(tokenScenarios) { (tokenType, accessToken: AccessToken) => s"send the given multipart request with the $tokenType to the endpoint" in new TestCase { @@ -299,7 +296,6 @@ class GitLabClientSpec .unsafeRunSync() shouldBe () } } - } "delete" should { diff --git a/utils/gitlab/src/test/scala/io/renku/http/client/GitLabUrlSpec.scala b/utils/gitlab/src/test/scala/io/renku/http/client/GitLabUrlSpec.scala index a00380879c..c9001e542f 100644 --- a/utils/gitlab/src/test/scala/io/renku/http/client/GitLabUrlSpec.scala +++ b/utils/gitlab/src/test/scala/io/renku/http/client/GitLabUrlSpec.scala @@ -29,11 +29,10 @@ class GitLabUrlSpec extends AnyWordSpec with ScalaCheckPropertyChecks with shoul "from" should { - "instantiate GitLabUrl when valid url is given" in { + "instantiate GitLabUrl when valid url is given" in forAll(httpUrls()) { path => GitLabUrl.from(path).map(_.value).value shouldBe path } - } "instantiate GitLabUrl when valid url is given with a slash at the end" in { val path = httpUrls().generateOne diff --git a/utils/http4s-client/src/test/scala/io/renku/http/rest/SortBySpec.scala b/utils/http4s-client/src/test/scala/io/renku/http/rest/SortBySpec.scala index 904988a76c..afe9479374 100644 --- a/utils/http4s-client/src/test/scala/io/renku/http/rest/SortBySpec.scala +++ b/utils/http4s-client/src/test/scala/io/renku/http/rest/SortBySpec.scala @@ -30,11 +30,10 @@ class SortBySpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "from" should { - "return the valid Sort.By instance for a valid name and direction" in { + "return the valid Sort.By instance for a valid name and direction" in forAll(testSortBys) { sort => TestSort.from(serialize(sort.sortBy.head)) shouldBe Right(sort.sortBy.head) } - } "return Left for a invalid name" in { val Left(exception) = TestSort.from(s"invalid:$Desc") @@ -62,13 +61,12 @@ class SortBySpec extends AnyWordSpec with ScalaCheckPropertyChecks with should.M "sort" should { - "decode a valid sort query parameter" in { + "decode a valid sort query parameter" in forAll(testSortBys) { sort => Map("sort" -> Seq(serialize(sort.sortBy.head))) match { case TestSort.sort(actual) => actual shouldBe Validated.validNel(sort.sortBy.toList) } } - } "fail to decode an invalid sort query parameter" in { Map("sort" -> Seq(s"invalid:$Desc")) match { diff --git a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingHeadersSpec.scala b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingHeadersSpec.scala index f2b99fa63c..da36d376d9 100644 --- a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingHeadersSpec.scala +++ b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingHeadersSpec.scala @@ -47,97 +47,89 @@ class PagingHeadersSpec "from" should { s"generate $Total, $TotalPages, $PerPage, $Page, $NextPage, $PrevPage and $Link headers " + - "if current page is neither the first nor the last page" in { - - forAll(currentPageNeitherFirstNorLast) { response => - import response._ - import response.pagingInfo._ - import response.pagingInfo.pagingRequest._ - - implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) - - val totalPages = findTotalPages(pagingInfo) - PagingHeaders.from(response) should contain theSameElementsAs Set( - Header.Raw(ci"Total", total.toString), - Header.Raw(ci"Total-Pages", totalPages.toString), - Header.Raw(ci"Per-Page", perPage.toString), - Header.Raw(ci"Page", page.toString), - Header.Raw(ci"Next-Page", (page.value + 1).toString), - Header.Raw(ci"Prev-Page", (page.value - 1).toString), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value + 1))}>; rel="next""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value - 1))}>; rel="prev""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") - ) - } + "if current page is neither the first nor the last page" in + forAll(currentPageNeitherFirstNorLast) { response => + import response._ + import response.pagingInfo._ + import response.pagingInfo.pagingRequest._ + + implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) + + val totalPages = findTotalPages(pagingInfo) + PagingHeaders.from(response) should contain theSameElementsAs Set( + Header.Raw(ci"Total", total.toString), + Header.Raw(ci"Total-Pages", totalPages.toString), + Header.Raw(ci"Per-Page", perPage.toString), + Header.Raw(ci"Page", page.toString), + Header.Raw(ci"Next-Page", (page.value + 1).toString), + Header.Raw(ci"Prev-Page", (page.value - 1).toString), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value + 1))}>; rel="next""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value - 1))}>; rel="prev""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") + ) } s"generate $Total, $TotalPages, $PerPage, $Page, $PrevPage and $Link headers " + - "if current page is the last page" in { - - forAll(currentPageLast) { response => - import response._ - import response.pagingInfo._ - import response.pagingInfo.pagingRequest._ - - implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) - - val totalPages = findTotalPages(pagingInfo) - PagingHeaders.from(response) should contain theSameElementsAs Set( - Header.Raw(ci"Total", total.toString), - Header.Raw(ci"Total-Pages", totalPages.toString), - Header.Raw(ci"Per-Page", perPage.toString), - Header.Raw(ci"Page", page.toString), - Header.Raw(ci"Prev-Page", (page.value - 1).toString), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value - 1))}>; rel="prev""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") - ) - } + "if current page is the last page" in + forAll(currentPageLast) { response => + import response._ + import response.pagingInfo._ + import response.pagingInfo.pagingRequest._ + + implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) + + val totalPages = findTotalPages(pagingInfo) + PagingHeaders.from(response) should contain theSameElementsAs Set( + Header.Raw(ci"Total", total.toString), + Header.Raw(ci"Total-Pages", totalPages.toString), + Header.Raw(ci"Per-Page", perPage.toString), + Header.Raw(ci"Page", page.toString), + Header.Raw(ci"Prev-Page", (page.value - 1).toString), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value - 1))}>; rel="prev""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") + ) } s"generate $Total, $TotalPages, $PerPage, $Page, $NextPage and $Link headers " + - "if current page is the first page" in { - - forAll(currentPageFirst) { response => - import response._ - import response.pagingInfo._ - import response.pagingInfo.pagingRequest._ - - implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) - - val totalPages = findTotalPages(pagingInfo) - PagingHeaders.from(response) should contain theSameElementsAs Set( - Header.Raw(ci"Total", total.toString), - Header.Raw(ci"Total-Pages", totalPages.toString), - Header.Raw(ci"Per-Page", perPage.toString), - Header.Raw(ci"Page", page.toString), - Header.Raw(ci"Next-Page", (page.value + 1).toString), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value + 1))}>; rel="next""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") - ) - } + "if current page is the first page" in + forAll(currentPageFirst) { response => + import response._ + import response.pagingInfo._ + import response.pagingInfo.pagingRequest._ + + implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) + + val totalPages = findTotalPages(pagingInfo) + PagingHeaders.from(response) should contain theSameElementsAs Set( + Header.Raw(ci"Total", total.toString), + Header.Raw(ci"Total-Pages", totalPages.toString), + Header.Raw(ci"Per-Page", perPage.toString), + Header.Raw(ci"Page", page.toString), + Header.Raw(ci"Next-Page", (page.value + 1).toString), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> (page.value + 1))}>; rel="next""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> totalPages)}>; rel="last"""") + ) } s"generate $Total, $TotalPages, $PerPage, $Page and $Link headers " + - "if there's one page only" in { - - forAll(onePageOnly) { response => - import response.pagingInfo._ - import response.pagingInfo.pagingRequest._ - - implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) - - PagingHeaders.from(response) should contain theSameElementsAs Set( - Header.Raw(ci"Total", total.toString), - Header.Raw(ci"Total-Pages", "1"), - Header.Raw(ci"Per-Page", perPage.toString), - Header.Raw(ci"Page", page.toString), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), - Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> 1)}>; rel="last"""") - ) - } + "if there's one page only" in + forAll(onePageOnly) { response => + import response.pagingInfo._ + import response.pagingInfo.pagingRequest._ + + implicit val resourceUrl: UrlTestType = resourceUrlFrom(page, perPage) + + PagingHeaders.from(response) should contain theSameElementsAs Set( + Header.Raw(ci"Total", total.toString), + Header.Raw(ci"Total-Pages", "1"), + Header.Raw(ci"Per-Page", perPage.toString), + Header.Raw(ci"Page", page.toString), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> first.value)}>; rel="first""""), + Header.Raw(ci"Link", s"""<${resourceUrl ? (pageParamName -> 1)}>; rel="last"""") + ) } s"generate $Total, $TotalPages, $PerPage, $Page and $Link headers " + diff --git a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingRequestSpec.scala b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingRequestSpec.scala index 9d2fcdd75f..8bff1435e8 100644 --- a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingRequestSpec.scala +++ b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingRequestSpec.scala @@ -38,13 +38,12 @@ class PagingRequestSpec "page" should { - "decode a valid page query parameter" in { + "decode a valid page query parameter" in forAll { page: Page => Map("page" -> Seq(page.toString)) match { case PagingRequest.Decoders.page(actual) => actual shouldBe Some(Validated.validNel(page)) } } - } "fail to decode a non-int page query parameter" in { Map("page" -> Seq("abc")) match { @@ -73,13 +72,12 @@ class PagingRequestSpec "perPage" should { - "decode a valid per_page values" in { + "decode a valid per_page values" in forAll { perPage: PerPage => Map("per_page" -> Seq(perPage.toString)) match { case PagingRequest.Decoders.perPage(actual) => actual shouldBe Some(Validated.validNel(perPage)) } } - } "fail to decode a non-int values" in { Map("per_page" -> Seq("abc")) match { diff --git a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingResponseSpec.scala b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingResponseSpec.scala index 4cd6752efd..5aa44a5b5f 100644 --- a/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingResponseSpec.scala +++ b/utils/http4s-client/src/test/scala/io/renku/http/rest/paging/PagingResponseSpec.scala @@ -48,7 +48,7 @@ class PagingResponseSpec "from" should { - "fail if the number of results > perPage" in { + "fail if the number of results > perPage" in forAll(perPages, pages) { (perPage, page) => val results = nonEmptyStrings().generateList(min = perPage.value + 1, max = perPage.value * 2) val total = Total((page.value - 1) * perPage.value + results.size) @@ -59,9 +59,8 @@ class PagingResponseSpec result.failure.exception shouldBe an[IllegalArgumentException] result.failure.exception.getMessage shouldBe s"PagingResponse cannot be instantiated for ${results.size} results, total: $total, page: $page and perPage: $perPage" } - } - "fix the total if results is not empty and (page - 1) * perPage + results.size > total" in { + "fix the total if results is not empty and (page - 1) * perPage + results.size > total" in forAll(perPages.retryUntil(_.value > 1), pages.retryUntil(_.value > 1)) { (perPage, page) => val results = nonEmptyStrings().generateNonEmptyList(max = perPage.value).toList val total = positiveInts((page.value - 1) * perPage.value + results.size - 1).map(_.value).generateAs(Total) @@ -73,9 +72,8 @@ class PagingResponseSpec result.success.value.pagingInfo.pagingRequest shouldBe request result.success.value.pagingInfo.total shouldBe Total((page.value - 1) * perPage.value + results.size) } - } - "instantiate successfully if results list is empty and (page - 1) * perPage > total" in { + "instantiate successfully if results list is empty and (page - 1) * perPage > total" in forAll(perPages.retryUntil(_.value > 1), pages.retryUntil(_.value > 1)) { (perPage, page) => val results = List.empty[String] val total = positiveInts((page.value - 1) * perPage.value + results.size - 1).map(_.value).generateAs(Total) @@ -87,9 +85,8 @@ class PagingResponseSpec result.success.value.pagingInfo.pagingRequest shouldBe request result.success.value.pagingInfo.total shouldBe total } - } - "instantiate successfully in other cases" in { + "instantiate successfully in other cases" in forAll(perPages, pages) { (perPage, page) => val results = nonEmptyStrings().generateNonEmptyList(max = perPage.value).toList val total = ints(min = (page.value - 1) * perPage.value + results.size).generateAs(Total) @@ -101,7 +98,6 @@ class PagingResponseSpec result.success.value.pagingInfo.pagingRequest shouldBe request result.success.value.pagingInfo.total shouldBe total } - } } "from with no total given" should { diff --git a/utils/sentry/src/test/scala/io/renku/config/sentry/SentryConfigSpec.scala b/utils/sentry/src/test/scala/io/renku/config/sentry/SentryConfigSpec.scala index a5038b5a9a..b7e1b15629 100644 --- a/utils/sentry/src/test/scala/io/renku/config/sentry/SentryConfigSpec.scala +++ b/utils/sentry/src/test/scala/io/renku/config/sentry/SentryConfigSpec.scala @@ -52,27 +52,26 @@ class SentryConfigSpec extends AnyWordSpec with ScalaCheckPropertyChecks with sh } "return a SentryConfig if 'services.sentry.enabled' is 'true' and all " + - "'services.sentry.url', 'services.sentry.environment', 'service-name' and 'version' are set" in { - forAll(sentryConfigs) { sentryConfig: SentryConfig => - val config = ConfigFactory.parseMap( - Map[String, AnyRef]( - "service-name" -> sentryConfig.serviceName.value, - "services" -> Map( - "sentry" -> Map( - "enabled" -> "true", - "dsn" -> sentryConfig.baseUrl.value, - "environment" -> sentryConfig.environmentName.value - ).asJava + "'services.sentry.url', 'services.sentry.environment', 'service-name' and 'version' are set" in + forAll(sentryConfigs) { sentryConfig: SentryConfig => + val config = ConfigFactory.parseMap( + Map[String, AnyRef]( + "service-name" -> sentryConfig.serviceName.value, + "services" -> Map( + "sentry" -> Map( + "enabled" -> "true", + "dsn" -> sentryConfig.baseUrl.value, + "environment" -> sentryConfig.environmentName.value ).asJava ).asJava - ) + ).asJava + ) - val versionConfig = ConfigFactory.parseMap( - Map("version" -> sentryConfig.serviceVersion.value).asJava - ) + val versionConfig = ConfigFactory.parseMap( + Map("version" -> sentryConfig.serviceVersion.value).asJava + ) - SentryConfig[Try](config, versionConfig.some) shouldBe sentryConfig.some.pure[Try] - } + SentryConfig[Try](config, versionConfig.some) shouldBe sentryConfig.some.pure[Try] } "fail if 'services.sentry.enabled' is 'true' but 'services.sentry.dsn' is invalid" in { diff --git a/webhook-service/src/test/scala/io/renku/webhookservice/ProjectInfoFinderSpec.scala b/webhook-service/src/test/scala/io/renku/webhookservice/ProjectInfoFinderSpec.scala index 8346afabf1..d71916f40b 100644 --- a/webhook-service/src/test/scala/io/renku/webhookservice/ProjectInfoFinderSpec.scala +++ b/webhook-service/src/test/scala/io/renku/webhookservice/ProjectInfoFinderSpec.scala @@ -82,10 +82,9 @@ class ProjectInfoFinderSpec ) shouldBe a[MatchError] } - it should "return an Exception if remote client responds with unexpected body" in { + it should "return an Exception if remote client responds with unexpected body" in mapResponse(Status.Ok, Request(), Response().withEntity(json"{}")) .assertThrowsError[Exception](_.getMessage should startWith("Invalid message body: Could not decode JSON")) - } private lazy val project = consumerProjects.generateOne private lazy val projectId = project.id diff --git a/webhook-service/src/test/scala/io/renku/webhookservice/eventstatus/StatusInfoSpec.scala b/webhook-service/src/test/scala/io/renku/webhookservice/eventstatus/StatusInfoSpec.scala index 8d1f3d203b..569906b265 100644 --- a/webhook-service/src/test/scala/io/renku/webhookservice/eventstatus/StatusInfoSpec.scala +++ b/webhook-service/src/test/scala/io/renku/webhookservice/eventstatus/StatusInfoSpec.scala @@ -35,8 +35,7 @@ class StatusInfoSpec extends AnyWordSpec with should.Matchers with ScalaCheckPro "encode" should { - "produce Json from a StatusInfo of an activated project with a NonZero progress" in { - + "produce Json from a StatusInfo of an activated project with a NonZero progress" in forAll(eventInfos()) { eventInfo => val info = StatusInfo.activated(eventInfo) @@ -54,7 +53,6 @@ class StatusInfoSpec extends AnyWordSpec with should.Matchers with ScalaCheckPro } }""".deepDropNullValues } - } "produce Json from a StatusInfo of a non-activated project" in { @@ -76,7 +74,7 @@ class ProgressSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope "from" should { - "return Progress.NonZero for the given EventStatus" in { + "return Progress.NonZero for the given EventStatus" in forAll { (eventStatus: EventStatus) => val progressStatus = Progress.from(eventStatus) @@ -84,7 +82,6 @@ class ProgressSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope progressStatus.total shouldBe EventStatusProgress.Stage.Final.value progressStatus.completion shouldBe EventStatusProgress(eventStatus).completion } - } } "Progress.Zero to have final stage set to EventStatusProgress.Stage.Final" in { @@ -94,8 +91,7 @@ class ProgressSpec extends AnyWordSpec with should.Matchers with ScalaCheckPrope class DetailsSpec extends AnyWordSpec with should.Matchers with TableDrivenPropertyChecks { - "Details" should { - + "Details" should forAll( Table( ("eventStatus", "status", "message", "maybeMessage"), @@ -130,5 +126,4 @@ class DetailsSpec extends AnyWordSpec with should.Matchers with TableDrivenPrope details.maybeDetails shouldBe maybeEventMessage.map(_.value) } } - } } diff --git a/webhook-service/src/test/scala/io/renku/webhookservice/hookfetcher/ProjectHookFetcherSpec.scala b/webhook-service/src/test/scala/io/renku/webhookservice/hookfetcher/ProjectHookFetcherSpec.scala index ee1db867ec..d934b2f854 100644 --- a/webhook-service/src/test/scala/io/renku/webhookservice/hookfetcher/ProjectHookFetcherSpec.scala +++ b/webhook-service/src/test/scala/io/renku/webhookservice/hookfetcher/ProjectHookFetcherSpec.scala @@ -85,10 +85,9 @@ class ProjectHookFetcherSpec } Status.Unauthorized :: Status.Forbidden :: Nil foreach { status => - it should show"return None if remote client responds with $status" in { + it should show"return None if remote client responds with $status" in mapResponse(status, Request(), Response()) .asserting(_ shouldBe None -> None) - } } it should "return an Exception if remote client responds with status any of OK , NOT_FOUND, UNAUTHORIZED or FORBIDDEN" in { @@ -97,10 +96,9 @@ class ProjectHookFetcherSpec } shouldBe a[MatchError] } - it should "return a RuntimeException if remote client responds with unexpected body" in { + it should "return a RuntimeException if remote client responds with unexpected body" in mapResponse((Status.Ok, Request(), Response().withEntity("""{}"""))) .assertThrowsError[Exception](_.getMessage should include("Could not decode JSON")) - } private implicit val logger: TestLogger[IO] = TestLogger[IO]() private implicit val glClient: GitLabClient[IO] = mock[GitLabClient[IO]]