Skip to content

Commit

Permalink
Updated test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Wil Simpson committed Apr 1, 2024
1 parent f40cef7 commit d4cce2b
Show file tree
Hide file tree
Showing 18 changed files with 654 additions and 126 deletions.
564 changes: 559 additions & 5 deletions coverage.out

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pkg/config/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ func NewGlobalConfig(ctx context.Context) *GlobalConfig {
}
}

viper.SetEnvPrefix("SRO")
// Read from environment variables
helpers.BindEnvsToStruct(config)

Expand Down
22 changes: 18 additions & 4 deletions pkg/config/global_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,48 @@ import (
"github.com/bxcodec/faker/v4"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus/hooks/test"
"gopkg.in/yaml.v2"

"github.com/ShatteredRealms/go-backend/pkg/config"
"github.com/ShatteredRealms/go-backend/pkg/log"
)

var _ = Describe("Global config", func() {
BeforeEach(func() {
log.Logger, _ = test.NewNullLogger()
})
Describe("NewGlobalConfig", func() {
It("should generate a valid config", func() {
Expect(config.NewGlobalConfig(nil)).NotTo(BeNil())
Expect(config.NewGlobalConfig(context.TODO())).NotTo(BeNil())
Expect(config.NewGlobalConfig(context.Background())).NotTo(BeNil())
})

It("should read in env variables", func() {
key := "SRO_CHARACTER_LOCAL_HOST"
key := "SRO_VERSION"
val := faker.Username()
GinkgoT().Setenv(key, val)
Expect(os.Getenv(key)).To(Equal(val))
conf := config.NewGlobalConfig(nil)
conf := config.NewGlobalConfig(context.TODO())
Expect(conf).NotTo(BeNil())
Expect(conf.Version).To(Equal(val))

key = "SRO_CHARACTER_LOCAL_HOST"
val = faker.Username()
GinkgoT().Setenv(key, val)
Expect(os.Getenv(key)).To(Equal(val))
conf = config.NewGlobalConfig(context.TODO())
Expect(conf).NotTo(BeNil())
Expect(conf.Character.Local.Host).To(Equal(val))
})

It("should read in from config file", func() {
confFromFile := &config.GlobalConfig{}
yamlFile, err := os.ReadFile("../../test/config.yaml")
Expect(err).To(BeNil())
err = yaml.Unmarshal(yamlFile, confFromFile)
Expect(err).To(BeNil())
conf := config.NewGlobalConfig(nil)
conf := config.NewGlobalConfig(context.TODO())
Expect(conf).NotTo(BeNil())
Expect(conf.Character.Keycloak.ClientSecret).To(Equal(confFromFile.Character.Keycloak.ClientSecret))
})
Expand Down
3 changes: 3 additions & 0 deletions pkg/config/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import (
"github.com/bxcodec/faker/v4"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus/hooks/test"

"github.com/ShatteredRealms/go-backend/pkg/config"
"github.com/ShatteredRealms/go-backend/pkg/log"
)

var _ = Describe("Server config", func() {
Describe("ServerAddress Address", func() {
It("should generate an address", func() {
log.Logger, _ = test.NewNullLogger()
config := config.NewGlobalConfig(context.TODO())
Expect(config).NotTo(BeNil())
Expect(config.Character.Local.Address()).To(Equal(fmt.Sprintf("%s:%d", config.Character.Local.Host, config.Character.Local.Port)))
Expand Down
4 changes: 2 additions & 2 deletions pkg/helpers/character_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var _ = Describe("Character helpers", func() {

It("should error on invalid target", func() {
id, err := helpers.GetCharacterIdFromTarget(ctx, mockCSC, target)
Expect(err).Should(MatchError(model.ErrHandleRequest))
Expect(err).Should(MatchError(model.ErrHandleRequest.Err()))
Expect(id).NotTo(Equal(uint(characterDetails.Id)))
Expect(hook.AllEntries()).To(HaveLen(1))
Expect(hook.LastEntry().String()).To(ContainSubstring("target type unknown"))
Expand Down Expand Up @@ -107,7 +107,7 @@ var _ = Describe("Character helpers", func() {

It("should error on invalid target", func() {
name, err := helpers.GetCharacterNameFromTarget(ctx, mockCSC, target)
Expect(err).Should(MatchError(model.ErrHandleRequest))
Expect(err).Should(MatchError(model.ErrHandleRequest.Err()))
Expect(name).NotTo(Equal(characterDetails.Name))
Expect(hook.AllEntries()).To(HaveLen(1))
Expect(hook.LastEntry().String()).To(ContainSubstring("target type unknown"))
Expand Down
23 changes: 9 additions & 14 deletions pkg/helpers/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,29 @@ func BindEnvsToStruct(obj interface{}) {
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
key := field.Name
env := field.Name
if field.Anonymous {
env = ""
key = ""
}
bindRecursive(key, env, val.Field(i))
bindRecursive(key, val.Field(i))
}
}

func bindRecursive(key, env string, val reflect.Value) {
func bindRecursive(key string, val reflect.Value) {
if val.Kind() != reflect.Struct {
env = "SRO_" + strings.ToUpper(env)
_ = viper.BindEnv(key, env)
env := "SRO_" + strings.ReplaceAll(strings.ToUpper(key), ".", "_")
viper.MustBindEnv(key, env)
return
}

for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
newKey := field.Name
newEnv := field.Name
if key != "" {
newKey = "." + newKey
}
if field.Anonymous {
newEnv = ""
} else if env != "" {
newEnv = "_" + newEnv
newKey = ""
} else if key != "" {
newKey = "." + newKey
}

bindRecursive(key+newKey, env+newEnv, val.Field(i))
bindRecursive(key+newKey, val.Field(i))
}
}
3 changes: 2 additions & 1 deletion pkg/helpers/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const (
)

type TestStruct struct {
EmbeddedStruct
EmbeddedStruct `yaml:",inline" mapstructure:",squash"`

Foo string
Bar TestInnerStruct
}
Expand Down
25 changes: 2 additions & 23 deletions pkg/helpers/srv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,7 @@ var _ = Describe("Srv helpers", func() {

BeforeEach(func() {
log.Logger, hook = test.NewNullLogger()
})

Describe("UnaryLogRequest", func() {
It("should handle requests", func() {
method := faker.Username()
fakeHandler := &mockHandler{}
testFunc := helpers.UnaryLogRequest()
testFunc(nil, nil, &grpc.UnaryServerInfo{FullMethod: method}, fakeHandler.UnaryHandler)
Expect(fakeHandler.WasCalled).To(BeTrue())
Expect(hook.LastEntry().Message).To(ContainSubstring(method))
})
})

Describe("StreamLogRequest", func() {
It("should handle requests", func() {
method := faker.Username()
fakeHandler := &mockHandler{}
testFunc := helpers.StreamLogRequest()
testFunc(nil, mockServerStream{}, &grpc.StreamServerInfo{FullMethod: method}, fakeHandler.StreamHandler)
Expect(fakeHandler.WasCalled).To(BeTrue())
Expect(hook.LastEntry().Message).To(ContainSubstring(method))
})
hook.Reset()
})

Describe("GrpcDialOpts", func() {
Expand Down Expand Up @@ -236,7 +215,7 @@ var _ = Describe("Srv helpers", func() {
jwtToken, outClaims, err := helpers.VerifyClaims(ctx, mockKeycloak, realm)
Expect(jwtToken).To(BeNil())
Expect(outClaims).To(BeNil())
Expect(err).To(MatchError(model.ErrUnauthorized))
Expect(err).To(MatchError(model.ErrUnauthorized.Err()))
})
})

Expand Down
4 changes: 2 additions & 2 deletions pkg/mocks/character_s_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 0 additions & 30 deletions pkg/mocks/gamebackend_r_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions pkg/repository/character_r.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ func NewCharacterRepository(db *gorm.DB) (repo CharacterRepository, err error) {
return
}

func (r characterRepository) FindByName(ctx context.Context, name string) (character *model.Character, err error) {
func (r characterRepository) FindByName(ctx context.Context, name string) (*model.Character, error) {
var character *model.Character
result := r.DB.WithContext(ctx).Where("name = ?", name).Find(&character)
if result.Error != nil {
log.Logger.WithContext(ctx).Debugf("find by name err: %v", result.Error)
Expand All @@ -58,7 +59,7 @@ func (r characterRepository) FindByName(ctx context.Context, name string) (chara

if result.RowsAffected == 0 {
log.Logger.WithContext(ctx).Debugf("find by name: no rows affected. character: %+v", character)
return
return nil, nil
}

log.Logger.WithContext(ctx).Debugf("character name %s found", name)
Expand Down
8 changes: 6 additions & 2 deletions pkg/repository/repository_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ func TestRepository(t *testing.T) {
mdb = testdb.ConnectMongoDocker(mdbConnStr)
Expect(mdb).NotTo(BeNil())

characterRepo = repository.NewCharacterRepository(gdb)
var err error
characterRepo, err = repository.NewCharacterRepository(gdb)
Expect(err).NotTo(HaveOccurred())
Expect(characterRepo).NotTo(BeNil())
Expect(characterRepo.Migrate(context.Background())).NotTo(HaveOccurred())

Expand Down Expand Up @@ -87,7 +89,9 @@ func TestRepository(t *testing.T) {
mdb = testdb.ConnectMongoDocker(hosts[1])
Expect(mdb).NotTo(BeNil())

characterRepo = repository.NewCharacterRepository(gdb)
var err error
characterRepo, err = repository.NewCharacterRepository(gdb)
Expect(err).NotTo(HaveOccurred())
Expect(characterRepo).NotTo(BeNil())
chatRepo = repository.NewChatRepository(gdb)
Expect(chatRepo).NotTo(BeNil())
Expand Down
6 changes: 3 additions & 3 deletions pkg/service/character_s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ var _ = Describe("Character service", func() {
Target: &pb.CharacterTarget{},
}
out, err := charService.Edit(ctx, editReq)
Expect(err).To(MatchError(model.ErrHandleRequest))
Expect(err).To(MatchError(model.ErrHandleRequest.Err()))
Expect(out).To(BeNil())
})
})
Expand Down Expand Up @@ -390,7 +390,7 @@ var _ = Describe("Character service", func() {
mockRepository.EXPECT().Save(ctx, gomock.Any()).Return(charOut, fakeError)
out, err := charService.AddPlayTime(ctx, character.ID, amount)
Expect(err).To(MatchError(fakeError))
Expect(out).To(BeEquivalentTo(charOut.PlayTime))
Expect(out.PlayTime).To(BeEquivalentTo(charOut.PlayTime))
})
})

Expand All @@ -399,7 +399,7 @@ var _ = Describe("Character service", func() {
mockRepository.EXPECT().FindById(ctx, character.ID).Return(nil, fakeError)
out, err := charService.AddPlayTime(ctx, character.ID, amount)
Expect(err).To(MatchError(fakeError))
Expect(out).To(BeEquivalentTo(0))
Expect(out).To(BeNil())
})
})
})
Expand Down
10 changes: 5 additions & 5 deletions pkg/srv/character_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ var _ = Describe("Character server", func() {
Time: 100,
}
mockCharService.EXPECT().FindByName(gomock.Any(), character.Name).Return(character, nil)
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(uint64(200), nil)
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(character, nil)
out, err := server.AddCharacterPlayTime(incAdminCtx, req)
Expect(err).NotTo(HaveOccurred())
Expect(out.Time).To(BeEquivalentTo(200))
Expect(out.Time).To(BeEquivalentTo(character.PlayTime))
})
It("should work given character id", func() {
req := &pb.AddPlayTimeRequest{
Expand All @@ -100,10 +100,10 @@ var _ = Describe("Character server", func() {
},
Time: 100,
}
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(uint64(200), nil)
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(character, nil)
out, err := server.AddCharacterPlayTime(incAdminCtx, req)
Expect(err).NotTo(HaveOccurred())
Expect(out.Time).To(BeEquivalentTo(200))
Expect(out.Time).To(BeEquivalentTo(character.PlayTime))
})
})
When("given invalid input", func() {
Expand All @@ -114,7 +114,7 @@ var _ = Describe("Character server", func() {
},
Time: 100,
}
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(uint64(200), fakeErr)
mockCharService.EXPECT().AddPlayTime(gomock.Any(), character.ID, req.Time).Return(character, fakeErr)
out, err := server.AddCharacterPlayTime(incAdminCtx, req)
Expect(err).To(HaveOccurred())
Expect(out).To(BeNil())
Expand Down
Loading

0 comments on commit d4cce2b

Please sign in to comment.