utils_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "github.com/dotcloud/docker"
  7. "github.com/dotcloud/docker/engine"
  8. "github.com/dotcloud/docker/utils"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/http/httptest"
  13. "os"
  14. "path"
  15. "strings"
  16. "testing"
  17. "time"
  18. )
  19. // This file contains utility functions for docker's unit test suite.
  20. // It has to be named XXX_test.go, apparently, in other to access private functions
  21. // from other XXX_test.go functions.
  22. // Create a temporary runtime suitable for unit testing.
  23. // Call t.Fatal() at the first error.
  24. func mkRuntime(f utils.Fataler) *docker.Runtime {
  25. root, err := newTestDirectory(unitTestStoreBase)
  26. if err != nil {
  27. f.Fatal(err)
  28. }
  29. config := &docker.DaemonConfig{
  30. Root: root,
  31. AutoRestart: false,
  32. }
  33. r, err := docker.NewRuntimeFromDirectory(config)
  34. if err != nil {
  35. f.Fatal(err)
  36. }
  37. r.UpdateCapabilities(true)
  38. return r
  39. }
  40. func createNamedTestContainer(eng *engine.Engine, config *docker.Config, f utils.Fataler, name string) (shortId string) {
  41. job := eng.Job("create", name)
  42. if err := job.ImportEnv(config); err != nil {
  43. f.Fatal(err)
  44. }
  45. job.StdoutParseString(&shortId)
  46. if err := job.Run(); err != nil {
  47. f.Fatal(err)
  48. }
  49. return
  50. }
  51. func createTestContainer(eng *engine.Engine, config *docker.Config, f utils.Fataler) (shortId string) {
  52. return createNamedTestContainer(eng, config, f, "")
  53. }
  54. func startContainer(eng *engine.Engine, id string, t utils.Fataler) {
  55. job := eng.Job("start", id)
  56. if err := job.Run(); err != nil {
  57. t.Fatal(err)
  58. }
  59. }
  60. func containerRun(eng *engine.Engine, id string, t utils.Fataler) {
  61. startContainer(eng, id, t)
  62. containerWait(eng, id, t)
  63. }
  64. func containerFileExists(eng *engine.Engine, id, dir string, t utils.Fataler) bool {
  65. c := getContainer(eng, id, t)
  66. if err := c.EnsureMounted(); err != nil {
  67. t.Fatal(err)
  68. }
  69. if _, err := os.Stat(path.Join(c.RootfsPath(), dir)); err != nil {
  70. if os.IsNotExist(err) {
  71. return false
  72. }
  73. t.Fatal(err)
  74. }
  75. return true
  76. }
  77. func containerAttach(eng *engine.Engine, id string, t utils.Fataler) (io.WriteCloser, io.ReadCloser) {
  78. c := getContainer(eng, id, t)
  79. i, err := c.StdinPipe()
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. o, err := c.StdoutPipe()
  84. if err != nil {
  85. t.Fatal(err)
  86. }
  87. return i, o
  88. }
  89. func containerWait(eng *engine.Engine, id string, t utils.Fataler) int {
  90. return getContainer(eng, id, t).Wait()
  91. }
  92. func containerWaitTimeout(eng *engine.Engine, id string, t utils.Fataler) error {
  93. return getContainer(eng, id, t).WaitTimeout(500 * time.Millisecond)
  94. }
  95. func containerKill(eng *engine.Engine, id string, t utils.Fataler) {
  96. if err := getContainer(eng, id, t).Kill(); err != nil {
  97. t.Fatal(err)
  98. }
  99. }
  100. func containerRunning(eng *engine.Engine, id string, t utils.Fataler) bool {
  101. return getContainer(eng, id, t).State.IsRunning()
  102. }
  103. func containerAssertExists(eng *engine.Engine, id string, t utils.Fataler) {
  104. getContainer(eng, id, t)
  105. }
  106. func containerAssertNotExists(eng *engine.Engine, id string, t utils.Fataler) {
  107. runtime := mkRuntimeFromEngine(eng, t)
  108. if c := runtime.Get(id); c != nil {
  109. t.Fatal(fmt.Errorf("Container %s should not exist", id))
  110. }
  111. }
  112. // assertHttpNotError expect the given response to not have an error.
  113. // Otherwise the it causes the test to fail.
  114. func assertHttpNotError(r *httptest.ResponseRecorder, t utils.Fataler) {
  115. // Non-error http status are [200, 400)
  116. if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest {
  117. t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code))
  118. }
  119. }
  120. // assertHttpError expect the given response to have an error.
  121. // Otherwise the it causes the test to fail.
  122. func assertHttpError(r *httptest.ResponseRecorder, t utils.Fataler) {
  123. // Non-error http status are [200, 400)
  124. if !(r.Code < http.StatusOK || r.Code >= http.StatusBadRequest) {
  125. t.Fatal(fmt.Errorf("Unexpected http success code: %v", r.Code))
  126. }
  127. }
  128. func getContainer(eng *engine.Engine, id string, t utils.Fataler) *docker.Container {
  129. runtime := mkRuntimeFromEngine(eng, t)
  130. c := runtime.Get(id)
  131. if c == nil {
  132. t.Fatal(fmt.Errorf("No such container: %s", id))
  133. }
  134. return c
  135. }
  136. func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Server {
  137. iSrv := eng.Hack_GetGlobalVar("httpapi.server")
  138. if iSrv == nil {
  139. panic("Legacy server field not set in engine")
  140. }
  141. srv, ok := iSrv.(*docker.Server)
  142. if !ok {
  143. panic("Legacy server field in engine does not cast to *docker.Server")
  144. }
  145. return srv
  146. }
  147. func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *docker.Runtime {
  148. iRuntime := eng.Hack_GetGlobalVar("httpapi.runtime")
  149. if iRuntime == nil {
  150. panic("Legacy runtime field not set in engine")
  151. }
  152. runtime, ok := iRuntime.(*docker.Runtime)
  153. if !ok {
  154. panic("Legacy runtime field in engine does not cast to *docker.Runtime")
  155. }
  156. return runtime
  157. }
  158. func NewTestEngine(t utils.Fataler) *engine.Engine {
  159. root, err := newTestDirectory(unitTestStoreBase)
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. eng, err := engine.New(root)
  164. if err != nil {
  165. t.Fatal(err)
  166. }
  167. // Load default plugins
  168. // (This is manually copied and modified from main() until we have a more generic plugin system)
  169. job := eng.Job("initapi")
  170. job.Setenv("Root", root)
  171. job.SetenvBool("AutoRestart", false)
  172. // TestGetEnabledCors and TestOptionsRoute require EnableCors=true
  173. job.SetenvBool("EnableCors", true)
  174. if err := job.Run(); err != nil {
  175. t.Fatal(err)
  176. }
  177. return eng
  178. }
  179. func newTestDirectory(templateDir string) (dir string, err error) {
  180. return utils.TestDirectory(templateDir)
  181. }
  182. func getCallerName(depth int) string {
  183. return utils.GetCallerName(depth)
  184. }
  185. // Write `content` to the file at path `dst`, creating it if necessary,
  186. // as well as any missing directories.
  187. // The file is truncated if it already exists.
  188. // Call t.Fatal() at the first error.
  189. func writeFile(dst, content string, t *testing.T) {
  190. // Create subdirectories if necessary
  191. if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  192. t.Fatal(err)
  193. }
  194. f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
  195. if err != nil {
  196. t.Fatal(err)
  197. }
  198. // Write content (truncate if it exists)
  199. if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
  200. t.Fatal(err)
  201. }
  202. }
  203. // Return the contents of file at path `src`.
  204. // Call t.Fatal() at the first error (including if the file doesn't exist)
  205. func readFile(src string, t *testing.T) (content string) {
  206. f, err := os.Open(src)
  207. if err != nil {
  208. t.Fatal(err)
  209. }
  210. data, err := ioutil.ReadAll(f)
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. return string(data)
  215. }
  216. // Create a test container from the given runtime `r` and run arguments `args`.
  217. // If the image name is "_", (eg. []string{"-i", "-t", "_", "bash"}, it is
  218. // dynamically replaced by the current test image.
  219. // The caller is responsible for destroying the container.
  220. // Call t.Fatal() at the first error.
  221. func mkContainer(r *docker.Runtime, args []string, t *testing.T) (*docker.Container, *docker.HostConfig, error) {
  222. config, hc, _, err := docker.ParseRun(args, nil)
  223. defer func() {
  224. if err != nil && t != nil {
  225. t.Fatal(err)
  226. }
  227. }()
  228. if err != nil {
  229. return nil, nil, err
  230. }
  231. if config.Image == "_" {
  232. config.Image = GetTestImage(r).ID
  233. }
  234. c, _, err := r.Create(config, "")
  235. if err != nil {
  236. return nil, nil, err
  237. }
  238. // NOTE: hostConfig is ignored.
  239. // If `args` specify privileged mode, custom lxc conf, external mount binds,
  240. // port redirects etc. they will be ignored.
  241. // This is because the correct way to set these things is to pass environment
  242. // to the `start` job.
  243. // FIXME: this helper function should be deprecated in favor of calling
  244. // `create` and `start` jobs directly.
  245. return c, hc, nil
  246. }
  247. // Create a test container, start it, wait for it to complete, destroy it,
  248. // and return its standard output as a string.
  249. // The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image.
  250. // If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally.
  251. func runContainer(eng *engine.Engine, r *docker.Runtime, args []string, t *testing.T) (output string, err error) {
  252. defer func() {
  253. if err != nil && t != nil {
  254. t.Fatal(err)
  255. }
  256. }()
  257. container, hc, err := mkContainer(r, args, t)
  258. if err != nil {
  259. return "", err
  260. }
  261. defer r.Destroy(container)
  262. stdout, err := container.StdoutPipe()
  263. if err != nil {
  264. return "", err
  265. }
  266. defer stdout.Close()
  267. job := eng.Job("start", container.ID)
  268. if err := job.ImportEnv(hc); err != nil {
  269. return "", err
  270. }
  271. if err := job.Run(); err != nil {
  272. return "", err
  273. }
  274. container.Wait()
  275. data, err := ioutil.ReadAll(stdout)
  276. if err != nil {
  277. return "", err
  278. }
  279. output = string(data)
  280. return
  281. }
  282. // FIXME: this is duplicated from graph_test.go in the docker package.
  283. func fakeTar() (io.Reader, error) {
  284. content := []byte("Hello world!\n")
  285. buf := new(bytes.Buffer)
  286. tw := tar.NewWriter(buf)
  287. for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} {
  288. hdr := new(tar.Header)
  289. hdr.Size = int64(len(content))
  290. hdr.Name = name
  291. if err := tw.WriteHeader(hdr); err != nil {
  292. return nil, err
  293. }
  294. tw.Write([]byte(content))
  295. }
  296. tw.Close()
  297. return buf, nil
  298. }