I was writing a test function in dprint and needed to create a fake
os.FileInfo
.
This was the function I was trying to test:
// checkName checks that the file info is a desktop file.
func checkName(fi os.FileInfo) bool {
if !fi.IsDir() {
if filepath.Ext(fi.Name()) == ".desktop" {
return true
}
}
return false
}
It just checks that a certain os.FileInfo
is a file with the .desktop
extension.
This is the full test file:
package main
import (
"os"
"testing"
)
type mockedFileInfo struct {
// Embed this so we only need to add methods used by testable functions.
os.FileInfo
name string
dir bool
}
// We only need to implement the methods used by the checkName function.
func (m mockedFileInfo) IsDir() bool { return m.dir }
func (m mockedFileInfo) Name() string { return m.name }
func TestCheckName(t *testing.T) {
tests := []struct {
name string
dir bool
want bool
}{
{
"hello.world",
false,
false,
},
{
"hello.desktop",
false,
true,
},
{
"hello.desktop",
true,
false,
},
{
"desktop",
false,
false,
},
{
".desktop",
false,
true,
},
{
".",
false,
false,
},
{
"",
false,
false,
},
}
for _, test := range tests {
var fi mockedFileInfo
fi.name = test.name
fi.dir = test.dir
want := test.want
got := checkName(fi)
if want != got {
t.Fatalf("checkName %s failed:\nwanted %v\ngot %v\n", test.name, want, got)
}
}
}
I know it's massive compared to the function lol, but a lot is just repeated test cases and a fair amount would be useful for writing tests for other functions in dprint. Go is an explicit language!