replacer: code refactor

Signed-off-by: Tw <tw19881113@gmail.com>
This commit is contained in:
Tw
2016-08-19 10:36:10 +08:00
parent bba1059ef9
commit 40c09d6789
2 changed files with 145 additions and 151 deletions

View File

@@ -24,28 +24,12 @@ func TestNewReplacer(t *testing.T) {
switch v := rep.(type) {
case *replacer:
if v.replacements["{host}"]() != "localhost" {
if v.getSubstitution("{host}") != "localhost" {
t.Error("Expected host to be localhost")
}
if v.replacements["{method}"]() != "POST" {
if v.getSubstitution("{method}") != "POST" {
t.Error("Expected request method to be POST")
}
// Response placeholders should only be set after call to Replace()
got, want := "", ""
if getReplacement, ok := v.replacements["{status}"]; ok {
got = getReplacement()
}
if want := ""; got != want {
t.Errorf("Expected status to NOT be set before Replace() is called; was: %s", got)
}
rep.Replace("{foobar}")
if getReplacement, ok := v.replacements["{status}"]; ok {
got = getReplacement()
}
if want = "200"; got != want {
t.Errorf("Expected status to be %s, was: %s", want, got)
}
default:
t.Fatalf("Expected *replacer underlying Replacer type, got: %#v", rep)
}
@@ -94,19 +78,21 @@ func TestReplace(t *testing.T) {
complexCases := []struct {
template string
replacements map[string]func() string
replacements map[string]string
expect string
}{
{"/a{1}/{2}",
map[string]func() string{
"{1}": func() string { return "12" },
"{2}": func() string { return "" }},
{
"/a{1}/{2}",
map[string]string{
"{1}": "12",
"{2}": "",
},
"/a12/"},
}
for _, c := range complexCases {
repl := &replacer{
replacements: c.replacements,
customReplacements: c.replacements,
}
if expected, actual := c.expect, repl.Replace(c.template); expected != actual {
t.Errorf("for template '%s', expected '%s', got '%s'", c.template, expected, actual)