(t *testing.T)
| 15 | ) |
| 16 | |
| 17 | func TestCaddyfileAdaptToJSON(t *testing.T) { |
| 18 | // load the list of test files from the dir |
| 19 | files, err := os.ReadDir("./caddyfile_adapt") |
| 20 | if err != nil { |
| 21 | t.Errorf("failed to read caddyfile_adapt dir: %s", err) |
| 22 | } |
| 23 | |
| 24 | // prep a regexp to fix strings on windows |
| 25 | winNewlines := regexp.MustCompile(`\r?\n`) |
| 26 | |
| 27 | for _, f := range files { |
| 28 | if f.IsDir() { |
| 29 | continue |
| 30 | } |
| 31 | filename := f.Name() |
| 32 | |
| 33 | // run each file as a subtest, so that we can see which one fails more easily |
| 34 | t.Run(filename, func(t *testing.T) { |
| 35 | // read the test file |
| 36 | data, err := os.ReadFile("./caddyfile_adapt/" + filename) |
| 37 | if err != nil { |
| 38 | t.Errorf("failed to read %s dir: %s", filename, err) |
| 39 | } |
| 40 | |
| 41 | // split the Caddyfile (first) and JSON (second) parts |
| 42 | // (append newline to Caddyfile to match formatter expectations) |
| 43 | parts := strings.Split(string(data), "----------") |
| 44 | caddyfile, expected := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1]) |
| 45 | |
| 46 | // replace windows newlines in the json with unix newlines |
| 47 | expected = winNewlines.ReplaceAllString(expected, "\n") |
| 48 | |
| 49 | // replace os-specific default path for file_server's hide field |
| 50 | replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile")) |
| 51 | expected = strings.ReplaceAll(expected, `"./Caddyfile"`, string(replacePath)) |
| 52 | |
| 53 | // if the expected output is JSON, compare it |
| 54 | if len(expected) > 0 && expected[0] == '{' { |
| 55 | ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", expected) |
| 56 | if !ok { |
| 57 | t.Errorf("failed to adapt %s", filename) |
| 58 | } |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | // otherwise, adapt the Caddyfile and check for errors |
| 63 | cfgAdapter := caddyconfig.GetAdapter("caddyfile") |
| 64 | _, _, err = cfgAdapter.Adapt([]byte(caddyfile), nil) |
| 65 | if err == nil { |
| 66 | t.Errorf("expected error for %s but got none", filename) |
| 67 | } else { |
| 68 | normalizedErr := winNewlines.ReplaceAllString(err.Error(), "\n") |
| 69 | if !strings.Contains(normalizedErr, expected) { |
| 70 | t.Errorf("expected error for %s to contain:\n%s\nbut got:\n%s", filename, expected, normalizedErr) |
| 71 | } |
| 72 | } |
| 73 | }) |
| 74 | } |
nothing calls this directly
no test coverage detected