docker_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. if err == nil {
  20. logger.Debugf("docker ps: '%s'", string(out))
  21. }
  22. return string(out), err
  23. }
  24. func TestDocker(t *testing.T) {
  25. Convey("Docker Should Work", t, func(ctx C) {
  26. tmpDir, err := ioutil.TempDir("", "tunasync")
  27. defer os.RemoveAll(tmpDir)
  28. So(err, ShouldBeNil)
  29. cmdScript := filepath.Join(tmpDir, "cmd.sh")
  30. tmpFile := filepath.Join(tmpDir, "log_file")
  31. expectedOutput := "HELLO_WORLD"
  32. c := cmdConfig{
  33. name: "tuna-docker",
  34. upstreamURL: "http://mirrors.tuna.moe/",
  35. command: "/bin/cmd.sh",
  36. workingDir: tmpDir,
  37. logDir: tmpDir,
  38. logFile: tmpFile,
  39. interval: 600 * time.Second,
  40. env: map[string]string{
  41. "TEST_CONTENT": expectedOutput,
  42. },
  43. }
  44. cmdScriptContent := `#!/bin/sh
  45. echo ${TEST_CONTENT}
  46. sleep 10
  47. `
  48. err = ioutil.WriteFile(cmdScript, []byte(cmdScriptContent), 0755)
  49. So(err, ShouldBeNil)
  50. provider, err := newCmdProvider(c)
  51. So(err, ShouldBeNil)
  52. d := &dockerHook{
  53. emptyHook: emptyHook{
  54. provider: provider,
  55. },
  56. image: "alpine",
  57. volumes: []string{
  58. fmt.Sprintf("%s:%s", cmdScript, "/bin/cmd.sh"),
  59. },
  60. }
  61. provider.AddHook(d)
  62. So(provider.Docker(), ShouldNotBeNil)
  63. err = d.preExec()
  64. So(err, ShouldBeNil)
  65. go func() {
  66. err = provider.Run()
  67. ctx.So(err, ShouldNotBeNil)
  68. }()
  69. // Wait for docker running
  70. time.Sleep(5 * time.Second)
  71. // assert container running
  72. names, err := getDockerByName(d.Name())
  73. So(err, ShouldBeNil)
  74. So(names, ShouldEqual, d.Name()+"\n")
  75. err = provider.Terminate()
  76. So(err, ShouldBeNil)
  77. // container should be terminated and removed
  78. names, err = getDockerByName(d.Name())
  79. So(err, ShouldBeNil)
  80. So(names, ShouldEqual, "")
  81. // check log content
  82. loggedContent, err := ioutil.ReadFile(provider.LogFile())
  83. So(err, ShouldBeNil)
  84. So(string(loggedContent), ShouldEqual, expectedOutput+"\n")
  85. d.postExec()
  86. })
  87. }