File: options_test.go

package info (click to toggle)
golang-github-gomarkdown-markdown 0.0~git20231115.a660076-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,168 kB
  • sloc: sh: 26; makefile: 5
file content (131 lines) | stat: -rw-r--r-- 2,184 bytes parent folder | download
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package parser

import (
	"bytes"
	"strings"
	"testing"

	"github.com/gomarkdown/markdown/ast"
)

type CustomNode struct {
	ast.Container
}

// we default to true so to test it, we need to test false
func (n *CustomNode) CanContain(ast.Node) bool {
	return false
}

type CustomNode2 struct {
	ast.Container
}

func blockTitleHook(data []byte) (ast.Node, []byte, int) {
	sep := []byte(`%%%`)
	// parse text between %%% and %%% and return it as a blockQuote.
	if !bytes.HasPrefix(data, sep) {
		return nil, data, 0
	}

	end := bytes.Index(data[3:], sep)
	if end < 0 {
		return nil, data, 0
	}
	end += 3
	node := &CustomNode{}
	return node, data[4:end], end + 3
}

func blockTitleHook2(data []byte) (ast.Node, []byte, int) {
	sep := []byte(`%%%`)
	// parse text between %%% and %%% and return it as a blockQuote.
	if !bytes.HasPrefix(data, sep) {
		return nil, data, 0
	}

	end := bytes.Index(data[3:], sep)
	if end < 0 {
		return nil, data, 0
	}
	end += 3
	node := &CustomNode2{}
	return node, data[4:end], end + 3
}

func astPrint(root ast.Node) string {
	buf := &bytes.Buffer{}
	ast.Print(buf, root)
	return buf.String()
}

func astPretty(s string) string {
	s = strings.Replace(s, " ", "_", -1)
	s = strings.Replace(s, "\t", "__", -1)
	s = strings.Replace(s, "\n", "+", -1)
	return s
}

func TestCustomNode(t *testing.T) {
	tests := []struct {
		data string
		want string
	}{
		{
			data: `
%%%
hallo
%%%
`,
			want: `CustomNode
Paragraph 'hallo'
`,
		},
	}

	p := New()
	p.Opts = Options{ParserHook: blockTitleHook}

	for _, test := range tests {
		p.Block([]byte(test.data))
		data := astPrint(p.Doc)
		got := astPretty(data)
		want := astPretty(test.want)

		if got != want {
			t.Errorf("want: %s, got: %s", want, got)
		}
	}
}

func TestCustomNode2(t *testing.T) {
	tests := []struct {
		data string
		want string
	}{
		{
			data: `
%%%
hallo
%%%
`,
			want: `CustomNode2
  Paragraph 'hallo'
`,
		},
	}

	p := New()
	p.Opts = Options{ParserHook: blockTitleHook2}

	for _, test := range tests {
		p.Block([]byte(test.data))
		data := astPrint(p.Doc)
		got := astPretty(data)
		want := astPretty(test.want)

		if got != want {
			t.Errorf("want: %s, got: %s", want, got)
		}
	}
}