-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate_templates.go
4235 lines (3691 loc) · 156 KB
/
create_templates.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 main
import (
"io/ioutil"
"strings"
"text/template"
"log"
"os"
)
// substituteGraves replaces each occurence of the sequence "%%GRAVE%%" with a
// single grave (backtick) rune. In this source file, all templates are quoted in
// graves, but some templates contain graves, and a grave within a grave causes a
// syntax error. The solution is to replace the graves in the template with
// "%%GRAVE%% and then pre-process the template before use.
func substituteGraves(s string) string {
return strings.Replace(s, "%%GRAVE%%", "\x60", -1)
}
// createTemplateFromFile creates a template from a file. The file is in the
// templates directory wherever the scaffolder is installed, and that is out of our
// control, so this should only be called when the "templatedir" command line
// argument is specified.
func createTemplateFromFile(templateName string) *template.Template {
log.SetPrefix("createTemplate() ")
templateFile := templateDir + templateName
buf, err := ioutil.ReadFile(templateFile)
if err != nil {
log.Printf("cannot open template file %s - %s ",
templateFile, err.Error())
os.Exit(-1)
}
tp := string(buf)
tp = substituteGraves(tp)
return template.Must(template.New(templateName).Parse(tp))
}
func createTemplates(useBuiltIn bool) {
templateName := "controller.go.template"
if useBuiltIn {
if verbose {
log.Printf("creating template %s from builtin template", templateName)
}
templateText := `
{{$resourceNameLower := .NameWithLowerFirst}}
{{$resourceNameUpper := .NameWithUpperFirst}}
package {{.NameWithLowerFirst}}
{{.Imports}}
// Generated by the goblimey scaffold generator. You are STRONGLY
// recommended not to alter this file, as it will be overwritten next time the
// scaffolder is run. For the same reason, do not commit this file to a
// source code repository. Commit the json specification which was used to
// produce it.
// Package {{.PluralNameWithLowerFirst}} provides the controller for the {{.PluralNameWithLowerFirst}} resource. It provides a
// set of action functions that are triggered by HTTP requests and implement the
// Create, Read, Update and Delete (CRUD) operations on the {{.PluralNameWithLowerFirst}} resource:
//
// GET {{.PluralNameWithLowerFirst}}/ - runs Index() to list all {{.PluralNameWithLowerFirst}}
// GET {{.PluralNameWithLowerFirst}}/n - runs Show() to display the details of the {{.NameWithLowerFirst}} with ID n
// GET {{.PluralNameWithLowerFirst}}/create - runs New() to display the page to create a {{.NameWithLowerFirst}} using any data in the form to pre-populate it
// PUT {{.PluralNameWithLowerFirst}}/n - runs Create() to create a new {{.NameWithLowerFirst}} using the data in the supplied form
// GET {{.PluralNameWithLowerFirst}}/n/edit - runs Edit() to display the page to edit the {{.NameWithLowerFirst}} with ID n, using any data in the form to pre-populate it
// PUT {{.PluralNameWithLowerFirst}}/n - runs Update() to update the {{.NameWithLowerFirst}} with ID n using the data in the form
// DELETE {{.PluralNameWithLowerFirst}}/n - runs Delete() to delete the {{.NameWithLowerFirst}} with id n
type Controller struct {
services services.Services
verbose bool
}
// MakeController is a factory that creates a {{.PluralNameWithLowerFirst}} controller
func MakeController(services services.Services, verbose bool) Controller {
var controller Controller
controller.SetServices(services)
controller.SetVerbose(verbose)
return controller
}
// Index fetches a list of all valid {{.PluralNameWithLowerFirst}} and displays the index page.
func (c Controller) Index(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.ListForm) {
log.SetPrefix("Index()")
c.List{{.PluralNameWithUpperFirst}}(req, resp, form)
return
}
// Show displays the details of the {{.NameWithLowerFirst}} with the ID given in the URI.
func (c Controller) Show(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("Show()")
repository := c.services.{{.NameWithUpperFirst}}Repository()
// Get the details of the {{.NameWithLowerFirst}} with the given ID.
{{.NameWithLowerFirst}}, err := repository.FindByID(form.{{.NameWithUpperFirst}}().ID())
if err != nil {
// no such {{.NameWithLowerFirst}}. Display index page with error message
em := "no such {{.NameWithLowerFirst}}"
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
// The {{.NameWithLowerFirst}} in the form contains just an ID. Replace it with the
// complete {{.NameWithLowerFirst}} record that we just fetched.
form.Set{{.NameWithUpperFirst}}({{.NameWithLowerFirst}})
page := c.services.Template("{{.NameWithLowerFirst}}", "Show")
if page == nil {
em := fmt.Sprintf("internal error displaying Show page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err = page.Execute(resp.ResponseWriter, form)
if err != nil {
em := fmt.Sprintf("error displaying page - %s", err.Error())
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
return
}
// New displays the page to create a {{.NameWithLowerFirst}},
func (c Controller) New(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("New()")
// Display the page.
page := c.services.Template("{{.NameWithLowerFirst}}", "Create")
if page == nil {
em := fmt.Sprintf("internal error displaying Create page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err := page.Execute(resp.ResponseWriter, form)
if err != nil {
log.Printf("error displaying new page - %s", err.Error())
em := fmt.Sprintf("error displaying page - %s", err.Error())
c.ErrorHandler(req, resp, em)
return
}
}
// Create creates a {{.NameWithLowerFirst}} using the data from the HTTP form displayed
// by a previous NEW request.
func (c Controller) Create(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("Create()")
if !(form.Valid()) {
// validation errors. Return to create screen with error messages in the form data
if c.verbose {
log.Printf("Validation failed\n")
}
page := c.services.Template("{{.NameWithLowerFirst}}", "Create")
if page == nil {
em := fmt.Sprintf("internal error displaying Create page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err := page.Execute(resp.ResponseWriter, &form)
if err != nil {
em := fmt.Sprintf("Internal error while preparing create form after failed validation - %s",
err.Error())
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
return
}
// Create a {{.NameWithLowerFirst}} in the database using the validated data in the form
repository := c.services.{{.NameWithUpperFirst}}Repository()
created{{.NameWithUpperFirst}}, err := repository.Create(form.{{.NameWithUpperFirst}}())
if err != nil {
// Failed to create {{.NameWithLowerFirst}}. Display index page with error message.
em := fmt.Sprintf("Could not create {{.NameWithLowerFirst}} %s - %s", form.{{.NameWithUpperFirst}}().DisplayName(), err.Error())
c.ErrorHandler(req, resp, em)
return
}
// Success! {{.NameWithUpperFirst}} created. Display index page with confirmation notice
notice := fmt.Sprintf("created {{.NameWithLowerFirst}} %s", created{{.NameWithUpperFirst}}.DisplayName())
if c.verbose {
log.Printf("%s\n", notice)
}
listForm := c.services.Make{{.NameWithUpperFirst}}ListForm()
listForm.SetNotice(notice)
c.List{{.PluralNameWithUpperFirst}}(req, resp, listForm)
return
}
// Edit fetches the data for the {{.PluralNameWithLowerFirst}} record with the given ID and displays
// the edit page, populated with that data.
func (c Controller) Edit(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("Edit() ")
id := form.{{.NameWithUpperFirst}}().ID()
repository := c.services.{{.NameWithUpperFirst}}Repository()
// Get the existing data for the {{.NameWithLowerFirst}}
{{.NameWithLowerFirst}}, err := repository.FindByID(id)
if err != nil {
// No such {{.NameWithLowerFirst}}. Display index page with error message.
em := err.Error()
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
// Got the {{.NameWithLowerFirst}} with the given ID. Put it into the form and validate it.
// If the data is invalid, continue - the user may be trying to fix it.
form.Set{{.NameWithUpperFirst}}({{.NameWithLowerFirst}})
if c.verbose && !form.Validate() {
em := fmt.Sprintf("invalid record in the {{.PluralNameWithLowerFirst}} database - %s",
{{.NameWithLowerFirst}}.String())
log.Printf("%s\n", em)
}
// Display the edit page
page := c.services.Template("{{.NameWithLowerFirst}}", "Edit")
if page == nil {
em := fmt.Sprintf("internal error displaying Edit page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err = page.Execute(resp.ResponseWriter, form)
if err != nil {
// error while preparing edit page
log.Printf("%s: error displaying edit page - %s", err.Error())
em := fmt.Sprintf("error displaying page - %s", err.Error())
c.ErrorHandler(req, resp, em)
}
}
// Update responds to a PUT request. For example:
// PUT /{{.PluralNameWithLowerFirst}}/1
// It's invoked by the form displayed by a previous Edit request. If the ID in the URI is
// valid and the request parameters from the form specify valid {{.PluralNameWithLowerFirst}} data, it updates the
// record and displays the index page with a confirmation message, otherwise it displays
// the edit page again with the given data and some error messages.
func (c Controller) Update(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("Update() ")
if !form.Valid() {
// The supplied data is invalid. The validator has set error messages.
// Return to the edit screen.
if c.verbose {
log.Printf("Validation failed\n")
}
page := c.services.Template("{{.NameWithLowerFirst}}", "Edit")
if page == nil {
em := fmt.Sprintf("internal error displaying Edit page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err := page.Execute(resp.ResponseWriter, form)
if err != nil {
log.Printf("%s: error displaying edit page - %s", err.Error())
em := fmt.Sprintf("error displaying page - %s", err.Error())
c.ErrorHandler(req, resp, em)
return
}
return
}
if form.{{.NameWithUpperFirst}}() == nil {
em := fmt.Sprint("internal error - form should contain an updated {{.NameWithLowerFirst}} record")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
// Get the {{.NameWithLowerFirst}} specified in the form from the DB.
// If that fails, the id in the form doesn't match any record.
repository := c.services.{{.NameWithUpperFirst}}Repository()
{{.NameWithLowerFirst}}, err := repository.FindByID(form.{{.NameWithUpperFirst}}().ID())
if err != nil {
// There is no {{.NameWithLowerFirst}} with this ID. The ID is chosen by the user from a
// supplied list and it should always be valid, so there's something screwy
// going on. Display the index page with an error message.
em := fmt.Sprintf("error searching for {{.NameWithLowerFirst}} with id %s - %s",
form.{{.NameWithUpperFirst}}().ID(), err.Error())
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
// We have a matching {{.NameWithLowerFirst}} from the DB.
if c.verbose {
log.Printf("got {{.NameWithLowerFirst}} %v\n", {{.NameWithLowerFirst}})
}
// we have a record and valid new values. Update.
{{range .Fields}}
{{$resourceNameLower}}.Set{{.NameWithUpperFirst}}(form.{{$resourceNameUpper}}().{{.NameWithUpperFirst}}())
{{end}}
if c.verbose {
log.Printf("updating {{.NameWithLowerFirst}} to %v\n", {{.NameWithLowerFirst}})
}
_, err = repository.Update({{.NameWithLowerFirst}})
if err != nil {
// The commit failed. Display the edit page with an error message
em := fmt.Sprintf("Could not update {{.NameWithLowerFirst}} - %s", err.Error())
log.Printf("%s\n", em)
form.SetErrorMessage(em)
page := c.services.Template("{{.NameWithLowerFirst}}", "Edit")
if page == nil {
em := fmt.Sprintf("internal error displaying Edit page - no HTML template")
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
err = page.Execute(resp.ResponseWriter, form)
if err != nil {
// Error while recovering from another error. This is looking like a habit!
em := fmt.Sprintf("Internal error while preparing edit page after failing to update {{.NameWithLowerFirst}} in DB - %s", err.Error())
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
} else {
return
}
}
// Success! Display the index page with a confirmation notice
notice := fmt.Sprintf("updated {{.NameWithLowerFirst}} %s", form.{{.NameWithUpperFirst}}().DisplayName())
if c.verbose {
log.Printf("%s:\n", notice)
}
listForm := c.services.Make{{.NameWithUpperFirst}}ListForm()
listForm.SetNotice(notice)
c.List{{.PluralNameWithUpperFirst}}(req, resp, listForm)
return
}
// Delete responds to a DELETE request and deletes the record with the given ID,
// eg DELETE http://server:port/{{.PluralNameWithLowerFirst}}/1.
func (c Controller) Delete(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.SingleItemForm) {
log.SetPrefix("Delete()")
repository := c.services.{{.NameWithUpperFirst}}Repository()
// Attempt the delete
_, err := repository.DeleteByID(form.{{.NameWithUpperFirst}}().ID())
if err != nil {
// failed - cannot delete {{.NameWithLowerFirst}}
em := fmt.Sprintf("Cannot delete {{.NameWithLowerFirst}} with id %d - %s",
form.{{.NameWithUpperFirst}}().ID(), err.Error())
log.Printf("%s\n", em)
c.ErrorHandler(req, resp, em)
return
}
// Success - {{.NameWithLowerFirst}} deleted. Display the index view with a notification.
listForm := c.services.Make{{.NameWithUpperFirst}}ListForm()
notice := fmt.Sprintf("deleted {{.NameWithLowerFirst}} with id %d",
form.{{.NameWithUpperFirst}}().ID())
if c.verbose {
log.Printf("%s:\n", notice)
}
listForm.SetNotice(notice)
c.List{{.PluralNameWithUpperFirst}}(req, resp, listForm)
return
}
// ErrorHandler displays the index page with an error message
func (c Controller) ErrorHandler(req *restful.Request, resp *restful.Response,
errormessage string) {
form := c.services.Make{{.NameWithUpperFirst}}ListForm()
form.SetErrorMessage(errormessage)
c.List{{.PluralNameWithUpperFirst}}(req, resp, form)
}
// SetServices sets the services.
func (c *Controller) SetServices(services services.Services) {
c.services = services
}
// SetVerbose sets the verbosity level.
func (c *Controller) SetVerbose(verbose bool) {
c.verbose = verbose
}
/*
* The List{{.PluralNameWithUpperFirst}} helper method fetches a list of {{.PluralNameWithLowerFirst}} and displays the
* index page. It's used to fulfil an index request but the index page is
* also used as the last page of a sequence of requests (for example new,
* create, index). If the sequence was successful, the form may contain a
* confirmation note. If the sequence failed, the form should contain an error
* message.
*/
func (c Controller) List{{.PluralNameWithUpperFirst}}(req *restful.Request, resp *restful.Response,
form {{.NameWithLowerFirst}}Forms.ListForm) {
log.SetPrefix("Controller.List{{.PluralNameWithUpperFirst}}() ")
repository := c.services.{{.NameWithUpperFirst}}Repository()
{{.PluralNameWithLowerFirst}}List, err := repository.FindAll()
if err != nil {
em := fmt.Sprintf("error getting the list of {{.PluralNameWithLowerFirst}} - %s", err.Error())
log.Printf("%s\n", em)
form.SetErrorMessage(em)
}
if c.verbose{
log.Printf("%d {{.PluralNameWithLowerFirst}}", len({{.PluralNameWithLowerFirst}}List))
}
if len({{.PluralNameWithLowerFirst}}List) <= 0 {
form.SetNotice("there are no {{.PluralNameWithLowerFirst}} currently set up")
}
form.Set{{.PluralNameWithUpperFirst}}({{.PluralNameWithLowerFirst}}List)
// Display the index page
page := c.services.Template("{{.NameWithLowerFirst}}", "Index")
if page == nil {
log.Printf("no Index page for {{.NameWithLowerFirst}} controller")
utilities.Dead(resp)
return
}
err = page.Execute(resp.ResponseWriter, form)
if err != nil {
/*
* Error while displaying the index page. We handle most internal
* errors by displaying the controller's index page. That's just failed,
* so fall back to the static error page.
*/
log.Printf(err.Error())
page = c.services.Template("html", "Error")
if page == nil {
log.Printf("no Error page")
utilities.Dead(resp)
return
}
err = page.Execute(resp.ResponseWriter, form)
if err != nil {
// Can't display the static error page either. Bale out.
em := fmt.Sprintf("fatal error - failed to display error page for error %s\n", err.Error())
log.Printf(em)
panic(em)
}
return
}
}
`
templateText = substituteGraves(templateText)
templateMap[templateName] =
template.Must(template.New(templateName).Parse(templateText))
} else {
if verbose {
log.Printf("creating template %s from file %s", templateName, templateDir+templateName)
}
templateMap[templateName] = createTemplateFromFile(templateName)
}
templateName = "controller.test.go.template"
if useBuiltIn {
if verbose {
log.Printf("creating template %s from builtin template", templateName)
}
templateText := `
{{$resourceNameLower := .NameWithLowerFirst}}
{{$resourceNameUpper := .NameWithUpperFirst}}
{{$resourceNamePluralUpper := .PluralNameWithUpperFirst}}
package {{.NameWithLowerFirst}}
{{.Imports}}
// Generated by the goblimey scaffold generator. You are STRONGLY
// recommended not to alter this file, as it will be overwritten next time the
// scaffolder is run. For the same reason, do not commit this file to a
// source code repository. Commit the json specification which was used to
// produce it.
// Unit tests for the {{.NameWithLowerFirst}} controller. Uses mock objects
// created by pegomock.
var panicValue string
{{/* This creates the expected values using the field names and the test
values, something like:
var expectedName1 string = "s1"
var expectedAge1 int64 = 2
var expectedName2 string = "s3"
var expectedAge2 int64 = 4 */}}
{{range $index, $element := .Fields}}
{{if eq .Type "string"}}
var expected{{.NameWithUpperFirst}}1 {{.GoType}} = "{{index .TestValues 0}}"
{{else}}
var expected{{.NameWithUpperFirst}}1 {{.GoType}} = {{index .TestValues 0}}
{{end}}
{{if eq .Type "string"}}
var expected{{.NameWithUpperFirst}}2 {{.GoType}} = "{{index .TestValues 1}}"
{{else}}
var expected{{.NameWithUpperFirst}}2 {{.GoType}} = {{index .TestValues 1}}
{{end}}
{{end}}
// TestUnitIndexWithOne{{.NameWithUpperFirst}} checks that the Index method of the
// {{.NameWithLowerFirst}} controller handles a list of {{.PluralNameWithLowerFirst}} from FindAll() containing one {{.NameWithLowerFirst}}.
func TestUnitIndexWithOne{{.NameWithUpperFirst}}(t *testing.T) {
var expectedID1 uint64 = 42
pegomock.RegisterMockTestingT(t)
// Create a list containing one {{.NameWithLowerFirst}}.
expected{{.NameWithUpperFirst}}1 := {{.NameWithLowerFirst}}.MakeInitialised{{$resourceNameUpper}}(expectedID1, {{range .Fields}}expected{{.NameWithUpperFirst}}1{{if not .LastItem}}, {{end}}{{end}})
expected{{.NameWithUpperFirst}}List := make([]{{.NameWithLowerFirst}}.{{.NameWithUpperFirst}}, 1)
expected{{.NameWithUpperFirst}}List[0] = expected{{.NameWithUpperFirst}}1
// Create the mocks and dummy objects.
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "GET"
var request restful.Request
request.Request = &httpRequest
writer := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = writer
mockTemplate := mocks.NewMockTemplate()
mockRepository := mock{{.NameWithUpperFirst}}.NewMockRepository()
innerPageMap := make(map[string]retrofitTemplate.Template)
innerPageMap["Index"] = mockTemplate
pageMap := make(map[string]map[string]retrofitTemplate.Template)
pageMap["{{.NameWithLowerFirst}}"] = innerPageMap
// Create a service that returns the mock repository and templates.
var services services.ConcreteServices
services.Set{{.NameWithUpperFirst}}Repository(mockRepository)
services.SetTemplates(&pageMap)
// Create the form
form := {{.NameWithLowerFirst}}Forms.MakeListForm()
// Expect the controller to call the {{.NameWithLowerFirst}} repository's FindAll method. Return
// the list containing one {{.NameWithLowerFirst}}.
pegomock.When(mockRepository.FindAll()).ThenReturn(expected{{.NameWithUpperFirst}}List, nil)
// The request supplies method "GET" and URI "/{{.PluralNameWithLowerFirst}}". Expect
// template.Execute to be called and return nil (no error).
pegomock.When(mockTemplate.Execute(writer, form)).ThenReturn(nil)
// Run the test.
var controller Controller
controller.SetServices(&services)
controller.Index(&request, &response, form)
// We expect that the form contains the expected {{.NameWithLowerFirst}} list -
// one {{.NameWithLowerFirst}} object with contents as expected.
if form.{{.PluralNameWithUpperFirst}}() == nil {
t.Errorf("Expected a list, got nil")
}
if len(form.{{.PluralNameWithUpperFirst}}()) != 1 {
t.Errorf("Expected a list of 1, got %d", len(form.{{.PluralNameWithUpperFirst}}()))
}
if form.{{.PluralNameWithUpperFirst}}()[0].ID() != expectedID1 {
t.Errorf("Expected ID %d, got %d",
expectedID1, form.{{.PluralNameWithUpperFirst}}()[0].ID())
}
{{range .Fields}}
if form.{{$resourceNamePluralUpper}}()[0].{{.NameWithUpperFirst}}() != expected{{.NameWithUpperFirst}}1 {
t.Errorf("Expected {{.NameWithLowerFirst}} %v, got %v",
expected{{.NameWithUpperFirst}}1, form.{{$resourceNamePluralUpper}}()[0].{{.NameWithUpperFirst}}())
}
{{end}}
}
// TestUnitIndexWithErrorWhenFetching{{.PluralNameWithUpperFirst}} checks that the {{.NameWithLowerFirst}} controller's
// Index() method handles errors from FindAll() correctly.
func TestUnitIndexWithErrorWhenFetching{{.PluralNameWithUpperFirst}}(t *testing.T) {
log.SetPrefix("TestUnitIndexWithErrorWhenFetching{{.PluralNameWithUpperFirst}} ")
log.Printf("This test is expected to provoke error messages in the log")
expectedErr := errors.New("Test Error Message")
expectedErrorMessage := "error getting the list of {{.PluralNameWithLowerFirst}} - Test Error Message"
// Create the mocks and dummy objects.
pegomock.RegisterMockTestingT(t)
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "GET"
var request restful.Request
request.Request = &httpRequest
writer := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = writer
mockTemplate := mocks.NewMockTemplate()
mockRepository := mock{{.NameWithUpperFirst}}.NewMockRepository()
// Create the form
form := {{.NameWithLowerFirst}}Forms.MakeListForm()
// Expect the controller to call the {{.NameWithLowerFirst}} repository's FindAll method. Return
// the list containing one {{.NameWithLowerFirst}}.
pegomock.When(mockRepository.FindAll()).ThenReturn(nil, expectedErr)
// Expect the controller to call the tenmplate's Execute() method. Return
// nil (no error).
pegomock.When(mockTemplate.Execute(writer, form)).ThenReturn(nil)
innerPageMap := make(map[string]retrofitTemplate.Template)
innerPageMap["Index"] = mockTemplate
pageMap := make(map[string]map[string]retrofitTemplate.Template)
pageMap["{{.NameWithLowerFirst}}"] = innerPageMap
// Create a service that returns the mock repository and templates.
var services services.ConcreteServices
services.Set{{.NameWithUpperFirst}}Repository(mockRepository)
services.SetTemplates(&pageMap)
// Create the controller and run the test.
controller := MakeController(&services, false)
controller.Index(&request, &response, form)
// Verify that the form contains the expected error message.
if form.ErrorMessage() != expectedErrorMessage {
t.Errorf("Expected error message to be %s actually %s", expectedErrorMessage, form.ErrorMessage())
}
}
// TestUnitIndexWithManyFailures checks that the {{.PluralNameWithUpperFirst}} controller's
// Index() method handles a series of errors correctly.
//
// Panic handling based on http://stackoverflow.com/questions/31595791/how-to-test-panics
//
func TestUnitIndexWithManyFailures(t *testing.T) {
log.SetPrefix("TestUnitIndexWithManyFailures ")
log.Printf("This test is expected to provoke error messages in the log")
em1 := "first error message"
expectedFirstErrorMessage := errors.New(em1)
em2 := "second error message"
expectedSecondErrorMessage := errors.New(em2)
em3 := "final error message"
finalErrorMessage := errors.New(em3)
// Create the mocks and dummy objects.
pegomock.RegisterMockTestingT(t)
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "GET"
var request restful.Request
request.Request = &httpRequest
mockResponseWriter := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = mockResponseWriter
mockIndexTemplate := mocks.NewMockTemplate()
mockErrorTemplate := mocks.NewMockTemplate()
mockRepository := mock{{.NameWithUpperFirst}}.NewMockRepository()
// Create a template map containing the mock templates
pageMap := make(map[string]map[string]retrofitTemplate.Template)
pageMap["html"] = make(map[string]retrofitTemplate.Template)
pageMap["html"]["Error"] = mockErrorTemplate
pageMap["{{.NameWithLowerFirst}}"] = make(map[string]retrofitTemplate.Template)
pageMap["{{.NameWithLowerFirst}}"]["Index"] = mockIndexTemplate
// Create a service that returns the mock repository and templates.
var services services.ConcreteServices
services.Set{{.NameWithUpperFirst}}Repository(mockRepository)
services.SetTemplates(&pageMap)
// Create the form
form := {{.NameWithLowerFirst}}Forms.MakeListForm()
// Expectations:
// Index will run List{{.PluralNameWithUpperFirst}} which will call the {{.NameWithLowerFirst}}
// repository's FindAll(). Make that return an error, then List{{.PluralNameWithUpperFirst}}
// will get the Index page from the template and call its Execute method. Make
// that fail, and the controller will get the error page and call its Execute
// method. Make that fail and the app will panic with a message "fatal error -
// failed to display error page for error ", followed by the error message from
// the last Execute call.
pegomock.When(mockRepository.FindAll()).ThenReturn(nil,
expectedFirstErrorMessage)
pegomock.When(mockIndexTemplate.Execute(mockResponseWriter, form)).
ThenReturn(expectedSecondErrorMessage)
pegomock.When(mockErrorTemplate.Execute(mockResponseWriter, form)).
ThenReturn(finalErrorMessage)
// Expect a panic, catch it and check the value. (If there is no panic,
// this raises an error.)
defer func() {
r := recover()
if r == nil {
t.Errorf("Expected the Index call to panic")
} else {
em := fmt.Sprintf("%s", r)
// Verify that the panic value is as expected.
if !strings.Contains(em, em3) {
t.Errorf("Expected a panic with value containing \"%s\" actually \"%s\"",
em3, em)
}
}
}()
// Run the test.
controller := MakeController(&services, false)
controller.Index(&request, &response, form)
// Verify that the form has an error message containing the expected text.
if strings.Contains(form.ErrorMessage(), em1) {
t.Errorf("Expected error message to be \"%s\" actually \"%s\"",
expectedFirstErrorMessage, form.ErrorMessage())
}
// Verify that the list of {{.PluralNameWithLowerFirst}} is nil
if form.{{.PluralNameWithUpperFirst}}() != nil {
t.Errorf("Expected the list of {{.PluralNameWithLowerFirst}} to be nil. Actually contains %d entries",
len(form.{{.PluralNameWithUpperFirst}}()))
}
}
// TestUnitSuccessfulCreate checks that the {{.NameWithLowerFirst}} controller's Create method
// correctly handles a successful attempt to create a {{.NameWithLowerFirst}} in the database.
func TestUnitSuccessfulCreate(t *testing.T) {
log.SetPrefix("TestUnitSuccessfulCreate ")
expectedNoticeFragment := "created {{.NameWithLowerFirst}}"
{{range .Fields}}
{{if not .ExcludeFromDisplay}}
{{if eq .Type "int"}}
expected{{.NameWithUpperFirst}}1_str := fmt.Sprintf("%d", expected{{.NameWithUpperFirst}}1)
{{end}}
{{if eq .Type "float"}}
expected{{.NameWithUpperFirst}}1_str := fmt.Sprintf("%f", expected{{.NameWithUpperFirst}}1)
{{end}}
{{if eq .Type "bool"}}
expected{{.NameWithUpperFirst}}1_str := fmt.Sprintf("%v", expected{{.NameWithUpperFirst}}1)
{{end}}
{{end}}
{{end}}
pegomock.RegisterMockTestingT(t)
// Create the mocks and dummy objects.
var expectedID1 uint64 = 42
expected{{.NameWithUpperFirst}}1 := {{.NameWithLowerFirst}}.MakeInitialised{{$resourceNameUpper}}(expectedID1, {{range .Fields}}expected{{.NameWithUpperFirst}}1{{if not .LastItem}}, {{end}}{{end}})
singleItemForm := {{.NameWithLowerFirst}}Forms.MakeInitialisedSingleItemForm(expected{{.NameWithUpperFirst}}1)
listForm := {{.NameWithLowerFirst}}Forms.MakeListForm()
{{.PluralNameWithLowerFirst}} := make([]{{.NameWithLowerFirst}}.{{.NameWithUpperFirst}}, 1)
{{.PluralNameWithLowerFirst}}[0] = expected{{.NameWithUpperFirst}}1
listForm.Set{{.PluralNameWithUpperFirst}}({{.PluralNameWithLowerFirst}})
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}/42" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}/42"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "POST"
var request restful.Request
request.Request = &httpRequest
writer := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = writer
mockIndexTemplate := mocks.NewMockTemplate()
mockCreateTemplate := mocks.NewMockTemplate()
mockRepository := mock{{.NameWithUpperFirst}}.NewMockRepository()
mockServices := mocks.NewMockServices()
// Create a template map containing the mock templates
pageMap := make(map[string]map[string]retrofitTemplate.Template)
pageMap["{{.NameWithLowerFirst}}"] = make(map[string]retrofitTemplate.Template)
pageMap["{{.NameWithLowerFirst}}"]["Index"] = mockIndexTemplate
pageMap["{{.NameWithLowerFirst}}"]["Create"] = mockCreateTemplate
// Set expectations. The controller will display the Create template,
// get some data, create a repository and use it to create a model object.
// Then it will use the Index template to display the index page.
pegomock.When(mockServices.Template("{{.NameWithLowerFirst}}", "Create")).ThenReturn(mockCreateTemplate)
pegomock.When(mockServices.{{.NameWithUpperFirst}}Repository()).ThenReturn(mockRepository)
pegomock.When(mockRepository.Create(expected{{.NameWithUpperFirst}}1)).
ThenReturn(expected{{.NameWithUpperFirst}}1, nil)
pegomock.When(mockServices.Make{{.NameWithUpperFirst}}ListForm()).ThenReturn(listForm)
pegomock.When(mockServices.Template("{{.NameWithLowerFirst}}", "Index")).ThenReturn(mockIndexTemplate)
pegomock.When(mockRepository.FindAll()).ThenReturn({{.PluralNameWithLowerFirst}}, nil)
pegomock.When(mockCreateTemplate.Execute(response.ResponseWriter, listForm)).
ThenReturn(nil)
// Run the test.
controller := MakeController(mockServices, false)
controller.Create(&request, &response, singleItemForm)
// Verify that the form contains a notice with the expected contents.
if !strings.Contains(listForm.Notice(), expectedNoticeFragment) {
t.Errorf("Expected notice to contain \"%s\" actually \"%s\"",
expectedNoticeFragment, listForm.Notice())
}
{{range .Fields}}
{{if not .ExcludeFromDisplay}}
{{if eq .Type "string"}}
if !strings.Contains(listForm.Notice(), expected{{.NameWithUpperFirst}}1) {
t.Errorf("Expected notice to contain \"%s\" actually \"%s\"",
expected{{.NameWithUpperFirst}}1, listForm.Notice())
}
{{else}}
if !strings.Contains(listForm.Notice(), expected{{.NameWithUpperFirst}}1_str) {
t.Errorf("Expected notice to contain \"%s\" actually \"%s\"",
expected{{.NameWithUpperFirst}}1_str, listForm.Notice())
}
{{end}}
{{end}}
{{end}}
}
// TestUnitCreateFailsWithMissingFields checks that the {{.NameWithLowerFirst}} controller's
// Create method correctly handles invalid data from the HTTP request. Note: by
// the time the code under test runs, number and boolean fields have already been
// extracted from the HTML form and converted, so the only fields that can be made
// invalid are mandatory string fields. If there are none of those, the test will
// run successfully but it will do nothing useful.
//
// The test uses pegomock to provide mocks.
func TestUnitCreateFailsWithMissingFields(t *testing.T) {
log.SetPrefix("TestUnitCreateFailsWithMissingFields ")
// This test only makes sense when there are mandatory fields in the form.
mandatoryFieldCount := 0
{{range .Fields}}
{{if and .Mandatory (eq .Type "string")}}
mandatoryFieldCount++ // {{.NameWithLowerFirst}} is mandatory
{{end}}
{{end}}
if mandatoryFieldCount > 0 {
{{range .Fields}}
{{if and .Mandatory (eq .Type "string")}}
expectedErrorMessage{{.NameWithUpperFirst}} := "you must specify the {{.NameWithLowerFirst}}"
{{end}}
{{end}}
pegomock.RegisterMockTestingT(t)
var expectedID1 uint64 = 42
// supply empty string for mandatory string fields, the given values for others.
expected{{.NameWithUpperFirst}}1 := {{.NameWithLowerFirst}}.MakeInitialised{{$resourceNameUpper}}(expectedID1, {{range .Fields}}{{if and .Mandatory (eq .Type "string")}}" "{{else}}expected{{.NameWithUpperFirst}}1{{end}}{{if not .LastItem}}, {{end}}{{end}})
singleItemForm := {{.NameWithLowerFirst}}Forms.MakeInitialisedSingleItemForm(expected{{.NameWithUpperFirst}}1)
// Create the mocks and dummy objects.
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}/42" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}/42"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "POST"
var request restful.Request
request.Request = &httpRequest
writer := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = writer
mockTemplate := mocks.NewMockTemplate()
// Create a services layer that returns the other mocks.
mockServices := mocks.NewMockServices()
pegomock.When(mockServices.Template("{{.NameWithLowerFirst}}", "Create")).ThenReturn(mockTemplate)
// Run the test.
// In the app, the form is validated before the controller method is called.
// Validate the fome and check that it fails.
valid := singleItemForm.Validate()
if valid {
t.Errorf("Expected the validation method to return false (invalid)")
}
// Check that the validation method set the valid flag in the form
if singleItemForm.Valid() {
t.Errorf("Expected the form to be marked as invalid")
}
controller := MakeController(mockServices, false)
controller.Create(&request, &response, singleItemForm)
// If the {{.NameWithLowerFirst}} has mandatory string fields, verify that the
// form contains the expected error messages.
{{range .Fields}}
{{if and .Mandatory (eq .Type "string")}}
if singleItemForm.ErrorForField("{{.NameWithUpperFirst}}") != expectedErrorMessage{{.NameWithUpperFirst}} {
t.Errorf("Expected error message to be %s actually %s",
expectedErrorMessage{{.NameWithUpperFirst}}, singleItemForm.ErrorForField("{{.NameWithUpperFirst}}"))
}
{{end}}
{{end}}
}
}
// TestUnitCreateFailsWithDBError checks that the {{.NameWithLowerFirst}} handler's Create method
// correctly handles an error from the repository while attempting to create a
// {{.NameWithLowerFirst}} in the database.
func TestUnitCreateFailsWithDBError(t *testing.T) {
log.SetPrefix("TestUnitCreateFailsWithDBError ")
expectedErrorMessage := "some error"
expectedErrorMessageLeader := "Could not create {{.NameWithLowerFirst}}"
pegomock.RegisterMockTestingT(t)
// Create the mocks and dummy objects.
var expectedID1 uint64 = 42
expected{{.NameWithUpperFirst}}1 := {{.NameWithLowerFirst}}.MakeInitialised{{$resourceNameUpper}}(expectedID1, {{range .Fields}}expected{{.NameWithUpperFirst}}1{{if not .LastItem}}, {{end}}{{end}})
singleItemForm := {{.NameWithLowerFirst}}Forms.MakeInitialisedSingleItemForm(expected{{.NameWithUpperFirst}}1)
listForm := {{.NameWithLowerFirst}}Forms.MakeListForm()
var url url.URL
url.Opaque = "/{{.PluralNameWithLowerFirst}}/42" // url.RequestURI() will return "/{{.PluralNameWithLowerFirst}}/42"
var httpRequest http.Request
httpRequest.URL = &url
httpRequest.Method = "POST"
var request restful.Request
request.Request = &httpRequest
writer := mocks.NewMockResponseWriter()
var response restful.Response
response.ResponseWriter = writer
mockIndexTemplate := mocks.NewMockTemplate()
mockCreateTemplate := mocks.NewMockTemplate()
// Create a services layer that returns the mock create template.
mockRepository := mock{{.NameWithUpperFirst}}.NewMockRepository()
mockServices := mocks.NewMockServices()
pegomock.When(mockServices.Template("{{.NameWithLowerFirst}}", "Create")).
ThenReturn(mockCreateTemplate)
pegomock.When(mockServices.{{.NameWithUpperFirst}}Repository()).ThenReturn(mockRepository)
pegomock.When(mockRepository.Create(expected{{.NameWithUpperFirst}}1)).
ThenReturn(nil, errors.New(expectedErrorMessage))
pegomock.When(mockServices.Template("{{.NameWithLowerFirst}}", "Index")).
ThenReturn(mockIndexTemplate)
pegomock.When(mockServices.Make{{.NameWithUpperFirst}}ListForm()).ThenReturn(listForm)
// Run the test.
controller := MakeController(mockServices, false)
controller.Create(&request, &response, singleItemForm)
// Verify that the form contains the expected error message.
if !strings.Contains(listForm.ErrorMessage(), expectedErrorMessageLeader) {
t.Errorf("Expected error message to contain \"%s\" actually \"%s\"",
expectedErrorMessageLeader, listForm.ErrorMessage())
}
if !strings.Contains(listForm.ErrorMessage(), expectedErrorMessage) {
t.Errorf("Expected error message to contain \"%s\" actually \"%s\"",
expectedErrorMessage, listForm.ErrorMessage())
}
}
// Recover from any panic and record the error.
func catchPanic() {
log.SetPrefix("catchPanic ")
if p := recover(); p != nil {
em := fmt.Sprintf("%v", p)
panicValue = em
log.Printf(em)
}
}
`
templateText = substituteGraves(templateText)
templateMap[templateName] =
template.Must(template.New(templateName).Parse(templateText))
} else {
if verbose {