1package diffview_test
2
3import (
4 "bytes"
5 "encoding/json"
6 "testing"
7
8 "github.com/aymanbagabas/go-udiff"
9 "github.com/charmbracelet/x/exp/golden"
10)
11
12func TestUdiff(t *testing.T) {
13 before := `package main
14
15 import (
16 "fmt"
17 )
18
19 func main() {
20 fmt.Println("Hello, World!")
21 }`
22
23 after := `package main
24
25 import (
26 "fmt"
27 )
28
29 func main() {
30 content := "Hello, World!"
31 fmt.Println(content)
32 }`
33
34 t.Run("Unified", func(t *testing.T) {
35 content := udiff.Unified("main.go", "main.go", before, after)
36 golden.RequireEqual(t, []byte(content))
37 })
38
39 t.Run("ToUnifiedDiff", func(t *testing.T) {
40 toUnifiedDiff := func(t *testing.T, before, after string, contextLines int) udiff.UnifiedDiff {
41 edits := udiff.Strings(before, after)
42 unifiedDiff, err := udiff.ToUnifiedDiff("main.go", "main.go", before, edits, contextLines)
43 if err != nil {
44 t.Fatalf("ToUnifiedDiff failed: %v", err)
45 }
46 return unifiedDiff
47 }
48 toJSON := func(t *testing.T, unifiedDiff udiff.UnifiedDiff) []byte {
49 var buff bytes.Buffer
50 encoder := json.NewEncoder(&buff)
51 encoder.SetIndent("", " ")
52 if err := encoder.Encode(unifiedDiff); err != nil {
53 t.Fatalf("Failed to encode unified diff: %v", err)
54 }
55 return buff.Bytes()
56 }
57
58 t.Run("DefaultContextLines", func(t *testing.T) {
59 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines)
60
61 t.Run("Content", func(t *testing.T) {
62 golden.RequireEqual(t, []byte(unifiedDiff.String()))
63 })
64 t.Run("JSON", func(t *testing.T) {
65 golden.RequireEqual(t, toJSON(t, unifiedDiff))
66 })
67 })
68
69 t.Run("DefaultContextLinesPlusOne", func(t *testing.T) {
70 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines+1)
71
72 t.Run("Content", func(t *testing.T) {
73 golden.RequireEqual(t, []byte(unifiedDiff.String()))
74 })
75 t.Run("JSON", func(t *testing.T) {
76 golden.RequireEqual(t, toJSON(t, unifiedDiff))
77 })
78 })
79
80 t.Run("DefaultContextLinesPlusTwo", func(t *testing.T) {
81 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines+2)
82
83 t.Run("Content", func(t *testing.T) {
84 golden.RequireEqual(t, []byte(unifiedDiff.String()))
85 })
86 t.Run("JSON", func(t *testing.T) {
87 golden.RequireEqual(t, toJSON(t, unifiedDiff))
88 })
89 })
90 })
91}