repos / pico

pico services mono repo
git clone https://github.com/picosh/pico.git

pico / pkg / apps / pgs
Antonio Mika  ·  2025-03-12

redirect_test.go

  1package pgs
  2
  3import (
  4	"testing"
  5
  6	"github.com/google/go-cmp/cmp"
  7)
  8
  9type RedirectFixture struct {
 10	name        string
 11	input       string
 12	expect      []*RedirectRule
 13	shouldError bool
 14}
 15
 16func TestParseRedirectText(t *testing.T) {
 17	empty := map[string]string{}
 18	spa := RedirectFixture{
 19		name:  "spa",
 20		input: "/*   /index.html   200",
 21		expect: []*RedirectRule{
 22			{
 23				From:       "/*",
 24				To:         "/index.html",
 25				Status:     200,
 26				Query:      empty,
 27				Conditions: empty,
 28			},
 29		},
 30	}
 31
 32	rss := RedirectFixture{
 33		name:  "rss",
 34		input: "/rss /rss.atom 200",
 35		expect: []*RedirectRule{
 36			{
 37				From:       "/rss",
 38				To:         "/rss.atom",
 39				Status:     200,
 40				Query:      empty,
 41				Conditions: empty,
 42			},
 43		},
 44	}
 45
 46	withStatus := RedirectFixture{
 47		name:  "with-status",
 48		input: "/wow     /index.html     301",
 49		expect: []*RedirectRule{
 50			{
 51				From:       "/wow",
 52				To:         "/index.html",
 53				Status:     301,
 54				Query:      empty,
 55				Conditions: empty,
 56			},
 57		},
 58	}
 59
 60	noStatus := RedirectFixture{
 61		name:  "no-status",
 62		input: "/wow     /index.html",
 63		expect: []*RedirectRule{
 64			{
 65				From:       "/wow",
 66				To:         "/index.html",
 67				Status:     301,
 68				Query:      empty,
 69				Conditions: empty,
 70			},
 71		},
 72	}
 73
 74	absoluteUriNoProto := RedirectFixture{
 75		name:        "absolute-uri-no-proto",
 76		input:       "/*  www.example.com  301",
 77		expect:      []*RedirectRule{},
 78		shouldError: true,
 79	}
 80
 81	absoluteUriWithProto := RedirectFixture{
 82		name:  "absolute-uri-no-proto",
 83		input: "/*  https://www.example.com  301",
 84		expect: []*RedirectRule{
 85			{
 86				From:       "/*",
 87				To:         "https://www.example.com",
 88				Status:     301,
 89				Query:      empty,
 90				Conditions: empty,
 91			},
 92		},
 93	}
 94
 95	fixtures := []RedirectFixture{
 96		spa,
 97		rss,
 98		withStatus,
 99		noStatus,
100		absoluteUriNoProto,
101		absoluteUriWithProto,
102	}
103
104	for _, fixture := range fixtures {
105		t.Run(fixture.name, func(t *testing.T) {
106			results, err := parseRedirectText(fixture.input)
107			if err != nil && !fixture.shouldError {
108				t.Error(err)
109			}
110			if cmp.Equal(results, fixture.expect) == false {
111				//nolint
112				t.Fatal(cmp.Diff(fixture.expect, results))
113			}
114		})
115	}
116}