|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +func TestEscapeSpace(t *testing.T) { |
| 11 | + got := escapeSpace("hello world") |
| 12 | + if got != "hello\\ world" { |
| 13 | + t.Errorf("expected 'hello\\\\ world', got %q", got) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +func TestLoadConfig(t *testing.T) { |
| 18 | + dir := t.TempDir() |
| 19 | + path := filepath.Join(dir, "cfg.toml") |
| 20 | + data := []byte(`listen = 8080 |
| 21 | +server_name = "example.com" |
| 22 | +
|
| 23 | +[[custom_keywords]] |
| 24 | +phrase = "foo bar" |
| 25 | +dest = "google"`) |
| 26 | + if err := os.WriteFile(path, data, 0644); err != nil { |
| 27 | + t.Fatalf("failed to write config: %v", err) |
| 28 | + } |
| 29 | + cfg, err := loadConfig(path) |
| 30 | + if err != nil { |
| 31 | + t.Fatalf("loadConfig returned error: %v", err) |
| 32 | + } |
| 33 | + if cfg.Listen != 8080 { |
| 34 | + t.Errorf("expected listen 8080, got %d", cfg.Listen) |
| 35 | + } |
| 36 | + if cfg.ServerName != "example.com" { |
| 37 | + t.Errorf("expected server name example.com, got %s", cfg.ServerName) |
| 38 | + } |
| 39 | + if len(cfg.CustomKeywords) != 1 { |
| 40 | + t.Fatalf("expected 1 custom keyword, got %d", len(cfg.CustomKeywords)) |
| 41 | + } |
| 42 | + if cfg.CustomKeywords[0].Phrase != "foo bar" || cfg.CustomKeywords[0].Dest != "google" { |
| 43 | + t.Errorf("unexpected custom keyword %+v", cfg.CustomKeywords[0]) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func TestGenerateNginx(t *testing.T) { |
| 48 | + cfg := Config{Listen: 8080, ServerName: "example.com", CustomKeywords: []KeywordRule{{Phrase: "foo", Dest: "google"}}} |
| 49 | + out, err := generateNginx(cfg) |
| 50 | + if err != nil { |
| 51 | + t.Fatalf("generateNginx returned error: %v", err) |
| 52 | + } |
| 53 | + if !strings.Contains(out, "server_name example.com;") { |
| 54 | + t.Errorf("generated config missing server name: %s", out) |
| 55 | + } |
| 56 | + if !strings.Contains(out, "~*(?i)^foo$") { |
| 57 | + t.Errorf("generated config missing custom rule: %s", out) |
| 58 | + } |
| 59 | +} |
0 commit comments