1// Copyright 2021 The Gitea Authors. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package migrations
6
7import (
8	"testing"
9
10	"code.gitea.io/gitea/modules/timeutil"
11
12	"github.com/stretchr/testify/assert"
13)
14
15func Test_deleteOrphanedIssueLabels(t *testing.T) {
16	// Create the models used in the migration
17	type IssueLabel struct {
18		ID      int64 `xorm:"pk autoincr"`
19		IssueID int64 `xorm:"UNIQUE(s)"`
20		LabelID int64 `xorm:"UNIQUE(s)"`
21	}
22
23	type Label struct {
24		ID              int64 `xorm:"pk autoincr"`
25		RepoID          int64 `xorm:"INDEX"`
26		OrgID           int64 `xorm:"INDEX"`
27		Name            string
28		Description     string
29		Color           string `xorm:"VARCHAR(7)"`
30		NumIssues       int
31		NumClosedIssues int
32		CreatedUnix     timeutil.TimeStamp `xorm:"INDEX created"`
33		UpdatedUnix     timeutil.TimeStamp `xorm:"INDEX updated"`
34	}
35
36	// Prepare and load the testing database
37	x, deferable := prepareTestEnv(t, 0, new(IssueLabel), new(Label))
38	if x == nil || t.Failed() {
39		defer deferable()
40		return
41	}
42	defer deferable()
43
44	var issueLabels []*IssueLabel
45	preMigration := map[int64]*IssueLabel{}
46	postMigration := map[int64]*IssueLabel{}
47
48	// Load issue labels that exist in the database pre-migration
49	if err := x.Find(&issueLabels); err != nil {
50		assert.NoError(t, err)
51		return
52	}
53	for _, issueLabel := range issueLabels {
54		preMigration[issueLabel.ID] = issueLabel
55	}
56
57	// Run the migration
58	if err := deleteOrphanedIssueLabels(x); err != nil {
59		assert.NoError(t, err)
60		return
61	}
62
63	// Load the remaining issue-labels
64	issueLabels = issueLabels[:0]
65	if err := x.Find(&issueLabels); err != nil {
66		assert.NoError(t, err)
67		return
68	}
69	for _, issueLabel := range issueLabels {
70		postMigration[issueLabel.ID] = issueLabel
71	}
72
73	// Now test what is left
74	if _, ok := postMigration[2]; ok {
75		t.Errorf("Orphaned Label[2] survived the migration")
76		return
77	}
78
79	if _, ok := postMigration[5]; ok {
80		t.Errorf("Orphaned Label[5] survived the migration")
81		return
82	}
83
84	for id, post := range postMigration {
85		pre := preMigration[id]
86		assert.Equal(t, pre, post, "migration changed issueLabel %d", id)
87	}
88
89}
90