docker_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. provider: provider,
  51. image: "alpine",
  52. volumes: []string{
  53. fmt.Sprintf("%s:%s", cmdScript, "/bin/cmd.sh"),
  54. },
  55. }
  56. provider.AddHook(d)
  57. So(provider.Docker(), ShouldNotBeNil)
  58. err = d.preExec()
  59. So(err, ShouldBeNil)
  60. go func() {
  61. err = provider.Run()
  62. ctx.So(err, ShouldNotBeNil)
  63. }()
  64. time.Sleep(1 * time.Second)
  65. // assert container running
  66. names, err := getDockerByName(d.Name())
  67. So(err, ShouldBeNil)
  68. So(names, ShouldEqual, d.Name()+"\n")
  69. err = provider.Terminate()
  70. So(err, ShouldBeNil)
  71. // container should be terminated and removed
  72. names, err = getDockerByName(d.Name())
  73. So(err, ShouldBeNil)
  74. So(names, ShouldEqual, "")
  75. // check log content
  76. loggedContent, err := ioutil.ReadFile(provider.LogFile())
  77. So(err, ShouldBeNil)
  78. So(string(loggedContent), ShouldEqual, expectedOutput+"\n")
  79. d.postExec()
  80. })
  81. }