utils_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package utils
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "io/ioutil"
  7. "os"
  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. ids := []string{}
  118. index := NewTruncIndex(ids)
  119. // Get on an empty index
  120. if _, err := index.Get("foobar"); err == nil {
  121. t.Fatal("Get on an empty index should return an error")
  122. }
  123. // Spaces should be illegal in an id
  124. if err := index.Add("I have a space"); err == nil {
  125. t.Fatalf("Adding an id with ' ' should return an error")
  126. }
  127. id := "99b36c2c326ccc11e726eee6ee78a0baf166ef96"
  128. // Add an id
  129. if err := index.Add(id); err != nil {
  130. t.Fatal(err)
  131. }
  132. // Get a non-existing id
  133. assertIndexGet(t, index, "abracadabra", "", true)
  134. // Get the exact id
  135. assertIndexGet(t, index, id, id, false)
  136. // The first letter should match
  137. assertIndexGet(t, index, id[:1], id, false)
  138. // The first half should match
  139. assertIndexGet(t, index, id[:len(id)/2], id, false)
  140. // The second half should NOT match
  141. assertIndexGet(t, index, id[len(id)/2:], "", true)
  142. id2 := id[:6] + "blabla"
  143. // Add an id
  144. if err := index.Add(id2); err != nil {
  145. t.Fatal(err)
  146. }
  147. // Both exact IDs should work
  148. assertIndexGet(t, index, id, id, false)
  149. assertIndexGet(t, index, id2, id2, false)
  150. // 6 characters or less should conflict
  151. assertIndexGet(t, index, id[:6], "", true)
  152. assertIndexGet(t, index, id[:4], "", true)
  153. assertIndexGet(t, index, id[:1], "", true)
  154. // 7 characters should NOT conflict
  155. assertIndexGet(t, index, id[:7], id, false)
  156. assertIndexGet(t, index, id2[:7], id2, false)
  157. // Deleting a non-existing id should return an error
  158. if err := index.Delete("non-existing"); err == nil {
  159. t.Fatalf("Deleting a non-existing id should return an error")
  160. }
  161. // Deleting id2 should remove conflicts
  162. if err := index.Delete(id2); err != nil {
  163. t.Fatal(err)
  164. }
  165. // id2 should no longer work
  166. assertIndexGet(t, index, id2, "", true)
  167. assertIndexGet(t, index, id2[:7], "", true)
  168. assertIndexGet(t, index, id2[:11], "", true)
  169. // conflicts between id and id2 should be gone
  170. assertIndexGet(t, index, id[:6], id, false)
  171. assertIndexGet(t, index, id[:4], id, false)
  172. assertIndexGet(t, index, id[:1], id, false)
  173. // non-conflicting substrings should still not conflict
  174. assertIndexGet(t, index, id[:7], id, false)
  175. assertIndexGet(t, index, id[:15], id, false)
  176. assertIndexGet(t, index, id, id, false)
  177. }
  178. func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult string, expectError bool) {
  179. if result, err := index.Get(input); err != nil && !expectError {
  180. t.Fatalf("Unexpected error getting '%s': %s", input, err)
  181. } else if err == nil && expectError {
  182. t.Fatalf("Getting '%s' should return an error", input)
  183. } else if result != expectedResult {
  184. t.Fatalf("Getting '%s' returned '%s' instead of '%s'", input, result, expectedResult)
  185. }
  186. }
  187. func BenchmarkTruncIndexAdd(b *testing.B) {
  188. ids := []string{"banana", "bananaa", "bananab"}
  189. b.ResetTimer()
  190. for i := 0; i < b.N; i++ {
  191. index := NewTruncIndex([]string{})
  192. for _, id := range ids {
  193. index.Add(id)
  194. }
  195. }
  196. }
  197. func BenchmarkTruncIndexNew(b *testing.B) {
  198. ids := []string{"banana", "bananaa", "bananab"}
  199. b.ResetTimer()
  200. for i := 0; i < b.N; i++ {
  201. NewTruncIndex(ids)
  202. }
  203. }
  204. func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) {
  205. if r := CompareKernelVersion(a, b); r != result {
  206. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  207. }
  208. }
  209. func TestCompareKernelVersion(t *testing.T) {
  210. assertKernelVersion(t,
  211. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  212. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  213. 0)
  214. assertKernelVersion(t,
  215. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  216. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  217. -1)
  218. assertKernelVersion(t,
  219. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  220. &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0},
  221. 1)
  222. assertKernelVersion(t,
  223. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  224. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  225. 0)
  226. assertKernelVersion(t,
  227. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5},
  228. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  229. 1)
  230. assertKernelVersion(t,
  231. &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20},
  232. &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
  233. -1)
  234. }
  235. func TestParseHost(t *testing.T) {
  236. var (
  237. defaultHttpHost = "127.0.0.1"
  238. defaultUnix = "/var/run/docker.sock"
  239. )
  240. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.0"); err == nil {
  241. t.Errorf("tcp 0.0.0.0 address expected error return, but err == nil, got %s", addr)
  242. }
  243. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://"); err == nil {
  244. t.Errorf("default tcp:// address expected error return, but err == nil, got %s", addr)
  245. }
  246. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.1:5555"); err != nil || addr != "tcp://0.0.0.1:5555" {
  247. t.Errorf("0.0.0.1:5555 -> expected tcp://0.0.0.1:5555, got %s", addr)
  248. }
  249. if addr, err := ParseHost(defaultHttpHost, defaultUnix, ":6666"); err != nil || addr != "tcp://127.0.0.1:6666" {
  250. t.Errorf(":6666 -> expected tcp://127.0.0.1:6666, got %s", addr)
  251. }
  252. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" {
  253. t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr)
  254. }
  255. if addr, err := ParseHost(defaultHttpHost, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" {
  256. t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr)
  257. }
  258. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" {
  259. t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
  260. }
  261. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix://"); err != nil || addr != "unix:///var/run/docker.sock" {
  262. t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
  263. }
  264. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1"); err == nil {
  265. t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
  266. }
  267. if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1:2375"); err == nil {
  268. t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
  269. }
  270. }
  271. func TestParseRepositoryTag(t *testing.T) {
  272. if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" {
  273. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag)
  274. }
  275. if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" {
  276. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag)
  277. }
  278. if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" {
  279. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag)
  280. }
  281. if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" {
  282. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag)
  283. }
  284. if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" {
  285. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag)
  286. }
  287. if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" {
  288. t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag)
  289. }
  290. }
  291. func TestCheckLocalDns(t *testing.T) {
  292. for resolv, result := range map[string]bool{`# Dynamic
  293. nameserver 10.0.2.3
  294. search dotcloud.net`: false,
  295. `# Dynamic
  296. #nameserver 127.0.0.1
  297. nameserver 10.0.2.3
  298. search dotcloud.net`: false,
  299. `# Dynamic
  300. nameserver 10.0.2.3 #not used 127.0.1.1
  301. search dotcloud.net`: false,
  302. `# Dynamic
  303. #nameserver 10.0.2.3
  304. #search dotcloud.net`: true,
  305. `# Dynamic
  306. nameserver 127.0.0.1
  307. search dotcloud.net`: true,
  308. `# Dynamic
  309. nameserver 127.0.1.1
  310. search dotcloud.net`: true,
  311. `# Dynamic
  312. `: true,
  313. ``: true,
  314. } {
  315. if CheckLocalDns([]byte(resolv)) != result {
  316. t.Fatalf("Wrong local dns detection: {%s} should be %v", resolv, result)
  317. }
  318. }
  319. }
  320. func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) {
  321. var (
  322. a *KernelVersionInfo
  323. )
  324. a, _ = ParseRelease(release)
  325. if r := CompareKernelVersion(a, b); r != result {
  326. t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
  327. }
  328. if a.Flavor != b.Flavor {
  329. t.Fatalf("Unexpected parsed kernel flavor. Found %s, expected %s", a.Flavor, b.Flavor)
  330. }
  331. }
  332. func TestParseRelease(t *testing.T) {
  333. assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0)
  334. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0)
  335. assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0)
  336. assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "-19-generic"}, 0)
  337. assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8, Flavor: "tag"}, 0)
  338. assertParseRelease(t, "3.12-1-amd64", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 0, Flavor: "-1-amd64"}, 0)
  339. }
  340. func TestParsePortMapping(t *testing.T) {
  341. data, err := PartParser("ip:public:private", "192.168.1.1:80:8080")
  342. if err != nil {
  343. t.Fatal(err)
  344. }
  345. if len(data) != 3 {
  346. t.FailNow()
  347. }
  348. if data["ip"] != "192.168.1.1" {
  349. t.Fail()
  350. }
  351. if data["public"] != "80" {
  352. t.Fail()
  353. }
  354. if data["private"] != "8080" {
  355. t.Fail()
  356. }
  357. }
  358. func TestReplaceAndAppendEnvVars(t *testing.T) {
  359. var (
  360. d = []string{"HOME=/"}
  361. o = []string{"HOME=/root", "TERM=xterm"}
  362. )
  363. env := ReplaceOrAppendEnvValues(d, o)
  364. if len(env) != 2 {
  365. t.Fatalf("expected len of 2 got %d", len(env))
  366. }
  367. if env[0] != "HOME=/root" {
  368. t.Fatalf("expected HOME=/root got '%s'", env[0])
  369. }
  370. if env[1] != "TERM=xterm" {
  371. t.Fatalf("expected TERM=xterm got '%s'", env[1])
  372. }
  373. }
  374. // Reading a symlink to a directory must return the directory
  375. func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {
  376. var err error
  377. if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil {
  378. t.Errorf("failed to create directory: %s", err)
  379. }
  380. if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil {
  381. t.Errorf("failed to create symlink: %s", err)
  382. }
  383. var path string
  384. if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil {
  385. t.Fatalf("failed to read symlink to directory: %s", err)
  386. }
  387. if path != "/tmp/testReadSymlinkToExistingDirectory" {
  388. t.Fatalf("symlink returned unexpected directory: %s", path)
  389. }
  390. if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil {
  391. t.Errorf("failed to remove temporary directory: %s", err)
  392. }
  393. if err = os.Remove("/tmp/dirLinkTest"); err != nil {
  394. t.Errorf("failed to remove symlink: %s", err)
  395. }
  396. }
  397. // Reading a non-existing symlink must fail
  398. func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {
  399. var path string
  400. var err error
  401. if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil {
  402. t.Fatalf("error expected for non-existing symlink")
  403. }
  404. if path != "" {
  405. t.Fatalf("expected empty path, but '%s' was returned", path)
  406. }
  407. }
  408. // Reading a symlink to a file must fail
  409. func TestReadSymlinkedDirectoryToFile(t *testing.T) {
  410. var err error
  411. var file *os.File
  412. if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
  413. t.Fatalf("failed to create file: %s", err)
  414. }
  415. file.Close()
  416. if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
  417. t.Errorf("failed to create symlink: %s", err)
  418. }
  419. var path string
  420. if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
  421. t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
  422. }
  423. if path != "" {
  424. t.Fatalf("path should've been empty: %s", path)
  425. }
  426. if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
  427. t.Errorf("failed to remove file: %s", err)
  428. }
  429. if err = os.Remove("/tmp/fileLinkTest"); err != nil {
  430. t.Errorf("failed to remove symlink: %s", err)
  431. }
  432. }