utils_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. package integration
  2. import (
  3. "io"
  4. "io/ioutil"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "testing"
  12. "time"
  13. )
  14. func TestIsKilledFalseWithNonKilledProcess(t *testing.T) {
  15. // TODO Windows: Port this test
  16. if runtime.GOOS == "windows" {
  17. t.Skip("Needs porting to Windows")
  18. }
  19. lsCmd := exec.Command("ls")
  20. lsCmd.Start()
  21. // Wait for it to finish
  22. err := lsCmd.Wait()
  23. if IsKilled(err) {
  24. t.Fatalf("Expected the ls command to not be killed, was.")
  25. }
  26. }
  27. func TestIsKilledTrueWithKilledProcess(t *testing.T) {
  28. // TODO Windows: Using golang 1.5.3, this seems to hit
  29. // a bug in go where Process.Kill() causes a panic.
  30. // Needs further investigation @jhowardmsft
  31. if runtime.GOOS == "windows" {
  32. t.SkipNow()
  33. }
  34. longCmd := exec.Command("top")
  35. // Start a command
  36. longCmd.Start()
  37. // Capture the error when *dying*
  38. done := make(chan error, 1)
  39. go func() {
  40. done <- longCmd.Wait()
  41. }()
  42. // Then kill it
  43. longCmd.Process.Kill()
  44. // Get the error
  45. err := <-done
  46. if !IsKilled(err) {
  47. t.Fatalf("Expected the command to be killed, was not.")
  48. }
  49. }
  50. func TestRunCommandWithOutput(t *testing.T) {
  51. var (
  52. echoHelloWorldCmd *exec.Cmd
  53. expected string
  54. )
  55. if runtime.GOOS != "windows" {
  56. echoHelloWorldCmd = exec.Command("echo", "hello", "world")
  57. expected = "hello world\n"
  58. } else {
  59. echoHelloWorldCmd = exec.Command("cmd", "/s", "/c", "echo", "hello", "world")
  60. expected = "hello world\r\n"
  61. }
  62. out, exitCode, err := RunCommandWithOutput(echoHelloWorldCmd)
  63. if out != expected || exitCode != 0 || err != nil {
  64. t.Fatalf("Expected command to output %s, got %s, %v with exitCode %v", expected, out, err, exitCode)
  65. }
  66. }
  67. func TestRunCommandWithOutputError(t *testing.T) {
  68. var (
  69. p string
  70. wrongCmd *exec.Cmd
  71. expected string
  72. expectedExitCode int
  73. )
  74. if runtime.GOOS != "windows" {
  75. p = "$PATH"
  76. wrongCmd = exec.Command("ls", "-z")
  77. expected = `ls: invalid option -- 'z'
  78. Try 'ls --help' for more information.
  79. `
  80. expectedExitCode = 2
  81. } else {
  82. p = "%PATH%"
  83. wrongCmd = exec.Command("cmd", "/s", "/c", "dir", "/Z")
  84. expected = "Invalid switch - " + strconv.Quote("Z") + ".\r\n"
  85. expectedExitCode = 1
  86. }
  87. cmd := exec.Command("doesnotexists")
  88. out, exitCode, err := RunCommandWithOutput(cmd)
  89. expectedError := `exec: "doesnotexists": executable file not found in ` + p
  90. if out != "" || exitCode != 127 || err == nil || err.Error() != expectedError {
  91. t.Fatalf("Expected command to output %s, got %s, %v with exitCode %v", expectedError, out, err, exitCode)
  92. }
  93. out, exitCode, err = RunCommandWithOutput(wrongCmd)
  94. if out != expected || exitCode != expectedExitCode || err == nil || !strings.Contains(err.Error(), "exit status "+strconv.Itoa(expectedExitCode)) {
  95. t.Fatalf("Expected command to output %s, got out:xxx%sxxx, err:%v with exitCode %v", expected, out, err, exitCode)
  96. }
  97. }
  98. func TestRunCommandWithStdoutStderr(t *testing.T) {
  99. echoHelloWorldCmd := exec.Command("echo", "hello", "world")
  100. stdout, stderr, exitCode, err := RunCommandWithStdoutStderr(echoHelloWorldCmd)
  101. expected := "hello world\n"
  102. if stdout != expected || stderr != "" || exitCode != 0 || err != nil {
  103. t.Fatalf("Expected command to output %s, got stdout:%s, stderr:%s, err:%v with exitCode %v", expected, stdout, stderr, err, exitCode)
  104. }
  105. }
  106. func TestRunCommandWithStdoutStderrError(t *testing.T) {
  107. p := "$PATH"
  108. if runtime.GOOS == "windows" {
  109. p = "%PATH%"
  110. }
  111. cmd := exec.Command("doesnotexists")
  112. stdout, stderr, exitCode, err := RunCommandWithStdoutStderr(cmd)
  113. expectedError := `exec: "doesnotexists": executable file not found in ` + p
  114. if stdout != "" || stderr != "" || exitCode != 127 || err == nil || err.Error() != expectedError {
  115. t.Fatalf("Expected command to output out:%s, stderr:%s, got stdout:%s, stderr:%s, err:%v with exitCode %v", "", "", stdout, stderr, err, exitCode)
  116. }
  117. wrongLsCmd := exec.Command("ls", "-z")
  118. expected := `ls: invalid option -- 'z'
  119. Try 'ls --help' for more information.
  120. `
  121. stdout, stderr, exitCode, err = RunCommandWithStdoutStderr(wrongLsCmd)
  122. if stdout != "" && stderr != expected || exitCode != 2 || err == nil || err.Error() != "exit status 2" {
  123. t.Fatalf("Expected command to output out:%s, stderr:%s, got stdout:%s, stderr:%s, err:%v with exitCode %v", "", expectedError, stdout, stderr, err, exitCode)
  124. }
  125. }
  126. func TestRunCommandWithOutputForDurationFinished(t *testing.T) {
  127. // TODO Windows: Port this test
  128. if runtime.GOOS == "windows" {
  129. t.Skip("Needs porting to Windows")
  130. }
  131. cmd := exec.Command("ls")
  132. out, exitCode, timedOut, err := RunCommandWithOutputForDuration(cmd, 50*time.Millisecond)
  133. if out == "" || exitCode != 0 || timedOut || err != nil {
  134. t.Fatalf("Expected the command to run for less 50 milliseconds and thus not time out, but did not : out:[%s], exitCode:[%d], timedOut:[%v], err:[%v]", out, exitCode, timedOut, err)
  135. }
  136. }
  137. func TestRunCommandWithOutputForDurationKilled(t *testing.T) {
  138. // TODO Windows: Port this test
  139. if runtime.GOOS == "windows" {
  140. t.Skip("Needs porting to Windows")
  141. }
  142. cmd := exec.Command("sh", "-c", "while true ; do echo 1 ; sleep .1 ; done")
  143. out, exitCode, timedOut, err := RunCommandWithOutputForDuration(cmd, 500*time.Millisecond)
  144. ones := strings.Split(out, "\n")
  145. if len(ones) != 6 || exitCode != 0 || !timedOut || err != nil {
  146. t.Fatalf("Expected the command to run for 500 milliseconds (and thus print six lines (five with 1, one empty) and time out, but did not : out:[%s], exitCode:%d, timedOut:%v, err:%v", out, exitCode, timedOut, err)
  147. }
  148. }
  149. func TestRunCommandWithOutputForDurationErrors(t *testing.T) {
  150. cmd := exec.Command("ls")
  151. cmd.Stdout = os.Stdout
  152. if _, _, _, err := RunCommandWithOutputForDuration(cmd, 1*time.Millisecond); err == nil || err.Error() != "cmd.Stdout already set" {
  153. t.Fatalf("Expected an error as cmd.Stdout was already set, did not (err:%s).", err)
  154. }
  155. cmd = exec.Command("ls")
  156. cmd.Stderr = os.Stderr
  157. if _, _, _, err := RunCommandWithOutputForDuration(cmd, 1*time.Millisecond); err == nil || err.Error() != "cmd.Stderr already set" {
  158. t.Fatalf("Expected an error as cmd.Stderr was already set, did not (err:%s).", err)
  159. }
  160. }
  161. func TestRunCommandWithOutputAndTimeoutFinished(t *testing.T) {
  162. // TODO Windows: Port this test
  163. if runtime.GOOS == "windows" {
  164. t.Skip("Needs porting to Windows")
  165. }
  166. cmd := exec.Command("ls")
  167. out, exitCode, err := RunCommandWithOutputAndTimeout(cmd, 50*time.Millisecond)
  168. if out == "" || exitCode != 0 || err != nil {
  169. t.Fatalf("Expected the command to run for less 50 milliseconds and thus not time out, but did not : out:[%s], exitCode:[%d], err:[%v]", out, exitCode, err)
  170. }
  171. }
  172. func TestRunCommandWithOutputAndTimeoutKilled(t *testing.T) {
  173. // TODO Windows: Port this test
  174. if runtime.GOOS == "windows" {
  175. t.Skip("Needs porting to Windows")
  176. }
  177. cmd := exec.Command("sh", "-c", "while true ; do echo 1 ; sleep .1 ; done")
  178. out, exitCode, err := RunCommandWithOutputAndTimeout(cmd, 500*time.Millisecond)
  179. ones := strings.Split(out, "\n")
  180. if len(ones) != 6 || exitCode != 0 || err == nil || err.Error() != "command timed out" {
  181. t.Fatalf("Expected the command to run for 500 milliseconds (and thus print six lines (five with 1, one empty) and time out with an error 'command timed out', but did not : out:[%s], exitCode:%d, err:%v", out, exitCode, err)
  182. }
  183. }
  184. func TestRunCommandWithOutputAndTimeoutErrors(t *testing.T) {
  185. cmd := exec.Command("ls")
  186. cmd.Stdout = os.Stdout
  187. if _, _, err := RunCommandWithOutputAndTimeout(cmd, 1*time.Millisecond); err == nil || err.Error() != "cmd.Stdout already set" {
  188. t.Fatalf("Expected an error as cmd.Stdout was already set, did not (err:%s).", err)
  189. }
  190. cmd = exec.Command("ls")
  191. cmd.Stderr = os.Stderr
  192. if _, _, err := RunCommandWithOutputAndTimeout(cmd, 1*time.Millisecond); err == nil || err.Error() != "cmd.Stderr already set" {
  193. t.Fatalf("Expected an error as cmd.Stderr was already set, did not (err:%s).", err)
  194. }
  195. }
  196. func TestRunCommand(t *testing.T) {
  197. // TODO Windows: Port this test
  198. if runtime.GOOS == "windows" {
  199. t.Skip("Needs porting to Windows")
  200. }
  201. p := "$PATH"
  202. if runtime.GOOS == "windows" {
  203. p = "%PATH%"
  204. }
  205. lsCmd := exec.Command("ls")
  206. exitCode, err := RunCommand(lsCmd)
  207. if exitCode != 0 || err != nil {
  208. t.Fatalf("Expected runCommand to run the command successfully, got: exitCode:%d, err:%v", exitCode, err)
  209. }
  210. var expectedError string
  211. exitCode, err = RunCommand(exec.Command("doesnotexists"))
  212. expectedError = `exec: "doesnotexists": executable file not found in ` + p
  213. if exitCode != 127 || err == nil || err.Error() != expectedError {
  214. t.Fatalf("Expected runCommand to run the command successfully, got: exitCode:%d, err:%v", exitCode, err)
  215. }
  216. wrongLsCmd := exec.Command("ls", "-z")
  217. expected := 2
  218. expectedError = `exit status 2`
  219. exitCode, err = RunCommand(wrongLsCmd)
  220. if exitCode != expected || err == nil || err.Error() != expectedError {
  221. t.Fatalf("Expected runCommand to run the command successfully, got: exitCode:%d, err:%v", exitCode, err)
  222. }
  223. }
  224. func TestRunCommandPipelineWithOutputWithNotEnoughCmds(t *testing.T) {
  225. _, _, err := RunCommandPipelineWithOutput(exec.Command("ls"))
  226. expectedError := "pipeline does not have multiple cmds"
  227. if err == nil || err.Error() != expectedError {
  228. t.Fatalf("Expected an error with %s, got err:%s", expectedError, err)
  229. }
  230. }
  231. func TestRunCommandPipelineWithOutputErrors(t *testing.T) {
  232. p := "$PATH"
  233. if runtime.GOOS == "windows" {
  234. p = "%PATH%"
  235. }
  236. cmd1 := exec.Command("ls")
  237. cmd1.Stdout = os.Stdout
  238. cmd2 := exec.Command("anything really")
  239. _, _, err := RunCommandPipelineWithOutput(cmd1, cmd2)
  240. if err == nil || err.Error() != "cannot set stdout pipe for anything really: exec: Stdout already set" {
  241. t.Fatalf("Expected an error, got %v", err)
  242. }
  243. cmdWithError := exec.Command("doesnotexists")
  244. cmdCat := exec.Command("cat")
  245. _, _, err = RunCommandPipelineWithOutput(cmdWithError, cmdCat)
  246. if err == nil || err.Error() != `starting doesnotexists failed with error: exec: "doesnotexists": executable file not found in `+p {
  247. t.Fatalf("Expected an error, got %v", err)
  248. }
  249. }
  250. func TestRunCommandPipelineWithOutput(t *testing.T) {
  251. cmds := []*exec.Cmd{
  252. // Print 2 characters
  253. exec.Command("echo", "-n", "11"),
  254. // Count the number or char from stdin (previous command)
  255. exec.Command("wc", "-m"),
  256. }
  257. out, exitCode, err := RunCommandPipelineWithOutput(cmds...)
  258. expectedOutput := "2\n"
  259. if out != expectedOutput || exitCode != 0 || err != nil {
  260. t.Fatalf("Expected %s for commands %v, got out:%s, exitCode:%d, err:%v", expectedOutput, cmds, out, exitCode, err)
  261. }
  262. }
  263. // Simple simple test as it is just a passthrough for json.Unmarshal
  264. func TestUnmarshalJSON(t *testing.T) {
  265. emptyResult := struct{}{}
  266. if err := UnmarshalJSON([]byte(""), &emptyResult); err == nil {
  267. t.Fatalf("Expected an error, got nothing")
  268. }
  269. result := struct{ Name string }{}
  270. if err := UnmarshalJSON([]byte(`{"name": "name"}`), &result); err != nil {
  271. t.Fatal(err)
  272. }
  273. if result.Name != "name" {
  274. t.Fatalf("Expected result.name to be 'name', was '%s'", result.Name)
  275. }
  276. }
  277. func TestConvertSliceOfStringsToMap(t *testing.T) {
  278. input := []string{"a", "b"}
  279. actual := ConvertSliceOfStringsToMap(input)
  280. for _, key := range input {
  281. if _, ok := actual[key]; !ok {
  282. t.Fatalf("Expected output to contains key %s, did not: %v", key, actual)
  283. }
  284. }
  285. }
  286. func TestCompareDirectoryEntries(t *testing.T) {
  287. tmpFolder, err := ioutil.TempDir("", "integration-cli-utils-compare-directories")
  288. if err != nil {
  289. t.Fatal(err)
  290. }
  291. defer os.RemoveAll(tmpFolder)
  292. file1 := filepath.Join(tmpFolder, "file1")
  293. file2 := filepath.Join(tmpFolder, "file2")
  294. os.Create(file1)
  295. os.Create(file2)
  296. fi1, err := os.Stat(file1)
  297. if err != nil {
  298. t.Fatal(err)
  299. }
  300. fi1bis, err := os.Stat(file1)
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. fi2, err := os.Stat(file2)
  305. if err != nil {
  306. t.Fatal(err)
  307. }
  308. cases := []struct {
  309. e1 []os.FileInfo
  310. e2 []os.FileInfo
  311. shouldError bool
  312. }{
  313. // Empty directories
  314. {
  315. []os.FileInfo{},
  316. []os.FileInfo{},
  317. false,
  318. },
  319. // Same FileInfos
  320. {
  321. []os.FileInfo{fi1},
  322. []os.FileInfo{fi1},
  323. false,
  324. },
  325. // Different FileInfos but same names
  326. {
  327. []os.FileInfo{fi1},
  328. []os.FileInfo{fi1bis},
  329. false,
  330. },
  331. // Different FileInfos, different names
  332. {
  333. []os.FileInfo{fi1},
  334. []os.FileInfo{fi2},
  335. true,
  336. },
  337. }
  338. for _, elt := range cases {
  339. err := CompareDirectoryEntries(elt.e1, elt.e2)
  340. if elt.shouldError && err == nil {
  341. t.Fatalf("Should have return an error, did not with %v and %v", elt.e1, elt.e2)
  342. }
  343. if !elt.shouldError && err != nil {
  344. t.Fatalf("Should have not returned an error, but did : %v with %v and %v", err, elt.e1, elt.e2)
  345. }
  346. }
  347. }
  348. // FIXME make an "unhappy path" test for ListTar without "panicking" :-)
  349. func TestListTar(t *testing.T) {
  350. // TODO Windows: Figure out why this fails. Should be portable.
  351. if runtime.GOOS == "windows" {
  352. t.Skip("Failing on Windows - needs further investigation")
  353. }
  354. tmpFolder, err := ioutil.TempDir("", "integration-cli-utils-list-tar")
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. defer os.RemoveAll(tmpFolder)
  359. // Let's create a Tar file
  360. srcFile := filepath.Join(tmpFolder, "src")
  361. tarFile := filepath.Join(tmpFolder, "src.tar")
  362. os.Create(srcFile)
  363. cmd := exec.Command("sh", "-c", "tar cf "+tarFile+" "+srcFile)
  364. _, err = cmd.CombinedOutput()
  365. if err != nil {
  366. t.Fatal(err)
  367. }
  368. reader, err := os.Open(tarFile)
  369. if err != nil {
  370. t.Fatal(err)
  371. }
  372. defer reader.Close()
  373. entries, err := ListTar(reader)
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. if len(entries) != 1 && entries[0] != "src" {
  378. t.Fatalf("Expected a tar file with 1 entry (%s), got %v", srcFile, entries)
  379. }
  380. }
  381. func TestRandomTmpDirPath(t *testing.T) {
  382. path := RandomTmpDirPath("something", runtime.GOOS)
  383. prefix := "/tmp/something"
  384. if runtime.GOOS == "windows" {
  385. prefix = os.Getenv("TEMP") + `\something`
  386. }
  387. expectedSize := len(prefix) + 11
  388. if !strings.HasPrefix(path, prefix) {
  389. t.Fatalf("Expected generated path to have '%s' as prefix, got %s'", prefix, path)
  390. }
  391. if len(path) != expectedSize {
  392. t.Fatalf("Expected generated path to be %d, got %d", expectedSize, len(path))
  393. }
  394. }
  395. func TestConsumeWithSpeed(t *testing.T) {
  396. reader := strings.NewReader("1234567890")
  397. chunksize := 2
  398. bytes1, err := ConsumeWithSpeed(reader, chunksize, 1*time.Second, nil)
  399. if err != nil {
  400. t.Fatal(err)
  401. }
  402. if bytes1 != 10 {
  403. t.Fatalf("Expected to have read 10 bytes, got %d", bytes1)
  404. }
  405. }
  406. func TestConsumeWithSpeedWithStop(t *testing.T) {
  407. reader := strings.NewReader("1234567890")
  408. chunksize := 2
  409. stopIt := make(chan bool)
  410. go func() {
  411. time.Sleep(1 * time.Millisecond)
  412. stopIt <- true
  413. }()
  414. bytes1, err := ConsumeWithSpeed(reader, chunksize, 20*time.Millisecond, stopIt)
  415. if err != nil {
  416. t.Fatal(err)
  417. }
  418. if bytes1 != 2 {
  419. t.Fatalf("Expected to have read 2 bytes, got %d", bytes1)
  420. }
  421. }
  422. func TestParseCgroupPathsEmpty(t *testing.T) {
  423. cgroupMap := ParseCgroupPaths("")
  424. if len(cgroupMap) != 0 {
  425. t.Fatalf("Expected an empty map, got %v", cgroupMap)
  426. }
  427. cgroupMap = ParseCgroupPaths("\n")
  428. if len(cgroupMap) != 0 {
  429. t.Fatalf("Expected an empty map, got %v", cgroupMap)
  430. }
  431. cgroupMap = ParseCgroupPaths("something:else\nagain:here")
  432. if len(cgroupMap) != 0 {
  433. t.Fatalf("Expected an empty map, got %v", cgroupMap)
  434. }
  435. }
  436. func TestParseCgroupPaths(t *testing.T) {
  437. cgroupMap := ParseCgroupPaths("2:memory:/a\n1:cpuset:/b")
  438. if len(cgroupMap) != 2 {
  439. t.Fatalf("Expected a map with 2 entries, got %v", cgroupMap)
  440. }
  441. if value, ok := cgroupMap["memory"]; !ok || value != "/a" {
  442. t.Fatalf("Expected cgroupMap to contains an entry for 'memory' with value '/a', got %v", cgroupMap)
  443. }
  444. if value, ok := cgroupMap["cpuset"]; !ok || value != "/b" {
  445. t.Fatalf("Expected cgroupMap to contains an entry for 'cpuset' with value '/b', got %v", cgroupMap)
  446. }
  447. }
  448. func TestChannelBufferTimeout(t *testing.T) {
  449. expected := "11"
  450. buf := &ChannelBuffer{make(chan []byte, 1)}
  451. defer buf.Close()
  452. go func() {
  453. time.Sleep(100 * time.Millisecond)
  454. io.Copy(buf, strings.NewReader(expected))
  455. }()
  456. // Wait long enough
  457. b := make([]byte, 2)
  458. _, err := buf.ReadTimeout(b, 50*time.Millisecond)
  459. if err == nil && err.Error() != "timeout reading from channel" {
  460. t.Fatalf("Expected an error, got %s", err)
  461. }
  462. // Wait for the end :)
  463. time.Sleep(150 * time.Millisecond)
  464. }
  465. func TestChannelBuffer(t *testing.T) {
  466. expected := "11"
  467. buf := &ChannelBuffer{make(chan []byte, 1)}
  468. defer buf.Close()
  469. go func() {
  470. time.Sleep(100 * time.Millisecond)
  471. io.Copy(buf, strings.NewReader(expected))
  472. }()
  473. // Wait long enough
  474. b := make([]byte, 2)
  475. _, err := buf.ReadTimeout(b, 200*time.Millisecond)
  476. if err != nil {
  477. t.Fatal(err)
  478. }
  479. if string(b) != expected {
  480. t.Fatalf("Expected '%s', got '%s'", expected, string(b))
  481. }
  482. }
  483. // FIXME doesn't work
  484. // func TestRunAtDifferentDate(t *testing.T) {
  485. // var date string
  486. // // Layout for date. MMDDhhmmYYYY
  487. // const timeLayout = "20060102"
  488. // expectedDate := "20100201"
  489. // theDate, err := time.Parse(timeLayout, expectedDate)
  490. // if err != nil {
  491. // t.Fatal(err)
  492. // }
  493. // RunAtDifferentDate(theDate, func() {
  494. // cmd := exec.Command("date", "+%Y%M%d")
  495. // out, err := cmd.Output()
  496. // if err != nil {
  497. // t.Fatal(err)
  498. // }
  499. // date = string(out)
  500. // })
  501. // }