toposort_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package toposort
  2. import "testing"
  3. func index(s []string, v string) int {
  4. for i, s := range s {
  5. if s == v {
  6. return i
  7. }
  8. }
  9. return -1
  10. }
  11. type Edge struct {
  12. From string
  13. To string
  14. }
  15. func TestDuplicatedNode(t *testing.T) {
  16. graph := NewGraph()
  17. graph.AddNode("a")
  18. if graph.AddNode("a") {
  19. t.Error("not raising duplicated node error")
  20. }
  21. }
  22. func TestRemoveNotExistEdge(t *testing.T) {
  23. graph := NewGraph()
  24. if graph.RemoveEdge("a", "b") {
  25. t.Error("not raising not exist edge error")
  26. }
  27. }
  28. func TestWikipedia(t *testing.T) {
  29. graph := NewGraph()
  30. graph.AddNodes("2", "3", "5", "7", "8", "9", "10", "11")
  31. edges := []Edge{
  32. {"7", "8"},
  33. {"7", "11"},
  34. {"5", "11"},
  35. {"3", "8"},
  36. {"3", "10"},
  37. {"11", "2"},
  38. {"11", "9"},
  39. {"11", "10"},
  40. {"8", "9"},
  41. }
  42. for _, e := range edges {
  43. graph.AddEdge(e.From, e.To)
  44. }
  45. result, ok := graph.Toposort()
  46. if !ok {
  47. t.Error("closed path detected in no closed pathed graph")
  48. }
  49. for _, e := range edges {
  50. if i, j := index(result, e.From), index(result, e.To); i > j {
  51. t.Errorf("dependency failed: not satisfy %v(%v) > %v(%v)", e.From, i, e.To, j)
  52. }
  53. }
  54. }
  55. func TestCycle(t *testing.T) {
  56. graph := NewGraph()
  57. graph.AddNodes("1", "2", "3")
  58. graph.AddEdge("1", "2")
  59. graph.AddEdge("2", "3")
  60. graph.AddEdge("3", "1")
  61. _, ok := graph.Toposort()
  62. if ok {
  63. t.Error("closed path not detected in closed pathed graph")
  64. }
  65. }