From 99223fc29f49c0f3d6b6dae762edc163b85dd373 Mon Sep 17 00:00:00 2001 From: yhua Date: Mon, 14 Nov 2016 14:46:20 +0800 Subject: [PATCH] update code for statics testing --- src/common/dao/register.go | 2 +- src/common/dao/user.go | 6 +- src/jobservice/job/statemachine.go | 2 +- src/ui/api/api_test.go | 9 --- src/ui/api/dataprepare_test.go | 33 +++++++-- src/ui/api/harborapi_test.go | 15 ++-- src/ui/api/project.go | 2 +- src/ui/api/statistic_test.go | 111 +++++++++++++---------------- src/ui/api/user.go | 14 ++-- src/ui/auth/ldap/ldap.go | 4 +- src/ui/main.go | 2 +- 11 files changed, 102 insertions(+), 98 deletions(-) delete mode 100644 src/ui/api/api_test.go diff --git a/src/common/dao/register.go b/src/common/dao/register.go index 770eb6de8..3b1d27a13 100644 --- a/src/common/dao/register.go +++ b/src/common/dao/register.go @@ -52,7 +52,7 @@ func Register(user models.User) (int64, error) { func UserExists(user models.User, target string) (bool, error) { if user.Username == "" && user.Email == "" { - return false, errors.New("User name and email are blank.") + return false, errors.New("user name and email are blank") } o := GetOrmer() diff --git a/src/common/dao/user.go b/src/common/dao/user.go index 765a504db..2ba35021a 100644 --- a/src/common/dao/user.go +++ b/src/common/dao/user.go @@ -131,7 +131,7 @@ func ToggleUserAdminRole(userID, hasAdmin int) error { // ChangeUserPassword ... func ChangeUserPassword(u models.User, oldPassword ...string) (err error) { if len(oldPassword) > 1 { - return errors.New("Wrong numbers of params.") + return errors.New("wrong numbers of params") } o := GetOrmer() @@ -153,7 +153,7 @@ func ChangeUserPassword(u models.User, oldPassword ...string) (err error) { return err } if c == 0 { - return errors.New("No record has been modified, change password failed.") + return errors.New("no record has been modified, change password failed") } return nil @@ -171,7 +171,7 @@ func ResetUserPassword(u models.User) error { return err } if count == 0 { - return errors.New("No record be changed, reset password failed.") + return errors.New("no record be changed, reset password failed") } return nil } diff --git a/src/jobservice/job/statemachine.go b/src/jobservice/job/statemachine.go index f0a02480a..fd12d5443 100644 --- a/src/jobservice/job/statemachine.go +++ b/src/jobservice/job/statemachine.go @@ -64,7 +64,7 @@ func (sm *SM) EnterState(s string) (string, error) { _, exist := targets[s] _, isForced := sm.ForcedStates[s] if !exist && !isForced { - return "", fmt.Errorf("Job id: %d, transition from %s to %s does not exist!", sm.JobID, sm.CurrentState, s) + return "", fmt.Errorf("job id: %d, transition from %s to %s does not exist", sm.JobID, sm.CurrentState, s) } exitHandler, ok := sm.Handlers[sm.CurrentState] if ok { diff --git a/src/ui/api/api_test.go b/src/ui/api/api_test.go deleted file mode 100644 index ce188a790..000000000 --- a/src/ui/api/api_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package api - -import ( - "testing" -) - -func TestMain(t *testing.T) { -} - diff --git a/src/ui/api/dataprepare_test.go b/src/ui/api/dataprepare_test.go index 928c517a1..c6fb6488a 100644 --- a/src/ui/api/dataprepare_test.go +++ b/src/ui/api/dataprepare_test.go @@ -16,18 +16,22 @@ package api import ( + "os" + "github.com/vmware/harbor/src/common/dao" "github.com/vmware/harbor/src/common/models" - "os" ) const ( //Prepare Test info - TestUserName = "testUser0001" - TestUserPwd = "testUser0001" - TestUserEmail = "testUser0001@mydomain.com" - TestProName = "testProject0001" - TestTargetName = "testTarget0001" + TestUserName = "testUser0001" + TestUserPwd = "testUser0001" + TestUserEmail = "testUser0001@mydomain.com" + TestProName = "testProject0001" + TestTargetName = "testTarget0001" + TestRepoName = "testRepo0001" + AdminName = "admin" + DefaultProjectName = "library" ) func CommonAddUser() { @@ -104,3 +108,20 @@ func CommonDelTarget() { func CommonPolicyEabled(policyID int, enabled int) { _ = dao.UpdateRepPolicyEnablement(int64(policyID), enabled) } + +func CommonAddRepository() { + commonRepository := &models.RepoRecord{ + RepositoryID: "1", + Name: TestRepoName, + OwnerName: AdminName, + OwnerID: 1, + ProjectName: DefaultProjectName, + ProjectID: 1, + PullCount: 1, + } + _ = dao.AddRepository(*commonRepository) +} + +func CommonDelRepository() { + _ = dao.DeleteRepository(TestRepoName) +} diff --git a/src/ui/api/harborapi_test.go b/src/ui/api/harborapi_test.go index 3169a6ed9..749927438 100644 --- a/src/ui/api/harborapi_test.go +++ b/src/ui/api/harborapi_test.go @@ -174,19 +174,20 @@ func (a testapi) ProjectsPost(prjUsr usrInfo, project apilib.ProjectReq) (int, e return httpStatusCode, err } -func (a testapi) StatisticGet(user usrInfo) (apilib.StatisticMap, error) { +func (a testapi) StatisticGet(user usrInfo) (int, apilib.StatisticMap, error) { _sling := sling.New().Get(a.basePath) // create path and map variables path := "/api/statistics/" - fmt.Printf("project statistic path: %s\n", path) + _sling = _sling.Path(path) - var successPayload = new(apilib.StatisticMap) - code, body, err := request(_sling, jsonAcceptHeader, user) - if 200 == code && nil == err { + var successPayload apilib.StatisticMap + httpStatusCode, body, err := request(_sling, jsonAcceptHeader, user) + + if err == nil && httpStatusCode == 200 { err = json.Unmarshal(body, &successPayload) } - return *successPayload, err + return httpStatusCode, successPayload, err } func (a testapi) LogGet(user usrInfo, startTime, endTime, lines string) (int, []apilib.AccessLog, error) { @@ -857,7 +858,7 @@ func updateInitPassword(userID int, password string) error { return fmt.Errorf("Failed to get user, userID: %d %v", userID, err) } if user == nil { - return fmt.Errorf("User id: %d does not exist.", userID) + return fmt.Errorf("user id: %d does not exist", userID) } if user.Salt == "" { user.Salt = utils.GenerateRandomString() diff --git a/src/ui/api/project.go b/src/ui/api/project.go index 9905630ec..d4212f762 100644 --- a/src/ui/api/project.go +++ b/src/ui/api/project.go @@ -413,7 +413,7 @@ func validateProjectReq(req projectReq) error { validProjectName := regexp.MustCompile(`^[a-z0-9](?:-*[a-z0-9])*(?:[._][a-z0-9](?:-*[a-z0-9])*)*$`) legal := validProjectName.MatchString(pn) if !legal { - return fmt.Errorf("Project name is not in lower case or contains illegal characters!") + return fmt.Errorf("project name is not in lower case or contains illegal characters") } return nil } diff --git a/src/ui/api/statistic_test.go b/src/ui/api/statistic_test.go index 37400bea4..64d87d421 100644 --- a/src/ui/api/statistic_test.go +++ b/src/ui/api/statistic_test.go @@ -2,14 +2,14 @@ package api import ( "fmt" - "strconv" "testing" "github.com/stretchr/testify/assert" - "github.com/vmware/harbor/tests/apitests/apilib" + //"github.com/vmware/harbor/tests/apitests/apilib" ) func TestStatisticGet(t *testing.T) { + fmt.Println("Testing Statistic API") assert := assert.New(t) @@ -17,69 +17,60 @@ func TestStatisticGet(t *testing.T) { //prepare for test - var myProCount, pubProCount, totalProCount int32 - result, err := apiTest.StatisticGet(*admin) + var priMyProjectCount, priMyRepoCount int32 + var priPublicProjectCount, priPublicRepoCount int32 + var priTotalProjectCount, priTotalRepoCount int32 + + //case 1: case 1: user not login, expect fail to get status info. + fmt.Println("case 1: user not login, expect fail to get status info.") + httpStatusCode, result, err := apiTest.StatisticGet(*unknownUsr) + if err != nil { + t.Error("Error get statistic info.", err.Error()) + t.Log(err) + } else { + assert.Equal(httpStatusCode, int(401), "Case 1: Get status info without login. (401)") + } + + //case 2: admin successful login, expect get status info successful. + fmt.Println("case 2: admin successful login, expect get status info successful.") + httpStatusCode, result, err = apiTest.StatisticGet(*admin) + if err != nil { + t.Error("Error get statistic info.", err.Error()) + t.Log(err) + } else { + assert.Equal(httpStatusCode, int(200), "Case 2: Get status info with admin login. (200)") + //fmt.Println("pri status data %+v", result) + priMyProjectCount = result.MyProjectCount + priMyRepoCount = result.MyRepoCount + priPublicProjectCount = result.PublicProjectCount + priPublicRepoCount = result.PublicRepoCount + priTotalProjectCount = result.TotalProjectCount + priTotalRepoCount = result.TotalRepoCount + } + + //case 3: status info increased after add more project and repo. + fmt.Println("case 3: status info increased after add more project and repo.") + + CommonAddProject() + CommonAddRepository() + + httpStatusCode, result, err = apiTest.StatisticGet(*admin) + //fmt.Println("new status data %+v", result) + if err != nil { t.Error("Error while get statistic information", err.Error()) t.Log(err) } else { - myProCount = result.MyProjectCount - pubProCount = result.PublicProjectCount - totalProCount = result.TotalProjectCount - } - //post project - var project apilib.ProjectReq - project.ProjectName = "statistic_project" - project.Public = 1 - - //case 2: admin successful login, expect project creation success. - fmt.Println("case 2: admin successful login, expect project creation success.") - reply, err := apiTest.ProjectsPost(*admin, project) - if err != nil { - t.Error("Error while creat project", err.Error()) - t.Log(err) - } else { - assert.Equal(reply, int(201), "Case 2: Project creation status should be 201") - } - - //get and compare - result, err = apiTest.StatisticGet(*admin) - if err != nil { - t.Error("Error while get statistic information", err.Error()) - t.Log(err) - } else { - assert.Equal(myProCount+1, result.MyProjectCount, "MyProjectCount should be equal") - assert.Equal(int32(2), result.MyRepoCount, "MyRepoCount should be equal") - assert.Equal(pubProCount+1, result.PublicProjectCount, "PublicProjectCount should be equal") - assert.Equal(int32(2), result.PublicRepoCount, "PublicRepoCount should be equal") - assert.Equal(totalProCount+1, result.TotalProjectCount, "TotalProCount should be equal") - assert.Equal(int32(2), result.TotalRepoCount, "TotalRepoCount should be equal") + assert.Equal(priMyProjectCount+1, result.MyProjectCount, "MyProjectCount should be +1") + assert.Equal(priMyRepoCount+1, result.MyRepoCount, "MyRepoCount should be +1") + assert.Equal(priPublicProjectCount, result.PublicProjectCount, "PublicProjectCount should be equal") + assert.Equal(priPublicRepoCount+1, result.PublicRepoCount, "PublicRepoCount should be +1") + assert.Equal(priTotalProjectCount+1, result.TotalProjectCount, "TotalProCount should be +1") + assert.Equal(priTotalRepoCount+1, result.TotalRepoCount, "TotalRepoCount should be +1") } - //get the project - var projects []apilib.Project - var addProjectID int32 - httpStatusCode, projects, err := apiTest.ProjectsGet(project.ProjectName, 1) - if err != nil { - t.Error("Error while search project by proName and isPublic", err.Error()) - t.Log(err) - } else { - assert.Equal(int(200), httpStatusCode, "httpStatusCode should be 200") - addProjectID = projects[0].ProjectId - } - - //delete the project - projectID := strconv.Itoa(int(addProjectID)) - httpStatusCode, err = apiTest.ProjectsDelete(*admin, projectID) - if err != nil { - t.Error("Error while delete project", err.Error()) - t.Log(err) - } else { - assert.Equal(int(200), httpStatusCode, "Case 1: Project creation status should be 200") - //t.Log(result) - } - - fmt.Printf("\n") - + //delete the project and repo + CommonDelProject() + CommonDelRepository() } diff --git a/src/ui/api/user.go b/src/ui/api/user.go index 17def3bf1..3a0387390 100644 --- a/src/ui/api/user.go +++ b/src/ui/api/user.go @@ -323,13 +323,13 @@ func (ua *UserAPI) ToggleUserAdminRole() { func validate(user models.User) error { if isIllegalLength(user.Username, 1, 20) { - return fmt.Errorf("Username with illegal length.") + return fmt.Errorf("username with illegal length") } if isContainIllegalChar(user.Username, []string{",", "~", "#", "$", "%"}) { - return fmt.Errorf("Username contains illegal characters.") + return fmt.Errorf("username contains illegal characters") } if isIllegalLength(user.Password, 8, 20) { - return fmt.Errorf("Password with illegal length.") + return fmt.Errorf("password with illegal length") } if err := commonValidate(user); err != nil { return err @@ -342,21 +342,21 @@ func commonValidate(user models.User) error { if len(user.Email) > 0 { if m, _ := regexp.MatchString(`^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`, user.Email); !m { - return fmt.Errorf("Email with illegal format.") + return fmt.Errorf("email with illegal format") } } else { return fmt.Errorf("Email can't be empty") } if isIllegalLength(user.Realname, 0, 20) { - return fmt.Errorf("Realname with illegal length.") + return fmt.Errorf("realname with illegal length") } if isContainIllegalChar(user.Realname, []string{",", "~", "#", "$", "%"}) { - return fmt.Errorf("Realname contains illegal characters.") + return fmt.Errorf("realname contains illegal characters") } if isIllegalLength(user.Comment, -1, 30) { - return fmt.Errorf("Comment with illegal length.") + return fmt.Errorf("comment with illegal length") } return nil diff --git a/src/ui/auth/ldap/ldap.go b/src/ui/auth/ldap/ldap.go index 26f124e67..6193485f1 100644 --- a/src/ui/auth/ldap/ldap.go +++ b/src/ui/auth/ldap/ldap.go @@ -48,7 +48,7 @@ func (l *Auth) Authenticate(m models.AuthModel) (*models.User, error) { } ldapURL := os.Getenv("LDAP_URL") if ldapURL == "" { - return nil, errors.New("Can not get any available LDAP_URL.") + return nil, errors.New("can not get any available LDAP_URL") } log.Debug("ldapURL:", ldapURL) ldap, err := openldap.Initialize(ldapURL) @@ -59,7 +59,7 @@ func (l *Auth) Authenticate(m models.AuthModel) (*models.User, error) { ldapBaseDn := os.Getenv("LDAP_BASE_DN") if ldapBaseDn == "" { - return nil, errors.New("Can not get any available LDAP_BASE_DN.") + return nil, errors.New("can not get any available LDAP_BASE_DN") } log.Debug("baseDn:", ldapBaseDn) diff --git a/src/ui/main.go b/src/ui/main.go index 0111f6537..d355a11cc 100644 --- a/src/ui/main.go +++ b/src/ui/main.go @@ -43,7 +43,7 @@ func updateInitPassword(userID int, password string) error { return fmt.Errorf("Failed to get user, userID: %d %v", userID, err) } if user == nil { - return fmt.Errorf("User id: %d does not exist.", userID) + return fmt.Errorf("user id: %d does not exist", userID) } if user.Salt == "" { salt := utils.GenerateRandomString()