Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add testcontainers #8

Merged
merged 3 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/gencoder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
_ "github.com/sijms/go-ora/v2"
)

var version = "0.0.3"
var version = "0.0.4"

func main() {

Expand Down
45 changes: 45 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,66 @@ require (
github.com/sijms/go-ora/v2 v2.8.21
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.9.0
github.com/testcontainers/testcontainers-go/modules/mysql v0.33.0
github.com/testcontainers/testcontainers-go/modules/postgres v0.33.0
github.com/xo/dburl v0.23.2
gopkg.in/yaml.v3 v3.0.1
)

require (
dario.cat/mergo v1.0.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/containerd/containerd v1.7.18 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/cpuguy83/dockercfg v0.3.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/docker/docker v27.1.1+incompatible // indirect
github.com/docker/go-connections v0.5.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/patternmatcher v0.6.0 // indirect
github.com/moby/sys/sequential v0.5.0 // indirect
github.com/moby/sys/user v0.1.0 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/shirou/gopsutil/v3 v3.23.12 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/testcontainers/testcontainers-go v0.33.0 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
go.opentelemetry.io/otel v1.24.0 // indirect
go.opentelemetry.io/otel/metric v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
)
190 changes: 187 additions & 3 deletions go.sum

Large diffs are not rendered by default.

9 changes: 4 additions & 5 deletions pkg/cmd/generate/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package generate

import (
"github.com/DanielLiu1123/gencoder/pkg/model"
"reflect"
"github.com/stretchr/testify/assert"
"testing"
)

func Test_parseBlocks(t *testing.T) {
func TestParseBlocks(t *testing.T) {
type args struct {
cfg *model.Config
content string
Expand Down Expand Up @@ -53,9 +53,8 @@ gencoder block end: block2`,
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := parseBlocks(tt.args.cfg, tt.args.content); !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseBlocks() = %v, want %v", got, tt.want)
}
got := parseBlocks(tt.args.cfg, tt.args.content)
assert.Equal(t, tt.want, got)
})
}
}
40 changes: 40 additions & 0 deletions pkg/cmd/init/init_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package init

import (
"github.com/DanielLiu1123/gencoder/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"path/filepath"
"testing"
)

func TestNewCmdInit(t *testing.T) {
tempDir, err := os.MkdirTemp("", "test")
require.NoError(t, err)
defer os.RemoveAll(tempDir)

err = os.Chdir(tempDir)
require.NoError(t, err)

cmd := NewCmdInit(&model.GlobalOptions{})

_, err = cmd.ExecuteC()
require.NoError(t, err)

configFilePath := filepath.Join(tempDir, "gencoder.yaml")
_, err = os.Stat(configFilePath)
assert.NoError(t, err, "gencoder.yaml should be created")

templatesDirPath := filepath.Join(tempDir, "templates")
_, err = os.Stat(templatesDirPath)
assert.NoError(t, err, "templates directory should be created")

entityJavaFilePath := filepath.Join(templatesDirPath, "entity.java.hbs")
_, err = os.Stat(entityJavaFilePath)
assert.NoError(t, err, "entity.java.hbs should be created")

javaTypePartialPath := filepath.Join(templatesDirPath, "java_type.partial.hbs")
_, err = os.Stat(javaTypePartialPath)
assert.NoError(t, err, "java_type.partial.hbs should be created")
}
80 changes: 29 additions & 51 deletions pkg/db/mysql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,64 +2,46 @@ package db

import (
"context"
"fmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/modules/mysql"
"github.com/xo/dburl"
"os/exec"
"testing"
"time"

_ "github.com/go-sql-driver/mysql"
)

// Helper function to check if Docker is available
func isDockerAvailable() bool {
cmd := exec.Command("docker", "info")
err := cmd.Run()
return err == nil
}

// Helper function to start a MySQL container
func startMySQLContainer() (string, error) {
const containerID = "gencoder_test_mysql"
cmd := exec.Command("docker", "run", "--name", containerID, "-e", "MYSQL_ROOT_PASSWORD=root", "-e", "MYSQL_DATABASE=testdb", "-p", "3306:3306", "-d", "mysql:latest")
if err := cmd.Run(); err != nil {
return "", err
}
return containerID, nil
}

// Helper function to stop and remove the MySQL container
func stopContainer(containerID string) {
err := exec.Command("docker", "stop", containerID).Run()
if err != nil {
panic(err)
}
err = exec.Command("docker", "rm", containerID).Run()
if err != nil {
panic(err)
}
}

func TestGenMySQLTable(t *testing.T) {
if !isDockerAvailable() {
t.Log("Docker is not available. Skipping test.")
return
}

containerID, err := startMySQLContainer()
err := exec.Command("docker", "info").Run()
if err != nil {
t.Fatalf("Failed to start MySQL container: %s", err)
t.Skip("Docker not available, skipping MySQL tests")
}

defer stopContainer(containerID)

// Wait for MySQL to initialize
time.Sleep(10 * time.Second)

db, err := dburl.Open("mysql://root:root@localhost:3306/testdb")
if err != nil {
t.Fatalf("Failed to open database connection: %s", err)
}
ctx := context.Background()
mysqlContainer, err := mysql.Run(ctx,
"mysql:latest",
mysql.WithDatabase("testdb"),
mysql.WithUsername("root"),
mysql.WithPassword("root"),
)
require.NoError(t, err)
defer func() {
if err := mysqlContainer.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
}()

host, err := mysqlContainer.Host(ctx)
require.NoError(t, err)
port, err := mysqlContainer.MappedPort(ctx, "3306")
require.NoError(t, err)

dsn := fmt.Sprintf("mysql://root:root@%s:%s/testdb", host, port.Port())
db, err := dburl.Open(dsn)
require.NoError(t, err)

_, err = db.Exec(`CREATE TABLE testdb.user (
id INT AUTO_INCREMENT PRIMARY KEY,
Expand All @@ -77,17 +59,13 @@ func TestGenMySQLTable(t *testing.T) {
INDEX idx_status_created (status, created_at),
INDEX idx_full_name (first_name, last_name)
) COMMENT='User account information';`)
if err != nil {
t.Fatalf("Failed to create test table: %s", err)
}
require.NoError(t, err)

schema := "testdb"
table := "user"

tb, err := GenMySQLTable(context.Background(), db, schema, table, []string{"deleted_at"})
if err != nil {
t.Fatalf("Failed to generate MySQL table: %s", err)
}
require.NoError(t, err)

assert.NotNil(t, tb)
assert.Equal(t, "testdb", tb.Schema)
Expand Down
58 changes: 29 additions & 29 deletions pkg/db/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,46 @@ package db

import (
"context"
"fmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/xo/dburl"
"os/exec"
"testing"
"time"

_ "github.com/lib/pq"
)

func TestGenPostgresTable(t *testing.T) {
if !isDockerAvailable() {
t.Log("Docker is not available. Skipping TestGenPostgresTable test.")
return
}

containerID, err := startPostgresContainer()
err := exec.Command("docker", "info").Run()
if err != nil {
t.Fatalf("Failed to start Postgres container: %s", err)
t.Skip("Docker not available, skipping MySQL tests")
}
defer stopContainer(containerID)

time.Sleep(5 * time.Second)
ctx := context.Background()
postgresContainer, err := postgres.Run(ctx,
"postgres:latest",
postgres.WithDatabase("testdb"),
postgres.WithUsername("root"),
postgres.WithPassword("root"),
postgres.BasicWaitStrategies(),
)
require.NoError(t, err)
defer func() {
if err := postgresContainer.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
}()

db, err := dburl.Open("postgres://root:root@localhost:5432/testdb?sslmode=disable")
if err != nil {
t.Fatalf("Failed to open database connection: %s", err)
}
host, err := postgresContainer.Host(ctx)
require.NoError(t, err)
port, err := postgresContainer.MappedPort(ctx, "5432")
require.NoError(t, err)

dsn := fmt.Sprintf("postgres://root:root@%s:%s/testdb?sslmode=disable", host, port.Port())
db, err := dburl.Open(dsn)
require.NoError(t, err)

_, err = db.Exec(`CREATE TABLE testdb.public."user" (
id SERIAL PRIMARY KEY,
Expand All @@ -55,17 +68,13 @@ COMMENT ON COLUMN testdb.public."user".updated_at IS 'Record update timestamp';
COMMENT ON COLUMN testdb.public."user".status IS 'Account status';
COMMENT ON COLUMN testdb.public."user".deleted_at IS 'Record deletion timestamp';
COMMENT ON TABLE testdb.public."user" IS 'User account information';`)
if err != nil {
t.Fatalf("Failed to create test table: %s", err)
}
require.NoError(t, err)

schema := "public"
table := "user"

tb, err := GenPostgresTable(context.Background(), db, schema, table, []string{"deleted_at"})
if err != nil {
t.Fatalf("Failed to generate Postgres table: %s", err)
}
require.NoError(t, err)

assert.NotNil(t, tb)
assert.Equal(t, "public", tb.Schema)
Expand All @@ -78,12 +87,3 @@ COMMENT ON TABLE testdb.public."user" IS 'User account information';`)

assert.Equal(t, 5, len(tb.Indexes))
}

func startPostgresContainer() (string, error) {
const containerID = "gencoder_test_postgres"
cmd := exec.Command("docker", "run", "--name", containerID, "-e", "POSTGRES_USER=root", "-e", "POSTGRES_PASSWORD=root", "-e", "POSTGRES_DB=testdb", "-p", "5432:5432", "-d", "postgres:latest")
if err := cmd.Run(); err != nil {
return "", err
}
return containerID, nil
}
Loading