| // Copyright 2021 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package codifier |
| |
| import ( |
| "errors" |
| "testing" |
| |
| "github.com/google/go-cmp/cmp" |
| ) |
| |
| func TestDoFn(t *testing.T) { |
| f := func(i string) (string, error) { return i + "bar", nil } |
| var p *Proc |
| if p.DoFn(f) != nil { |
| t.Error("expected nil Proc") |
| } |
| p = NewProcFromString("foo") |
| if p.DoFn(nil) != nil { |
| t.Error("expected nil Proc") |
| } |
| if p.DoFn(func(i string) (string, error) { return "", errors.New("oops") }) != nil { |
| t.Error("expected nil Proc due to function error") |
| } |
| if p.DoFn(f) == nil { |
| t.Error("expected non-nil Proc") |
| } |
| if p.replacement != "foobar" { |
| t.Error("DoFn failed to replace") |
| } |
| } |
| |
| func TestDoFnWith(t *testing.T) { |
| f := func(i, j string) (string, []string, map[string]interface{}, error) { return i + "bar", nil, nil, nil } |
| var p *Proc |
| if p.DoFnWith("foo", f) != nil { |
| t.Error("expected nil Proc") |
| } |
| p = NewProcFromString("foo") |
| if p.DoFnWith("foo", nil) != nil { |
| t.Error("expected nil Proc") |
| } |
| if p.DoFnWith("foo", f) != nil { |
| t.Error("expected nil Proc due to missing key") |
| } |
| p.Store["foo"] = "baz" |
| if p.DoFnWith("foo", func(i, j string) (string, []string, map[string]interface{}, error) { |
| return "", nil, nil, errors.New("oops") |
| }) != nil { |
| t.Error("expected nil Proc due to function error") |
| } |
| p = p.DoFnWith("foo", f) |
| if p == nil { |
| t.Error("expected non-nil Proc after finding the key") |
| } |
| if p.replacement != "bazbar" { |
| t.Errorf("got: %s, want: bazbar", p.replacement) |
| } |
| if len(p.changedFiles) != 0 { |
| t.Errorf("got: %v, want: empty changedFiles", p.changedFiles) |
| } |
| if len(p.Store) != 1 { |
| t.Errorf("got: %v, want: no additions to store", p.Store) |
| } |
| |
| amap := make(map[string]interface{}, 0) |
| amap["k1"] = "v1" |
| amap["k2"] = "v2" |
| f2 := func(i, j string) (string, []string, map[string]interface{}, error) { |
| return i + "bar", []string{"f1", "f2"}, amap, nil |
| } |
| q := NewProcFromString("contents").StoreKeyValue("foo", "baz").DoFnWith("foo", f2) |
| if q == nil { |
| t.Error("expected non-nil Proc after finding the key") |
| } |
| if q.replacement != "bazbar" { |
| t.Errorf("got: %s, want: bazbar", p.replacement) |
| } |
| if len(q.changedFiles) != 2 { |
| t.Errorf("got: %v, want: empty changedFiles", q.changedFiles) |
| } |
| if !cmp.Equal(q.changedFiles, orderedStrings{"f1", "f2"}) { |
| t.Errorf("got: %v, want: [f1, f2]", q.changedFiles) |
| } |
| if len(q.Store) != 3 { |
| t.Errorf("got: %v, want: len == 3", p.Store) |
| } |
| amap["foo"] = "baz" |
| if !cmp.Equal(q.Store, amap) { |
| t.Errorf("got: %v, want: %v", q.Store, amap) |
| } |
| } |