udiff_test.go 2.3 KB

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