on 94de6bc help sign in
crush/internal/tui/exp/diffview/udiff_test.go
91 lines 2.3 kB history raw
1package diffview_test
3import (
4 "bytes"
5 "encoding/json"
6 "testing"
8 "github.com/aymanbagabas/go-udiff"
9 "github.com/charmbracelet/x/exp/golden"
12func TestUdiff(t *testing.T) {
13 before := `package main
15 import (
16 "fmt"
17 )
19 func main() {
20 fmt.Println("Hello, World!")
21 }`
23 after := `package main
25 import (
26 "fmt"
27 )
29 func main() {
30 content := "Hello, World!"
31 fmt.Println(content)
32 }`
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 })
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 }
58 t.Run("DefaultContextLines", func(t *testing.T) {
59 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines)
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 })
69 t.Run("DefaultContextLinesPlusOne", func(t *testing.T) {
70 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines+1)
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 })
80 t.Run("DefaultContextLinesPlusTwo", func(t *testing.T) {
81 unifiedDiff := toUnifiedDiff(t, before, after, udiff.DefaultContextLines+2)
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 })