Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(cli-test): add test framework (#661)
qsliu17ad5090a0d5
diff --git a/bin/bb/cmd/dump.go b/bin/bb/cmd/dump.goindex da1d7ce025..2293905dec 100644--- a/bin/bb/cmd/dump.go+++ b/bin/bb/cmd/dump.go@@ -4,9 +4,13 @@ package cmdimport ("context""fmt"+ "io""os""github.com/bytebase/bytebase/plugin/db"++ // install mysql driver.+ _ "github.com/bytebase/bytebase/plugin/db/mysql""github.com/spf13/cobra")@@ -39,14 +43,23 @@ var (SslCert: sslCert,SslKey: sslKey,}- return dumpDatabase(context.Background(), databaseType, username, password, hostname, port, database, file, tlsCfg, schemaOnly)+ out := cmd.OutOrStdout()+ if file != "" {+ f, err := os.Create(file)+ if err != nil {+ return fmt.Errorf("failed to create dump file %s, got error: %w", file, err)+ }+ defer f.Close()+ out = f+ }+ return dumpDatabase(context.Background(), databaseType, username, password, hostname, port, database, out, tlsCfg, schemaOnly)},})// dumpDatabase exports the schema of a database instance.// When file isn't specified, the schema will be exported to stdout.-func dumpDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TLSConfig, schemaOnly bool) error {+func dumpDatabase(ctx context.Context, databaseType, username, password, hostname, port, database string, out io.Writer, tlsCfg db.TLSConfig, schemaOnly bool) error {var dbType db.Typeswitch databaseType {case "mysql":@@ -79,15 +92,6 @@ func dumpDatabase(ctx context.Context, databaseType, username, password, hostnam}defer db.Close(ctx)- out := os.Stdout- if file != "" {- out, err = os.Create(file)- if err != nil {- return fmt.Errorf("failed to create dump file %s, got error: %w", file, err)- }- }- defer out.Close()-if err := db.Dump(ctx, database, out, schemaOnly); err != nil {return fmt.Errorf("failed to create dump %s, got error: %w", file, err)}diff --git a/bin/bb/cmd/dump_test.go b/bin/bb/cmd/dump_test.gonew file mode 100644index 0000000000..bee4c31db9--- /dev/null+++ b/bin/bb/cmd/dump_test.go@@ -0,0 +1,42 @@+package cmd++import (+ "fmt"+ "os"+ "testing"++ // Embeded expected output.+ _ "embed"++ "github.com/bytebase/bytebase/resources/mysql"+)++var (+ //go:embed testdata/expected/test_dump_todo+ expectedTodo string+)++func TestDump(t *testing.T) {+ mysql, stop := mysql.SetupTestInstance(t, 13306)+ defer stop()++ t.Log("Importing MySQL data...")+ if err := mysql.Import("testdata/mysql_test_schema", os.Stdout, os.Stderr); err != nil {+ t.Fatal(err)+ }++ tt := []testTable{+ {+ args: []string{+ "dump",+ "--type", "mysql",+ "--username", "root",+ "--hostname", "localhost",+ "--port", fmt.Sprint(mysql.Port()),+ "--database", "bytebase_test_todo",+ },+ expected: expectedTodo,+ },+ }+ tableTest(t, tt)+}diff --git a/bin/bb/cmd/root_test.go b/bin/bb/cmd/root_test.goindex 38d34c0968..1a264ab2eb 100644--- a/bin/bb/cmd/root_test.go+++ b/bin/bb/cmd/root_test.go@@ -5,9 +5,16 @@ import ("strings""testing"+ _ "github.com/go-sql-driver/mysql"+ "github.com/google/go-cmp/cmp""github.com/spf13/cobra"+ "go.uber.org/zap")+func init() {+ logger = zap.NewNop()+}+func execute(t *testing.T, cmd *cobra.Command, args ...string) (string, error) {t.Helper()@@ -34,27 +41,15 @@ func tableTest(t *testing.T, tables []testTable) {if err != tc.expectedErr {t.Errorf(`"> bb %v"got unexpected error:->>>>>>>>>>-%v-<<<<<<<<<<-want:->>>>>>>>>>-%v-<<<<<<<<<<-`, strings.Join(tc.args, " "), err, tc.expectedErr)+%s+`, strings.Join(tc.args, " "), cmp.Diff(err, tc.expectedErr))}if actual != tc.expected {t.Errorf(`"> bb %v"got unexpected output:->>>>>>>>>>-%v-<<<<<<<<<<-want:->>>>>>>>>>-%v-<<<<<<<<<<-`, strings.Join(tc.args, " "), actual, tc.expected)+%s+`, strings.Join(tc.args, " "), cmp.Diff(actual, tc.expected))}}}diff --git a/bin/bb/cmd/testdata/expected/test_dump_todo b/bin/bb/cmd/testdata/expected/test_dump_todonew file mode 100644index 0000000000..b094db79e4--- /dev/null+++ b/bin/bb/cmd/testdata/expected/test_dump_todo@@ -0,0 +1,28 @@+--+-- Table structure for `author`+--+CREATE TABLE `author` (+ `id` int NOT NULL AUTO_INCREMENT,+ `name` varchar(255) DEFAULT NULL COMMENT 'name of the author',+ PRIMARY KEY (`id`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;+++--+-- Table structure for `todo`+--+CREATE TABLE `todo` (+ `id` int NOT NULL AUTO_INCREMENT,+ `name` varchar(255) DEFAULT NULL COMMENT 'name of the todo',+ `content` text,+ `author_id` int DEFAULT NULL,+ `created_ts` bigint NOT NULL,+ `updated_ts` bigint NOT NULL,+ PRIMARY KEY (`id`),+ KEY `author_id` (`author_id`),+ KEY `name` (`name`) COMMENT 'index on todo.name',+ KEY `created_ts` (`created_ts`) COMMENT 'index on todo.created_ts',+ CONSTRAINT `todo_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;++diff --git a/bin/bb/cmd/testdata/mysql_test_schema/1_todo.sql b/bin/bb/cmd/testdata/mysql_test_schema/1_todo.sqlnew file mode 100644index 0000000000..aebba355f7--- /dev/null+++ b/bin/bb/cmd/testdata/mysql_test_schema/1_todo.sql@@ -0,0 +1,23 @@+-- Covered objects:+-- - Table+-- - Index++CREATE DATABASE bytebase_test_todo;++-- Table and Index+CREATE TABLE bytebase_test_todo.author (+ id INTEGER PRIMARY KEY AUTO_INCREMENT,+ name VARCHAR(255) COMMENT 'name of the author'+);++CREATE TABLE bytebase_test_todo.todo (+ id INTEGER PRIMARY KEY AUTO_INCREMENT,+ name VARCHAR(255) COMMENT 'name of the todo',+ content TEXT,+ author_id INTEGER,+ created_ts BIGINT NOT NULL,+ updated_ts BIGINT NOT NULL,+ FOREIGN KEY (author_id) REFERENCES author (id) ON DELETE CASCADE,+ INDEX (name) COMMENT 'index on todo.name',+ INDEX (created_ts) COMMENT 'index on todo.created_ts'+);diff --git a/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sql b/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sqlnew file mode 100644index 0000000000..b9b6b8ff31--- /dev/null+++ b/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sql@@ -0,0 +1,104 @@+-- Covered objects:+-- - Table+-- - Index+-- - View+-- - Procedure+-- - Function+-- - Event+-- - Trigger++CREATE DATABASE bytebase_test_blog;++-- Table and Index+CREATE TABLE bytebase_test_blog.author (+ id INTEGER PRIMARY KEY AUTO_INCREMENT,+ name VARCHAR(255) COMMENT 'name of the author',+ email VARCHAR(255),+ coin INTEGER DEFAULT 0 COMMENT 'coin can be earned by posting posts, comments'+);++CREATE TABLE bytebase_test_blog.post (+ id INTEGER PRIMARY KEY AUTO_INCREMENT,+ created_ts BIGINT NOT NULL,+ updated_ts BIGINT NOT NULL,+ author_id INTEGER NOT NULL,+ name VARCHAR(255) COMMENT 'name of the post',+ content TEXT,+ like_count INTEGER DEFAULT 0,+ FOREIGN KEY (author_id) REFERENCES author (id) ON DELETE CASCADE,+ INDEX (name),+ INDEX (created_ts)+);++CREATE TABLE bytebase_test_blog.comment (+ id INTEGER PRIMARY KEY AUTO_INCREMENT,+ created_ts BIGINT NOT NULL,+ updated_ts BIGINT NOT NULL,+ post_id INTEGER,+ author_id INTEGER,+ content TEXT,+ FOREIGN KEY (post_id) REFERENCES post (id) ON DELETE CASCADE,+ FOREIGN KEY (author_id) REFERENCES author (id) ON DELETE CASCADE,+ INDEX (created_ts)+);++-- View+CREATE VIEW bytebase_test_blog.top_like_post AS+SELECT+ *+FROM+ bytebase_test_blog.post+ORDER BY+ like_count DESC+LIMIT 10;++-- Procedure+DELIMITER //+CREATE PROCEDURE bytebase_test_blog.author_post_count (IN author_id INT, OUT post_count INT)+BEGIN+ SELECT+ COUNT(*) INTO post_count+ FROM+ author, post+ WHERE+ author.id = post.author_id AND author.id = author_id;+END //+DELIMITER ;++-- Function+DELIMITER //+CREATE FUNCTION bytebase_test_blog.author_comment_count (author_id INT)+ RETURNS INT DETERMINISTIC+BEGIN+DECLARE+ comment_count INT DEFAULT 0;+ SELECT+ COUNT(*) INTO comment_count+ FROM+ author,+ COMMENT+ WHERE+ author.id = comment.author_id+ AND author.id = author_id;+ RETURN comment_count;+END //+DELIMITER ;++-- Event+DELIMITER //+CREATE EVENT bytebase_test_blog.increase_author_coin_daily ON SCHEDULE EVERY 1 DAY DO UPDATE author+SET coin = coin + 1;++-- Trigger+CREATE TRIGGER bytebase_test_blog.update_post_updated_ts+ AFTER UPDATE ON post+ FOR EACH ROW+BEGIN+ UPDATE+ post+ SET+ updated_ts = NOW()+ WHERE+ id = OLD.id;+END //+DELIMITER ;diff --git a/go.mod b/go.modindex 2ad3631073..814f59d591 100644--- a/go.mod+++ b/go.mod@@ -8,6 +8,7 @@ require (github.com/casbin/casbin/v2 v2.40.6github.com/go-sql-driver/mysql v1.6.0github.com/golang-jwt/jwt/v4 v4.0.0+ github.com/google/go-cmp v0.5.6github.com/google/jsonapi v1.0.0github.com/google/uuid v1.3.0github.com/gosimple/slug v1.10.0@@ -24,6 +25,8 @@ require (github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8go.uber.org/zap v1.19.1golang.org/x/crypto v0.0.0-20210817164053-32db794688a5+ golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect+ golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99 // indirect)// copied from pingcap/tidbdiff --git a/go.sum b/go.sumindex a9facb1885..e0c2edf1cf 100644--- a/go.sum+++ b/go.sum@@ -1098,8 +1098,9 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxgolang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=-golang.org/x/net v0.0.0-20210913180222-943fd674d43e h1:+b/22bPvDYt4NPDcy4xAGCmON713ONAWFeY3Z7I3tR8=golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=+golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk=+golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=@@ -1205,9 +1206,12 @@ golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBcgolang.org/x/sys v0.0.0-20210818153620-00dd8d7831e7/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20210910150752-751e447fb3d0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ=golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99 h1:Us899Z5PCfOrSgeCYWobI1/bSigAz9Rhf8+fz5Grkzc=+golang.org/x/sys v0.0.0-20220224003255-dbe011f71a99/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=diff --git a/resources/mysql/mysql.go b/resources/mysql/mysql.goindex fd20c6790f..a39b9e0455 100644--- a/resources/mysql/mysql.go+++ b/resources/mysql/mysql.go@@ -1,6 +1,7 @@package mysqlimport (+ "bytes""database/sql""fmt""io"@@ -8,6 +9,7 @@ import ("os/exec""path/filepath""runtime"+ "testing""time""github.com/bytebase/bytebase/resources/utils"@@ -104,22 +106,9 @@ func Install(basedir, datadir, user string) (*Instance, error) {basedir = filepath.Join(basedir, version)- socket, err := os.Create(filepath.Join(basedir, "mysql.sock"))- if err != nil {- return nil, err- }- socket.Close()-- pidFile, err := os.Create(filepath.Join(basedir, "mysql.pid"))- if err != nil {- return nil, err- }- pidFile.Close()-const configFmt = `[mysqld]basedir=%sdatadir=%s-pid-file=mysql.pidsocket=mysql.sockuser=%s`@@ -147,3 +136,76 @@ user=%sdatadir: datadir,}, nil}++// SetupTestInstance installs and starts a mysql instance for testing,+// returns the instance and the stop function.+func SetupTestInstance(t *testing.T, port int) (*Instance, func()) {+ basedir, datadir := t.TempDir(), t.TempDir()+ t.Log("Installing Mysql...")+ i, err := Install(basedir, datadir, "root")+ if err != nil {+ t.Fatal(err)+ }+ t.Log("Starting Mysql...")+ if err := i.Start(port, os.Stdout, os.Stderr, 60); err != nil {+ t.Fatal(err)+ }++ stopFn := func() {+ t.Log("Stopping Mysql...")+ if err := i.Stop(os.Stdout, os.Stderr); err != nil {+ t.Fatal(err)+ }+ }++ return i, stopFn+}++// Import executes sql script in the given path on the instance.+// If the path is a directory, it imports all sql scripts in the directory recursively.+func (i *Instance) Import(path string, stdout, stderr io.Writer) error {+ var buf bytes.Buffer+ if err := cat(path, &buf); err != nil {+ return err+ }++ cmd := exec.Command(filepath.Join(i.basedir, "bin", "mysql"),+ "--user=root",+ "--protocol=TCP",+ "--host=localhost",+ fmt.Sprintf("--port=%d", i.port),+ )+ cmd.Stdin = bytes.NewReader(buf.Bytes())+ cmd.Stdout = stdout+ cmd.Stderr = stderr+ return cmd.Run()+}++func cat(path string, out io.Writer) error {+ fi, err := os.Stat(path)+ if err != nil {+ return err+ }++ if fi.IsDir() {+ entries, err := os.ReadDir(path)+ if err != nil {+ return err+ }+ for _, entry := range entries {+ if err := cat(filepath.Join(path, entry.Name()), out); err != nil {+ return err+ }+ }+ } else {+ f, err := os.Open(path)+ if err != nil {+ return err+ }+ defer f.Close()+ if _, err = io.Copy(out, f); err != nil {+ return err+ }+ }+ return nil+}