utils_test.go 9.5 KB

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