Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

test(github): add VCS integration tests (#2070)

Joe Chen3173b84a7b77
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index c6ced37f07..f2397f09df 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -240,15 +240,18 @@ func (p *Provider) TryLogin(ctx context.Context, oauthCtx common.OauthContext, i
return p.fetchUserInfo(ctx, oauthCtx, instanceURL, "user")
}
+// CommitAuthor represents a GitHub API response for a commit author.
+type CommitAuthor struct {
+ // Date expects corresponding JSON value is a string in RFC 3339 format,
+ // see https://pkg.go.dev/time#Time.MarshalJSON.
+ Date time.Time `json:"date"`
+ Name string `json:"name"`
+}
+
// Commit represents a GitHub API response for a commit.
type Commit struct {
- SHA string `json:"sha"`
- Author struct {
- // Date expects corresponding JSON value is a string in RFC 3339 format,
- // see https://pkg.go.dev/time#Time.MarshalJSON.
- Date time.Time `json:"date"`
- Name string `json:"name"`
- } `json:"author"`
+ SHA string `json:"sha"`
+ Author CommitAuthor `json:"author"`
}
// FileCommit represents a GitHub API request for committing a file.
diff --git a/server/project.go b/server/project.go
index b154c9dfe8..cc2036b640 100644
--- a/server/project.go
+++ b/server/project.go
@@ -242,9 +242,13 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal request body for creating webhook for project ID: %d", repositoryCreate.ProjectID)).SetInternal(err)
}
case vcsPlugin.GitHubCom:
+ webhookHost := s.profile.BackendHost
+ if s.profile.BackendHost == "http://localhost" {
+ webhookHost = fmt.Sprintf("%s:%d", s.profile.BackendHost, s.profile.BackendPort)
+ }
webhookPost := github.WebhookCreateOrUpdate{
Config: github.WebhookConfig{
- URL: fmt.Sprintf("%s/%s/%s", s.profile.BackendHost, githubWebhookPath, repositoryCreate.WebhookEndpointID),
+ URL: fmt.Sprintf("%s/%s/%s", webhookHost, githubWebhookPath, repositoryCreate.WebhookEndpointID),
ContentType: "json",
Secret: repositoryCreate.WebhookSecretToken,
InsecureSSL: 1, // TODO: Allow user to specify this value through api.RepositoryCreate
diff --git a/tests/fake/github.go b/tests/fake/github.go
new file mode 100644
index 0000000000..eff03c9b6c
--- /dev/null
+++ b/tests/fake/github.go
@@ -0,0 +1,299 @@
+package fake
+
+import (
+ "bytes"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "path"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/labstack/echo/v4/middleware"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/plugin/vcs/github"
+)
+
+// GitHub is a fake implementation of GitHub VCS provider.
+type GitHub struct {
+ port int
+ echo *echo.Echo
+
+ client *http.Client
+
+ nextWebhookID int
+ repositories map[string]*repositoryData
+}
+
+type repositoryData struct {
+ webhooks []*github.WebhookCreateOrUpdate
+ // files is a map that the full file path is the key and the file content is the
+ // value.
+ files map[string]string
+}
+
+// NewGitHub creates a new fake implementation of GitHub VCS provider.
+func NewGitHub(port int) VCSProvider {
+ e := echo.New()
+ e.Use(middleware.Logger())
+ e.Use(middleware.Recover())
+
+ gh := &GitHub{
+ port: port,
+ echo: e,
+ client: &http.Client{},
+ nextWebhookID: 20210113,
+ repositories: make(map[string]*repositoryData),
+ }
+
+ g := e.Group("/api/v3")
+ g.POST("/repos/:owner/:repo/hooks", gh.createRepositoryWebhook)
+ g.GET("/repos/:owner/:repo/git/commits/:commitID", gh.getRepositoryCommit)
+ g.GET("/repos/:owner/:repo/git/trees/:ref", gh.getRepositoryTree)
+ g.GET("/repos/:owner/:repo/contents/:filePath", gh.readRepositoryFile)
+ g.PUT("/repos/:owner/:repo/contents/:filePath", gh.createRepositoryFile)
+ return gh
+}
+
+func (gh *GitHub) createRepositoryWebhook(c echo.Context) error {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating repository webhook: %v", err))
+ }
+
+ var webhookCreate github.WebhookCreateOrUpdate
+ if err = json.Unmarshal(body, &webhookCreate); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository webhook: %v", err))
+ }
+ r.webhooks = append(r.webhooks, &webhookCreate)
+
+ buf, err := json.Marshal(github.WebhookInfo{ID: gh.nextWebhookID})
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for creating repository webhook: %v", err))
+ }
+ gh.nextWebhookID++
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) getRepositoryCommit(c echo.Context) error {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ if _, ok := gh.repositories[repositoryID]; !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ buf, err := json.Marshal(
+ github.Commit{
+ SHA: "fake_github_commit_sha",
+ Author: github.CommitAuthor{
+ Date: time.Now(),
+ Name: "fake_github_author",
+ },
+ },
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository commit: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) getRepositoryTree(c echo.Context) error {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ var treeNodes []github.RepositoryTreeNode
+ for filePath := range r.files {
+ treeNodes = append(treeNodes,
+ github.RepositoryTreeNode{
+ Path: filePath,
+ Type: "blob",
+ },
+ )
+ }
+ buf, err := json.Marshal(
+ github.RepositoryTree{
+ Tree: treeNodes,
+ },
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository tree: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) readRepositoryFile(c echo.Context) error {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ filePathEscaped := c.Param("filePath")
+ filePath, err := url.QueryUnescape(filePathEscaped)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unescape file path %q: %v", filePathEscaped, err))
+ }
+
+ content, ok := r.files[filePath]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))
+ }
+
+ buf, err := json.Marshal(
+ github.File{
+ Encoding: "base64",
+ Size: int64(len(content)),
+ Name: path.Base(filePath),
+ Path: filePath,
+ Content: base64.StdEncoding.EncodeToString([]byte(content)),
+ SHA: "fake_github_commit_sha",
+ },
+ )
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body for getting repository file: %v", err))
+ }
+ return c.String(http.StatusOK, string(buf))
+}
+
+func (gh *GitHub) createRepositoryFile(c echo.Context) error {
+ repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return c.String(http.StatusNotFound, fmt.Sprintf("GitHub repository %q does not exist", repositoryID))
+ }
+
+ filePathEscaped := c.Param("filePath")
+ filePath, err := url.QueryUnescape(filePathEscaped)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unescape file path %q: %v", filePathEscaped, err))
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read request body for creating repository file: %v", err))
+ }
+
+ var fileCommit github.FileCommit
+ if err = json.Unmarshal(body, &fileCommit); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal request body for creating repository webhook: %v", err))
+ }
+
+ content, err := base64.StdEncoding.DecodeString(fileCommit.Content)
+ if err != nil {
+ return c.String(http.StatusBadRequest, fmt.Sprintf("failed to decode file content for %q: %v", filePathEscaped, err))
+ }
+ r.files[filePath] = string(content)
+ return nil
+}
+
+// Run starts the GitHub VCS provider server.
+func (gh *GitHub) Run() error {
+ return gh.echo.Start(fmt.Sprintf(":%d", gh.port))
+}
+
+// Close shuts down the GitHub VCS provider server.
+func (gh *GitHub) Close() error {
+ return gh.echo.Close()
+}
+
+// ListenerAddr returns the GitHub VCS provider server listener address.
+func (gh *GitHub) ListenerAddr() net.Addr {
+ return gh.echo.ListenerAddr()
+}
+
+// APIURL returns the GitHub VCS provider API URL.
+func (*GitHub) APIURL(instanceURL string) string {
+ return fmt.Sprintf("%s/api/v3", instanceURL)
+}
+
+// CreateRepository creates a GitHub repository with given ID.
+func (gh *GitHub) CreateRepository(id string) {
+ gh.repositories[id] = &repositoryData{
+ files: make(map[string]string),
+ }
+}
+
+// SendWebhookPush sends out a webhook for a push event for the GitHub
+// repository using given payload.
+func (gh *GitHub) SendWebhookPush(repositoryID string, payload []byte) error {
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return errors.Errorf("GitHub repository %q does not exist", repositoryID)
+ }
+
+ // Trigger all webhooks
+ for _, webhook := range r.webhooks {
+ req, err := http.NewRequest("POST", webhook.Config.URL, bytes.NewReader(payload))
+ if err != nil {
+ return errors.Wrapf(err, "failed to create a new POST request to %q", webhook.Config.URL)
+ }
+
+ m := hmac.New(sha256.New, []byte(webhook.Config.Secret))
+ m.Write(payload)
+ signature := "sha256=" + hex.EncodeToString(m.Sum(nil))
+ req.Header.Set("X-Hub-Signature-256", signature)
+ req.Header.Set("X-GitHub-Event", "push")
+
+ resp, err := gh.client.Do(req)
+ if err != nil {
+ return errors.Wrapf(err, "failed to send POST request to %q", webhook.Config.URL)
+ }
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return errors.Wrap(err, "failed to read response body")
+ }
+ if resp.StatusCode != http.StatusOK {
+ return errors.Errorf("unexpected response status code %d, body: %s", resp.StatusCode, body)
+ }
+ gh.echo.Logger.Infof("SendWebhookPush response body %s\n", body)
+ }
+ return nil
+}
+
+// AddFiles adds given files to the GitHub repository.
+func (gh *GitHub) AddFiles(repositoryID string, files map[string]string) error {
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return errors.Errorf("GitHub repository %q does not exist", repositoryID)
+ }
+
+ // Save or overwrite files
+ for path, content := range files {
+ r.files[path] = content
+ }
+ return nil
+}
+
+// GetFiles returns files with given paths from the GitHub repository.
+func (gh *GitHub) GetFiles(repositoryID string, filePaths ...string) (map[string]string, error) {
+ r, ok := gh.repositories[repositoryID]
+ if !ok {
+ return nil, errors.Errorf("GitHub repository %q does not exist", repositoryID)
+ }
+
+ // Get files
+ files := make(map[string]string)
+ for _, path := range filePaths {
+ if content, ok := r.files[path]; ok {
+ files[path] = content
+ }
+ }
+ return files, nil
+}
diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.go
index e0b9b1220e..41d9617bc5 100644
--- a/tests/fake/gitlab.go
+++ b/tests/fake/gitlab.go
@@ -95,7 +95,7 @@ func (gl *GitLab) CreateRepository(id string) {
// createProjectHook creates a project webhook.
func (gl *GitLab) createProjectHook(c echo.Context) error {
projectID := c.Param("id")
- c.Logger().Info("create webhook for project %q", c.Param("id"))
+ c.Logger().Infof("Create webhook for project %q", c.Param("id"))
b, err := io.ReadAll(c.Request().Body)
if err != nil {
return fmt.Errorf("failed to read create project hook request body, error %w", err)
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index d35d2edf48..272d82b800 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -7,12 +7,14 @@ import (
"os"
"path"
"testing"
+ "time"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/bytebase/bytebase/plugin/vcs/github"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
"github.com/bytebase/bytebase/tests/fake"
)
@@ -274,219 +276,268 @@ func TestSchemaAndDataUpdate(t *testing.T) {
a.NoError(err)
}
-func TestVCS_GitLab(t *testing.T) {
- t.Parallel()
- a := require.New(t)
- ctx := context.Background()
- ctl := &controller{}
- dataDir := t.TempDir()
- err := ctl.StartServer(ctx, dataDir, fake.NewGitLab, getTestPort(t.Name()))
- a.NoError(err)
- defer ctl.Close(ctx)
- err = ctl.Login()
- a.NoError(err)
- err = ctl.setLicense()
- a.NoError(err)
-
- // Create a VCS.
- applicationID := "testApplicationID"
- applicationSecret := "testApplicationSecret"
- vcs, err := ctl.createVCS(api.VCSCreate{
- Name: "TestVCS",
- Type: vcs.GitLabSelfHost,
- InstanceURL: ctl.vcsURL,
- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
- ApplicationID: applicationID,
- Secret: applicationSecret,
- })
- a.NoError(err)
-
- // Create a project.
- project, err := ctl.createProject(api.ProjectCreate{
- Name: "Test VCS Project",
- Key: "TestVCSSchemaUpdate",
- })
- a.NoError(err)
-
- // Create a repository.
- repositoryPath := "test/schemaUpdate"
- accessToken := "accessToken1"
- refreshToken := "refreshToken1"
- gitlabProjectID := 121
- gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)
- // Create a GitLab project.
- ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)
- _, err = ctl.createRepository(api.RepositoryCreate{
- VCSID: vcs.ID,
- ProjectID: project.ID,
- Name: "Test Repository",
- FullPath: repositoryPath,
- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repositoryPath),
- BranchFilter: "feature/foo",
- BaseDirectory: "bbtest",
- FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
- SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",
- ExternalID: gitlabProjectIDStr,
- AccessToken: accessToken,
- ExpiresTs: 0,
- RefreshToken: refreshToken,
- })
- a.NoError(err)
-
- // Provision an instance.
- instanceRootDir := t.TempDir()
- instanceName := "testInstance1"
- instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, instanceName)
- a.NoError(err)
-
- environments, err := ctl.getEnvironments()
- a.NoError(err)
- prodEnvironment, err := findEnvironment(environments, "Prod")
- a.NoError(err)
-
- // Add an instance.
- instance, err := ctl.addInstance(api.InstanceCreate{
- EnvironmentID: prodEnvironment.ID,
- Name: instanceName,
- Engine: db.SQLite,
- Host: instanceDir,
- })
- a.NoError(err)
-
- // Create an issue that creates a database.
- databaseName := "testVCSSchemaUpdate"
- err = ctl.createDatabase(project, instance, databaseName, nil /* labelMap */)
- a.NoError(err)
-
- // Simulate Git commits for schema update.
- gitFile := "bbtest/Prod/testVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
- pushEvent := &gitlab.WebhookPushEvent{
- ObjectKind: gitlab.WebhookPush,
- Ref: "refs/heads/feature/foo",
- Project: gitlab.WebhookProject{
- ID: gitlabProjectID,
- },
- CommitList: []gitlab.WebhookCommit{
- {
- Timestamp: "2021-01-13T13:14:00Z",
- AddedList: []string{
- gitFile,
- },
- },
- },
- }
- err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})
- a.NoError(err)
-
- payload, err := json.Marshal(pushEvent)
- a.NoError(err)
- err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)
- a.NoError(err)
-
- // Get schema update issue.
- openStatus := []api.IssueStatus{api.IssueOpen}
- issues, err := ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
- a.NoError(err)
- a.Equal(1, len(issues))
- issue := issues[0]
- status, err := ctl.waitIssuePipeline(issue.ID)
- a.NoError(err)
- a.Equal(api.TaskDone, status)
- _, err = ctl.patchIssueStatus(api.IssueStatusPatch{
- ID: issue.ID,
- Status: api.IssueDone,
- })
- a.NoError(err)
-
- // Query schema.
- result, err := ctl.query(instance, databaseName, bookTableQuery)
- a.NoError(err)
- a.Equal(bookSchemaSQLResult, result)
-
- // Simulate Git commits for schema update.
- gitFile = "bbtest/Prod/testVCSSchemaUpdate__ver2__data__insert_data.sql"
- pushEvent = &gitlab.WebhookPushEvent{
- ObjectKind: gitlab.WebhookPush,
- Ref: "refs/heads/feature/foo",
- Project: gitlab.WebhookProject{
- ID: gitlabProjectID,
- },
- CommitList: []gitlab.WebhookCommit{
- {
- Timestamp: "2021-01-13T13:14:00Z",
- AddedList: []string{
- gitFile,
- },
- },
- },
- }
- err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: dataUpdateStatement})
- a.NoError(err)
-
- payload, err = json.Marshal(pushEvent)
- a.NoError(err)
- err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)
- a.NoError(err)
-
- // Get data update issue.
- openStatus = []api.IssueStatus{api.IssueOpen}
- issues, err = ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
- a.NoError(err)
- a.Equal(1, len(issues))
- issue = issues[0]
- status, err = ctl.waitIssuePipeline(issue.ID)
- a.NoError(err)
- a.Equal(api.TaskDone, status)
- _, err = ctl.patchIssueStatus(api.IssueStatusPatch{
- ID: issue.ID,
- Status: api.IssueDone,
- })
- a.NoError(err)
-
- // Get migration history.
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
- a.NoError(err)
- wantHistories := []api.MigrationHistory{
+func TestVCS(t *testing.T) {
+ tests := []struct {
+ name string
+ vcsProviderCreator fake.VCSProviderCreator
+ vcsType vcs.Type
+ externalID string
+ repositoryFullPath string
+ newWebhookPushEvent func(gitFile string) interface{}
+ }{
{
- Database: databaseName,
- Source: db.VCS,
- Type: db.Data,
- Status: db.Done,
- Schema: dumpedSchema,
- SchemaPrev: dumpedSchema,
- },
- {
- Database: databaseName,
- Source: db.VCS,
- Type: db.Migrate,
- Status: db.Done,
- Schema: dumpedSchema,
- SchemaPrev: "",
+ name: "GitLab",
+ vcsProviderCreator: fake.NewGitLab,
+ vcsType: vcs.GitLabSelfHost,
+ externalID: "121",
+ repositoryFullPath: "test/schemaUpdate",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return gitlab.WebhookPushEvent{
+ ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
+ Project: gitlab.WebhookProject{
+ ID: 121,
+ },
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{gitFile},
+ },
+ },
+ }
+ },
},
{
- Database: databaseName,
- Source: db.UI,
- Type: db.Baseline,
- Status: db.Done,
- Schema: "",
- SchemaPrev: "",
+ name: "GitHub",
+ vcsProviderCreator: fake.NewGitHub,
+ vcsType: vcs.GitHubCom,
+ externalID: "octocat/Hello-World",
+ repositoryFullPath: "octocat/Hello-World",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return github.WebhookPushEvent{
+ Ref: "refs/heads/feature/foo",
+ Repository: github.WebhookRepository{
+ ID: 211,
+ FullName: "octocat/Hello-World",
+ HTMLURL: "https://github.com/octocat/Hello-World",
+ },
+ Sender: github.WebhookSender{
+ Login: "fake_github_author",
+ },
+ Commits: []github.WebhookCommit{
+ {
+ ID: "fake_github_commit_id",
+ Distinct: true,
+ Message: "Fake GitHub commit message",
+ Timestamp: time.Now(),
+ URL: "https://api.github.com/octocat/Hello-World/commits/fake_github_commit_id",
+ Author: github.WebhookCommitAuthor{
+ Name: "fake_github_author",
+ Email: "fake_github_author@localhost",
+ },
+ Added: []string{gitFile},
+ },
+ },
+ }
+ },
},
}
- a.Equal(len(wantHistories), len(histories))
-
- for i, history := range histories {
- got := api.MigrationHistory{
- Database: history.Database,
- Source: history.Source,
- Type: history.Type,
- Status: history.Status,
- Schema: history.Schema,
- SchemaPrev: history.SchemaPrev,
- }
- want := wantHistories[i]
- a.Equal(want, got)
- a.NotEqual(history.Version, "")
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ err := ctl.StartServer(ctx, t.TempDir(), test.vcsProviderCreator, getTestPort(t.Name()))
+ a.NoError(err)
+ defer func() { _ = ctl.Close(ctx) }()
+
+ err = ctl.Login()
+ a.NoError(err)
+ err = ctl.setLicense()
+ a.NoError(err)
+
+ // Create a VCS.
+ vcs, err := ctl.createVCS(
+ api.VCSCreate{
+ Name: t.Name(),
+ Type: test.vcsType,
+ InstanceURL: ctl.vcsURL,
+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
+ ApplicationID: "testApplicationID",
+ Secret: "testApplicationSecret",
+ },
+ )
+ a.NoError(err)
+
+ // Create a project.
+ project, err := ctl.createProject(
+ api.ProjectCreate{
+ Name: "Test VCS Project",
+ Key: "TestVCSSchemaUpdate",
+ },
+ )
+ a.NoError(err)
+
+ // Create a repository.
+ ctl.vcsProvider.CreateRepository(test.externalID)
+ _, err = ctl.createRepository(
+ api.RepositoryCreate{
+ VCSID: vcs.ID,
+ ProjectID: project.ID,
+ Name: "Test Repository",
+ FullPath: test.repositoryFullPath,
+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),
+ BranchFilter: "feature/foo",
+ BaseDirectory: baseDirectory,
+ FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
+ SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",
+ ExternalID: test.externalID,
+ AccessToken: "accessToken1",
+ RefreshToken: "refreshToken1",
+ },
+ )
+ a.NoError(err)
+
+ // Provision an instance.
+ instanceName := "testInstance1"
+ instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), instanceName)
+ a.NoError(err)
+
+ environments, err := ctl.getEnvironments()
+ a.NoError(err)
+ prodEnvironment, err := findEnvironment(environments, "Prod")
+ a.NoError(err)
+
+ // Add an instance.
+ instance, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: instanceName,
+ Engine: db.SQLite,
+ Host: instanceDir,
+ })
+ a.NoError(err)
+
+ // Create an issue that creates a database.
+ databaseName := "testVCSSchemaUpdate"
+ err = ctl.createDatabase(project, instance, databaseName, nil /* labelMap */)
+ a.NoError(err)
+
+ // Simulate Git commits for schema update.
+ gitFile := "bbtest/Prod/testVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: migrationStatement})
+ a.NoError(err)
+
+ payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))
+ a.NoError(err)
+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ a.NoError(err)
+
+ // Get schema update issue.
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(
+ api.IssueFind{
+ ProjectID: &project.ID,
+ StatusList: &openStatus,
+ },
+ )
+ a.NoError(err)
+ a.Len(issues, 1)
+ issue := issues[0]
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+ _, err = ctl.patchIssueStatus(
+ api.IssueStatusPatch{
+ ID: issue.ID,
+ Status: api.IssueDone,
+ },
+ )
+ a.NoError(err)
+
+ // Query schema.
+ result, err := ctl.query(instance, databaseName, bookTableQuery)
+ a.NoError(err)
+ a.Equal(bookSchemaSQLResult, result)
+
+ // Simulate Git commits for schema update.
+ gitFile = "bbtest/Prod/testVCSSchemaUpdate__ver2__data__insert_data.sql"
+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: dataUpdateStatement})
+ a.NoError(err)
+
+ payload, err = json.Marshal(test.newWebhookPushEvent(gitFile))
+ a.NoError(err)
+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ a.NoError(err)
+
+ // Get data update issue.
+ openStatus = []api.IssueStatus{api.IssueOpen}
+ issues, err = ctl.getIssues(
+ api.IssueFind{
+ ProjectID: &project.ID,
+ StatusList: &openStatus,
+ },
+ )
+ a.NoError(err)
+ a.Len(issues, 1)
+ issue = issues[0]
+ status, err = ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+ _, err = ctl.patchIssueStatus(
+ api.IssueStatusPatch{
+ ID: issue.ID,
+ Status: api.IssueDone,
+ },
+ )
+ a.NoError(err)
+
+ // Get migration history.
+ histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
+ a.NoError(err)
+ wantHistories := []api.MigrationHistory{
+ {
+ Database: databaseName,
+ Source: db.VCS,
+ Type: db.Data,
+ Status: db.Done,
+ Schema: dumpedSchema,
+ SchemaPrev: dumpedSchema,
+ },
+ {
+ Database: databaseName,
+ Source: db.VCS,
+ Type: db.Migrate,
+ Status: db.Done,
+ Schema: dumpedSchema,
+ SchemaPrev: "",
+ },
+ {
+ Database: databaseName,
+ Source: db.UI,
+ Type: db.Baseline,
+ Status: db.Done,
+ Schema: "",
+ SchemaPrev: "",
+ },
+ }
+ a.Equal(len(wantHistories), len(histories))
+
+ for i, history := range histories {
+ got := api.MigrationHistory{
+ Database: history.Database,
+ Source: history.Source,
+ Type: history.Type,
+ Status: history.Status,
+ Schema: history.Schema,
+ SchemaPrev: history.SchemaPrev,
+ }
+ a.Equal(wantHistories[i], got)
+ a.NotEmpty(history.Version)
+ }
+ a.Equal(histories[0].Version, "ver2")
+ a.Equal(histories[1].Version, "ver1")
+ })
}
- a.Equal(histories[0].Version, "ver2")
- a.Equal(histories[1].Version, "ver1")
}
diff --git a/tests/sheet_vcs_test.go b/tests/sheet_vcs_test.go
index 585b5f714c..8233813548 100644
--- a/tests/sheet_vcs_test.go
+++ b/tests/sheet_vcs_test.go
@@ -12,84 +12,108 @@ import (
"github.com/bytebase/bytebase/tests/fake"
)
-func TestSheetVCS_GitLab(t *testing.T) {
- t.Parallel()
- a := require.New(t)
- ctx := context.Background()
- ctl := &controller{}
- dataDir := t.TempDir()
- err := ctl.StartServer(ctx, dataDir, fake.NewGitLab, getTestPort(t.Name()))
- a.NoError(err)
- defer ctl.Close(ctx)
- err = ctl.Login()
- a.NoError(err)
- err = ctl.setLicense()
- a.NoError(err)
+func TestSheetVCS(t *testing.T) {
+ tests := []struct {
+ name string
+ vcsProviderCreator fake.VCSProviderCreator
+ vcsType vcs.Type
+ externalID string
+ repositoryFullPath string
+ }{
+ {
+ name: "GitLab",
+ vcsProviderCreator: fake.NewGitLab,
+ vcsType: vcs.GitLabSelfHost,
+ externalID: "121",
+ repositoryFullPath: "test/schemaUpdate",
+ },
+ {
+ name: "GitHub",
+ vcsProviderCreator: fake.NewGitHub,
+ vcsType: vcs.GitHubCom,
+ externalID: "octocat/Hello-World",
+ repositoryFullPath: "octocat/Hello-World",
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
- // Create a test VCS.
- applicationID := "testApplicationID"
- applicationSecret := "testApplicationSecret"
- vcs, err := ctl.createVCS(api.VCSCreate{
- Name: "TestVCS",
- Type: vcs.GitLabSelfHost,
- InstanceURL: ctl.vcsURL,
- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
- ApplicationID: applicationID,
- Secret: applicationSecret,
- })
- a.NoError(err)
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ err := ctl.StartServer(ctx, t.TempDir(), test.vcsProviderCreator, getTestPort(t.Name()))
+ a.NoError(err)
+ defer func() { _ = ctl.Close(ctx) }()
- // Create a project.
- project, err := ctl.createProject(api.ProjectCreate{
- Name: "Test VCS Project",
- Key: "TestVCSSyncSheet",
- })
- a.NoError(err)
+ err = ctl.Login()
+ a.NoError(err)
+ err = ctl.setLicense()
+ a.NoError(err)
- // Create a repository.
- repositoryPath := "test/sync-sheet"
- accessToken := "accessToken"
- refreshToken := "refreshToken"
- gitlabProjectID := 121
- gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)
- // Create a GitLab project.
- ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)
- _, err = ctl.createRepository(api.RepositoryCreate{
- VCSID: vcs.ID,
- ProjectID: project.ID,
- Name: "Test Repository",
- FullPath: repositoryPath,
- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repositoryPath),
- BranchFilter: "feature/foo",
- BaseDirectory: "bbtest",
- FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
- SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",
- SheetPathTemplate: "sheet/{{NAME}}.sql",
- ExternalID: gitlabProjectIDStr,
- AccessToken: accessToken,
- ExpiresTs: 0,
- RefreshToken: refreshToken,
- })
- a.NoError(err)
+ // Create a VCS.
+ vcs, err := ctl.createVCS(
+ api.VCSCreate{
+ Name: t.Name(),
+ Type: test.vcsType,
+ InstanceURL: ctl.vcsURL,
+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
+ ApplicationID: "testApplicationID",
+ Secret: "testApplicationSecret",
+ },
+ )
+ a.NoError(err)
- // Initial git files.
- files := map[string]string{}
- gitFile := "sheet/all_employee.sql"
- fileContent := "SELECT * FROM employee"
- files[gitFile] = fileContent
- err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, files)
- a.NoError(err)
+ // Create a project.
+ project, err := ctl.createProject(
+ api.ProjectCreate{
+ Name: "Test VCS Project",
+ Key: "TestVCSSchemaUpdate",
+ },
+ )
+ a.NoError(err)
- err = ctl.syncSheet(project.ID)
- a.NoError(err)
+ // Create a repository.
+ ctl.vcsProvider.CreateRepository(test.externalID)
+ _, err = ctl.createRepository(
+ api.RepositoryCreate{
+ VCSID: vcs.ID,
+ ProjectID: project.ID,
+ Name: "Test Repository",
+ FullPath: test.repositoryFullPath,
+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),
+ BranchFilter: "feature/foo",
+ BaseDirectory: baseDirectory,
+ FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
+ SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}__LATEST.sql",
+ SheetPathTemplate: "sheet/{{NAME}}.sql",
+ ExternalID: test.externalID,
+ AccessToken: "accessToken1",
+ RefreshToken: "refreshToken1",
+ },
+ )
+ a.NoError(err)
- sheets, err := ctl.listSheets(api.SheetFind{
- ProjectID: &project.ID,
- })
- a.NoError(err)
- a.Equal(1, len(sheets))
+ // Initial git files.
+ gitFile := "sheet/all_employee.sql"
+ fileContent := "SELECT * FROM employee"
+ files := map[string]string{
+ gitFile: fileContent,
+ }
+ files[gitFile] = fileContent
+ err = ctl.vcsProvider.AddFiles(test.externalID, files)
+ a.NoError(err)
- sheetFromVCS := sheets[0]
- a.Equal("all_employee", sheetFromVCS.Name)
- a.Equal(fileContent, sheetFromVCS.Statement)
+ err = ctl.syncSheet(project.ID)
+ a.NoError(err)
+
+ sheets, err := ctl.listSheets(api.SheetFind{ProjectID: &project.ID})
+ a.NoError(err)
+ a.Len(sheets, 1)
+
+ sheetFromVCS := sheets[0]
+ a.Equal("all_employee", sheetFromVCS.Name)
+ a.Equal(fileContent, sheetFromVCS.Statement)
+ })
+ }
}
diff --git a/tests/tenant_test.go b/tests/tenant_test.go
index ec297115a7..772ff03d04 100644
--- a/tests/tenant_test.go
+++ b/tests/tenant_test.go
@@ -5,12 +5,14 @@ import (
"encoding/json"
"fmt"
"testing"
+ "time"
"github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/vcs"
+ "github.com/bytebase/bytebase/plugin/vcs/github"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
"github.com/bytebase/bytebase/tests/fake"
)
@@ -204,232 +206,298 @@ func TestTenant(t *testing.T) {
a.Equal(1, len(hm2))
}
-func TestTenantVCS_GitLab(t *testing.T) {
- t.Parallel()
- a := require.New(t)
- ctx := context.Background()
- ctl := &controller{}
- dataDir := t.TempDir()
- err := ctl.StartServer(ctx, dataDir, fake.NewGitLab, getTestPort(t.Name()))
- a.NoError(err)
- defer ctl.Close(ctx)
- err = ctl.Login()
- a.NoError(err)
- err = ctl.setLicense()
- a.NoError(err)
-
- // Create a VCS.
- applicationID := "testApplicationID"
- applicationSecret := "testApplicationSecret"
- vcs, err := ctl.createVCS(api.VCSCreate{
- Name: "TestVCS",
- Type: vcs.GitLabSelfHost,
- InstanceURL: ctl.vcsURL,
- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
- ApplicationID: applicationID,
- Secret: applicationSecret,
- })
- a.NoError(err)
-
- // Create a project.
- project, err := ctl.createProject(api.ProjectCreate{
- Name: "Test Project",
- Key: "TestSchemaUpdate",
- TenantMode: api.TenantModeTenant,
- })
- a.NoError(err)
-
- // Create a repository.
- repositoryPath := "test/schemaUpdate"
- accessToken := "accessToken1"
- refreshToken := "refreshToken1"
- gitlabProjectID := 121
- gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)
- // Create a GitLab project.
- ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)
- _, err = ctl.createRepository(api.RepositoryCreate{
- VCSID: vcs.ID,
- ProjectID: project.ID,
- Name: "Test Repository",
- FullPath: repositoryPath,
- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repositoryPath),
- BranchFilter: "feature/foo",
- BaseDirectory: baseDirectory,
- FilePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
- SchemaPathTemplate: ".{{DB_NAME}}__LATEST.sql",
- ExternalID: gitlabProjectIDStr,
- AccessToken: accessToken,
- ExpiresTs: 0,
- RefreshToken: refreshToken,
- })
- a.NoError(err)
-
- // Provision instances.
- instanceRootDir := t.TempDir()
-
- var stagingInstanceDirs []string
- var prodInstanceDirs []string
- for i := 0; i < stagingTenantNumber; i++ {
- instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceName, i))
- a.NoError(err)
- stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)
- }
- for i := 0; i < prodTenantNumber; i++ {
- instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", prodInstanceName, i))
- a.NoError(err)
- prodInstanceDirs = append(prodInstanceDirs, instanceDir)
- }
- environments, err := ctl.getEnvironments()
- a.NoError(err)
- stagingEnvironment, err := findEnvironment(environments, "Staging")
- a.NoError(err)
- prodEnvironment, err := findEnvironment(environments, "Prod")
- a.NoError(err)
-
- // Add the provisioned instances.
- var stagingInstances []*api.Instance
- var prodInstances []*api.Instance
- for i, stagingInstanceDir := range stagingInstanceDirs {
- instance, err := ctl.addInstance(api.InstanceCreate{
- EnvironmentID: stagingEnvironment.ID,
- Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),
- Engine: db.SQLite,
- Host: stagingInstanceDir,
- })
- a.NoError(err)
- stagingInstances = append(stagingInstances, instance)
- }
- for i, prodInstanceDir := range prodInstanceDirs {
- instance, err := ctl.addInstance(api.InstanceCreate{
- EnvironmentID: prodEnvironment.ID,
- Name: fmt.Sprintf("%s-%d", prodInstanceName, i),
- Engine: db.SQLite,
- Host: prodInstanceDir,
- })
- a.NoError(err)
- prodInstances = append(prodInstances, instance)
- }
-
- // Set up label values for tenants.
- // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.
- var tenants []string
- for i := 0; i < prodTenantNumber; i++ {
- tenants = append(tenants, fmt.Sprintf("tenant%d", i))
- }
- err = ctl.addLabelValues(api.TenantLabelKey, tenants)
- a.NoError(err)
-
- // Create deployment configuration.
- _, err = ctl.upsertDeploymentConfig(
- api.DeploymentConfigUpsert{
- ProjectID: project.ID,
+func TestTenantVCS(t *testing.T) {
+ tests := []struct {
+ name string
+ vcsProviderCreator fake.VCSProviderCreator
+ vcsType vcs.Type
+ externalID string
+ repositoryFullPath string
+ newWebhookPushEvent func(gitFile string) interface{}
+ }{
+ {
+ name: "GitLab",
+ vcsProviderCreator: fake.NewGitLab,
+ vcsType: vcs.GitLabSelfHost,
+ externalID: "121",
+ repositoryFullPath: "test/schemaUpdate",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return gitlab.WebhookPushEvent{
+ ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
+ Project: gitlab.WebhookProject{
+ ID: 121,
+ },
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{gitFile},
+ },
+ },
+ }
+ },
+ },
+ {
+ name: "GitHub",
+ vcsProviderCreator: fake.NewGitHub,
+ vcsType: vcs.GitHubCom,
+ externalID: "octocat/Hello-World",
+ repositoryFullPath: "octocat/Hello-World",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return github.WebhookPushEvent{
+ Ref: "refs/heads/feature/foo",
+ Repository: github.WebhookRepository{
+ ID: 211,
+ FullName: "octocat/Hello-World",
+ HTMLURL: "https://github.com/octocat/Hello-World",
+ },
+ Sender: github.WebhookSender{
+ Login: "fake_github_author",
+ },
+ Commits: []github.WebhookCommit{
+ {
+ ID: "fake_github_commit_id",
+ Distinct: true,
+ Message: "Fake GitHub commit message",
+ Timestamp: time.Now(),
+ URL: "https://api.github.com/octocat/Hello-World/commits/fake_github_commit_id",
+ Author: github.WebhookCommitAuthor{
+ Name: "fake_github_author",
+ Email: "fake_github_author@localhost",
+ },
+ Added: []string{gitFile},
+ },
+ },
+ }
+ },
},
- deploymentSchedule,
- )
- a.NoError(err)
-
- // Create issues that create databases.
- databaseName := "testTenantVCSSchemaUpdate"
- for i, stagingInstance := range stagingInstances {
- err := ctl.createDatabase(project, stagingInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})
- a.NoError(err)
- }
- for i, prodInstance := range prodInstances {
- err := ctl.createDatabase(project, prodInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})
- a.NoError(err)
}
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ err := ctl.StartServer(ctx, t.TempDir(), test.vcsProviderCreator, getTestPort(t.Name()))
+ a.NoError(err)
+ defer func() { _ = ctl.Close(ctx) }()
+
+ err = ctl.Login()
+ a.NoError(err)
+ err = ctl.setLicense()
+ a.NoError(err)
+
+ // Create a VCS.
+ vcs, err := ctl.createVCS(
+ api.VCSCreate{
+ Name: t.Name(),
+ Type: test.vcsType,
+ InstanceURL: ctl.vcsURL,
+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
+ ApplicationID: "testApplicationID",
+ Secret: "testApplicationSecret",
+ },
+ )
+ a.NoError(err)
+
+ // Create a project.
+ project, err := ctl.createProject(
+ api.ProjectCreate{
+ Name: "Test VCS Project",
+ Key: "TestVCSSchemaUpdate",
+ TenantMode: api.TenantModeTenant,
+ },
+ )
+ a.NoError(err)
+
+ // Create a repository.
+ ctl.vcsProvider.CreateRepository(test.externalID)
+ _, err = ctl.createRepository(
+ api.RepositoryCreate{
+ VCSID: vcs.ID,
+ ProjectID: project.ID,
+ Name: "Test Repository",
+ FullPath: test.repositoryFullPath,
+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),
+ BranchFilter: "feature/foo",
+ BaseDirectory: baseDirectory,
+ FilePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
+ SchemaPathTemplate: ".{{DB_NAME}}__LATEST.sql",
+ ExternalID: test.externalID,
+ AccessToken: "accessToken1",
+ RefreshToken: "refreshToken1",
+ },
+ )
+ a.NoError(err)
+
+ // Provision instances.
+ instanceRootDir := t.TempDir()
+
+ var stagingInstanceDirs []string
+ var prodInstanceDirs []string
+ for i := 0; i < stagingTenantNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceName, i))
+ a.NoError(err)
+ stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)
+ }
+ for i := 0; i < prodTenantNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", prodInstanceName, i))
+ a.NoError(err)
+ prodInstanceDirs = append(prodInstanceDirs, instanceDir)
+ }
+ environments, err := ctl.getEnvironments()
+ a.NoError(err)
+ stagingEnvironment, err := findEnvironment(environments, "Staging")
+ a.NoError(err)
+ prodEnvironment, err := findEnvironment(environments, "Prod")
+ a.NoError(err)
+
+ // Add the provisioned instances.
+ var stagingInstances []*api.Instance
+ var prodInstances []*api.Instance
+ for i, stagingInstanceDir := range stagingInstanceDirs {
+ instance, err := ctl.addInstance(
+ api.InstanceCreate{
+ EnvironmentID: stagingEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),
+ Engine: db.SQLite,
+ Host: stagingInstanceDir,
+ },
+ )
+ a.NoError(err)
+ stagingInstances = append(stagingInstances, instance)
+ }
+ for i, prodInstanceDir := range prodInstanceDirs {
+ instance, err := ctl.addInstance(
+ api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", prodInstanceName, i),
+ Engine: db.SQLite,
+ Host: prodInstanceDir,
+ },
+ )
+ a.NoError(err)
+ prodInstances = append(prodInstances, instance)
+ }
- // Getting databases for each environment.
- databases, err := ctl.getDatabases(api.DatabaseFind{
- ProjectID: &project.ID,
- })
- a.NoError(err)
+ // Set up label values for tenants.
+ // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.
+ var tenants []string
+ for i := 0; i < prodTenantNumber; i++ {
+ tenants = append(tenants, fmt.Sprintf("tenant%d", i))
+ }
+ err = ctl.addLabelValues(api.TenantLabelKey, tenants)
+ a.NoError(err)
- var stagingDatabases []*api.Database
- var prodDatabases []*api.Database
- for _, stagingInstance := range stagingInstances {
- for _, database := range databases {
- if database.Instance.ID == stagingInstance.ID {
- stagingDatabases = append(stagingDatabases, database)
- break
+ // Create deployment configuration.
+ _, err = ctl.upsertDeploymentConfig(
+ api.DeploymentConfigUpsert{
+ ProjectID: project.ID,
+ },
+ deploymentSchedule,
+ )
+ a.NoError(err)
+
+ // Create issues that create databases.
+ databaseName := "testTenantVCSSchemaUpdate"
+ for i, stagingInstance := range stagingInstances {
+ err := ctl.createDatabase(project, stagingInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})
+ a.NoError(err)
}
- }
- }
- for _, prodInstance := range prodInstances {
- for _, database := range databases {
- if database.Instance.ID == prodInstance.ID {
- prodDatabases = append(prodDatabases, database)
- break
+ for i, prodInstance := range prodInstances {
+ err := ctl.createDatabase(project, prodInstance, databaseName, map[string]string{api.TenantLabelKey: fmt.Sprintf("tenant%d", i)})
+ a.NoError(err)
}
- }
- }
- a.Equal(len(stagingDatabases), stagingTenantNumber)
- a.Equal(len(prodDatabases), prodTenantNumber)
- // Simulate Git commits.
- gitFile := "bbtest/testTenantVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
- pushEvent := &gitlab.WebhookPushEvent{
- ObjectKind: gitlab.WebhookPush,
- Ref: "refs/heads/feature/foo",
- Project: gitlab.WebhookProject{
- ID: gitlabProjectID,
- },
- CommitList: []gitlab.WebhookCommit{
- {
- Timestamp: "2021-01-13T13:14:00Z",
- AddedList: []string{
- gitFile,
+ // Getting databases for each environment.
+ databases, err := ctl.getDatabases(api.DatabaseFind{ProjectID: &project.ID})
+ a.NoError(err)
+
+ var stagingDatabases []*api.Database
+ var prodDatabases []*api.Database
+ for _, stagingInstance := range stagingInstances {
+ for _, database := range databases {
+ if database.Instance.ID == stagingInstance.ID {
+ stagingDatabases = append(stagingDatabases, database)
+ break
+ }
+ }
+ }
+ for _, prodInstance := range prodInstances {
+ for _, database := range databases {
+ if database.Instance.ID == prodInstance.ID {
+ prodDatabases = append(prodDatabases, database)
+ break
+ }
+ }
+ }
+ a.Equal(len(stagingDatabases), stagingTenantNumber)
+ a.Equal(len(prodDatabases), prodTenantNumber)
+
+ // Simulate Git commits.
+ gitFile := "bbtest/testTenantVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: migrationStatement})
+ a.NoError(err)
+
+ payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))
+ a.NoError(err)
+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ a.NoError(err)
+
+ // Get schema update issue.
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(
+ api.IssueFind{
+ ProjectID: &project.ID,
+ StatusList: &openStatus,
},
- },
- },
- }
- err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})
- a.NoError(err)
- payload, err := json.Marshal(pushEvent)
- a.NoError(err)
- err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)
- a.NoError(err)
-
- // Get schema update issue.
- openStatus := []api.IssueStatus{api.IssueOpen}
- issues, err := ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
- a.NoError(err)
- a.Equal(1, len(issues))
- issue := issues[0]
- // Test pipeline stage patch status.
- status, err := ctl.waitIssuePipelineWithStageApproval(issue.ID)
- a.NoError(err)
- a.Equal(api.TaskDone, status)
-
- // Query schema.
- for _, stagingInstance := range stagingInstances {
- result, err := ctl.query(stagingInstance, databaseName, bookTableQuery)
- a.NoError(err)
- a.Equal(bookSchemaSQLResult, result)
- }
- for _, prodInstance := range prodInstances {
- result, err := ctl.query(prodInstance, databaseName, bookTableQuery)
- a.NoError(err)
- a.Equal(bookSchemaSQLResult, result)
- }
+ )
+ a.NoError(err)
+ a.Len(issues, 1)
+ issue := issues[0]
+
+ // Test pipeline stage patch status.
+ status, err := ctl.waitIssuePipelineWithStageApproval(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+
+ // Query schema.
+ for _, stagingInstance := range stagingInstances {
+ result, err := ctl.query(stagingInstance, databaseName, bookTableQuery)
+ a.NoError(err)
+ a.Equal(bookSchemaSQLResult, result)
+ }
+ for _, prodInstance := range prodInstances {
+ result, err := ctl.query(prodInstance, databaseName, bookTableQuery)
+ a.NoError(err)
+ a.Equal(bookSchemaSQLResult, result)
+ }
- // Query migration history
- var instances []*api.Instance
- instances = append(instances, stagingInstances...)
- instances = append(instances, prodInstances...)
- hm1 := map[string]bool{}
- hm2 := map[string]bool{}
- for _, instance := range instances {
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID, Database: &databaseName})
- a.NoError(err)
- a.Equal(len(histories), 2)
- a.Equal(histories[0].Version, "ver1")
- a.NotEqual(histories[1].Version, "")
- hm1[histories[0].Version] = true
- hm2[histories[1].Version] = true
+ // Query migration history
+ var instances []*api.Instance
+ instances = append(instances, stagingInstances...)
+ instances = append(instances, prodInstances...)
+ hm1 := map[string]bool{}
+ hm2 := map[string]bool{}
+ for _, instance := range instances {
+ histories, err := ctl.getInstanceMigrationHistory(
+ db.MigrationHistoryFind{
+ ID: &instance.ID,
+ Database: &databaseName,
+ },
+ )
+ a.NoError(err)
+ a.Len(histories, 2)
+ a.Equal(histories[0].Version, "ver1")
+ a.NotEqual(histories[1].Version, "")
+ hm1[histories[0].Version] = true
+ hm2[histories[1].Version] = true
+ }
+ a.Len(hm1, 1)
+ a.Len(hm2, 1)
+ })
}
- a.Equal(1, len(hm1))
- a.Equal(1, len(hm2))
}
func TestTenantDatabaseNameTemplate(t *testing.T) {
@@ -585,253 +653,323 @@ func TestTenantDatabaseNameTemplate(t *testing.T) {
}
}
-func TestTenantVCSDatabaseNameTemplate_GitLab(t *testing.T) {
- t.Parallel()
- a := require.New(t)
- ctx := context.Background()
- ctl := &controller{}
- dataDir := t.TempDir()
- err := ctl.StartServer(ctx, dataDir, fake.NewGitLab, getTestPort(t.Name()))
- a.NoError(err)
- defer ctl.Close(ctx)
- err = ctl.Login()
- a.NoError(err)
- err = ctl.setLicense()
- a.NoError(err)
-
- // Create a VCS.
- applicationID := "testApplicationID"
- applicationSecret := "testApplicationSecret"
- vcs, err := ctl.createVCS(api.VCSCreate{
- Name: "TestVCS",
- Type: vcs.GitLabSelfHost,
- InstanceURL: ctl.vcsURL,
- APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
- ApplicationID: applicationID,
- Secret: applicationSecret,
- })
- a.NoError(err)
-
- // Create a project.
- project, err := ctl.createProject(api.ProjectCreate{
- Name: "Test Project",
- Key: "TestSchemaUpdate",
- TenantMode: api.TenantModeTenant,
- DBNameTemplate: "{{DB_NAME}}_{{TENANT}}",
- })
- a.NoError(err)
-
- // Create a repository.
- repositoryPath := "test/schemaUpdate"
- accessToken := "accessToken1"
- refreshToken := "refreshToken1"
- gitlabProjectID := 121
- gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)
- // Create a GitLab project.
- ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)
- _, err = ctl.createRepository(api.RepositoryCreate{
- VCSID: vcs.ID,
- ProjectID: project.ID,
- Name: "Test Repository",
- FullPath: repositoryPath,
- WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, repositoryPath),
- BranchFilter: "feature/foo",
- BaseDirectory: "bbtest",
- FilePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
- SchemaPathTemplate: ".{{DB_NAME}}__LATEST.sql",
- ExternalID: gitlabProjectIDStr,
- AccessToken: accessToken,
- ExpiresTs: 0,
- RefreshToken: refreshToken,
- })
- a.NoError(err)
-
- // Provision instances.
- instanceRootDir := t.TempDir()
-
- var stagingInstanceDirs []string
- var prodInstanceDirs []string
- for i := 0; i < stagingTenantNumber; i++ {
- instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceName, i))
- a.NoError(err)
- stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)
- }
- for i := 0; i < prodTenantNumber; i++ {
- instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", prodInstanceName, i))
- a.NoError(err)
- prodInstanceDirs = append(prodInstanceDirs, instanceDir)
- }
- environments, err := ctl.getEnvironments()
- a.NoError(err)
- stagingEnvironment, err := findEnvironment(environments, "Staging")
- a.NoError(err)
- prodEnvironment, err := findEnvironment(environments, "Prod")
- a.NoError(err)
-
- // Add the provisioned instances.
- var stagingInstances []*api.Instance
- var prodInstances []*api.Instance
- for i, stagingInstanceDir := range stagingInstanceDirs {
- instance, err := ctl.addInstance(api.InstanceCreate{
- EnvironmentID: stagingEnvironment.ID,
- Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),
- Engine: db.SQLite,
- Host: stagingInstanceDir,
- })
- a.NoError(err)
- stagingInstances = append(stagingInstances, instance)
- }
- for i, prodInstanceDir := range prodInstanceDirs {
- instance, err := ctl.addInstance(api.InstanceCreate{
- EnvironmentID: prodEnvironment.ID,
- Name: fmt.Sprintf("%s-%d", prodInstanceName, i),
- Engine: db.SQLite,
- Host: prodInstanceDir,
- })
- a.NoError(err)
- prodInstances = append(prodInstances, instance)
- }
-
- // Set up label values for tenants.
- // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.
- var tenants []string
- for i := 0; i < prodTenantNumber; i++ {
- tenants = append(tenants, fmt.Sprintf("tenant%d", i))
- }
- err = ctl.addLabelValues(api.TenantLabelKey, tenants)
- a.NoError(err)
-
- // Create deployment configuration.
- _, err = ctl.upsertDeploymentConfig(
- api.DeploymentConfigUpsert{
- ProjectID: project.ID,
+func TestTenantVCSDatabaseNameTemplate(t *testing.T) {
+ tests := []struct {
+ name string
+ vcsProviderCreator fake.VCSProviderCreator
+ vcsType vcs.Type
+ externalID string
+ repositoryFullPath string
+ newWebhookPushEvent func(gitFile string) interface{}
+ }{
+ {
+ name: "GitLab",
+ vcsProviderCreator: fake.NewGitLab,
+ vcsType: vcs.GitLabSelfHost,
+ externalID: "121",
+ repositoryFullPath: "test/schemaUpdate",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return gitlab.WebhookPushEvent{
+ ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
+ Project: gitlab.WebhookProject{
+ ID: 121,
+ },
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{gitFile},
+ },
+ },
+ }
+ },
+ },
+ {
+ name: "GitHub",
+ vcsProviderCreator: fake.NewGitHub,
+ vcsType: vcs.GitHubCom,
+ externalID: "octocat/Hello-World",
+ repositoryFullPath: "octocat/Hello-World",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return github.WebhookPushEvent{
+ Ref: "refs/heads/feature/foo",
+ Repository: github.WebhookRepository{
+ ID: 211,
+ FullName: "octocat/Hello-World",
+ HTMLURL: "https://github.com/octocat/Hello-World",
+ },
+ Sender: github.WebhookSender{
+ Login: "fake_github_author",
+ },
+ Commits: []github.WebhookCommit{
+ {
+ ID: "fake_github_commit_id",
+ Distinct: true,
+ Message: "Fake GitHub commit message",
+ Timestamp: time.Now(),
+ URL: "https://api.github.com/octocat/Hello-World/commits/fake_github_commit_id",
+ Author: github.WebhookCommitAuthor{
+ Name: "fake_github_author",
+ Email: "fake_github_author@localhost",
+ },
+ Added: []string{gitFile},
+ },
+ },
+ }
+ },
},
- deploymentSchedule,
- )
- a.NoError(err)
-
- // Create issues that create databases.
- baseDatabaseName := "testTenantVCSSchemaUpdate"
-
- for i, stagingInstance := range stagingInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- err := ctl.createDatabase(project, stagingInstance, databaseName, map[string]string{api.TenantLabelKey: tenant})
- a.NoError(err)
- }
- for i, prodInstance := range prodInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- err := ctl.createDatabase(project, prodInstance, databaseName, map[string]string{api.TenantLabelKey: tenant})
- a.NoError(err)
}
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ err := ctl.StartServer(ctx, t.TempDir(), fake.NewGitHub, getTestPort(t.Name()))
+ a.NoError(err)
+ defer func() { _ = ctl.Close(ctx) }()
+
+ err = ctl.Login()
+ a.NoError(err)
+ err = ctl.setLicense()
+ a.NoError(err)
+
+ // Create a VCS.
+ vcs, err := ctl.createVCS(
+ api.VCSCreate{
+ Name: t.Name(),
+ Type: test.vcsType,
+ InstanceURL: ctl.vcsURL,
+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),
+ ApplicationID: "testApplicationID",
+ Secret: "testApplicationSecret",
+ },
+ )
+ a.NoError(err)
+
+ // Create a project.
+ project, err := ctl.createProject(
+ api.ProjectCreate{
+ Name: "Test VCS Project",
+ Key: "TestVCSSchemaUpdate",
+ TenantMode: api.TenantModeTenant,
+ DBNameTemplate: "{{DB_NAME}}_{{TENANT}}",
+ },
+ )
+ a.NoError(err)
+
+ // Create a repository.
+ ctl.vcsProvider.CreateRepository(test.externalID)
+ _, err = ctl.createRepository(
+ api.RepositoryCreate{
+ VCSID: vcs.ID,
+ ProjectID: project.ID,
+ Name: "Test Repository",
+ FullPath: test.repositoryFullPath,
+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),
+ BranchFilter: "feature/foo",
+ BaseDirectory: baseDirectory,
+ FilePathTemplate: "{{DB_NAME}}__{{VERSION}}__{{TYPE}}__{{DESCRIPTION}}.sql",
+ SchemaPathTemplate: ".{{DB_NAME}}__LATEST.sql",
+ ExternalID: test.externalID,
+ AccessToken: "accessToken1",
+ RefreshToken: "refreshToken1",
+ },
+ )
+ a.NoError(err)
+
+ // Provision instances.
+ instanceRootDir := t.TempDir()
+
+ var stagingInstanceDirs []string
+ var prodInstanceDirs []string
+ for i := 0; i < stagingTenantNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", stagingInstanceName, i))
+ a.NoError(err)
+ stagingInstanceDirs = append(stagingInstanceDirs, instanceDir)
+ }
+ for i := 0; i < prodTenantNumber; i++ {
+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, fmt.Sprintf("%s-%d", prodInstanceName, i))
+ a.NoError(err)
+ prodInstanceDirs = append(prodInstanceDirs, instanceDir)
+ }
+ environments, err := ctl.getEnvironments()
+ a.NoError(err)
+ stagingEnvironment, err := findEnvironment(environments, "Staging")
+ a.NoError(err)
+ prodEnvironment, err := findEnvironment(environments, "Prod")
+ a.NoError(err)
+
+ // Add the provisioned instances.
+ var stagingInstances []*api.Instance
+ var prodInstances []*api.Instance
+ for i, stagingInstanceDir := range stagingInstanceDirs {
+ instance, err := ctl.addInstance(
+ api.InstanceCreate{
+ EnvironmentID: stagingEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", stagingInstanceName, i),
+ Engine: db.SQLite,
+ Host: stagingInstanceDir,
+ },
+ )
+ a.NoError(err)
+ stagingInstances = append(stagingInstances, instance)
+ }
+ for i, prodInstanceDir := range prodInstanceDirs {
+ instance, err := ctl.addInstance(
+ api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: fmt.Sprintf("%s-%d", prodInstanceName, i),
+ Engine: db.SQLite,
+ Host: prodInstanceDir,
+ },
+ )
+ a.NoError(err)
+ prodInstances = append(prodInstances, instance)
+ }
- // Getting databases for each environment.
- databases, err := ctl.getDatabases(api.DatabaseFind{
- ProjectID: &project.ID,
- })
- a.NoError(err)
+ // Set up label values for tenants.
+ // Prod and staging are using the same tenant values. Use prodInstancesNumber because it's larger than stagingInstancesNumber.
+ var tenants []string
+ for i := 0; i < prodTenantNumber; i++ {
+ tenants = append(tenants, fmt.Sprintf("tenant%d", i))
+ }
+ err = ctl.addLabelValues(api.TenantLabelKey, tenants)
+ a.NoError(err)
- var stagingDatabases []*api.Database
- var prodDatabases []*api.Database
- for _, stagingInstance := range stagingInstances {
- for _, database := range databases {
- if database.Instance.ID == stagingInstance.ID {
- stagingDatabases = append(stagingDatabases, database)
- break
+ // Create deployment configuration.
+ _, err = ctl.upsertDeploymentConfig(
+ api.DeploymentConfigUpsert{
+ ProjectID: project.ID,
+ },
+ deploymentSchedule,
+ )
+ a.NoError(err)
+
+ // Create issues that create databases.
+ baseDatabaseName := "testTenantVCSSchemaUpdate"
+
+ for i, stagingInstance := range stagingInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ err := ctl.createDatabase(project, stagingInstance, databaseName, map[string]string{api.TenantLabelKey: tenant})
+ a.NoError(err)
}
- }
- }
- for _, prodInstance := range prodInstances {
- for _, database := range databases {
- if database.Instance.ID == prodInstance.ID {
- prodDatabases = append(prodDatabases, database)
- break
+ for i, prodInstance := range prodInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ err := ctl.createDatabase(project, prodInstance, databaseName, map[string]string{api.TenantLabelKey: tenant})
+ a.NoError(err)
}
- }
- }
- a.Equal(stagingTenantNumber, len(stagingDatabases))
- a.Equal(prodTenantNumber, len(prodDatabases))
- // Simulate Git commits.
- gitFile := "bbtest/testTenantVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
- pushEvent := &gitlab.WebhookPushEvent{
- ObjectKind: gitlab.WebhookPush,
- Ref: "refs/heads/feature/foo",
- Project: gitlab.WebhookProject{
- ID: gitlabProjectID,
- },
- CommitList: []gitlab.WebhookCommit{
- {
- Timestamp: "2021-01-13T13:14:00Z",
- AddedList: []string{
- gitFile,
+ // Getting databases for each environment.
+ databases, err := ctl.getDatabases(api.DatabaseFind{ProjectID: &project.ID})
+ a.NoError(err)
+
+ var stagingDatabases []*api.Database
+ var prodDatabases []*api.Database
+ for _, stagingInstance := range stagingInstances {
+ for _, database := range databases {
+ if database.Instance.ID == stagingInstance.ID {
+ stagingDatabases = append(stagingDatabases, database)
+ break
+ }
+ }
+ }
+ for _, prodInstance := range prodInstances {
+ for _, database := range databases {
+ if database.Instance.ID == prodInstance.ID {
+ prodDatabases = append(prodDatabases, database)
+ break
+ }
+ }
+ }
+ a.Equal(stagingTenantNumber, len(stagingDatabases))
+ a.Equal(prodTenantNumber, len(prodDatabases))
+
+ // Simulate Git commits.
+ gitFile := "bbtest/testTenantVCSSchemaUpdate__ver1__migrate__create_a_test_table.sql"
+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: migrationStatement})
+ a.NoError(err)
+
+ payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))
+ a.NoError(err)
+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ a.NoError(err)
+
+ // Get schema update issue.
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(
+ api.IssueFind{
+ ProjectID: &project.ID,
+ StatusList: &openStatus,
},
- },
- },
- }
- err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})
- a.NoError(err)
- payload, err := json.Marshal(pushEvent)
- a.NoError(err)
- err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)
- a.NoError(err)
+ )
+ a.NoError(err)
+ a.Len(issues, 1)
+ issue := issues[0]
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+
+ // Query schema.
+ for i, stagingInstance := range stagingInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ result, err := ctl.query(stagingInstance, databaseName, bookTableQuery)
+ a.NoError(err)
+ a.Equal(bookSchemaSQLResult, result)
+ }
+ for i, prodInstance := range prodInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ result, err := ctl.query(prodInstance, databaseName, bookTableQuery)
+ a.NoError(err)
+ a.Equal(bookSchemaSQLResult, result)
+ }
- // Get schema update issue.
- openStatus := []api.IssueStatus{api.IssueOpen}
- issues, err := ctl.getIssues(api.IssueFind{ProjectID: &project.ID, StatusList: &openStatus})
- a.NoError(err)
- a.Equal(1, len(issues))
- issue := issues[0]
- status, err := ctl.waitIssuePipeline(issue.ID)
- a.NoError(err)
- a.Equal(api.TaskDone, status)
+ // Query migration history
+ hm1 := map[string]bool{}
+ hm2 := map[string]bool{}
+ for i, instance := range stagingInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ histories, err := ctl.getInstanceMigrationHistory(
+ db.MigrationHistoryFind{
+ ID: &instance.ID,
+ Database: &databaseName,
+ },
+ )
+ a.NoError(err)
+ a.Len(histories, 2)
+ a.Equal(histories[0].Version, "ver1")
+ a.NotEqual(histories[1].Version, "")
+ hm1[histories[0].Version] = true
+ }
+ for i, instance := range prodInstances {
+ tenant := fmt.Sprintf("tenant%d", i)
+ databaseName := baseDatabaseName + "_" + tenant
+ histories, err := ctl.getInstanceMigrationHistory(
+ db.MigrationHistoryFind{
+ ID: &instance.ID,
+ Database: &databaseName,
+ },
+ )
+ a.NoError(err)
+ a.Len(histories, 2)
+ a.Equal("ver1", histories[0].Version)
+ a.NotEqual("", histories[1].Version)
+ hm2[histories[0].Version] = true
+ }
- // Query schema.
- for i, stagingInstance := range stagingInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- result, err := ctl.query(stagingInstance, databaseName, bookTableQuery)
- a.NoError(err)
- a.Equal(bookSchemaSQLResult, result)
- }
- for i, prodInstance := range prodInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- result, err := ctl.query(prodInstance, databaseName, bookTableQuery)
- a.NoError(err)
- a.Equal(bookSchemaSQLResult, result)
- }
+ a.Len(hm1, 1)
+ a.Len(hm2, 1)
- // Query migration history
- hm1 := map[string]bool{}
- hm2 := map[string]bool{}
- for i, instance := range stagingInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID, Database: &databaseName})
- a.NoError(err)
- a.Equal(2, len(histories))
- a.Equal(histories[0].Version, "ver1")
- a.NotEqual(histories[1].Version, "")
- hm1[histories[0].Version] = true
- }
- for i, instance := range prodInstances {
- tenant := fmt.Sprintf("tenant%d", i)
- databaseName := baseDatabaseName + "_" + tenant
- histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID, Database: &databaseName})
- a.NoError(err)
- a.Equal(2, len(histories))
- a.Equal("ver1", histories[0].Version)
- a.NotEqual("", histories[1].Version)
- hm2[histories[0].Version] = true
+ // Check latestSchemaFile
+ files, err := ctl.vcsProvider.GetFiles(test.externalID, fmt.Sprintf("%s/.%s__LATEST.sql", baseDirectory, baseDatabaseName))
+ a.NoError(err)
+ a.Len(files, 1)
+ })
}
-
- a.Equal(1, len(hm1))
- a.Equal(1, len(hm2))
-
- // Check latestSchemaFile
- files, err := ctl.vcsProvider.GetFiles(gitlabProjectIDStr, fmt.Sprintf("%s/.%s__LATEST.sql", baseDirectory, baseDatabaseName))
- a.NoError(err)
- a.Equal(1, len(files))
}
diff --git a/tests/tests.go b/tests/tests.go
index 12b7b797b2..3b6c55f46e 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -116,15 +116,19 @@ func getTestPort(testName string) int {
tests := []string{
"TestServiceRestart",
"TestSchemaAndDataUpdate",
- "TestVCS_GitLab",
+ "TestVCS/GitLab",
+ "TestVCS/GitHub",
"TestTenant",
- "TestTenantVCS_GitLab",
+ "TestTenantVCS/GitLab",
+ "TestTenantVCS/GitHub",
"TestTenantDatabaseNameTemplate",
"TestGhostSchemaUpdate",
"TestBackupRestoreBasic",
- "TestTenantVCSDatabaseNameTemplate_GitLab",
+ "TestTenantVCSDatabaseNameTemplate/GitLab",
+ "TestTenantVCSDatabaseNameTemplate/GitHub",
"TestBootWithExternalPg",
- "TestSheetVCS_GitLab",
+ "TestSheetVCS/GitLab",
+ "TestSheetVCS/GitHub",
"TestPrepare",
// PITR related cases