### Install and Run GoConvey Source: https://github.com/smartystreets/goconvey/wiki/Home Commands to install the GoConvey package and start the web server for automatic test monitoring. ```shell go get github.com/smartystreets/goconvey go install github.com/smartystreets/goconvey $GOPATH/bin/goconvey ``` -------------------------------- ### Install and Run GoConvey Server Source: https://github.com/smartystreets/goconvey/wiki/Web-UI Instructions for installing the GoConvey binary and running the web server. Assumes GOPATH is set and GoConvey is already downloaded. ```shell go install github.com/smartystreets/goconvey $GOPATH/bin/goconvey ``` -------------------------------- ### Install GoConvey via Go Modules Source: https://context7.com/smartystreets/goconvey/llms.txt The standard command to install the GoConvey package into your Go project environment. ```bash go install github.com/smartystreets/goconvey ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/smartystreets/goconvey/blob/master/web/client/resources/fonts/FontAwesome/README.md Commands to install project dependencies and build the Font Awesome project locally. ```shell bundle install npm install bundle exec jekyll build bundle exec jekyll -w serve ``` -------------------------------- ### Start GoConvey Web UI Server Source: https://context7.com/smartystreets/goconvey/llms.txt Provides the command to start the GoConvey web server from the project directory. This server allows viewing test results in a browser with live updates. ```bash # Start the web server from your project directory cd /path/to/your/project $GOPATH/bin/goconvey ``` -------------------------------- ### Web UI Server Source: https://context7.com/smartystreets/goconvey/llms.txt Command to start the GoConvey web server for real-time test monitoring. ```APIDOC ## Web UI Server ### Description Run the GoConvey web server to view test results in your browser with automatic updates on file changes. ### Command ```bash $GOPATH/bin/goconvey ``` ``` -------------------------------- ### GoConvey Test Example Source: https://github.com/smartystreets/goconvey/blob/master/README.md Demonstrates how to write a basic test using GoConvey's `Convey` and `So` functions. This example shows nested test contexts and assertions. ```go package package_name import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestSpec(t *testing.T) { // Only pass t into top-level Convey calls Convey("Given some integer with a starting value", t, func() { x := 1 Convey("When the integer is incremented", func() { x++ Convey("The value should be greater by one", func() { So(x, ShouldEqual, 2) }) }) }) } ``` -------------------------------- ### Install Font Awesome via Component Source: https://github.com/smartystreets/goconvey/blob/master/web/client/resources/fonts/FontAwesome/README.md Commands and configuration to add Font Awesome as a dependency using the component package manager. ```shell component install FortAwesome/Font-Awesome ``` ```json "FortAwesome/Font-Awesome": "*" ``` -------------------------------- ### Write a GoConvey Test Source: https://github.com/smartystreets/goconvey/wiki/Home Example of a nested test structure using the Convey and So functions to verify logic in a Go test file. ```go package package_name import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Incr(i int) int { return i+1 } func TestIncr(t *testing.T) { Convey("Given some integer with a starting value", t, func() { x := 1 Convey("When the integer is incremented", func() { x = Incr(x) Convey("The value should be greater by one", func() { So(x, ShouldEqual, 2) }) }) }) } ``` -------------------------------- ### GoConvey String Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Provides examples of GoConvey assertions for string manipulation and validation. This includes checking prefixes, suffixes, substring containment, and whether a string is blank or not. ```go So("asdf", ShouldStartWith, "as") So("asdf", ShouldNotStartWith, "df") So("asdf", ShouldEndWith, "df") So("asdf", ShouldNotEndWith, "df") So("asdf", ShouldContainSubstring, "sd") So("asdf", ShouldNotContainSubstring, "er") So("adsf", ShouldBeBlank) So("asdf", ShouldNotBeBlank) ``` -------------------------------- ### Register GoConvey URL Handler on Linux Source: https://github.com/smartystreets/goconvey/wiki/Opening-files-in-your-editor-from-the-Web-UI This bash script installs a custom URL handler for the goconvey:// protocol on Ubuntu systems. It parses the incoming URL, extracts file paths and line numbers, and opens them in the configured editor (defaulting to VS Code). ```bash #!/usr/bin/env bash cat < /usr/bin/goconvey-handler #!/usr/bin/env bash request="${1#*://}" # Remove schema from url (goconvey://) request="${request#*?url=}" # Remove open?url= request="${request#*://}" # Remove file:// request="${request//%2F//}" # Replace %2F with / request="${request/&line=/:}" # Replace &line= with : request="${request/&column=/:}" # Replace &column= with : if [ -n "${GOCONVEY_EDITOR}" ]; then $GOCONVEY_EDITOR $GOCONVEY_EDITOR_FLAGS "$request" # Launch specified goconvey editor elif [ -n "${EDITOR}" ]; then $EDITOR $GOCONVEY_EDITOR_FLAGS "$request" # Launch default editor else code -g "$request" # Launch code as editor fi EOF-HANDLER cat < /usr/share/applications/goconvey-handler.desktop [Desktop Entry] Name=GoConvey URL Handler GenericName=Text Editor Comment=Handle URL Scheme goconvey:// Exec=/usr/bin/goconvey-handler %u Terminal=false Type=Application MimeType=x-scheme-handler/goconvey; Icon=code Categories=TextEditor;Development;Utility; Name[en_US]=GoConvey URL handler EOF-DESKTOP chmod +x /usr/bin/goconvey-handler update-desktop-database xdg-mime default /usr/share/applications/goconvey-handler.desktop x-scheme-handler/goconvey ``` -------------------------------- ### Example Custom Assertion and Usage in GoConvey Source: https://github.com/smartystreets/goconvey/wiki/Custom-Assertions This Go code demonstrates a specific custom assertion function, `shouldScareGophersMoreThan`, which checks if a string is 'BOO!' and the expected value is 'boo'. It then shows how to use this custom assertion within a GoConvey test using the `So()` method. ```go func shouldScareGophersMoreThan(actual interface{}, expected ...interface{}) string { if actual == "BOO!" && expected[0] == "boo" { return "" } return "Ha! You'll have to get a lot friendlier with the capslock if you want to scare a gopher!" } Convey("All caps always makes text more meaningful", func() { So("BOO!", shouldScareGophersMoreThan, "boo") }) ``` -------------------------------- ### Define Test Scopes with Convey Source: https://context7.com/smartystreets/goconvey/llms.txt Demonstrates the hierarchical structure of GoConvey tests using nested Convey blocks. The top-level block requires a *testing.T object, while nested blocks inherit setup and run in isolation. ```go package mypackage import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestUserRegistration(t *testing.T) { Convey("Given a user registration service", t, func() { service := NewRegistrationService() Convey("When registering a new user with valid data", func() { user, err := service.Register("john@example.com", "securepass123") Convey("The user should be created successfully", func() { So(err, ShouldBeNil) So(user, ShouldNotBeNil) So(user.Email, ShouldEqual, "john@example.com") }) Convey("The user should have a generated ID", func() { So(user.ID, ShouldNotBeEmpty) }) }) Convey("When registering with an invalid email", func() { user, err := service.Register("invalid-email", "password") Convey("An error should be returned", func() { So(err, ShouldNotBeNil) So(user, ShouldBeNil) }) }) }) } ``` -------------------------------- ### Execute GoConvey Tests via CLI Source: https://context7.com/smartystreets/goconvey/llms.txt Standard commands for running Go tests, including verbose output, specific test filtering, and coverage report generation. ```bash go test go test -v go test -run TestUserRegistration go test -cover go test -coverprofile=coverage.out go tool cover -html=coverage.out ``` -------------------------------- ### Initialize GoConvey Test Imports Source: https://github.com/smartystreets/goconvey/wiki/Composition Shows the required imports for a Go test file using GoConvey. The dot-notation import is recommended for convenient access to the Convey and So functions. ```go import( "testing" . "github.com/smartystreets/goconvey/convey" ) ``` -------------------------------- ### Use SoMsg for Custom Assertion Messages Source: https://context7.com/smartystreets/goconvey/llms.txt Demonstrates how to provide custom failure messages using SoMsg to improve debugging context when assertions fail. ```go func TestWithCustomMessages(t *testing.T) { Convey("Testing with custom error messages", t, func() { userAge := 17 minAge := 18 SoMsg("User must be at least 18 years old to register", userAge, ShouldBeGreaterThanOrEqualTo, minAge) balance := 50.00 requiredAmount := 100.00 SoMsg("Insufficient funds for transaction", balance, ShouldBeGreaterThanOrEqualTo, requiredAmount) }) } ``` -------------------------------- ### GoConvey Server Command Line Flags Source: https://github.com/smartystreets/goconvey/wiki/Web-UI Displays the available command-line flags for configuring the GoConvey server, including options for coverage, host, port, and parallel testing. ```shell $GOPATH/bin/goconvey -help Usage of goconvey: -cover=true: Enable package-level coverage statistics. Warning: this will obfuscate line number reporting on panics and build failures! Requires Go 1.2+ and the go cover tool. (default: true) -gobin="go": The path to the 'go' binary (default: search on the PATH). -host="127.0.0.1": The host at which to serve http. -packages=10: The number of packages to test in parallel. Higher == faster but more costly in terms of computing. (default: 10) -poll=250ms: The interval to wait between polling the file system for changes (default: 250ms). -port=8080: The port at which to serve http. ``` -------------------------------- ### Define a Basic GoConvey Test Function Source: https://github.com/smartystreets/goconvey/wiki/Composition Demonstrates the standard structure of a Go test function compatible with GoConvey. This function acts as the entry point for test execution. ```go func TestSomething(t *testing.T) { } ``` -------------------------------- ### Configure GoConvey CLI Options Source: https://context7.com/smartystreets/goconvey/llms.txt Common command-line flags for customizing the GoConvey server, including port, host, polling intervals, and parallel package execution settings. ```bash goconvey -help goconvey -port=9090 -host=0.0.0.0 goconvey -cover=false goconvey -poll=500ms goconvey -packages=20 goconvey -gobin=/usr/local/go/bin/go ``` -------------------------------- ### Go: Manage Database Transactions in Tests Source: https://github.com/smartystreets/goconvey/wiki/Decorating-tests-to-provide-common-logic This Go function, `WithTransaction`, simplifies managing database transactions within tests. It sets up a transaction, provides a `Reset` function to rollback the transaction after the test, and executes a provided closure with the active transaction. It relies on the `database/sql` package and the GoConvey testing framework. ```go package main import ( "database/sql" "testing" _ "github.com/lib/pq" . "github.com/smartystreets/goconvey/convey" ) func WithTransaction(db *sql.DB, f func(tx *sql.Tx)) func() { return func() { tx, err := db.Begin() So(err, ShouldBeNil) Reset(func() { /* Verify that the transaction is alive by executing a command */ _, err := tx.Exec("SELECT 1") So(err, ShouldBeNil) tx.Rollback() }) /* Here we invoke the actual test-closure and provide the transaction */ f(tx) } } func TestUsers(t *testing.T) { db, err := sql.Open("postgres", "postgres://localhost?sslmode=disable") if err != nil { panic(err) } Convey("Given a user in the database", t, WithTransaction(db, func(tx *sql.Tx) { _, err := tx.Exec(`INSERT INTO "Users" ("id", "name") VALUES (1, 'Test User')`) So(err, ShouldBeNil) Convey("Attempting to retrieve the user should return the user", func() { var name string data := tx.QueryRow(`SELECT "name" FROM "Users" WHERE "id" = 1`) err = data.Scan(&name) So(err, ShouldBeNil) So(name, ShouldEqual, "Test User") }) })) } /* Required table to run the test: CREATE TABLE "public"."Users" ( "id" INTEGER NOT NULL UNIQUE, "name" CHARACTER VARYING( 2044 ) NOT NULL ); */ ``` -------------------------------- ### Perform Assertions with Convey and So Source: https://github.com/smartystreets/goconvey/wiki/Composition Illustrates how to define a test scope using Convey and perform an assertion using So. The top-level Convey call requires the *testing.T object. ```go Convey("1 should equal 1", t, func() { So(1, ShouldEqual, 1) }) ``` -------------------------------- ### GoConvey Context for Goroutines Source: https://context7.com/smartystreets/goconvey/llms.txt Shows how to obtain and use the GoConvey context (C interface) explicitly, which is crucial for passing test assertions into goroutines or closures in concurrent test scenarios. ```go func TestWithContext(t *testing.T) { Convey("Testing concurrent operations", t, func(c C) { done := make(chan bool) result := make(chan int) go func() { // Use context 'c' instead of global functions time.Sleep(10 * time.Millisecond) result <- 42 done <- true }() go func() { value := <-result // Assertions in goroutines MUST use context c.So(value, ShouldEqual, 42) <-done }() <-done }) } ``` -------------------------------- ### Skip a Test Scope Source: https://github.com/smartystreets/goconvey/wiki/Composition Demonstrates how to mark a test scope as skipped by passing nil as the function argument to Convey. ```go Convey("This isn't yet implemented", nil) ``` -------------------------------- ### Go Debug Printing with GoConvey Source: https://context7.com/smartystreets/goconvey/llms.txt Demonstrates the use of `Print`, `Println`, and `Printf` functions within GoConvey tests to output debug information directly in the web UI, alongside assertion results. ```go func TestWithPrinting(t *testing.T) { Convey("Debugging with print statements", t, func() { data := fetchTestData() Println("Fetched data:", data) Printf("Data length: %d\n", len(data)) So(len(data), ShouldBeGreaterThan, 0) for i, item := range data { Printf("Processing item %d: %v\n", i, item) So(item, ShouldNotBeNil) } }) } ``` -------------------------------- ### GoConvey General Equality Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Demonstrates GoConvey's standard assertions for checking general equality between values, including deep equality, pointer comparison, nil checks, and boolean states. These are fundamental for verifying expected outcomes in tests. ```go So(thing1, ShouldEqual, thing2) So(thing1, ShouldNotEqual, thing2) So(thing1, ShouldResemble, thing2) So(thing1, ShouldNotResemble, thing2) So(thing1, ShouldPointTo, thing2) So(thing1, ShouldNotPointTo, thing2) So(thing1, ShouldBeNil) So(thing1, ShouldNotBeNil) So(thing1, ShouldBeTrue) So(thing1, ShouldBeFalse) So(thing1, ShouldBeZeroValue) ``` -------------------------------- ### GoConvey Numeric Quantity Comparison Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Illustrates GoConvey assertions for comparing numeric values. This includes greater than, less than, between, and approximate equality checks, with optional tolerance for floating-point comparisons. ```go So(1, ShouldBeGreaterThan, 0) So(1, ShouldBeGreaterThanOrEqualTo, 0) So(1, ShouldBeLessThan, 2) So(1, ShouldBeLessThanOrEqualTo, 2) So(1.1, ShouldBeBetween, .8, 1.2) So(1.1, ShouldNotBeBetween, 2, 3) So(1.1, ShouldBeBetweenOrEqual, .9, 1.1) So(1.1, ShouldNotBeBetweenOrEqual, 1000, 2000) So(1.0, ShouldAlmostEqual, 0.99999999, .0001) So(1.0, ShouldNotAlmostEqual, 0.9, .0001) ``` -------------------------------- ### Go Custom Assertions with GoConvey Source: https://context7.com/smartystreets/goconvey/llms.txt Explains how to create custom assertion functions in Go using GoConvey. These functions accept an 'actual' value and optional 'expected' values, returning an empty string on success or an error message on failure. ```go // Custom assertion function signature func shouldBeValidEmail(actual interface{}, expected ...interface{}) string { email, ok := actual.(string) if !ok { return "Expected a string email address" } if !strings.Contains(email, "@") || !strings.Contains(email, ".") { return fmt.Sprintf("'%s' is not a valid email address", email) } return "" // empty string means success } func shouldHaveStatusCode(actual interface{}, expected ...interface{}) string { response, ok := actual.(*http.Response) if !ok { return "Expected an *http.Response" } expectedCode, ok := expected[0].(int) if !ok { return "Expected status code should be an int" } if response.StatusCode != expectedCode { return fmt.Sprintf("Expected status %d but got %d", expectedCode, response.StatusCode) } return "" } func TestCustomAssertions(t *testing.T) { Convey("Using custom assertions", t, func() { So("user@example.com", shouldBeValidEmail) So("invalid-email", shouldBeValidEmail) // fails with custom message resp := &http.Response{StatusCode: 200} So(resp, shouldHaveStatusCode, 200) }) } ``` -------------------------------- ### GoConvey time.Time and time.Duration Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Showcases GoConvey assertions for comparing time.Time values and durations. This includes checks for happening before, after, between, and within a specified duration. ```go So(time.Now(), ShouldHappenBefore, time.Now()) So(time.Now(), ShouldHappenOnOrBefore, time.Now()) So(time.Now(), ShouldHappenAfter, time.Now()) So(time.Now(), ShouldHappenOnOrAfter, time.Now()) So(time.Now(), ShouldHappenBetween, time.Now(), time.Now()) So(time.Now(), ShouldHappenOnOrBetween, time.Now(), time.Now()) So(time.Now(), ShouldNotHappenOnOrBetween, time.Now(), time.Now()) So(time.Now(), ShouldHappenWithin, duration, time.Now()) So(time.Now(), ShouldNotHappenWithin, duration, time.Now()) ``` -------------------------------- ### Implement Custom Assertion Function in Go Source: https://github.com/smartystreets/goconvey/wiki/Custom-Assertions This Go function signature defines a custom assertion. It takes an actual value and optional expected values, returning an empty string if the assertion passes or a descriptive error message if it fails. This pattern allows for highly specific test conditions. ```go func should(actual interface{}, expected ...interface{}) string { if { return "" // empty string means the assertion passed } return "" } ``` -------------------------------- ### Perform Assertions with So Source: https://context7.com/smartystreets/goconvey/llms.txt Showcases various assertion types available in GoConvey, including equality, nil checks, numeric comparisons, collection validation, and string manipulation checks. ```go func TestAssertions(t *testing.T) { Convey("Demonstrating assertion types", t, func() { So(42, ShouldEqual, 42) So("hello", ShouldNotEqual, "world") So(1.0, ShouldAlmostEqual, 0.99999999, 0.0001) type Person struct { Name string; Age int } So(Person{"Alice", 30}, ShouldResemble, Person{"Alice", 30}) var ptr *string So(ptr, ShouldBeNil) So(true, ShouldBeTrue) So(false, ShouldBeFalse) So(0, ShouldBeZeroValue) So(10, ShouldBeGreaterThan, 5) So(10, ShouldBeLessThanOrEqualTo, 10) So(5, ShouldBeBetween, 1, 10) So([]int{1, 2, 3}, ShouldContain, 2) So([]int{1, 2, 3}, ShouldHaveLength, 3) So([]int{}, ShouldBeEmpty) So(map[string]int{"a": 1}, ShouldContainKey, "a") So(2, ShouldBeIn, []int{1, 2, 3}) So("GoConvey", ShouldStartWith, "Go") So("GoConvey", ShouldEndWith, "vey") So("GoConvey", ShouldContainSubstring, "Conv") So("", ShouldBeBlank) So("text", ShouldNotBeBlank) So(42, ShouldHaveSameTypeAs, 0) }) } ``` -------------------------------- ### Variable Scoping in GoConvey Source: https://github.com/smartystreets/goconvey/wiki/Execution-order Demonstrates the difference between creating a new variable with short declaration (:=) and assigning to an existing variable (=) within nested Convey scopes. ```Go Convey("Setup", func() { foo := &Bar{} Convey("This creates a new variable foo in this scope", func() { foo := &Bar{} }) Convey("This assigns a new value to the previous declared foo", func() { foo = &Bar{} }) }) ``` -------------------------------- ### GoConvey Type Checking Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Illustrates GoConvey assertions for verifying the types of variables. This allows for checks to ensure that a variable has the same type as another or a different type. ```go So(1, ShouldHaveSameTypeAs, 0) So(1, ShouldNotHaveSameTypeAs, "asdf") ``` -------------------------------- ### Manage Console Statistics in Go Tests Source: https://context7.com/smartystreets/goconvey/llms.txt Programmatically control the output of test statistics using the convey package. This is useful for custom TestMain implementations where you want to suppress automatic output and print it manually. ```go func TestMain(m *testing.M) { convey.SuppressConsoleStatistics() result := m.Run() convey.PrintConsoleStatistics() os.Exit(result) } ``` -------------------------------- ### GoConvey Panic Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Demonstrates GoConvey assertions for testing functions that are expected to panic or not panic. It also includes checks for panics with specific error messages or types. ```go So(func(), ShouldPanic) So(func(), ShouldNotPanic) So(func(), ShouldPanicWith, "") So(func(), ShouldNotPanicWith, "") ``` -------------------------------- ### Nest Test Scopes in GoConvey Source: https://github.com/smartystreets/goconvey/wiki/Composition Shows how to nest multiple Convey blocks to organize test cases. Nested calls omit the *testing.T object parameter. ```go Convey("Comparing two variables", t, func() { myVar := "Hello, world!" Convey(`"Asdf" should NOT equal "qwerty"`, func() { So("Asdf", ShouldNotEqual, "qwerty") }) Convey("myVar should not be nil", func() { So(myVar, ShouldNotBeNil) }) }) ``` -------------------------------- ### GoConvey Reset for Test Teardown Source: https://github.com/smartystreets/goconvey/wiki/Reset Demonstrates the use of the Reset() function in GoConvey to execute teardown logic after each test within a given scope. This is useful for cleaning up resources like database connections that were set up before the tests. ```go Convey("Top-level", t, func() { // setup (run before each `Convey` at this scope): db.Open() db.Initialize() Convey("Test a query", t, func() { db.Query() // TODO: assertions here }) Convey("Test inserts", t, func() { db.Insert() // TODO: assertions here }) Reset(func() { // This reset is run after each `Convey` at the same scope. db.Close() }) }) ``` -------------------------------- ### Configure Failure Mode in GoConvey Source: https://github.com/smartystreets/goconvey/wiki/FAQ Demonstrates how to override the default test behavior to allow execution to continue after a failure. This can be applied to specific Convey blocks or set globally using an init function. ```go Convey("A", t, FailureContinues, func() { // ... }); func init() { SetDefaultFailureMode(FailureContinues); } ``` -------------------------------- ### GoConvey SkipConvey and SkipSo - Skip Tests Source: https://context7.com/smartystreets/goconvey/llms.txt SkipConvey() skips an entire test scope and its children, while SkipSo() skips individual assertions. Both are marked as skipped in test output, allowing for tests that are not yet implemented or are temporarily disabled. ```go func TestWithSkipping(t *testing.T) { Convey("Feature tests", t, func() { Convey("Implemented feature", func() { So(1+1, ShouldEqual, 2) }) // Skip entire scope - not yet implemented SkipConvey("Pending feature", func() { So(AdvancedCalculation(), ShouldEqual, 42) }) Convey("Partially implemented feature", func() { So(BasicOperation(), ShouldEqual, 10) // Skip specific assertion SkipSo(UnfinishedOperation(), ShouldEqual, 20) }) // Using nil also marks as unimplemented Convey("Future feature placeholder", nil) }) } ``` -------------------------------- ### Time Assertions Source: https://context7.com/smartystreets/goconvey/llms.txt Provides specialized assertions for time.Time comparisons including chronological ordering and duration-based proximity. ```APIDOC ## Time Assertions ### Description Provides specialized assertions for time.Time comparisons including chronological ordering and duration-based proximity checks. ### Assertions - **ShouldHappenBefore**: Asserts that the actual time is before the expected time. - **ShouldHappenAfter**: Asserts that the actual time is after the expected time. - **ShouldHappenBetween**: Asserts that the actual time is between two provided times. - **ShouldHappenWithin**: Asserts that the actual time is within a specific duration of the expected time. ### Usage Example ```go So(yesterday, ShouldHappenBefore, now) So(almostNow, ShouldHappenWithin, oneHour, now) ``` ``` -------------------------------- ### Focusing on Specific Convey Registrations Source: https://github.com/smartystreets/goconvey/wiki/Skip Use FocusConvey to isolate and run only specific test branches. All parent Convey registrations and the target leaf registration must be marked with FocusConvey to execute correctly. ```go FocusConvey("A", func() { Convey("B", nil) FocusConvey("C", func() { FocusConvey("D", func() { }) }) }) ``` -------------------------------- ### GoConvey Collections Assertions Source: https://github.com/smartystreets/goconvey/wiki/Assertions Showcases GoConvey assertions for working with collections like slices, maps, and arrays. It covers checking for containment of elements, presence of keys, emptiness, and length. ```go So([]int{2, 4, 6}, ShouldContain, 4) So([]int{2, 4, 6}, ShouldNotContain, 5) So(4, ShouldBeIn, ...[]int{2, 4, 6}) So(4, ShouldNotBeIn, ...[]int{1, 3, 5}) So([]int{}, ShouldBeEmpty) So([]int{1}, ShouldNotBeEmpty) So(map[string]string{"a": "b"}, ShouldContainKey, "a") So(map[string]string{"a": "b"}, ShouldNotContainKey, "b") So(map[string]string{"a": "b"}, ShouldNotBeEmpty) So(map[string]string{}, ShouldBeEmpty) So(map[string]string{"a": "b"}, ShouldHaveLength, 1) ``` -------------------------------- ### Panic Assertions Source: https://context7.com/smartystreets/goconvey/llms.txt Assertions to verify that functions panic or do not panic, optionally checking for specific error messages. ```APIDOC ## Panic Assertions ### Description Test that functions panic (or don't panic) with specific values using panic-related assertions. ### Assertions - **ShouldPanic**: Asserts that the function panics. - **ShouldPanicWith**: Asserts that the function panics with a specific value. - **ShouldNotPanic**: Asserts that the function does not panic. ### Usage Example ```go So(riskyFunc, ShouldPanicWith, "something went wrong") So(safeFunc, ShouldNotPanic) ``` ``` -------------------------------- ### Convey Context (C Interface) Source: https://context7.com/smartystreets/goconvey/llms.txt Obtain the Convey context explicitly for use in goroutines or concurrent closures. ```APIDOC ## Convey Context (C Interface) ### Description Obtain the Convey context explicitly when you need to pass it to goroutines or closures. This is essential for concurrent test code. ### Parameters - **c (C)**: The context object passed into the Convey block. ### Usage Example ```go Convey("Testing concurrent operations", t, func(c C) { go func() { c.So(value, ShouldEqual, 42) }() }) ``` ``` -------------------------------- ### FailureMode - Controlling Test Execution Flow Source: https://context7.com/smartystreets/goconvey/llms.txt Constants and functions to define whether a test suite should halt immediately upon failure or continue executing subsequent assertions. ```APIDOC ## FailureMode Constants ### Description - **FailureHalts**: Stops execution of the current scope immediately upon an assertion failure. - **FailureContinues**: Continues executing subsequent assertions even after a failure. ## SetDefaultFailureMode(FailureMode) ### Description Sets the global default failure behavior for the entire package. ### Request Example ```go Convey("With FailureContinues", t, FailureContinues, func() { So(1, ShouldEqual, 2) // Fails So(1, ShouldEqual, 1) // Still executes }) ``` ``` -------------------------------- ### Skipping Individual So Assertions Source: https://github.com/smartystreets/goconvey/wiki/Skip Use SkipSo to prevent a single assertion from executing. The test report will reflect that the specific assertion was skipped. ```go Convey("1 Should Equal 2", func() { SkipSo(1, ShouldEqual, 2) }) ``` -------------------------------- ### Reset - Cleanup After Each Test Source: https://context7.com/smartystreets/goconvey/llms.txt The Reset function registers cleanup code to run after each nested Convey block in the same scope, ensuring proper teardown of resources. ```APIDOC ## Reset(func()) ### Description Registers a function to be executed after each nested Convey block within the current scope. This is typically used for database rollbacks, closing connections, or resetting state. ### Method N/A (Go Function) ### Parameters - **cleanup** (func()) - Required - The function containing the teardown logic. ### Request Example ```go Reset(func() { db.RollbackTransaction() db.Close() }) ``` ``` -------------------------------- ### GoConvey Reset - Cleanup After Each Test Source: https://context7.com/smartystreets/goconvey/llms.txt The Reset() function registers cleanup code to run after each nested Convey() block. This is useful for ensuring resources like database connections are properly closed or rolled back after tests. ```go func TestDatabaseOperations(t *testing.T) { Convey("Given an open database connection", t, func() { db := OpenTestDatabase() db.BeginTransaction() Convey("When inserting a new record", func() { err := db.Insert("users", map[string]interface{}{ "name": "Alice", "email": "alice@example.com", }) Convey("The insert should succeed", func() { So(err, ShouldBeNil) }) }) Convey("When querying existing records", func() { results, err := db.Query("SELECT * FROM users") Convey("Results should be returned", func() { So(err, ShouldBeNil) So(results, ShouldNotBeEmpty) }) }) Reset(func() { // Runs after each nested Convey block db.RollbackTransaction() db.Close() }) }) } ``` -------------------------------- ### Skipping Convey Registrations Source: https://github.com/smartystreets/goconvey/wiki/Skip Use SkipConvey to prevent a specific test scope and all its nested registrations from executing. This is a cleaner alternative to commenting out code as it avoids unused variable or import errors. ```go SkipConvey("Important stuff", func() { Convey("More important stuff", func() { So("asdf", ShouldEqual, "asdf") }) }) ``` -------------------------------- ### Marking Unimplemented Convey Registrations Source: https://github.com/smartystreets/goconvey/wiki/Skip Passing nil instead of a function to a Convey registration marks the scope as skipped in the test report, indicating incomplete test coverage. ```go Convey("Some stuff", func() { Convey("Should go boink", nil) }) ``` -------------------------------- ### GoConvey FocusConvey - Run Only Specific Tests Source: https://context7.com/smartystreets/goconvey/llms.txt FocusConvey() runs only the focused test scopes and their children, ignoring all other tests. This is useful for debugging specific failing tests without running the entire test suite. ```go func TestWithFocus(t *testing.T) { FocusConvey("Only this top-level scope runs", t, func() { // This will NOT run because it's not focused Convey("Skipped test", func() { So(1, ShouldEqual, 1) }) // This WILL run because the chain is focused FocusConvey("This nested scope runs", func() { FocusConvey("This leaf test executes", func() { So(2+2, ShouldEqual, 4) }) }) }) } ``` -------------------------------- ### SkipConvey and SkipSo - Skipping Tests Source: https://context7.com/smartystreets/goconvey/llms.txt Functions to bypass specific test scopes or individual assertions, marking them as skipped in the test output. ```APIDOC ## SkipConvey(string, func()) ### Description Skips an entire test scope and all its nested children. ## SkipSo(interface{}, ...interface{}) ### Description Skips a specific assertion within a test scope. ### Request Example ```go SkipConvey("Pending feature", func() { So(AdvancedCalculation(), ShouldEqual, 42) }) SkipSo(UnfinishedOperation(), ShouldEqual, 20) ``` ``` -------------------------------- ### GoConvey FailureMode - Control Test Behavior on Failure Source: https://context7.com/smartystreets/goconvey/llms.txt FailureMode constants control whether tests halt or continue after assertion failures. The default FailureHalts stops execution, while FailureContinues runs all assertions, even after failures. ```go func TestFailureModes(t *testing.T) { // Default behavior: halt on first failure Convey("With FailureHalts (default)", t, FailureHalts, func() { So(1, ShouldEqual, 1) // passes So(1, ShouldEqual, 2) // fails - execution stops here So(1, ShouldEqual, 1) // never runs }) // Continue running after failures Convey("With FailureContinues", t, FailureContinues, func() { So(1, ShouldEqual, 1) // passes So(1, ShouldEqual, 2) // fails - but continues So(1, ShouldEqual, 1) // still runs }) // Nested scopes inherit failure mode Convey("Parent scope", t, FailureContinues, func() { Convey("Child inherits FailureContinues", func() { So(false, ShouldBeTrue) // fails So(true, ShouldBeTrue) // still runs }) // Override in nested scope Convey("Child with override", FailureHalts, func() { So(false, ShouldBeTrue) // fails - stops So(true, ShouldBeTrue) // won't run }) }) } // Set default for entire package func init() { SetDefaultFailureMode(FailureContinues) } ``` -------------------------------- ### FocusConvey - Focused Test Execution Source: https://context7.com/smartystreets/goconvey/llms.txt FocusConvey allows running only specific test scopes, ignoring others to facilitate faster debugging of failing tests. ```APIDOC ## FocusConvey(string, ...interface{}) ### Description Executes only the focused test scope and its children. All other non-focused tests in the suite are ignored. ### Request Example ```go FocusConvey("Only this scope runs", t, func() { FocusConvey("This nested scope also runs", func() { So(2+2, ShouldEqual, 4) }) }) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.