Files
godoxy/internal/route/rules/do_blocks_test.go
yusing 1a17f3943a refactor(rules): change default rule from baseline to fallback behavior
The default rule should runs only when no non-default pre rule matches, instead of running first as a baseline.
This follows the old behavior as before the pr is established.:

- Default rules act as fallback handlers that execute only when no matching non-default rule exists in the pre phase
- IfElseBlockCommand now returns early when a condition matches with a nil Do block, instead of falling through to else blocks
- Add nil check for auth handler to allow requests when no auth is configured
- Fix unterminated environment variable parsing to preserve input

Updates tests to verify the new fallback behavior where special rules suppress default rule execution.
2026-02-24 00:11:03 +08:00

74 lines
1.5 KiB
Go

package rules
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
httputils "github.com/yusing/goutils/http"
)
func TestIfElseBlockCommandServeHTTP_UnconditionalNilDoNotFallsThrough(t *testing.T) {
elseCalled := false
cmd := IfElseBlockCommand{
Ifs: []IfBlockCommand{
{
On: RuleOn{},
Do: nil,
},
},
Else: []CommandHandler{
Handler{
fn: func(_ *httputils.ResponseModifier, _ *http.Request, _ http.HandlerFunc) error {
elseCalled = true
return nil
},
phase: PhaseNone,
},
},
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
rm := httputils.NewResponseModifier(w)
err := cmd.ServeHTTP(rm, req, nil)
require.NoError(t, err)
assert.False(t, elseCalled)
}
func TestIfElseBlockCommandServeHTTP_ConditionalMatchedNilDoNotFallsThrough(t *testing.T) {
elseCalled := false
cmd := IfElseBlockCommand{
Ifs: []IfBlockCommand{
{
On: RuleOn{
checker: CheckFunc(func(_ *httputils.ResponseModifier, _ *http.Request) bool {
return true
}),
},
Do: nil,
},
},
Else: []CommandHandler{
Handler{
fn: func(_ *httputils.ResponseModifier, _ *http.Request, _ http.HandlerFunc) error {
elseCalled = true
return nil
},
phase: PhaseNone,
},
},
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
rm := httputils.NewResponseModifier(w)
err := cmd.ServeHTTP(rm, req, nil)
require.NoError(t, err)
assert.False(t, elseCalled)
}