Skip to content

🤗 [Question]: In fiber v3 - how to test context #4112

@JonasDoe

Description

@JonasDoe

Question Description

To get a better understanding of the new fiber.Ctx (and possibly test some custom setters later on), I'm trying to create a test like how setting and getting values work. (See an example in the snippet below.)

However, fiberCtx.SetContext(...) won't achieve anything b/c c.fasthttp == nil. My question is: Is there a more straight-forward way than this?

app := fiber.New()
app.Get("/", func(ctx fiber.Ctx) error {
	ctx.SetContext(context.WithValue(context.Background(), "hello", "world"))
	assert.Equal(t, "world", ctx.Context().Value("hello"))
	...
	return ctx.SendStatus(200)
})
req := httptest.NewRequest("GET", "/", nil)
...

Code Snippet (which won't work due to c.fasthttp == nil)

// Some tests are supposed to fail. But none of them will work b/c setting the value will never work
func TestFiberCompatibility(t *testing.T) {
	fiberCtx := fiber.NewDefaultCtx(fiber.New())
	fiberCtx.SetContext(context.WithValue(context.Background(), "hello", "world"))
	assert.Equal(t, "world", fiberCtx.Context().Value("hello"))
	assert.Equal(t, "world", fiberCtx.Value("hello"))
	assert.Equal(t, "world", fiberCtx.Locals("hello"))
	if fromContext, ok := fiber.ValueFromContext[string](fiberCtx, "hello"); assert.True(t, ok) {
		assert.Equal(t, "world", fromContext)
	}
	if fromContext, ok := fiber.ValueFromContext[string](fiberCtx.Context(), "hello"); assert.True(t, ok) {
		assert.Equal(t, "world", fromContext)
	}

	fiberCtx2 := fiber.NewDefaultCtx(fiber.New())
	fiber.StoreInContext(fiberCtx2, "hello", "world")
	assert.Equal(t, "world", fiberCtx2.Context().Value("hello"))
	assert.Equal(t, "world", fiberCtx2.Value("hello"))
	assert.Equal(t, "world", fiberCtx2.Locals("hello"))
	if fromContext2, ok := fiber.ValueFromContext[string](fiberCtx2, "hello"); assert.True(t, ok) {
		assert.Equal(t, "world", fromContext2)
	}
	if fromContext2, ok := fiber.ValueFromContext[string](fiberCtx2.Context(), "hello"); assert.True(t, ok) {
		assert.Equal(t, "world", fromContext2)
	}
}

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my questions prior to opening this one.
  • I understand that improperly formatted questions may be closed without explanation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions