utils_test.go 9.4 KB

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