email_addresses_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "gogs.io/gogs/internal/errutil"
  12. )
  13. func TestEmailAddresses(t *testing.T) {
  14. if testing.Short() {
  15. t.Skip()
  16. }
  17. t.Parallel()
  18. tables := []any{new(EmailAddress)}
  19. db := &emailAddresses{
  20. DB: dbtest.NewDB(t, "emailAddresses", tables...),
  21. }
  22. for _, tc := range []struct {
  23. name string
  24. test func(t *testing.T, db *emailAddresses)
  25. }{
  26. {"GetByEmail", emailAddressesGetByEmail},
  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 emailAddressesGetByEmail(t *testing.T, db *emailAddresses) {
  41. ctx := context.Background()
  42. const testEmail = "[email protected]"
  43. _, err := db.GetByEmail(ctx, testEmail, false)
  44. wantErr := ErrEmailNotExist{
  45. args: errutil.Args{
  46. "email": testEmail,
  47. },
  48. }
  49. assert.Equal(t, wantErr, err)
  50. // TODO: Use EmailAddresses.Create to replace SQL hack when the method is available.
  51. err = db.Exec(`INSERT INTO email_address (uid, email, is_activated) VALUES (1, ?, FALSE)`, testEmail).Error
  52. require.NoError(t, err)
  53. got, err := db.GetByEmail(ctx, testEmail, false)
  54. require.NoError(t, err)
  55. assert.Equal(t, testEmail, got.Email)
  56. // Should not return if we only want activated emails
  57. _, err = db.GetByEmail(ctx, testEmail, true)
  58. assert.Equal(t, wantErr, err)
  59. // TODO: Use EmailAddresses.MarkActivated to replace SQL hack when the method is available.
  60. err = db.Exec(`UPDATE email_address SET is_activated = TRUE WHERE email = ?`, testEmail).Error
  61. require.NoError(t, err)
  62. got, err = db.GetByEmail(ctx, testEmail, true)
  63. require.NoError(t, err)
  64. assert.Equal(t, testEmail, got.Email)
  65. }