public_keys_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2023 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. "fmt"
  7. "os"
  8. "path/filepath"
  9. "testing"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "gogs.io/gogs/internal/conf"
  13. "gogs.io/gogs/internal/dbtest"
  14. )
  15. func TestPublicKeys(t *testing.T) {
  16. if testing.Short() {
  17. t.Skip()
  18. }
  19. t.Parallel()
  20. tables := []any{new(PublicKey)}
  21. db := &publicKeys{
  22. DB: dbtest.NewDB(t, "publicKeys", tables...),
  23. }
  24. for _, tc := range []struct {
  25. name string
  26. test func(t *testing.T, db *publicKeys)
  27. }{
  28. {"RewriteAuthorizedKeys", publicKeysRewriteAuthorizedKeys},
  29. } {
  30. t.Run(tc.name, func(t *testing.T) {
  31. t.Cleanup(func() {
  32. err := clearTables(t, db.DB, tables...)
  33. require.NoError(t, err)
  34. })
  35. tc.test(t, db)
  36. })
  37. if t.Failed() {
  38. break
  39. }
  40. }
  41. }
  42. func publicKeysRewriteAuthorizedKeys(t *testing.T, db *publicKeys) {
  43. // TODO: Use PublicKeys.Add to replace SQL hack when the method is available.
  44. publicKey := &PublicKey{
  45. OwnerID: 1,
  46. Name: "test-key",
  47. Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
  48. Content: "test-key-content",
  49. }
  50. err := db.DB.Create(publicKey).Error
  51. require.NoError(t, err)
  52. tempSSHRootPath := filepath.Join(os.TempDir(), "publicKeysRewriteAuthorizedKeys-tempSSHRootPath")
  53. conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
  54. err = db.RewriteAuthorizedKeys()
  55. require.NoError(t, err)
  56. authorizedKeys, err := os.ReadFile(authorizedKeysPath())
  57. require.NoError(t, err)
  58. assert.Contains(t, string(authorizedKeys), fmt.Sprintf("key-%d", publicKey.ID))
  59. assert.Contains(t, string(authorizedKeys), publicKey.Content)
  60. }