Skip to content

Commit

Permalink
feat: update tests framework; maintain CourseGroup.CourseCount and Re…
Browse files Browse the repository at this point in the history
…view.ModifyCount and Course.ReviewCount
  • Loading branch information
JingYiJun committed Sep 27, 2023
1 parent 03bb639 commit 78a3ea2
Show file tree
Hide file tree
Showing 13 changed files with 144 additions and 67 deletions.
4 changes: 2 additions & 2 deletions all_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package main
import (
"testing"

"github.com/opentreehole/backend/tests/auth"
"github.com/opentreehole/backend/tests"
)

func TestAuth(t *testing.T) {
auth.TestAuth(t)
tests.TestAuth(t)
}
3 changes: 3 additions & 0 deletions cmd/migrate/danke_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ where true`).Error
return err
}

// update course_group.course_count
err = tx.Exec(`update course_group set course_count = (select count(*) from course where course.course_group_id = course_group.id) where true`).Error

if m.HasColumn(&model.Review{}, "upvoters") {
err = m.DropColumn(&model.Review{}, "upvoters")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/wire/wire_gen.go

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

15 changes: 3 additions & 12 deletions internal/model/achievement.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,9 @@ import (

// Achievement 成就
type Achievement struct {
// 成就 ID , primary key
ID int `json:"id"`

// 创建时间
ID int `json:"id"`
CreatedAt time.Time `json:"created_at"`

// 更新时间
UpdatedAt time.Time `json:"updated_at"`

// 成就名称
Name string `json:"name" gorm:"not null"`

// 可能是成就作用域?
Domain string `json:"domain"`
Name string `json:"name" gorm:"not null"` // 成就名称
Domain string `json:"domain"` // 可能是成就作用域?
}
24 changes: 7 additions & 17 deletions internal/model/course_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,11 @@ package model

// CourseGroup 课程组
type CourseGroup struct {
// 课程组 ID , primary key
ID int `json:"id"`

// 课程组名称
Name string `json:"name" gorm:"not null"`

// 课程组编号
Code string `json:"code" gorm:"not null"`

// 开课学院
Department string `json:"department" gorm:"not null"`

// 开课校区
CampusName string `json:"campus_name" gorm:"not null"`

// 所有课程
Courses []*Course `json:"courses"`
ID int `json:"id"`
Name string `json:"name" gorm:"not null"` // 课程组名称
Code string `json:"code" gorm:"not null"` // 课程组编号
Department string `json:"department" gorm:"not null"` // 开课学院
CampusName string `json:"campus_name" gorm:"not null"` // 开课校区
CourseCount int `json:"course_count" gorm:"not null;default:0"` // 课程数量
Courses []*Course `json:"courses"`
}
13 changes: 11 additions & 2 deletions internal/repository/course.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,17 @@ func (r *courseRepository) FindCoursesByGroupID(ctx context.Context, groupID int
}

func (r *courseRepository) CreateCourse(ctx context.Context, course *model.Course) (err error) {
err = r.GetDB(ctx).Create(course).Error

err = r.Transaction(ctx, func(ctx context.Context) error {
err = r.GetDB(ctx).Create(course).Error
if err != nil {
return err
}

return r.GetDB(ctx).Model(&model.CourseGroup{ID: course.CourseGroupID}).Update("course_count", gorm.Expr("course_count + 1")).Error
})
if err != nil {
return err
}
// clear cache
return r.GetCache(ctx).Delete(ctx, "danke:course_group")
}
20 changes: 17 additions & 3 deletions internal/repository/review.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,14 @@ func (r *reviewRepository) GetReview(ctx context.Context, condition func(tx *gor
}

func (r *reviewRepository) CreateReview(ctx context.Context, review *model.Review) (err error) {
return r.GetDB(ctx).Create(review).Error
return r.Transaction(ctx, func(ctx context.Context) error {
err = r.GetDB(ctx).Create(review).Error
if err != nil {
return err
}
return r.GetDB(ctx).Model(&model.Course{ID: review.CourseID}).
Update("review_count", gorm.Expr("review_count + 1")).Error
})
}

func (r *reviewRepository) GetReviewByID(ctx context.Context, id int) (review *model.Review, err error) {
Expand All @@ -101,8 +108,15 @@ func (r *reviewRepository) UpdateReview(ctx context.Context, userID int, oldRevi
}

// 更新 review
return r.GetDB(ctx).Model(oldReview).
Select("Title", "Content", "Rank").Updates(newReview).Error
return r.GetDB(ctx).Model(oldReview).Updates(map[string]any{
"title": newReview.Title,
"content": newReview.Content,
"modify_count": gorm.Expr("modify_count + 1"),
"rank_overall": newReview.Rank.Overall,
"rank_content": newReview.Rank.Content,
"rank_workload": newReview.Rank.Workload,
"rank_assessment": newReview.Rank.Assessment,
}).Error
}

func (r *reviewRepository) UpdateReviewVote(ctx context.Context, userID int, review *model.Review, data int) (err error) {
Expand Down
60 changes: 50 additions & 10 deletions internal/schema/review.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,16 +232,56 @@ type ReviewRankV3 = ReviewRankV1

type AchievementV3Response = AchievementV1Response

type UserExtraV3 = UserExtraV1
type UserExtraV3 struct {
Achievements []*AchievementV3Response `json:"achievements"`
}

type ReviewV3Response struct {
ID int `json:"id"`
CreatedAt time.Time `json:"created_at"` // 创建时间
UpdatedAt time.Time `json:"updated_at"` // 更新时间
Title string `json:"title"` // 评教标题
Content string `json:"content"` // 评教内容
ReviewerID int `json:"reviewer_id"` // 评教者 ID
Rank *ReviewRankV3 `json:"rank"` // 评价
MyVote int `json:"my_vote"` // 自己是否点赞或点踩,0 未操作,1 点赞,-1 点踩
VoterCount int `json:"voter_count"` // 点赞数 + 点踩数
ID int `json:"id"`
CreatedAt time.Time `json:"created_at"` // 创建时间
UpdatedAt time.Time `json:"updated_at"` // 更新时间
CourseID int `json:"course_id"` // 课程 ID
Title string `json:"title"` // 评教标题
Content string `json:"content"` // 评教内容
ReviewerID int `json:"reviewer_id"` // 评教者 ID
Rank *ReviewRankV3 `json:"rank"` // 评价
MyVote int `json:"my_vote"` // 自己是否点赞或点踩,0 未操作,1 点赞,-1 点踩
UpvoteCount int `json:"upvote_count"` // 点赞数
DownvoteCount int `json:"downvote_count"` // 点踩数
IsMe bool `json:"is_me"` // 是否是自己的评教
Extra UserExtraV3 `json:"extra"` // 额外信息
}

func (r *ReviewV3Response) FromModel(
user *model.User,
review *model.Review,
votesMap map[int]*model.ReviewVote,
) *ReviewV3Response {
err := copier.Copy(r, review)
if err != nil {
panic(err)
}

if user != nil {
r.IsMe = user.ID == review.ReviewerID
} else {
r.IsMe = false
}

r.Rank = new(ReviewRankV1).FromModel(review.Rank)
if votesMap != nil && votesMap[review.ID] != nil {
r.MyVote = votesMap[review.ID].Data
} else {
r.MyVote = 0
}

r.Extra.Achievements = make([]*AchievementV1Response, 0, len(review.UserAchievements))
for _, userAchievement := range review.UserAchievements {
if userAchievement.Achievement == nil {
continue
}
r.Extra.Achievements = append(r.Extra.Achievements, new(AchievementV1Response).FromModel(userAchievement.Achievement, userAchievement))
}
return r

}
30 changes: 24 additions & 6 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
"gorm.io/gorm"

"github.com/opentreehole/backend/internal/config"
"github.com/opentreehole/backend/internal/handler"
Expand All @@ -18,6 +19,8 @@ import (
type Server struct {
config *config.AtomicAllConfig
logger *log.Logger
db *gorm.DB
app *fiber.App
rootRegister []handler.RouteRegister
handlers []handler.RouteRegister
}
Expand All @@ -40,6 +43,7 @@ func NewServer(
// others
logger *log.Logger,
config *config.AtomicAllConfig,
db *gorm.DB,
) *Server {
var handlers []handler.RouteRegister

Expand All @@ -65,36 +69,50 @@ func NewServer(
return &Server{
logger: logger,
config: config,
db: db,
rootRegister: []handler.RouteRegister{
docsHandler,
},
handlers: handlers,
}
}

func (s *Server) Run() {
func (s *Server) GetFiberApp() *fiber.App {
if s.app != nil {
return s.app
}

var disableStartupMessage = true
if s.config.Load().Mode == "dev" {
disableStartupMessage = false
}
var app = fiber.New(fiber.Config{
s.app = fiber.New(fiber.Config{
DisableStartupMessage: disableStartupMessage,
ErrorHandler: schema.ErrorHandler,
})

RegisterMiddlewares(s.config)(app)
RegisterMiddlewares(s.config)(s.app)
for _, h := range s.rootRegister {
h.RegisterRoute(app)
h.RegisterRoute(s.app)
}
for _, h := range s.handlers {
h.RegisterRoute(app.Group("/api"))
h.RegisterRoute(s.app.Group("/api"))
}
app.Get("/api", func(c *fiber.Ctx) error {
s.app.Get("/api", func(c *fiber.Ctx) error {
// TODO: add meta info
return c.JSON(fiber.Map{
"message": "Hello, World!",
})
})
return s.app
}

func (s *Server) GetDB() *gorm.DB {
return s.db
}

func (s *Server) Run() {
app := s.GetFiberApp()

// start server
go func() {
Expand Down
1 change: 1 addition & 0 deletions tests/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package tests
1 change: 0 additions & 1 deletion tests/auth/account.go

This file was deleted.

13 changes: 0 additions & 13 deletions tests/auth/init.go

This file was deleted.

25 changes: 25 additions & 0 deletions tests/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package tests

import (
"testing"

"gorm.io/gorm"

"github.com/opentreehole/backend/cmd/wire"
)

var DB *gorm.DB

func init() {
server, _, err := wire.NewApp()
if err != nil {
panic(err)
}

RegisterApp(server.GetFiberApp())
DB = server.GetDB()
}

func TestAuth(t *testing.T) {
DefaultTester.Get(t, "/docs/index.html", 200, RequestConfig{})
}

0 comments on commit 78a3ea2

Please sign in to comment.