### Running Weaver Suites for Tracing Example Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md This code snippet demonstrates how to run the TracingSuite to see the example report. ```scala println(weaver.docs.Output.runSuites(TracingSuite)) ``` -------------------------------- ### SimpleIOSuite Example Source: https://github.com/typelevel/weaver-test/blob/main/README.md Demonstrates a SimpleIOSuite with a pure test, a test with side-effects using IO, and a test with side-effects and logging. ```scala import weaver.SimpleIOSuite import cats.effect._ // Suites must be "objects" for them to be picked by the framework object MySuite extends SimpleIOSuite { pureTest "non-effectful (pure) test"{ expect("hello".size == 6) } private val random = IO(java.util.UUID.randomUUID()) test "test with side-effects" { for { x <- random y <- random } yield expect(x != y) } loggedTest "test with side-effects and a logger"{ log => for { x <- random _ <- log.info(s"x : $x") y <- random _ <- log.info(s"y : $y") } yield expect(x != y) } } ``` -------------------------------- ### Running Weaver Suites for Source Location Example Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md This code snippet demonstrates how to run the SourceLocationSuite to see the example report. ```scala println(weaver.docs.Output.runSuites(SourceLocationSuite)) ``` -------------------------------- ### Running Weaver Example Suite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md This code snippet demonstrates how to execute the defined Weaver test suite and print its report. ```scala println(weaver.docs.Output.runSuites(ExpectationsSuite)) ``` -------------------------------- ### Demonstrate Resource Lifecycle Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/resources.md This example shows how `Resource.make` acquires and releases a resource, recording messages at each stage. The `record` helper function logs lifecycle events. ```scala import java.util.concurrent.ConcurrentLinkedQueue // We will store the messages in this queue val order = new ConcurrentLinkedQueue[String]() object ResourceDemo extends IOSuite { def record(msg: String) = IO(order.add(msg)).void override type Res = Int override def sharedResource = { val acquire = record("Acquiring resource") *> IO.pure(42) val release = (i: Int) => record(s"Releasing resource $i") Resource.make(acquire)(release) } test("Test 1") { res => record(s"Test 1 is using resource $res").as(success) } test("Test 2") { res => record(s"Test 2 is using resource $res").as(expect(res == 45)) } } ``` -------------------------------- ### Import Weaver for Testing Source: https://github.com/typelevel/weaver-test/blob/main/docs/overview/installation.md Import the necessary Weaver library to start writing tests. ```scala import weaver._ ``` -------------------------------- ### IOSuite Example with Shared Resource Source: https://github.com/typelevel/weaver-test/blob/main/README.md Illustrates an IOSuite where a shared resource is created once for all tests. Includes tests that do not use the resource, use the resource, and use the resource with a logger. ```scala import weaver.IOSuite import cats.effect._ object MySuite extends IOSuite { type Res = Int def sharedResource : Resource[IO, Int] = Resource .make( IO(println("Making resource")) .as(123) )(n => IO(println(s"Closing resource $n"))) test "test, but resource not visible"{ IO(expect(123 == 123)) } test "test with resource"{ n => IO(expect(n == 123)) } test "test with resource and a logger"{ (n, log) => log.info("log was available") *> \ IO(expect(n == 123)) } } ``` -------------------------------- ### Develop Scalafix Rule Source: https://github.com/typelevel/weaver-test/blob/main/scalafix/readme.md Use this command to start the development process for a Scalafix rule. It automatically recompiles the tests when rule files are edited. ```shell sbt ~tests/test # edit rules/src/main/scala/fix/RenameAssertToExpect.scala ``` -------------------------------- ### Basic Test Suite with SimpleIOSuite Source: https://github.com/typelevel/weaver-test/blob/main/docs/overview/installation.md Example of a basic test suite extending `SimpleIOSuite` for side-effecting functions. Tests are registered imperatively and executed as a single `IO`. ```scala import cats.effect._ // Suites must be "objects" for them to be picked by the framework object MySuite extends SimpleIOSuite { val randomUUID = IO(java.util.UUID.randomUUID()) // A test for side-effecting functions test("hello side-effects") { for { x <- randomUUID y <- randomUUID } yield expect(x != y) } } ``` -------------------------------- ### Accessing Global Resources in a Suite Source: https://context7.com/typelevel/weaver-test/llms.txt Demonstrates how to access globally shared resources within a test suite by declaring the resource type and retrieving it using `global.getOrFailR`. This example accesses an HTTP client. ```scala // Access global resources via constructor parameter class MySuite(global: GlobalRead) extends IOSuite { type Res = Client[IO] def sharedResource: Resource[IO, Client[IO]] = global.getOrFailR[Client[IO]]() test("using global http client") { client => for { status <- client.get("https://example.com")(r => IO.pure(r.status.code)) } yield expect(status == 200) } } ``` -------------------------------- ### Example Suite Demonstrating Equality Assertions Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md This suite showcases various equality assertion methods in Weaver, including expect.eql for standard and user-defined types, and expect.same for relaxed comparisons. ```scala import weaver._ object ExpectationsSuite extends SimpleIOSuite { pureTest("expect.eql for standard data types") { expect.eql(1, 2) } import cats.Eq case class Pet(name: String) implicit val eqPet: Eq[Pet] = Eq.by[Pet, String](_.name) pureTest("expect.eql for user-defined data types") { expect.same(Pet("Maru"), Pet("Fido")) } // Note that we don't have an instance of Eq[Dog] // anywhere in scope case class Dog(name: String) pureTest("expect.same relaxed equality comparison") { expect.same(Dog("Maru"), Dog("Fido")) } } ``` -------------------------------- ### Example of a failing property test Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/scalacheck.md Demonstrates a property test that is expected to fail, using two `Arbitrary` integer parameters. ```scala test("Failure example") { // There are 6 overloads, to pass 1-6 parameters forall { (a1: Int, a2: Int) => expect(a1 + a2 % 2 == 0) } } ``` -------------------------------- ### Use the Timed Test Function Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/custom_test_functions.md Example of using the custom `timedTest` function defined in `TimedSuite`. This demonstrates how to call the custom test function with a test case that includes a delay. ```scala import scala.concurrent.duration.* object ExampleSuite extends TimedSuite { timedTest("timed test")(IO.sleep(2.seconds).as(failure("failed"))) } ``` -------------------------------- ### Fallback for `testOnly` Commands Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/global_resources.md Provide a fallback mechanism for resources when using build tool commands like `testOnly` that might not pass all global resources. This example uses `getR` and falls back to `baseResources` if the resource is not found. ```scala // package yourproject.resource import cats.effect.{ IO, Resource } import weaver._ object MyResources extends GlobalResource { override def sharedResources(global: GlobalWrite): Resource[IO, Unit] = baseResources.flatMap(global.putR(_)) def baseResources: Resource[IO, String] = Resource.pure[IO, String]("hello world!") // Provides a fallback to support running individual tests via testOnly def sharedResourceOrFallback(read: GlobalRead): Resource[IO, String] = read.getR[String]().flatMap { case Some(value) => Resource.eval(IO(value)) case None => baseResources } } ``` ```scala // package yourproject.somepackage class MySuite(global: GlobalRead) extends IOSuite { import MyResources._ override type Res = String def sharedResource: Resource[IO, String] = sharedResourceOrFallback(global) test "a stranger, from the outside ! ooooh" { sharedString => IO(expect(sharedString == "hello world!")) } } ``` ```scala // package yourproject.somepackage class MyOtherSuite(global: GlobalRead) extends IOSuite { import MyResources._ override type Res = String def sharedResource: Resource[IO, String] = sharedResourceOrFallback(global) test "oops, forgot something here" { sharedString => IO(expect(sharedString == "hello world!")) } } ``` -------------------------------- ### Define a Simple IO Test Suite Source: https://github.com/typelevel/weaver-test/blob/main/docs/samples/multiple_suites_success.md Create a test suite using SimpleIOSuite for tests involving Cats Effect IO. This example demonstrates testing side-effects like generating random UUIDs. ```scala import cats.effect._ object MySuite extends SimpleIOSuite { val randomUUID = IO(java.util.UUID.randomUUID()) test("hello side-effects") { for { x <- randomUUID y <- randomUUID } yield expect(x != y) } } ``` -------------------------------- ### Define a Test Suite for String Reversal Source: https://github.com/typelevel/weaver-test/blob/main/docs/samples/multiple_suites_success.md Another example using SimpleIOSuite to test a property: double reversing a string is an identity operation. It uses IO to generate a random string. ```scala object MyAnotherSuite extends SimpleIOSuite { import scala.util.Random.alphanumeric val randomString = IO(alphanumeric.take(10).mkString("")) test("double reversing is identity") { for { x <- randomString } yield expect(x == x.reverse.reverse) } } ``` -------------------------------- ### Label Shared Resources in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/global_resources.md This example shows how to label shared resources using `global.putR` with optional string tags. It then demonstrates how to retrieve these labelled resources in a test suite using `global.getOrFailR`. ```scala import cats.syntax.all._ object LabelSharedResources extends GlobalResource { def sharedResources(global: GlobalWrite): Resource[IO, Unit] = for { _ <- global.putR(1, "one".some) _ <- global.putR(2, "two".some) } yield () } class LabelSharingSuite(global: GlobalRead) extends IOSuite { type Res = Int // We didn't store an `Int` value in our `GlobalResourcesInit` impl def sharedResource: Resource[IO, Int] = for { one <- global.getOrFailR[Int]("one".some) two <- global.getOrFailR[Int]("two".some) } yield one + two test("labels work") { sharedInt => IO(expect(sharedInt == 3)) } } ``` -------------------------------- ### Access Global Resources in a Suite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/global_resources.md Access globally declared resources by defining a suite constructor that accepts `GlobalRead`. Use `getOrFailR` to retrieve a resource, expecting it to be present. This example retrieves a `String` resource. ```scala class SharingSuite(global: GlobalRead) extends IOSuite { type Res = String def sharedResource: Resource[IO, String] = global.getOrFailR[String]() test "a stranger, from the outside ! ooooh" { sharedString => IO(expect(sharedString == "hello world!")) } } ``` -------------------------------- ### Access Potentially Missing Global Resources Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/global_resources.md Safely access global resources using `getR` which returns an `Option`. This is useful when a resource might not have been declared or is optional. This example retrieves an `Option[Int]`. ```scala class OtherSharingSuite(global: GlobalRead) extends IOSuite { type Res = Option[Int] // We didn't store an `Int` value in our `GlobalResourcesInit` impl def sharedResource: Resource[IO, Option[Int]] = global.getR[Int]() test "oops, forgot something here" { sharedInt => IO(expect(sharedInt.isEmpty)) } } ``` -------------------------------- ### Use the Redefined Test Function Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/custom_test_functions.md Example of using the redefined `test` function from a custom `TimedSuite`. This shows how to define a test case that will be timed using the custom `test` implementation. ```scala import scala.concurrent.duration._ object ExampleSuite extends TimedSuite { test("timed test")(IO.sleep(2.seconds).as(failure("failed"))) } ``` -------------------------------- ### ScalaCheck Integration - Local Config Override Source: https://context7.com/typelevel/weaver-test/llms.txt Shows how to override ScalaCheck's configuration locally for a specific test property. This example overrides the initial seed for reproducibility. ```scala test("local config override") { forall.withConfig(checkConfig.copy(initialSeed = Some(7L))) { (x: Int) => expect(x * 0 == 0) } } ``` -------------------------------- ### Investigate failures using clue Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Wrap values with `clue` within an `expect` assertion to get more detailed information about the failure when the assertion does not hold. ```scala expect(clue(list).size > 4) ``` -------------------------------- ### Declare Global Resources with `GlobalResource` Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/global_resources.md Implement `GlobalResource` in a static object to declare resources shared across suites. Use `GlobalWrite` to store resources indexed by type. This example shows storing a `String` resource. ```scala import weaver._ import cats.effect.IO import cats.effect.Resource // note how this is a static object object SharedResources extends GlobalResource { def sharedResources(global: GlobalWrite): Resource[IO, Unit] = for { foo <- Resource.pure[IO, String]("hello world!") _ <- global.putR(foo) } yield () } ``` -------------------------------- ### Use Discipline with Weaver FunSuite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/discipline.md Mixin `weaver.discipline.Discipline` into a `FunSuite` to enable Discipline law testing. This example checks the `Eq` laws for `Int` and `Boolean`. ```scala import weaver._ import weaver.discipline._ import cats.kernel.laws.discipline.EqTests object DisciplineTests extends FunSuite with Discipline { checkAll("Int", EqTests[Int].eqv) checkAll("Boolean", EqTests[Boolean].eqv) } ``` -------------------------------- ### Define Custom Test Functions with `registerTest` Source: https://context7.com/typelevel/weaver-test/llms.txt Extend the test interface by defining custom test functions using `registerTest`. This example creates a `timedTest` that logs the duration of test execution. ```scala import weaver._ import cats.effect._ import scala.concurrent.duration._ trait TimedSuite extends SimpleIOSuite { def timedTest(name: TestName)(run: IO[Expectations]): Unit = registerTest(name)(_ => Test[IO]( name.name, (log: Log[IO]) => for { (duration, expectations) <- run.timed _ <- log.info(s"Test completed in ${duration.toMillis}ms") } yield expectations ) ) } object TimedExampleSuite extends TimedSuite { timedTest("slow operation") { IO.sleep(500.millis).as(expect(true)) } timedTest("fast operation") { IO(expect(1 + 1 == 2)) } } ``` -------------------------------- ### Defining Eq Instance for Custom Types Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md To use expect.eql with custom data types, you need to provide an Eq typeclass instance. This example shows how to define an Eq instance for a Pet case class based on its name. ```scala case class Pet(name: String) // A cats.Eq instance is needed import cats.Eq implicit val petEq: Eq[Pet] = Eq.by(_.name) object ExpectEqlSuite extends SimpleIOSuite { pureTest("Simple expectation") { expect.eql(Pet("Maru"), Pet("Fido")) } } ``` -------------------------------- ### Logging Failing Tests with Context in Scala Source: https://github.com/typelevel/weaver-test/blob/main/docs/samples/multiple_suites_logging.md Shows how to log messages with custom context for tests that are expected to fail. The `context` map allows attaching arbitrary key-value pairs to log entries. This example uses `SimpleIOSuite` and `loggedTest`. ```scala import weaver._ import cats.effect._ import scala.util.Random.alphanumeric object MyAnotherSuite extends SimpleIOSuite { val randomString = IO(alphanumeric.take(10).mkString("")) loggedTest("failure should print logs") { log => for { currentTime <- IO.realTime.map(_.toSeconds) context = Map("time" -> currentTime.toString, "purpose" -> "docs") _ <- log.info("Starting the test...", context) x <- randomString _ <- log.debug(s"Generated random string: $x") } yield expect(x.length > 20) } } ``` -------------------------------- ### Access Logger with Shared Resources Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md Access the logger as the second argument in the `test` function when using shared resources. This allows logging within tests that also utilize shared setup. ```scala import weaver._ import cats.effect._ import org.http4s.ember.client._ import org.http4s.client._ object HttpSuite extends IOSuite { override type Res = Client[IO] override def sharedResource : Resource[IO, Res] = EmberClientBuilder.default[IO].build // The log is passed as the second argument test("This test fails") { (httpClient, log) => for { statusCode <- httpClient.get("https://httpbin.org/oops") { response => for { _ <- log.info(s"Content length: ${response.contentLength}") } yield response.status.code } } yield expect.eql(200, statusCode) } } ``` -------------------------------- ### Build Weaver Website Locally Source: https://github.com/typelevel/weaver-test/blob/main/README.md Build the documentation website locally using `sbt docs/tlSitePreview`. Navigate to `http://localhost:4242` to view changes. ```bash sbt docs/tlSitePreview ``` -------------------------------- ### Create Input File for SymbolMatcher Source: https://github.com/typelevel/weaver-test/blob/main/scalafix/readme.md Create a Scala file to serve as input for exploring symbols with SymbolMatcher. This file will be used to generate semanticdb files. ```shell # create v0_9_0/input/src/main/scala/fix/AddClueToExpectTest.scala ``` -------------------------------- ### Compile Code with sbt Source: https://github.com/typelevel/weaver-test/blob/main/scalafix/readme.md Compile your Scala code using sbt. This step is necessary before generating or exploring semanticdb files. ```shell sbt compile ``` -------------------------------- ### Print Resource Lifecycle Output Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/resources.md This passthrough code executes the `ResourceDemo` suites and prints the contents of the `order` queue to demonstrate the resource acquisition and release sequence. ```scala println(weaver.docs.Output.runSuites(ResourceDemo)) println("Contents of `order` are:\n") println("```") order.toArray.foreach { el => println(s"// * $el") } println("```") ``` -------------------------------- ### Run FunSuite Tests Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/funsuite.md This snippet demonstrates how to execute the defined `FunSuite` tests and view their output using `weaver.docs.Output.runSuites`. ```scala println(weaver.docs.Output.runSuites(CatsFunSuite)) ``` -------------------------------- ### SimpleIOSuite - Basic Test Suite Source: https://context7.com/typelevel/weaver-test/llms.txt Extend SimpleIOSuite for basic test suites. Tests are registered imperatively and executed in parallel within a single IO. ```scala import weaver.SimpleIOSuite import cats.effect._ object MySuite extends SimpleIOSuite { // Pure test without side effects pureTest("non-effectful (pure) test") { expect("hello".size == 5) } private val random = IO(java.util.UUID.randomUUID()) // Test with side effects test("test with side-effects") { for { x <- random y <- random } yield expect(x != y) } // Test with logging - logs only shown on failure loggedTest("test with side-effects and a logger") { log => for { x <- random _ <- log.info(s"x : $x") y <- random _ <- log.info(s"y : $y") } yield expect(x != y) } } ``` -------------------------------- ### Explore Symbols with Metap Source: https://github.com/typelevel/weaver-test/blob/main/scalafix/readme.md Use the metap tool to explore the contents of a .semanticdb file. This is useful for understanding symbol information and debugging Scalafix rules. ```shell metap v0_9_0/input/target/jvm-3/meta/META-INF/semanticdb/v0_9_0/input/src/main/scala/fix/AddClueToExpectTest.scala.semanticdb ``` -------------------------------- ### Use forall with composed Gen instances Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/scalacheck.md Shows how to compose multiple `Gen` instances monadically to create a single `Gen` for use with `forall` when testing pairs of positive integers. ```scala test("Multiple Gen form") { // Compose into a single `Gen[(Int, Int)]` val gen = for { a <- Gen.posNum[Int] b <- Gen.posNum[Int] } yield (a, b) // Unapply the tuple to access individual members forall(gen) { case (a, b) => expect(a > 0) and expect(b > 0) } } ``` -------------------------------- ### Use forall with a single Gen instance Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/scalacheck.md Demonstrates using `forall` with a single explicit `Gen` instance to test properties of generated positive integers. ```scala test("Single Gen form") { // Takes a single, explicit `Gen` instance forall(Gen.posNum[Int]) { a => expect(a > 0) } } ``` -------------------------------- ### Use forall with Arbitrary instances Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/scalacheck.md Illustrates using `forall` with multiple `Arbitrary` instances to test properties of generated integers. Supports up to 6 parameters. ```scala test("Arbitrary form") { // There are 6 overloads, to pass 1-6 parameters forall { (a1: Int, a2: Int, a3: Int) => expect(a1 * a2 * a3 == a3 * a2 * a1) } } ``` -------------------------------- ### IOSuite - Shared Resources Source: https://context7.com/typelevel/weaver-test/llms.txt Use IOSuite to construct and share a resource across all tests in a suite. This pattern ensures resource cleanup after all tests complete. ```scala import weaver.IOSuite import cats.effect._ import org.http4s.ember.client._ import org.http4s.client._ object HttpSuite extends IOSuite { // Define the shared resource type override type Res = Client[IO] // Resource is acquired once before all tests, released after all tests override def sharedResource: Resource[IO, Res] = EmberClientBuilder.default[IO].build // Test without resource access test("test without resource") { IO(expect(1 + 1 == 2)) } // Test receives shared resource as argument test("test with resource") { httpClient => for { statusCode <- httpClient.get("https://httpbin.org/get") { response => IO.pure(response.status.code) } } yield expect(statusCode == 200) } // Test with both resource and logger test("test with resource and logger") { (httpClient, log) => for { _ <- log.info("Making HTTP request") statusCode <- httpClient.get("https://httpbin.org/get") { response => IO.pure(response.status.code) } } yield expect(statusCode == 200) } } ``` -------------------------------- ### Run RewriteExpect Scalafix Rule Source: https://github.com/typelevel/weaver-test/blob/main/docs/faqs/expecty_removal.md Use this command to automatically rewrite `expect` and `expect.all` assertions to use improved failure messages. Replace `@VERSION@` with the actual version. ```sh sbt scalafixAll github:typelevel/weaver-test/RewriteExpect?sha=@VERSION@ ``` -------------------------------- ### Build Expectations with `expect` and `clue` Source: https://github.com/typelevel/weaver-test/blob/main/README.md Use `expect` and `clue` to create test expectations. `clue` captures compile-time boolean expressions for better feedback on failures. ```scala expect(clue(List(1, 2, 3).size) == 4) ``` -------------------------------- ### Simple Expectations in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Illustrates basic success and failure assertions using `expect` and `clue` for debugging. ```scala import weaver._ import cats.effect.IO object ExpectationsSuite extends SimpleIOSuite { def test(a: Int) = a + 5 pureTest("Simple expectations (success)") { val z = 15 expect(test(z) < z + 6) } pureTest("Simple expectations (failure)") { val z = 15 expect(clue(test(z)) > z + 6) } } ``` -------------------------------- ### Share HTTP Client Across Tests Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/resources.md Implement `sharedResource` to provide a single `Client[IO]` instance for all tests in the suite. The client is acquired before tests run and released afterwards. ```scala import weaver._ import cats.effect._ // Using http4s import org.http4s.ember.client._ import org.http4s.client._ object HttpSuite extends IOSuite { // Sharing a single http client across all tests override type Res = Client[IO] override def sharedResource : Resource[IO, Res] = EmberClientBuilder.default[IO].build // The test receives the shared client as an argument test("Good requests lead to good results") { httpClient => for { statusCode <- httpClient.get("https://httpbin.org/get"){ response => IO.pure(response.status.code) } } yield expect(statusCode == 200) } test("Bad requests lead to bad results") { httpClient => for { statusCode <- httpClient.get("https://httpbin.org/oops"){ response => IO.pure(response.status.code) } } yield expect(statusCode == 404) } } ``` -------------------------------- ### Locate SemanticDB File Source: https://github.com/typelevel/weaver-test/blob/main/scalafix/readme.md Find the generated .semanticdb file after compiling your code. This file contains symbol information used by Scalafix and other tools. ```shell ls v0_9_0/input/target/jvm-3/meta/META-INF/semanticdb/v0_9_0/input/src/main/scala/fix/AddClueToExpectTest.scala.semanticdb ``` -------------------------------- ### Run AddClueToExpect Scalafix Rule Source: https://github.com/typelevel/weaver-test/blob/main/docs/faqs/expecty_removal.md Apply this rule to add `clue` calls to remaining `expect` assertions, ensuring failure messages include captured values. Replace `@VERSION@` with the actual version. ```sh sbt scalafixAll github:typelevel/weaver-test/AddClueToExpect?sha=@VERSION@ ``` -------------------------------- ### Accessing Labeled Global Resources Source: https://context7.com/typelevel/weaver-test/llms.txt Shows how to access globally shared resources that have been labeled. This allows for disambiguation when multiple resources of the same type are shared. ```scala // Access labeled resources class DbSuite(global: GlobalRead) extends IOSuite { type Res = String def sharedResource: Resource[IO, String] = global.getOrFailR[String](Some("db")) test("using labeled database resource") { dbConn => IO(expect(dbConn == "database-connection")) } } ``` -------------------------------- ### FunSuite - Pure Tests Source: https://context7.com/typelevel/weaver-test/llms.txt Use FunSuite for tests that do not require effect types. Tests run sequentially without the overhead of effect management. ```scala import weaver.FunSuite object PureSuite extends FunSuite { test("simple assertion") { expect(Some(5).contains(5)) } test("equality check") { expect.eql(List(1, 2, 3), (1 to 3).toList) } test("multiple assertions") { expect(1 > 0) and expect(2 > 1) } } ``` -------------------------------- ### Defining Global Resources Source: https://context7.com/typelevel/weaver-test/llms.txt Shows how to define global resources using `GlobalResource` that can be shared across multiple test suites. Resources are defined in a static object and managed by Weaver. ```scala import weaver._ import cats.effect._ // Define global resources as a static object object SharedResources extends GlobalResource { def sharedResources(global: GlobalWrite): Resource[IO, Unit] = for { httpClient <- EmberClientBuilder.default[IO].build _ <- global.putR(httpClient) dbPool <- Resource.pure[IO, String]("database-connection") _ <- global.putR(dbPool, Some("db")) // Labeled resource } yield () } ``` -------------------------------- ### Assert on boolean values using expect Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use the `expect` macro to assert on boolean conditions. This is the most basic form of expectation. ```scala expect(list.size > 4) ``` -------------------------------- ### Logging Successful Tests in Scala Source: https://github.com/typelevel/weaver-test/blob/main/docs/samples/multiple_suites_logging.md Demonstrates how to use the `log.info` method within a `loggedTest` to record information for tests that pass. Ensure `weaver-cats` is imported for `SimpleIOSuite`. ```scala import weaver._ import cats.effect._ object MySuite extends SimpleIOSuite { val randomUUID = IO(java.util.UUID.randomUUID()) loggedTest("logging for success") { log => for { x <- randomUUID y <- randomUUID _ <- log.info(s"Generated $x and $y") } yield expect(x != y) } } ``` -------------------------------- ### Basic Expectation in Weaver Source: https://context7.com/typelevel/weaver-test/llms.txt Demonstrates a simple assertion using the `expect` macro. This is the most basic way to construct a pure, composable expectation. ```scala import weaver._ import cats.effect.IO object ExpectationsSuite extends SimpleIOSuite { pureTest("basic expect") { expect(1 + 1 == 2) } } ``` -------------------------------- ### Working with Collections in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Illustrates testing collections using `forEach`, `exists`, and `and` for combined checks on lists and options. ```scala pureTest("Working with collections (success)") { forEach(List(1, 2, 3))(i => expect(i < 5)) and forEach(Option("hello"))(msg => expect.eql("hello", msg)) and exists(List("a", "b", "c"))(i => expect.eql("c", i)) and exists(Vector(true, true, false))(i => expect.eql(false, i)) } pureTest("Working with collections (failure 1)") { forEach(Vector("hello", "world"))(msg => expect.eql("hello", msg)) } pureTest("Working with collections (failure 2)") { exists(Option(39))(i => expect(clue(i) > 50)) } ``` -------------------------------- ### Using expect with clue for Relational Assertions Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md When using expect for relational assertions like 'greater than', combine it with clue to provide better failure messages, as demonstrated with checking if x > 2. ```scala expect(clue(x) > 2) ``` -------------------------------- ### Compose expectations using symbolic aliases &&/|| Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use the symbolic aliases `&&` for `and` and `||` for `or` to compose expectations in a more concise, infix notation. ```scala (expect(1 > 0) && expect(2 > 1)) || expect(5 < 6) ``` -------------------------------- ### Displaying a Trace of Source Locations Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md Utilize the traced(here) function to display a trace of source locations from nested helper functions when tests fail. ```scala import weaver._ object TracingSuite extends FunSuite { case class Response(body: String, status: Int) test("This test fails") { val response = Response("this went wrong", 500) expectOk(response) // The failure points here first } def expectOk(response: Response)(implicit loc: SourceLocation): Expectations = { expectOkStatus(response) .traced(here) // The failure points here third } def expectOkStatus(response: Response)(implicit loc: SourceLocation): Expectations = { expect.eql(200, response.status) .traced(here) // The failure points here second } } ``` -------------------------------- ### Using expect.same with Custom Types without Eq Instance Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md expect.same can be used with custom data types even if an Eq instance is not defined, as shown with the Dog case class. ```scala case class Dog(name: String) // No Eq instance defined object ExpectSameSuite extends SimpleIOSuite { pureTest("Simple expectation") { expect.same(Dog("Maru"), Dog("Fido")) } } ``` -------------------------------- ### Generate Test Report Output Source: https://github.com/typelevel/weaver-test/blob/main/docs/samples/multiple_suites_failures.md Use this passthrough code to generate the report output by running the defined suites. ```scala println(weaver.docs.Output.runSuites(MySuite, MyAnotherSuite)) ``` -------------------------------- ### Create succeeding/failing expectations with success/failure Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use `success` to create an expectation that always passes, and `failure` to create one that always fails with a given message. These are useful for setting baseline expectations or for conditional logic. ```scala val result = if(5 == 5) success else failure("oh no") ``` -------------------------------- ### Assert on all boolean values using expect.all Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md The `expect.all` method provides a varargs short form to assert that all provided boolean expressions evaluate to true. It's a convenient way to check multiple conditions simultaneously. ```scala expect.all(1 > 0, 2 > 1, 3 > 2) ``` -------------------------------- ### Compare values using expect.same Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use `expect.same` for relaxed equality comparison, which does not require an `Eq` instance. This is useful for types that don't have a readily available `Eq` instance or when a simpler comparison is sufficient. ```scala expect.same(List(1, 2, 3), (1 to 3).toList) ``` -------------------------------- ### Run Weaver Suites Standalone Source: https://github.com/typelevel/weaver-test/blob/main/README.md Instantiate `weaver.Runner`, create a `fs2.Stream` of suites, and call `runner.run(stream)` to execute suites outside of a build tool. ```scala import weaver._ // Example of running a suite standalone (implementation details omitted) // val runner = new weaver.Runner[IO] // val stream = fs2.Stream(new MySuite) // runner.run(stream) ``` -------------------------------- ### Configure Weaver-Cats for scala-cli Source: https://github.com/typelevel/weaver-test/blob/main/docs/overview/installation.md Add Weaver-Cats as a library dependency and specify the test framework for scala-cli. ```scala //> using lib "org.typelevel::weaver-cats:@VERSION@" //> using testFramework "weaver.framework.CatsEffect" // this may be neccessary if you have other testFramework on your dependencies ``` -------------------------------- ### Non-Macro Based Expectations in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Demonstrates manual success and failure reporting using `success` and `failure` when macro-based expectations are not suitable. ```scala pureTest("Non macro-based expectations") { val condition : Boolean = false if (condition) success else failure("Condition failed") } ``` -------------------------------- ### Configure Weaver-Cats for Mill Source: https://github.com/typelevel/weaver-test/blob/main/docs/overview/installation.md Configure Mill build tool to use Weaver-Cats by specifying ivy dependencies and the test framework. ```scala object test extends Tests { def ivyDeps = Agg( ivy"org.typelevel::weaver-cats:@VERSION@" ) def testFramework = "weaver.framework.CatsEffect" } ``` -------------------------------- ### Configure Weaver-Test for Gradle Source: https://github.com/typelevel/weaver-test/blob/main/docs/overview/installation.md Use the Gradle plugin for multi-backend Scala to integrate Weaver-Test. ```groovy plugins { id 'org.podval.tools.scalajs' version '' } dependencies { testImplementation scalaBackend.testFramework(org.podval.tools.test.framework.WeaverTest) } ``` -------------------------------- ### Test every element of a collection using forEach Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use `forEach` to apply an expectation to every element within a `Foldable` collection. This is ideal for verifying that a condition holds true for all items in a list, set, or other foldable structures. ```scala forEach(List(1, 2, 3))(i => expect(i < 5)) ``` -------------------------------- ### Run a Single Test in a Suite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/filtering.md Append `.only` to a test's name to ensure only that specific test is executed within its suite. Other tests in the same suite will be skipped. ```scala import weaver._ object ExampleSuite extends FunSuite { test ("Only run this test".only) { expect.eql(1, 2) } test ("This test will not be run") { expect.eql(1, 1) } } ``` -------------------------------- ### ScalaCheck Integration - Composing Generators Source: https://context7.com/typelevel/weaver-test/llms.txt Demonstrates composing multiple ScalaCheck generators monadically to create more complex input data for property-based tests. The `forall` function then uses this combined generator. ```scala test("multiple Gens composed monadically") { val gen = for { a <- Gen.posNum[Int] b <- Gen.posNum[Int] } yield (a, b) forall(gen) { case (a, b) => expect(a > 0) and expect(b > 0) } } ``` -------------------------------- ### Failing Fast with Match in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Shows how to use `matchOrFailFast` within a failing fast context to assert on pattern matching results. ```scala test("Failing fast match") { for { h <- IO.pure(Some(4)) x <- matchOrFailFast[IO](h) { case Some(v) => v } g <- IO.pure(Option.empty[Int]) y <- matchOrFailFast[IO](g) { case Some(v) => v } } yield expect.eql(x, y) } ``` -------------------------------- ### Define a Timed Test Function with IOSuite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/custom_test_functions.md Define a `timedTest` function that extends `SimpleIOSuite` to log test duration. This function uses `registerTest` to wrap the test execution and log its time. ```scala import weaver._ import cats.effect._ trait TimedSuite extends SimpleIOSuite { def timedTest(name: TestName)(run: IO[Expectations]): Unit = registerTest(name)(_ => Test[IO]( name.name, (log: Log[IO]) => // Run the test, then log the time. for { (time, expectations) <- run.timed _ <- log.info(s"Test took ${time.toSeconds} seconds") } yield expectations ) ) } ``` -------------------------------- ### Pattern match and evaluate eagerly with matchOrFailFast Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Similar to `failFast`, `matchOrFailFast` attempts to match an expression against a pattern. If successful, it returns the matched value within the effect type; otherwise, it fails fast. This combines pattern matching with eager error handling. ```scala for { b <- IO(Some(4)) s <- matchOrFailFast[IO](b) { case Some(v) => v.toString } c <- IO("4") } yield expect.eql(s, c) ``` -------------------------------- ### Success and Failure Helpers Source: https://context7.com/typelevel/weaver-test/llms.txt Uses `success` and `failure` helpers to explicitly return a passing or failing expectation. This is useful for conditional assertions or when an explicit outcome is needed. ```scala if (5 == 5) success else failure("oh no") ``` -------------------------------- ### Expectation with Clue for Diagnostics Source: https://context7.com/typelevel/weaver-test/llms.txt Uses the `clue` macro to provide better diagnostics when an expectation fails. It shows the value of the expression that failed, which is helpful for debugging. ```scala val list = List(1, 2, 3) expect(clue(list.size) > 4) // Shows: list.size = 3 ``` -------------------------------- ### Discipline Integration - Law Testing Source: https://context7.com/typelevel/weaver-test/llms.txt Integrates the `weaver-discipline` library for testing typeclass laws. The `checkAll` method from `Discipline` is used to run law tests for specified typeclasses. ```scala // libraryDependencies += "org.typelevel" %% "weaver-discipline" % "0.8.4" % Test import weaver._ import weaver.discipline._ import cats.kernel.laws.discipline.EqTests object LawsSuite extends FunSuite with Discipline { checkAll("Int", EqTests[Int].eqv) checkAll("Boolean", EqTests[Boolean].eqv) } ``` -------------------------------- ### Run Weaver test suites with ScalaCheck Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/scalacheck.md This code snippet is used to execute the defined Weaver test suites, including those with ScalaCheck integration, and print their output. ```scala println(weaver.docs.Output.runSuites(ForallExamples)) ``` -------------------------------- ### Scalacheck Integration: `forall` with `Gen` Source: https://github.com/typelevel/weaver-test/blob/main/README.md Integrate scalacheck for property-based testing using the `forall` function with an explicit `Gen` instance. This overload is unique. ```scala import weaver._ import weaver.scalacheck._ import org.scalacheck.Gen object ForallExamples extends SimpleIOSuite with Checkers { override def checkConfig: CheckConfig = super.checkConfig.copy(perPropertyParallelism = 100) test("Gen form") { forall(Gen.posNum[Int]) { a => expect(a > 0) } } test("Arbitrary form") { forall { (a1: Int, a2: Int, a3: Int) => expect(a1 * a2 * a3 == a3 * a2 * a1) } } test("foobar") { forall.withConfig(super.checkConfig.copy(perPropertyParallelism = 1, initialSeed = Some(7L))) { (x: Int) => expect(x > 0) } } } ``` -------------------------------- ### Basic Equality Assertion with expect.eql Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md Use expect.eql for strict equality checks. Ensure that the data types being compared have an Eq typeclass instance available. ```scala expect.eql(expected, found) ``` -------------------------------- ### Define Pure Tests with FunSuite Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/funsuite.md Use `FunSuite` for tests that do not require effect-types. Each `test` block defines an assertion, a failing check, or an exception. ```scala object CatsFunSuite extends weaver.FunSuite { test("asserts") { expect(Some(5).contains(5)) } test("fails") { expect(Some(25).contains(5)) } test("throws") { throw new RuntimeException("oops") } } ``` -------------------------------- ### FailFast Expectation for Early Termination Source: https://context7.com/typelevel/weaver-test/llms.txt Demonstrates the use of `failFast` to stop a test immediately when an expectation fails. This is useful in for-comprehensions to prevent further execution after an error. ```scala for { x <- IO("hello") _ <- expect(x.length > 3).failFast y = x + "world" _ <- expect(y.size > x.size).failFast } yield expect(y.contains(x)) ``` -------------------------------- ### Use `clue` for Failure Diagnostics Source: https://context7.com/typelevel/weaver-test/llms.txt Employ `clue` to add variable values to test failures. The values are only displayed when a test fails, aiding in debugging. ```scala import weaver._ import cats.effect.IO object DiagnosticsSuite extends SimpleIOSuite { pureTest("clue shows variable values on failure") { val x = 1 val y = 2 expect(clue(x) > clue(y)) // Shows: x = 1, y = 2 } pureTest("nested clues") { val list = List(1, 2, 3) expect(clue(clue(list).size) > 5) // Shows list and list.size } loggedTest("logging for complex diagnostics") { log => for { response <- IO.pure(Map("status" -> 500, "body" -> "error")) _ <- log.info(s"Response status: ${response("status")}") _ <- log.info(s"Response body: ${response("body")}") } yield expect(response("status") == 200) } // Custom source location in helper functions def expectPositive(n: Int)(implicit loc: SourceLocation): Expectations = expect(n > 0) pureTest("helper with source location") { expectPositive(-1) // Points to this line, not helper definition } // Traced assertions for nested helpers def expectValid(s: String)(implicit loc: SourceLocation): Expectations = expectNonEmpty(s).traced(here) def expectNonEmpty(s: String)(implicit loc: SourceLocation): Expectations = expect(s.nonEmpty).traced(here) pureTest("traced assertions show call stack") { expectValid("") // Shows trace through both helpers } } ``` -------------------------------- ### Basic Equality Assertion with expect.same Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/asserting_equality.md Use expect.same for universal equality checks. This method compiles even when comparing different types, but the test will fail at runtime. ```scala expect.same(expected, found) ``` -------------------------------- ### Run Subset of Tests with sbt Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/filtering.md Use the `testOnly` command with a filter to execute only tests matching a specific pattern in their qualified name. ```scala > testOnly -- -o *foo* ``` -------------------------------- ### Relaxed Equality Comparison in Weaver Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Shows how `expect.same` performs relaxed equality checks, using `equals` method instead of `Eq` instances. ```scala // Note that we don't have an instance of Eq[Hello] // anywhere in scope class Hello(val d: Double) { override def toString = s"Hello to $d" override def equals(other: Any) = if(other != null && other.isInstanceOf[Hello]) other.asInstanceOf[Hello].d == this.d else false } pureTest("Relaxed equality comparison (success)") { expect.same(new Hello(25.0), new Hello(25.0)) } pureTest("Relaxed equality comparison (failure)") { expect.same(new Hello(25.0), new Hello(50.0)) } ``` -------------------------------- ### Compose expectations using xor Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/expectations.md Use the `xor` operator to create an expectation that is true if exactly one of the two composed expectations is true. This is useful for exclusive conditions. ```scala expect(1 > 0) xor expect(2 > 1) ``` -------------------------------- ### Displaying Source Location in Helper Functions Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md Use an implicit SourceLocation argument in helper functions to ensure assertions point to the correct call site when they fail. ```scala import weaver._ object SourceLocationSuite extends FunSuite { case class Response(body: String, status: Int) test("This test fails") { val response = Response("this went wrong", 500) expectOk(response) // The failure points here } test("This test fails with a different source location") { val response = Response("this also went wrong", 500) expectOk(response) // The other failure points here } def expectOk(response: Response)(implicit loc: SourceLocation): Expectations = { expect.eql(200, response.status) && expect.eql("OK", response.body) } } ``` -------------------------------- ### Diagnose Failing Tests with `clue` Source: https://github.com/typelevel/weaver-test/blob/main/docs/features/troubleshooting_failures.md This test demonstrates how `clue` helps diagnose failures by showing the values of variables involved in the assertion. A test without `clue` will fail without providing specific details. ```scala import weaver._ object ExpectWithClueTest extends FunSuite { test("This fails, and we can diagnose why") { val x = 1 val y = 2 expect(clue(x) > clue(y)) } test("This fails, but we don't know why") { val x = 1 val y = 2 expect(x > y) } test("This succeeds so nothing is printed") { val x = 1 val y = 0 expect(clue(x) > clue(y)) } } ```