1package stdlib
2
3import (
4	"testing"
5
6	"github.com/zclconf/go-cty/cty"
7)
8
9func TestReplace(t *testing.T) {
10	tests := []struct {
11		Input           cty.Value
12		Substr, Replace cty.Value
13		Want            cty.Value
14	}{
15		{
16			cty.StringVal("hello"),
17			cty.StringVal("l"),
18			cty.StringVal(""),
19			cty.StringVal("heo"),
20		},
21		{
22			cty.StringVal("������������"),
23			cty.StringVal("��"),
24			cty.StringVal("��"),
25			cty.StringVal("������������"),
26		},
27		{
28			cty.StringVal("������������"),
29			cty.StringVal("��"),
30			cty.StringVal("��"),
31			cty.StringVal("������������"),
32		},
33	}
34
35	for _, test := range tests {
36		t.Run(test.Input.GoString()+"_replace", func(t *testing.T) {
37			got, err := Replace(test.Input, test.Substr, test.Replace)
38
39			if err != nil {
40				t.Fatalf("unexpected error: %s", err)
41			}
42
43			if !got.RawEquals(test.Want) {
44				t.Fatalf("wrong result\ngot:  %#v\nwant: %#v", got, test.Want)
45			}
46		})
47		t.Run(test.Input.GoString()+"_regex_replace", func(t *testing.T) {
48			got, err := Replace(test.Input, test.Substr, test.Replace)
49
50			if err != nil {
51				t.Fatalf("unexpected error: %s", err)
52			}
53
54			if !got.RawEquals(test.Want) {
55				t.Fatalf("wrong result\ngot:  %#v\nwant: %#v", got, test.Want)
56			}
57		})
58	}
59}
60
61func TestRegexReplace(t *testing.T) {
62	tests := []struct {
63		Input           cty.Value
64		Substr, Replace cty.Value
65		Want            cty.Value
66	}{
67		{
68			cty.StringVal("-ab-axxb-"),
69			cty.StringVal("a(x*)b"),
70			cty.StringVal("T"),
71			cty.StringVal("-T-T-"),
72		},
73		{
74			cty.StringVal("-ab-axxb-"),
75			cty.StringVal("a(x*)b"),
76			cty.StringVal("${1}W"),
77			cty.StringVal("-W-xxW-"),
78		},
79	}
80
81	for _, test := range tests {
82		t.Run(test.Input.GoString(), func(t *testing.T) {
83			got, err := RegexReplace(test.Input, test.Substr, test.Replace)
84
85			if err != nil {
86				t.Fatalf("unexpected error: %s", err)
87			}
88
89			if !got.RawEquals(test.Want) {
90				t.Fatalf("wrong result\ngot:  %#v\nwant: %#v", got, test.Want)
91			}
92		})
93	}
94}
95
96func TestRegexReplaceInvalidRegex(t *testing.T) {
97	_, err := RegexReplace(cty.StringVal(""), cty.StringVal("("), cty.StringVal(""))
98	if err == nil {
99		t.Fatal("expected an error")
100	}
101}
102