From 600445143335e9f0af24c3f58d4a3a88e1597242 Mon Sep 17 00:00:00 2001 From: Som Snytt Date: Fri, 15 Mar 2024 22:24:26 -0700 Subject: [PATCH] Prefer docstrings.style = AsteriskSpace --- .scalafmt.conf | 2 + .../scala/org/scalacheck/bench/GenBench.scala | 48 +- .../org/scalacheck/ChooseSpecification.scala | 8 +- .../org/scalacheck/GenSpecification.scala | 22 +- .../scalacheck/ShrinkSpecificationJVM.scala | 4 +- .../util/BuildableVersionSpecific.scala | 2 +- .../util/BuildableVersionSpecific.scala | 2 +- .../main/scala/org/scalacheck/Arbitrary.scala | 138 ++-- .../src/main/scala/org/scalacheck/Gen.scala | 736 +++++++++--------- .../src/main/scala/org/scalacheck/Prop.scala | 176 ++--- .../scala/org/scalacheck/Properties.scala | 58 +- .../main/scala/org/scalacheck/Shrink.scala | 8 +- .../src/main/scala/org/scalacheck/Test.scala | 116 +-- .../org/scalacheck/commands/Commands.scala | 148 ++-- .../main/scala/org/scalacheck/rng/Seed.scala | 70 +- .../scalacheck/time/JavaTimeArbitrary.scala | 16 +- .../org/scalacheck/time/JavaTimeChoose.scala | 62 +- .../org/scalacheck/util/CmdLineParser.scala | 2 +- .../org/scalacheck/util/ConsoleReporter.scala | 8 +- .../scala/org/scalacheck/util/Pretty.scala | 16 +- .../time/OrderingVersionSpecific.scala | 2 +- .../time/OrderingVersionSpecific.scala | 6 +- 22 files changed, 826 insertions(+), 824 deletions(-) diff --git a/.scalafmt.conf b/.scalafmt.conf index 1b646fcd..5d4d53d5 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -11,6 +11,8 @@ danglingParentheses { callSite = false } +docstrings.style = AsteriskSpace + newlines { source = keep } diff --git a/bench/src/main/scala/org/scalacheck/bench/GenBench.scala b/bench/src/main/scala/org/scalacheck/bench/GenBench.scala index c9043bf5..c7b85129 100644 --- a/bench/src/main/scala/org/scalacheck/bench/GenBench.scala +++ b/bench/src/main/scala/org/scalacheck/bench/GenBench.scala @@ -17,30 +17,30 @@ import org.scalacheck.Gen import org.scalacheck.rng.Seed /** Generator benchmarks - * - * Since generators may run very quickly (or very slowly) depending on the seed and size parameter used, we want to - * make sure these are held constant across runs. Otherwise, we might believe a particular change made a given - * generator faster (or slower) when in fact we just got lucky (or unlucky). - * - * We use `seedCount` to choose how many seeds we will benchmark with. For each seed, we run the given generator. So if - * `seedCount` is 100, the average time we get is the time to generate values for the 100 seeds we started with. - * - * The size parameter also plays a major role in how long generators take. ScalaCheck's default parameters start with - * 100. You can benchmark additional size parameters to see how changes to this parameter effect generator run time. - * - * Finally, a generator's `apply` method may fail to generate a value. This might allow a slow generator that fails 50% - * of the time to appear faster than other generators that don't fail. Since we expect all generators to be able to - * succeed, we benchmark using `pureApply`, which will retry up to 100 times before crashing. This way, there's no - * chance that a flaky generator gets an advantage during benchmarking. - * - * In theory, we should do as much work as possible outside the benchmark methods to avoid benchmarking construction - * time. However, since many generators are constructed inside of `flatMap` calls during generation we do want these - * constructors to also run as quickly as possible. For that reason, we mostly choose to assemble our generators inside - * the benchmark methods. - * - * Prefer to add new benchmarks instead of modifying existing ones. This will enable us to compare the results for a - * given benchmark over time. - */ + * + * Since generators may run very quickly (or very slowly) depending on the seed and size parameter used, we want to + * make sure these are held constant across runs. Otherwise, we might believe a particular change made a given + * generator faster (or slower) when in fact we just got lucky (or unlucky). + * + * We use `seedCount` to choose how many seeds we will benchmark with. For each seed, we run the given generator. So if + * `seedCount` is 100, the average time we get is the time to generate values for the 100 seeds we started with. + * + * The size parameter also plays a major role in how long generators take. ScalaCheck's default parameters start with + * 100. You can benchmark additional size parameters to see how changes to this parameter effect generator run time. + * + * Finally, a generator's `apply` method may fail to generate a value. This might allow a slow generator that fails 50% + * of the time to appear faster than other generators that don't fail. Since we expect all generators to be able to + * succeed, we benchmark using `pureApply`, which will retry up to 100 times before crashing. This way, there's no + * chance that a flaky generator gets an advantage during benchmarking. + * + * In theory, we should do as much work as possible outside the benchmark methods to avoid benchmarking construction + * time. However, since many generators are constructed inside of `flatMap` calls during generation we do want these + * constructors to also run as quickly as possible. For that reason, we mostly choose to assemble our generators inside + * the benchmark methods. + * + * Prefer to add new benchmarks instead of modifying existing ones. This will enable us to compare the results for a + * given benchmark over time. + */ @State(Scope.Benchmark) @BenchmarkMode(Array(Mode.AverageTime)) @OutputTimeUnit(TimeUnit.MICROSECONDS) diff --git a/core/jvm/src/test/scala/org/scalacheck/ChooseSpecification.scala b/core/jvm/src/test/scala/org/scalacheck/ChooseSpecification.scala index f3e28f4b..c6bc0e0a 100644 --- a/core/jvm/src/test/scala/org/scalacheck/ChooseSpecification.scala +++ b/core/jvm/src/test/scala/org/scalacheck/ChooseSpecification.scala @@ -61,8 +61,8 @@ object ChooseSpecification extends Properties("Choose") with time.OrderingVersio property("choose[ZonedDateTime]") = chooseProp[ZonedDateTime] /** Generate a duration which is at least 1 second smaller than the max duration the type can support. We use this to - * avoid the incredibly unlikely event of overflowing in the handle-min-nanos-duration test. - */ + * avoid the incredibly unlikely event of overflowing in the handle-min-nanos-duration test. + */ lazy val genOneSecondLessThanMaxDuration: Gen[Duration] = Gen.choose(Duration.ofSeconds(Long.MinValue), Duration.ofSeconds(Long.MaxValue - 1L, 999999999L)) @@ -80,8 +80,8 @@ object ChooseSpecification extends Properties("Choose") with time.OrderingVersio } /** Generate an Instant which is at least 1 second smaller than the max Instant the type can support. We use this to - * avoid the incredibly unlikely event of overflowing in the handle-min-nanos-instant test. - */ + * avoid the incredibly unlikely event of overflowing in the handle-min-nanos-instant test. + */ lazy val genOneSecondLessThanMaxInstant: Gen[Instant] = Gen.choose(Instant.MIN, Instant.MAX.minusSeconds(1L)) diff --git a/core/jvm/src/test/scala/org/scalacheck/GenSpecification.scala b/core/jvm/src/test/scala/org/scalacheck/GenSpecification.scala index 45a9dace..abc5ed22 100644 --- a/core/jvm/src/test/scala/org/scalacheck/GenSpecification.scala +++ b/core/jvm/src/test/scala/org/scalacheck/GenSpecification.scala @@ -273,13 +273,13 @@ object GenSpecification extends Properties("Gen") with GenSpecificationVersionSp } /** Expect: - * {{{ - * 25% 1, 2, 3 - * 25% 1, 2, 4 - * 25% 1, 4, 3 - * 25% 4, 2, 3 - * }}} - */ + * {{{ + * 25% 1, 2, 3 + * 25% 1, 2, 4 + * 25% 1, 4, 3 + * 25% 4, 2, 3 + * }}} + */ property("distributed pick") = { val lst = (1 to 4).toIterable val n = 3 @@ -640,10 +640,10 @@ object GenSpecification extends Properties("Gen") with GenSpecificationVersionSp } /** Ensure that the given generator runs deterministically with the same initialSeed parameter or the same seed. - * - * This test should be run with a generator that can produce multiple values, and where the odds of 30 trials coming - * back with the same result is low enough that the test won't produce many false positives. - */ + * + * This test should be run with a generator that can produce multiple values, and where the odds of 30 trials coming + * back with the same result is low enough that the test won't produce many false positives. + */ def testDeterministicGen[A](g: Gen[A]): Prop = { val params0 = Gen.Parameters.default val params1 = params0.withInitialSeed(1248163264L) diff --git a/core/jvm/src/test/scala/org/scalacheck/ShrinkSpecificationJVM.scala b/core/jvm/src/test/scala/org/scalacheck/ShrinkSpecificationJVM.scala index e8449cde..899bf9e2 100644 --- a/core/jvm/src/test/scala/org/scalacheck/ShrinkSpecificationJVM.scala +++ b/core/jvm/src/test/scala/org/scalacheck/ShrinkSpecificationJVM.scala @@ -14,8 +14,8 @@ import Shrink.shrink import ShrinkSpecification.shrinkClosure /** @todo - * should work not only JVM but also Scala.js - */ + * should work not only JVM but also Scala.js + */ object ShrinkSpecificationJVM extends Properties("Shrink JVM") { property("list") = forAll { (l: List[Int]) => diff --git a/core/shared/src/main/scala-2.12-/org/scalacheck/util/BuildableVersionSpecific.scala b/core/shared/src/main/scala-2.12-/org/scalacheck/util/BuildableVersionSpecific.scala index 43ffcb9a..95a18bca 100644 --- a/core/shared/src/main/scala-2.12-/org/scalacheck/util/BuildableVersionSpecific.scala +++ b/core/shared/src/main/scala-2.12-/org/scalacheck/util/BuildableVersionSpecific.scala @@ -33,7 +33,7 @@ private[util] class ArrayListBuilder[T] extends Builder[T, ArrayList[T]] { } /** CanBuildFrom instances implementing Serializable, so that the objects capturing those can be serializable too. - */ + */ object SerializableCanBuildFroms { implicit def listCanBuildFrom[T]: CanBuildFrom[List[T], T, List[T]] = new CanBuildFrom[List[T], T, List[T]] with Serializable { diff --git a/core/shared/src/main/scala-2.13+/org/scalacheck/util/BuildableVersionSpecific.scala b/core/shared/src/main/scala-2.13+/org/scalacheck/util/BuildableVersionSpecific.scala index 1e95b7e5..c4221cc5 100644 --- a/core/shared/src/main/scala-2.13+/org/scalacheck/util/BuildableVersionSpecific.scala +++ b/core/shared/src/main/scala-2.13+/org/scalacheck/util/BuildableVersionSpecific.scala @@ -31,7 +31,7 @@ private[util] class ArrayListBuilder[T] extends Builder[T, ArrayList[T]] { } /** Factory instances implementing Serializable, so that the objects capturing those can be serializable too. - */ + */ // Named `...CanBuildFroms` for 2.12 source compatibility (`import SerializableCanBuildFroms._`) // Can be renamed to `SerializableFactories` in a major release. object SerializableCanBuildFroms { diff --git a/core/shared/src/main/scala/org/scalacheck/Arbitrary.scala b/core/shared/src/main/scala/org/scalacheck/Arbitrary.scala index 753424d1..c5483e51 100644 --- a/core/shared/src/main/scala/org/scalacheck/Arbitrary.scala +++ b/core/shared/src/main/scala/org/scalacheck/Arbitrary.scala @@ -20,65 +20,65 @@ import util.Buildable import util.SerializableCanBuildFroms._ /** Define an arbitrary generator for properties - * - * The [[Arbitrary]] module defines implicit generator instances for common types. - * - * The implicit definitions of [[Arbitrary]] provide type-directed [[Gen]]s so they are available for properties, - * generators, or other definitions of [[Arbitrary]]. - * - * ScalaCheck expects an implicit [[Arbitrary]] instance is in scope for [[Prop]]s that are defined with functions, - * like [[Prop$.forAll[T1,P](g1* Prop.forAll]] and so on. - * - * For instance, the definition for `Arbitrary[Boolean]` is used by `Prop.forAll` to automatically provide a - * `Gen[Boolean]` when one of the parameters is a `Boolean`: - * - * {{{ - * Prop.forAll { (b: Boolean) => - * b || !b - * } - * }}} - * - * Thanks to `Arbitrary`, you don't need to provide an explicit `Gen` instance to `Prop.forAll`. For instance, this is - * unnecessary: - * - * {{{ - * val genBool: Gen[Boolean] = Gen.oneOf(true,false) - * Prop.forAll(genBool) { (b: Boolean) => - * b || !b - * } - * }}} - * - * Since an arbitrary `Gen` for `Boolean` is defined in `Arbitrary`, it can be summoned with `Arbitrary.arbitrary` in - * cases where you need to provide one explicitly: - * - * {{{ - * val genBool: Gen[Boolean] = Arbitrary.arbitrary[Boolean] - * val genSmallInt: Gen[Int] = Gen.choose(0, 9) - * Prop.forAll(genBool, genSmallInt) { (b: Boolean, i: Int) => - * i < 10 && b || !b - * } - * }}} - * - * For a user-defined `MyClass`, writing the following requires that there exists an implicit `Arbitrary[MyClass]` - * instance: - * - * {{{ - * Prop.forAll { (myClass: MyClass) => - * ... - * } - * }}} - * - * The implicit definition of `Arbitrary[MyClass]` would look like: - * - * {{{ - * implicit val arbMyClass: Arbitrary[MyClass] = Arbitrary { - * ... - * } - * }}} - * - * The factory method `Arbitrary(...)` expects a generator of type `Gen[MyClass]` then it will return an instance of - * `Arbitrary[MyClass]`. - */ + * + * The [[Arbitrary]] module defines implicit generator instances for common types. + * + * The implicit definitions of [[Arbitrary]] provide type-directed [[Gen]]s so they are available for properties, + * generators, or other definitions of [[Arbitrary]]. + * + * ScalaCheck expects an implicit [[Arbitrary]] instance is in scope for [[Prop]]s that are defined with functions, + * like [[Prop$.forAll[T1,P](g1* Prop.forAll]] and so on. + * + * For instance, the definition for `Arbitrary[Boolean]` is used by `Prop.forAll` to automatically provide a + * `Gen[Boolean]` when one of the parameters is a `Boolean`: + * + * {{{ + * Prop.forAll { (b: Boolean) => + * b || !b + * } + * }}} + * + * Thanks to `Arbitrary`, you don't need to provide an explicit `Gen` instance to `Prop.forAll`. For instance, this is + * unnecessary: + * + * {{{ + * val genBool: Gen[Boolean] = Gen.oneOf(true,false) + * Prop.forAll(genBool) { (b: Boolean) => + * b || !b + * } + * }}} + * + * Since an arbitrary `Gen` for `Boolean` is defined in `Arbitrary`, it can be summoned with `Arbitrary.arbitrary` in + * cases where you need to provide one explicitly: + * + * {{{ + * val genBool: Gen[Boolean] = Arbitrary.arbitrary[Boolean] + * val genSmallInt: Gen[Int] = Gen.choose(0, 9) + * Prop.forAll(genBool, genSmallInt) { (b: Boolean, i: Int) => + * i < 10 && b || !b + * } + * }}} + * + * For a user-defined `MyClass`, writing the following requires that there exists an implicit `Arbitrary[MyClass]` + * instance: + * + * {{{ + * Prop.forAll { (myClass: MyClass) => + * ... + * } + * }}} + * + * The implicit definition of `Arbitrary[MyClass]` would look like: + * + * {{{ + * implicit val arbMyClass: Arbitrary[MyClass] = Arbitrary { + * ... + * } + * }}} + * + * The factory method `Arbitrary(...)` expects a generator of type `Gen[MyClass]` then it will return an instance of + * `Arbitrary[MyClass]`. + */ sealed abstract class Arbitrary[T] extends Serializable { def arbitrary: Gen[T] } @@ -103,7 +103,7 @@ private[scalacheck] sealed trait ArbitraryLowPriority { def arbitrary[T](implicit a: Arbitrary[T]): Gen[T] = a.arbitrary /** ** Arbitrary instances for each AnyVal *** - */ + */ /** Arbitrary AnyVal */ implicit lazy val arbAnyVal: Arbitrary[AnyVal] = Arbitrary(oneOf( @@ -174,7 +174,7 @@ private[scalacheck] sealed trait ArbitraryLowPriority { Arbitrary(Gen.const(())) /** Arbitrary instances of other common types - */ + */ /** Arbitrary instance of String */ implicit lazy val arbString: Arbitrary[String] = @@ -307,10 +307,10 @@ private[scalacheck] sealed trait ArbitraryLowPriority { Arbitrary(Gen.finiteDuration) /** Arbitrary instance of Duration. - * - * In addition to `FiniteDuration` values, this can generate `Duration.Inf`, `Duration.MinusInf`, and - * `Duration.Undefined`. - */ + * + * In addition to `FiniteDuration` values, this can generate `Duration.Inf`, `Duration.MinusInf`, and + * `Duration.Undefined`. + */ implicit lazy val arbDuration: Arbitrary[Duration] = Arbitrary(Gen.duration) @@ -385,8 +385,8 @@ private[scalacheck] sealed trait ArbitraryLowPriority { Arbitrary(Gen.oneOf(arbitrary[T].map(Success(_)), arbitrary[Throwable].map(Failure(_)))) /** Arbitrary instance of any [[org.scalacheck.util.Buildable]] container (such as lists, arrays, streams / lazy - * lists, etc). The maximum size of the container depends on the size generation parameter. - */ + * lists, etc). The maximum size of the container depends on the size generation parameter. + */ implicit def arbContainer[C[_], T](implicit a: Arbitrary[T], b: Buildable[T, C[T]], @@ -394,8 +394,8 @@ private[scalacheck] sealed trait ArbitraryLowPriority { ): Arbitrary[C[T]] = Arbitrary(buildableOf[C[T], T](arbitrary[T])) /** Arbitrary instance of any [[org.scalacheck.util.Buildable]] container (such as maps). The maximum size of the - * container depends on the size generation parameter. - */ + * container depends on the size generation parameter. + */ implicit def arbContainer2[C[_, _], T, U](implicit a: Arbitrary[(T, U)], b: Buildable[(T, U), C[T, U]], diff --git a/core/shared/src/main/scala/org/scalacheck/Gen.scala b/core/shared/src/main/scala/org/scalacheck/Gen.scala index 69d2091d..fc70d388 100644 --- a/core/shared/src/main/scala/org/scalacheck/Gen.scala +++ b/core/shared/src/main/scala/org/scalacheck/Gen.scala @@ -25,186 +25,186 @@ import util.SerializableCanBuildFroms._ import ScalaVersionSpecific._ /** A generator produces values for [[Prop]]s - * - * This module provides: - * 1. Definitions for non-arbitrary generators, - * 1. Factories to construct generators, - * 1. Methods to modify a generator, and - * 1. Various combinators for producing generators of values for more complex data types. - * - * Explicit generators aren't required to write [[Prop]]s: - * - * {{{ - * Prop.forAll { (n: Int) => - * n == n - * } - * }}} - * - * The [[Prop]] above is defined with parameters only and without an explicit generator, because generators are - * implicitly provided by [[Arbitrary]] for various data types. - * - * However, it's not uncommon to need to write explicit custom generators: - * - * {{{ - * val genInt: Gen[Int] = Gen.choose(1,10) - * Prop.forAll(genInt) { (n: Int) => - * 1 <= n && n <= 10 - * } - * }}} - * - * This is a simple definition of a generator for booleans: - * {{{ - * val genBool: Gen[Boolean] = Gen.oneOf(true,false) - * }}} - * - * The above definition isn't necessary, though. The same boolean generator is defined in [[Arbitrary]] as an implicit - * declaration for automatically parameterizing [[Prop]]s. Instead, use the generator that is defined in [[Arbitrary]] - * and available from the polymorphic method [[Arbitrary.arbitrary]] with an explicit type parameter: - * - * {{{ - * val genBool: Gen[Boolean] = Arbitrary.arbitrary[Boolean] - * }}} - * - * Alternatively, this is a boolean generator, but one that always produces true: - * {{{ - * val genBool = Gen.const(true) - * }}} - * - * This is a generator of booleans that is true at a 2-to-1 ratio: - * {{{ - * val genBool = Gen.frequency(2 -> true, 1 -> false) - * }}} - * - * This is a boolean generator that will produce true 75% of the time: - * {{{ - * val genBool = Gen.prob(0.75) - * }}} - * - * For more information on designing custom generators and the motivations for doing so, see chapter 6, ''Generators in - * Detail'', of the book ''ScalaCheck: The Definitive Guide'' (2013) by Rickard Nilsson published by Artima Press. - * - * This is an example of a custom generator for integers: - * {{{ - * val genSmallInt: Gen[Int] = Gen.choose(-100,100) - * }}} - * - * This can be used to generate different collections of zero or more small integers: - * {{{ - * val genListOfInts: Gen[List[Int]] = Gen.listOf(genSmallInt) - * - * val genSeqOfInts: Gen[Seq[Int]] = Gen.someOf(-100 to 100) - * - * val genVectorOfInts: Gen[Vector[Int]] = Gen.containerOf[Vector,Int](genSmallInt) - * - * val genMap: Gen[Map[Int,Boolean]] = Gen.mapOf(Gen.zip(genSmallInt, genBool)) - * - * val genOptionalInt: Gen[Option[Int]] = Gen.option(genSmallInt) - * }}} - * - * Or collections of one or more small integers: - * {{{ - * val genListOfInts: Gen[List[Int]] = Gen.nonEmptyListOf(genSmallInt) - * - * val genSeqOfInts: Gen[Seq[Int]] = Gen.atLeastOne(-100 to 100) - * - * val genVectorOfInts: Gen[Vector[Int]] = Gen.nonEmptyContainerOf[Vector,Int](genSmallInt) - * - * val genMap: Gen[Map[Int,Boolean]] = Gen.nonEmptyMap(Gen.zip(genSmallInt, genBool)) - * - * val genOptionalInt: Gen[Option[Int]] = Gen.some(genSmallInt) - * }}} - * - * The class methods for [[Gen]] should be familiar with those in the [[scala.collection Scala collections API]]: - * - * - [[map]] - Apply a function to generated values - * - [[flatMap]] - Apply a function that returns a generator - * - [[filter]] - Use values that satisfy a predicate - * - * The [[Gen]] class also supports for-comprehensions to compose complex generators: - * - * {{{ - * val genPerson = for { - * firstName <- Gen.oneOf("Alan", "Ada", "Alonzo") - * lastName <- Gen.oneOf("Lovelace", "Turing", "Church") - * age <- Gen.choose(0,100) if (age >= 18) - * } yield Person(firstName, lastName, age) - * }}} - * - * Constructors and factories for generators: - * - [[Gen$.const const]] - Always generates a single value - * - [[Gen$.oneOf[T](t0* oneOf]] - Generate a value from a list of values - * - [[Gen$.atLeastOne[T](g1* atLeastOne]] - Generate a collection with at least one value from a list - * - [[Gen$.someOf[T](l* someOf]] - Generate a collection with zero or more values from a list - * - [[Gen$.choose choose]] - Generate numeric values in an (inclusive) range - * - [[Gen$.frequency frequency]] - Choose from multiple values with a weighted distribution - * - * Combinators of generators: - * - [[Gen$.buildableOf buildableOf]] - Generates a collection with a generator - * - [[Gen$.buildableOfN buildableOfN]] - Generates a collection of at most ''n'' elements - * - [[Gen$.nonEmptyBuildableOf nonEmptyBuildableOf]] - Generates a non-empty collection - * - [[Gen$.containerOf containerOf]] - Generates a collection with a generator - * - [[Gen$.containerOfN containerOfN]] - Generates a collection of at most ''n'' elements - * - [[Gen$.nonEmptyContainerOf nonEmptyContainerOf]] - Generates a non-empty collection - * - [[Gen$.either either]] - Generate a disjoint union of [[scala.util.Either]] - * - infiniteLazyList - Generates an infinite lazy list - * - [[Gen$.infiniteStream infiniteStream]] - Generates an infinite stream - * - [[Gen$.listOf listOf]] - Generates a list of random length - * - [[Gen$.listOfN listOfN]] - Generates a list of at most ''n'' elements - * - [[Gen$.nonEmptyListOf nonEmptyListOf]] - Generates a non-empty list of random length. - * - [[Gen$.mapOf mapOf]] - Generates a [[scala.collection.Map]] - * - [[Gen$.mapOfN mapOfN]] - Generates a [[scala.collection.Map]] with at most ''n'' elements - * - [[Gen$.nonEmptyMap nonEmptyMap]] - Generates a non-empty map of random length - * - [[Gen$.option option]] - Generate values of [[scala.Some]] and [[scala.None]] - * - [[Gen$.pick[T](n:Int,g1* pick]] - A generator that randomly picks ''n'' elements from a list - * - [[Gen$.sequence sequence]] - Sequences generators. - * - [[Gen$.some some]] - A generator of [[scala.Some]] - * - [[Gen.someOf[T](g1* someOf]] - A generator that picks a random number of elements from a list - * - [[Gen$.stringOf stringOf]] - Generate string of characters - * - [[Gen$.stringOfN stringOfN]] - Generate string of at most ''n'' characters - * - [[Gen$.nonEmptyStringOf nonEmptyStringOf]] - Generate a non-empty string of characters - * - * Methods for working with [[Gen]] internals: - * - [[Gen$.resize resize]] - Creates a resized version of a generator - * - [[Gen$.parameterized parameterized]] - Generator with the parameters - * - [[Gen$.size size]] - Generate with the value of the default size parameter - * - [[Gen$.sized sized]] - Build a generator using the default size parameter - * - * Methods for probabilistic generators: - * - [[Gen$.exponential exponential]] - Generate numbers according to an exponential distribution - * - [[Gen$.gaussian gaussian]] - Generates numbers according to a Gaussian distribution - * - [[Gen$.geometric geometric]] - Generates numbers according to a geometric distribution - * - [[Gen$.poisson poisson]] - Generates numbers according to a Poisson distribution - * - [[Gen$.prob prob]] - Generates a boolean for the probability of true - * - * Definitions for generating various, non-arbitrary, common values of strings and characters: - * - [[Gen$.alphaChar alphaChar]] - Generates an alpha character - * - [[Gen$.alphaStr alphaStr]] - Generates a string of alpha characters - * - [[Gen$.numChar numChar]] - Generates a numerical character - * - [[Gen$.numStr numStr]] - Generates a string of digits - * - [[Gen$.alphaNumChar alphaNumChar]] - Generates an alphanumerical character - * - [[Gen$.alphaNumStr alphaNumStr]] - Generates a string of alphanumerical characters - * - [[Gen$.alphaLowerChar alphaLowerChar]] - Generates a lower-case alpha character - * - [[Gen$.alphaLowerStr alphaLowerStr]] - Generates a string of lower-case alpha characters - * - [[Gen$.alphaUpperChar alphaUpperChar]] - Generates an upper-case alpha character - * - [[Gen$.alphaUpperStr alphaUpperStr]] - Generates a string of upper-case alpha characters - * - [[Gen$.asciiChar asciiChar]] - Generates an ASCII character - * - [[Gen$.asciiStr asciiStr]] - Generates a string of ASCII characters - * - [[Gen$.identifier identifier]] - Generates an identifier - * - [[Gen$.uuid uuid]] - Generates a UUID - * - [[Gen$.hexChar hexChar]] - Generates a character of a hexadecimal digit - * - [[Gen$.hexStr hexStr]] - Generates a string of hexadecimal digits - * - * Definitions for generating arbitrary values of commonly used types in Scala are defined elsewhere, see - * [[Arbitrary]]. - * - * There are a couple of factory methods that are for advanced uses of generators: - * - [[Gen$.delay delay]] - Generate a value of an expression by-name - * - [[Gen$.lzy lzy]] - Lazily generate a value of an expression - * - [[Gen$.fail fail]] - Fail to generate any values of a type - * - [[Gen$.recursive recursive]] - A fixed point generator - * - [[Gen$.resultOf[T,R0](f* resultOf]] - Generate values with a function or class - * - [[Gen$.zip[T1](g1* zip]] - Generate tuples - */ + * + * This module provides: + * 1. Definitions for non-arbitrary generators, + * 1. Factories to construct generators, + * 1. Methods to modify a generator, and + * 1. Various combinators for producing generators of values for more complex data types. + * + * Explicit generators aren't required to write [[Prop]]s: + * + * {{{ + * Prop.forAll { (n: Int) => + * n == n + * } + * }}} + * + * The [[Prop]] above is defined with parameters only and without an explicit generator, because generators are + * implicitly provided by [[Arbitrary]] for various data types. + * + * However, it's not uncommon to need to write explicit custom generators: + * + * {{{ + * val genInt: Gen[Int] = Gen.choose(1,10) + * Prop.forAll(genInt) { (n: Int) => + * 1 <= n && n <= 10 + * } + * }}} + * + * This is a simple definition of a generator for booleans: + * {{{ + * val genBool: Gen[Boolean] = Gen.oneOf(true,false) + * }}} + * + * The above definition isn't necessary, though. The same boolean generator is defined in [[Arbitrary]] as an implicit + * declaration for automatically parameterizing [[Prop]]s. Instead, use the generator that is defined in [[Arbitrary]] + * and available from the polymorphic method [[Arbitrary.arbitrary]] with an explicit type parameter: + * + * {{{ + * val genBool: Gen[Boolean] = Arbitrary.arbitrary[Boolean] + * }}} + * + * Alternatively, this is a boolean generator, but one that always produces true: + * {{{ + * val genBool = Gen.const(true) + * }}} + * + * This is a generator of booleans that is true at a 2-to-1 ratio: + * {{{ + * val genBool = Gen.frequency(2 -> true, 1 -> false) + * }}} + * + * This is a boolean generator that will produce true 75% of the time: + * {{{ + * val genBool = Gen.prob(0.75) + * }}} + * + * For more information on designing custom generators and the motivations for doing so, see chapter 6, ''Generators in + * Detail'', of the book ''ScalaCheck: The Definitive Guide'' (2013) by Rickard Nilsson published by Artima Press. + * + * This is an example of a custom generator for integers: + * {{{ + * val genSmallInt: Gen[Int] = Gen.choose(-100,100) + * }}} + * + * This can be used to generate different collections of zero or more small integers: + * {{{ + * val genListOfInts: Gen[List[Int]] = Gen.listOf(genSmallInt) + * + * val genSeqOfInts: Gen[Seq[Int]] = Gen.someOf(-100 to 100) + * + * val genVectorOfInts: Gen[Vector[Int]] = Gen.containerOf[Vector,Int](genSmallInt) + * + * val genMap: Gen[Map[Int,Boolean]] = Gen.mapOf(Gen.zip(genSmallInt, genBool)) + * + * val genOptionalInt: Gen[Option[Int]] = Gen.option(genSmallInt) + * }}} + * + * Or collections of one or more small integers: + * {{{ + * val genListOfInts: Gen[List[Int]] = Gen.nonEmptyListOf(genSmallInt) + * + * val genSeqOfInts: Gen[Seq[Int]] = Gen.atLeastOne(-100 to 100) + * + * val genVectorOfInts: Gen[Vector[Int]] = Gen.nonEmptyContainerOf[Vector,Int](genSmallInt) + * + * val genMap: Gen[Map[Int,Boolean]] = Gen.nonEmptyMap(Gen.zip(genSmallInt, genBool)) + * + * val genOptionalInt: Gen[Option[Int]] = Gen.some(genSmallInt) + * }}} + * + * The class methods for [[Gen]] should be familiar with those in the [[scala.collection Scala collections API]]: + * + * - [[map]] - Apply a function to generated values + * - [[flatMap]] - Apply a function that returns a generator + * - [[filter]] - Use values that satisfy a predicate + * + * The [[Gen]] class also supports for-comprehensions to compose complex generators: + * + * {{{ + * val genPerson = for { + * firstName <- Gen.oneOf("Alan", "Ada", "Alonzo") + * lastName <- Gen.oneOf("Lovelace", "Turing", "Church") + * age <- Gen.choose(0,100) if (age >= 18) + * } yield Person(firstName, lastName, age) + * }}} + * + * Constructors and factories for generators: + * - [[Gen$.const const]] - Always generates a single value + * - [[Gen$.oneOf[T](t0* oneOf]] - Generate a value from a list of values + * - [[Gen$.atLeastOne[T](g1* atLeastOne]] - Generate a collection with at least one value from a list + * - [[Gen$.someOf[T](l* someOf]] - Generate a collection with zero or more values from a list + * - [[Gen$.choose choose]] - Generate numeric values in an (inclusive) range + * - [[Gen$.frequency frequency]] - Choose from multiple values with a weighted distribution + * + * Combinators of generators: + * - [[Gen$.buildableOf buildableOf]] - Generates a collection with a generator + * - [[Gen$.buildableOfN buildableOfN]] - Generates a collection of at most ''n'' elements + * - [[Gen$.nonEmptyBuildableOf nonEmptyBuildableOf]] - Generates a non-empty collection + * - [[Gen$.containerOf containerOf]] - Generates a collection with a generator + * - [[Gen$.containerOfN containerOfN]] - Generates a collection of at most ''n'' elements + * - [[Gen$.nonEmptyContainerOf nonEmptyContainerOf]] - Generates a non-empty collection + * - [[Gen$.either either]] - Generate a disjoint union of [[scala.util.Either]] + * - infiniteLazyList - Generates an infinite lazy list + * - [[Gen$.infiniteStream infiniteStream]] - Generates an infinite stream + * - [[Gen$.listOf listOf]] - Generates a list of random length + * - [[Gen$.listOfN listOfN]] - Generates a list of at most ''n'' elements + * - [[Gen$.nonEmptyListOf nonEmptyListOf]] - Generates a non-empty list of random length. + * - [[Gen$.mapOf mapOf]] - Generates a [[scala.collection.Map]] + * - [[Gen$.mapOfN mapOfN]] - Generates a [[scala.collection.Map]] with at most ''n'' elements + * - [[Gen$.nonEmptyMap nonEmptyMap]] - Generates a non-empty map of random length + * - [[Gen$.option option]] - Generate values of [[scala.Some]] and [[scala.None]] + * - [[Gen$.pick[T](n:Int,g1* pick]] - A generator that randomly picks ''n'' elements from a list + * - [[Gen$.sequence sequence]] - Sequences generators. + * - [[Gen$.some some]] - A generator of [[scala.Some]] + * - [[Gen.someOf[T](g1* someOf]] - A generator that picks a random number of elements from a list + * - [[Gen$.stringOf stringOf]] - Generate string of characters + * - [[Gen$.stringOfN stringOfN]] - Generate string of at most ''n'' characters + * - [[Gen$.nonEmptyStringOf nonEmptyStringOf]] - Generate a non-empty string of characters + * + * Methods for working with [[Gen]] internals: + * - [[Gen$.resize resize]] - Creates a resized version of a generator + * - [[Gen$.parameterized parameterized]] - Generator with the parameters + * - [[Gen$.size size]] - Generate with the value of the default size parameter + * - [[Gen$.sized sized]] - Build a generator using the default size parameter + * + * Methods for probabilistic generators: + * - [[Gen$.exponential exponential]] - Generate numbers according to an exponential distribution + * - [[Gen$.gaussian gaussian]] - Generates numbers according to a Gaussian distribution + * - [[Gen$.geometric geometric]] - Generates numbers according to a geometric distribution + * - [[Gen$.poisson poisson]] - Generates numbers according to a Poisson distribution + * - [[Gen$.prob prob]] - Generates a boolean for the probability of true + * + * Definitions for generating various, non-arbitrary, common values of strings and characters: + * - [[Gen$.alphaChar alphaChar]] - Generates an alpha character + * - [[Gen$.alphaStr alphaStr]] - Generates a string of alpha characters + * - [[Gen$.numChar numChar]] - Generates a numerical character + * - [[Gen$.numStr numStr]] - Generates a string of digits + * - [[Gen$.alphaNumChar alphaNumChar]] - Generates an alphanumerical character + * - [[Gen$.alphaNumStr alphaNumStr]] - Generates a string of alphanumerical characters + * - [[Gen$.alphaLowerChar alphaLowerChar]] - Generates a lower-case alpha character + * - [[Gen$.alphaLowerStr alphaLowerStr]] - Generates a string of lower-case alpha characters + * - [[Gen$.alphaUpperChar alphaUpperChar]] - Generates an upper-case alpha character + * - [[Gen$.alphaUpperStr alphaUpperStr]] - Generates a string of upper-case alpha characters + * - [[Gen$.asciiChar asciiChar]] - Generates an ASCII character + * - [[Gen$.asciiStr asciiStr]] - Generates a string of ASCII characters + * - [[Gen$.identifier identifier]] - Generates an identifier + * - [[Gen$.uuid uuid]] - Generates a UUID + * - [[Gen$.hexChar hexChar]] - Generates a character of a hexadecimal digit + * - [[Gen$.hexStr hexStr]] - Generates a string of hexadecimal digits + * + * Definitions for generating arbitrary values of commonly used types in Scala are defined elsewhere, see + * [[Arbitrary]]. + * + * There are a couple of factory methods that are for advanced uses of generators: + * - [[Gen$.delay delay]] - Generate a value of an expression by-name + * - [[Gen$.lzy lzy]] - Lazily generate a value of an expression + * - [[Gen$.fail fail]] - Fail to generate any values of a type + * - [[Gen$.recursive recursive]] - A fixed point generator + * - [[Gen$.resultOf[T,R0](f* resultOf]] - Generate values with a function or class + * - [[Gen$.zip[T1](g1* zip]] - Generate tuples + */ sealed abstract class Gen[+T] extends Serializable { self => //// Private interface //// @@ -241,12 +241,12 @@ sealed abstract class Gen[+T] extends Serializable { self => } /** Evaluate this generator with the given parameters. - * - * The generator will attempt to generate a valid `T` value. If a valid value is not produced it may retry several - * times, determined by the `retries` parameter (which defaults to 100). - * - * If all the retries fail it will throw a `Gen.RetrievalError` exception. - */ + * + * The generator will attempt to generate a valid `T` value. If a valid value is not produced it may retry several + * times, determined by the `retries` parameter (which defaults to 100). + * + * If all the retries fail it will throw a `Gen.RetrievalError` exception. + */ def pureApply(p: Gen.Parameters, seed: Seed, retries: Int = 100): T = doPureApply(p, seed, retries).retrieve.get @@ -260,24 +260,24 @@ sealed abstract class Gen[+T] extends Serializable { self => } /** Create a new generator that uses this generator to produce a value that fulfills the given condition. If the - * condition is not fulfilled, the generator fails (returns None). Also, make sure that the provided test property is - * side-effect free, e.g. it should not use external vars. - */ + * condition is not fulfilled, the generator fails (returns None). Also, make sure that the provided test property is + * side-effect free, e.g. it should not use external vars. + */ def filter(p: T => Boolean): Gen[T] = suchThat(p) /** Create a new generator that uses this generator to produce a value that doesn't fulfill the given condition. If - * the condition is fulfilled, the generator fails (returns None). Also, make sure that the provided test property is - * side-effect free, e.g. it should not use external vars. - */ + * the condition is fulfilled, the generator fails (returns None). Also, make sure that the provided test property is + * side-effect free, e.g. it should not use external vars. + */ def filterNot(p: T => Boolean): Gen[T] = suchThat(x => !p(x)) /** Creates a non-strict filtered version of this generator. */ def withFilter(p: T => Boolean): WithFilter = new WithFilter(p) /** Create a new generator that uses this generator to produce a value that fulfills the given condition. If the - * condition is not fulfilled, the generator fails (returns None). Also, make sure that the provided test property is - * side-effect free, e.g. it should not use external vars. This method is identical to [Gen.filter]. - */ + * condition is not fulfilled, the generator fails (returns None). Also, make sure that the provided test property is + * side-effect free, e.g. it should not use external vars. This method is identical to [Gen.filter]. + */ def suchThat(f: T => Boolean): Gen[T] = new Gen[T] { def doApply(p: Gen.Parameters, seed: Seed): Gen.R[T] = @@ -290,11 +290,11 @@ sealed abstract class Gen[+T] extends Serializable { self => case class RetryUntilException(n: Int) extends RuntimeException(s"retryUntil failed after $n attempts") /** Create a generator that calls this generator repeatedly until the given condition is fulfilled. The generated - * value is then returned. Make sure that the provided test property is side-effect free (it should not use external - * vars). - * - * If the generator fails more than maxTries, a RetryUntilException will be thrown. - */ + * value is then returned. Make sure that the provided test property is side-effect free (it should not use external + * vars). + * + * If the generator fails more than maxTries, a RetryUntilException will be thrown. + */ def retryUntil(p: T => Boolean, maxTries: Int): Gen[T] = { require(maxTries > 0) def loop(params: Gen.Parameters, seed: Seed, tries: Int): R[T] = @@ -307,12 +307,12 @@ sealed abstract class Gen[+T] extends Serializable { self => } /** Create a generator that calls this generator repeatedly until the given condition is fulfilled. The generated - * value is then returned. Make sure that the provided test property is side-effect free (it should not use external - * vars). - * - * If the generator fails more than 10000 times, a RetryUntilException will be thrown. You can call `retryUntil` with - * a second parameter to change this number. - */ + * value is then returned. Make sure that the provided test property is side-effect free (it should not use external + * vars). + * + * If the generator fails more than 10000 times, a RetryUntilException will be thrown. You can call `retryUntil` with + * a second parameter to change this number. + */ def retryUntil(p: T => Boolean): Gen[T] = retryUntil(p, 10000) @@ -320,8 +320,8 @@ sealed abstract class Gen[+T] extends Serializable { self => doApply(Gen.Parameters.default, Seed.random()).retrieve /** Returns a new property that holds if and only if both this and the given generator generates the same result, or - * both generators generate no result. - */ + * both generators generate no result. + */ def ==[U](g: Gen[U]): Prop = Prop { prms => // test equality using a random seed val seed = Seed.random() @@ -452,9 +452,9 @@ object Gen extends GenArities with GenVersionSpecific { } /** The size of the generated value. Generator implementations are allowed to freely interpret (or ignore) this - * value. During test execution, the value of this parameter is controlled by [[Test.Parameters.minSize]] and - * [[Test.Parameters.maxSize]]. - */ + * value. During test execution, the value of this parameter is controlled by [[Test.Parameters.minSize]] and + * [[Test.Parameters.maxSize]]. + */ val size: Int private[this] def cpy( @@ -469,7 +469,7 @@ object Gen extends GenArities with GenVersionSpecific { } /** Create a copy of this [[Gen.Parameters]] instance with [[Gen.Parameters.size]] set to the specified value. - */ + */ def withSize(size: Int): Parameters = cpy(size0 = size) @@ -534,7 +534,7 @@ object Gen extends GenArities with GenVersionSpecific { extends IllegalArgumentException(s"invalid bounds: low=$low, high=$high") /** This method gets a ton of use -- so we want it to be as fast as possible for many of our common cases. - */ + */ private def chLng(l: Long, h: Long)(p: P, seed: Seed): R[Long] = { if (h < l) { throw new IllegalBoundsError(l, h) @@ -590,17 +590,17 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generate a random BigInt within [lower, lower + span). - * - * Note that unlike the choose method, whose bounds are inclusive, this method's upper bound is exclusive. We - * determine how many random bits we need (bitLen), and then round up to the nearest number of bytes (byteLen). We - * generate the bytes, possibly truncating the most significant byte (bytes(0)) if bitLen is not evenly-divisible - * by 8. - * - * Finally, we check to see if the BigInt we ended up with is in our range. If it is not, we restart this method. - * The likelihood of needing to restart depends on span. In the worst case we have almost a 50% chance of this - * (which occurs when span is a power of 2 + 1) and in the best case we never restart (which occurs when span is a - * power of 2). - */ + * + * Note that unlike the choose method, whose bounds are inclusive, this method's upper bound is exclusive. We + * determine how many random bits we need (bitLen), and then round up to the nearest number of bytes (byteLen). We + * generate the bytes, possibly truncating the most significant byte (bytes(0)) if bitLen is not evenly-divisible + * by 8. + * + * Finally, we check to see if the BigInt we ended up with is in our range. If it is not, we restart this method. + * The likelihood of needing to restart depends on span. In the worst case we have almost a 50% chance of this + * (which occurs when span is a power of 2 + 1) and in the best case we never restart (which occurs when span is a + * power of 2). + */ private def chBigInteger(lower: BigInteger, span: BigInteger, seed0: Seed): R[BigInteger] = { val bitLen = span.bitLength val byteLen = (bitLen + 7) / 8 @@ -697,29 +697,29 @@ object Gen extends GenArities with GenVersionSpecific { } /** Choose a BigDecimal number between two given numbers. - * - * The minimum scale used will be 34. That means that the fractional part will have at least 34 digits (more if one - * of the given numbers has a scale larger than 34). - * - * The minimum scale was chosen based on Scala's default scale for expanding infinite fractions: - * - * BigDecimal(1) / 3 // 0.3333333333333333333333333333333333 - * - * See chooseBigDecimalScale for more information about scale. - */ + * + * The minimum scale used will be 34. That means that the fractional part will have at least 34 digits (more if one + * of the given numbers has a scale larger than 34). + * + * The minimum scale was chosen based on Scala's default scale for expanding infinite fractions: + * + * BigDecimal(1) / 3 // 0.3333333333333333333333333333333333 + * + * See chooseBigDecimalScale for more information about scale. + */ implicit val chooseBigDecimal: Choose[BigDecimal] = chooseBigDecimalScale(minScale = 34) /** The "scale" of a decimal number refers to the number of digits in the fractional part. For example, 3.0000 has a - * scale of 4. - * - * We can generate an arbitrary number of digits in the decimal expansion of a number, so if a user calls choose(0, - * 1) we need to decide "how much" work to do. The minScale ensures that we do "enough" work to generate - * interesting numbers. - * - * The implicit instance fixes this value, but since users may want to use other scales we expose this method as - * well. - */ + * scale of 4. + * + * We can generate an arbitrary number of digits in the decimal expansion of a number, so if a user calls choose(0, + * 1) we need to decide "how much" work to do. The minScale ensures that we do "enough" work to generate + * interesting numbers. + * + * The implicit instance fixes this value, but since users may want to use other scales we expose this method as + * well. + */ private[this] def chooseBigDecimalScale(minScale: Int): Choose[BigDecimal] = new Choose[BigDecimal] { private val c = chooseJavaBigDecimalScale(minScale) @@ -728,14 +728,14 @@ object Gen extends GenArities with GenVersionSpecific { } /** Choose a java.math.BigDecimal number between two given numbers. - * - * See chooseBigDecimal and chooseBigDecimalScale for more comments. - */ + * + * See chooseBigDecimal and chooseBigDecimalScale for more comments. + */ implicit val chooseJavaBigDecimal: Choose[JavaDecimal] = chooseJavaBigDecimalScale(minScale = 34) /** See chooseBigDecimalScale for comments. - */ + */ private[this] def chooseJavaBigDecimalScale(minScale: Int): Choose[JavaDecimal] = new Choose[JavaDecimal] { def choose(low: JavaDecimal, high: JavaDecimal): Gen[JavaDecimal] = @@ -753,8 +753,8 @@ object Gen extends GenArities with GenVersionSpecific { } /** Transform a Choose[T] to a Choose[U] where T and U are two isomorphic types whose relationship is described by - * the provided transformation functions. (exponential functor map) - */ + * the provided transformation functions. (exponential functor map) + */ def xmap[T, U](from: T => U, to: U => T)(implicit c: Choose[T]): Choose[U] = new Choose[U] { def choose(low: U, high: U): Gen[U] = @@ -771,10 +771,10 @@ object Gen extends GenArities with GenVersionSpecific { def fail[T]: Gen[T] = gen((_, seed) => failed[T](seed)) /** A fixed point generator. This is useful for making recursive structures e.g. - * - * Gen.recursive[List[Int]] { recurse => Gen.choose(0, 10).flatMap { idx => if (idx < 5) recurse.map(idx :: _) else - * Gen.const(idx :: Nil) } } - */ + * + * Gen.recursive[List[Int]] { recurse => Gen.choose(0, 10).flatMap { idx => if (idx < 5) recurse.map(idx :: _) else + * Gen.const(idx :: Nil) } } + */ def recursive[A](fn: Gen[A] => Gen[A]): Gen[A] = { lazy val result: Gen[A] = lzy(fn(result)) result @@ -788,13 +788,13 @@ object Gen extends GenArities with GenVersionSpecific { } /** A generator that generates a random value in the given (inclusive) range. If the range is invalid, an - * IllegalBoundsError exception will be thrown. - */ + * IllegalBoundsError exception will be thrown. + */ def choose[T](min: T, max: T)(implicit c: Choose[T]): Gen[T] = c.choose(min, max) /** Sequences generators. If any of the given generators fails, the resulting generator will also fail. - */ + */ def sequence[C, T](gs: Traversable[Gen[T]])(implicit b: Buildable[T, C]): Gen[C] = { val g = gen { (p, seed) => gs.foldLeft(r(Some(Vector.empty[T]), seed)) { @@ -807,18 +807,18 @@ object Gen extends GenArities with GenVersionSpecific { } /** Monadic recursion on Gen This is a stack-safe loop that is the same as: - * - * {{{ - * - * fn(a).flatMap { - * case Left(a) => tailRec(a)(fn) - * case Right(b) => Gen.const(b) - * } - * - * }}} - * - * which is useful for doing monadic loops without blowing up the stack - */ + * + * {{{ + * + * fn(a).flatMap { + * case Left(a) => tailRec(a)(fn) + * case Right(b) => Gen.const(b) + * } + * + * }}} + * + * which is useful for doing monadic loops without blowing up the stack + */ def tailRecM[A, B](a0: A)(fn: A => Gen[Either[A, B]]): Gen[B] = { @tailrec def tailRecMR(a: A, seed: Seed, labs: Set[String])(fn: (A, Seed) => R[Either[A, B]]): R[B] = { @@ -839,16 +839,16 @@ object Gen extends GenArities with GenVersionSpecific { } /** Wraps a generator lazily. The given parameter is only evaluated once, and not until the wrapper generator is - * evaluated. - */ + * evaluated. + */ def lzy[T](g: => Gen[T]): Gen[T] = { lazy val h = g gen { (p, seed) => h.doApply(p, seed) } } /** Wraps a generator for later evaluation. The given parameter is evaluated each time the wrapper generator is - * evaluated. - */ + * evaluated. + */ def delay[T](g: => Gen[T]): Gen[T] = gen { (p, seed) => g.doApply(p, seed) } @@ -876,9 +876,9 @@ object Gen extends GenArities with GenVersionSpecific { } /** Picks a random value from a list. - * @todo - * Remove this overloaded method in the next major release. See #438. - */ + * @todo + * Remove this overloaded method in the next major release. See #438. + */ def oneOf[T](xs: Seq[T]): Gen[T] = oneOf(xs: Iterable[T]) @@ -921,20 +921,20 @@ object Gen extends GenArities with GenVersionSpecific { } /** Implicit convenience method for using the `frequency` method like this: - * {{{ - * frequency((1, "foo"), (3, "bar")) - * }}} - */ + * {{{ + * frequency((1, "foo"), (3, "bar")) + * }}} + */ implicit def freqTuple[T](t: (Int, T)): (Int, Gen[T]) = (t._1, const(t._2)) //// List Generators //// /** Generates a container of any Traversable type for which there exists an implicit [[org.scalacheck.util.Buildable]] - * instance. The elements in the container will be generated by the given generator. The size of the generated - * container is limited by `n`. Depending on what kind of container that is generated, the resulting container may - * contain fewer elements than `n`, but not more. If the given generator fails generating a value, the complete - * container generator will also fail. - */ + * instance. The elements in the container will be generated by the given generator. The size of the generated + * container is limited by `n`. Depending on what kind of container that is generated, the resulting container may + * contain fewer elements than `n`, but not more. If the given generator fails generating a value, the complete + * container generator will also fail. + */ def buildableOfN[C, T](n: Int, g: Gen[T])(implicit evb: Buildable[T, C], evt: C => Traversable[T] @@ -965,9 +965,9 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates a container of any Traversable type for which there exists an implicit [[org.scalacheck.util.Buildable]] - * instance. The elements in the container will be generated by the given generator. The size of the container is - * bounded by the size parameter used when generating values. - */ + * instance. The elements in the container will be generated by the given generator. The size of the container is + * bounded by the size parameter used when generating values. + */ def buildableOf[C, T](g: Gen[T])(implicit evb: Buildable[T, C], evt: C => Traversable[T] @@ -976,9 +976,9 @@ object Gen extends GenArities with GenVersionSpecific { .flatMap(n => buildableOfN(n, g)(evb, evt)) /** Generates a non-empty container of any Traversable type for which there exists an implicit - * [[org.scalacheck.util.Buildable]] instance. The elements in the container will be generated by the given - * generator. The size of the container is bounded by the size parameter used when generating values. - */ + * [[org.scalacheck.util.Buildable]] instance. The elements in the container will be generated by the given + * generator. The size of the container is bounded by the size parameter used when generating values. + */ def nonEmptyBuildableOf[C, T](g: Gen[T])(implicit evb: Buildable[T, C], evt: C => Traversable[T] @@ -1005,39 +1005,39 @@ object Gen extends GenArities with GenVersionSpecific { ): Gen[C[T]] = nonEmptyBuildableOf[C[T], T](g)(evb, evt) /** Generates a list of random length. The maximum length depends on the size parameter. This method is equal to - * calling `containerOf[List,T](g)`. - */ + * calling `containerOf[List,T](g)`. + */ def listOf[T](g: => Gen[T]) = buildableOf[List[T], T](g) /** Generates a non-empty list of random length. The maximum length depends on the size parameter. This method is - * equal to calling `nonEmptyContainerOf[List,T](g)`. - */ + * equal to calling `nonEmptyContainerOf[List,T](g)`. + */ def nonEmptyListOf[T](g: => Gen[T]) = nonEmptyBuildableOf[List[T], T](g) /** Generates a list with at most the given number of elements. This method is equal to calling - * `containerOfN[List,T](n,g)`. - */ + * `containerOfN[List,T](n,g)`. + */ def listOfN[T](n: Int, g: Gen[T]) = buildableOfN[List[T], T](n, g) /** Generates a map of random length. The maximum length depends on the size parameter. This method is equal to - * calling containerOf[Map,(T,U)](g). - */ + * calling containerOf[Map,(T,U)](g). + */ def mapOf[T, U](g: => Gen[(T, U)]) = buildableOf[Map[T, U], (T, U)](g) /** Generates a non-empty map of random length. The maximum length depends on the size parameter. This method is equal - * to calling nonEmptyContainerOf[Map,(T,U)](g). - */ + * to calling nonEmptyContainerOf[Map,(T,U)](g). + */ def nonEmptyMap[T, U](g: => Gen[(T, U)]) = nonEmptyBuildableOf[Map[T, U], (T, U)](g) /** Generates a map with at most the given number of elements. This method is equal to calling - * containerOfN[Map,(T,U)](n,g). - */ + * containerOfN[Map,(T,U)](n,g). + */ def mapOfN[T, U](n: Int, g: Gen[(T, U)]) = buildableOfN[Map[T, U], (T, U)](n, g) /** Generates an infinite stream. - * - * Failures in the underlying generator may terminate the stream. Otherwise it will continue forever. - */ + * + * Failures in the underlying generator may terminate the stream. Otherwise it will continue forever. + */ def infiniteStream[T](g: => Gen[T]): Gen[Stream[T]] = { val attemptsPerItem = 10 def unfold(p: P, seed: Seed, attemptsLeft: Int): Stream[T] = @@ -1075,9 +1075,9 @@ object Gen extends GenArities with GenVersionSpecific { choose(1, gs.length + 2).flatMap(pick(_, g1, g2, gs: _*)) /** A generator that randomly picks a given number of elements from a list - * - * The elements are not guaranteed to be permuted in random order. - */ + * + * The elements are not guaranteed to be permuted in random order. + */ def pick[T](n: Int, l: Iterable[T]): Gen[collection.Seq[T]] = { if (n > l.size || n < 0) throw new IllegalArgumentException(s"invalid choice: $n") else if (n == 0) Gen.const(Nil) @@ -1103,15 +1103,15 @@ object Gen extends GenArities with GenVersionSpecific { } /** A generator that randomly picks a given number of elements from a list - * - * The elements are not guaranteed to be permuted in random order. - */ + * + * The elements are not guaranteed to be permuted in random order. + */ def pick[T](n: Int, g1: Gen[T], g2: Gen[T], gn: Gen[T]*): Gen[Seq[T]] = pick(n, g1 +: g2 +: gn).flatMap(sequence[Seq[T], T](_)) /** Takes a function and returns a generator that generates arbitrary results of that function by feeding it with - * arbitrarily generated input parameters. - */ + * arbitrarily generated input parameters. + */ def resultOf[T, R0](f: T => R0)(implicit a: Arbitrary[T]): Gen[R0] = arbitrary[T].map(f) @@ -1160,8 +1160,8 @@ object Gen extends GenArities with GenVersionSpecific { charSample((32.toChar to 126.toChar).toArray) /** Generates a character that can represent a valid hexadecimal digit. This includes both upper and lower case - * values. - */ + * values. + */ val hexChar: Gen[Char] = charSample("0123456789abcdef0123456789ABCDEF".toArray) @@ -1205,7 +1205,7 @@ object Gen extends GenArities with GenVersionSpecific { .flatMap(n => stringOfN(n, gc)) /** Generates a string that starts with a lower-case alpha character, and only contains alphanumerical characters - */ + */ val identifier: Gen[String] = gen { (p, seed0) => val (n, seed1) = Gen.mkSize(p, seed0) @@ -1244,16 +1244,16 @@ object Gen extends GenArities with GenVersionSpecific { stringOf(asciiPrintableChar) /** Generates a string that can represent a valid hexadecimal digit. This includes both upper and lower case values. - */ + */ val hexStr: Gen[String] = stringOf(hexChar) //// Number Generators //// /** Generate a uniformly-distributed Long. - * - * This method has an equally likely method of generating every possible Long value. - */ + * + * This method has an equally likely method of generating every possible Long value. + */ val long: Gen[Long] = gen { (_, s0) => val (n, s1) = s0.long @@ -1261,9 +1261,9 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generate a Double uniformly-distributed in [0, 1). - * - * This method will generate one of 2^53 distinct Double values in the unit interval. - */ + * + * This method will generate one of 2^53 distinct Double values in the unit interval. + */ val double: Gen[Double] = gen { (_, s0) => val (x, s1) = s0.double @@ -1271,12 +1271,12 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates a Boolean which has the given chance to be true. - * - * - prob(1.0) is always true - * - prob(0.5) is true 50% of the time - * - prob(0.1) is true 10% of the time - * - prob(0.0) is never true - */ + * + * - prob(1.0) is always true + * - prob(0.5) is true 50% of the time + * - prob(0.1) is true 10% of the time + * - prob(0.0) is never true + */ def prob(chance: Double): Gen[Boolean] = if (chance <= 0.0) Gen.const(false) else if (chance >= 1.0) Gen.const(true) @@ -1286,12 +1286,12 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates Double values according to the given gaussian distribution, specified by its mean and standard - * deviation. - * - * Gaussian distributions are also called normal distributions. - * - * The range of values is theoretically (-∞, ∞) but 99.7% of all values will be contained within (mean ± 3 * stdDev). - */ + * deviation. + * + * Gaussian distributions are also called normal distributions. + * + * The range of values is theoretically (-∞, ∞) but 99.7% of all values will be contained within (mean ± 3 * stdDev). + */ def gaussian(mean: Double, stdDev: Double): Gen[Double] = { def loop(s0: Seed): R[Double] = { val (x0, s1) = s0.double @@ -1311,11 +1311,11 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates Double values according to the given exponential distribution, specified by its rate parameter. - * - * The mean and standard deviation are both equal to 1/rate. - * - * The range of values is [0, ∞). - */ + * + * The mean and standard deviation are both equal to 1/rate. + * + * The range of values is [0, ∞). + */ def exponential(rate: Double): Gen[Double] = { require(rate > 0.0, s"rate must be positive (got: $rate)") val mean = 1.0 / rate @@ -1326,13 +1326,13 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates Int values according to the given geometric distribution, specified by its mean. - * - * This distribution represents the expected number of failures before a successful test, where the probability of a - * successful test is p = 1 / (mean + 1). - * - * The ideal range of values is [0, ∞), although the largest value that can be produced here is 2147483647 - * (Int.MaxValue). - */ + * + * This distribution represents the expected number of failures before a successful test, where the probability of a + * successful test is p = 1 / (mean + 1). + * + * The ideal range of values is [0, ∞), although the largest value that can be produced here is 2147483647 + * (Int.MaxValue). + */ def geometric(mean: Double): Gen[Int] = { require(mean > 0.0, s"mean must be positive (got: $mean)") val p = 1.0 / (mean + 1.0) @@ -1344,12 +1344,12 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates Int values according to the given Poisson distribution, specified by its rate parameters. - * - * The mean equals the rate; the standard deviation is sqrt(rate). - * - * In principle any positive value is a valid rate parameter. However, our method of generating values cannot handle - * large rates, so we require rate <= 745. - */ + * + * The mean equals the rate; the standard deviation is sqrt(rate). + * + * In principle any positive value is a valid rate parameter. However, our method of generating values cannot handle + * large rates, so we require rate <= 745. + */ def poisson(rate: Double): Gen[Int] = { require(0 < rate && rate <= 745.0, s"rate must be between 0 and 745 (got $rate)") val L = Math.exp(-rate) @@ -1365,12 +1365,12 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates Int values according to the given binomial distribution, specified by the number of trials to conduct, - * and the probability of a true test. - * - * This distribution counts the number of trials which were successful according to a given test probability. - * - * The range of values is [0, trials]. - */ + * and the probability of a true test. + * + * This distribution counts the number of trials which were successful according to a given test probability. + * + * The range of values is [0, trials]. + */ def binomial(test: Gen[Boolean], trials: Int): Gen[Int] = { def loop(ps: Gen.Parameters, s: Seed, i: Int, n: Int): R[Int] = if (i >= trials) { @@ -1384,7 +1384,7 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates positive numbers of uniform distribution, with an upper bound of the generation size parameter. - */ + */ def posNum[T](implicit num: Numeric[T], c: Choose[T]): Gen[T] = { import num._ num match { @@ -1394,13 +1394,13 @@ object Gen extends GenArities with GenVersionSpecific { } /** Generates negative numbers of uniform distribution, with an lower bound of the negated generation size parameter. - */ + */ def negNum[T](implicit num: Numeric[T], c: Choose[T]): Gen[T] = posNum.map(num.negate(_)) /** Generates numbers within the given inclusive range, with extra weight on zero, +/- unity, both extremities, and - * any special numbers provided. The special numbers must lie within the given range, otherwise they won't be - * included. - */ + * any special numbers provided. The special numbers must lie within the given range, otherwise they won't be + * included. + */ def chooseNum[T](minT: T, maxT: T, specials: T*)( implicit num: Numeric[T], @@ -1511,10 +1511,10 @@ object Gen extends GenArities with GenVersionSpecific { chooseNum(Long.MinValue + 1, Long.MaxValue).map(Duration.fromNanos) /** Generates instance of Duration. - * - * In addition to `FiniteDuration` values, this can generate `Duration.Inf`, `Duration.MinusInf`, and - * `Duration.Undefined`. - */ + * + * In addition to `FiniteDuration` values, this can generate `Duration.Inf`, `Duration.MinusInf`, and + * `Duration.Undefined`. + */ val duration: Gen[Duration] = frequency( 1 -> const(Duration.Inf), 1 -> const(Duration.MinusInf), diff --git a/core/shared/src/main/scala/org/scalacheck/Prop.scala b/core/shared/src/main/scala/org/scalacheck/Prop.scala index dedb1ec8..365e2fd0 100644 --- a/core/shared/src/main/scala/org/scalacheck/Prop.scala +++ b/core/shared/src/main/scala/org/scalacheck/Prop.scala @@ -15,7 +15,7 @@ import rng.Seed import util.{Pretty, ConsoleReporter} /** Helper class to satisfy ScalaJS compilation. Do not use this directly, use `Prop.apply` instead. - */ + */ sealed class PropFromFun(f: Gen.Parameters => Prop.Result) extends Prop { def apply(prms: Gen.Parameters) = f(prms) } @@ -64,8 +64,8 @@ sealed abstract class Prop extends Serializable { self => for (r1 <- this; r2 <- p) yield f(r1, r2) /** Convenience method that checks this property with the given parameters and reports the result on the console. - * Should only be used when running tests interactively within the Scala REPL. - */ + * Should only be used when running tests interactively within the Scala REPL. + */ def check(prms: Test.Parameters): Unit = Test.check_( if (prms.testCallback.isInstanceOf[ConsoleReporter]) prms else prms.withTestCallback(prms.testCallback.chain(ConsoleReporter(1))), @@ -73,34 +73,34 @@ sealed abstract class Prop extends Serializable { self => ) /** Convenience method that checks this property and reports the result on the console. Should only be used when - * running tests interactively within the Scala REPL. - * - * The default test parameters ([[Test.Parameters.default]]) are used for the check. - */ + * running tests interactively within the Scala REPL. + * + * The default test parameters ([[Test.Parameters.default]]) are used for the check. + */ def check(): Unit = check(Test.Parameters.default) /** Convenience method that checks this property and reports the result on the console. Should only be used when - * running tests interactively within the Scala REPL. - * - * The provided argument should be a function that takes the default test parameters ([[Test.Parameters.default]]) as - * input and outputs a modified [[Test.Parameters]] instance that Example use: - * - * {{{ - * p.check(_.withMinSuccessfulTests(500)) - * - * p.check { _. - * withMinSuccessfulTests(80000). - * withWorkers(4) - * } - * }}} - */ + * running tests interactively within the Scala REPL. + * + * The provided argument should be a function that takes the default test parameters ([[Test.Parameters.default]]) as + * input and outputs a modified [[Test.Parameters]] instance that Example use: + * + * {{{ + * p.check(_.withMinSuccessfulTests(500)) + * + * p.check { _. + * withMinSuccessfulTests(80000). + * withWorkers(4) + * } + * }}} + */ def check(paramFun: Test.Parameters => Test.Parameters): Unit = check( paramFun(Test.Parameters.default) ) /** Convenience method that makes it possible to use this property as an application that checks itself on execution. - * Calls `System.exit` with a non-zero exit code if the property check fails. - */ + * Calls `System.exit` with a non-zero exit code if the property check fails. + */ def main(args: Array[String]): Unit = { val ret = Test.CmdLineParser.parseParams(args) match { case (applyCmdParams, Nil) => @@ -116,17 +116,17 @@ sealed abstract class Prop extends Serializable { self => } /** Returns a new property that holds if and only if both this and the given property hold. If one of the properties - * doesn't generate a result, the new property will generate false. - */ + * doesn't generate a result, the new property will generate false. + */ def &&(p: => Prop) = combine(p)(_ && _) /** Returns a new property that holds if either this or the given property (or both) hold. - */ + */ def ||(p: => Prop) = combine(p)(_ || _) /** Returns a new property that holds if and only if both this and the given property hold. If one of the properties - * doesn't generate a result, the new property will generate the same result as the other property. - */ + * doesn't generate a result, the new property will generate the same result as the other property. + */ def ++(p: => Prop): Prop = combine(p)(_ ++ _) /** Combines two properties through implication */ @@ -137,9 +137,9 @@ sealed abstract class Prop extends Serializable { self => } /** Returns a new property that holds if and only if both this and the given property generates a result with the - * exact same status. Note that this means that if one of the properties is proved, and the other one passed, then - * the resulting property will fail. - */ + * exact same status. Note that this means that if one of the properties is proved, and the other one passed, then + * the resulting property will fail. + */ def ==(p: => Prop) = this.flatMap { r1 => p.map { r2 => mergeRes(r1, r2, if (r1.status == r2.status) True else False) @@ -316,7 +316,7 @@ object Prop { // Implicits /** A collection of property operators on `Any` values. Import [[Prop.AnyOperators]] to make the operators available. - */ + */ class ExtendedAny[T](x: => T)(implicit ev: T => Pretty) { /** See [[Prop.imply]] */ @@ -333,8 +333,8 @@ object Prop { } /** A collection of property operators on `Boolean` values. Import [[Prop.propBoolean]] to make the operators - * available. The availability of this class as an implicit via `BooleanOperators` was removed in 1.15.0. - */ + * available. The availability of this class as an implicit via `BooleanOperators` was removed in 1.15.0. + */ class ExtendedBoolean(b: => Boolean) { /** See the documentation for [[org.scalacheck.Prop]] */ @@ -354,13 +354,13 @@ object Prop { } /** Implicit method that makes a number of property operators on values of type `Any` available in the current scope. - * See [[Prop.ExtendedAny]] for documentation on the operators. - */ + * See [[Prop.ExtendedAny]] for documentation on the operators. + */ implicit def AnyOperators[T](x: => T)(implicit ev: T => Pretty): ExtendedAny[T] = new ExtendedAny[T](x) /** Implicit method that makes a number of property operators on boolean values available in the current scope. See - * [[Prop.ExtendedBoolean]] for documentation on the operators. - */ + * [[Prop.ExtendedBoolean]] for documentation on the operators. + */ @deprecated("Please import Prop.propBoolean instead", since = "1.14.1") def BooleanOperators(b: => Boolean): ExtendedBoolean = new ExtendedBoolean(b) @@ -395,8 +395,8 @@ object Prop { lazy val exception: Prop = exception(null) /** Create a property that compares two values. If the values aren't equal, the property will fail and report that - * first value doesn't match the expected (second) value. - */ + * first value doesn't match the expected (second) value. + */ def ?=[T](x: T, y: T)(implicit pp: T => Pretty): Prop = if (x == y) proved else falsified :| { @@ -406,8 +406,8 @@ object Prop { } /** Create a property that compares two values. If the values aren't equal, the property will fail and report that - * second value doesn't match the expected (first) value. - */ + * second value doesn't match the expected (first) value. + */ def =?[T](x: T, y: T)(implicit pp: T => Pretty): Prop = ?=(y, x) /** A property that depends on the generator size */ @@ -424,35 +424,35 @@ object Prop { } /** Property holds only if the given partial function is defined at `x`, and returns a property that holds - */ + */ def iff[T](x: T, f: PartialFunction[T, Prop]): Prop = secure { if (f.isDefinedAt(x)) f(x) else falsified } /** Combines properties into one, which is true if and only if all the properties are true - */ + */ def all(ps: Prop*) = if (ps.isEmpty) proved else Prop(prms => ps.map(p => p(prms)).reduceLeft(_ && _)) /** Combines properties into one, which is true if at least one of the properties is true - */ + */ def atLeastOne(ps: Prop*) = if (ps.isEmpty) falsified else Prop(prms => ps.map(p => p(prms)).reduceLeft(_ || _)) /** A property that holds if at least one of the given generators fails generating a value - */ + */ def someFailing[T](gs: Seq[Gen[T]]): Prop = atLeastOne(gs.map(_ == Gen.fail): _*) /** A property that holds iff none of the given generators fails generating a value - */ + */ def noneFailing[T](gs: Seq[Gen[T]]): Prop = all(gs.map(_ !== Gen.fail): _*) /** Returns true if the given statement throws an exception of the specified type - */ + */ def throws[T <: Throwable](c: Class[T])(x: => Any): Boolean = try { x; false } catch { case e if c.isInstance(e) => true } @@ -479,27 +479,27 @@ object Prop { if (c) collect(ifTrue)(prop) else collect(ifFalse)(prop) /** Wraps and protects a property, turning exceptions thrown by the property into test failures. - */ + */ def secure[P](p: => P)(implicit ev: P => Prop): Prop = try ev(p) catch { case e: Throwable => exception(e) } /** Wraps a property to delay its evaluation. The given parameter is evaluated each time the wrapper property is - * evaluated. - */ + * evaluated. + */ def delay(p: => Prop): Prop = Prop(params => p(params)) /** Wraps a property lazily. The given parameter is only evaluated once, and not until the wrapper property is - * evaluated. - */ + * evaluated. + */ def lzy(p: => Prop): Prop = { lazy val q = p Prop(params => q(params)) } /** Wraps and protects a property, delaying its evaluation and turning exceptions into test failures. - */ + */ def protect(p: => Prop): Prop = delay(secure(p)) @@ -511,14 +511,14 @@ object Prop { ): Prop = exists(aa.arbitrary)(f) /** This handles situations where we have a starting seed in our parameters. - * - * If we do, then we remove it from parameters and return it. If not, we create a new random seed. The new parameters - * from this method should be used with all the generation that this prop needs itself. - * - * Note that if this Prop needs to evaluate other Props (e.g. in forAll), you should make sure *not* to use the - * parameters returned from this method. We need for all Props evaluated by this one to behave deterministically if - * this Prop was given a seed. In that case you should use `slideSeed` to update the parameters. - */ + * + * If we do, then we remove it from parameters and return it. If not, we create a new random seed. The new parameters + * from this method should be used with all the generation that this prop needs itself. + * + * Note that if this Prop needs to evaluate other Props (e.g. in forAll), you should make sure *not* to use the + * parameters returned from this method. We need for all Props evaluated by this one to behave deterministically if + * this Prop was given a seed. In that case you should use `slideSeed` to update the parameters. + */ def startSeed(prms: Gen.Parameters): (Gen.Parameters, Seed) = prms.initialSeed match { case Some(seed) => (prms.withNoInitialSeed, seed) @@ -554,7 +554,7 @@ object Prop { } /** Universal quantifier for an explicit generator. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, P]( g1: Gen[T1] )( @@ -575,7 +575,7 @@ object Prop { } /** Universal quantifier for two explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, P]( g1: Gen[T1], g2: Gen[T2] @@ -588,7 +588,7 @@ object Prop { ): Prop = forAllNoShrink(g1)(t => forAllNoShrink(g2)(f(t, _: T2))) /** Universal quantifier for three explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, P]( g1: Gen[T1], g2: Gen[T2], @@ -603,7 +603,7 @@ object Prop { ): Prop = forAllNoShrink(g1)(t => forAllNoShrink(g2, g3)(f(t, _: T2, _: T3))) /** Universal quantifier for four explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, T4, P]( g1: Gen[T1], g2: Gen[T2], @@ -620,7 +620,7 @@ object Prop { ): Prop = forAllNoShrink(g1)(t => forAllNoShrink(g2, g3, g4)(f(t, _: T2, _: T3, _: T4))) /** Universal quantifier for five explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, T4, T5, P]( g1: Gen[T1], g2: Gen[T2], @@ -639,7 +639,7 @@ object Prop { ): Prop = forAllNoShrink(g1)(t => forAllNoShrink(g2, g3, g4, g5)(f(t, _: T2, _: T3, _: T4, _: T5))) /** Universal quantifier for six explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, T4, T5, T6, P]( g1: Gen[T1], g2: Gen[T2], @@ -660,7 +660,7 @@ object Prop { ): Prop = forAllNoShrink(g1)(t => forAllNoShrink(g2, g3, g4, g5, g6)(f(t, _: T2, _: T3, _: T4, _: T5, _: T6))) /** Universal quantifier for seven explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, T4, T5, T6, T7, P]( g1: Gen[T1], g2: Gen[T2], @@ -684,7 +684,7 @@ object Prop { forAllNoShrink(g1)(t => forAllNoShrink(g2, g3, g4, g5, g6, g7)(f(t, _: T2, _: T3, _: T4, _: T5, _: T6, _: T7))) /** Universal quantifier for eight explicit generators. Does not shrink failed test cases. - */ + */ def forAllNoShrink[T1, T2, T3, T4, T5, T6, T7, T8, P]( g1: Gen[T1], g2: Gen[T2], @@ -857,7 +857,7 @@ object Prop { } /** Universal quantifier for an explicit generator. Shrinks failed arguments with the given shrink function - */ + */ def forAllShrink[T, P](g: Gen[T], shrink: T => Stream[T])(f: T => P)(implicit pv: P => Prop, pp: T => Pretty): Prop = Prop { prms0 => val (prms, seed) = startSeed(prms0) @@ -920,8 +920,8 @@ object Prop { } /** Universal quantifier for an explicit generator. Shrinks failed arguments with the default shrink function for the - * type - */ + * type + */ def forAll[T1, P]( g1: Gen[T1] )( @@ -933,8 +933,8 @@ object Prop { ): Prop = forAllShrink[T1, P](g1, s1.shrink)(f) /** Universal quantifier for two explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, P]( g1: Gen[T1], g2: Gen[T2] @@ -949,8 +949,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2)(f(t, _: T2))) /** Universal quantifier for three explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, P]( g1: Gen[T1], g2: Gen[T2], @@ -968,8 +968,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2, g3)(f(t, _: T2, _: T3))) /** Universal quantifier for four explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, T4, P]( g1: Gen[T1], g2: Gen[T2], @@ -990,8 +990,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2, g3, g4)(f(t, _: T2, _: T3, _: T4))) /** Universal quantifier for five explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, T4, T5, P]( g1: Gen[T1], g2: Gen[T2], @@ -1015,8 +1015,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2, g3, g4, g5)(f(t, _: T2, _: T3, _: T4, _: T5))) /** Universal quantifier for six explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, T4, T5, T6, P]( g1: Gen[T1], g2: Gen[T2], @@ -1043,8 +1043,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2, g3, g4, g5, g6)(f(t, _: T2, _: T3, _: T4, _: T5, _: T6))) /** Universal quantifier for seven explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, T4, T5, T6, T7, P]( g1: Gen[T1], g2: Gen[T2], @@ -1074,8 +1074,8 @@ object Prop { ): Prop = forAll(g1)(t => forAll(g2, g3, g4, g5, g6, g7)(f(t, _: T2, _: T3, _: T4, _: T5, _: T6, _: T7))) /** Universal quantifier for eight explicit generators. Shrinks failed arguments with the default shrink function for - * the type - */ + * the type + */ def forAll[T1, T2, T3, T4, T5, T6, T7, T8, P]( g1: Gen[T1], g2: Gen[T2], @@ -1272,7 +1272,7 @@ object Prop { ): Prop = forAll((a: A1) => forAll(f(a, _: A2, _: A3, _: A4, _: A5, _: A6, _: A7, _: A8))) /** Ensures that the property expression passed in completes within the given space of time. - */ + */ def within(maximumMs: Long)(wrappedProp: => Prop): Prop = { @tailrec def attempt(prms: Gen.Parameters, endTime: Long): Result = { val result = wrappedProp.apply(prms) diff --git a/core/shared/src/main/scala/org/scalacheck/Properties.scala b/core/shared/src/main/scala/org/scalacheck/Properties.scala index e7a289c8..66330d6c 100644 --- a/core/shared/src/main/scala/org/scalacheck/Properties.scala +++ b/core/shared/src/main/scala/org/scalacheck/Properties.scala @@ -14,16 +14,16 @@ import org.scalacheck.rng.Seed import util.ConsoleReporter /** Represents a collection of properties, with convenient methods for checking all properties at once.

Properties - * are added in the following way:

- * - * {{{ - * object MyProps extends Properties("MyProps") { - * property("myProp1") = forAll { (n:Int, m:Int) => - * n+m == m+n - * } - * } - * }}} - */ + * are added in the following way:

+ * + * {{{ + * object MyProps extends Properties("MyProps") { + * property("myProp1") = forAll { (n:Int, m:Int) => + * n+m == m+n + * } + * } + * }}} + */ @Platform.EnableReflectiveInstantiation open class Properties(val name: String) { @@ -31,26 +31,26 @@ open class Properties(val name: String) { private var frozen = false /** Customize the parameters specific to this class. - * - * After the command-line (either [[main]] above or sbt) modifies the default parameters, this method is called with - * the current state of the parameters. This method must then return parameters. The default implementation returns - * the parameters unchanged. However, a user can override this method in a properties subclass. Their method can - * modify the parameters. Those parameters will take precedence when the properties are executed. - */ + * + * After the command-line (either [[main]] above or sbt) modifies the default parameters, this method is called with + * the current state of the parameters. This method must then return parameters. The default implementation returns + * the parameters unchanged. However, a user can override this method in a properties subclass. Their method can + * modify the parameters. Those parameters will take precedence when the properties are executed. + */ def overrideParameters(p: Test.Parameters): Test.Parameters = p /** Returns all properties of this collection in a list of name/property pairs. - */ + */ def properties: collection.Seq[(String, Prop)] = { frozen = true // once the properties have been exposed, they must be frozen props } /** Convenience method that checks the properties with the given parameters (or default parameters, if not specified) - * and reports the result on the console. Should only be used when running tests interactively within the Scala REPL. - * - * If you need to get the results from the test use the `check` methods in [[org.scalacheck.Test]] instead. - */ + * and reports the result on the console. Should only be used when running tests interactively within the Scala REPL. + * + * If you need to get the results from the test use the `check` methods in [[org.scalacheck.Test]] instead. + */ def check(prms: Test.Parameters = Test.Parameters.default): Unit = { val params = overrideParameters(prms) Test.checkProperties_( @@ -60,8 +60,8 @@ open class Properties(val name: String) { } /** Convenience method that makes it possible to use this property collection as an application that checks itself on - * execution. Calls `System.exit` with the exit code set to the number of failed properties. - */ + * execution. Calls `System.exit` with the exit code set to the number of failed properties. + */ def main(args: Array[String]): Unit = Test.CmdLineParser.parseParams(args) match { case (applyCmdParams, Nil) => @@ -85,16 +85,16 @@ open class Properties(val name: String) { include(ps, prefix = "") /** Adds all properties from another property collection to this one with a prefix this is prepended to each included - * property's name. - */ + * property's name. + */ def include(ps: Properties, prefix: String): Unit = for ((n, p) <- ps.properties) property(prefix + n) = p /** Used for specifying properties. Usage: - * {{{ - * property("myProp") = ... - * }}} - */ + * {{{ + * property("myProp") = ... + * }}} + */ sealed class PropertySpecifier() { def update(propName: String, p: => Prop) = { if (frozen) throw new IllegalStateException("cannot nest properties or create properties during execution") diff --git a/core/shared/src/main/scala/org/scalacheck/Shrink.scala b/core/shared/src/main/scala/org/scalacheck/Shrink.scala index 1eae3d18..25ff8eb4 100644 --- a/core/shared/src/main/scala/org/scalacheck/Shrink.scala +++ b/core/shared/src/main/scala/org/scalacheck/Shrink.scala @@ -19,7 +19,7 @@ sealed abstract class Shrink[T] extends Serializable { def shrink(x: T): Stream[T] /** Create a new shrink that only produces values satisfying the given condition. - */ + */ def suchThat(f: T => Boolean): Shrink[T] = Shrink(v => this.shrink(v).filter(f)) } @@ -49,7 +49,7 @@ object Shrink extends ShrinkLowPriority with ShrinkVersionSpecific with time.Jav def shrink[T](x: T)(implicit s: Shrink[T]): Stream[T] = s.shrink(x) /** Shrink a value, but also return the original value as the first element in the resulting stream - */ + */ def shrinkWithOrig[T](x: T)(implicit s: Shrink[T]): Stream[T] = cons(x, s.shrink(x)) @@ -268,8 +268,8 @@ object Shrink extends ShrinkLowPriority with ShrinkVersionSpecific with time.Jav } /** Transform a Shrink[T] to a Shrink[U] where T and U are two isomorphic types whose relationship is described by the - * provided transformation functions. (exponential functor map) - */ + * provided transformation functions. (exponential functor map) + */ def xmap[T, U](from: T => U, to: U => T)(implicit st: Shrink[T]): Shrink[U] = Shrink[U] { (u: U) => st.shrink(to(u)).map(from) } diff --git a/core/shared/src/main/scala/org/scalacheck/Test.scala b/core/shared/src/main/scala/org/scalacheck/Test.scala index 30806a7c..c030838d 100644 --- a/core/shared/src/main/scala/org/scalacheck/Test.scala +++ b/core/shared/src/main/scala/org/scalacheck/Test.scala @@ -23,16 +23,16 @@ import Prop.Arg object Test { /** Test parameters used by the check methods. Default parameters are defined by [[Test.Parameters.default]]. - */ + */ sealed abstract class Parameters { outer => /** The minimum number of tests that must succeed for ScalaCheck to consider a property passed. - */ + */ val minSuccessfulTests: Int /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.minSuccessfulTests]] set to the - * specified value. - */ + * specified value. + */ def withMinSuccessfulTests(minSuccessfulTests: Int): Parameters = cpy(minSuccessfulTests0 = minSuccessfulTests) @@ -40,7 +40,7 @@ object Test { val minSize: Int /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.minSize]] set to the specified value. - */ + */ def withMinSize(minSize: Int): Parameters = cpy(minSize0 = minSize) @@ -48,7 +48,7 @@ object Test { val maxSize: Int /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.maxSize]] set to the specified value. - */ + */ def withMaxSize(maxSize: Int): Parameters = cpy(maxSize0 = maxSize) @@ -56,7 +56,7 @@ object Test { val workers: Int /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.workers]] set to the specified value. - */ + */ def withWorkers(workers: Int): Parameters = cpy(workers0 = workers) @@ -64,21 +64,21 @@ object Test { val testCallback: TestCallback /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.testCallback]] set to the specified - * value. - */ + * value. + */ def withTestCallback(testCallback: TestCallback): Parameters = cpy(testCallback0 = testCallback) /** The maximum ratio between discarded and passed tests allowed before ScalaCheck gives up and discards the whole - * property (with status [[Test.Exhausted]]). Additionally, ScalaCheck will always allow at least - * `minSuccessfulTests * maxDiscardRatio` discarded tests, so the resulting discard ratio might be higher than - * `maxDiscardRatio`. - */ + * property (with status [[Test.Exhausted]]). Additionally, ScalaCheck will always allow at least + * `minSuccessfulTests * maxDiscardRatio` discarded tests, so the resulting discard ratio might be higher than + * `maxDiscardRatio`. + */ val maxDiscardRatio: Float /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.maxDiscardRatio]] set to the specified - * value. - */ + * value. + */ def withMaxDiscardRatio(maxDiscardRatio: Float): Parameters = cpy(maxDiscardRatio0 = maxDiscardRatio) @@ -86,8 +86,8 @@ object Test { val customClassLoader: Option[ClassLoader] /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.customClassLoader]] set to the - * specified value. - */ + * specified value. + */ def withCustomClassLoader(customClassLoader: Option[ClassLoader]): Parameters = cpy(customClassLoader0 = customClassLoader) @@ -95,8 +95,8 @@ object Test { val propFilter: Option[String] /** Create a copy of this [[Test.Parameters]] instance with [[Test.Parameters.propFilter]] set to the specified - * regular expression filter. - */ + * regular expression filter. + */ def withPropFilter(propFilter: Option[String]): Parameters = cpy(propFilter0 = propFilter) @@ -135,9 +135,9 @@ object Test { cpy(useLegacyShrinking0 = b) /** Maximum number of spins of the RNG to perform between checks. Greater values will reduce reuse of values (with - * dimimishing returns) for a given number of arguments to Prop.forAll tests. Greater values will also generally - * lead to slower tests, so be careful. - */ + * dimimishing returns) for a given number of arguments to Prop.forAll tests. Greater values will also generally + * lead to slower tests, so be careful. + */ val maxRNGSpins: Int = 1 /** Set maximum RNG spins between checks */ @@ -205,17 +205,17 @@ object Test { } /** Test parameters used by the check methods. Default parameters are defined by [[Test.Parameters.default]]. - */ + */ object Parameters { /** Default test parameters. Can be overridden if you need to tweak the parameters: - * - * {{{ - * val myParams = Parameters.default - * .withMinSuccessfulTests(600) - * .withMaxDiscardRatio(8) - * }}} - */ + * + * {{{ + * val myParams = Parameters.default + * .withMinSuccessfulTests(600) + * .withMaxDiscardRatio(8) + * }}} + */ val default: Parameters = new Parameters { val minSuccessfulTests: Int = 100 val minSize: Int = 0 @@ -251,8 +251,8 @@ object Test { sealed trait Status /** ScalaCheck found enough cases for which the property holds, so the property is considered correct. (It is not - * proved correct, though). - */ + * proved correct, though). + */ case object Passed extends Status /** ScalaCheck managed to prove the property correct */ @@ -262,13 +262,13 @@ object Test { sealed case class Failed(args: List[Arg[Any]], labels: Set[String]) extends Status /** The property test was exhausted, it wasn't possible to generate enough concrete arguments satisfying the - * preconditions to get enough passing property evaluations. - */ + * preconditions to get enough passing property evaluations. + */ case object Exhausted extends Status /** An exception was raised when trying to evaluate the property with the given concrete arguments. If an exception - * was raised before or during argument generation, the argument list will be empty. - */ + * was raised before or during argument generation, the argument list will be empty. + */ sealed case class PropException(args: List[Arg[Any]], e: Throwable, labels: Set[String]) extends Status trait TestCallback { self => @@ -421,20 +421,20 @@ object Test { } /** Tests a property with parameters that are calculated by applying the provided function to - * [[Test.Parameters.default]]. Example use: - * - * {{{ - * Test.check(p) { _. - * withMinSuccessfulTests(80000). - * withWorkers(4) - * } - * }}} - */ + * [[Test.Parameters.default]]. Example use: + * + * {{{ + * Test.check(p) { _. + * withMinSuccessfulTests(80000). + * withWorkers(4) + * } + * }}} + */ def check(p: Prop)(f: Parameters => Parameters): Result = check(f(Parameters.default), p) /** Tests a property with the given testing parameters, and returns the test results. - */ + */ def check(params: Parameters, p: Prop): Result = { assertParams(params) @@ -523,23 +523,23 @@ object Test { } /** As `check`, but discards the result. Useful for when you just want to read the console output. - */ + */ def check_(params: Parameters, p: Prop): Unit = { check(params, p); () } /** As `check`, but discards the result. Useful for when you just want to read the console output. - */ + */ def check_(p: Prop)(f: Parameters => Parameters): Unit = check_(f(Parameters.default), p) /** Returns the result of filtering a property name by a supplied regular expression. - * - * @param propertyName - * The name of the property to be filtered. - * @param regex - * The regular expression to filter the property name by. - * @return - * true if the regular expression matches the property name, false if not. - */ + * + * @param propertyName + * The name of the property to be filtered. + * @param regex + * The regular expression to filter the property name by. + * @return + * true if the regular expression matches the property name, false if not. + */ def matchPropFilter(propertyName: String, regex: Regex): Boolean = { regex.findFirstIn(propertyName).isDefined } @@ -574,7 +574,7 @@ object Test { } /** As `checkProperties`, but discards the result. Useful for when you just want to observe the results on the - * console. - */ + * console. + */ def checkProperties_(prms: Parameters, ps: Properties): Unit = { checkProperties(prms, ps); () } } diff --git a/core/shared/src/main/scala/org/scalacheck/commands/Commands.scala b/core/shared/src/main/scala/org/scalacheck/commands/Commands.scala index 4891dd8f..4fd548d9 100644 --- a/core/shared/src/main/scala/org/scalacheck/commands/Commands.scala +++ b/core/shared/src/main/scala/org/scalacheck/commands/Commands.scala @@ -16,105 +16,105 @@ import scala.util.Success import scala.util.Try /** An API for stateful testing in ScalaCheck. - * - * For an implementation overview, see the examples in ScalaCheck's source tree. - * - * @since 1.12.0 - */ + * + * For an implementation overview, see the examples in ScalaCheck's source tree. + * + * @since 1.12.0 + */ trait Commands { /** The abstract state type. Must be immutable. The [[State]] type should model the state of the system under test - * (SUT). It should only contain details needed for specifying our pre- and post-conditions, and for creating [[Sut]] - * instances. - */ + * (SUT). It should only contain details needed for specifying our pre- and post-conditions, and for creating [[Sut]] + * instances. + */ type State /** A type representing one instance of the system under test (SUT). The [[Sut]] type should be a proxy to the actual - * system under test and is therefore, by definition, a mutable type. It is used by the [[Command.run]] method to - * execute commands in the system under test. It should be possible to have any number of co-existing instances of - * the [[Sut]] type, as long as [[canCreateNewSut]] isn't violated, and each [[Sut]] instance should be a proxy to a - * distinct SUT instance. There should be no dependencies between the [[Sut]] instances, as they might be used in - * parallel by ScalaCheck. [[Sut]] instances are created by [[newSut]] and destroyed by [[destroySut]]. [[newSut]] - * and [[destroySut]] might be called at any time by ScalaCheck, as long as [[canCreateNewSut]] isn't violated. - */ + * system under test and is therefore, by definition, a mutable type. It is used by the [[Command.run]] method to + * execute commands in the system under test. It should be possible to have any number of co-existing instances of + * the [[Sut]] type, as long as [[canCreateNewSut]] isn't violated, and each [[Sut]] instance should be a proxy to a + * distinct SUT instance. There should be no dependencies between the [[Sut]] instances, as they might be used in + * parallel by ScalaCheck. [[Sut]] instances are created by [[newSut]] and destroyed by [[destroySut]]. [[newSut]] + * and [[destroySut]] might be called at any time by ScalaCheck, as long as [[canCreateNewSut]] isn't violated. + */ type Sut /** Decides if [[newSut]] should be allowed to be called with the specified state instance. This can be used to limit - * the number of co-existing [[Sut]] instances. The list of existing states represents the initial states (not the - * current states) for all [[Sut]] instances that are active for the moment. If this method is implemented - * incorrectly, for example if it returns false even if the list of existing states is empty, ScalaCheck might hang. - * - * If you want to allow only one [[Sut]] instance to exist at any given time (a singleton [[Sut]]), implement this - * method the following way: - * - * {{{ - * def canCreateNewSut(newState: State, initSuts: Traversable[State] - * runningSuts: Traversable[Sut] - * ) = { - * initSuts.isEmpty && runningSuts.isEmpty - * } - * }}} - */ + * the number of co-existing [[Sut]] instances. The list of existing states represents the initial states (not the + * current states) for all [[Sut]] instances that are active for the moment. If this method is implemented + * incorrectly, for example if it returns false even if the list of existing states is empty, ScalaCheck might hang. + * + * If you want to allow only one [[Sut]] instance to exist at any given time (a singleton [[Sut]]), implement this + * method the following way: + * + * {{{ + * def canCreateNewSut(newState: State, initSuts: Traversable[State] + * runningSuts: Traversable[Sut] + * ) = { + * initSuts.isEmpty && runningSuts.isEmpty + * } + * }}} + */ def canCreateNewSut(newState: State, initSuts: Traversable[State], runningSuts: Traversable[Sut]): Boolean /** Create a new [[Sut]] instance with an internal state that corresponds to the provided abstract state instance. The - * provided state is guaranteed to fulfill [[initialPreCondition]], and [[newSut]] will never be called if - * [[canCreateNewSut]] is not true for the given state. - */ + * provided state is guaranteed to fulfill [[initialPreCondition]], and [[newSut]] will never be called if + * [[canCreateNewSut]] is not true for the given state. + */ def newSut(state: State): Sut /** Destroy the system represented by the given [[Sut]] instance, and release any resources related to it. - */ + */ def destroySut(sut: Sut): Unit /** The precondition for the initial state, when no commands yet have run. This is used by ScalaCheck when command - * sequences are shrunk and the first state might differ from what is returned from [[genInitialState]]. - */ + * sequences are shrunk and the first state might differ from what is returned from [[genInitialState]]. + */ def initialPreCondition(state: State): Boolean /** A generator that should produce an initial [[State]] instance that is usable by [[newSut]] to create a new system - * under test. The state returned by this generator is always checked with the [[initialPreCondition]] method before - * it is used. - */ + * under test. The state returned by this generator is always checked with the [[initialPreCondition]] method before + * it is used. + */ def genInitialState: Gen[State] /** A generator that, given the current abstract state, should produce a suitable Command instance. - */ + */ def genCommand(state: State): Gen[Command] /** A type representing the commands that can run in the system under test. This type should be immutable and - * implement the equality operator properly. - */ + * implement the equality operator properly. + */ trait Command { /** An abstract representation of the result of running this command in the system under test. The [[Result]] type - * should be immutable and it should encode everything about the command run that is necessary to know in order to - * correctly implement the [[[Command!.postCondition* postCondition]]] method. - */ + * should be immutable and it should encode everything about the command run that is necessary to know in order to + * correctly implement the [[[Command!.postCondition* postCondition]]] method. + */ type Result /** Executes the command in the system under test, and returns a representation of the result of the command run. - * The result value is later used for verifying that the command behaved according to the specification, by the - * [[Command!.postCondition* postCondition]] method. - */ + * The result value is later used for verifying that the command behaved according to the specification, by the + * [[Command!.postCondition* postCondition]] method. + */ def run(sut: Sut): Result /** Returns a new [[State]] instance that represents the state of the system after this command has run, given the - * system was in the provided state before the run. - */ + * system was in the provided state before the run. + */ def nextState(state: State): State /** Precondition that decides if this command is allowed to run when the system under test is in the provided state. - */ + */ def preCondition(state: State): Boolean /** Postcondition that decides if this command produced the correct result or not, given the system was in the - * provided state before the command ran. - */ + * provided state before the command ran. + */ def postCondition(state: State, result: Try[Result]): Prop /** Wraps the run and postCondition methods in order not to leak the dependent Result type. - */ + */ private[Commands] def runPC(sut: Sut): (Try[String], State => Prop) = { import Prop.propBoolean val r = Try(run(sut)) @@ -150,10 +150,10 @@ trait Commands { } /** A command that runs a sequence of other commands. All commands (and their post conditions) are executed even if - * some command fails. Note that you probably can't use this method if you're testing in parallel (`threadCount` - * larger than 1). This is because ScalaCheck regards each command as atomic, even if the command is a sequence of - * other commands. - */ + * some command fails. Note that you probably can't use this method if you're testing in parallel (`threadCount` + * larger than 1). This is because ScalaCheck regards each command as atomic, even if the command is a sequence of + * other commands. + */ def commandSequence(head: Command, snd: Command, rest: Command*): Command = new CommandSequence(head, snd, rest: _*) @@ -179,20 +179,20 @@ trait Commands { } /** A property that can be used to test this [[Commands]] specification. - * - * The parameter `threadCount` specifies the number of commands that might be executed in parallel. Defaults to one, - * which means the commands will only be run serially for the same [[Sut]] instance. Distinct [[Sut]] instances might - * still receive commands in parallel, if the [[Test.Parameters.workers]] parameter is larger than one. Setting - * `threadCount` higher than one enables ScalaCheck to reveal thread-related issues in your system under test. - * - * When setting `threadCount` larger than one, ScalaCheck must evaluate all possible command interleavings (and the - * end [[State]] instances they produce), since parallel command execution is non-deterministic. ScalaCheck tries out - * all possible end states with the [[Command.postCondition]] function of the very last command executed (there is - * always exactly one command executed after all parallel command executions). If it fails to find an end state that - * satisfies the postcondition, the test fails. However, the number of possible end states grows rapidly with - * increasing values of `threadCount`. Therefore, the lengths of the parallel command sequences are limited so that - * the number of possible end states don't exceed `maxParComb`. The default value of `maxParComb` is 1000000. - */ + * + * The parameter `threadCount` specifies the number of commands that might be executed in parallel. Defaults to one, + * which means the commands will only be run serially for the same [[Sut]] instance. Distinct [[Sut]] instances might + * still receive commands in parallel, if the [[Test.Parameters.workers]] parameter is larger than one. Setting + * `threadCount` higher than one enables ScalaCheck to reveal thread-related issues in your system under test. + * + * When setting `threadCount` larger than one, ScalaCheck must evaluate all possible command interleavings (and the + * end [[State]] instances they produce), since parallel command execution is non-deterministic. ScalaCheck tries out + * all possible end states with the [[Command.postCondition]] function of the very last command executed (there is + * always exactly one command executed after all parallel command executions). If it fails to find an end state that + * satisfies the postcondition, the test fails. However, the number of possible end states grows rapidly with + * increasing values of `threadCount`. Therefore, the lengths of the parallel command sequences are limited so that + * the number of possible end states don't exceed `maxParComb`. The default value of `maxParComb` is 1000000. + */ final def property(threadCount: Int = 1, maxParComb: Int = 1000000): Prop = { val suts = collection.mutable.Map.empty[AnyRef, (State, Option[Sut])] @@ -241,8 +241,8 @@ trait Commands { } /** Override this to provide a custom Shrinker for your internal [[State]]. By default no shrinking is done for - * [[State]]. - */ + * [[State]]. + */ def shrinkState: Shrink[State] = implicitly // Private methods // diff --git a/core/shared/src/main/scala/org/scalacheck/rng/Seed.scala b/core/shared/src/main/scala/org/scalacheck/rng/Seed.scala index af7f7dd5..88638dfc 100644 --- a/core/shared/src/main/scala/org/scalacheck/rng/Seed.scala +++ b/core/shared/src/main/scala/org/scalacheck/rng/Seed.scala @@ -14,9 +14,9 @@ import scala.annotation.tailrec import scala.util.Try /** Simple RNG by Bob Jenkins: - * - * http://burtleburtle.net/bob/rand/smallprng.html - */ + * + * http://burtleburtle.net/bob/rand/smallprng.html + */ sealed abstract class Seed extends Serializable { protected val a: Long protected val b: Long @@ -24,13 +24,13 @@ sealed abstract class Seed extends Serializable { protected val d: Long /** Generate a Base-64 representation of this seed. - * - * Given a seed, this method will return a String with 44 characters, according to the web-safe Base-64 specification - * (i.e. using minus (-) and underscore (_) in addition to alphanumeric characters). - * - * The 256-bit seed is serialized as a little-endian array of 64-bit Long values. Strings produced by this method are - * guaranteed to be parseable by the Seed.fromBase64 method. - */ + * + * Given a seed, this method will return a String with 44 characters, according to the web-safe Base-64 specification + * (i.e. using minus (-) and underscore (_) in addition to alphanumeric characters). + * + * The 256-bit seed is serialized as a little-endian array of 64-bit Long values. Strings produced by this method are + * guaranteed to be parseable by the Seed.fromBase64 method. + */ def toBase64: String = { def enc(x: Long): Char = Seed.Alphabet((x & 0x3f).toInt) val chars = new Array[Char](44) @@ -73,26 +73,26 @@ sealed abstract class Seed extends Serializable { } /** This is a quick way of deterministically sliding this RNG to a different part of the PRNG sequence. - * - * We use this as an easy way to "split" the RNG off into a new part of the sequence. We want to do this in - * situations where we've already called .next several times, and we want to avoid repeating those numbers while - * preserving determinism. - */ + * + * We use this as an easy way to "split" the RNG off into a new part of the sequence. We want to do this in + * situations where we've already called .next several times, and we want to avoid repeating those numbers while + * preserving determinism. + */ def slide: Seed = { val (n, s) = long s.reseed(n) } /** Generates a Long value. - * - * The values will be uniformly distributed. - */ + * + * The values will be uniformly distributed. + */ def long: (Long, Seed) = (d, next) /** Generates a Double value. - * - * The values will be uniformly distributed, and will be contained in the interval [0.0, 1.0). - */ + * + * The values will be uniformly distributed, and will be contained in the interval [0.0, 1.0). + */ def double: (Double, Seed) = ((d >>> 11) * 1.1102230246251565e-16, next) } @@ -111,10 +111,10 @@ object Seed { } /** Generate a seed directly from four Long values. - * - * Warning: unlike Seed.apply(Long), this method just directly constructs a seed from the four Long values. Prefer - * using `Seed(Long)` if you aren't sure whether these will be good seed values. - */ + * + * Warning: unlike Seed.apply(Long), this method just directly constructs a seed from the four Long values. Prefer + * using `Seed(Long)` if you aren't sure whether these will be good seed values. + */ def fromLongs(a: Long, b: Long, c: Long, d: Long): Seed = { if (a == 0 && b == 0 && c == 0 && d == 0) { throw new IllegalArgumentException("illegal Seed.fromLongs(0, 0, 0, 0)") @@ -123,10 +123,10 @@ object Seed { } /** Alphabet of characters used by the `toBase64` method. - * - * Since we're using the web-safe Base-64 specification, we are using minus (-) and underscore(_) in addition to the - * alphanumeric characters. - */ + * + * Since we're using the web-safe Base-64 specification, we are using minus (-) and underscore(_) in addition to the + * alphanumeric characters. + */ private[scalacheck] final val Alphabet: Array[Char] = ((0 until 26).map(i => ('A' + i).toChar) ++ (0 until 26).map(i => ('a' + i).toChar) ++ @@ -134,12 +134,12 @@ object Seed { Vector('-', '_')).toArray /** Parse a Base-64 encoded seed, returning a Seed value. - * - * This method requires the exact format produced by `toBase64` (i.e. a 44-character string using the web-safe - * Base-64 alphabet). Other encodings must produce precisely the same outputs to be supported. - * - * This method will throw an IllegalArgumentException if parsing fails. - */ + * + * This method requires the exact format produced by `toBase64` (i.e. a 44-character string using the web-safe + * Base-64 alphabet). Other encodings must produce precisely the same outputs to be supported. + * + * This method will throw an IllegalArgumentException if parsing fails. + */ def fromBase64(s: String): Try[Seed] = { def fail(s: String): Nothing = throw new IllegalArgumentException(s) diff --git a/core/shared/src/main/scala/org/scalacheck/time/JavaTimeArbitrary.scala b/core/shared/src/main/scala/org/scalacheck/time/JavaTimeArbitrary.scala index 57d3d427..bc5a9cfd 100644 --- a/core/shared/src/main/scala/org/scalacheck/time/JavaTimeArbitrary.scala +++ b/core/shared/src/main/scala/org/scalacheck/time/JavaTimeArbitrary.scala @@ -14,11 +14,11 @@ import org.scalacheck._ import java.time._ /** [[Arbitrary]] instances for `java.time` types. - * - * @note - * [[Arbitrary]] instances for `java.time` types which are Java enum types are provided by ScalaCheck's general Java - * enum support. - */ + * + * @note + * [[Arbitrary]] instances for `java.time` types which are Java enum types are provided by ScalaCheck's general Java + * enum support. + */ private[scalacheck] trait JavaTimeArbitrary { // Duration @@ -76,9 +76,9 @@ private[scalacheck] trait JavaTimeArbitrary { // ZoneId /** ''Technically'' the available zone ids can change at runtime, so we store an immutable snapshot in time here. We - * avoid going through the scala/java collection converters to avoid having to deal with the scala 2.13 changes and - * adding a dependency on the collection compatibility library. - */ + * avoid going through the scala/java collection converters to avoid having to deal with the scala 2.13 changes and + * adding a dependency on the collection compatibility library. + */ private final lazy val availableZoneIds: Set[ZoneId] = ZoneId.getAvailableZoneIds.toArray(Array.empty[String]).toSet.map((value: String) => ZoneId.of(value)) diff --git a/core/shared/src/main/scala/org/scalacheck/time/JavaTimeChoose.scala b/core/shared/src/main/scala/org/scalacheck/time/JavaTimeChoose.scala index 6df64fa0..10e12594 100644 --- a/core/shared/src/main/scala/org/scalacheck/time/JavaTimeChoose.scala +++ b/core/shared/src/main/scala/org/scalacheck/time/JavaTimeChoose.scala @@ -15,11 +15,11 @@ import org.scalacheck._ import java.time._ /** [[Gen#Choose]] instances for `java.time` types. - * - * @note - * [[Gen#Choose]] instances for `java.time` types which are Java enum types are provided by ScalaCheck's general Java - * enum support. - */ + * + * @note + * [[Gen#Choose]] instances for `java.time` types which are Java enum types are provided by ScalaCheck's general Java + * enum support. + */ private[scalacheck] trait JavaTimeChoose { // Duration @@ -221,32 +221,32 @@ private[scalacheck] trait JavaTimeChoose { // ZoneOffset /** ZoneOffset values have some unusual semantics when it comes to ordering. The short explanation is that - * `(ZoneOffset.MAX < ZoneOffset.MIN) == true`. This is because for any given `LocalDateTime`, that time applied to - * `ZoneOffset.MAX` will be an older moment in time than that same `LocalDateTime` applied to `ZoneOffset.MIN`. - * - * From the JavaDoc, - * - * "The offsets are compared in the order that they occur for the same time of day around the world. Thus, an offset - * of +10:00 comes before an offset of +09:00 and so on down to -18:00." - * - * This has the following implication, - * - * {{{ - * scala> ZoneOffset.MIN - * val res0: java.time.ZoneOffset = -18:00 - * - * scala> ZoneOffset.MAX - * val res1: java.time.ZoneOffset = +18:00 - * - * scala> ZoneOffset.MIN.compareTo(ZoneOffset.MAX) - * val res3: Int = 129600 - * }}} - * - * This implementation is consistent with that comparison. - * - * @see - * [[https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html#compareTo-java.time.ZoneOffset-]] - */ + * `(ZoneOffset.MAX < ZoneOffset.MIN) == true`. This is because for any given `LocalDateTime`, that time applied to + * `ZoneOffset.MAX` will be an older moment in time than that same `LocalDateTime` applied to `ZoneOffset.MIN`. + * + * From the JavaDoc, + * + * "The offsets are compared in the order that they occur for the same time of day around the world. Thus, an offset + * of +10:00 comes before an offset of +09:00 and so on down to -18:00." + * + * This has the following implication, + * + * {{{ + * scala> ZoneOffset.MIN + * val res0: java.time.ZoneOffset = -18:00 + * + * scala> ZoneOffset.MAX + * val res1: java.time.ZoneOffset = +18:00 + * + * scala> ZoneOffset.MIN.compareTo(ZoneOffset.MAX) + * val res3: Int = 129600 + * }}} + * + * This implementation is consistent with that comparison. + * + * @see + * [[https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html#compareTo-java.time.ZoneOffset-]] + */ implicit final lazy val chooseZoneOffset: Choose[ZoneOffset] = new Choose[ZoneOffset] { override def choose(min: ZoneOffset, max: ZoneOffset): Gen[ZoneOffset] = diff --git a/core/shared/src/main/scala/org/scalacheck/util/CmdLineParser.scala b/core/shared/src/main/scala/org/scalacheck/util/CmdLineParser.scala index 25639696..32879dd0 100644 --- a/core/shared/src/main/scala/org/scalacheck/util/CmdLineParser.scala +++ b/core/shared/src/main/scala/org/scalacheck/util/CmdLineParser.scala @@ -61,7 +61,7 @@ private[scalacheck] trait CmdLineParser { } /** Parses a command line and returns a tuple of the parsed options, and any unrecognized strings - */ + */ def parseArgs[T](args: Array[String]): (OptMap, List[String]) = { def parse( diff --git a/core/shared/src/main/scala/org/scalacheck/util/ConsoleReporter.scala b/core/shared/src/main/scala/org/scalacheck/util/ConsoleReporter.scala index 5cf30e3c..8d6797a7 100644 --- a/core/shared/src/main/scala/org/scalacheck/util/ConsoleReporter.scala +++ b/core/shared/src/main/scala/org/scalacheck/util/ConsoleReporter.scala @@ -14,8 +14,8 @@ import org.scalacheck.Test import Pretty.{Params, pretty, format} /** A [[org.scalacheck.Test.TestCallback]] implementation that prints test results directly to the console. This is the - * callback used by ScalaCheck's command line test runner, and when you run `org.scalacheck.Prop.check()`. - */ + * callback used by ScalaCheck's command line test runner, and when you run `org.scalacheck.Prop.check()`. + */ class ConsoleReporter(val verbosity: Int, val columnWidth: Int) extends Test.TestCallback { @@ -39,8 +39,8 @@ class ConsoleReporter(val verbosity: Int, val columnWidth: Int) object ConsoleReporter { /** Factory method, creates a ConsoleReporter with the the given verbosity and wraps output at the given column width - * (use 0 for unlimited width). - */ + * (use 0 for unlimited width). + */ def apply(verbosity: Int = 0, columnWidth: Int = 75) = new ConsoleReporter(verbosity, columnWidth) diff --git a/core/shared/src/main/scala/org/scalacheck/util/Pretty.scala b/core/shared/src/main/scala/org/scalacheck/util/Pretty.scala index 9dd110e1..b4091e97 100644 --- a/core/shared/src/main/scala/org/scalacheck/util/Pretty.scala +++ b/core/shared/src/main/scala/org/scalacheck/util/Pretty.scala @@ -50,14 +50,14 @@ object Pretty { else s + List.fill(length - s.length)(c).mkString /** Break a long string across lines. - * - * This method will wrap the given string at `length` characters, inserting newlines and an optional prefix (`lead`) - * on every line other than the first. - * - * All lines in the resulting string are guaranteed to be `length` or shorter. - * - * We require `lead.length < length`; otherwise it would be impossible to legally wrap lines. - */ + * + * This method will wrap the given string at `length` characters, inserting newlines and an optional prefix (`lead`) + * on every line other than the first. + * + * All lines in the resulting string are guaranteed to be `length` or shorter. + * + * We require `lead.length < length`; otherwise it would be impossible to legally wrap lines. + */ def break(s: String, lead: String, length: Int): String = { require(lead.length < length, s"lead ($lead) should be shorter than length ($length)") val step = length - lead.length diff --git a/core/shared/src/test/scala-2.12-/org/scalacheck/time/OrderingVersionSpecific.scala b/core/shared/src/test/scala-2.12-/org/scalacheck/time/OrderingVersionSpecific.scala index 9e1c2933..b6fc538c 100644 --- a/core/shared/src/test/scala-2.12-/org/scalacheck/time/OrderingVersionSpecific.scala +++ b/core/shared/src/test/scala-2.12-/org/scalacheck/time/OrderingVersionSpecific.scala @@ -13,7 +13,7 @@ import java.time._ import java.time.chrono._ /** On Scala <= 2.12 it is used to help the compiler figure out some `Ordering` instances needed for testing. - */ + */ trait OrderingVersionSpecific { implicit final lazy val localDateOrdering: Ordering[LocalDate] = diff --git a/core/shared/src/test/scala-2.13+/org/scalacheck/time/OrderingVersionSpecific.scala b/core/shared/src/test/scala-2.13+/org/scalacheck/time/OrderingVersionSpecific.scala index a41aa2c4..952aa6f5 100644 --- a/core/shared/src/test/scala-2.13+/org/scalacheck/time/OrderingVersionSpecific.scala +++ b/core/shared/src/test/scala-2.13+/org/scalacheck/time/OrderingVersionSpecific.scala @@ -10,7 +10,7 @@ package org.scalacheck.time /** This is unused on Scala >= 2.13. - * - * On Scala <= 2.12 it is used to help the compiler figure out some `Ordering` instances needed for testing. - */ + * + * On Scala <= 2.12 it is used to help the compiler figure out some `Ordering` instances needed for testing. + */ trait OrderingVersionSpecific {}