### Full SQL Server Example with Permission Note Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md A complete example for SQL Server fixtures, emphasizing the requirement for the user to have ALTER TABLE permissions. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("sqlserver"), testfixtures.Directory("fixtures"), // Ensure user has ALTER TABLE permission ) ``` -------------------------------- ### Spanner: Complete Example Configuration Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md An example demonstrating a full Spanner configuration using `FilesMultiTables` and skipping the database check, with a corresponding YAML structure. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("spanner"), testfixtures.FilesMultiTables("fixtures/complete_scenario.yml"), ttestfixtures.DangerousSkipTestDatabaseCheck(), ) // In complete_scenario.yml: // users: // - id: 1 // name: John Doe // // profiles: # Interleaved child of users // - user_id: 1 // bio: Software engineer ``` -------------------------------- ### PostgreSQL Example Configuration Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md An example of configuring testfixtures for PostgreSQL with specific options for foreign key handling, sequence reset, and dialect. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("fixtures"), testfixtures.UseAlterConstraint(), testfixtures.ResetSequencesTo(10000), ) ``` -------------------------------- ### Full PostgreSQL Configuration Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md A comprehensive example showing multiple PostgreSQL-specific configuration options applied together, including foreign key handling, sequence reset, and checksum computation. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("fixtures"), ttestfixtures.UseAlterConstraint(), // No SUPERUSER required ttestfixtures.ResetSequencesTo(5000), // Custom sequence start ttestfixtures.SkipTableChecksumComputation(), ) ``` -------------------------------- ### SQLite Database Connection Examples Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Examples of opening SQLite database connections, including safe and in-memory options. ```go // Valid test databases: db, _ := sql.Open("sqlite3", "file:myapp_test.db") db, _ := sql.Open("sqlite3", ":memory:") // No safety check needed db, _ := sql.Open("sqlite3", "/tmp/test.db") // Invalid (will fail safety check): db, _ := sql.Open("sqlite3", "myapp.db") // "myapp" doesn't contain "test" ``` -------------------------------- ### Full MySQL/MariaDB Example with Customizations Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md A comprehensive example for MySQL/MariaDB fixtures, including custom auto-increment reset and enabling multiple statements per query. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("mysql"), testfixtures.Directory("fixtures"), testfixtures.ResetSequencesTo(1000), ttestfixtures.AllowMultipleStatementsInOneQuery(), // Requires multistatements=true ) ``` -------------------------------- ### Full ClickHouse Example with DELETE FROM Option Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md A complete example for ClickHouse fixtures, explicitly enabling the use of DELETE FROM for cleanup if TRUNCATE is not suitable. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("clickhouse"), testfixtures.Directory("fixtures"), ttestfixtures.ClickhouseUseDeleteFrom(), // If needed ) ``` -------------------------------- ### MySQL Example Configuration with Multistatement Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md An example of configuring testfixtures for MySQL, enabling the multistatement optimization and setting a custom auto-increment reset value. ```go // MySQL with multistatement optimization fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("mysql"), testfixtures.Directory("fixtures"), testfixtures.AllowMultipleStatementsInOneQuery(), testfixtures.ResetSequencesTo(1000), ) ``` -------------------------------- ### Full Google Cloud Spanner Example with File Loading Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md A complete example for Spanner fixtures, demonstrating the use of `Files()` for loading multiple tables in the correct order and skipping the database check. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("spanner"), testfixtures.Files( "fixtures/users.yml", // Parent table first "fixtures/posts.yml", // Child table second "fixtures/comments.yml", // Grandchild table third ), ttestfixtures.DangerousSkipTestDatabaseCheck(), ) ``` -------------------------------- ### YAML Fixture File Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/00-START-HERE.md An example of a YAML fixture file for defining user data. ```yaml # testdata/fixtures/users.yml - id: 1 name: John Doe email: john@example.com created_at: 2025-08-15 ``` -------------------------------- ### Fixture Output Directory Creation Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example demonstrating how to ensure the fixture output directory exists and is writable before creating a Dumper. ```go // Ensure directory exists and is writable os.MkdirAll("testdata/fixtures", 0755) dumper, _ := testfixtures.NewDumper( ttestfixtures.DumpDatabase(db), ttestfixtures.DumpDialect("postgres"), ttestfixtures.DumpDirectory("testdata/fixtures"), ) ``` -------------------------------- ### YAML Fixture Output Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/dumper-api.md This is an example of the YAML format generated by the Dumper for user data. ```yaml # users.yml - id: 1 email: user@example.com name: John Doe created_at: 2023-01-15 10:30:45 - id: 2 email: another@example.com name: Jane Smith created_at: 2023-01-16 14:22:30 ``` -------------------------------- ### Multi-Step Test Setup with Additional Data Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md Demonstrates loading base fixtures and then inserting additional data directly into the database before running the test. ```go func TestUserWithPosts(t *testing.T) { // Load base fixtures if err := fixtures.Load(); err != nil { t.Fatal(err) } // Add additional test data _, err := db.Exec( "INSERT INTO users (id, name, email) VALUES ($1, $2, $3)", 999, "Test User", "test@example.com" ) if err != nil { t.Fatal(err) } // Run test with combined data user, err := GetUser(999) if err != nil { t.Fatal(err) } if user.Name != "Test User" { t.Errorf("Expected 'Test User', got '%s'", user.Name) } } ``` -------------------------------- ### Database Connection Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Go code demonstrating how to open and ping a PostgreSQL database connection, essential for avoiding connection errors. ```go // Ensure database is running and connection string is correct db, err := sql.Open("postgres", "postgres://user:pass@localhost:5432/myapp_test") if err != nil { log.Fatal(err) } // Test connection if err := db.Ping(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Install Testfixtures CLI with Homebrew Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Install the testfixtures command-line tool using Homebrew for loading and dumping fixtures. ```bash brew install go-testfixtures/tap/testfixtures ``` -------------------------------- ### Basic YAML Fixture Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/README.md Example of a YAML file defining user data for fixtures. The filename (without extension) maps to a table name. ```yaml # testdata/fixtures/users.yml - id: 1 name: John Doe email: john@example.com created_at: 2025-08-15 - id: 2 name: Jane Smith email: jane@example.com created_at: 2025-08-16 ``` -------------------------------- ### Testfixtures Initialization with Dialect Options Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/types.md Example demonstrating how to initialize testfixtures with custom dialect options, such as setting a specific placeholder type for the database. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres", testfixtures.WithCustomPlaceholder(testfixtures.ParamTypeQuestion), ), testfixtures.Directory("fixtures"), ) ``` -------------------------------- ### SQLite Example Configuration with Skipped Checksum Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Configure test fixtures for SQLite, skipping table checksum computation. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("sqlite"), testfixtures.Directory("fixtures"), testfixtures.SkipTableChecksumComputation(), ) ``` -------------------------------- ### Basic Template Setup with Data and Functions Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Configure testfixtures with template processing enabled, providing custom data and functions for dynamic fixture generation. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("fixtures"), testfixtures.Template(), // Enable template processing testfixtures.TemplateData(map[string]any{ "Count": 10, "AppID": 123, "Names": []string{"Alice", "Bob", "Charlie"}, }), testfixtures.TemplateFuncs(template.FuncMap{ "multiply": func(a, b int) int { return a * b }, }), ) ``` -------------------------------- ### Fixture Solution: NOT NULL Constraint Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML demonstrating how to provide all required fields to satisfy NOT NULL constraints. ```yaml # Provide all required fields - id: 1 email: user@example.com # Required field name: John Doe ``` -------------------------------- ### Basic TestMain Setup with Testfixtures Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/README.md Initializes the testfixtures Loader in TestMain for database testing. Ensure the database connection and dialect are correctly configured. ```go package myapp import ( "database/sql" "os" testing" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) var fixtures *testfixtures.Loader func TestMain(m *testing.M) { db, _ := sql.Open("postgres", "dbname=myapp_test") fixtures, _ = testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("testdata/fixtures"), ) os.Exit(m.Run()) } func TestGetUser(t *testing.T) { fixtures.Load() // Clean and load fixtures // Your test code here } ``` -------------------------------- ### Cloud-Native Testing with Spanner Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Example configuration for using Spanner in a cloud-native context, specifying files and skipping the database check. ```go db, _ := sql.Open("spanner", "projects/PROJECT_ID/instances/INSTANCE_ID/databases/myapp_test") fixtures, _ := testfixtures.New( ttestfixtures.Database(db), ttestfixtures.Dialect("spanner"), ttestfixtures.Files("fixtures/users.yml", "fixtures/posts.yml"), ttestfixtures.DangerousSkipTestDatabaseCheck(), ) ``` -------------------------------- ### YAML Fixture Example with Table Mapping Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/README.md Demonstrates how a YAML file named 'posts.yml' is automatically mapped to the 'posts' table for fixture loading. ```yaml # posts.yml → loads into 'posts' table - id: 1 title: First Post author_id: 1 ``` -------------------------------- ### Complex Fixture Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md A comprehensive example demonstrating nested structures, various data types, and the use of `RAW=` for dynamic values within a single fixture record. ```yaml - id: 1 username: john_doe email: john@example.com password_hash: 0x24326124313024486c6c4f # Hex-encoded hash profile: full_name: John Michael Doe avatar_url: https://example.com/john.jpg bio: Software engineer and Go enthusiast social: twitter: "@johndoe" github: "johndoe" preferences: theme: dark language: en notifications: true created_at: 2025-01-15 updated_at: RAW=NOW() last_login: 2025-08-15 14:30:45 metadata: roles: - admin - moderator permissions: - read - write - delete api_keys: - key: secret_key_1 created: 2025-01-15 - key: secret_key_2 created: 2025-02-20 active: true verified: true - id: 2 username: jane_smith email: jane@example.com password_hash: 0xabcdef0123456789 profile: full_name: Jane Elizabeth Smith avatar_url: https://example.com/jane.jpg bio: null # Or omit the line social: {} # Empty object preferences: theme: light language: fr notifications: false created_at: 2025-02-01 updated_at: 2025-08-16 10:15:30 last_login: null metadata: null active: true verified: false ``` -------------------------------- ### Full SQLite Example with Performance Optimization Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Initializes SQLite test fixtures and includes an optimization to skip table checksum computation, suitable for test-only data loads. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("sqlite"), testfixtures.Directory("fixtures"), ttestfixtures.SkipTableChecksumComputation(), // Small optimization for test-only loads ) ``` -------------------------------- ### Configure MySQL Performance: Multiple Statements Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Enables grouping multiple setup statements into a single query for performance. Requires the connection string to include '?multistatements=true'. ```go // Group multiple setup statements into one query // Connection string must have: ?multistatements=true testfixtures.AllowMultipleStatementsInOneQuery() ``` -------------------------------- ### Use Custom Parameter Style Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/types.md Example of using the WithCustomPlaceholder option to set a custom parameter style for a dialect. ```go // Use custom parameter style with a dialect fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres", testfixtures.WithCustomPlaceholder(testfixtures.ParamTypeQuestion), ), testfixtures.Directory("fixtures"), ) ``` -------------------------------- ### Example Fixture Data (YAML) Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Define fixture data for a specific database table in a YAML file. The filename should correspond to the table name. This example shows data for the 'comments' table. ```yaml # comments.yml - id: 1 post_id: 1 content: A comment... author_name: John Doe author_email: john@doe.com created_at: 2020-12-31 23:59:59 updated_at: 2020-12-31 23:59:59 - id: 2 post_id: 2 content: Another comment... author_name: John Doe author_email: john@doe.com created_at: 2020-12-31 23:59:59 updated_at: 2020-12-31 23:59:59 ``` -------------------------------- ### Handle InsertError Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/types.md Example of how to check for and handle an InsertError after attempting to load fixtures. ```go if err := fixtures.Load(); err != nil { if insertErr, ok := err.(*testfixtures.InsertError); ok { log.Printf("Insert error in %s at record %d: %v\n", insertErr.File, insertErr.Index, insertErr.Err) log.Printf("Attempted SQL: %s\n", insertErr.SQL) log.Printf("Parameters: %v\n", insertErr.Params) // Handle the specific insert error } else { log.Printf("Other fixture error: %v\n", err) } } ``` -------------------------------- ### YAML Fixture with Templating Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md Example of a YAML fixture file utilizing Go's text/template syntax with custom functions like `randomHex` and `until`. ```yaml # users.yml with templates enabled {{ range $i := until .UserCount }} - id: {{ $i }} email: user{{ $i }}@example.com name: User {{ $i }} api_key: {{ randomHex 32 }} created_at: 2025-08-15 {{ end }} ``` -------------------------------- ### Example YAML with Templating Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Demonstrates dynamic value generation using SHA256 hashing and random text, as well as iterating over data for record generation within YAML fixtures. ```yaml # It's possible generate values... - id: {{sha256 "my-awesome-post"}} title: My Awesome Post text: {{randomText}} # ... or records {{range $post := $.Posts}} - id: {{$post.Id}} title: {{$post.Title}} text: {{$post.Text}} {{end}} ``` -------------------------------- ### YAML to JSON Conversion Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Demonstrates a YAML array structure that will be converted to a native JSON type in the database. ```yaml - id: 1 post_attributes: author: John Due author_email: john@due.com title: "..." tags: - programming - go - testing post: "..." ``` -------------------------------- ### Recommended SQLite Schema for Deferred Foreign Keys Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Example SQL schema demonstrating how to enable deferred foreign keys using `DEFERRABLE INITIALLY DEFERRED`. ```sql -- Enable deferred foreign keys in your schema CREATE TABLE posts ( id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL, FOREIGN KEY(author_id) REFERENCES users(id) DEFERRABLE INITIALLY DEFERRED ); ``` -------------------------------- ### Basic User Fixture Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Example of a basic YAML fixture file for a 'users' table, demonstrating common column types like ID, email, name, active status, and creation timestamp. ```yaml # users.yml - id: 1 email: user1@example.com name: John Doe active: true created_at: 2025-08-15 10:30:45 - id: 2 email: user2@example.com name: Jane Smith active: false created_at: 2025-08-16 14:22:30 ``` -------------------------------- ### Configure MySQL/MariaDB with AllowMultipleStatements Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Configure the dialect for MySQL or MariaDB and enable the 'AllowMultipleStatements' option for potentially faster execution by allowing multiple setup statements in a single query. ```go testfixtures.New( ... testfixtures.Dialect("mysql"), // or "mariadb" testfixtures.AllowMultipleStatementsInOneQuery(), ) ``` -------------------------------- ### Fixture Solution: Unique Constraint Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML showing how to ensure unique values in columns to avoid unique constraint violations. ```yaml # Ensure unique values - id: 1 email: user1@example.com - id: 2 email: user2@example.com # Different email ``` -------------------------------- ### RAW= Prefix Usage Examples Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Illustrates the `RAW=` prefix for preserving values as raw SQL or preventing automatic type conversions, such as for timestamps or specific string formats. ```yaml - id: 1 created_at: RAW=NOW() # Raw SQL function date_string: RAW=20250815 # Prevent time conversion uuid: RAW=uuid_generate_v4() # UUID function ``` -------------------------------- ### TestMain Pattern for TestFixtures Setup Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md This pattern demonstrates how to initialize the database connection and testfixtures loader within the TestMain function, making them available for all tests in the suite. Ensure your test database is accessible and fixtures are located in the specified directory. ```go package myapp import ( "database/sql" "os" "testing" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) var ( db *sql.DB fixtures *testfixtures.Loader ) func TestMain(m *testing.M) { var err error // Connect to test database db, err = sql.Open("postgres", "dbname=myapp_test") if err != nil { panic(err) } defer db.Close() // Initialize fixtures fixtures, err = testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("testdata/fixtures"), ) if err != nil { panic(err) } // Run tests code := m.Run() os.Exit(code) } // Load fixtures before each test func TestGetUser(t *testing.T) { if err := fixtures.Load(); err != nil { t "testdata/fixtures/users.yml" "testAdata/fixtures/core" "testdata/fixtures/posts.yml" "testdata/common_fixtures" ), ) ``` }, { ``` ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.FilesMultiTables( "testdata/fixtures/scenario1.yml", "testdata/fixtures/scenario2.yml", ), ) ``` ```go package myapp import ( "database/sql" "embed" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) //go:embed testdata/fixtures var embeddedFS embed.FS func setupFixtures(db *sql.DB) (*testfixtures.Loader, error) { fixtures, err := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.FS(embeddedFS), testfixtures.Directory("testdata/fixtures"), ) return fixtures, err } ``` ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("testdata/fixtures"), // Use ALTER CONSTRAINT instead of SUPERUSER-requiring DISABLE TRIGGER ttestfixtures.UseAlterConstraint(), // Reset sequences to a safe value ttestfixtures.ResetSequencesTo(10000), ) ``` ```go // Connection string must include multistatements=true db, _ := sql.Open("mysql", "user:password@tcp(localhost:3306)/myapp_test?multistatements=true") fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("mysql"), ttestfixtures.Directory("testdata/fixtures"), // Batch multiple statements into one query for faster execution ttestfixtures.AllowMultipleStatementsInOneQuery(), ttestfixtures.ResetSequencesTo(10000), ) ``` ```go // In-memory database for ultra-fast tests db, _ := sql.Open("sqlite3", "file::memory:?cache=shared") // Create schema db.Exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)`) db.Exec(`CREATE TABLE posts (id INTEGER PRIMARY KEY, user_id INTEGER, title TEXT, FOREIGN KEY(user_id) REFERENCES users(id) DEFERRABLE INITIALLY DEFERRED)`) fixtures, _ := testfixtures.New( ttestfixtures.Database(db), testfixtures.Dialect("sqlite"), ttestfixtures.Directory("testdata/fixtures"), ) ``` ```go db, _ := sql.Open("spanner", "projects/my-project/instances/my-instance/databases/myapp_test") fixtures, _ := testfixtures.New( ttestfixtures.Database(db), ttestfixtures.Dialect("spanner"), ttestfixtures.Files( "testdata/fixtures/users.yml", // Parent table first "testdata/fixtures/profiles.yml", // Child table second "testdata/fixtures/posts.yml", "testdata/fixtures/comments.yml", ), ttestfixtures.DangerousSkipTestDatabaseCheck(), ) ``` -------------------------------- ### PostgreSQL Sequence Reset Configuration Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Demonstrates how to configure sequence reset behavior for PostgreSQL. You can set a custom starting value or skip the reset entirely. ```go // Reset sequences to 10000 (default) testfixtures.ResetSequencesTo(10000) ``` ```go // Reset sequences to 1000 testfixtures.ResetSequencesTo(1000) ``` ```go // Skip sequence reset testfixtures.SkipResetSequences() ``` -------------------------------- ### YAML Fixture Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/types.md Illustrates a YAML structure for fixture data, showcasing how various data types like strings, numbers, booleans, nulls, hex strings, dates, timestamps, raw SQL, arrays, and objects are handled and converted. ```yaml - id: 1 name: John Doe email: john@example.com created_at: 2025-08-15 # Auto-converted to time.Time updated_at: RAW=NOW() # Raw SQL function metadata: # Converted to JSON role: admin permissions: - read - write binary_field: 0x48656c6c6f # Hex string to bytes ``` -------------------------------- ### Minimal Record Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Keep fixture records concise by including only the essential fields required for the test. Avoid adding unnecessary or duplicate data. ```yaml # Good: Only required fields - id: 1 name: John email: john@example.com # Avoid: Duplicate or unused fields - id: 1 name: John email: john@example.com phone: null address: null notes: null ``` -------------------------------- ### Fixture Solution: Foreign Key Constraint Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML demonstrating how to resolve foreign key constraint violations by loading parent records first. ```yaml # Load parent table first (in Files or better organization) # users.yml - id: 1 name: John Doe # posts.yml - id: 1 author_id: 1 # Must exist in users title: Post Title ``` -------------------------------- ### Fixture Solution: Data Type Mismatch (Correct) Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML showing correct data types for columns to avoid type mismatch errors. ```yaml # CORRECT: - id: 1 author_id: 1 ``` -------------------------------- ### YAML Structure for Multiple Tables Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md An example YAML file demonstrating how to define data for multiple tables ('posts' and 'comments') within a single file, including various data types. ```yaml # test_case1.yml posts: - id: 1 post_id: 1 content: A comment... author_name: John Doe author_email: john@doe.com created_at: 2020-12-31 23:59:59 updated_at: 2020-12-31 23:59:59 - id: 2 post_id: 2 content: Another comment... author_name: John Doe author_email: john@doe.com created_at: 2020-12-31 23:59:59 updated_at: 2020-12-31 23:59:59 comments: - id: 1 post_id: 1 content: Post 1 comment 1 author_name: John Doe author_email: john@doe.com created_at: 2016-01-01 12:30:12 updated_at: 2016-01-01 12:30:12 # ... ``` -------------------------------- ### PostgreSQL/TimescaleDB/CockroachDB Configuration Options Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/00-START-HERE.md Configuration options specific to PostgreSQL-compatible databases. UseAlterConstraint is recommended for environments without SUPERUSER privileges. ResetSequencesTo sets the starting value for auto-incrementing sequences. ```go testfixtures.Dialect("postgres"), testfixtures.UseAlterConstraint(), // Recommended, no SUPERUSER required testfixtures.ResetSequencesTo(10000), ``` -------------------------------- ### Load Fixtures with Multiple Sources Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Demonstrates how to specify multiple sources for loading fixtures. Fixtures are loaded in the order the options are provided. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Files("fixtures/users.yml"), // Loaded first testfixtures.Directory("fixtures/common"), // Loaded second testfixtures.Paths("fixtures/posts.yml"), // Loaded third ) ``` -------------------------------- ### Create and Initialize a New Loader Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/api-reference.md Creates a new `Loader` instance with optional configuration functions. Ensure the `Database` and `Dialect` options are provided, and specify the `Directory` containing fixture files. ```go package main import ( "database/sql" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) func main() { db, _ := sql.Open("postgres", "dbname=myapp_test") fixtures, err := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("testdata/fixtures"), ) if err != nil { panic(err) } if err := fixtures.Load(); err != nil { panic(err) } } ``` -------------------------------- ### Timezone-Aware Fixture Data Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md Example of fixture data where timestamps are interpreted within a specified timezone (e.g., Tokyo). Dates and times are parsed relative to the configured location. ```yaml # With Tokyo timezone - id: 1 name: John Doe created_at: 2025-08-15 09:00:00 # Interpreted as Tokyo time updated_at: 2025-08-16 14:30:00 ``` -------------------------------- ### TestFixtures Initialization with Directory Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Sets up the testfixtures loader by opening a database connection, specifying the dialect, and providing a directory for YAML fixture files. ```go package myapp import ( "database/sql" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) var ( db *sql.DB fixtures *testfixtures.Loader ) func TestMain(m *testing.M) { var err error // Open connection to the test database. // Do NOT import fixtures in a production database! // Existing data would be deleted. db, err = sql.Open("postgres", "dbname=myapp_test") if err != nil { ... } fixtures, err = testfixtures.New( testfixtures.Database(db), // You database connection testfixtures.Dialect("postgres"), // Available: "postgresql", "timescaledb", "mysql", "mariadb", "sqlite" and "sqlserver" testfixtures.Directory("testdata/fixtures"), // The directory containing the YAML files ) if err != nil { ... } os.Exit(m.Run()) } func prepareTestDatabase() { if err := fixtures.Load(); err != nil { ... } } func TestX(t *testing.T) { prepareTestDatabase() // Your test here ... } func TestY(t *testing.T) { prepareTestDatabase() // Your test here ... } func TestZ(t *testing.T) { prepareTestDatabase() // Your test here ... } ``` -------------------------------- ### Numeric Data Types Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Shows examples of different numeric types: integers and floating-point numbers. ```yaml - id: 1 count: 42 rating: 4.5 price: 19.99 views: 1000000 ``` -------------------------------- ### Create and Initialize New Dumper Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/dumper-api.md Creates a new Dumper instance with specified configuration options. Ensure all required options like database connection, dialect, and directory are provided. ```go package main import ( "database/sql" _ "github.com/lib/pq" "github.com/go-testfixtures/testfixtures/v3" ) func main() { db, _ := sql.Open("postgres", "dbname=myapp_sample") dumper, err := testfixtures.NewDumper( testfixtures.DumpDatabase(db), testfixtures.DumpDialect("postgres"), testfixtures.DumpDirectory("testdata/fixtures"), ) if err != nil { panic(err) } if err := dumper.Dump(); err != nil { panic(err) } } ``` -------------------------------- ### Loading Fixtures by File Path Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Use `testfixtures.Files()` to specify individual fixture files to be loaded in the exact order they are listed. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Files( "fixtures/users.yml", // Loaded first "fixtures/posts.yml", // Loaded second "fixtures/comments.yml", // Loaded third ), ) ``` -------------------------------- ### JSON Column Data Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Example of a YAML structure that will be automatically converted to a JSON object for storage in JSON/JSONB database columns. ```yaml - id: 1 metadata: role: admin permissions: - read - write - delete settings: theme: dark notifications: true ``` -------------------------------- ### TestFixtures Initialization with Files Option Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Initializes testfixtures, specifying the database connection, dialect, and a list of specific YAML files to load. ```go fixtures, err := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Files( "fixtures/orders.yml", "fixtures/customers.yml", ), ) if err != nil { ... } ``` -------------------------------- ### Automatic Date/Time Conversion Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Examples of string values that will be automatically converted to `time.Time` by the library, based on supported standard formats. ```yaml - id: 1 created_at: 2025-08-15 # Auto-converted updated_at: 2025-08-15 14:30:45 # Auto-converted published_at: "2025-08-15T14:30-05:00" # Auto-converted ``` -------------------------------- ### SQL: Create and prepare a template database Source: https://github.com/go-testfixtures/testfixtures/blob/master/dbtests/examples.md This SQL snippet demonstrates how to create and prepare a template database in PostgreSQL. This template can then be used to efficiently create new logical databases for testing purposes. ```sql CREATE DATABASE dbname TEMPLATE template; ``` -------------------------------- ### Bootstrap Test Fixtures from Staging Database Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md Generate test fixtures by connecting to a staging database. This script connects to the staging database, dumps its contents to fixture files, and logs success. ```go // In bootstrap script func main() { // Connect to staging database with representative data db, _ := sql.Open("postgres", "dbname=myapp_staging") defer db.Close() dumper, _ := testfixtures.NewDumper( testfixtures.DumpDatabase(db), testfixtures.DumpDialect("postgres"), testfixtures.DumpDirectory("testdata/fixtures"), ) if err := dumper.Dump(); err != nil { log.Fatal(err) } log.Println("Fixtures generated successfully!") } ``` -------------------------------- ### AllowMultipleStatementsInOneQuery Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/api-reference.md Enables grouping of multiple setup statements into a single query for better performance. The connection string must have multistatements=true. ```APIDOC ## AllowMultipleStatementsInOneQuery ### Description Enables grouping of multiple setup statements into a single query for better performance. The connection string must have `multistatements=true`. ### Method func ### Endpoint AllowMultipleStatementsInOneQuery() ### Parameters None ### Request Example ```go fixtures, _ := testfixtures.New( ttestfixtures.Database(db), ttestfixtures.Dialect("mysql"), ttestfixtures.Directory("fixtures"), ttestfixtures.AllowMultipleStatementsInOneQuery(), ) ``` ### Response #### Success Response (200) `func(*Loader) error` #### Response Example None ``` -------------------------------- ### Loader Constructor Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/exported-symbols.md Creates and initializes a new Loader. Requires database and dialect options. ```go func New(options ...func(*Loader) error) (*Loader, error) ``` -------------------------------- ### MySQL Connection String for Multistatement Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Example of a MySQL database connection string that includes the 'multistatements=true' parameter, required for the 'AllowMultipleStatementsInOneQuery' option. ```go // Must include multistatements=true db, _ := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname?multistatements=true") ``` -------------------------------- ### Production-like Testing with PostgreSQL Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Set up testfixtures for production-like testing using PostgreSQL, enabling `UseAlterConstraint` and directory scanning. ```go db, _ := sql.Open("postgres", "dbname=myapp_test") fixtures, _ := testfixtures.New( ttestfixtures.Database(db), ttestfixtures.Dialect("postgres"), ttestfixtures.UseAlterConstraint(), ttestfixtures.Directory("fixtures"), ) ``` -------------------------------- ### Fixture Solution: Data Type Mismatch (Incorrect) Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML with incorrect data types that will cause a type mismatch error. ```yaml # WRONG: String for integer column - id: "not a number" author_id: "also not a number" ``` -------------------------------- ### Fixture Solution: Column Not Found (Incorrect) Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML illustrating an incorrect field name that causes a 'column not found' error. ```yaml # Check table schema # WRONG: Column name mismatch - id: 1 full_name: John Doe # Table has 'name' not 'full_name' ``` -------------------------------- ### SQL Server Configuration Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/00-START-HERE.md Sets the dialect for SQL Server. ```go testfixtures.Dialect("sqlserver"), ``` -------------------------------- ### Fixture Solution: Column Not Found (Correct) Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Example YAML showing the correct field name to resolve 'column not found' errors. ```yaml # CORRECT: - id: 1 name: John Doe ``` -------------------------------- ### Configure SQLite Test Fixtures Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Initializes test fixtures for SQLite. Defaults include '?' parameter type, deferred foreign keys, and enabled checksum optimization. Foreign keys are no-ops by default but DEFERRABLE is recommended. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("sqlite"), testfixtures.Directory("fixtures"), // Defaults: // - ParamType: ? (question mark) // - FK constraints: Deferred via PRAGMA defer_foreign_keys // - Checksum optimization: Enabled // - Note: Foreign keys are no-op by default, but using DEFERRABLE is recommended ) ``` -------------------------------- ### Stored JSON Object Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md The JSON representation of the YAML object shown in the previous example, as it would be stored in a JSON/JSONB database column. ```json { "role": "admin", "permissions": ["read", "write", "delete"], "settings": { "theme": "dark", "notifications": true } } ``` -------------------------------- ### UUID Generation with RAW= Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Example of using `RAW=` to insert a UUID generated by a database function. This avoids manual UUID generation in fixtures. ```yaml - id: RAW=uuid_generate_v4() name: John Doe ``` -------------------------------- ### Non-List Fixture Root Error Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Shows an example of an invalid YAML fixture structure where the root element is a string instead of a list or map. ```yaml # WRONG: String as root "This is invalid" ``` -------------------------------- ### Validating Fixture Configuration in Go Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Shows how to validate fixture configuration during initialization and fail fast if any errors occur. ```go fixtures, err := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("fixtures"), ) if err != nil { log.Fatalf("Failed to configure fixtures: %v", err) } ``` -------------------------------- ### Configure Dynamic Fixtures with Templates Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/00-START-HERE.md Enable dynamic fixtures using templates. You can provide custom template functions and data to customize fixture generation. ```go testfixtures.Template(), testfixtures.TemplateFuncs(customFuncs), testfixtures.TemplateData(data) ``` -------------------------------- ### Ensuring Safe Database Testing with Go Testfixtures Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Demonstrates how to initialize test fixtures and optionally verify that the database being used is a test database before running tests. ```go func TestMain(m *testing.M) { // Verify database safety fixtures, err := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Directory("fixtures"), ) if err != nil { log.Fatalf("Fixture configuration error: %v", err) } // Optional: Verify it's a test database if err := fixtures.EnsureTestDatabase(); err != nil { log.Fatalf("Not a test database: %v", err) } os.Exit(m.Run()) } ``` -------------------------------- ### Descriptive Field Names Example Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Use clear and descriptive field names that accurately reflect the database schema to improve fixture readability and maintainability. ```yaml # Good: Clear, matches database schema - id: 1 user_id: 1 post_title: First Post created_at: 2025-08-15 # Avoid: Ambiguous names - id: 1 u: 1 t: First Post c: 2025-08-15 ``` -------------------------------- ### Enterprise Environments with SQL Server Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Configure testfixtures for SQL Server in enterprise environments, using directory scanning for fixture loading. ```go db, _ := sql.Open("sqlserver", "server=localhost;database=myapp_test") fixtures, _ := testfixtures.New( ttestfixtures.Database(db), ttestfixtures.Dialect("sqlserver"), ttestfixtures.Directory("fixtures"), ) ``` -------------------------------- ### Computed Values with RAW= Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Example of using `RAW=` for computed values based on other fields or database logic, such as concatenating names or calculating age from dates. ```yaml - id: 1 full_name: RAW=CONCAT(first_name, ' ', last_name) age: RAW=EXTRACT(YEAR FROM AGE(birth_date)) ``` -------------------------------- ### Selective Fixture Loading by Files (Users and Posts) Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/usage-patterns.md Loads both 'users.yml' and 'posts.yml' fixture files for tests requiring data from both sources. ```go // For post-specific tests postFixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("postgres"), testfixtures.Files( "testdata/fixtures/users.yml", "testdata/fixtures/posts.yml", ), ) ``` -------------------------------- ### Loader Option: Files Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/exported-symbols.md Loads specific fixture files provided as arguments. Use this to load a precise set of files in a defined order. ```go func(files ...string) func(*Loader) error ``` -------------------------------- ### Initialize ClickHouse Database Connection Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Opens a connection to a ClickHouse database and initializes test fixtures with the ClickHouse dialect. Ensure the ClickHouse server is running and accessible. ```go db, _ := sql.Open("clickhouse", "tcp://localhost:9000?database=myapp_test") fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("clickhouse"), testfixtures.Directory("fixtures"), ) ``` -------------------------------- ### Configure MySQL/MariaDB Test Fixtures Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Initializes test fixtures for MySQL or MariaDB. Defaults include '?' parameter type, disabled FK constraints, auto-increment reset to 10000, and enabled checksum optimization. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("mysql"), testfixtures.Directory("fixtures"), // Defaults: // - ParamType: ? (question mark) // - FK constraints: Disabled via SET FOREIGN_KEY_CHECKS = 0 // - Auto-increment reset: Yes, to 10000 // - Checksum optimization: Enabled ) ``` -------------------------------- ### YAML Unmarshal Error Examples Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/errors.md Illustrates common YAML syntax errors, such as missing colons and inconsistent indentation, contrasted with correct YAML structure. ```yaml # WRONG: Invalid YAML syntax - id: 1 name John Doe # Missing colon # CORRECT: - id: 1 name: John Doe ``` -------------------------------- ### PostgreSQL Loader Option: ResetSequencesTo Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/exported-symbols.md Sets a specific value to which PostgreSQL sequences should be reset after loading data. Provide the desired starting value for sequences. ```go func(value int64) func(*Loader) error ``` -------------------------------- ### Multi-Table Fixture Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/fixture-format.md Example of a multi-table YAML fixture file. Table data is organized under top-level keys corresponding to table names, intended for use with FilesMultiTables(). ```yaml # multi_fixture.yml (loaded with FilesMultiTables) users: - id: 1 name: John Doe - id: 2 name: Jane Smith posts: - id: 1 author_id: 1 title: First Post - id: 2 author_id: 2 title: Second Post ``` -------------------------------- ### ClickHouse DELETE FROM Cleanup Strategy Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/database-dialects.md Initialize test fixtures for ClickHouse using the DELETE FROM cleanup strategy, useful when TRUNCATE is problematic. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("clickhouse"), testfixtures.Directory("fixtures"), testfixtures.ClickhouseUseDeleteFrom(), ) ``` -------------------------------- ### Configure MySQL/MariaDB Dialect Source: https://github.com/go-testfixtures/testfixtures/blob/master/README.md Configure the dialect for MySQL or MariaDB. ```go testfixtures.New( ... testfixtures.Dialect("mysql"), // or "mariadb" ) ``` -------------------------------- ### Configure MySQL Auto-Increment Reset Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Sets the starting value for auto-increment sequences or skips the reset entirely. Use `ResetSequencesTo` for a specific value or `SkipResetSequences` to disable. ```go // Reset auto-increment to 10000 (default) testfixtures.ResetSequencesTo(10000) // Skip auto-increment reset testfixtures.SkipResetSequences() ``` -------------------------------- ### Configure ClickHouse Test Fixtures Source: https://github.com/go-testfixtures/testfixtures/blob/master/_autodocs/configuration.md Initializes test fixtures for ClickHouse. Defaults include '$' parameter type, TRUNCATE TABLE cleanup, and no FK constraint enforcement. TRUNCATE is faster and atomic. ```go fixtures, _ := testfixtures.New( testfixtures.Database(db), testfixtures.Dialect("clickhouse"), testfixtures.Directory("fixtures"), // Defaults: // - ParamType: $ (dollar) // - Cleanup: TRUNCATE TABLE (atomic, fast) // - FK constraints: Not enforced (not supported by ClickHouse) ) ```