cache_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package autocert
  5. import (
  6. "context"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "testing"
  12. )
  13. // make sure DirCache satisfies Cache interface
  14. var _ Cache = DirCache("/")
  15. func TestDirCache(t *testing.T) {
  16. dir, err := ioutil.TempDir("", "autocert")
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. defer os.RemoveAll(dir)
  21. dir = filepath.Join(dir, "certs") // a nonexistent dir
  22. cache := DirCache(dir)
  23. ctx := context.Background()
  24. // test cache miss
  25. if _, err := cache.Get(ctx, "nonexistent"); err != ErrCacheMiss {
  26. t.Errorf("get: %v; want ErrCacheMiss", err)
  27. }
  28. // test put/get
  29. b1 := []byte{1}
  30. if err := cache.Put(ctx, "dummy", b1); err != nil {
  31. t.Fatalf("put: %v", err)
  32. }
  33. b2, err := cache.Get(ctx, "dummy")
  34. if err != nil {
  35. t.Fatalf("get: %v", err)
  36. }
  37. if !reflect.DeepEqual(b1, b2) {
  38. t.Errorf("b1 = %v; want %v", b1, b2)
  39. }
  40. name := filepath.Join(dir, "dummy")
  41. if _, err := os.Stat(name); err != nil {
  42. t.Error(err)
  43. }
  44. // test put deletes temp file
  45. tmp, err := filepath.Glob(name + "?*")
  46. if err != nil {
  47. t.Error(err)
  48. }
  49. if tmp != nil {
  50. t.Errorf("temp file exists: %s", tmp)
  51. }
  52. // test delete
  53. if err := cache.Delete(ctx, "dummy"); err != nil {
  54. t.Fatalf("delete: %v", err)
  55. }
  56. if _, err := cache.Get(ctx, "dummy"); err != ErrCacheMiss {
  57. t.Errorf("get: %v; want ErrCacheMiss", err)
  58. }
  59. }