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