Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Abstract fake.VCSProvider and update controller (#2049)
Joe Chen50739617a2ba
diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 172ebba0a3..12e7937f80 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -1,9 +1,11 @@package fakeimport (+ "bytes""encoding/json""fmt""io"+ "net""net/http""net/url""path/filepath"@@ -17,10 +19,10 @@ import ("github.com/bytebase/bytebase/plugin/vcs/gitlab")-// GitLab is a fake implementation of GitLab.+// GitLab is a fake implementation of GitLab VCS provider.type GitLab struct {port int- Echo *echo.Echo+ echo *echo.Echoclient *http.Client@@ -30,12 +32,13 @@ type GitLab struct {type projectData struct {webhooks []*gitlab.WebhookCreate- // files is a map that the full file path is the key and the file content is the value.+ // files is a map that the full file path is the key and the file content is the+ // value.files map[string]string}-// NewGitLab creates a fake GitLab.-func NewGitLab(port int) *GitLab {+// NewGitLab creates a new fake implementation of GitLab VCS provider.+func NewGitLab(port int) VCSProvider {e := echo.New()// Middlewaree.Use(middleware.Logger())@@ -43,7 +46,7 @@ func NewGitLab(port int) *GitLab {gl := &GitLab{port: port,- Echo: e,+ echo: e,client: &http.Client{},nextWebhookID: 20210113,projects: map[string]*projectData{},@@ -62,18 +65,23 @@ func NewGitLab(port int) *GitLab {return gl}-// Run runs a GitLab server.+// Run starts the GitLab VCS provider server.func (gl *GitLab) Run() error {- return gl.Echo.Start(fmt.Sprintf(":%d", gl.port))+ return gl.echo.Start(fmt.Sprintf(":%d", gl.port))}-// Close close a GitLab server.+// Close shuts down the GitLab VCS provider server.func (gl *GitLab) Close() error {- return gl.Echo.Close()+ return gl.echo.Close()}-// CreateProject creates a GitLab project.-func (gl *GitLab) CreateProject(id string) {+// ListenerAddr returns the GitLab VCS provider server listener address.+func (gl *GitLab) ListenerAddr() net.Addr {+ return gl.echo.ListenerAddr()+}++// CreateRepository creates a GitLab project with given ID.+func (gl *GitLab) CreateRepository(id string) {gl.projects[id] = &projectData{files: map[string]string{},}@@ -81,7 +89,7 @@ func (gl *GitLab) CreateProject(id string) {// createProjectHook creates a project webhook.func (gl *GitLab) createProjectHook(c echo.Context) error {- gitlabProjectID := c.Param("id")+ projectID := c.Param("id")c.Logger().Info("create webhook for project %q", c.Param("id"))b, err := io.ReadAll(c.Request().Body)if err != nil {@@ -91,9 +99,9 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {if err := json.Unmarshal(b, webhookCreate); err != nil {return fmt.Errorf("failed to unmarshal create project hook request body, error %w", err)}- pd, ok := gl.projects[gitlabProjectID]+ pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)+ return fmt.Errorf("gitlab project %q doesn't exist", projectID)}pd.webhooks = append(pd.webhooks, webhookCreate)@@ -109,11 +117,11 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {// readProjectTree reads a project file nodes.func (gl *GitLab) readProjectTree(c echo.Context) error {- gitlabProjectID := c.Param("id")+ projectID := c.Param("id")path := c.QueryParam("path")- pd, ok := gl.projects[gitlabProjectID]+ pd, ok := gl.projects[projectID]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}fileNodes := []*vcs.RepositoryTreeNode{}@@ -137,16 +145,16 @@ func (gl *GitLab) readProjectTree(c echo.Context) error {// readProjectFile reads a project file.func (gl *GitLab) readProjectFile(c echo.Context) error {- gitlabProjectID := c.Param("id")+ projectID := c.Param("id")filePathEscaped := c.Param("filePath")filePath, err := url.QueryUnescape(filePathEscaped)if err != nil {return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", filePathEscaped, err))}- pd, ok := gl.projects[gitlabProjectID]+ pd, ok := gl.projects[projectID]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}content, ok := pd.files[filePath]@@ -159,16 +167,16 @@ func (gl *GitLab) readProjectFile(c echo.Context) error {// readProjectFileMetadata reads a project file metadata.func (gl *GitLab) readProjectFileMetadata(c echo.Context) error {- gitlabProjectID := c.Param("id")+ projectID := c.Param("id")filePathEscaped := c.Param("filePath")filePath, err := url.QueryUnescape(filePathEscaped)if err != nil {return c.String(http.StatusBadRequest, fmt.Sprintf("failed to query unescape %q, error: %v", filePathEscaped, err))}- pd, ok := gl.projects[gitlabProjectID]+ pd, ok := gl.projects[projectID]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}if _, ok := pd.files[filePath]; !ok {@@ -193,10 +201,10 @@ func (gl *GitLab) readProjectFileMetadata(c echo.Context) error {// getFakeCommit get a fake commit data.func (gl *GitLab) getFakeCommit(c echo.Context) error {- gitlabProjectID := c.Param("id")- _, ok := gl.projects[gitlabProjectID]+ projectID := c.Param("id")+ _, ok := gl.projects[projectID]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}commit := gitlab.Commit{@@ -214,7 +222,7 @@ func (gl *GitLab) getFakeCommit(c echo.Context) error {// createProjectFile creates a project file.func (gl *GitLab) createProjectFile(c echo.Context) error {- gitlabProjectID := c.Param("id")+ projectID := c.Param("id")filePathEscaped := c.Param("filePath")filePath, err := url.QueryUnescape(filePathEscaped)if err != nil {@@ -229,9 +237,9 @@ func (gl *GitLab) createProjectFile(c echo.Context) error {return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unmarshal create project file request body, error %v", err))}- pd, ok := gl.projects[gitlabProjectID]+ pd, ok := gl.projects[projectID]if !ok {- return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", gitlabProjectID))+ return c.String(http.StatusBadRequest, fmt.Sprintf("gitlab project %q doesn't exist", projectID))}// Save file.@@ -240,21 +248,18 @@ func (gl *GitLab) createProjectFile(c echo.Context) error {return c.String(http.StatusOK, "")}-// SendCommits sends comments to webhooks.-func (gl *GitLab) SendCommits(gitlabProjectID string, webhookPushEvent *gitlab.WebhookPushEvent) error {- pd, ok := gl.projects[gitlabProjectID]+// SendWebhookPush sends out a webhook for a push event for the GitLab project+// using given payload.+func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {+ pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)+ return fmt.Errorf("gitlab project %q doesn't exist", projectID)}// Trigger webhooks.for _, webhook := range pd.webhooks {// Send post request.- buf, err := json.Marshal(webhookPushEvent)- if err != nil {- return fmt.Errorf("failed to marshal webhookPushEvent, error %w", err)- }- req, err := http.NewRequest("POST", webhook.URL, strings.NewReader(string(buf)))+ req, err := http.NewRequest("POST", webhook.URL, bytes.NewReader(payload))if err != nil {return fmt.Errorf("fail to create a new POST request(%q), error: %w", webhook.URL, err)}@@ -271,17 +276,17 @@ func (gl *GitLab) SendCommits(gitlabProjectID string, webhookPushEvent *gitlab.Wif resp.StatusCode != http.StatusOK {return fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}- gl.Echo.Logger.Infof("SendCommits response body %s\n", body)+ gl.echo.Logger.Infof("SendWebhookPush response body %s\n", body)}return nil}-// AddFiles add files to repository.-func (gl *GitLab) AddFiles(gitlabProjectID string, files map[string]string) error {- pd, ok := gl.projects[gitlabProjectID]+// AddFiles adds given files to the GitLab project.+func (gl *GitLab) AddFiles(projectID string, files map[string]string) error {+ pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)+ return fmt.Errorf("gitlab project %q doesn't exist", projectID)}// Save files@@ -291,11 +296,11 @@ func (gl *GitLab) AddFiles(gitlabProjectID string, files map[string]string) erroreturn nil}-// GetFiles get files from repository.-func (gl *GitLab) GetFiles(gitlabProjectID string, filePaths ...string) (map[string]string, error) {- pd, ok := gl.projects[gitlabProjectID]+// GetFiles returns files with given paths from the GitLab project.+func (gl *GitLab) GetFiles(projectID string, filePaths ...string) (map[string]string, error) {+ pd, ok := gl.projects[projectID]if !ok {- return nil, fmt.Errorf("gitlab project %q doesn't exist", gitlabProjectID)+ return nil, fmt.Errorf("gitlab project %q doesn't exist", projectID)}// Get filesdiff --git a/tests/fake/provider.go b/tests/fake/provider.gonew file mode 100644index 0000000000..1b9b91b07c--- /dev/null+++ b/tests/fake/provider.go@@ -0,0 +1,25 @@+package fake++import (+ "net"+)++// VCSProvider is a fake implementation of a VCS provider.+type VCSProvider interface {+ // Run starts the server of the VCS provider.+ Run() error+ // Close shuts down the server of the VCS provider.+ Close() error+ // ListenerAddr returns listener address of the server.+ ListenerAddr() net.Addr++ // CreateRepository creates a new repository with given ID.+ CreateRepository(id string)+ // SendWebhookPush sends out a webhook for a push event for the repository using+ // given payload.+ SendWebhookPush(repositoryID string, payload []byte) error+ // AddFiles adds given files to the repository.+ AddFiles(repositoryID string, files map[string]string) error+ // GetFiles returns files with given paths from the repository.+ GetFiles(repositoryID string, filePaths ...string) (map[string]string, error)+}diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 9f21c17689..41818576f4 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -8,11 +8,12 @@ import ("path""testing"+ "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/gitlab"- "github.com/stretchr/testify/require")func TestSchemaAndDataUpdate(t *testing.T) {@@ -272,7 +273,7 @@ func TestSchemaAndDataUpdate(t *testing.T) {a.NoError(err)}-func TestVCS(t *testing.T) {+func TestVCS_GitLab(t *testing.T) {t.Parallel()a := require.New(t)ctx := context.Background()@@ -312,8 +313,8 @@ func TestVCS(t *testing.T) {refreshToken := "refreshToken1"gitlabProjectID := 121gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)- // create a gitlab project.- ctl.gitlab.CreateProject(gitlabProjectIDStr)+ // create a vcsProvider project.+ ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)_, err = ctl.createRepository(api.RepositoryCreate{VCSID: vcs.ID,ProjectID: project.ID,@@ -373,10 +374,12 @@ func TestVCS(t *testing.T) {},},}- err = ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})+ err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})a.NoError(err)- err = ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent)+ payload, err := json.Marshal(pushEvent)+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)a.NoError(err)// Get schema update issue.@@ -416,10 +419,12 @@ func TestVCS(t *testing.T) {},},}- err = ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: dataUpdateStatement})+ err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: dataUpdateStatement})a.NoError(err)- err = ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent)+ payload, err = json.Marshal(pushEvent)+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)a.NoError(err)// Get data update issue.diff --git a/tests/sheet_vcs_test.go b/tests/sheet_vcs_test.goindex 5c54f46518..1b9bbfe888 100644--- a/tests/sheet_vcs_test.go+++ b/tests/sheet_vcs_test.go@@ -5,12 +5,13 @@ import ("fmt""testing"+ "github.com/stretchr/testify/require"+"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/plugin/vcs"- "github.com/stretchr/testify/require")-func TestSheetVCS(t *testing.T) {+func TestSheetVCS_GitLab(t *testing.T) {t.Parallel()a := require.New(t)ctx := context.Background()@@ -50,8 +51,8 @@ func TestSheetVCS(t *testing.T) {refreshToken := "refreshToken"gitlabProjectID := 121gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)- // create a gitlab project.- ctl.gitlab.CreateProject(gitlabProjectIDStr)+ // create a vcsProvider project.+ ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)_, err = ctl.createRepository(api.RepositoryCreate{VCSID: vcs.ID,ProjectID: project.ID,@@ -75,7 +76,7 @@ func TestSheetVCS(t *testing.T) {gitFile := "sheet/all_employee.sql"fileContent := "SELECT * FROM employee"files[gitFile] = fileContent- err = ctl.gitlab.AddFiles(gitlabProjectIDStr, files)+ err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, files)a.NoError(err)err = ctl.syncSheet(project.ID)diff --git a/tests/tenant_test.go b/tests/tenant_test.goindex f6ce55f0f6..afd0ffe9da 100644--- a/tests/tenant_test.go+++ b/tests/tenant_test.go@@ -6,11 +6,12 @@ import ("fmt""testing"+ "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/gitlab"- "github.com/stretchr/testify/require")var (@@ -202,7 +203,7 @@ func TestTenant(t *testing.T) {a.Equal(1, len(hm2))}-func TestTenantVCS(t *testing.T) {+func TestTenantVCS_GitLab(t *testing.T) {t.Parallel()a := require.New(t)ctx := context.Background()@@ -243,8 +244,8 @@ func TestTenantVCS(t *testing.T) {refreshToken := "refreshToken1"gitlabProjectID := 121gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)- // create a gitlab project.- ctl.gitlab.CreateProject(gitlabProjectIDStr)+ // create a vcsProvider project.+ ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)_, err = ctl.createRepository(api.RepositoryCreate{VCSID: vcs.ID,ProjectID: project.ID,@@ -381,9 +382,11 @@ func TestTenantVCS(t *testing.T) {},},}- err = ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})+ err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})a.NoError(err)- err = ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent)+ payload, err := json.Marshal(pushEvent)+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)a.NoError(err)// Get schema update issue.@@ -581,7 +584,7 @@ func TestTenantDatabaseNameTemplate(t *testing.T) {}}-func TestTenantVCSDatabaseNameTemplate(t *testing.T) {+func TestTenantVCSDatabaseNameTemplate_GitLab(t *testing.T) {t.Parallel()a := require.New(t)ctx := context.Background()@@ -623,8 +626,8 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {refreshToken := "refreshToken1"gitlabProjectID := 121gitlabProjectIDStr := fmt.Sprintf("%d", gitlabProjectID)- // create a gitlab project.- ctl.gitlab.CreateProject(gitlabProjectIDStr)+ // create a vcsProvider project.+ ctl.vcsProvider.CreateRepository(gitlabProjectIDStr)_, err = ctl.createRepository(api.RepositoryCreate{VCSID: vcs.ID,ProjectID: project.ID,@@ -766,9 +769,11 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {},},}- err = ctl.gitlab.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})+ err = ctl.vcsProvider.AddFiles(gitlabProjectIDStr, map[string]string{gitFile: migrationStatement})+ a.NoError(err)+ payload, err := json.Marshal(pushEvent)a.NoError(err)- err = ctl.gitlab.SendCommits(gitlabProjectIDStr, pushEvent)+ err = ctl.vcsProvider.SendWebhookPush(gitlabProjectIDStr, payload)a.NoError(err)// Get schema update issue.@@ -825,7 +830,7 @@ func TestTenantVCSDatabaseNameTemplate(t *testing.T) {a.Equal(1, len(hm2))// Check latestSchemaFile- files, err := ctl.gitlab.GetFiles(gitlabProjectIDStr, fmt.Sprintf("%s/.%s__LATEST.sql", baseDirectory, baseDatabaseName))+ 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.goindex 0d79a4d77c..d49b3d69ff 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -6,8 +6,6 @@ import ("embed""encoding/json""fmt"- "strconv"-"io""io/fs""net/http"@@ -15,9 +13,13 @@ import ("os""path""reflect"+ "strconv""strings""time"+ "github.com/google/jsonapi"+ "go.uber.org/zap"+"github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/bin/server/cmd""github.com/bytebase/bytebase/common/log"@@ -26,8 +28,6 @@ import ("github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/server""github.com/bytebase/bytebase/tests/fake"- "github.com/google/jsonapi"- "go.uber.org/zap")//go:embed fake@@ -100,10 +100,10 @@ var ()type controller struct {- server *server.Server- client *http.Client- cookie string- gitlab *fake.GitLab+ server *server.Server+ client *http.Client+ cookie string+ vcsProvider fake.VCSProviderrootURL stringapiURL string@@ -117,15 +117,15 @@ func getTestPort(testName string) int {tests := []string{"TestServiceRestart","TestSchemaAndDataUpdate",- "TestVCS",+ "TestVCS_GitLab","TestTenant",- "TestTenantVCS",+ "TestTenantVCS_GitLab","TestTenantDatabaseNameTemplate","TestGhostSchemaUpdate","TestBackupRestoreBasic",- "TestTenantVCSDatabaseNameTemplate",+ "TestTenantVCSDatabaseNameTemplate_GitLab","TestBootWithExternalPg",- "TestSheetVCS",+ "TestSheetVCS_GitLab","TestPrepare",// PITR related cases@@ -185,9 +185,9 @@ func (ctl *controller) start(ctx context.Context, port int) error {ctl.rootURL = fmt.Sprintf("http://localhost:%d", port)ctl.apiURL = fmt.Sprintf("http://localhost:%d/api", port)- // set up gitlab.+ // set up vcsProvider.gitlabPort := port + 2- ctl.gitlab = fake.NewGitLab(gitlabPort)+ ctl.vcsProvider = fake.NewGitLab(gitlabPort)ctl.gitURL = fmt.Sprintf("http://localhost:%d", gitlabPort)ctl.gitAPIURL = fmt.Sprintf("%s/api/v4", ctl.gitURL)@@ -200,16 +200,16 @@ func (ctl *controller) start(ctx context.Context, port int) error {}()go func() {- if err := ctl.gitlab.Run(); err != nil {- errChan <- fmt.Errorf("failed to run gitlab server, error: %w", err)+ if err := ctl.vcsProvider.Run(); err != nil {+ errChan <- fmt.Errorf("failed to run vcsProvider server, error: %w", err)}}()if err := waitForServerStart(ctl.server, errChan); err != nil {return fmt.Errorf("failed to wait for server to start, error: %w", err)}- if err := waitForGitLabStart(ctl.gitlab, errChan); err != nil {- return fmt.Errorf("failed to wait for gitlab to start, error: %w", err)+ if err := waitForVCSStart(ctl.vcsProvider, errChan); err != nil {+ return fmt.Errorf("failed to wait for vcsProvider to start, error: %w", err)}// initialize controller clients.@@ -249,17 +249,14 @@ func waitForServerStart(s *server.Server, errChan <-chan error) error {}}-func waitForGitLabStart(g *fake.GitLab, errChan <-chan error) error {+func waitForVCSStart(p fake.VCSProvider, errChan <-chan error) error {ticker := time.NewTicker(100 * time.Millisecond)defer ticker.Stop()for {select {case <-ticker.C:- if g.Echo == nil {- continue- }- addr := g.Echo.ListenerAddr()+ addr := p.ListenerAddr()if addr != nil && strings.Contains(addr.String(), ":") {return nil // was started}@@ -321,8 +318,8 @@ func (ctl *controller) Close(ctx context.Context) error {if ctl.server != nil {e = ctl.server.Shutdown(ctx)}- if ctl.gitlab != nil {- if err := ctl.gitlab.Close(); err != nil {+ if ctl.vcsProvider != nil {+ if err := ctl.vcsProvider.Close(); err != nil {e = err}}