github.com/mholt/caddy-l4@v0.0.0-20241104153248-ec8fae209322/integration/caddyfile_adapt_test.go (about)

     1  package integration
     2  
     3  import (
     4  	jsonMod "encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  	"regexp"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/caddyserver/caddy/v2/caddytest"
    13  
    14  	_ "github.com/mholt/caddy-l4"
    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  
    32  		// read the test file
    33  		filename := f.Name()
    34  		data, err := os.ReadFile("./caddyfile_adapt/" + filename)
    35  		if err != nil {
    36  			t.Errorf("failed to read %s dir: %s", filename, err)
    37  		}
    38  
    39  		// split the Caddyfile (first) and JSON (second) parts
    40  		// (append newline to Caddyfile to match formatter expectations)
    41  		parts := strings.Split(string(data), "----------")
    42  		caddyfile, json := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1])
    43  
    44  		// replace windows newlines in the json with unix newlines
    45  		json = winNewlines.ReplaceAllString(json, "\n")
    46  
    47  		// replace os-specific default path for file_server's hide field
    48  		replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile"))
    49  		json = strings.ReplaceAll(json, `"./Caddyfile"`, string(replacePath))
    50  
    51  		// run the test
    52  		ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", json)
    53  		if !ok {
    54  			t.Errorf("failed to adapt %s", filename)
    55  		}
    56  	}
    57  }