utils_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. package utils
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "io/ioutil"
  7. "strings"
  8. "testing"
  9. )
  10. func TestBufReader(t *testing.T) {
  11. reader, writer := io.Pipe()
  12. bufreader := NewBufReader(reader)
  13. // Write everything down to a Pipe
  14. // Usually, a pipe should block but because of the buffered reader,
  15. // the writes will go through
  16. done := make(chan bool)
  17. go func() {
  18. writer.Write([]byte("hello world"))
  19. writer.Close()
  20. done <- true
  21. }()
  22. // Drain the reader *after* everything has been written, just to verify
  23. // it is indeed buffering
  24. <-done
  25. output, err := ioutil.ReadAll(bufreader)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if !bytes.Equal(output, []byte("hello world")) {
  30. t.Error(string(output))
  31. }
  32. }
  33. type dummyWriter struct {
  34. buffer bytes.Buffer
  35. failOnWrite bool
  36. }
  37. func (dw *dummyWriter) Write(p []byte) (n int, err error) {
  38. if dw.failOnWrite {
  39. return 0, errors.New("Fake fail")
  40. }
  41. return dw.buffer.Write(p)
  42. }
  43. func (dw *dummyWriter) String() string {
  44. return dw.buffer.String()
  45. }
  46. func (dw *dummyWriter) Close() error {
  47. return nil
  48. }
  49. func TestWriteBroadcaster(t *testing.T) {
  50. writer := NewWriteBroadcaster()
  51. // Test 1: Both bufferA and bufferB should contain "foo"
  52. bufferA := &dummyWriter{}
  53. writer.AddWriter(bufferA, "")
  54. bufferB := &dummyWriter{}
  55. writer.AddWriter(bufferB, "")
  56. writer.Write([]byte("foo"))
  57. if bufferA.String() != "foo" {
  58. t.Errorf("Buffer contains %v", bufferA.String())
  59. }
  60. if bufferB.String() != "foo" {
  61. t.Errorf("Buffer contains %v", bufferB.String())
  62. }
  63. // Test2: bufferA and bufferB should contain "foobar",
  64. // while bufferC should only contain "bar"
  65. bufferC := &dummyWriter{}
  66. writer.AddWriter(bufferC, "")
  67. writer.Write([]byte("bar"))
  68. if bufferA.String() != "foobar" {
  69. t.Errorf("Buffer contains %v", bufferA.String())
  70. }
  71. if bufferB.String() != "foobar" {
  72. t.Errorf("Buffer contains %v", bufferB.String())
  73. }
  74. if bufferC.String() != "bar" {
  75. t.Errorf("Buffer contains %v", bufferC.String())
  76. }
  77. // Test3: Test eviction on failure
  78. bufferA.failOnWrite = true
  79. writer.Write([]byte("fail"))
  80. if bufferA.String() != "foobar" {
  81. t.Errorf("Buffer contains %v", bufferA.String())
  82. }
  83. if bufferC.String() != "barfail" {
  84. t.Errorf("Buffer contains %v", bufferC.String())
  85. }
  86. // Even though we reset the flag, no more writes should go in there
  87. bufferA.failOnWrite = false
  88. writer.Write([]byte("test"))
  89. if bufferA.String() != "foobar" {
  90. t.Errorf("Buffer contains %v", bufferA.String())
  91. }
  92. if bufferC.String() != "barfailtest" {
  93. t.Errorf("Buffer contains %v", bufferC.String())
  94. }
  95. writer.CloseWriters()
  96. }
  97. type devNullCloser int
  98. func (d devNullCloser) Close() error {
  99. return nil
  100. }
  101. func (d devNullCloser) Write(buf []byte) (int, error) {
  102. return len(buf), nil
  103. }
  104. // This test checks for races. It is only useful when run with the race detector.
  105. func TestRaceWriteBroadcaster(t *testing.T) {
  106. writer := NewWriteBroadcaster()
  107. c := make(chan bool)
  108. go func() {
  109. writer.AddWriter(devNullCloser(0), "")
  110. c <- true
  111. }()
  112. writer.Write([]byte("hello"))
  113. <-c
  114. }
  115. // Test the behavior of TruncIndex, an index for querying IDs from a non-conflicting prefix.
  116. func TestTruncIndex(t *testing.T) {
  117. index := NewTruncIndex()
  118. // Get on an empty index
  119. if _, err := index.Get("foobar"); err == nil {
  120. t.Fatal("Get on an empty index should return an error")
  121. }
  122. // Spaces should be illegal in an id
  123. if err := index.Add("I have a space"); err == nil {
  124. t.Fatalf("Adding an id with ' ' should return an error")
  125. }
  126. id := "99b36c2c326ccc11e726eee6ee78a0baf166ef96"
  127. // Add an id
  128. if err := index.Add(id); err != nil {
  129. t.Fatal(err)
  130. }
  131. // Get a non-existing id
  132. assertIndexGet(t, index, "abracadabra", "", true)
  133. // Get the exact id
  134. assertIndexGet(t, index, id, id, false)
  135. // The first letter should match
  136. assertIndexGet(t, index, id[:1], id, false)
  137. // The first half should match
  138. assertIndexGet(t, index, id[:len(id)/2], id, false)
  139. // The second half should NOT match
  140. assertIndexGet(t, index, id[len(id)/2:], "", true)
  141. id2 := id[:6] + "blabla"
  142. // Add an id
  143. if err := index.Add(id2); err != nil {
  144. t.Fatal(err)
  145. }
  146. // Both exact IDs should work
  147. assertIndexGet(t, index, id, id, false)
  148. assertIndexGet(t, index, id2, id2, false)
  149. // 6 characters or less should conflict
  150. assertIndexGet(t, index, id[:6], "", true)
  151. assertIndexGet(t, index, id[:4], "", true)
  152. assertIndexGet(t, index, id[:1], "", true)
  153. // 7 characters should NOT conflict
  154. assertIndexGet(t, index, id[:7], id, false)
  155. assertIndexGet(t, index, id2[:7], id2, false)
  156. // Deleting a non-existing id should return an error
  157. if err := index.Delete("non-existing"); err == nil {
  158. t.Fatalf("Deleting a non-existing id should return an error")
  159. }
  160. // Deleting id2 should remove conflicts
  161. if err := index.Delete(id2); err != nil {
  162. t.Fatal(err)
  163. }
  164. // id2 should no longer work
  165. assertIndexGet(t, index, id2, "", true)
  166. assertIndexGet(t, index, id2[:7], "", true)
  167. assertIndexGet(t, index, id2[:11], "", true)
  168. // conflicts between id and id2 should be gone
  169. assertIndexGet(t, index, id[:6], id, false)
  170. assertIndexGet(t, index, id[:4], id, false)
  171. assertIndexGet(t, index, id[:1], id, false)
  172. // non-conflicting substrings should still not conflict
  173. assertIndexGet(t, index, id[:7], id, false)
  174. assertIndexGet(t, index, id[:15], id, false)
  175. assertIndexGet(t, index, id, id, false)
  176. }
  177. func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult string, expectError bool) {
  178. if result, err := index.Get(input); err != nil && !expectError {
  179. t.Fatalf("Unexpected error getting '%s': %s", input, err)
  180. } else if err == nil && expectError {
  181. t.Fatalf("Getting '%s' should return an error", input)
  182. } else if result != expectedResult {
  183. t.Fatalf("Getting '%s' returned '%s' instead of '%s'", input, result, expectedResult)
  184. }
  185. }
  186. func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) {
  187. if r := CompareKernelVersion(a, b); r != result {
  188. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  189. }
  190. }
  191. func TestCompareKernelVersion(t *testing.T) {
  192. assertKernelVersion(t,
  193. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  194. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  195. 0)
  196. assertKernelVersion(t,
  197. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  198. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  199. -1)
  200. assertKernelVersion(t,
  201. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  202. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  203. 1)
  204. assertKernelVersion(t,
  205. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "0"},
  206. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "16"},
  207. 0)
  208. assertKernelVersion(t,
  209. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5},
  210. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  211. 1)
  212. assertKernelVersion(t,
  213. &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20, Flavor: "25"},
  214. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "0"},
  215. -1)
  216. }
  217. func TestHumanSize(t *testing.T) {
  218. size := strings.Trim(HumanSize(1000), " \t")
  219. expect := "1 kB"
  220. if size != expect {
  221. t.Errorf("1000 -> expected '%s', got '%s'", expect, size)
  222. }
  223. size = strings.Trim(HumanSize(1024), " \t")
  224. expect = "1.024 kB"
  225. if size != expect {
  226. t.Errorf("1024 -> expected '%s', got '%s'", expect, size)
  227. }
  228. }
  229. func TestRAMInBytes(t *testing.T) {
  230. assertRAMInBytes(t, "32", false, 32)
  231. assertRAMInBytes(t, "32b", false, 32)
  232. assertRAMInBytes(t, "32B", false, 32)
  233. assertRAMInBytes(t, "32k", false, 32*1024)
  234. assertRAMInBytes(t, "32K", false, 32*1024)
  235. assertRAMInBytes(t, "32kb", false, 32*1024)
  236. assertRAMInBytes(t, "32Kb", false, 32*1024)
  237. assertRAMInBytes(t, "32Mb", false, 32*1024*1024)
  238. assertRAMInBytes(t, "32Gb", false, 32*1024*1024*1024)
  239. assertRAMInBytes(t, "", true, -1)
  240. assertRAMInBytes(t, "hello", true, -1)
  241. assertRAMInBytes(t, "-32", true, -1)
  242. assertRAMInBytes(t, " 32 ", true, -1)
  243. assertRAMInBytes(t, "32 mb", true, -1)
  244. assertRAMInBytes(t, "32m b", true, -1)
  245. assertRAMInBytes(t, "32bm", true, -1)
  246. }
  247. func assertRAMInBytes(t *testing.T, size string, expectError bool, expectedBytes int64) {
  248. actualBytes, err := RAMInBytes(size)
  249. if (err != nil) && !expectError {
  250. t.Errorf("Unexpected error parsing '%s': %s", size, err)
  251. }
  252. if (err == nil) && expectError {
  253. t.Errorf("Expected to get an error parsing '%s', but got none (bytes=%d)", size, actualBytes)
  254. }
  255. if actualBytes != expectedBytes {
  256. t.Errorf("Expected '%s' to parse as %d bytes, got %d", size, expectedBytes, actualBytes)
  257. }
  258. }
  259. func TestParseHost(t *testing.T) {
  260. if addr, err := ParseHost("127.0.0.1", 4243, "0.0.0.0"); err != nil || addr != "tcp://0.0.0.0:4243" {
  261. t.Errorf("0.0.0.0 -> expected tcp://0.0.0.0:4243, got %s", addr)
  262. }
  263. if addr, err := ParseHost("127.0.0.1", 4243, "0.0.0.1:5555"); err != nil || addr != "tcp://0.0.0.1:5555" {
  264. t.Errorf("0.0.0.1:5555 -> expected tcp://0.0.0.1:5555, got %s", addr)
  265. }
  266. if addr, err := ParseHost("127.0.0.1", 4243, ":6666"); err != nil || addr != "tcp://127.0.0.1:6666" {
  267. t.Errorf(":6666 -> expected tcp://127.0.0.1:6666, got %s", addr)
  268. }
  269. if addr, err := ParseHost("127.0.0.1", 4243, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" {
  270. t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr)
  271. }
  272. if addr, err := ParseHost("127.0.0.1", 4243, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" {
  273. t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
  274. }
  275. if addr, err := ParseHost("127.0.0.1", 4243, "udp://127.0.0.1"); err == nil {
  276. t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
  277. }
  278. }
  279. func TestParseRepositoryTag(t *testing.T) {
  280. if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" {
  281. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag)
  282. }
  283. if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" {
  284. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag)
  285. }
  286. if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" {
  287. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag)
  288. }
  289. if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" {
  290. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag)
  291. }
  292. if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" {
  293. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag)
  294. }
  295. if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" {
  296. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag)
  297. }
  298. }
  299. func TestGetResolvConf(t *testing.T) {
  300. resolvConfUtils, err := GetResolvConf()
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  305. if err != nil {
  306. t.Fatal(err)
  307. }
  308. if string(resolvConfUtils) != string(resolvConfSystem) {
  309. t.Fatalf("/etc/resolv.conf and GetResolvConf have different content.")
  310. }
  311. }
  312. func TestCheckLocalDns(t *testing.T) {
  313. for resolv, result := range map[string]bool{`# Dynamic
  314. nameserver 10.0.2.3
  315. search dotcloud.net`: false,
  316. `# Dynamic
  317. #nameserver 127.0.0.1
  318. nameserver 10.0.2.3
  319. search dotcloud.net`: false,
  320. `# Dynamic
  321. nameserver 10.0.2.3 #not used 127.0.1.1
  322. search dotcloud.net`: false,
  323. `# Dynamic
  324. #nameserver 10.0.2.3
  325. #search dotcloud.net`: true,
  326. `# Dynamic
  327. nameserver 127.0.0.1
  328. search dotcloud.net`: true,
  329. `# Dynamic
  330. nameserver 127.0.1.1
  331. search dotcloud.net`: true,
  332. `# Dynamic
  333. `: true,
  334. ``: true,
  335. } {
  336. if CheckLocalDns([]byte(resolv)) != result {
  337. t.Fatalf("Wrong local dns detection: {%s} should be %v", resolv, result)
  338. }
  339. }
  340. }
  341. func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) {
  342. var (
  343. a *KernelVersionInfo
  344. )
  345. a, _ = ParseRelease(release)
  346. if r := CompareKernelVersion(a, b); r != result {
  347. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  348. }
  349. }
  350. func TestParseRelease(t *testing.T) {
  351. assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0)
  352. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54}, 0)
  353. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: "1"}, 0)
  354. assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "19-generic"}, 0)
  355. }
  356. func TestDependencyGraphCircular(t *testing.T) {
  357. g1 := NewDependencyGraph()
  358. a := g1.NewNode("a")
  359. b := g1.NewNode("b")
  360. g1.AddDependency(a, b)
  361. g1.AddDependency(b, a)
  362. res, err := g1.GenerateTraversalMap()
  363. if res != nil {
  364. t.Fatalf("Expected nil result")
  365. }
  366. if err == nil {
  367. t.Fatalf("Expected error (circular graph can not be resolved)")
  368. }
  369. }
  370. func TestDependencyGraph(t *testing.T) {
  371. g1 := NewDependencyGraph()
  372. a := g1.NewNode("a")
  373. b := g1.NewNode("b")
  374. c := g1.NewNode("c")
  375. d := g1.NewNode("d")
  376. g1.AddDependency(b, a)
  377. g1.AddDependency(c, a)
  378. g1.AddDependency(d, c)
  379. g1.AddDependency(d, b)
  380. res, err := g1.GenerateTraversalMap()
  381. if err != nil {
  382. t.Fatalf("%s", err)
  383. }
  384. if res == nil {
  385. t.Fatalf("Unexpected nil result")
  386. }
  387. if len(res) != 3 {
  388. t.Fatalf("Expected map of length 3, found %d instead", len(res))
  389. }
  390. if len(res[0]) != 1 || res[0][0] != "a" {
  391. t.Fatalf("Expected [a], found %v instead", res[0])
  392. }
  393. if len(res[1]) != 2 {
  394. t.Fatalf("Expected 2 nodes for step 2, found %d", len(res[1]))
  395. }
  396. if (res[1][0] != "b" && res[1][1] != "b") || (res[1][0] != "c" && res[1][1] != "c") {
  397. t.Fatalf("Expected [b, c], found %v instead", res[1])
  398. }
  399. if len(res[2]) != 1 || res[2][0] != "d" {
  400. t.Fatalf("Expected [d], found %v instead", res[2])
  401. }
  402. }
  403. func TestParsePortMapping(t *testing.T) {
  404. data, err := PartParser("ip:public:private", "192.168.1.1:80:8080")
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. if len(data) != 3 {
  409. t.FailNow()
  410. }
  411. if data["ip"] != "192.168.1.1" {
  412. t.Fail()
  413. }
  414. if data["public"] != "80" {
  415. t.Fail()
  416. }
  417. if data["private"] != "8080" {
  418. t.Fail()
  419. }
  420. }
  421. func TestGetNameserversAsCIDR(t *testing.T) {
  422. for resolv, result := range map[string][]string{`
  423. nameserver 1.2.3.4
  424. nameserver 40.3.200.10
  425. search example.com`: {"1.2.3.4/32", "40.3.200.10/32"},
  426. `search example.com`: {},
  427. `nameserver 1.2.3.4
  428. search example.com
  429. nameserver 4.30.20.100`: {"1.2.3.4/32", "4.30.20.100/32"},
  430. ``: {},
  431. ` nameserver 1.2.3.4 `: {"1.2.3.4/32"},
  432. `search example.com
  433. nameserver 1.2.3.4
  434. #nameserver 4.3.2.1`: {"1.2.3.4/32"},
  435. `search example.com
  436. nameserver 1.2.3.4 # not 4.3.2.1`: {"1.2.3.4/32"},
  437. } {
  438. test := GetNameserversAsCIDR([]byte(resolv))
  439. if !StrSlicesEqual(test, result) {
  440. t.Fatalf("Wrong nameserver string {%s} should be %v. Input: %s", test, result, resolv)
  441. }
  442. }
  443. }
  444. func StrSlicesEqual(a, b []string) bool {
  445. if len(a) != len(b) {
  446. return false
  447. }
  448. for i, v := range a {
  449. if v != b[i] {
  450. return false
  451. }
  452. }
  453. return true
  454. }