Files
gocqlx/cmd/schemagen/schemagen_test.go

102 lines
2.0 KiB
Go
Raw Normal View History

2021-11-13 13:55:44 +02:00
package main
import (
"flag"
2021-11-13 13:55:44 +02:00
"fmt"
"io/ioutil"
2021-11-13 13:55:44 +02:00
"os"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/scylladb/gocqlx/v2/gocqlxtest"
)
2021-11-13 13:55:44 +02:00
var flagUpdate = flag.Bool("update", false, "update golden file")
2021-11-13 13:55:44 +02:00
func TestSchemagen(t *testing.T) {
flag.Parse()
2021-11-13 13:55:44 +02:00
createTestSchema(t)
b := runSchemagen(t, "foobar")
2021-11-13 13:55:44 +02:00
const goldenFile = "testdata/models.go.txt"
if *flagUpdate {
if err := ioutil.WriteFile(goldenFile, b, os.ModePerm); err != nil {
t.Fatal(err)
}
2021-11-13 13:55:44 +02:00
}
golden, err := ioutil.ReadFile(goldenFile)
2021-11-13 13:55:44 +02:00
if err != nil {
t.Fatal(err)
2021-11-13 13:55:44 +02:00
}
if diff := cmp.Diff(string(golden), string(b)); diff != "" {
t.Fatalf(diff)
2021-11-13 13:55:44 +02:00
}
}
func createTestSchema(t *testing.T) {
t.Helper()
2021-11-13 13:55:44 +02:00
session := gocqlxtest.CreateSession(t)
defer session.Close()
err := session.ExecStmt(`CREATE KEYSPACE IF NOT EXISTS schemagen WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}`)
2021-11-13 13:55:44 +02:00
if err != nil {
t.Fatal("create keyspace:", err)
}
err = session.ExecStmt(`CREATE TABLE IF NOT EXISTS schemagen.songs (
2021-11-13 13:55:44 +02:00
id uuid PRIMARY KEY,
title text,
album text,
artist text,
tags set<text>,
data blob)`)
if err != nil {
t.Fatal("create table:", err)
}
err = session.ExecStmt(`CREATE TYPE IF NOT EXISTS schemagen.album (
name text,
songwriters set<text>,)`)
if err != nil {
t.Fatal("create type:", err)
}
err = session.ExecStmt(`CREATE TABLE IF NOT EXISTS schemagen.playlists (
2021-11-13 13:55:44 +02:00
id uuid,
title text,
album frozen<album>,
2021-11-13 13:55:44 +02:00
artist text,
song_id uuid,
PRIMARY KEY (id, title, album, artist))`)
if err != nil {
t.Fatal("create table:", err)
}
}
func runSchemagen(t *testing.T, pkgname string) []byte {
t.Helper()
2021-11-13 13:55:44 +02:00
dir, err := os.MkdirTemp("", "gocqlx")
2021-11-13 13:55:44 +02:00
if err != nil {
t.Fatal(err)
}
keyspace := "schemagen"
2021-11-13 13:55:44 +02:00
flagKeyspace = &keyspace
flagPkgname = &pkgname
flagOutput = &dir
2021-11-13 13:55:44 +02:00
if err := schemagen(); err != nil {
t.Fatalf("schemagen() error %s", err)
2021-11-13 13:55:44 +02:00
}
f := fmt.Sprintf("%s/%s.go", dir, pkgname)
b, err := os.ReadFile(f)
2021-11-13 13:55:44 +02:00
if err != nil {
t.Fatalf("%s: %s", f, err)
2021-11-13 13:55:44 +02:00
}
return b
2021-11-13 13:55:44 +02:00
}