watches_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2022 The Gogs 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. package db
  5. import (
  6. "context"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. "gogs.io/gogs/internal/dbtest"
  11. )
  12. func TestWatches(t *testing.T) {
  13. if testing.Short() {
  14. t.Skip()
  15. }
  16. t.Parallel()
  17. tables := []any{new(Watch), new(Repository)}
  18. db := &watches{
  19. DB: dbtest.NewDB(t, "watches", tables...),
  20. }
  21. for _, tc := range []struct {
  22. name string
  23. test func(t *testing.T, db *watches)
  24. }{
  25. {"ListByRepo", watchesListByRepo},
  26. {"Watch", watchesWatch},
  27. } {
  28. t.Run(tc.name, func(t *testing.T) {
  29. t.Cleanup(func() {
  30. err := clearTables(t, db.DB, tables...)
  31. require.NoError(t, err)
  32. })
  33. tc.test(t, db)
  34. })
  35. if t.Failed() {
  36. break
  37. }
  38. }
  39. }
  40. func watchesListByRepo(t *testing.T, db *watches) {
  41. ctx := context.Background()
  42. err := db.Watch(ctx, 1, 1)
  43. require.NoError(t, err)
  44. err = db.Watch(ctx, 2, 1)
  45. require.NoError(t, err)
  46. err = db.Watch(ctx, 2, 2)
  47. require.NoError(t, err)
  48. got, err := db.ListByRepo(ctx, 1)
  49. require.NoError(t, err)
  50. for _, w := range got {
  51. w.ID = 0
  52. }
  53. want := []*Watch{
  54. {UserID: 1, RepoID: 1},
  55. {UserID: 2, RepoID: 1},
  56. }
  57. assert.Equal(t, want, got)
  58. }
  59. func watchesWatch(t *testing.T, db *watches) {
  60. ctx := context.Background()
  61. reposStore := NewReposStore(db.DB)
  62. repo1, err := reposStore.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
  63. require.NoError(t, err)
  64. err = db.Watch(ctx, 2, repo1.ID)
  65. require.NoError(t, err)
  66. // It is OK to watch multiple times and just be noop.
  67. err = db.Watch(ctx, 2, repo1.ID)
  68. require.NoError(t, err)
  69. repo1, err = reposStore.GetByID(ctx, repo1.ID)
  70. require.NoError(t, err)
  71. assert.Equal(t, 2, repo1.NumWatches) // The owner is watching the repo by default.
  72. }