Giter Club home page Giter Club logo

mocha's Introduction

mocha's People

Contributors

dependabot[bot] avatar kishaningithub avatar vitorsalgado avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mocha's Issues

_examples/application/handler_test.go fails to compile

Describe the bug
newly cloned repo from main branch fails to execute some of the tests.

To Reproduce
Steps to reproduce the behavior:

try to compile handler_test.go

Expected behavior
compiles with no errors

Actual Behavior
Code does not compile. in the readme file, it is still mentioned, that mocha.New(t) or mocha.NewSimple() is to be used to instantiate mocha instance to facilitate tests, however these methods are not found.in other tests, e.g. mhttp_test.go a different way to instantiate mocha is used, namely `NewAPI

also I can't find AddMocks() in current code.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Binary content corrupted

Describe the bug

I'm trying to use mocha to mock a .tar.gz artifact download, but the binary response body is corrupted.

The error occur because the Scanner used to write the mocked body, because "Successive calls to the Scanner.Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens.", and it causes an error when I try to read the file.

The error occurs because of a behavior of the bufio.Scanner used to write the mocked body into the response. The library doc says that "successive calls to the Scanner.Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens" and, as the default token is a \n character, causes the corruption

I'm using github.com/vitorsalgado/mocha/v3 v3.0.2

To Reproduce

package whatever

var (
	//go:embed test/*.tar.gz
	testFiles embed.FS
)

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

	content, _ := testFiles.ReadFile("test/any_file.tar.gz")
	m.AddMocks(mocha.Get(expect.URLPath("/test.tar.gz")).
		Reply(reply.OK().Body(content)))

	client := resty.New().SetBaseURL(m.URL())
	resp, err := client.R().Get("/test.tar.gz")
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, content, resp.Body()) // Not equal
}

Expected behavior
I expect that the response body be equal to the configured body.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: MacOS Monterey 12.6
  • Version go 1.22.2 darwin/amd64

Additional context

Response body from file content in `testdata/` directory

A pattern I currently follow for all my Go tests is to store JSON response bodies in e.g testdata/all_users.json or testdata/europe_users.json and so on.

The testdata directory is considered the idiomatic way to do this in Go.

It would be super convenient if I could do something like the following, with an error/failure if the file does not exist:

m := mocha.New(t).CloseOnCleanup(t)
m.Start()
m.AddMocks(mocha.
    Get(expect.URLPath("/users")).
    Reply(reply.OK().BodyFile("testdata/all_users.json)))

Currently I'm using a separate helper function to read the files and pass the string in using BodyString(...)

Can't reply sequentially

Describe the bug
I'm trying to setup a mock server with 2 replies for the same URL Path, but all requests fail with 418 - I'm a teapot. From what I could gather from the lib examples, I believe this should have worked

To Reproduce

Run the following test

package main

import (
	"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")).Reply(reply.Seq().Add(reply.Unauthorized(), reply.OK())))

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

	res, err := http.DefaultClient.Do(req)

	assert.Nil(t, err)
	assert.Equal(t, 401, res.StatusCode)

	res, err = http.DefaultClient.Do(req)

	assert.Nil(t, err)
	assert.Equal(t, 200, res.StatusCode)
}

Expected behavior
Test should run with no errors

Screenshots
N/A

Environment (please complete the following information):

  • OS: Mac OS Ventura 13.0.1 / Mac M1 Pro 2020
  • Golang Version 1.19.4
  • Lib Version 3.0.1

Additional context

Stack trace

2023/01/09 15:30:32 panic=runtime error: index out of range [-1]
goroutine 48 [running]:
github.com/vitorsalgado/mocha/v3/internal/middleware/recover.Recover.func1.1()
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/internal/middleware/recover/recover.go:18 +0x6c
panic({0x102f51b80, 0x140000d4090})
	/opt/homebrew/Cellar/go/1.19.4/libexec/src/runtime/panic.go:884 +0x204
github.com/vitorsalgado/mocha/v3/reply.(*SequentialReply).Build(0x14000386e10, 0x1400039b380?, {0x102fa6ea0, 0x1400046c0c0?}, {0x102faeb80, 0x1400039c0b8})
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/reply/seq.go:46 +0x1a0
github.com/vitorsalgado/mocha/v3.(*mockHandler).ServeHTTP(0x140003a0b40, {0x102fad2c0, 0x140000e2000}, 0x140003de800)
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/http_handler.go:97 +0x4a0
github.com/vitorsalgado/mocha/v3/internal/middleware/recover.Recover.func1({0x102fad2c0?, 0x140000e2000?}, 0x0?)
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/internal/middleware/recover/recov
2023/01/09 15:30:32 panic=runtime error: index out of range [-1]
goroutine 11 [running]:
github.com/vitorsalgado/mocha/v3/internal/middleware/recover.Recover.func1.1()
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/internal/middleware/recover/recover.go:18 +0x6c
panic({0x102f51b80, 0x140005a6060})
	/opt/homebrew/Cellar/go/1.19.4/libexec/src/runtime/panic.go:884 +0x204
github.com/vitorsalgado/mocha/v3/reply.(*SequentialReply).Build(0x14000386e10, 0x1400039b380?, {0x102fa6ea0, 0x1400046c0c0?}, {0x102faeb80, 0x1400039c0b8})
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/reply/seq.go:46 +0x1a0
github.com/vitorsalgado/mocha/v3.(*mockHandler).ServeHTTP(0x140003a0b40, {0x102fad2c0, 0x1400047e000}, 0x140001aad00)
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/http_handler.go:97 +0x4a0
github.com/vitorsalgado/mocha/v3/internal/middleware/recover.Recover.func1({0x102fad2c0?, 0x1400047e000?}, 0x10000001000000?)
	/home/resilva/project/vendor/github.com/vitorsalgado/mocha/v3/internal/middleware/

Body not repeat

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

Nil error on request without body and body matcher

Describe the bug
If you submit a request to the Mocha server without a body, and you have a matcher with a body match, mocha gets a memory panic

To Reproduce
Create mocha server

func TestMochaNil(t *testing.T) {
	m := mocha.New(t, mocha.Configure().Addr("localhost:8080").Build()).CloseOnCleanup(t)

	// Start mock CCM API
	m.Start()

	m.AddMocks(
		// Missing data for runConfig
		mocha.Post(expect.URLPath("/test")).
			Body(expect.JSONPath("data", expect.ToContain("aaa"))).
			Reply(reply.OK().BodyJSON("hello world")),
		// Metrics cost mapper
		mocha.Get(expect.URLPath("/test")).
			Reply(reply.OK().BodyJSON("hello world")),
	)

	url := "http://localhost:8080/test"

	// Create a new HTTP client
	client := &http.Client{}

	// Create a new GET request
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

}

Expected behavior
At the very least, when the check for method "Post" fails, the loop of expect checks should short stop before the body check ever happens.

But the body check should fail if the body is nil

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.