/
config_test.go
607 lines (495 loc) · 19.4 KB
/
config_test.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package ddevapp_test
import (
"bufio"
"fmt"
"github.com/stretchr/testify/require"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
. "github.com/drud/ddev/pkg/ddevapp"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/testcommon"
"github.com/drud/ddev/pkg/util"
"github.com/drud/ddev/pkg/version"
"github.com/google/uuid"
asrt "github.com/stretchr/testify/assert"
)
// TestNewConfig tests functionality around creating a new config, writing it to disk, and reading the resulting config.
func TestNewConfig(t *testing.T) {
assert := asrt.New(t)
// Create a temporary directory and change to it for the duration of this test.
testDir := testcommon.CreateTmpDir("TestNewConfig")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Load a new Config
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Ensure the config uses specified defaults.
assert.Equal(app.APIVersion, version.DdevVersion)
assert.Equal(app.DBImage, version.GetDBImage())
assert.Equal(app.WebImage, version.GetWebImage())
assert.Equal(app.DBAImage, version.GetDBAImage())
app.Name = util.RandString(32)
app.Type = AppTypeDrupal8
// WriteConfig the app.
err = app.WriteConfig()
assert.NoError(err)
_, err = os.Stat(app.ConfigPath)
assert.NoError(err)
loadedConfig, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
assert.Equal(app.Name, loadedConfig.Name)
assert.Equal(app.Type, loadedConfig.Type)
}
// TestAllowedAppType tests the IsAllowedAppType function.
func TestAllowedAppTypes(t *testing.T) {
assert := asrt.New(t)
for _, v := range GetValidAppTypes() {
assert.True(IsValidAppType(v))
}
for i := 1; i <= 50; i++ {
randomType := util.RandString(32)
assert.False(IsValidAppType(randomType))
}
}
// TestPrepDirectory ensures the configuration directory can be created with the correct permissions.
func TestPrepDirectory(t *testing.T) {
assert := asrt.New(t)
// Create a temporary directory and change to it for the duration of this test.
testDir := testcommon.CreateTmpDir("TestPrepDirectory")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Prep the directory.
err = PrepDdevDirectory(filepath.Dir(app.ConfigPath))
assert.NoError(err)
// Read directory info an ensure it exists.
_, err = os.Stat(filepath.Dir(app.ConfigPath))
assert.NoError(err)
}
// TestHostName tests that the TestSite.Hostname() field returns the hostname as expected.
func TestHostName(t *testing.T) {
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestHostName")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
app.Name = util.RandString(32)
assert.Equal(app.GetHostname(), app.Name+"."+version.DDevTLD)
}
// TestWriteDockerComposeYaml tests the writing of a docker-compose.yaml file.
func TestWriteDockerComposeYaml(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestWriteDockerCompose")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
app.Name = util.RandString(32)
app.Type = GetValidAppTypes()[0]
// WriteConfig a config to create/prep necessary directories.
err = app.WriteConfig()
assert.NoError(err)
// After the config has been written and directories exist, the write should work.
err = app.WriteDockerComposeConfig()
assert.NoError(err)
// Ensure we can read from the file and that it's a regular file with the expected name.
fileinfo, err := os.Stat(app.DockerComposeYAMLPath())
assert.NoError(err)
assert.False(fileinfo.IsDir())
assert.Equal(fileinfo.Name(), filepath.Base(app.DockerComposeYAMLPath()))
composeBytes, err := ioutil.ReadFile(app.DockerComposeYAMLPath())
assert.NoError(err)
contentString := string(composeBytes)
assert.Contains(contentString, app.Platform)
assert.Contains(contentString, app.Type)
}
// TestConfigCommand tests the interactive config options.
func TestConfigCommand(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
const apptypePos = 0
const phpVersionPos = 1
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName, testValues := range testMatrix {
testDir := testcommon.CreateTmpDir("TestConfigCommand_" + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a docroot folder.
err := os.Mkdir(filepath.Join(testDir, "docroot"), 0644)
if err != nil {
t.Errorf("Could not create docroot directory under %s", testDir)
}
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
invalidAppType := strings.ToLower(util.RandString(8))
// Create an example input buffer that writes the sitename, a valid document root,
// an invalid app type, and finally a valid app type (from test matrix)
input := fmt.Sprintf("%s\ndocroot\n%s\n%s", name, invalidAppType, testValues[apptypePos])
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, testDir)
assert.Contains(out, fmt.Sprintf("'%s' is not a valid project type", invalidAppType))
// Create an example input buffer that writes an invalid projectname, then a valid-project-name,
// a valid document root,
// a valid app type
input = fmt.Sprintf("invalid_project_name\n%s\ndocroot\n%s", name, testValues[apptypePos])
scanner = bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput = util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out = restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, testDir)
assert.Contains(out, "invalid_project_name is not a valid project name")
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(testValues[apptypePos], app.Type)
assert.Equal("docroot", app.Docroot)
assert.EqualValues(testValues[phpVersionPos], app.PHPVersion)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandInteractiveCreateDocrootDenied
func TestConfigCommandInteractiveCreateDocrootDenied(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
noninteractiveEnv := "DRUD_NONINTERACTIVE"
// nolint: errcheck
defer os.Setenv(noninteractiveEnv, os.Getenv(noninteractiveEnv))
err := os.Unsetenv(noninteractiveEnv)
assert.NoError(err)
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName := range testMatrix {
testDir := testcommon.CreateTmpDir(t.Name() + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := uuid.New().String()
nonexistentDocroot := filepath.Join("does", "not", "exist")
// Create an example input buffer that writes the sitename, a nonexistent document root,
// and a "no"
input := fmt.Sprintf("%s\n%s\nno", name, nonexistentDocroot)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
err = app.PromptForConfig()
assert.Error(err, t)
// Ensure we have expected vales in output.
assert.Contains(err.Error(), "docroot must exist to continue configuration")
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandCreateDocrootAllowed
func TestConfigCommandCreateDocrootAllowed(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
const apptypePos = 0
const phpVersionPos = 1
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName, testValues := range testMatrix {
testDir := testcommon.CreateTmpDir(t.Name() + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := uuid.New().String()
nonexistentDocroot := filepath.Join("does", "not", "exist")
// Create an example input buffer that writes the sitename, a nonexistent document root,
// a "yes", and a valid apptype
input := fmt.Sprintf("%s\n%s\nyes\n%s", name, nonexistentDocroot, testValues[apptypePos])
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, nonexistentDocroot)
assert.Contains(out, "Created docroot")
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(testValues[apptypePos], app.Type)
assert.Equal(nonexistentDocroot, app.Docroot)
assert.EqualValues(testValues[phpVersionPos], app.PHPVersion)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandDocrootDetection asserts the default docroot is detected.
func TestConfigCommandDocrootDetection(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testMatrix := AvailableDocrootLocations()
for index, testDocrootName := range testMatrix {
testDir := testcommon.CreateTmpDir(fmt.Sprintf("TestConfigCommand_%v", index))
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a document root folder.
err := os.MkdirAll(filepath.Join(testDir, filepath.Join(testDocrootName)), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", testDocrootName, testDir)
}
_, err = os.OpenFile(filepath.Join(testDir, filepath.Join(testDocrootName), "index.php"), os.O_RDONLY|os.O_CREATE, 0664)
assert.NoError(err)
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
// Create an example input buffer that writes the site name, accepts the
// default document root and provides a valid app type.
input := fmt.Sprintf("%s\n\ndrupal8", name)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureStdOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
assert.Contains(out, fmt.Sprintf("Docroot Location (%s)", testDocrootName))
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(AppTypeDrupal8, app.Type)
assert.Equal(testDocrootName, app.Docroot)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandDocrootDetection asserts the default docroot is detected and has index.php.
// The `web` docroot check is before `docroot` this verifies the directory with an
// existing index.php is selected.
func TestConfigCommandDocrootDetectionIndexVerification(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestConfigCommand_testDocrootIndex")
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a document root folder.
err := os.MkdirAll(filepath.Join(testDir, filepath.Join("web")), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", "web", testDir)
}
err = os.MkdirAll(filepath.Join(testDir, filepath.Join("docroot")), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", "docroot", testDir)
}
_, err = os.OpenFile(filepath.Join(testDir, "docroot", "index.php"), os.O_RDONLY|os.O_CREATE, 0664)
assert.NoError(err)
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
// Create an example input buffer that writes the site name, accepts the
// default document root and provides a valid app type.
input := fmt.Sprintf("%s\n\ndrupal8", name)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureStdOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
assert.Contains(out, fmt.Sprintf("Docroot Location (%s)", "docroot"))
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(AppTypeDrupal8, app.Type)
assert.Equal("docroot", app.Docroot)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
// TestReadConfig tests reading config values from file and fallback to defaults for values not exposed.
func TestReadConfig(t *testing.T) {
assert := asrt.New(t)
// This closely resembles the values one would have from NewApp()
app := &DdevApp{
APIVersion: version.DdevVersion,
ConfigPath: filepath.Join("testdata", "config.yaml"),
AppRoot: "testdata",
Name: "TestRead",
Provider: ProviderDefault,
}
err := app.ReadConfig()
if err != nil {
t.Fatalf("Unable to c.ReadConfig(), err: %v", err)
}
// Values not defined in file, we should still have default values
assert.Equal(app.Name, "TestRead")
assert.Equal(app.APIVersion, version.DdevVersion)
// Values defined in file, we should have values from file
assert.Equal(app.Type, AppTypeDrupal8)
assert.Equal(app.Docroot, "test")
assert.Equal(app.WebImage, "test/testimage:latest")
}
// TestConfigValidate tests validation of configuration values.
func TestConfigValidate(t *testing.T) {
assert := asrt.New(t)
cwd, err := os.Getwd()
assert.NoError(err)
app := &DdevApp{
Name: "TestConfigValidate",
ConfigPath: filepath.Join("testdata", "config.yaml"),
AppRoot: cwd,
Docroot: "testdata",
Type: AppTypeWordPress,
PHPVersion: PHPDefault,
MariaDBVersion: version.MariaDBDefaultVersion,
WebserverType: WebserverDefault,
Provider: ProviderDefault,
}
err = app.ValidateConfig()
if err != nil {
t.Fatalf("Failed to app.ValidateConfig(), err=%v", err)
}
app.Name = "Invalid!"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "not a valid project name")
app.Docroot = "testdata"
app.Name = "valid"
app.Type = "potato"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid app type")
app.Type = AppTypeWordPress
app.PHPVersion = "1.1"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid PHP")
app.PHPVersion = PHPDefault
app.WebserverType = "server"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid webserver type")
app.WebserverType = WebserverDefault
app.AdditionalHostnames = []string{"good", "b@d"}
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid hostname")
app.AdditionalHostnames = []string{}
app.AdditionalFQDNs = []string{"good.com", "b@d.com"}
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid hostname")
}
// TestWriteConfig tests writing config values to file
func TestWriteConfig(t *testing.T) {
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestConfigWrite")
// This closely resembles the values one would have from NewApp()
app := &DdevApp{
ConfigPath: filepath.Join(testDir, "config.yaml"),
AppRoot: testDir,
APIVersion: version.DdevVersion,
Name: "TestWrite",
WebImage: version.GetWebImage(),
DBImage: version.GetDBImage(),
DBAImage: version.GetDBAImage(),
Type: AppTypeDrupal8,
Provider: ProviderDefault,
}
err := app.WriteConfig()
assert.NoError(err)
out, err := ioutil.ReadFile(filepath.Join(testDir, "config.yaml"))
assert.NoError(err)
assert.Contains(string(out), "TestWrite")
assert.Contains(string(out), `exec: drush cr`)
app.Type = AppTypeWordPress
err = app.WriteConfig()
assert.NoError(err)
out, err = ioutil.ReadFile(filepath.Join(testDir, "config.yaml"))
assert.NoError(err)
assert.Contains(string(out), `- exec: wp cli version`)
err = os.RemoveAll(testDir)
assert.NoError(err)
}
// TestConfigOverrideDetection tests to make sure we tell them about config overrides.
func TestConfigOverrideDetection(t *testing.T) {
assert := asrt.New(t)
app := &DdevApp{}
testDir, _ := os.Getwd()
site := TestSites[0]
switchDir := site.Chdir()
defer switchDir()
runTime := testcommon.TimeTrack(time.Now(), fmt.Sprintf("%s ConfigOverrideDetection", site.Name))
// Copy test overrides into the project .ddev directory
for _, item := range []string{"apache", "php", "mysql"} {
err := fileutil.CopyDir(filepath.Join(testDir, "testdata/TestConfigOverrideDetection/.ddev", item), filepath.Join(site.Dir, ".ddev", item))
assert.NoError(err)
err = fileutil.CopyFile(filepath.Join(testDir, "testdata/TestConfigOverrideDetection/.ddev", "nginx-site.conf"), filepath.Join(site.Dir, ".ddev", "nginx-site.conf"))
assert.NoError(err)
}
// And when we're done, we have to clean those out again.
defer func() {
for _, item := range []string{"apache", "php", "mysql", "nginx-site.conf"} {
_ = os.RemoveAll(filepath.Join(".ddev", item))
}
}()
testcommon.ClearDockerEnv()
err := app.Init(site.Dir)
assert.NoError(err)
restoreOutput := util.CaptureUserOut()
startErr := app.StartAndWaitForSync(2)
out := restoreOutput()
//nolint: errcheck
defer app.Down(true, false)
var logs string
if startErr != nil {
logs, _ = GetErrLogsFromApp(app, startErr)
}
require.NoError(t, startErr, "app.StartAndWaitForSync() did not succeed: output:\n=====\n%s\n===== logs:\n========= logs =======\n%s\n========\n", out, logs)
assert.Contains(out, "utf.cnf")
assert.Contains(out, "my-php.ini")
switch app.WebserverType {
case WebserverNginxFPM:
assert.Contains(out, "nginx-site.conf")
assert.NotContains(out, "apache-site.conf")
default:
assert.Contains(out, "apache-site.conf")
assert.NotContains(out, "nginx-site.conf")
}
assert.Contains(out, "Custom configuration takes effect")
runTime()
}