Skip to content

Mysql

package mysql

import (
    "context"

    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/wait"
)

// mysqlContainer represents the mysql container type used in the module
type mysqlContainer struct {
    testcontainers.Container
}

// setupMysql creates an instance of the mysql container type
func setupMysql(ctx context.Context) (*mysqlContainer, error) {
    req := testcontainers.ContainerRequest{
        Image:        "mysql:8",
        ExposedPorts: []string{"3306/tcp", "33060/tcp"},
        Env: map[string]string{
            "MYSQL_ROOT_PASSWORD": "password",
            "MYSQL_DATABASE":      "database",
        },
        WaitingFor: wait.ForAll(
            wait.ForLog("port: 3306  MySQL Community Server - GPL"),
            wait.ForListeningPort("3306/tcp"),
        ),
    }
    container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
        ContainerRequest: req,
        Started:          true,
    })
    if err != nil {
        return nil, err
    }

    return &mysqlContainer{Container: container}, nil
}
package mysql

import (
    "context"
    "database/sql"
    "fmt"
    "testing"

    // Import mysql into the scope of this package (required)
    _ "github.com/go-sql-driver/mysql"
)

func TestMysql(t *testing.T) {
    ctx := context.Background()

    container, err := setupMysql(ctx)
    if err != nil {
        t.Fatal(err)
    }

    // Clean up the container after the test is complete
    t.Cleanup(func() {
        if err := container.Terminate(ctx); err != nil {
            t.Fatalf("failed to terminate container: %s", err)
        }
    })

    // perform assertions

    host, _ := container.Host(ctx)

    p, _ := container.MappedPort(ctx, "3306/tcp")
    port := p.Int()

    connectionString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=skip-verify",
        "root", "password", host, port, "database")

    db, err := sql.Open("mysql", connectionString)
    if err != nil {
        t.Fatal(err)
    }
    defer db.Close()

    if err = db.Ping(); err != nil {
        t.Errorf("error pinging db: %+v\n", err)
    }
    _, err = db.Exec("CREATE TABLE IF NOT EXISTS a_table ( \n" +
        " `col_1` VARCHAR(128) NOT NULL, \n" +
        " `col_2` VARCHAR(128) NOT NULL, \n" +
        " PRIMARY KEY (`col_1`, `col_2`) \n" +
        ")")
    if err != nil {
        t.Errorf("error creating table: %+v\n", err)
    }
}