cert_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2016 Circonus, Inc. 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 checkmgr
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. "github.com/circonus-labs/circonus-gometrics/api"
  12. )
  13. var (
  14. apiCert = CACert{
  15. Contents: string(circonusCA),
  16. }
  17. )
  18. func testCertServer() *httptest.Server {
  19. f := func(w http.ResponseWriter, r *http.Request) {
  20. switch r.URL.Path {
  21. case "/pki/ca.crt":
  22. ret, err := json.Marshal(apiCert)
  23. if err != nil {
  24. panic(err)
  25. }
  26. w.WriteHeader(200)
  27. w.Header().Set("Content-Type", "application/json")
  28. fmt.Fprintln(w, string(ret))
  29. default:
  30. w.WriteHeader(500)
  31. fmt.Fprintln(w, "unsupported")
  32. }
  33. }
  34. return httptest.NewServer(http.HandlerFunc(f))
  35. }
  36. func TestLoadCACert(t *testing.T) {
  37. t.Log("default cert, no fetch")
  38. cm := &CheckManager{
  39. enabled: false,
  40. }
  41. cm.loadCACert()
  42. if cm.certPool == nil {
  43. t.Errorf("Expected cert pool to be initialized, still nil.")
  44. }
  45. subjs := cm.certPool.Subjects()
  46. if len(subjs) == 0 {
  47. t.Errorf("Expected > 0 certs in pool")
  48. }
  49. }
  50. func TestFetchCert(t *testing.T) {
  51. server := testCertServer()
  52. defer server.Close()
  53. cm := &CheckManager{
  54. enabled: true,
  55. }
  56. ac := &api.Config{
  57. TokenApp: "abcd",
  58. TokenKey: "1234",
  59. URL: server.URL,
  60. }
  61. apih, err := api.NewAPI(ac)
  62. if err != nil {
  63. t.Errorf("Expected no error, got '%v'", err)
  64. }
  65. cm.apih = apih
  66. _, err = cm.fetchCert()
  67. if err != nil {
  68. t.Fatalf("Expected no error, got %v", err)
  69. }
  70. t.Log("load cert w/fetch")
  71. cm.loadCACert()
  72. if cm.certPool == nil {
  73. t.Errorf("Expected cert pool to be initialized, still nil.")
  74. }
  75. subjs := cm.certPool.Subjects()
  76. if len(subjs) == 0 {
  77. t.Errorf("Expected > 0 certs in pool")
  78. }
  79. }