Skip to content

Commit

Permalink
Add testfile.Ext (#22)
Browse files Browse the repository at this point in the history
* Add testfile.Ext

* Better docstring
  • Loading branch information
earthboundkid authored Jan 14, 2025
1 parent ef9d8be commit e2a0992
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
12 changes: 12 additions & 0 deletions testfile/testfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ import (
"testing"
)

// Ext return path with its current extension stripped and ext added.
// It treats ext with and without a leading dot the same for simplicity of operation.
// If ext is "", path is returned with its current extension stripped off.
func Ext(path, ext string) string {
currExt := filepath.Ext(path)
path = strings.TrimSuffix(path, currExt)
if !strings.HasPrefix(ext, ".") && ext != "" {
ext = "." + ext
}
return path + ext
}

// Read returns the contents of file at path.
// It calls t.Fatalf if there is an error.
func Read(t testing.TB, path string) string {
Expand Down
19 changes: 19 additions & 0 deletions testfile/testfile_example_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package testfile_test

import (
"fmt"
"strings"
"testing"

Expand Down Expand Up @@ -64,3 +65,21 @@ func ExampleRun() {
}
// Output:
}

func ExampleExt() {
for _, path := range []string{
"foo.txt",
"foo.bar/spam",
} {
fmt.Println(testfile.Ext(path, ""))
fmt.Println(testfile.Ext(path, ".json"))
fmt.Println(testfile.Ext(path, "gob"))
}
// Output:
// foo
// foo.json
// foo.gob
// foo.bar/spam
// foo.bar/spam.json
// foo.bar/spam.gob
}

0 comments on commit e2a0992

Please sign in to comment.