Skip to content

Commit

Permalink
fix: ParseFromStr, add unittest (#755)
Browse files Browse the repository at this point in the history
Signed-off-by: Keming <kemingyang@tensorchord.ai>
  • Loading branch information
kemingy committed Aug 10, 2022
1 parent 53d8e13 commit 8675316
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 11 deletions.
27 changes: 16 additions & 11 deletions pkg/builder/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,18 +321,23 @@ func resolveExporterDest(exporter, dest string) (func(map[string]string) (io.Wri
func ParseFromStr(fromStr string) (string, string, error) {
filename := defaultFile
funcname := defaultFunc
if strings.Contains(fromStr, ":") {
fromArr := strings.Split(fromStr, ":")

if len(fromArr) != 2 {
return "", "", errors.New("invalid from format, expected `file:func`")
}
if fromArr[0] != "" {
filename = fromArr[0]
}
if fromArr[1] != "" {
funcname = fromArr[1]
if !strings.Contains(fromStr, ":") {
if len(fromStr) > 0 {
filename = fromStr
}
return filename, funcname, nil
}

fromArr := strings.Split(fromStr, ":")

if len(fromArr) != 2 {
return "", "", errors.New("invalid from format, expected `file:func`")
}
if fromArr[0] != "" {
filename = fromArr[0]
}
if fromArr[1] != "" {
funcname = fromArr[1]
}
return filename, funcname, nil
}
65 changes: 65 additions & 0 deletions pkg/builder/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,68 @@ func TestParseOutput(t *testing.T) {
})
}
}

func TestParseFromStr(t *testing.T) {
type testCase struct {
name string
from string
expectFile string
expectFunc string
expectError bool
}

testCases := []testCase{
{
"empty",
"",
"build.envd",
"build",
false,
},
{
"without func",
"main.envd",
"main.envd",
"build",
false,
},
{
"without func but has :",
"test.envd:",
"test.envd",
"build",
false,
},
{
"without file",
":test",
"build.envd",
"test",
false,
},
{
"all",
"hello.envd:run",
"hello.envd",
"run",
false,
},
{
"more than 2 :",
"test.envd:run:foo",
"",
"",
true,
},
}

for _, tc := range testCases {
file, function, err := ParseFromStr(tc.from)
if tc.expectError {
require.Error(t, err)
} else {
require.Equal(t, file, tc.expectFile, tc.name)
require.Equal(t, function, tc.expectFunc, tc.name)
}
}
}

0 comments on commit 8675316

Please sign in to comment.