2
0

docker_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package worker
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "github.com/codeskyblue/go-sh"
  10. . "github.com/smartystreets/goconvey/convey"
  11. )
  12. func getDockerByName(name string) (string, error) {
  13. // docker ps -f 'name=$name' --format '{{.Names}}'
  14. out, err := sh.Command(
  15. "docker", "ps",
  16. "--filter", "name="+name,
  17. "--format", "{{.Names}}",
  18. ).Output()
  19. return string(out), err
  20. }
  21. func TestDocker(t *testing.T) {
  22. Convey("Docker Should Work", t, func(ctx C) {
  23. tmpDir, err := ioutil.TempDir("", "tunasync")
  24. defer os.RemoveAll(tmpDir)
  25. So(err, ShouldBeNil)
  26. cmdScript := filepath.Join(tmpDir, "cmd.sh")
  27. tmpFile := filepath.Join(tmpDir, "log_file")
  28. expectedOutput := "HELLO_WORLD"
  29. c := cmdConfig{
  30. name: "tuna-docker",
  31. upstreamURL: "http://mirrors.tuna.moe/",
  32. command: "/bin/cmd.sh",
  33. workingDir: tmpDir,
  34. logDir: tmpDir,
  35. logFile: tmpFile,
  36. interval: 600 * time.Second,
  37. env: map[string]string{
  38. "TEST_CONTENT": expectedOutput,
  39. },
  40. }
  41. cmdScriptContent := `#!/bin/sh
  42. echo ${TEST_CONTENT}
  43. sleep 10
  44. `
  45. err = ioutil.WriteFile(cmdScript, []byte(cmdScriptContent), 0755)
  46. So(err, ShouldBeNil)
  47. provider, err := newCmdProvider(c)
  48. So(err, ShouldBeNil)
  49. d := &dockerHook{
  50. emptyHook: emptyHook{
  51. provider: provider,
  52. },
  53. image: "alpine",
  54. volumes: []string{
  55. fmt.Sprintf("%s:%s", cmdScript, "/bin/cmd.sh"),
  56. },
  57. }
  58. provider.AddHook(d)
  59. So(provider.Docker(), ShouldNotBeNil)
  60. err = d.preExec()
  61. So(err, ShouldBeNil)
  62. go func() {
  63. err = provider.Run()
  64. ctx.So(err, ShouldNotBeNil)
  65. }()
  66. time.Sleep(1 * time.Second)
  67. // assert container running
  68. names, err := getDockerByName(d.Name())
  69. So(err, ShouldBeNil)
  70. So(names, ShouldEqual, d.Name()+"\n")
  71. err = provider.Terminate()
  72. So(err, ShouldBeNil)
  73. // container should be terminated and removed
  74. names, err = getDockerByName(d.Name())
  75. So(err, ShouldBeNil)
  76. So(names, ShouldEqual, "")
  77. // check log content
  78. loggedContent, err := ioutil.ReadFile(provider.LogFile())
  79. So(err, ShouldBeNil)
  80. So(string(loggedContent), ShouldEqual, expectedOutput+"\n")
  81. d.postExec()
  82. })
  83. }