summaryrefslogtreecommitdiff
path: root/integration/utils_test.go
blob: 8ad6ccb1238ccd2310337f081a3793d9789b6097 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package docker

import (
	"bytes"
	"fmt"
	"github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"path"
	"strings"
	"testing"
	"time"

	"github.com/dotcloud/docker/builtins"
	"github.com/dotcloud/docker/engine"
	"github.com/dotcloud/docker/runconfig"
	"github.com/dotcloud/docker/runtime"
	"github.com/dotcloud/docker/server"
	"github.com/dotcloud/docker/utils"
)

// This file contains utility functions for docker's unit test suite.
// It has to be named XXX_test.go, apparently, in other to access private functions
// from other XXX_test.go functions.

// Create a temporary runtime suitable for unit testing.
// Call t.Fatal() at the first error.
func mkRuntime(f utils.Fataler) *runtime.Runtime {
	eng := newTestEngine(f, false, "")
	return mkRuntimeFromEngine(eng, f)
	// FIXME:
	// [...]
	// Mtu:         docker.GetDefaultNetworkMtu(),
	// [...]
}

func createNamedTestContainer(eng *engine.Engine, config *runconfig.Config, f utils.Fataler, name string) (shortId string) {
	job := eng.Job("create", name)
	if err := job.ImportEnv(config); err != nil {
		f.Fatal(err)
	}
	job.Stdout.AddString(&shortId)
	if err := job.Run(); err != nil {
		f.Fatal(err)
	}
	return
}

func createTestContainer(eng *engine.Engine, config *runconfig.Config, f utils.Fataler) (shortId string) {
	return createNamedTestContainer(eng, config, f, "")
}

func startContainer(eng *engine.Engine, id string, t utils.Fataler) {
	job := eng.Job("start", id)
	if err := job.Run(); err != nil {
		t.Fatal(err)
	}
}

func containerRun(eng *engine.Engine, id string, t utils.Fataler) {
	startContainer(eng, id, t)
	containerWait(eng, id, t)
}

func containerFileExists(eng *engine.Engine, id, dir string, t utils.Fataler) bool {
	c := getContainer(eng, id, t)
	if err := c.Mount(); err != nil {
		t.Fatal(err)
	}
	defer c.Unmount()
	if _, err := os.Stat(path.Join(c.RootfsPath(), dir)); err != nil {
		if os.IsNotExist(err) {
			return false
		}
		t.Fatal(err)
	}
	return true
}

func containerAttach(eng *engine.Engine, id string, t utils.Fataler) (io.WriteCloser, io.ReadCloser) {
	c := getContainer(eng, id, t)
	i, err := c.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	o, err := c.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	return i, o
}

func containerWait(eng *engine.Engine, id string, t utils.Fataler) int {
	return getContainer(eng, id, t).Wait()
}

func containerWaitTimeout(eng *engine.Engine, id string, t utils.Fataler) error {
	return getContainer(eng, id, t).WaitTimeout(500 * time.Millisecond)
}

func containerKill(eng *engine.Engine, id string, t utils.Fataler) {
	if err := eng.Job("kill", id).Run(); err != nil {
		t.Fatal(err)
	}
}

func containerRunning(eng *engine.Engine, id string, t utils.Fataler) bool {
	return getContainer(eng, id, t).State.IsRunning()
}

func containerAssertExists(eng *engine.Engine, id string, t utils.Fataler) {
	getContainer(eng, id, t)
}

func containerAssertNotExists(eng *engine.Engine, id string, t utils.Fataler) {
	runtime := mkRuntimeFromEngine(eng, t)
	if c := runtime.Get(id); c != nil {
		t.Fatal(fmt.Errorf("Container %s should not exist", id))
	}
}

// assertHttpNotError expect the given response to not have an error.
// Otherwise the it causes the test to fail.
func assertHttpNotError(r *httptest.ResponseRecorder, t utils.Fataler) {
	// Non-error http status are [200, 400)
	if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest {
		t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code))
	}
}

// assertHttpError expect the given response to have an error.
// Otherwise the it causes the test to fail.
func assertHttpError(r *httptest.ResponseRecorder, t utils.Fataler) {
	// Non-error http status are [200, 400)
	if !(r.Code < http.StatusOK || r.Code >= http.StatusBadRequest) {
		t.Fatal(fmt.Errorf("Unexpected http success code: %v", r.Code))
	}
}

func getContainer(eng *engine.Engine, id string, t utils.Fataler) *runtime.Container {
	runtime := mkRuntimeFromEngine(eng, t)
	c := runtime.Get(id)
	if c == nil {
		t.Fatal(fmt.Errorf("No such container: %s", id))
	}
	return c
}

func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *server.Server {
	iSrv := eng.Hack_GetGlobalVar("httpapi.server")
	if iSrv == nil {
		panic("Legacy server field not set in engine")
	}
	srv, ok := iSrv.(*server.Server)
	if !ok {
		panic("Legacy server field in engine does not cast to *server.Server")
	}
	return srv
}

func mkRuntimeFromEngine(eng *engine.Engine, t utils.Fataler) *runtime.Runtime {
	iRuntime := eng.Hack_GetGlobalVar("httpapi.runtime")
	if iRuntime == nil {
		panic("Legacy runtime field not set in engine")
	}
	runtime, ok := iRuntime.(*runtime.Runtime)
	if !ok {
		panic("Legacy runtime field in engine does not cast to *runtime.Runtime")
	}
	return runtime
}

func newTestEngine(t utils.Fataler, autorestart bool, root string) *engine.Engine {
	if root == "" {
		if dir, err := newTestDirectory(unitTestStoreBase); err != nil {
			t.Fatal(err)
		} else {
			root = dir
		}
	}
	eng, err := engine.New(root)
	if err != nil {
		t.Fatal(err)
	}
	// Load default plugins
	builtins.Register(eng)
	// (This is manually copied and modified from main() until we have a more generic plugin system)
	job := eng.Job("initserver")
	job.Setenv("Root", root)
	job.SetenvBool("AutoRestart", autorestart)
	job.Setenv("ExecDriver", "native")
	// TestGetEnabledCors and TestOptionsRoute require EnableCors=true
	job.SetenvBool("EnableCors", true)
	if err := job.Run(); err != nil {
		t.Fatal(err)
	}
	return eng
}

func NewTestEngine(t utils.Fataler) *engine.Engine {
	return newTestEngine(t, false, "")
}

func newTestDirectory(templateDir string) (dir string, err error) {
	return utils.TestDirectory(templateDir)
}

func getCallerName(depth int) string {
	return utils.GetCallerName(depth)
}

// Write `content` to the file at path `dst`, creating it if necessary,
// as well as any missing directories.
// The file is truncated if it already exists.
// Call t.Fatal() at the first error.
func writeFile(dst, content string, t *testing.T) {
	// Create subdirectories if necessary
	if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) {
		t.Fatal(err)
	}
	f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700)
	if err != nil {
		t.Fatal(err)
	}
	// Write content (truncate if it exists)
	if _, err := io.Copy(f, strings.NewReader(content)); err != nil {
		t.Fatal(err)
	}
}

// Return the contents of file at path `src`.
// Call t.Fatal() at the first error (including if the file doesn't exist)
func readFile(src string, t *testing.T) (content string) {
	f, err := os.Open(src)
	if err != nil {
		t.Fatal(err)
	}
	data, err := ioutil.ReadAll(f)
	if err != nil {
		t.Fatal(err)
	}
	return string(data)
}

// Create a test container from the given runtime `r` and run arguments `args`.
// If the image name is "_", (eg. []string{"-i", "-t", "_", "bash"}, it is
// dynamically replaced by the current test image.
// The caller is responsible for destroying the container.
// Call t.Fatal() at the first error.
func mkContainer(r *runtime.Runtime, args []string, t *testing.T) (*runtime.Container, *runconfig.HostConfig, error) {
	config, hc, _, err := runconfig.Parse(args, nil)
	defer func() {
		if err != nil && t != nil {
			t.Fatal(err)
		}
	}()
	if err != nil {
		return nil, nil, err
	}
	if config.Image == "_" {
		config.Image = GetTestImage(r).ID
	}
	c, _, err := r.Create(config, "")
	if err != nil {
		return nil, nil, err
	}
	// NOTE: hostConfig is ignored.
	// If `args` specify privileged mode, custom lxc conf, external mount binds,
	// port redirects etc. they will be ignored.
	// This is because the correct way to set these things is to pass environment
	// to the `start` job.
	// FIXME: this helper function should be deprecated in favor of calling
	// `create` and `start` jobs directly.
	return c, hc, nil
}

// Create a test container, start it, wait for it to complete, destroy it,
// and return its standard output as a string.
// The image name (eg. the XXX in []string{"-i", "-t", "XXX", "bash"}, is dynamically replaced by the current test image.
// If t is not nil, call t.Fatal() at the first error. Otherwise return errors normally.
func runContainer(eng *engine.Engine, r *runtime.Runtime, args []string, t *testing.T) (output string, err error) {
	defer func() {
		if err != nil && t != nil {
			t.Fatal(err)
		}
	}()
	container, hc, err := mkContainer(r, args, t)
	if err != nil {
		return "", err
	}
	defer r.Destroy(container)
	stdout, err := container.StdoutPipe()
	if err != nil {
		return "", err
	}
	defer stdout.Close()

	job := eng.Job("start", container.ID)
	if err := job.ImportEnv(hc); err != nil {
		return "", err
	}
	if err := job.Run(); err != nil {
		return "", err
	}

	container.Wait()
	data, err := ioutil.ReadAll(stdout)
	if err != nil {
		return "", err
	}
	output = string(data)
	return
}

// FIXME: this is duplicated from graph_test.go in the docker package.
func fakeTar() (io.ReadCloser, error) {
	content := []byte("Hello world!\n")
	buf := new(bytes.Buffer)
	tw := tar.NewWriter(buf)
	for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} {
		hdr := new(tar.Header)
		hdr.Size = int64(len(content))
		hdr.Name = name
		if err := tw.WriteHeader(hdr); err != nil {
			return nil, err
		}
		tw.Write([]byte(content))
	}
	tw.Close()
	return ioutil.NopCloser(buf), nil
}

func getAllImages(eng *engine.Engine, t *testing.T) *engine.Table {
	return getImages(eng, t, true, "")
}

func getImages(eng *engine.Engine, t *testing.T, all bool, filter string) *engine.Table {
	job := eng.Job("images")
	job.SetenvBool("all", all)
	job.Setenv("filter", filter)
	images, err := job.Stdout.AddListTable()
	if err != nil {
		t.Fatal(err)
	}
	if err := job.Run(); err != nil {
		t.Fatal(err)
	}
	return images

}