utils_test.go 9.7 KB

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