Ruby on Rails like test fixtures for Go. Write tests against a real database

testfixtures

PkgGoDev

Warning: this package will wipe the database data before loading the fixtures! It is supposed to be used on a test database. Please, double check if you are running it against the correct database.

TIP: There are options not described in this README page. It's recommended that you also check the documentation.

Writing tests is hard, even more when you have to deal with an SQL database. This package aims to make writing functional tests for web apps written in Go easier.

Basically this package mimics the "Ruby on Rails' way" of writing tests for database applications, where sample data is kept in fixtures files. Before the execution of every test, the test database is cleaned and the fixture data is loaded into the database.

The idea is running tests against a real database, instead of relying in mocks, which is boring to setup and may lead to production bugs not being caught in the tests.

Installation

First, import it like this:

import (
        "github.com/go-testfixtures/testfixtures/v3"
)

Usage

Create a folder for the fixture files. Each file should contain data for a single table and have the name <table_name>.yml:

myapp/
  myapp.go
  myapp_test.go
  ...
  fixtures/
    posts.yml
    comments.yml
    tags.yml
    posts_tags.yml
    ...

The file would look like this (it can have as many record you want):

# comments.yml
- id: 1
  post_id: 1
  content: A comment...
  author_name: John Doe
  author_email: [email protected]
  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: [email protected]
  created_at: 2020-12-31 23:59:59
  updated_at: 2020-12-31 23:59:59

# ...

An YAML object or array will be converted to JSON. It will be stored on a native JSON type like JSONB on PostgreSQL & CockroachDB or as a TEXT or VARCHAR column on other databases.

- id: 1
  post_attributes:
    author: John Due
    author_email: [email protected]
    title: "..."
    tags:
      - programming
      - go
      - testing
    post: "..."

Binary columns can be represented as hexadecimal strings (should start with 0x):

- id: 1
  binary_column: 0x1234567890abcdef

If you need to write raw SQL, probably to call a function, prefix the value of the column with RAW=:

- id: 1
  uuid_column: RAW=uuid_generate_v4()
  postgis_type_column: RAW=ST_GeomFromText('params...')
  created_at: RAW=NOW()
  updated_at: RAW=NOW()

Your tests would look like this:

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 ...
}

Alternatively, you can use the Files option, to specify which files you want to load into the database:

fixtures, err := testfixtures.New(
        testfixtures.Database(db),
        testfixtures.Dialect("postgres"),
        testfixtures.Files(
                "fixtures/orders.yml",
                "fixtures/customers.yml",
        ),
)
if err != nil {
        ...
}

fixtures, err := testfixtures.NewFiles(db, &testfixtures.PostgreSQL{},
        "fixtures/orders.yml",
        "fixtures/customers.yml",
        // add as many files you want
)
if err != nil {
        ...
}

With Paths option, you can specify the paths that fixtures will load from. Path can be directory or file. If directory, we will search YAML files in it.

fixtures, err := testfixtures.New(
        testfixtures.Database(db),
        testfixtures.Dialect("postgres"),
        testfixtures.Paths(
                "fixtures/orders.yml",
                "fixtures/customers.yml",
                "common_fixtures/users"
        ),
)
if err != nil {
        ...
}

Security check

In order to prevent you from accidentally wiping the wrong database, this package will refuse to load fixtures if the database name (or database filename for SQLite) doesn't contains "test". If you want to disable this check, use:

testfixtures.New(
        ...
        testfixtures.DangerousSkipTestDatabaseCheck(),
)

Sequences

For PostgreSQL, this package also resets all sequences to a high number to prevent duplicated primary keys while running the tests. The default is 10000, but you can change that with:

testfixtures.New(
        ...
        testfixtures.ResetSequencesTo(10000),
)

Or, if you want to skip the reset of sequences entirely:

testfixtures.New(
        ...
        testfixtures.SkipResetSequences(),
)

Compatible databases

PostgreSQL / TimescaleDB / CockroachDB

This package has three approaches to disable foreign keys while importing fixtures for PostgreSQL databases:

With DISABLE TRIGGER

This is the default approach. For that use:

testfixtures.New(
        ...
        testfixtures.Dialect("postgres"), // or "timescaledb"
)

With the above snippet this package will use DISABLE TRIGGER to temporarily disabling foreign key constraints while loading fixtures. This work with any version of PostgreSQL, but it is required to be connected in the database as a SUPERUSER. You can make a PostgreSQL user a SUPERUSER with:

ALTER USER your_user SUPERUSER;

With ALTER CONSTRAINT

This approach don't require to be connected as a SUPERUSER, but only work with PostgreSQL versions >= 9.4. Try this if you are getting foreign key violation errors with the previous approach. It is as simple as using:

testfixtures.New(
        ...
        testfixtures.Dialect("postgres"),
        testfixtures.UseAlterConstraint(),
)

With DROP CONSTRAINT

This approach is implemented to support databases that do not support above methods (namely CockroachDB).

testfixtures.New(
        ...
        testfixtures.Dialect("postgres"),
        testfixtures.UseDropConstraint(),
)

Tested using the github.com/lib/pq and github.com/jackc/pgx drivers.

MySQL / MariaDB

Just make sure the connection string have the multistatement parameter set to true, and use:

testfixtures.New(
        ...
        testfixtures.Dialect("mysql"), // or "mariadb"
)

Tested using the github.com/go-sql-driver/mysql driver.

SQLite

SQLite is also supported. It is recommended to create foreign keys as DEFERRABLE (the default) to prevent problems. See more on the SQLite documentation. (Foreign key constraints are no-op by default on SQLite, but enabling it is recommended).

testfixtures.New(
        ...
        testfixtures.Dialect("sqlite"),
)

Tested using the github.com/mattn/go-sqlite3 driver.

Microsoft SQL Server

SQL Server support requires SQL Server >= 2008. Inserting on IDENTITY columns are handled as well. Just make sure you are logged in with a user with ALTER TABLE permission.

testfixtures.New(
        ...
        testfixtures.Dialect("sqlserver"),
)

Tested using the mssql and sqlserver drivers from the github.com/denisenkom/go-mssqldb lib.

Templating

Testfixtures supports templating, but it's disabled by default. Most people won't need it, but it may be useful to dynamically generate data.

Enable it by doing:

testfixtures.New(
        ...
        testfixtures.Template(),

        // the above options are optional
        TemplateFuncs(...),
        TemplateDelims("{{", "}}"),
        TemplateOptions("missingkey=zero"),
        TemplateData(...),
)

The YAML file could look like this:

# 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}}

Generating fixtures for a existing database

The following code will generate a YAML file for each table of the database into a given folder. It may be useful to boostrap a test scenario from a sample database of your app.

dumper, err := testfixtures.NewDumper(
        testfixtures.DumpDatabase(db),
        testfixtures.DumpDialect("postgres"), // or your database of choice
        testfixtures.DumpDirectory("tmp/fixtures"),
        textfixtures.DumpTables( // optional, will dump all table if not given
          "posts",
          "comments",
          "tags",
        )
)
if err != nil {
        ...
}
if err := dumper.Dump(); err != nil {
        ...
}

This was intended to run in small sample databases. It will likely break if run in a production/big database.

Gotchas

Parallel testing

This library doesn't yet support running tests in parallel! Running tests in parallel can result in random data being present in the database, which will likely cause tests to randomly/intermittently fail.

This is specially tricky since it's not immediately clear that go test ./... run tests for each package in parallel. If more than one package use this library, you can face this issue. Please, use go test -p 1 ./... or run tests for each package in separated commands to fix this issue.

If you're looking into being able to run tests in parallel you can try using testfixtures together with the txdb package, which allows wrapping each test run in a transaction.

CLI

We also have a CLI to load fixtures in a given database.

Grab it from the releases page or install with Homebrew:

brew install go-testfixtures/tap/testfixtures

Usage is like this:

testfixtures -d postgres -c "postgres://user:password@localhost/database" -D testdata/fixtures

The connection string changes for each database driver.

Use testfixtures --help for all flags.

Contributing

We recommend you to install Task and Docker before contributing to this package, since some stuff is automated using these tools.

It's recommended to use Docker Compose to run tests, since it runs tests for all supported databases once. To do that you just need to run:

task docker

But if you want to run tests locally, copy the .sample.env file as .env and edit it according to your database setup. You'll need to create a database (likely names testfixtures_test) before continuing. Then run the command for the database you want to run tests against:

task test:pg # PostgreSQL
task test:crdb # CockroachDB
task test:mysql # MySQL
task test:sqlite # SQLite
task test:sqlserver # Microsoft SQL Server

GitHub Actions (CI) runs the same Docker setup available locally.

Alternatives

If you don't think using fixtures is a good idea, you can try one of these packages instead:

  • factory-go: Factory for Go. Inspired by Python's Factory Boy and Ruby's Factory Girl
  • go-txdb (Single transaction SQL driver for Go): Use a single database transaction for each functional test, so you can rollback to previous state between tests to have the same database state in all tests
  • go-sqlmock: A mock for the sql.DB interface. This allow you to unit test database code without having to connect to a real database
  • dbcleaner - Clean database for testing, inspired by database_cleaner for Ruby
Comments
  • Provide CLI to allow database seeding outside of tests

    Provide CLI to allow database seeding outside of tests

    It would be great to have a command line interface with basic fixtures load/unload commands.

    This would allow users to seed database using same fixtures and use them in development environment. It would be useful for manual testing or as demonstration data.

  • Add support for

    Add support for "pgx" postgres driver/dialect.

    I'm currently using pgx (https://github.com/jackc/pgx) instead of pq I would like to use this driver/dialect in testfixtures, but it's not currently supported. Seems like I can just add pgx to the helperForDialect function. I tested it out and it seemed to work. It also passed the unit tests.

    There was one slight difference that I noticed. In one of my fixtures I have a zip code string field, which I populate like this 11111. In postgres/pq it gets converted to a string automatically. But I noticed in pgx I need to explicitly make the zip code a string (e.g. '11111'). There may be more differences, but haven't tested it too extensively so far.

    func helperForDialect(dialect string) (helper, error) {
    	switch dialect {
    	case "postgres", "postgresql", "timescaledb", "pgx":
    		return &postgreSQL{}, nil
    	case "mysql", "mariadb":
    		return &mySQL{}, nil
    	case "sqlite", "sqlite3":
    		return &sqlite{}, nil
    	case "mssql", "sqlserver":
    		return &sqlserver{}, nil
    	default:
    		return nil, fmt.Errorf(`testfixtures: unrecognized dialect "%s"`, dialect)
    	}
    }
    
  • Tests sometimes run before Load() method finishes

    Tests sometimes run before Load() method finishes

    Go version: go1.11.2 linux/amd64 DB: MariaDB 5.5.60 testfixtures: v2.5.1

    I'm running into some weird issues where it seems that func (c *Context) Load() either isn't blocking the tests from running until it finishes or silently errors out. In a couple of my tests I have a yaml file with 7 rows defined, sometimes running my tests everything works as expected the table is correctly cleaned of old data and the new data is populated and my tests passes. Other times only 1-2 rows may get loaded which causes my tests to be wrong due to the missing data.

    I'm not too sure of an easy way to trace down what exactly is going on though that is causing this error.

  • [PostgreSQL]ALTER CONSTRAINT problem

    [PostgreSQL]ALTER CONSTRAINT problem

    Environment

    • PostgreSQL 10
    • testfixtures 2.4.3
    • Go 1.8.3

    Error message

    2017/12/20 19:43:41 pq: update or delete on table "users" violates foreign key constraint "environments_created_by_users_id_foreign" on table "environments"
    

    SUPERUSER + &testfixtures.PostgreSQL{} => Success SUPERUSER + &testfixtures.PostgreSQL{UseAlterConstraint: true} => Failure USER + &testfixtures.PostgreSQL{} => Failure USER + &testfixtures.PostgreSQL{UseAlterConstraint: true} => Failure

    It seems ALTER CONSTRAINT is ineffective. Do you have any information?

  • Add support for PostgreSQL schema escaped table names and schemas

    Add support for PostgreSQL schema escaped table names and schemas

    Continuation of https://github.com/go-testfixtures/testfixtures/pull/14 , but now to enable the usage of schema-spaced tables with testfixtures :). Example filenames for schema namespace:

    fixtures/schema_one.table_one.yml
    fixtures/schema_one.table_two.yml
    fixtures/schema_two.table_one.yml
    

    These changes allow escaping schema and table names separately; see postgresql_test.go for added tests on the new quoteKeyword method.

  • Can't unload or load empty table

    Can't unload or load empty table

    Some of my tests require that my queries return zero results because the DB is empty.

    If I don't call load on my first test, I can get this behaviour, however on subsequent runs, due to having loaded in a later test, this test now fails (more than zero results) as the sqlite DB still exists.

    It'd be helpful to have an unload/reset or a way to load in an empty table using the NewFiles for this purpose.

  • Postgresql: Support for TimescaleDB

    Postgresql: Support for TimescaleDB

    Hi there, this PR is my attempt to add support in testfixtures for TimescaleDB, a Postgres extension that supports time-series operations & workflows. I really like the idea of testing with a live db data especially when there's complex db functions involved, so testfixtures was a great find. Unfortunately, this library breaks when attempting to restage the timescaledb tables with the error ERROR: operation not supported on chunk tables.

    TimescaleDB works transparently by manipulating the database, automatically generating partition tables, hooking into the query planner, and other tricks.

    psql~> \dn
              List of schemas
              Name           |  Owner   
    -------------------------+----------
     _timescaledb_cache      | postgres
     _timescaledb_catalog    | postgres
     _timescaledb_config     | postgres
     _timescaledb_internal   | postgres
     public                  | postgres
    

    My approach to fix the issue I saw, was to ignore those schemas and let the extension do the book-keeping. Specifically, I added an exclusion for all pg namespaces that are prefixed by underscores (_), which are considered private, off-limits by the extension. This may be kludgy and break existing user's tests if they happen to prefix similar ways, though I've never personally seen that naming strategy used by anyone but applications that mess with postgres internals.

    I would be willing to investigate an alternative approach. Such as searching for partition tables that do not support DELETE/TRUNCATE, or adding an option field to the testfixtures.Helper to specify a blacklist of table namespaces. Let me know what you think!


    Another user wondered about Timescale before, #27 . Around that time, I started using this patch with my own projects, and I have seen no unexpected breaks. Testing was done with PG v10 & v11, and the extension for TimescaleDB v0.9 (beta) through v1.4 (current).

  • Cannot change time.Location of parsing date

    Cannot change time.Location of parsing date

    I would like to change time.Location of date, but cannot change because of this code.

    https://github.com/go-testfixtures/testfixtures/blob/fa3fb89109b0b31957a5430cef3e93e535de362b/time.go#L25-L34

    So, I fixed my yaml file the following temporary.

    -  datetime: 2018-01-01 18:00:00
    +  datetime: RAW="2018-01-01 18:00:00"
    

    Is there other solution?

  • Can't correctly load binary data from generated yml file

    Can't correctly load binary data from generated yml file

    I use SQLite3 to store small binary data (data type blob). Call GenerateFixtures() and obtain a .yml file like following:

    - type: 0
      value:
      - 8
      - 128
      - 8
      - 16
      - 13
    ...
    

    When I use Load() to read this *.yml file and overwrite the whole DB entries, the values are not the same as they were when I generated the fixtures. Except for blob, other data types remain intact.

    Before GenerateFixtures():

    INSERT INTO logs VALUES(2,1024,1,X'088008100d18a4f3f488a8c3aad015','2019-05-21 17:55:01.882239396+08:00',NULL,0,0);
    

    After Load():

    INSERT INTO logs VALUES(2,1024,1,X'5b382c3132382c382c31362c31332c32342c3136342c3234332c3234342c3133362c3136382c3139352c3137302c3230382c32315d','2019-05-21 17:55:01.882239396+08:00',NULL,0,0);
    

    I believe the inconsistency is caused by json.Marshal in jsonArray's receiver function Value(). It will automatically convert []int to marshaled []byte, but the result is unexpected.

    An easy workaround is like this:

    func (a jsonArray) Value() (driver.Value, error) {
        var arr []byte
        for _, v := range a {
            arr = append(arr, byte(v.(int)))
        }
        return arr, nil
    }
    

    However, it just considers int array case.

    Any suggestions?

  • Allow fixture names to have deeper extensions

    Allow fixture names to have deeper extensions

    Hello, motivation for the change is most of the time in one single test file I have multiple tests and I want to have separate test fixtures for them, so that I can load specifically, and not loose the table naming convention. This is not a breaking change and only introduces new functionality. test 1

    fixtures, err := testfixtures.NewFiles(db, &testfixtures.PostgreSQL{},
        "fixtures/favorites#1.yml",
        "fixtures/customers.yml",
    )
    if err != nil {
        log.Fatal(err)
    }
    

    test 2

    fixtures, err := testfixtures.NewFiles(db, &testfixtures.PostgreSQL{},
        "fixtures/favorites#2.yml",
        "fixtures/customers.yml",
    )
    if err != nil {
        log.Fatal(err)
    }
    

    Let's discuss. 😄

  • JSONB types in Postgres

    JSONB types in Postgres

    Whenever I add to a fixture a map or array, I get an error like:

    "sql: converting Exec argument #3's type: unsupported type map[interface {}]interface {}, a map"
    

    Any chance we can support JSONB?

  • Error loading string data

    Error loading string data

    I have the current data in the table creation:

    amount varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
    

    and in the fixture file:

    amount: "000000601"
    

    When it loads the fixtures, for some unknown reason, it converts it to: 0000-06-01 00:00:00 -0659 LMT.

    When I remove the quotes in the fixture file:

    amount: 000000601
    

    it converts correctly to a varchar.

    However, I would like to keep being explicit about the data type by using quotes.

  • Bump github.com/go-sql-driver/mysql from 1.6.0 to 1.7.0

    Bump github.com/go-sql-driver/mysql from 1.6.0 to 1.7.0

    Bumps github.com/go-sql-driver/mysql from 1.6.0 to 1.7.0.

    Release notes

    Sourced from github.com/go-sql-driver/mysql's releases.

    Version 1.7

    Changes:

    • Drop support of Go 1.12 (#1211)
    • Refactoring (*textRows).readRow in a more clear way (#1230)
    • util: Reduce boundary check in escape functions. (#1316)
    • enhancement for mysqlConn handleAuthResult (#1250)

    New Features:

    • support Is comparison on MySQLError (#1210)
    • return unsigned in database type name when necessary (#1238)
    • Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370)
    • Add SQLState to MySQLError (#1321)

    Bugfixes:

    • Fix parsing 0 year. (#1257)
    Changelog

    Sourced from github.com/go-sql-driver/mysql's changelog.

    Version 1.7 (2022-11-29)

    Changes:

    • Drop support of Go 1.12 (#1211)
    • Refactoring (*textRows).readRow in a more clear way (#1230)
    • util: Reduce boundary check in escape functions. (#1316)
    • enhancement for mysqlConn handleAuthResult (#1250)

    New Features:

    • support Is comparison on MySQLError (#1210)
    • return unsigned in database type name when necessary (#1238)
    • Add API to express like a --ssl-mode=PREFERRED MySQL client (#1370)
    • Add SQLState to MySQLError (#1321)

    Bugfixes:

    • Fix parsing 0 year. (#1257)

    Version 1.6 (2021-04-01)

    Changes:

    • Migrate the CI service from travis-ci to GitHub Actions (#1176, #1183, #1190)
    • NullTime is deprecated (#960, #1144)
    • Reduce allocations when building SET command (#1111)
    • Performance improvement for time formatting (#1118)
    • Performance improvement for time parsing (#1098, #1113)

    New Features:

    • Implement driver.Validator interface (#1106, #1174)
    • Support returning uint64 from Valuer in ConvertValue (#1143)
    • Add json.RawMessage for converter and prepared statement (#1059)
    • Interpolate json.RawMessage as string (#1058)
    • Implements CheckNamedValue (#1090)

    Bugfixes:

    • Stop rounding times (#1121, #1172)
    • Put zero filler into the SSL handshake packet (#1066)
    • Fix checking cancelled connections back into the connection pool (#1095)
    • Fix remove last 0 byte for mysql_old_password when password is empty (#1133)

    Version 1.5 (2020-01-07)

    Changes:

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • CLI not working anymore on docker compose + M1 chip

    CLI not working anymore on docker compose + M1 chip

    I run the CLI inside a docker compose container on a 2021 M1 chip macbook pro but recently I get this error and I'm not able anymore to run the command

     qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
    

    Here is an example of the container

    fixtures:
      container_name: "load-fixtures"
      image: golang:1.19-alpine
      working_dir: /data
      env_file:
        - .env
      volumes:
        - "./fixtures:/data/fixtures"
        - "./scripts/load-fixtures.sh:/data/load-fixtures.sh"
      entrypoint: ["./load-fixtures.sh"]
      depends_on:
        - db
    

    When I run this container and install the testfixtures binary using wget and latest release, I get the error above.

    I test using alpine and golang alpine images without success.

    Version used:

    • testfixtures v3.8.1
    • docker 20.10.21
    • docker compose 2.12.2
    • alpine 3.17
  • Dump output for a string is read as a date

    Dump output for a string is read as a date

    The dump command generates the correct string for a field. For example:

    - id: 1
      some_code: "20200909"
    

    How ever when loading the dump file, due to https://github.com/go-testfixtures/testfixtures/blob/fa3fb89109b0b31957a5430cef3e93e535de362b/time.go#L25 tryStrToDate function, it converts it to date.

    Maybe to always add RAW= prefix for a string in the dump file?

  • I want to create array type test data in postgres, but I’m struggling

    I want to create array type test data in postgres, but I’m struggling

    I created the following yml file and ran it, but I am getting an error

    users.yml

    - id: 1
      warehouse_ids:
        - 1
        - 2
    

    error

    &testfixtures.InsertError{
      Err: &pq.Error{
        Severity:         "ERROR",
        Code:             "22P02",
        Message:          "malformed array literal: \"[1,2]\"",
        Detail:           "Missing \"]\" after array dimensions.",
        Hint:             "",
        Position:         "",
        InternalPosition: "",
        InternalQuery:    "",
        Where:            "",
        Schema:           "",
        Table:            "",
        Column:           "",
        DataTypeName:     "",
        Constraint:       "",
        File:             "arrayfuncs.c",
        Line:             "292",
        Routine:          "array_in",
      },
       SQL:    "INSERT INTO \"users\" (\"id\", \"warehouse_ids\") VALUES ($1, $2)",
     Params: []interface {}{
        1,
        "[1,2]",
      },
    }
    

    How can I solve this?

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.
Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

GoConvey is awesome Go testing Welcome to GoConvey, a yummy Go testing tool for gophers. Works with go test. Use it in the terminal or browser accordi

Dec 30, 2022
Clean database for testing, inspired by database_cleaner for Ruby

DbCleaner Clean database for testing, inspired by database_cleaner for Ruby. It uses flock syscall under the hood to make sure the test can runs in pa

Nov 17, 2022
Run a real Postgres database locally on Linux, OSX or Windows as part of another Go application or test
Run a real Postgres database locally on Linux, OSX or Windows as part of another Go application or test

embedded-postgres Run a real Postgres database locally on Linux, OSX or Windows as part of another Go application or test. When testing this provides

Dec 27, 2022
Rr-e2e-tests - Roadrunner end-to-end tests repository
Rr-e2e-tests - Roadrunner end-to-end tests repository

RoadRunner end-to-end plugins tests License: The MIT License (MIT). Please see L

Dec 15, 2022
A next-generation testing tool. Orion provides a powerful DSL to write and automate your acceptance tests

Orion is born to change the way we implement our acceptance tests. It takes advantage of HCL from Hashicorp t o provide a simple DSL to write the acceptance tests.

Aug 31, 2022
Terratest is a Go library that makes it easier to write automated tests for your infrastructure code.

Terratest is a Go library that makes it easier to write automated tests for your infrastructure code. It provides a variety of helper functions and patterns for common infrastructure testing tasks,

Dec 30, 2022
go-test-trace is like go test but it also generates distributed traces.
go-test-trace is like go test but it also generates distributed traces.

go-test-trace go-test-trace is like go test but it also generates distributed traces. Generated traces are exported in OTLP to a OpenTelemetry collect

Jan 5, 2023
Flugel Test Documentation for steps to run and test the automatio
Flugel Test Documentation for steps to run and test the automatio

Flugel Test Documentation Documentation for steps to run and test the automation #Test-01 1 - Local Test Using Terratest (End To End) 1- By runing " t

Nov 13, 2022
Test-assignment - Test assignment with golang
Test-assignment - Test assignment with golang

test-assignment We have a two steam of data and we need to save it in the map: I

Jan 19, 2022
This repository includes consumer driven contract test for provider, unit test and counter api.

This repository includes consumer driven contract test for provider, unit test and counter api.

Feb 1, 2022
Generate a test coverage badge like this one for your go projects.

coverage-badge-go ?? Generate a test coverage badge like this one for your go projects. Usage on: pull_request: branches: -

Dec 11, 2022
Library created for testing JSON against patterns.

Gomatch Library created for testing JSON against patterns. The goal was to be able to validate JSON focusing only on parts essential in given test cas

Oct 28, 2022
Tesuto - a little library for testing against HTTP services

tesuto import "github.com/guregu/tesuto" tesuto is a little library for testing

Jan 18, 2022
Sql mock driver for golang to test database interactions

Sql driver mock for Golang sqlmock is a mock library implementing sql/driver. Which has one and only purpose - to simulate any sql driver behavior in

Dec 31, 2022
Cloud Spanner load generator to load test your application and pre-warm the database before launch

GCSB GCSB Quickstart Create a test table Load data into table Run a load test Operations Load Single table load Multiple table load Loading into inter

Nov 30, 2022
Package for comparing Go values in tests

Package for equality of Go values This package is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two

Dec 29, 2022
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Dec 22, 2022
Record and replay your HTTP interactions for fast, deterministic and accurate tests

go-vcr go-vcr simplifies testing by recording your HTTP interactions and replaying them in future runs in order to provide fast, deterministic and acc

Dec 25, 2022
Testing framework for Go. Allows writing self-documenting tests/specifications, and executes them concurrently and safely isolated. [UNMAINTAINED]

GoSpec GoSpec is a BDD-style testing framework for the Go programming language. It allows writing self-documenting tests/specs, and executes them in p

Nov 28, 2022