utils_test.go 9.5 KB

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