-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
ddevapp_test.go
3328 lines (2768 loc) · 113 KB
/
ddevapp_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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ddevapp_test
import (
"bufio"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/drud/ddev/pkg/nodeps"
"github.com/drud/ddev/pkg/version"
"github.com/drud/ddev/pkg/globalconfig"
"github.com/stretchr/testify/require"
"github.com/drud/ddev/pkg/archive"
"github.com/drud/ddev/pkg/ddevapp"
"github.com/drud/ddev/pkg/dockerutil"
"github.com/drud/ddev/pkg/exec"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/output"
"github.com/drud/ddev/pkg/testcommon"
"github.com/drud/ddev/pkg/util"
docker "github.com/fsouza/go-dockerclient"
"github.com/google/uuid"
"github.com/lunixbochs/vtclean"
log "github.com/sirupsen/logrus"
asrt "github.com/stretchr/testify/assert"
)
var (
DdevBin = "ddev"
TestSites = []testcommon.TestSite{
{
Name: "TestPkgWordpress",
SourceURL: "https://github.com/drud/wordpress/archive/v0.4.0.tar.gz",
ArchiveInternalExtractionPath: "wordpress-0.4.0/",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.0/wordpress_files.tar.gz",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.0/wordpress_db.tar.gz",
Docroot: "htdocs",
Type: nodeps.AppTypeWordPress,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/readme.html", Expect: "Welcome. WordPress is a very special project to me."},
DynamicURI: testcommon.URIWithExpect{URI: "/", Expect: "this post has a photo"},
FilesImageURI: "/wp-content/uploads/2017/04/pexels-photo-265186-1024x683.jpeg",
},
{
Name: "TestPkgDrupal8",
SourceURL: "https://ftp.drupal.org/files/projects/drupal-8.8.4.tar.gz",
ArchiveInternalExtractionPath: "drupal-8.8.4/",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d8_umami.files.tar.gz",
FilesZipballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d8_umami.files.zip",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d8_umami.sql.tar.gz",
DBZipURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d8_umami.sql.zip",
FullSiteTarballURL: "",
Type: nodeps.AppTypeDrupal8,
Docroot: "",
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/README.txt", Expect: "Drupal is an open source content management platform"},
DynamicURI: testcommon.URIWithExpect{URI: "/node/2", Expect: "Vegan chocolate and nut brownies"},
FilesImageURI: "/sites/default/files/vegan-chocolate-nut-brownies.jpg",
},
{
Name: "TestPkgDrupal7", // Drupal D7
SourceURL: "https://ftp.drupal.org/files/projects/drupal-7.61.tar.gz",
ArchiveInternalExtractionPath: "drupal-7.61/",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d7test-7.59.files.tar.gz",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d7test-7.59-db.tar.gz",
FullSiteTarballURL: "",
Docroot: "",
Type: nodeps.AppTypeDrupal7,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/README.txt", Expect: "Drupal is an open source content management platform"},
DynamicURI: testcommon.URIWithExpect{URI: "/node/1", Expect: "D7 test project, kittens edition"},
FilesImageURI: "/sites/default/files/field/image/kittens-large.jpg",
FullSiteArchiveExtPath: "docroot/sites/default/files",
},
{
Name: "TestPkgDrupal6",
SourceURL: "https://ftp.drupal.org/files/projects/drupal-6.38.tar.gz",
ArchiveInternalExtractionPath: "drupal-6.38/",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/drupal6.38_db.tar.gz",
FullSiteTarballURL: "",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/drupal6_files.tar.gz",
Docroot: "",
Type: nodeps.AppTypeDrupal6,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/CHANGELOG.txt", Expect: "Drupal 6.38, 2016-02-24"},
DynamicURI: testcommon.URIWithExpect{URI: "/node/2", Expect: "This is a story. The story is somewhat shaky"},
FilesImageURI: "/sites/default/files/garland_logo.jpg",
},
{
Name: "TestPkgBackdrop",
SourceURL: "https://github.com/backdrop/backdrop/archive/1.11.0.tar.gz",
ArchiveInternalExtractionPath: "backdrop-1.11.0/",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/backdrop_db.11.0.tar.gz",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/backdrop_files.11.0.tar.gz",
FullSiteTarballURL: "",
Docroot: "",
Type: nodeps.AppTypeBackdrop,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/README.md", Expect: "Backdrop is a full-featured content management system"},
DynamicURI: testcommon.URIWithExpect{URI: "/posts/first-post-all-about-kittens", Expect: "Lots of kittens are a good thing"},
FilesImageURI: "/files/styles/large/public/field/image/kittens-large.jpg",
},
{
Name: "TestPkgTypo3",
SourceURL: "https://github.com/drud/typo3-v9-test/archive/v0.2.2.tar.gz",
ArchiveInternalExtractionPath: "typo3-v9-test-0.2.2/",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/typo3_v9.5_introduction_db.tar.gz",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/typo3_v9.5_introduction_files.tar.gz",
FullSiteTarballURL: "",
Docroot: "public",
Type: nodeps.AppTypeTYPO3,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/README.txt", Expect: "junk readme simply for reading"},
DynamicURI: testcommon.URIWithExpect{URI: "/index.php?id=65", Expect: "Boxed Content"},
FilesImageURI: "/fileadmin/introduction/images/streets/nikita-maru-70928.jpg",
},
{
Name: "testpkgmagento",
SourceURL: "https://github.com/OpenMage/magento-mirror/archive/1.9.4.3.tar.gz",
ArchiveInternalExtractionPath: "magento-mirror-1.9.4.3/",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/TestPkgMagento_db_secure_url.tar.gz",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/magento_upload_files.tgz",
FullSiteTarballURL: "",
Docroot: "",
Type: nodeps.AppTypeMagento,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/LICENSE.txt", Expect: `Open Software License ("OSL")`},
DynamicURI: testcommon.URIWithExpect{URI: "/", Expect: "This is a demo store"},
FilesImageURI: "/media/wrapping/Chrysanthemum.jpg",
},
// Note that testpkgmagento2 code is enormous and makes this really, really slow.
{
Name: "testpkgmagento2",
SourceURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/magento2_code_no_dev_with_media.tgz",
ArchiveInternalExtractionPath: "",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/magento2_db.tgz",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/magento2_files.tgz",
FullSiteTarballURL: "",
Docroot: "pub",
Type: nodeps.AppTypeMagento2,
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/junk.txt", Expect: `This is a junk`},
DynamicURI: testcommon.URIWithExpect{URI: "/index.php/junk-product.html", Expect: "junk product"},
FilesImageURI: "/media/catalog/product/r/a/randy_4th_of_july_unicycle.jpg",
},
{
Name: "TestPkgDrupal9",
SourceURL: "https://ftp.drupal.org/files/projects/drupal-9.0.0-beta1.tar.gz",
ArchiveInternalExtractionPath: "drupal-9.0.0-beta1/",
FilesTarballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d9_umami_files.tgz",
FilesZipballURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d9_umami_files.zip",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d9_umami_sql.tar.gz",
DBZipURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/d9_umami.sql.zip",
FullSiteTarballURL: "",
Type: nodeps.AppTypeDrupal9,
Docroot: "",
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/README.txt", Expect: "Drupal is an open source content management platform"},
DynamicURI: testcommon.URIWithExpect{URI: "/node/1", Expect: "Deep mediterranean quiche"},
FilesImageURI: "/sites/default/files/mediterranean-quiche-umami.jpg",
},
{
Name: "TestPkgLaravel",
SourceURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/ddev-lumen-testapp.tar.gz",
ArchiveInternalExtractionPath: "ddev-lumen-testapp/",
FilesTarballURL: "",
FilesZipballURL: "",
DBTarURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/ddev-lumen-testapp_sql.tar.gz",
DBZipURL: "https://github.com/drud/ddev_test_tarballs/releases/download/v1.1/ddev-lumen-testapp_sql.zip",
FullSiteTarballURL: "",
Type: nodeps.AppTypeLaravel,
Docroot: "public",
Safe200URIWithExpectation: testcommon.URIWithExpect{URI: "/", Expect: "Laravel Components"},
DynamicURI: testcommon.URIWithExpect{URI: "/api/status-code/200", Expect: "indicates that the request has succeeded."},
FilesImageURI: "/images/200.jpg",
},
}
FullTestSites = TestSites
)
func init() {
// Make sets DDEV_BINARY_FULLPATH when building the executable
if os.Getenv("DDEV_BINARY_FULLPATH") != "" {
DdevBin = os.Getenv("DDEV_BINARY_FULLPATH")
}
}
func TestMain(m *testing.M) {
output.LogSetUp()
// Since this may be first time ddev has been used, we need the
// ddev_default network available.
dockerutil.EnsureDdevNetwork()
// Avoid having sudo try to add to /etc/hosts.
// This is normally done by Testsite.Prepare()
_ = os.Setenv("DRUD_NONINTERACTIVE", "true")
// If GOTEST_SHORT is an integer, then use it as index for a single usage
// in the array. Any value can be used, it will default to just using the
// first site in the array.
gotestShort := os.Getenv("GOTEST_SHORT")
if gotestShort != "" {
useSite := 0
if site, err := strconv.Atoi(gotestShort); err == nil && site >= 0 && site < len(TestSites) {
useSite = site
}
TestSites = []testcommon.TestSite{TestSites[useSite]}
}
// testRun is the exit result we'll provide.
// Start with a clean exit result, it will be changed if we have trouble.
testRun := 0
err := globalconfig.ReadGlobalConfig()
if err != nil {
log.Fatalf("could not read globalconfig: %v", err)
}
token := os.Getenv("DDEV_PANTHEON_API_TOKEN")
if token != "" {
out, err := exec.RunCommand(DdevBin, []string{"auth", "pantheon", token})
if err != nil {
log.Fatalf("Unable to ddev auth pantheon: %v (%v)", err, out)
}
} else {
log.Info("No DDEV_PANTHEON_API_TOKEN env var has been set. Skipping Pantheon specific tests.")
}
token = os.Getenv("DDEV_DDEVLIVE_API_TOKEN")
if token != "" {
// ddev auth ddev-live can create a .ddev folder, which we don't need right now,
// so drop it in /tmp
out, err := exec.RunCommand("bash", []string{"-c", "cd /tmp && ddev auth ddev-live " + token})
if err != nil {
log.Fatalf("Unable to ddev auth ddev-live: %v (%v)", err, out)
}
} else {
log.Info("No DDEV_DDEVLIVE_API_TOKEN env var has been set. Skipping ddev-live specific tests.")
}
for i, site := range TestSites {
app := &ddevapp.DdevApp{Name: site.Name}
_ = app.Stop(true, false)
_ = globalconfig.RemoveProjectInfo(site.Name)
err := TestSites[i].Prepare()
if err != nil {
log.Fatalf("Prepare() failed on TestSite.Prepare() site=%s, err=%v", TestSites[i].Name, err)
}
switchDir := TestSites[i].Chdir()
testcommon.ClearDockerEnv()
app = &ddevapp.DdevApp{}
err = app.Init(TestSites[i].Dir)
if err != nil {
testRun = -1
log.Errorf("TestMain startup: app.Init() failed on site %s in dir %s, err=%v", TestSites[i].Name, TestSites[i].Dir, err)
continue
}
err = app.WriteConfig()
if err != nil {
testRun = -1
log.Errorf("TestMain startup: app.WriteConfig() failed on site %s in dir %s, err=%v", TestSites[i].Name, TestSites[i].Dir, err)
continue
}
for _, volume := range []string{app.Name + "-mariadb"} {
err = dockerutil.RemoveVolume(volume)
if err != nil {
log.Errorf("TestMain startup: Failed to delete volume %s: %v", volume, err)
}
}
switchDir()
}
if testRun == 0 {
log.Debugln("Running tests.")
testRun = m.Run()
}
for i, site := range TestSites {
testcommon.ClearDockerEnv()
app := &ddevapp.DdevApp{}
err := app.Init(site.Dir)
if err != nil {
log.Fatalf("TestMain shutdown: app.Init() failed on site %s in dir %s, err=%v", TestSites[i].Name, TestSites[i].Dir, err)
}
if app.SiteStatus() != ddevapp.SiteStopped {
err = app.Stop(true, false)
if err != nil {
log.Fatalf("TestMain shutdown: app.Stop() failed on site %s, err=%v", TestSites[i].Name, err)
}
}
site.Cleanup()
}
os.Exit(testRun)
}
// TestDdevStart tests the functionality that is called when "ddev start" is executed
func TestDdevStart(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
// Make sure this leaves us in the original test directory
testDir, _ := os.Getwd()
//nolint: errcheck
defer os.Chdir(testDir)
site := TestSites[0]
switchDir := site.Chdir()
defer switchDir()
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s DdevStart", site.Name))
err := app.Init(site.Dir)
assert.NoError(err)
// Before start, since we haven't changed MariaDBVersion, it should be ""
assert.EqualValues("", app.MariaDBVersion)
err = app.Start()
assert.NoError(err)
// Make sure the -built docker image exists before stop
webBuilt := version.GetWebImage() + "-" + site.Name + "-built"
dbBuilt := version.GetWebImage() + "-" + site.Name + "-built"
exists, err := dockerutil.ImageExistsLocally(webBuilt)
assert.NoError(err)
assert.True(exists)
// After start, we haven't changed default version, the dbimage
// should now be set and should be the default
assert.EqualValues(app.DBImage, version.GetDBImage(nodeps.MariaDB))
//nolint: errcheck
defer app.Stop(true, false)
// ensure .ddev/.ddev-docker-compose* exists inside .ddev site folder
composeFile := fileutil.FileExists(app.DockerComposeYAMLPath())
assert.True(composeFile)
for _, containerType := range [3]string{"web", "db", "dba"} {
containerName, err := constructContainerName(containerType, app)
assert.NoError(err)
check, err := testcommon.ContainerCheck(containerName, "running")
assert.NoError(err)
assert.True(check, "Container check on %s failed", containerType)
}
if util.IsCommandAvailable("mysql") {
dbPort, err := app.GetPublishedPort("db")
assert.NoError(err)
dockerIP, _ := dockerutil.GetDockerIP()
out, err := exec.RunCommand("mysql", []string{"--user=db", "--password=db", "--port=" + strconv.Itoa(dbPort), "--database=db", "--host=" + dockerIP, "-e", "SELECT 1;"})
assert.NoError(err)
assert.Contains(out, "1")
} else {
fmt.Print("TestDddevStart skipping check for local mysql connection because mysql command not in path")
}
err = app.Stop(true, false)
assert.NoError(err)
// Make sure the -built docker images do not exist after stop with removeData
for _, imageName := range []string{webBuilt, dbBuilt} {
exists, err = dockerutil.ImageExistsLocally(imageName)
assert.NoError(err)
assert.False(exists, "image %s should not have existed but still exists (while testing %s)", app.Name)
}
runTime()
switchDir()
// Start up TestSites[0] again with a post-start hook
// When run the first time, it should execute the hook, second time it should not
err = os.Chdir(site.Dir)
assert.NoError(err)
err = app.Init(site.Dir)
app.Hooks = map[string][]ddevapp.YAMLTask{"post-start": {{"exec": "echo hello"}}}
assert.NoError(err)
stdoutFunc, err := util.CaptureOutputToFile()
assert.NoError(err)
promptOutFunc := util.CaptureUserOut()
err = app.Start()
assert.NoError(err)
//nolint: errcheck
defer app.Stop(true, false)
out := stdoutFunc()
UOut := promptOutFunc()
assert.Contains(UOut, "Running task: Exec command 'echo hello' in container/service 'web'")
assert.Contains(out, "hello\n")
// try to start a site of same name at different path
another := site
tmpDir := testcommon.CreateTmpDir("another")
copyDir := filepath.Join(tmpDir, "copy")
err = fileutil.CopyDir(site.Dir, copyDir)
assert.NoError(err)
another.Dir = copyDir
//nolint: errcheck
defer os.RemoveAll(copyDir)
badapp := &ddevapp.DdevApp{}
err = badapp.Init(copyDir)
//nolint: errcheck
defer badapp.Stop(true, false)
if err == nil {
logs, logErr := app.CaptureLogs("web", false, "")
require.Error(t, err, "did not receive err from badapp.Init, logErr=%v, logs:\n======================= logs from app webserver =================\n%s\n============ end logs =========\n", logErr, logs)
}
if err != nil {
assert.Contains(err.Error(), fmt.Sprintf("a project (web container) in running state already exists for %s that was created at %s", TestSites[0].Name, TestSites[0].Dir))
}
// Try to start a site of same name at an equivalent but different path. It should work.
tmpDir, err = testcommon.OsTempDir()
assert.NoError(err)
symlink := filepath.Join(tmpDir, fileutil.RandomFilenameBase())
err = os.Symlink(app.AppRoot, symlink)
assert.NoError(err)
//nolint: errcheck
defer os.Remove(symlink)
symlinkApp := &ddevapp.DdevApp{}
err = symlinkApp.Init(symlink)
assert.NoError(err)
//nolint: errcheck
defer symlinkApp.Stop(true, false)
// Make sure that GetActiveApp() also fails when trying to start app of duplicate name in current directory.
switchDir = another.Chdir()
defer switchDir()
_, err = ddevapp.GetActiveApp("")
assert.Error(err)
if err != nil {
assert.Contains(err.Error(), fmt.Sprintf("a project (web container) in running state already exists for %s that was created at %s", TestSites[0].Name, TestSites[0].Dir))
}
testcommon.CleanupDir(another.Dir)
}
// TestDdevStartMultipleHostnames tests start with multiple hostnames
func TestDdevStartMultipleHostnames(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
for _, site := range TestSites {
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s DdevStartMultipleHostnames", site.Name))
testcommon.ClearDockerEnv()
err := app.Init(site.Dir)
assert.NoError(err)
// site.Name is explicitly added because if not removed in GetHostNames() it will cause ddev-router failure
// "a" is repeated for the same reason; a user error of this type should not cause a failure; GetHostNames()
// should uniqueify them.
app.AdditionalHostnames = []string{"sub1." + site.Name, "sub2." + site.Name, "subname.sub3." + site.Name, site.Name, site.Name, site.Name}
// sub1.<sitename>.ddev.site and sitename.ddev.site are deliberately included to prove they don't
// cause ddev-router failures"
app.AdditionalFQDNs = []string{"one.example.com", "two.example.com", "a.one.example.com", site.Name + "." + app.ProjectTLD, "sub1." + site.Name + "." + app.ProjectTLD}
err = app.WriteConfig()
assert.NoError(err)
err = app.StartAndWait(5)
assert.NoError(err)
if err != nil && strings.Contains(err.Error(), "db container failed") {
container, err := app.FindContainerByType("db")
assert.NoError(err)
out, err := exec.RunCommand("docker", []string{"logs", container.Names[0]})
assert.NoError(err)
t.Logf("DB Logs after app.Start: \n%s\n=== END DB LOGS ===", out)
}
// ensure .ddev/docker-compose*.yaml exists inside .ddev site folder
composeFile := fileutil.FileExists(app.DockerComposeYAMLPath())
assert.True(composeFile)
for _, containerType := range [3]string{"web", "db", "dba"} {
containerName, err := constructContainerName(containerType, app)
assert.NoError(err)
check, err := testcommon.ContainerCheck(containerName, "running")
assert.NoError(err)
assert.True(check, "Container check on %s failed", containerType)
}
_, _, urls := app.GetAllURLs()
t.Logf("Testing these URLs: %v", urls)
_, _, allURLs := app.GetAllURLs()
for _, url := range allURLs {
_, _ = testcommon.EnsureLocalHTTPContent(t, url+site.Safe200URIWithExpectation.URI, site.Safe200URIWithExpectation.Expect)
}
out, err := exec.RunCommand(DdevBin, []string{"list"})
assert.NoError(err)
t.Logf("=========== output of ddev list ==========\n%s\n============", out)
// Multiple projects can't run at the same time with the fqdns, so we need to clean
// up these for tests that run later.
app.AdditionalFQDNs = []string{}
app.AdditionalHostnames = []string{}
err = app.WriteConfig()
assert.NoError(err)
err = app.Stop(true, false)
assert.NoError(err)
runTime()
}
}
// TestDdevStartUnmanagedSettings start and config with disable_settings_management
func TestDdevStartUnmanagedSettings(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
// Make sure this leaves us in the original test directory
testDir, _ := os.Getwd()
//nolint: errcheck
defer os.Chdir(testDir)
// Use Drupal8 only, mostly for the composer example
site := FullTestSites[1]
// If running this with GOTEST_SHORT we have to create the directory, tarball etc.
if site.Dir == "" || !fileutil.FileExists(site.Dir) {
app := &ddevapp.DdevApp{Name: site.Name}
_ = app.Stop(true, false)
_ = globalconfig.RemoveProjectInfo(site.Name)
err := site.Prepare()
require.NoError(t, err)
// nolint: errcheck
defer os.RemoveAll(site.Dir)
}
switchDir := site.Chdir()
defer switchDir()
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s DdevStart", site.Name))
defer runTime()
err := app.Init(site.Dir)
assert.NoError(err)
// Previous tests may have left settings files
_ = os.Remove(app.SiteSettingsPath)
_ = os.Remove(app.SiteDdevSettingsFile)
// On initial init, settings files should not exist
assert.False(fileutil.FileExists(app.SiteSettingsPath))
assert.False(fileutil.FileExists(app.SiteDdevSettingsFile))
app.DisableSettingsManagement = true
err = app.WriteConfig()
assert.NoError(err)
// After config, they should still not exist, because we had DisableSettingsManagement
assert.False(fileutil.FileExists(app.SiteSettingsPath))
assert.False(fileutil.FileExists(app.SiteDdevSettingsFile))
err = app.Start()
assert.NoError(err)
//nolint: errcheck
defer app.Stop(true, false)
// After start, they should still not exist, because we had DisableSettingsManagement
assert.False(fileutil.FileExists(app.SiteSettingsPath))
assert.False(fileutil.FileExists(app.SiteDdevSettingsFile))
app.DisableSettingsManagement = false
err = app.WriteConfig()
assert.NoError(err)
_, err = app.CreateSettingsFile()
assert.NoError(err)
// Now with DisableSettingsManagement=false, both should exist after config/settings creation
assert.FileExists(app.SiteSettingsPath)
assert.FileExists(app.SiteDdevSettingsFile)
_ = os.Remove(filepath.Join(app.SiteSettingsPath))
_ = os.Remove(filepath.Join(app.SiteDdevSettingsFile))
assert.False(fileutil.FileExists(app.SiteSettingsPath))
assert.False(fileutil.FileExists(app.SiteDdevSettingsFile))
err = app.Start()
assert.NoError(err)
//nolint: errcheck
defer app.Stop(true, false)
// Now with DisableSettingsManagement=false, start should have created both
assert.FileExists(app.SiteSettingsPath)
assert.FileExists(app.SiteDdevSettingsFile)
}
// TestDdevNoProjectMount tests running without the app file mount.
func TestDdevNoProjectMount(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
// Make sure this leaves us in the original test directory
testDir, _ := os.Getwd()
//nolint: errcheck
defer os.Chdir(testDir)
site := TestSites[0]
switchDir := site.Chdir()
defer switchDir()
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s %s", t.Name(), site.Name))
defer runTime()
err := app.Init(site.Dir)
assert.NoError(err)
app.NoProjectMount = true
err = app.WriteConfig()
assert.NoError(err)
defer func() {
err = app.Stop(true, false)
assert.NoError(err)
app.NoProjectMount = false
err = app.WriteConfig()
assert.NoError(err)
}()
err = app.Start()
assert.NoError(err)
stdout, _, err := app.Exec(&ddevapp.ExecOpts{
Service: "web",
Dir: "/var/www/html",
Cmd: `findmnt -T /var/www/html | awk '$1 != "TARGET" {printf $1}'`,
})
assert.NoError(err)
assert.NotEqual("/var/www/html", stdout)
}
// TestDdevXdebugEnabled tests running with xdebug_enabled = true, etc.
func TestDdevXdebugEnabled(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
testcommon.ClearDockerEnv()
site := TestSites[0]
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s %s", site.Name, t.Name()))
phpVersions := nodeps.ValidPHPVersions
phpKeys := make([]string, 0, len(phpVersions))
for k := range phpVersions {
phpKeys = append(phpKeys, k)
}
sort.Strings(phpKeys)
err := app.Init(site.Dir)
assert.NoError(err)
//nolint: errcheck
defer app.Stop(true, false)
for _, v := range phpKeys {
app.PHPVersion = v
t.Logf("Beginning XDebug checks with XDebug php%s\n", v)
fmt.Printf("Attempting XDebug checks with XDebug %s\n", v)
app.XdebugEnabled = false
assert.NoError(err)
err = app.Start()
require.NoError(t, err)
opts := &ddevapp.ExecOpts{
Service: "web",
Cmd: "php --ri xdebug",
}
stdout, _, err := app.Exec(opts)
assert.Error(err)
assert.Contains(stdout, "Extension 'xdebug' not present")
// Run with xdebug_enabled: true
testcommon.ClearDockerEnv()
app.XdebugEnabled = true
err = app.Start()
require.NoError(t, err)
stdout, _, err = app.Exec(opts)
assert.NoError(err)
if err != nil {
t.Errorf("Aborting xdebug check for php%s: %v", v, err)
continue
}
assert.Contains(stdout, "xdebug support => enabled", "xdebug not enabled for %s", v)
assert.Contains(stdout, "xdebug.remote_host => host.docker.internal => host.docker.internal")
// Start a listener on port 9000 of localhost (where PHPStorm or whatever would listen)
listener, err := net.Listen("tcp", ":9000")
assert.NoError(err)
if err != nil || listener == nil {
continue
}
// Curl to the project's index.php or anything else
_, _, _ = testcommon.GetLocalHTTPResponse(t, app.GetHTTPURL(), 1)
fmt.Printf("Attempting accept of port 9000 with xdebug enabled, XDebug version=%s\n", v)
// Accept is blocking, no way to timeout, so use
// goroutine instead.
acceptListenDone := make(chan bool, 1)
defer close(acceptListenDone)
go func() {
conn, err := listener.Accept()
assert.NoError(err)
if err != nil {
t.Logf("Completed accept of port 9000 with xdebug enabled, XDebug version=%s, time=%v\n", v, time.Now())
}
// Grab the Xdebug connection start and look in it for "Xdebug"
b := make([]byte, 650)
_, err = bufio.NewReader(conn).Read(b)
assert.NoError(err)
lineString := string(b)
assert.Contains(lineString, "Xdebug")
assert.Contains(lineString, `xdebug:language_version="`+v)
acceptListenDone <- true
}()
select {
case <-acceptListenDone:
fmt.Printf("Read from acceptListenDone at %v\n", time.Now())
case <-time.After(10 * time.Second):
fmt.Printf("Timed out waiting for accept/listen at %v\n", time.Now())
}
}
runTime()
}
// TestDdevMysqlWorks tests that mysql client can be run in both containers.
func TestDdevMysqlWorks(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
site := TestSites[0]
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s DdevMysqlWorks", site.Name))
err := app.Init(site.Dir)
assert.NoError(err)
testcommon.ClearDockerEnv()
err = app.StartAndWait(0)
//nolint: errcheck
defer app.Stop(true, false)
require.NoError(t, err)
// Test that mysql + .my.cnf works on web container
_, _, err = app.Exec(&ddevapp.ExecOpts{
Service: "web",
Cmd: "mysql -e 'SELECT USER();' | grep 'db@'",
})
assert.NoError(err)
_, _, err = app.Exec(&ddevapp.ExecOpts{
Service: "web",
Cmd: "mysql -e 'SELECT DATABASE();' | grep 'db'",
})
assert.NoError(err)
// Test that mysql + .my.cnf works on db container
_, _, err = app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: "mysql -e 'SELECT USER();' | grep 'root@localhost'",
})
assert.NoError(err)
_, _, err = app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: "mysql -e 'SELECT DATABASE();' | grep 'db'",
})
assert.NoError(err)
err = app.Stop(true, false)
assert.NoError(err)
runTime()
}
// TestStartWithoutDdev makes sure we don't have a regression where lack of .ddev
// causes a panic.
func TestStartWithoutDdevConfig(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestStartWithoutDdevConfig")
// testcommon.Chdir()() and CleanupDir() check their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
err := os.MkdirAll(testDir+"/sites/default", 0777)
assert.NoError(err)
err = os.Chdir(testDir)
assert.NoError(err)
_, err = ddevapp.GetActiveApp("")
assert.Error(err)
if err != nil {
assert.Contains(err.Error(), "Could not find a project")
}
}
// TestGetApps tests the GetActiveProjects function to ensure it accurately returns a list of running applications.
func TestGetApps(t *testing.T) {
assert := asrt.New(t)
// Start the apps.
for _, site := range TestSites {
testcommon.ClearDockerEnv()
app := &ddevapp.DdevApp{}
err := app.Init(site.Dir)
assert.NoError(err)
err = app.Start()
assert.NoError(err)
}
apps := ddevapp.GetActiveProjects()
for _, testSite := range TestSites {
var found bool
for _, app := range apps {
if testSite.Name == app.GetName() {
found = true
break
}
}
assert.True(found, "Found testSite %s in list", testSite.Name)
}
// Now shut down all sites as we expect them to be shut down.
for _, site := range TestSites {
testcommon.ClearDockerEnv()
app := &ddevapp.DdevApp{}
err := app.Init(site.Dir)
assert.NoError(err)
err = app.Stop(true, false)
assert.NoError(err)
}
}
// TestDdevImportDB tests the functionality that is called when "ddev import-db" is executed
func TestDdevImportDB(t *testing.T) {
assert := asrt.New(t)
app := &ddevapp.DdevApp{}
testDir, _ := os.Getwd()
site := TestSites[0]
switchDir := site.Chdir()
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s %s", site.Name, t.Name()))
testcommon.ClearDockerEnv()
err := app.Init(site.Dir)
assert.NoError(err)
err = app.Start()
assert.NoError(err)
defer func() {
app.Hooks = nil
_ = app.WriteConfig()
_ = app.Stop(true, false)
}()
app.Hooks = map[string][]ddevapp.YAMLTask{"post-import-db": {{"exec-host": "touch hello-post-import-db-" + app.Name}}, "pre-import-db": {{"exec-host": "touch hello-pre-import-db-" + app.Name}}}
// Test simple db loads.
for _, file := range []string{"users.sql", "users.mysql", "users.sql.gz", "users.mysql.gz", "users.sql.tar", "users.mysql.tar", "users.sql.tar.gz", "users.mysql.tar.gz", "users.sql.tgz", "users.mysql.tgz", "users.sql.zip", "users.mysql.zip", "users_with_USE_statement.sql"} {
path := filepath.Join(testDir, "testdata", t.Name(), file)
err = app.ImportDB(path, "", false, false, "db")
assert.NoError(err, "Failed to app.ImportDB path: %s err: %v", path, err)
if err != nil {
continue
}
// There should be exactly the one users table for each of these files
out, _, err := app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: "mysql -N -e 'SHOW TABLES;' | cat",
})
assert.NoError(err)
assert.Equal("users\n", out)
// Verify that no extra database was created
out, _, err = app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: `mysql -N -e 'SHOW DATABASES;' | egrep -v "^(information_schema|performance_schema|mysql)$"`,
})
assert.NoError(err)
assert.Equal("db\n", out)
// Test that a settings file has correct hash_salt format
switch app.Type {
case nodeps.AppTypeDrupal7:
drupalHashSalt, err := fileutil.FgrepStringInFile(app.SiteDdevSettingsFile, "$drupal_hash_salt")
assert.NoError(err)
assert.True(drupalHashSalt)
case nodeps.AppTypeDrupal8:
settingsHashSalt, err := fileutil.FgrepStringInFile(app.SiteDdevSettingsFile, "settings['hash_salt']")
assert.NoError(err)
assert.True(settingsHashSalt)
case nodeps.AppTypeWordPress:
hasAuthSalt, err := fileutil.FgrepStringInFile(app.SiteSettingsPath, "SECURE_AUTH_SALT")
assert.NoError(err)
assert.True(hasAuthSalt)
}
}
if site.DBTarURL != "" {
_, cachedArchive, err := testcommon.GetCachedArchive(site.Name, site.Name+"_siteTarArchive", "", site.DBTarURL)
assert.NoError(err)
err = app.ImportDB(cachedArchive, "", false, false, "db")
assert.NoError(err)
assert.FileExists("hello-pre-import-db-" + app.Name)
assert.FileExists("hello-post-import-db-" + app.Name)
err = os.Remove("hello-pre-import-db-" + app.Name)
assert.NoError(err)
err = os.Remove("hello-post-import-db-" + app.Name)
assert.NoError(err)
}
if site.DBZipURL != "" {
_, cachedArchive, err := testcommon.GetCachedArchive(site.Name, site.Name+"_siteZipArchive", "", site.DBZipURL)
assert.NoError(err)
err = app.ImportDB(cachedArchive, "", false, false, "db")
assert.NoError(err)
assert.FileExists("hello-pre-import-db-" + app.Name)
assert.FileExists("hello-post-import-db-" + app.Name)
_ = os.RemoveAll("hello-pre-import-db-" + app.Name)
_ = os.RemoveAll("hello-post-import-db-" + app.Name)
}
if site.FullSiteTarballURL != "" {
_, cachedArchive, err := testcommon.GetCachedArchive(site.Name, site.Name+"_FullSiteTarballURL", "", site.FullSiteTarballURL)
assert.NoError(err)
err = app.ImportDB(cachedArchive, "data.sql", false, false, "db")
assert.NoError(err, "Failed to find data.sql at root of tarball %s", cachedArchive)
assert.FileExists("hello-pre-import-db-" + app.Name)
assert.FileExists("hello-post-import-db-" + app.Name)
_ = os.RemoveAll("hello-pre-import-db-" + app.Name)
_ = os.RemoveAll("hello-post-import-db-" + app.Name)
}
app.Hooks = nil
for _, db := range []string{"db", "extradb"} {
// Import from stdin, make sure that works
inputFile := filepath.Join(testDir, "testdata", t.Name(), "stdintable.sql")
f, err := os.Open(inputFile)
require.NoError(t, err)
// nolint: errcheck
defer f.Close()
savedStdin := os.Stdin
os.Stdin = f
err = app.ImportDB("", "", false, false, db)
os.Stdin = savedStdin
assert.NoError(err)
out, _, err := app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: fmt.Sprintf(`echo "SHOW DATABASES LIKE '%s'; SELECT COUNT(*) FROM stdintable;" | mysql -N %s`, db, db),
})
assert.NoError(err)
assert.Equal(out, fmt.Sprintf("%s\n2\n", db))
// Import 2-user users.sql into users table
path := filepath.Join(testDir, "testdata", t.Name(), "users.sql")
err = app.ImportDB(path, "", false, false, db)
assert.NoError(err)
out, stderr, err := app.Exec(&ddevapp.ExecOpts{
Service: "db",
Cmd: fmt.Sprintf(`echo "SELECT COUNT(*) AS TOTALNUMBEROFTABLES FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s';" | mysql -N %s`, db, db),
})
assert.NoError(err, "exec failed: %v", stderr)
assert.Equal("1\n", out)