utils_test.go 16 KB

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