gencsr_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package gencsr
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "os"
  7. "testing"
  8. "github.com/cloudflare/cfssl/cli"
  9. )
  10. const (
  11. testKeyFile = "testdata/test-key.pem"
  12. testCAKeyFile = "../testdata/ca-key.pem"
  13. testCACertFile = "../testdata/ca.pem"
  14. )
  15. type stdoutRedirect struct {
  16. r *os.File
  17. w *os.File
  18. saved *os.File
  19. }
  20. func newStdoutRedirect() (*stdoutRedirect, error) {
  21. r, w, err := os.Pipe()
  22. if err != nil {
  23. return nil, err
  24. }
  25. pipe := &stdoutRedirect{r, w, os.Stdout}
  26. os.Stdout = pipe.w
  27. return pipe, nil
  28. }
  29. func (pipe *stdoutRedirect) readAll() ([]byte, error) {
  30. pipe.w.Close()
  31. os.Stdout = pipe.saved
  32. return ioutil.ReadAll(pipe.r)
  33. }
  34. func checkResponse(out []byte) error {
  35. var response map[string]interface{}
  36. if err := json.Unmarshal(out, &response); err != nil {
  37. return err
  38. }
  39. if response["key"] == nil {
  40. return errors.New("no key is outputted")
  41. }
  42. if response["csr"] == nil {
  43. return errors.New("no csr is outputted")
  44. }
  45. return nil
  46. }
  47. func TestGencsr(t *testing.T) {
  48. var pipe *stdoutRedirect
  49. var out []byte
  50. var err error
  51. if pipe, err = newStdoutRedirect(); err != nil {
  52. t.Fatal(err)
  53. }
  54. if err := gencsrMain([]string{"testdata/csr.json"}, cli.Config{KeyFile: testKeyFile}); err != nil {
  55. t.Fatal(err)
  56. }
  57. if out, err = pipe.readAll(); err != nil {
  58. t.Fatal(err)
  59. }
  60. if err := checkResponse(out); err != nil {
  61. t.Fatal(err)
  62. }
  63. }
  64. func TestGencsrFromCert(t *testing.T) {
  65. var pipe *stdoutRedirect
  66. var out []byte
  67. var err error
  68. if pipe, err = newStdoutRedirect(); err != nil {
  69. t.Fatal(err)
  70. }
  71. if err := gencsrMain([]string{}, cli.Config{KeyFile: testCAKeyFile, CertFile: testCACertFile}); err != nil {
  72. t.Fatal(err)
  73. }
  74. if out, err = pipe.readAll(); err != nil {
  75. t.Fatal(err)
  76. }
  77. if err := checkResponse(out); err != nil {
  78. t.Fatal(err)
  79. }
  80. }
  81. func TestGencsrError(t *testing.T) {
  82. if err := gencsrMain([]string{"testdata/csr.json"}, cli.Config{}); err == nil {
  83. t.Fatal("should have erred.")
  84. }
  85. }