utils_test.go 9.3 KB

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