~poldi1405/go-ansi

ref: 38df6d151fa06b8ea8ed0695c667d6608ffe04c3 go-ansi/strip_test.go -rw-r--r-- 1.5 KiB
38df6d15 — Moritz Poldrack expanded strip for notifications 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ansi

import (
	"fmt"
	"regexp"
	"testing"
)

func BenchmarkStripping(b *testing.B) {
	DetectionPattern := regexp.MustCompile(`(?m)(((\x1b\[[;\d]*[A-Za-z])|\x1b]8;;|\x1b\\.*?\x1b|]8;;\x1b\\)*)`)
	str := fmt.Sprint(Black("black text"), "some kept text", ReverseVideo("inverted text"), Green("green text"), Bold("bold text"))

	b.Run("regex", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			DetectionPattern.ReplaceAllString(str, "")
		}
	})

	b.Run("split", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			StripString(str)
		}
	})
}

func TestStrip(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		expected string
	}{
		{
			name:     "formatting",
			input:    fmt.Sprint(Black("black text"), "some kept text", ReverseVideo("inverted text"), Green("green text"), Bold("bold text")),
			expected: "black textsome kept textinverted textgreen textbold text",
		},
		{
			name:     "link",
			input:    fmt.Sprintf("Link to my homepage: %s", LinkString("https://moritz.sh", "Linktext")),
			expected: "Link to my homepage: https://moritz.sh",
		},
		{
			name:     "notification",
			input:    fmt.Sprintf("Send a notification %sto me", SendNotification("title", "body")),
			expected: "Send a notification to me",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			if StripString(test.input) != test.expected {
				t.Logf("got:      %s\n", StripString(test.input))
				t.Logf("expected: %s\n", test.expected)
				t.Log([]byte(StripString(test.input)))
				t.Log([]byte(test.expected))
			}
		})
	}
}