mocha icon indicating copy to clipboard operation
mocha copied to clipboard

Body not repeat

Open tigerza117 opened this issue 2 years ago • 1 comments

Describe the bug I'm trying to setup a mock server with 2 replies for the same URL Path, but 2nd request no body From what I could gather from the lib examples, I believe this should have worked

To Reproduce Run the following test

package main

import (
	"io"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/vitorsalgado/mocha/v3"
	"github.com/vitorsalgado/mocha/v3/expect"
	"github.com/vitorsalgado/mocha/v3/reply"
)

func TestSeqReply(t *testing.T) {
	m := mocha.New(t)
	m.Start()

	m.AddMocks(mocha.Get(expect.URLPath("/test")).Repeat(2).Reply(reply.OK().BodyString("Hello")))

	req, _ := http.NewRequest(http.MethodGet, m.URL()+"/test", nil)

	{
		res, err := http.DefaultClient.Do(req)
		assert.Nil(t, err)
		assert.Equal(t, 200, res.StatusCode)
		b, err := io.ReadAll(res.Body)
		assert.Nil(t, err)
		assert.Equal(t, []byte("Hello"), b)

	}

	{
		res, err := http.DefaultClient.Do(req)
		assert.Nil(t, err)
		assert.Equal(t, 200, res.StatusCode)
		b, err := io.ReadAll(res.Body)
		assert.Nil(t, err)
		assert.Equal(t, []byte("Hello"), b)
	}
}

Expected behavior Test should run with no errors

Environment (please complete the following information):

  • OS: Mac OS Ventura 13.2 / Apple M1 Pro 2021
  • Golang Version 1.20.1
  • Version 3.0.2

tigerza117 avatar Apr 06 '23 12:04 tigerza117

Solve specific problems


package main

import (
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/vitorsalgado/mocha/v3"
	"github.com/vitorsalgado/mocha/v3/expect"
	"github.com/vitorsalgado/mocha/v3/params"
	"github.com/vitorsalgado/mocha/v3/reply"
)

func TestSeqReply(t *testing.T) {
	m := mocha.New(t)
	m.Start()

	m.AddMocks(mocha.Get(expect.URLPath("/test")).Repeat(2).ReplyFunction(func(request *http.Request, m reply.M, p params.P) (*reply.Response, error) {
		r := strings.NewReader("Hello")
		return &reply.Response{
			Status: http.StatusOK,
			Body:   r,
		}, nil
	}))

	req, _ := http.NewRequest(http.MethodGet, m.URL()+"/test", nil)

	{
		res, err := http.DefaultClient.Do(req)
		assert.Nil(t, err)
		assert.Equal(t, 200, res.StatusCode)
		b, err := io.ReadAll(res.Body)
		assert.Nil(t, err)
		assert.Equal(t, []byte("Hello"), b)

	}

	{
		res, err := http.DefaultClient.Do(req)
		assert.Nil(t, err)
		assert.Equal(t, 200, res.StatusCode)
		b, err := io.ReadAll(res.Body)
		assert.Nil(t, err)
		assert.Equal(t, []byte("Hello"), b)
	}
}


tigerza117 avatar Apr 06 '23 13:04 tigerza117