|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +func TestCreateTemplates(t *testing.T) { |
| 11 | + // Create a temporary file |
| 12 | + tmpfile, err := os.CreateTemp("", "template") |
| 13 | + if err != nil { |
| 14 | + t.Fatal(err) |
| 15 | + } |
| 16 | + defer os.Remove(tmpfile.Name()) // clean up |
| 17 | + |
| 18 | + // Write some data to the file |
| 19 | + text := "This is a test template" |
| 20 | + if _, err := tmpfile.Write([]byte(text)); err != nil { |
| 21 | + t.Fatal(err) |
| 22 | + } |
| 23 | + if err := tmpfile.Close(); err != nil { |
| 24 | + t.Fatal(err) |
| 25 | + } |
| 26 | + |
| 27 | + // Call createTemplates |
| 28 | + templates, err := createTemplates([]string{tmpfile.Name()}) |
| 29 | + if err != nil { |
| 30 | + t.Fatal(err) |
| 31 | + } |
| 32 | + |
| 33 | + // Check the returned map |
| 34 | + if len(templates) != 1 { |
| 35 | + t.Fatalf("Expected 1 template, got %d", len(templates)) |
| 36 | + } |
| 37 | + if templates[filepath.Base(tmpfile.Name())] != text { |
| 38 | + t.Fatalf("Expected template content to be '%s', got '%s'", text, templates[filepath.Base(tmpfile.Name())]) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func TestCreateTemplates_DuplicateFilenames(t *testing.T) { |
| 43 | + // Create two temporary files with the same base name in different directories |
| 44 | + dir1 := filepath.Join(os.TempDir(), "dir1") |
| 45 | + if err := os.Mkdir(dir1, 0755); err != nil { |
| 46 | + t.Fatal(err) |
| 47 | + } |
| 48 | + defer os.RemoveAll(dir1) // clean up |
| 49 | + tmpfile1, err := os.Create(filepath.Join(os.TempDir(), "dir1", "fool.tmpl")) |
| 50 | + if err != nil { |
| 51 | + t.Fatal(err) |
| 52 | + } |
| 53 | + defer os.Remove(tmpfile1.Name()) // clean up |
| 54 | + |
| 55 | + dir2 := filepath.Join(os.TempDir(), "dir2") |
| 56 | + if err := os.Mkdir(dir2, 0755); err != nil { |
| 57 | + t.Fatal(err) |
| 58 | + } |
| 59 | + defer os.RemoveAll(dir2) // clean up |
| 60 | + tmpfile2, err := os.Create(filepath.Join(os.TempDir(), "dir2", "fool.tmpl")) |
| 61 | + if err != nil { |
| 62 | + t.Fatal(err) |
| 63 | + } |
| 64 | + defer os.Remove(tmpfile2.Name()) // clean up |
| 65 | + |
| 66 | + // Call createTemplates |
| 67 | + _, err = createTemplates([]string{tmpfile1.Name(), tmpfile2.Name()}) |
| 68 | + if err == nil { |
| 69 | + t.Fatal("Expected error due to duplicate filenames, got nil") |
| 70 | + } |
| 71 | + |
| 72 | + // Check that the error message contains "duplicate template file name" |
| 73 | + if !strings.Contains(err.Error(), "duplicate template file name") { |
| 74 | + t.Fatalf("Expected error message to contain 'duplicate template file name', got '%s'", err.Error()) |
| 75 | + } |
| 76 | +} |
0 commit comments