utils_test.go 9.5 KB

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