| package mock |
| |
| import ( |
| "fmt" |
| "net/http" |
| "os" |
| "testing" |
| "encoding/pem" |
| "encoding/json" |
| "io/ioutil" |
| "crypto/x509" |
| "github.com/apid/istioApigeeAdapter/common" |
| ) |
| |
| var testMockServer *MockServer |
| |
| func TestMain(m *testing.M) { |
| var err error |
| testMockServer, err = StartMockServer(0) |
| if err != nil { |
| panic(err.Error()) |
| } |
| |
| result := m.Run() |
| testMockServer.Stop() |
| os.Exit(result) |
| } |
| |
| func TestServerSanity(t *testing.T) { |
| if mockKeyPEM == nil { |
| t.Fatal("Expected mock key to be generated") |
| } |
| if mockCertPEM == nil { |
| t.Fatal("Expected mock cert to be generated") |
| } |
| } |
| |
| func TestPublicKey(t *testing.T) { |
| resp, err := http.Get(fmt.Sprintf("http://%s/publicKey", testMockServer.Address())) |
| if err != nil { |
| t.Fatalf("Network error: %s", err) |
| } |
| defer resp.Body.Close() |
| if resp.StatusCode != 200 { |
| t.Fatalf("Got HTTP status code %d", resp.StatusCode) |
| } |
| |
| body, err := ioutil.ReadAll(resp.Body) |
| if err != nil { |
| t.Fatalf("Error reading body: %s", err) |
| } |
| pb, _ := pem.Decode(body) |
| if pb == nil { |
| t.Fatalf("Failed decoding public key body \"%s\"", string(body)) |
| } |
| if pb.Type != "CERTIFICATE" { |
| t.Fatalf("Got back invalid PEM type %s", pb.Type) |
| } |
| |
| cert, err := x509.ParseCertificate(pb.Bytes) |
| if err != nil { |
| t.Fatalf("Error decoding certificate: %s", err) |
| } |
| if cert.Subject.CommonName != "mockserver" { |
| t.Fatalf("Common name does not match \"mockserver\": \"%s\"", cert.Subject.CommonName) |
| } |
| } |
| |
| func TestProducts(t *testing.T) { |
| resp, err := http.Get(fmt.Sprintf("http://%s/products", testMockServer.Address())) |
| if err != nil { |
| t.Fatalf("Network error: %s", err) |
| } |
| defer resp.Body.Close() |
| if resp.StatusCode != 200 { |
| t.Fatalf("Got HTTP status code %d", resp.StatusCode) |
| } |
| if resp.Header.Get("content-type") != "application/json" { |
| t.Fatalf("Invalid content typs %s", resp.Header.Get("content-type")) |
| } |
| |
| dec := json.NewDecoder(resp.Body) |
| var products []common.APIProduct |
| err = dec.Decode(&products) |
| if err != nil { |
| t.Fatalf("Error decoding response json: %s", err) |
| } |
| } |