code.gitea.io/gitea@v1.21.7/models/migrations/v1_16/v195_test.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package v1_16 //nolint
     5  
     6  import (
     7  	"testing"
     8  
     9  	"code.gitea.io/gitea/models/migrations/base"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func Test_AddTableCommitStatusIndex(t *testing.T) {
    15  	// Create the models used in the migration
    16  	type CommitStatus struct {
    17  		ID     int64  `xorm:"pk autoincr"`
    18  		Index  int64  `xorm:"INDEX UNIQUE(repo_sha_index)"`
    19  		RepoID int64  `xorm:"INDEX UNIQUE(repo_sha_index)"`
    20  		SHA    string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
    21  	}
    22  
    23  	// Prepare and load the testing database
    24  	x, deferable := base.PrepareTestEnv(t, 0, new(CommitStatus))
    25  	if x == nil || t.Failed() {
    26  		defer deferable()
    27  		return
    28  	}
    29  	defer deferable()
    30  
    31  	// Run the migration
    32  	if err := AddTableCommitStatusIndex(x); err != nil {
    33  		assert.NoError(t, err)
    34  		return
    35  	}
    36  
    37  	type CommitStatusIndex struct {
    38  		ID       int64
    39  		RepoID   int64  `xorm:"unique(repo_sha)"`
    40  		SHA      string `xorm:"unique(repo_sha)"`
    41  		MaxIndex int64  `xorm:"index"`
    42  	}
    43  
    44  	start := 0
    45  	const batchSize = 1000
    46  	for {
    47  		indexes := make([]CommitStatusIndex, 0, batchSize)
    48  		err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
    49  		assert.NoError(t, err)
    50  
    51  		for _, idx := range indexes {
    52  			var maxIndex int
    53  			has, err := x.SQL("SELECT max(`index`) FROM commit_status WHERE repo_id = ? AND sha = ?", idx.RepoID, idx.SHA).Get(&maxIndex)
    54  			assert.NoError(t, err)
    55  			assert.True(t, has)
    56  			assert.EqualValues(t, maxIndex, idx.MaxIndex)
    57  		}
    58  		if len(indexes) < batchSize {
    59  			break
    60  		}
    61  		start += len(indexes)
    62  	}
    63  }