Skip to content

Commit

Permalink
add: url service test
Browse files Browse the repository at this point in the history
  • Loading branch information
FantasyRL committed Dec 14, 2024
1 parent 9adae81 commit 64f0562
Show file tree
Hide file tree
Showing 10 changed files with 567 additions and 27 deletions.
28 changes: 14 additions & 14 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,19 @@ import (
)

var (
Server *server
Mysql *mySQL
Snowflake *snowflake
Service *service
Jaeger *jaeger
Etcd *etcd
Redis *redis
DefaultUser *defaultUser
Elasticsearch *elasticsearch
Kafka *kafka
UpYun *upyun
UrlService *url
runtimeViper = viper.New()
Server *server
Mysql *mySQL
Snowflake *snowflake
Service *service
Jaeger *jaeger
Etcd *etcd
Redis *redis
DefaultUser *defaultUser
Elasticsearch *elasticsearch
Kafka *kafka
UpYun *upyun
VersionUploadService *url
runtimeViper = viper.New()
)

func Init(service string) {
Expand Down Expand Up @@ -89,7 +89,7 @@ func configMapping(srv string) {
Elasticsearch = &c.Elasticsearch
Kafka = &c.Kafka
DefaultUser = &c.DefaultUser
UrlService = &c.Url
VersionUploadService = &c.Url

Check warning on line 92 in config/config.go

View check run for this annotation

Codecov / codecov/patch

config/config.go#L92

Added line #L92 was not covered by tests
upy, ok := c.UpYuns[srv]
if ok {
UpYun = &upy
Expand Down
97 changes: 97 additions & 0 deletions internal/version/service/get_all_setting_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package service

import (
"fmt"
"github.com/west2-online/fzuhelper-server/pkg/upyun"
"testing"

"github.com/bytedance/mockey"
"github.com/stretchr/testify/assert"
)

func TestGetAllCloudSetting(t *testing.T) {
type testCase struct {
name string // 测试用例名称
mockSettingJson *[]byte // mock返回的设置 JSON 数据
mockError error // mock返回的错误
expectedResult *[]byte // 期望返回的结果
expectingError bool // 是否期望抛出错误
expectedErrorInfo string // 期望的错误信息
mockCommentedJson string // 模拟带注释的 JSON 数据
mockCommentedError error // 模拟去掉注释过程的错误
}

mockResult := []byte(`{"key": "value"}`)
// 测试用例
testCases := []testCase{
{
name: "SuccessCase",
mockSettingJson: &mockResult,
mockError: nil,
expectedResult: &mockResult,
expectingError: false,
expectedErrorInfo: "",
mockCommentedJson: `{"key": "value"}`,
mockCommentedError: nil,
},
{
name: "FileNotFound",
mockSettingJson: nil,
mockError: fmt.Errorf("file not found"),
expectedResult: nil,
expectingError: true,
expectedErrorInfo: "VersionService.GetAllCloudSetting error:file not found",
mockCommentedJson: "",
mockCommentedError: nil,
},
{
name: "RemoveCommentsError",
mockSettingJson: &mockResult,
mockError: nil,
expectedResult: nil,
expectingError: true,
expectedErrorInfo: "VersionService.GetAllCloudSetting error:invalid JSON format",
mockCommentedJson: "",
mockCommentedError: fmt.Errorf("invalid JSON format"),
},
}

defer mockey.UnPatchAll() // 清理所有mock

for _, tc := range testCases {
mockey.PatchConvey(tc.name, t, func() {
// Mock upyun.URlGetFile 方法
mockey.Mock(upyun.URlGetFile).To(func(filename string) (*[]byte, error) {
return tc.mockSettingJson, tc.mockError
}).Build()
mockey.Mock(upyun.JoinFileName).To(func(filename string) string {
return filename
}).Build()

// Mock getJSONWithoutComments 方法
mockey.Mock(getJSONWithoutComments).To(func(json string) (string, error) {
if tc.mockCommentedError != nil {
return "", tc.mockCommentedError
}
return tc.mockCommentedJson, nil
}).Build()

// 初始化UrlService实例
versionService := &VersionService{}

// 调用方法
result, err := versionService.GetAllCloudSetting()

if tc.expectingError {
// 如果期望抛错,检查错误信息
assert.NotNil(t, err)
assert.EqualError(t, err, tc.expectedErrorInfo)
assert.Equal(t, tc.expectedResult, result)
} else {
// 如果不期望抛错,验证结果
assert.Nil(t, err)
assert.Equal(t, tc.expectedResult, result)
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,68 @@ func TestGetReleaseVersion(t *testing.T) {
})
}
}

func TestGetBetaVersion(t *testing.T) {
type testCase struct {
name string // 测试用例名称
mockJsonBytes *[]byte // mock返回的JSON数据
mockError error // mock返回的错误
expectedResult *pack.Version // 期望返回的结果
expectingError bool // 是否期望抛出错误
expectedErrorInfo string // 期望的错误信息
}

// 模拟数据
mockVersion := &pack.Version{Url: "http://example.com/beta.apk", Version: "1.0.0"}
mockVersionBytes, _ := json.Marshal(mockVersion)

testCases := []testCase{
{
name: "SuccessCase",
mockJsonBytes: &mockVersionBytes,
mockError: nil,
expectedResult: mockVersion,
expectingError: false,
expectedErrorInfo: "",
},
{
name: "FileNotFound",
mockJsonBytes: nil,
mockError: fmt.Errorf("file not found"),
expectedResult: nil,
expectingError: true,
expectedErrorInfo: "VersionService.GetBetaVersion error:file not found",
},
}

defer mockey.UnPatchAll() // 清理所有mock

for _, tc := range testCases {
mockey.PatchConvey(tc.name, t, func() {
// Mock upyun.URlGetFile 方法
mockey.Mock(upyun.URlGetFile).To(func(filename string) (*[]byte, error) {
return tc.mockJsonBytes, tc.mockError
}).Build()
mockey.Mock(upyun.JoinFileName).To(func(filename string) string {
return filename
}).Build()

// 初始化 VersionService 实例
urlService := &VersionService{}

// 调用方法
result, err := urlService.GetBetaVersion()

if tc.expectingError {
// 如果期望抛错,检查错误信息
assert.NotNil(t, err)
assert.EqualError(t, err, tc.expectedErrorInfo)
assert.Nil(t, result)
} else {
// 如果不期望抛错,验证结果
assert.Nil(t, err)
assert.Equal(t, tc.expectedResult, result)
}
})
}
}
67 changes: 67 additions & 0 deletions internal/version/service/login_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package service

import (
"testing"

"github.com/bytedance/mockey"
"github.com/stretchr/testify/assert"

"github.com/west2-online/fzuhelper-server/kitex_gen/version"
"github.com/west2-online/fzuhelper-server/pkg/utils"
)

func TestLogin(t *testing.T) {
type testCase struct {
name string // 测试用例名称
mockCheckPwd bool // 模拟 CheckPwd 的返回值
request *version.LoginRequest // 输入的登录请求
expectedError bool // 是否期望抛出错误
expectedErrorMsg string // 期望的错误类型或信息
}

testCases := []testCase{
{
name: "ValidPassword",
mockCheckPwd: true,
request: &version.LoginRequest{
Password: "validpassword",
},
expectedError: false,
},
{
name: "InvalidPassword",
mockCheckPwd: false,
request: &version.LoginRequest{
Password: "invalidpassword",
},
expectedError: true,
expectedErrorMsg: "[401] authorization failed",
},
}

defer mockey.UnPatchAll() // 清理所有mock

for _, tc := range testCases {
mockey.PatchConvey(tc.name, t, func() {
// Mock utils.CheckPwd 方法
mockey.Mock(utils.CheckPwd).To(func(password string) bool {
return tc.mockCheckPwd
}).Build()

// 初始化 UrlService 实例
versionService := &VersionService{}

// 调用方法
err := versionService.Login(tc.request)

if tc.expectedError {
// 如果期望抛错,检查错误信息
assert.NotNil(t, err)
assert.Contains(t, err.Error(), tc.expectedErrorMsg)
} else {
// 如果不期望抛错,验证结果
assert.Nil(t, err)
}
})
}
}
93 changes: 93 additions & 0 deletions internal/version/service/set_setting_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package service

import (
"fmt"
"testing"

"github.com/bytedance/mockey"
"github.com/stretchr/testify/assert"

"github.com/west2-online/fzuhelper-server/kitex_gen/version"
"github.com/west2-online/fzuhelper-server/pkg/upyun"
"github.com/west2-online/fzuhelper-server/pkg/utils"
)

func TestSetSetting(t *testing.T) {
type testCase struct {
name string // 测试用例名称
mockCheckPwd bool // 模拟 CheckPwd 的返回值
mockUploadError error // 模拟 URlUploadFile 的错误
request *version.SetCloudRequest // 输入的请求
expectedError bool // 是否期望抛出错误
expectedErrorInfo string // 期望的错误信息
}

testCases := []testCase{
{
name: "ValidPasswordAndSuccessfulUpload",
mockCheckPwd: true,
mockUploadError: nil,
request: &version.SetCloudRequest{
Password: "validpassword",
Setting: "{\"key\": \"value\"}",
},
expectedError: false,
},
{
name: "InvalidPassword",
mockCheckPwd: false,
mockUploadError: nil,
request: &version.SetCloudRequest{
Password: "invalidpassword",
Setting: "{\"key\": \"value\"}",
},
expectedError: true,
expectedErrorInfo: "[401] authorization failed", // 假设 buildAuthFailedError 返回这个错误信息
},
{
name: "ValidPasswordButUploadFails",
mockCheckPwd: true,
mockUploadError: fmt.Errorf("upload failed"),
request: &version.SetCloudRequest{
Password: "validpassword",
Setting: "{\"key\": \"value\"}",
},
expectedError: true,
expectedErrorInfo: "upload failed",
},
}

defer mockey.UnPatchAll() // 清理所有mock

for _, tc := range testCases {
mockey.PatchConvey(tc.name, t, func() {
// Mock utils.CheckPwd 方法
mockey.Mock(utils.CheckPwd).To(func(password string) bool {
return tc.mockCheckPwd
}).Build()

// Mock upyun.URlUploadFile 方法
mockey.Mock(upyun.URlUploadFile).To(func(data []byte, filename string) error {
return tc.mockUploadError
}).Build()
mockey.Mock(upyun.JoinFileName).To(func(filename string) string {
return filename
}).Build()

// 初始化 UrlService 实例
versionService := &VersionService{}

// 调用方法
err := versionService.SetSetting(tc.request)

if tc.expectedError {
// 如果期望抛错,检查错误信息
assert.NotNil(t, err)
assert.Contains(t, err.Error(), tc.expectedErrorInfo)
} else {
// 如果不期望抛错,验证结果
assert.Nil(t, err)
}
})
}
}
5 changes: 2 additions & 3 deletions internal/version/service/upload_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package service

import (
"github.com/west2-online/fzuhelper-server/config"
"github.com/west2-online/fzuhelper-server/kitex_gen/version"
"github.com/west2-online/fzuhelper-server/pkg/upyun"
"github.com/west2-online/fzuhelper-server/pkg/utils"
Expand All @@ -28,7 +27,7 @@ func (s *VersionService) UploadParams(req *version.UploadParamsRequest) (string,
if !utils.CheckPwd(req.Password) {
return "", "", buildAuthFailedError()
}
policy := upyun.GetPolicy(config.UrlService.Bucket, config.UrlService.Path, int(config.UrlService.TokenTimeout))
authorization := upyun.SignStr(config.UrlService.Operator, config.UrlService.Pass, config.UrlService.Bucket, policy)
policy := upyun.GetPolicy()
authorization := upyun.SignStr(policy)
return policy, authorization, nil
}
Loading

0 comments on commit 64f0562

Please sign in to comment.