|
| 1 | +// Copyright 2025 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package v1_25 |
| 5 | + |
| 6 | +import ( |
| 7 | + "testing" |
| 8 | + |
| 9 | + "code.gitea.io/gitea/models/migrations/base" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +type UserBadgeBefore struct { |
| 15 | + ID int64 `xorm:"pk autoincr"` |
| 16 | + BadgeID int64 |
| 17 | + UserID int64 `xorm:"INDEX"` |
| 18 | +} |
| 19 | + |
| 20 | +func (UserBadgeBefore) TableName() string { |
| 21 | + return "user_badge" |
| 22 | +} |
| 23 | + |
| 24 | +func Test_AddUniqueIndexForUserBadge(t *testing.T) { |
| 25 | + x, deferable := base.PrepareTestEnv(t, 0, new(UserBadgeBefore)) |
| 26 | + defer deferable() |
| 27 | + if x == nil || t.Failed() { |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + testData := []*UserBadgeBefore{ |
| 32 | + {UserID: 1, BadgeID: 1}, |
| 33 | + {UserID: 1, BadgeID: 1}, // duplicate |
| 34 | + {UserID: 2, BadgeID: 1}, |
| 35 | + {UserID: 1, BadgeID: 2}, |
| 36 | + {UserID: 3, BadgeID: 3}, |
| 37 | + {UserID: 3, BadgeID: 3}, // duplicate |
| 38 | + } |
| 39 | + |
| 40 | + for _, data := range testData { |
| 41 | + _, err := x.Insert(data) |
| 42 | + assert.NoError(t, err) |
| 43 | + } |
| 44 | + |
| 45 | + // check that we have duplicates |
| 46 | + count, err := x.Where("user_id = ? AND badge_id = ?", 1, 1).Count(&UserBadgeBefore{}) |
| 47 | + assert.NoError(t, err) |
| 48 | + assert.Equal(t, int64(2), count) |
| 49 | + |
| 50 | + count, err = x.Where("user_id = ? AND badge_id = ?", 3, 3).Count(&UserBadgeBefore{}) |
| 51 | + assert.NoError(t, err) |
| 52 | + assert.Equal(t, int64(2), count) |
| 53 | + |
| 54 | + totalCount, err := x.Count(&UserBadgeBefore{}) |
| 55 | + assert.NoError(t, err) |
| 56 | + assert.Equal(t, int64(6), totalCount) |
| 57 | + |
| 58 | + // run the migration |
| 59 | + if err := AddUniqueIndexForUserBadge(x); err != nil { |
| 60 | + assert.NoError(t, err) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // verify the duplicates were removed |
| 65 | + count, err = x.Where("user_id = ? AND badge_id = ?", 1, 1).Count(&UserBadgeBefore{}) |
| 66 | + assert.NoError(t, err) |
| 67 | + assert.Equal(t, int64(1), count) |
| 68 | + |
| 69 | + count, err = x.Where("user_id = ? AND badge_id = ?", 3, 3).Count(&UserBadgeBefore{}) |
| 70 | + assert.NoError(t, err) |
| 71 | + assert.Equal(t, int64(1), count) |
| 72 | + |
| 73 | + // check total count |
| 74 | + totalCount, err = x.Count(&UserBadgeBefore{}) |
| 75 | + assert.NoError(t, err) |
| 76 | + assert.Equal(t, int64(4), totalCount) |
| 77 | + |
| 78 | + // fail to insert a duplicate |
| 79 | + _, err = x.Insert(&UserBadge{UserID: 1, BadgeID: 1}) |
| 80 | + assert.Error(t, err) |
| 81 | + |
| 82 | + // succeed adding a non-duplicate |
| 83 | + _, err = x.Insert(&UserBadge{UserID: 4, BadgeID: 1}) |
| 84 | + assert.NoError(t, err) |
| 85 | +} |
0 commit comments