-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
testcommon.go
394 lines (345 loc) · 12.7 KB
/
testcommon.go
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package testcommon
import (
"crypto/tls"
"github.com/drud/ddev/pkg/ddevapp"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/drud/ddev/pkg/output"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"time"
log "github.com/sirupsen/logrus"
"path"
"fmt"
"github.com/drud/ddev/pkg/archive"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/util"
"github.com/pkg/errors"
asrt "github.com/stretchr/testify/assert"
"net/http"
"net/url"
"testing"
)
// URIWithExpect pairs a URI like "/readme.html" with some substring content "should be found in URI"
type URIWithExpect struct {
URI string
Expect string
}
// TestSite describes a site for testing, with name, URL of tarball, and optional dir.
type TestSite struct {
// Name is the generic name of the site, and is used as the default dir.
Name string
// SourceURL is the URL of the source code tarball to be used for building the site.
SourceURL string
// ArchiveExtractionPath is the relative path within the tarball which should be extracted, ending with /
ArchiveInternalExtractionPath string
// FullSiteTarballURL is the URL of the tarball of a full site archive used for testing import.
FullSiteTarballURL string
// FilesTarballURL is the URL of the tarball of file uploads used for testing file import.
FilesTarballURL string
// FilesZipballURL is the URL of the zipball of file uploads used for testing file import.
FilesZipballURL string
// DBTarURL is the URL of the database dump tarball used for testing database import.
DBTarURL string
// DBZipURL is the URL of an optional zip-style db dump.
DBZipURL string
// Dir is the rooted full path of the test site
Dir string
// HTTPProbeURI is the URI that can be probed to look for a working web container
HTTPProbeURI string
// Docroot is the subdirectory witin the site that is the root/index.php
Docroot string
// Type is the type of application. This can be specified when a config file is not present
// for a test site.
Type string
// Safe200URIWithExpectation provides a static URI with contents that it can be expected to contain.
Safe200URIWithExpectation URIWithExpect
// DynamicURI provides a dynamic (after db load) URI with contents we can expect.
DynamicURI URIWithExpect
// FilesImageURI is URI to a file loaded by import-files that is a jpg.
FilesImageURI string
// FullSiteArchiveExtPath is the path that should be extracted from inside an archive when
// importing the files from a full site archive
FullSiteArchiveExtPath string
}
// Prepare downloads and extracts a site codebase to a temporary directory.
func (site *TestSite) Prepare() error {
testDir := CreateTmpDir(site.Name)
site.Dir = testDir
err := os.Setenv("DRUD_NONINTERACTIVE", "true")
util.CheckErr(err)
cachedSrcDir, _, err := GetCachedArchive(site.Name, site.Name+"_siteArchive", site.ArchiveInternalExtractionPath, site.SourceURL)
if err != nil {
site.Cleanup()
return fmt.Errorf("Failed to GetCachedArchive, err=%v", err)
}
// We must copy into a directory that does not yet exist :(
err = os.Remove(site.Dir)
util.CheckErr(err)
err = fileutil.CopyDir(cachedSrcDir, site.Dir)
if err != nil {
site.Cleanup()
return fmt.Errorf("Failed to CopyDir from %s to %s, err=%v", cachedSrcDir, site.Dir, err)
}
// Create an app. Err is ignored as we may not have
// a config file to read in from a test site.
app, _ := ddevapp.NewApp(site.Dir, "")
// Set app name to the name we define for test sites. We'll
// ignore app name defined in config file if present.
app.Name = site.Name
app.Docroot = site.Docroot
app.Type = app.DetectAppType()
if app.Type != site.Type {
return errors.Errorf("Detected apptype does not match provided apptype")
}
err = app.ConfigFileOverrideAction()
util.CheckErr(err)
err = app.WriteConfig()
if err != nil {
return errors.Errorf("Failed to write site config for site %s, dir %s, err: %v", site.Name, site.Dir, err)
}
return nil
}
// Chdir will change to the directory for the site specified by TestSite.
func (site *TestSite) Chdir() func() {
return Chdir(site.Dir)
}
// Cleanup removes the archive and codebase extraction for a site after a test run has completed.
func (site *TestSite) Cleanup() {
// CleanupDir checks its own errors.
CleanupDir(site.Dir)
siteData := filepath.Join(globalconfig.GetGlobalDdevDir(), site.Name)
if fileutil.FileExists(siteData) {
CleanupDir(siteData)
}
}
// CleanupDir removes a directory specified by string.
func CleanupDir(dir string) {
err := os.RemoveAll(dir)
if err != nil {
log.Warn(fmt.Sprintf("Failed to remove directory %s, err: %v", dir, err))
}
}
// OsTempDir gets os.TempDir() (usually provided by $TMPDIR) but expands any symlinks found within it.
// This wrapper function can prevent problems with docker-for-mac trying to use /var/..., which is not typically
// shared/mounted. It will be expanded via the /var symlink to /private/var/...
func OsTempDir() (string, error) {
dirName := os.TempDir()
tmpDir, err := filepath.EvalSymlinks(dirName)
if err != nil {
return "", err
}
tmpDir = filepath.Clean(tmpDir)
return tmpDir, nil
}
// CreateTmpDir creates a temporary directory and returns its path as a string.
func CreateTmpDir(prefix string) string {
systemTempDir, err := OsTempDir()
if err != nil {
log.Fatalln("Failed getting system temp dir", err)
}
fullPath, err := ioutil.TempDir(systemTempDir, prefix)
if err != nil {
log.Fatalln("Failed to create temp directory, err=", err)
}
return fullPath
}
// Chdir will change to the directory for the site specified by TestSite.
// It returns an anonymous function which will return to the original working directory when called.
func Chdir(path string) func() {
curDir, _ := os.Getwd()
err := os.Chdir(path)
if err != nil {
log.Errorf("Could not change to directory %s: %v\n", path, err)
}
return func() {
err := os.Chdir(curDir)
if err != nil {
log.Errorf("Failed to change directory to original dir=%s, err=%v", curDir, err)
}
}
}
// ClearDockerEnv unsets env vars set in platform DockerEnv() so that
// they can be set by another test run.
func ClearDockerEnv() {
envVars := []string{
"COMPOSE_PROJECT_NAME",
"COMPOSE_CONVERT_WINDOWS_PATHS",
"DDEV_SITENAME",
"DDEV_DBIMAGE",
"DDEV_WEBIMAGE",
"DDEV_BGSYNCIMAGE",
"DDEV_APPROOT",
"DDEV_DOCROOT",
"DDEV_URL",
"DDEV_HOSTNAME",
"DDEV_PHP_VERSION",
"DDEV_PROJECT_TYPE",
"DDEV_ROUTER_HTTP_PORT",
"DDEV_ROUTER_HTTPS_PORT",
"COLUMNS",
"LINES",
"DDEV_XDEBUG_ENABLED",
}
for _, env := range envVars {
err := os.Unsetenv(env)
if err != nil {
log.Printf("failed to unset %s: %v\n", env, err)
}
}
}
// ContainerCheck determines if a given container name exists and matches a given state
func ContainerCheck(checkName string, checkState string) (bool, error) {
// ensure we have docker network
client := dockerutil.GetDockerClient()
err := dockerutil.EnsureNetwork(client, dockerutil.NetName)
if err != nil {
log.Fatal(err)
}
containers, err := dockerutil.GetDockerContainers(true)
if err != nil {
log.Fatal(err)
}
for _, container := range containers {
name := dockerutil.ContainerName(container)
if name == checkName {
if container.State == checkState {
return true, nil
}
return false, errors.New("container " + name + " returned " + container.State)
}
}
return false, errors.New("unable to find container " + checkName)
}
// TimeTrack determines the amount of time a function takes to return. Timing starts when it is called.
// It returns an anonymous function that, when called, will print the elapsed run time.
func TimeTrack(start time.Time, name string) func() {
return func() {
elapsed := time.Since(start)
log.Printf("PERF: %s took %s", name, elapsed)
}
}
// GetCachedArchive returns a directory populated with the contents of the specified archive, either from cache or
// from downloading and creating cache.
// siteName is the site.Name used for storage
// prefixString is the prefix used to disambiguate downloads and extracts
// internalExtractionPath is the place in the archive to start extracting
// sourceURL is the actual URL to download.
// Returns the extracted path, the tarball path (both possibly cached), and an error value.
func GetCachedArchive(siteName string, prefixString string, internalExtractionPath string, sourceURL string) (string, string, error) {
uniqueName := prefixString + "_" + path.Base(sourceURL)
testCache := filepath.Join(globalconfig.GetGlobalDdevDir(), "testcache", siteName)
archiveFullPath := filepath.Join(testCache, "tarballs", uniqueName)
_ = os.MkdirAll(filepath.Dir(archiveFullPath), 0777)
extractPath := filepath.Join(testCache, prefixString)
// Check to see if we have it cached, if so just return it.
dStat, dErr := os.Stat(extractPath)
aStat, aErr := os.Stat(archiveFullPath)
if dErr == nil && dStat.IsDir() && aErr == nil && !aStat.IsDir() {
return extractPath, archiveFullPath, nil
}
output.UserOut.Printf("Downloading %s", archiveFullPath)
_ = os.MkdirAll(extractPath, 0777)
err := util.DownloadFile(archiveFullPath, sourceURL, false)
if err != nil {
return extractPath, archiveFullPath, fmt.Errorf("Failed to download url=%s into %s, err=%v", sourceURL, archiveFullPath, err)
}
output.UserOut.Printf("Downloaded %s into %s", sourceURL, archiveFullPath)
if filepath.Ext(archiveFullPath) == ".zip" {
err = archive.Unzip(archiveFullPath, extractPath, internalExtractionPath)
} else {
err = archive.Untar(archiveFullPath, extractPath, internalExtractionPath)
}
if err != nil {
_ = fileutil.PurgeDirectory(extractPath)
_ = os.RemoveAll(extractPath)
_ = os.RemoveAll(archiveFullPath)
return extractPath, archiveFullPath, fmt.Errorf("archive extraction of %s failed err=%v", archiveFullPath, err)
}
return extractPath, archiveFullPath, nil
}
// GetLocalHTTPResponse takes a URL and optional timeout in seconds,
// hits the local docker for it, returns result
// Returns error (with the body) if not 200 status code.
func GetLocalHTTPResponse(t *testing.T, rawurl string, timeoutSecsAry ...int) (string, *http.Response, error) {
var timeoutSecs = 20
if len(timeoutSecsAry) > 0 {
timeoutSecs = timeoutSecsAry[0]
}
timeoutTime := time.Duration(timeoutSecs) * time.Second
assert := asrt.New(t)
u, err := url.Parse(rawurl)
if err != nil {
t.Fatalf("Failed to parse url %s: %v", rawurl, err)
}
port := u.Port()
dockerIP, err := dockerutil.GetDockerIP()
assert.NoError(err)
fakeHost := u.Hostname()
u.Host = dockerIP
// Add the port if there is one.
if port != "" {
fakeHost = u.Hostname() + ":" + port
u.Host = dockerIP + ":" + port
}
localAddress := u.String()
// Ignore https cert failure, since we are in testing environment.
insecureTransport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// Do not follow redirects, https://stackoverflow.com/a/38150816/215713
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Transport: insecureTransport,
Timeout: timeoutTime,
}
req, err := http.NewRequest("GET", localAddress, nil)
if err != nil {
return "", nil, fmt.Errorf("Failed to NewRequest GET %s: %v", localAddress, err)
}
req.Host = fakeHost
resp, err := client.Do(req)
if err != nil {
return "", resp, err
}
//nolint: errcheck
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", resp, fmt.Errorf("unable to ReadAll resp.body: %v", err)
}
bodyString := string(bodyBytes)
if resp.StatusCode != 200 {
return bodyString, resp, fmt.Errorf("http status code was %d, not 200", resp.StatusCode)
}
return bodyString, resp, nil
}
// EnsureLocalHTTPContent will verify a URL responds with a 200 and expected content string
func EnsureLocalHTTPContent(t *testing.T, rawurl string, expectedContent string, timeoutSeconds ...int) (*http.Response, error) {
var httpTimeout = 20
if len(timeoutSeconds) > 0 {
httpTimeout = timeoutSeconds[0]
}
assert := asrt.New(t)
body, resp, err := GetLocalHTTPResponse(t, rawurl, httpTimeout)
// We see intermittent php-fpm SIGBUS failures, only on macOS.
// That results in a 502/503. If we get a 502/503 on macOS, try again.
// It seems to be a 502 with nginx-fpm and a 503 with apache-fpm
if runtime.GOOS == "darwin" && resp != nil && (resp.StatusCode == 502 || resp.StatusCode == 503) {
t.Logf("Received %d error on macOS, retrying GetLocalHTTPResponse", resp.StatusCode)
time.Sleep(time.Second)
body, resp, err = GetLocalHTTPResponse(t, rawurl, httpTimeout)
}
assert.NoError(err, "GetLocalHTTPResponse returned err on rawurl %s: %v", rawurl, err)
assert.Contains(body, expectedContent, "request %s got resp=%v, body:\n========\n%s\n==========\n", rawurl, resp, body)
return resp, err
}
// PortPair is for tests to use naming portsets for tests
type PortPair struct {
HTTPPort string
HTTPSPort string
}