MCPcopy
hub / github.com/caddyserver/caddy / TestImport

Function TestImport

modules/caddyhttp/templates/tplcontext_test.go:134–188  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

132}
133
134func TestImport(t *testing.T) {
135 for i, test := range []struct {
136 fileContent string
137 fileName string
138 shouldErr bool
139 expect string
140 }{
141 {
142 // file exists, template is defined
143 fileContent: `{{ define "imported" }}text{{end}}`,
144 fileName: "file1",
145 shouldErr: false,
146 expect: `"imported"`,
147 },
148 {
149 // file does not exit
150 fileContent: "",
151 fileName: "",
152 shouldErr: true,
153 },
154 } {
155 tplContext := getContextOrFail(t)
156 var absFilePath string
157
158 // create files for test case
159 if test.fileName != "" {
160 absFilePath := filepath.Join(fmt.Sprintf("%s", tplContext.Root), test.fileName)
161 if err := os.WriteFile(absFilePath, []byte(test.fileContent), os.ModePerm); err != nil {
162 os.Remove(absFilePath)
163 t.Fatalf("Test %d: Expected no error creating file, got: '%s'", i, err.Error())
164 }
165 }
166
167 // perform test
168 tplContext.NewTemplate("parent")
169 actual, err := tplContext.funcImport(test.fileName)
170 templateWasDefined := strings.Contains(tplContext.tpl.DefinedTemplates(), test.expect)
171 if err != nil {
172 if !test.shouldErr {
173 t.Errorf("Test %d: Expected no error, got: '%s'", i, err)
174 }
175 } else if test.shouldErr {
176 t.Errorf("Test %d: Expected error but had none", i)
177 } else if !templateWasDefined && actual != "" {
178 // template should be defined, return value should be an empty string
179 t.Errorf("Test %d: Expected template %s to be define but got %s", i, test.expect, tplContext.tpl.DefinedTemplates())
180 }
181
182 if absFilePath != "" {
183 if err := os.Remove(absFilePath); err != nil && !errors.Is(err, fs.ErrNotExist) {
184 t.Fatalf("Test %d: Expected no error removing temporary test file, got: %v", i, err)
185 }
186 }
187 }
188}
189
190func TestNestedInclude(t *testing.T) {
191 for i, test := range []struct {

Callers

nothing calls this directly

Calls 4

getContextOrFailFunction · 0.85
NewTemplateMethod · 0.80
funcImportMethod · 0.80
ErrorMethod · 0.45

Tested by

no test coverage detected