Beispiel #1
0
// New creates a new recorder
func New(cassetteName string) (*Recorder, error) {
	var mode int
	var c *cassette.Cassette
	cassetteFile := fmt.Sprintf("%s.yaml", cassetteName)

	// Depending on whether the cassette file exists or not we
	// either create a new empty cassette or load from file
	if _, err := os.Stat(cassetteFile); os.IsNotExist(err) {
		// Create new cassette and enter in recording mode
		c = cassette.New(cassetteName)
		mode = ModeRecording
	} else {
		// Load cassette from file and enter replay mode
		c, err = cassette.Load(cassetteName)
		if err != nil {
			return nil, err
		}
		mode = ModeReplaying
	}

	// A transport which can be used by clients to inject
	transport := &Transport{c: c, mode: mode}

	r := &Recorder{
		mode:      mode,
		cassette:  c,
		Transport: transport,
	}

	return r, nil
}
Beispiel #2
0
func TestRecord(t *testing.T) {
	runID := time.Now().Format(time.RFC3339Nano)
	tests := []recordTest{
		{
			method: "GET",
			out:    "GET " + runID,
		},
		{
			method: "POST",
			body:   "post body",
			out:    "POST " + runID + "\npost body",
		},
	}

	dir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatal(err)
	}
	cassPath := path.Join(dir, "record_test")
	var serverURL string
	serverUp := false

	func() {
		// Start our recorder
		r, err := recorder.New(cassPath)
		if err != nil {
			t.Fatal(err)
		}
		defer r.Stop() // Make sure recorder is stopped once done with it

		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintf(w, "%s %s", r.Method, runID)
			if r.Body != nil {
				defer r.Body.Close()
				fmt.Fprintln(w)
				io.Copy(w, r.Body)
			}
		}))
		serverUp = true
		defer func() {
			server.Close()
			t.Log("server shut down")
			serverUp = false
		}()
		serverURL = server.URL

		t.Log("recording")
		for _, test := range tests {
			test.perform(t, serverURL, r)
		}
	}()

	c, err := cassette.Load(cassPath)
	if err != nil {
		t.Fatal(err)
	}
	for i, test := range tests {
		body := c.Interactions[i].Request.Body
		if body != test.body {
			t.Fatalf("got:\t%s\n\twant:\t%s", string(body), string(test.body))
		}
	}

	if serverUp {
		t.Fatal("expected server to have shut down")
	}

	// Re-run without the actual server
	r, err := recorder.New(cassPath)
	if err != nil {
		t.Fatal(err)
	}
	defer r.Stop()

	t.Log("replaying")
	for _, test := range tests {
		test.perform(t, serverURL, r)
	}
}