udiff_test.go 2.2 KB

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