How to use FixNestedStyle method of gop Package

Best Got code snippet using gop.FixNestedStyle

Run Got automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

format_test.go

Source: format_test.go Github

copy
1package gop_test
2
3import (
4	"bytes"
5	"encoding/base64"
6	"fmt"
7	"io/ioutil"
8	"os"
9	"os/exec"
10	"reflect"
11	"testing"
12	"text/template"
13	"time"
14	"unsafe"
15
16	"github.com/ysmood/got"
17	"github.com/ysmood/got/lib/diff"
18	"github.com/ysmood/got/lib/gop"
19)
20
21func TestStyle(t *testing.T) {
22	g := got.T(t)
23	s := gop.Style{Set: "<s>", Unset: "</s>"}
24
25	g.Eq(gop.S("test", s), "<s>test</s>")
26	g.Eq(gop.S("", s), "<s></s>")
27	g.Eq(gop.S("", gop.None), "")
28}
29
30func TestTokenize(t *testing.T) {
31	g := got.T(t)
32	ref := "test"
33	timeStamp, _ := time.Parse(time.RFC3339Nano, "2021-08-28T08:36:36.807908+08:00")
34	fn := func(string) int { return 10 }
35	ch1 := make(chan int)
36	ch2 := make(chan string, 3)
37	ch3 := make(chan struct{})
38
39	v := []interface{}{
40		nil,
41		[]int{},
42		[]interface{}{true, false, uintptr(0x17), float32(100.121111133)},
43		true, 10, int8(2), int32(100),
44		float64(100.121111133),
45		complex64(1 + 2i), complex128(1 + 2i),
46		[3]int{1, 2},
47		ch1,
48		ch2,
49		ch3,
50		fn,
51		map[interface{}]interface{}{
52			`"test"`: 10,
53			"a":      1,
54		},
55		unsafe.Pointer(&ref),
56		struct {
57			Int int
58			str string
59			M   map[int]int
60		}{10, "ok", map[int]int{1: 0x20}},
61		[]byte("aa\xe2"),
62		[]byte("bytes\n\tbytes"),
63		[]byte("long long long long string"),
64		byte('a'),
65		byte(1),
66		'天',
67		"long long long long string",
68		"\ntest",
69		"\t\n`",
70		&ref,
71		(*struct{ Int int })(nil),
72		&struct{ Int int }{},
73		&map[int]int{1: 2, 3: 4},
74		&[]int{1, 2},
75		&[2]int{1, 2},
76		&[]byte{1, 2},
77		timeStamp,
78		time.Hour,
79		`{"a": 1}`,
80		[]byte(`{"a": 1}`),
81	}
82
83	check := func(out string, tpl ...string) {
84		g.Helper()
85
86		expected := bytes.NewBuffer(nil)
87
88		t := template.New("")
89		g.E(t.Parse(g.Read(g.Open(false, tpl...)).String()))
90		g.E(t.Execute(expected, map[string]interface{}{
91			"ch1": fmt.Sprintf("0x%x", reflect.ValueOf(ch1).Pointer()),
92			"ch2": fmt.Sprintf("0x%x", reflect.ValueOf(ch2).Pointer()),
93			"ch3": fmt.Sprintf("0x%x", reflect.ValueOf(ch3).Pointer()),
94			"fn":  fmt.Sprintf("0x%x", reflect.ValueOf(fn).Pointer()),
95			"ptr": fmt.Sprintf("%v", &ref),
96		}))
97
98		if out != expected.String() {
99			g.Fail()
100			g.Log(diff.Diff(out, expected.String()))
101		}
102	}
103
104	out := gop.StripANSI(gop.F(v))
105
106	{
107		code := fmt.Sprintf(g.Read(g.Open(false, "fixtures", "compile_check.go.tmpl")).String(), out)
108		f := g.Open(true, "tmp", g.RandStr(8), "main.go")
109		g.Cleanup(func() { _ = os.Remove(f.Name()) })
110		g.Write(code)(f)
111		b, err := exec.Command("go", "run", f.Name()).CombinedOutput()
112		if err != nil {
113			g.Error(string(b))
114		}
115	}
116
117	check(out, "fixtures", "expected.tmpl")
118
119	out = gop.VisualizeANSI(gop.F(v))
120	check(out, "fixtures", "expected_with_color.tmpl")
121}
122
123func TestRef(t *testing.T) {
124	g := got.T(t)
125	a := [2][]int{{1}}
126	a[1] = a[0]
127
128	g.Eq(gop.Plain(a), `[2][]int{
129    []int/* len=1 cap=1 */{
130        1,
131    },
132    []int/* len=1 cap=1 */{
133        1,
134    },
135}`)
136}
137
138type A struct {
139	Int int
140	B   *B
141}
142
143type B struct {
144	s string
145	a *A
146}
147
148func TestCircularRef(t *testing.T) {
149	g := got.T(t)
150	a := A{Int: 10}
151	b := B{"test", &a}
152	a.B = &b
153
154	g.Eq(gop.StripANSI(gop.F(a)), `gop_test.A{
155    Int: 10,
156    B: &gop_test.B{
157        s: "test",
158        a: &gop_test.A{
159            Int: 10,
160            B: gop.Circular("B").(*gop_test.B),
161        },
162    },
163}`)
164}
165
166func TestCircularNilRef(t *testing.T) {
167	arr := []A{{}, {}}
168
169	got.T(t).Eq(gop.StripANSI(gop.F(arr)), `[]gop_test.A/* len=2 cap=2 */{
170    gop_test.A{
171        Int: 0,
172        B: (*gop_test.B)(nil),
173    },
174    gop_test.A{
175        Int: 0,
176        B: (*gop_test.B)(nil),
177    },
178}`)
179}
180
181func TestCircularMap(t *testing.T) {
182	g := got.T(t)
183	a := map[int]interface{}{}
184	a[0] = a
185
186	ts := gop.Tokenize(a)
187
188	g.Eq(gop.Format(ts, gop.ThemeNone), `map[int]interface {}{
189    0: gop.Circular().(map[int]interface {}),
190}`)
191}
192
193func TestCircularSlice(t *testing.T) {
194	g := got.New(t)
195	a := [][]interface{}{{nil}, {nil}}
196	a[0][0] = a[1]
197	a[1][0] = a[0][0]
198
199	ts := gop.Tokenize(a)
200
201	g.Eq(gop.Format(ts, gop.ThemeNone), `[][]interface {}/* len=2 cap=2 */{
202    []interface {}/* len=1 cap=1 */{
203        []interface {}/* len=1 cap=1 */{
204            gop.Circular(0, 0).([]interface {}),
205        },
206    },
207    []interface {}/* len=1 cap=1 */{
208        gop.Circular(1).([]interface {}),
209    },
210}`)
211}
212
213func TestPlain(t *testing.T) {
214	g := got.T(t)
215	g.Eq(gop.Plain(10), "10")
216}
217
218func TestP(t *testing.T) {
219	gop.Stdout = ioutil.Discard
220	_ = gop.P("test")
221	gop.Stdout = os.Stdout
222}
223
224func TestConvertors(t *testing.T) {
225	g := got.T(t)
226	g.Nil(gop.Circular(""))
227
228	s := g.RandStr(8)
229	g.Eq(gop.Ptr(s).(*string), &s)
230
231	bs := base64.StdEncoding.EncodeToString([]byte(s))
232
233	g.Eq(gop.Base64(bs), []byte(s))
234	now := time.Now()
235	g.Eq(gop.Time(now.Format(time.RFC3339Nano), 1234), now)
236	g.Eq(gop.Duration("10m"), 10*time.Minute)
237
238	g.Eq(gop.JSONStr(nil, "[1, 2]"), "[1, 2]")
239	g.Eq(gop.JSONBytes(nil, "[1, 2]"), []byte("[1, 2]"))
240}
241
242func TestGetPrivateFieldErr(t *testing.T) {
243	g := got.T(t)
244	g.Panic(func() {
245		gop.GetPrivateField(reflect.ValueOf(1), 0)
246	})
247	g.Panic(func() {
248		gop.GetPrivateFieldByName(reflect.ValueOf(1), "test")
249	})
250}
251
252func TestTypeName(t *testing.T) {
253	g := got.T(t)
254
255	type f float64
256	type i int
257	type c complex128
258	type b byte
259
260	g.Eq(gop.Plain(f(1)), "gop_test.f(1.0)")
261	g.Eq(gop.Plain(i(1)), "gop_test.i(1)")
262	g.Eq(gop.Plain(c(1)), "gop_test.c(1+0i)")
263	g.Eq(gop.Plain(b('a')), "gop_test.b(97)")
264}
265
266func TestSliceCapNotEqual(t *testing.T) {
267	g := got.T(t)
268
269	x := gop.Plain(make([]int, 3, 10))
270	y := gop.Plain(make([]int, 3))
271
272	g.Desc("we should show the diff of cap").Neq(x, y)
273}
274
275func TestFixNestedStyle(t *testing.T) {
276	g := got.T(t)
277
278	s := gop.S(" 0 "+gop.S(" 1 "+
279		gop.S(" 2 "+
280			gop.S(" 3 ", gop.Cyan)+
281			" 4 ", gop.Blue)+
282		" 5 ", gop.Red)+" 6 ", gop.BgRed)
283	fmt.Println(gop.VisualizeANSI(s))
284	out := gop.VisualizeANSI(gop.FixNestedStyle(s))
285	g.Eq(out, `<41> 0 <31> 1 <39><34> 2 <39><36> 3 <39><34> 4 <39><31> 5 <39> 6 <49>`)
286
287	gop.FixNestedStyle("test")
288}
289
290func TestStripANSI(t *testing.T) {
291	g := got.T(t)
292	g.Eq(gop.StripANSI(gop.S("test", gop.Red)), "test")
293}
294
295func TestTheme(t *testing.T) {
296	g := got.T(t)
297	g.Eq(gop.ThemeDefault(gop.Error), []gop.Style{gop.Underline, gop.Red})
298}
299
Full Screen

style.go

Source: style.go Github

copy
1package gop
2
3import (
4	"fmt"
5	"os"
6	"os/exec"
7	"regexp"
8	"strconv"
9	"strings"
10)
11
12// Style type
13type Style struct {
14	Set   string
15	Unset string
16}
17
18var (
19	// Bold style
20	Bold = addStyle(1, 22)
21	// Faint style
22	Faint = addStyle(2, 22)
23	// Italic style
24	Italic = addStyle(3, 23)
25	// Underline style
26	Underline = addStyle(4, 24)
27	// Blink style
28	Blink = addStyle(5, 25)
29	// RapidBlink style
30	RapidBlink = addStyle(6, 26)
31	// Invert style
32	Invert = addStyle(7, 27)
33	// Hide style
34	Hide = addStyle(8, 28)
35	// Strike style
36	Strike = addStyle(9, 29)
37
38	// Black color
39	Black = addStyle(30, 39)
40	// Red color
41	Red = addStyle(31, 39)
42	// Green color
43	Green = addStyle(32, 39)
44	// Yellow color
45	Yellow = addStyle(33, 39)
46	// Blue color
47	Blue = addStyle(34, 39)
48	// Magenta color
49	Magenta = addStyle(35, 39)
50	// Cyan color
51	Cyan = addStyle(36, 39)
52	// White color
53	White = addStyle(37, 39)
54
55	// BgBlack color
56	BgBlack = addStyle(40, 49)
57	// BgRed color
58	BgRed = addStyle(41, 49)
59	// BgGreen color
60	BgGreen = addStyle(42, 49)
61	// BgYellow color
62	BgYellow = addStyle(43, 49)
63	// BgBlue color
64	BgBlue = addStyle(44, 49)
65	// BgMagenta color
66	BgMagenta = addStyle(45, 49)
67	// BgCyan color
68	BgCyan = addStyle(46, 49)
69	// BgWhite color
70	BgWhite = addStyle(47, 49)
71
72	// None type
73	None = Style{}
74)
75
76var regNewline = regexp.MustCompile(`\r?\n`)
77
78// S is the shortcut for Stylize
79func S(str string, styles ...Style) string {
80	return Stylize(str, styles)
81}
82
83// Stylize string
84func Stylize(str string, styles []Style) string {
85	for _, s := range styles {
86		str = stylize(s, str)
87	}
88	return str
89}
90
91func stylize(s Style, str string) string {
92	if NoStyle || s == None {
93		return str
94	}
95
96	newline := regNewline.FindString(str)
97
98	lines := regNewline.Split(str, -1)
99	out := []string{}
100
101	for _, l := range lines {
102		out = append(out, s.Set+l+s.Unset)
103	}
104
105	return strings.Join(out, newline)
106}
107
108// NoStyle respects https://no-color.org/ and "tput colors"
109var NoStyle = func() bool {
110	_, noColor := os.LookupEnv("NO_COLOR")
111
112	b, _ := exec.Command("tput", "colors").CombinedOutput()
113	n, _ := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 32)
114	return noColor || n == 0
115}()
116
117// RegANSI token
118var RegANSI = regexp.MustCompile(`\x1b\[\d+m`)
119
120// StripANSI tokens
121func StripANSI(str string) string {
122	return RegANSI.ReplaceAllString(str, "")
123}
124
125var regNum = regexp.MustCompile(`\d+`)
126
127// VisualizeANSI tokens
128func VisualizeANSI(str string) string {
129	return RegANSI.ReplaceAllStringFunc(str, func(s string) string {
130		return "<" + regNum.FindString(s) + ">"
131	})
132}
133
134// FixNestedStyle like
135//     <d><a>1<b>2<c>3</d></>4</>5</>
136// into
137//     <d><a>1</><b>2</><c>3</d></><b>4</><a>5</>
138func FixNestedStyle(s string) string {
139	out := ""
140	stacks := map[string][]string{}
141	i := 0
142	l := 0
143	r := 0
144
145	for i < len(s) {
146		loc := RegANSI.FindStringIndex(s[i:])
147		if loc == nil {
148			break
149		}
150
151		l, r = i+loc[0], i+loc[1]
152		token := s[l:r]
153
154		out += s[i:l]
155
156		unset := GetStyle(token).Unset
157
158		if unset == "" {
159			unset = token
160		}
161
162		if _, has := stacks[unset]; !has {
163			stacks[unset] = []string{}
164		}
165
166		stack := stacks[unset]
167		if len(stack) == 0 {
168			stack = append(stack, token)
169			out += token
170		} else {
171			if token == GetStyle(last(stack)).Unset {
172				out += token
173				stack = stack[:len(stack)-1]
174				if len(stack) > 0 {
175					out += last(stack)
176				}
177			} else {
178				out += GetStyle(last(stack)).Unset
179				stack = append(stack, token)
180				out += token
181			}
182		}
183		stacks[unset] = stack
184
185		i = r
186	}
187
188	return out + s[i:]
189}
190
191// GetStyle from available styles
192func GetStyle(s string) Style {
193	return styleSetMap[s]
194}
195
196func last(list []string) string {
197	return list[len(list)-1]
198}
199
200var styleSetMap = map[string]Style{}
201
202func addStyle(set, unset int) Style {
203	s := Style{
204		fmt.Sprintf("\x1b[%dm", set),
205		fmt.Sprintf("\x1b[%dm", unset),
206	}
207	styleSetMap[s.Set] = s
208	return s
209}
210
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)