utils_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. "path/filepath"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  16. "github.com/docker/docker/builtins"
  17. "github.com/docker/docker/daemon"
  18. "github.com/docker/docker/engine"
  19. flag "github.com/docker/docker/pkg/mflag"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/docker/utils"
  22. )
  23. type Fataler interface {
  24. Fatal(...interface{})
  25. }
  26. // This file contains utility functions for docker's unit test suite.
  27. // It has to be named XXX_test.go, apparently, in other to access private functions
  28. // from other XXX_test.go functions.
  29. // Create a temporary daemon suitable for unit testing.
  30. // Call t.Fatal() at the first error.
  31. func mkDaemon(f Fataler) *daemon.Daemon {
  32. eng := newTestEngine(f, false, "")
  33. return mkDaemonFromEngine(eng, f)
  34. }
  35. func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f 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 Fataler) (shortId string) {
  48. return createNamedTestContainer(eng, config, f, "")
  49. }
  50. func startContainer(eng *engine.Engine, id string, t 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 Fataler) {
  57. startContainer(eng, id, t)
  58. containerWait(eng, id, t)
  59. }
  60. func containerFileExists(eng *engine.Engine, id, dir string, t 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 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 Fataler) int {
  87. ex, _ := getContainer(eng, id, t).WaitStop(-1 * time.Second)
  88. return ex
  89. }
  90. func containerWaitTimeout(eng *engine.Engine, id string, t Fataler) error {
  91. _, err := getContainer(eng, id, t).WaitStop(500 * time.Millisecond)
  92. return err
  93. }
  94. func containerKill(eng *engine.Engine, id string, t Fataler) {
  95. if err := eng.Job("kill", id).Run(); err != nil {
  96. t.Fatal(err)
  97. }
  98. }
  99. func containerRunning(eng *engine.Engine, id string, t Fataler) bool {
  100. return getContainer(eng, id, t).IsRunning()
  101. }
  102. func containerAssertExists(eng *engine.Engine, id string, t Fataler) {
  103. getContainer(eng, id, t)
  104. }
  105. func containerAssertNotExists(eng *engine.Engine, id string, t Fataler) {
  106. daemon := mkDaemonFromEngine(eng, t)
  107. if c := daemon.Get(id); c != nil {
  108. t.Fatal(fmt.Errorf("Container %s should not exist", id))
  109. }
  110. }
  111. // assertHttpNotError expect the given response to not have an error.
  112. // Otherwise the it causes the test to fail.
  113. func assertHttpNotError(r *httptest.ResponseRecorder, t Fataler) {
  114. // Non-error http status are [200, 400)
  115. if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest {
  116. t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code))
  117. }
  118. }
  119. // assertHttpError expect the given response to have an error.
  120. // Otherwise the it causes the test to fail.
  121. func assertHttpError(r *httptest.ResponseRecorder, t Fataler) {
  122. // Non-error http status are [200, 400)
  123. if !(r.Code < http.StatusOK || r.Code >= http.StatusBadRequest) {
  124. t.Fatal(fmt.Errorf("Unexpected http success code: %v", r.Code))
  125. }
  126. }
  127. func getContainer(eng *engine.Engine, id string, t Fataler) *daemon.Container {
  128. daemon := mkDaemonFromEngine(eng, t)
  129. c := daemon.Get(id)
  130. if c == nil {
  131. t.Fatal(fmt.Errorf("No such container: %s", id))
  132. }
  133. return c
  134. }
  135. func mkDaemonFromEngine(eng *engine.Engine, t Fataler) *daemon.Daemon {
  136. iDaemon := eng.Hack_GetGlobalVar("httpapi.daemon")
  137. if iDaemon == nil {
  138. panic("Legacy daemon field not set in engine")
  139. }
  140. daemon, ok := iDaemon.(*daemon.Daemon)
  141. if !ok {
  142. panic("Legacy daemon field in engine does not cast to *daemon.Daemon")
  143. }
  144. return daemon
  145. }
  146. func newTestEngine(t Fataler, autorestart bool, root string) *engine.Engine {
  147. if root == "" {
  148. if dir, err := newTestDirectory(unitTestStoreBase); err != nil {
  149. t.Fatal(err)
  150. } else {
  151. root = dir
  152. }
  153. }
  154. os.MkdirAll(root, 0700)
  155. eng := engine.New()
  156. eng.Logging = false
  157. // Load default plugins
  158. builtins.Register(eng)
  159. // (This is manually copied and modified from main() until we have a more generic plugin system)
  160. cfg := &daemon.Config{
  161. Root: root,
  162. AutoRestart: autorestart,
  163. ExecDriver: "native",
  164. // Either InterContainerCommunication or EnableIptables must be set,
  165. // otherwise NewDaemon will fail because of conflicting settings.
  166. InterContainerCommunication: true,
  167. TrustKeyPath: filepath.Join(root, "key.json"),
  168. }
  169. d, err := daemon.NewDaemon(cfg, eng)
  170. if err != nil {
  171. t.Fatal(err)
  172. }
  173. if err := d.Install(eng); err != nil {
  174. t.Fatal(err)
  175. }
  176. return eng
  177. }
  178. func NewTestEngine(t 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 daemon `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 *daemon.Daemon, args []string, t *testing.T) (*daemon.Container, *runconfig.HostConfig, error) {
  224. config, hc, _, err := parseRun(args)
  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, nil, "")
  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 *daemon.Daemon, 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.WaitStop(-1 * time.Second)
  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. }
  317. func parseRun(args []string) (*runconfig.Config, *runconfig.HostConfig, *flag.FlagSet, error) {
  318. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  319. cmd.SetOutput(ioutil.Discard)
  320. cmd.Usage = nil
  321. return runconfig.Parse(cmd, args)
  322. }