From 656fc4173b880c9538c47cdb7b982eefcea46618 Mon Sep 17 00:00:00 2001 From: jchappelow <140431406+jchappelow@users.noreply.github.com> Date: Mon, 28 Aug 2023 11:49:36 -0500 Subject: [PATCH] sqlite: fix formatFilepath to handle paths w/wo trailing slash This adds a a testable helper function to ensure this path construction always remains robust. --- pkg/sql/sqlite/connection.go | 6 +++- pkg/sql/sqlite/helpers_test.go | 57 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 pkg/sql/sqlite/helpers_test.go diff --git a/pkg/sql/sqlite/connection.go b/pkg/sql/sqlite/connection.go index de814c2db..edd2800bc 100644 --- a/pkg/sql/sqlite/connection.go +++ b/pkg/sql/sqlite/connection.go @@ -83,8 +83,12 @@ func (c *Connection) getFilePath() string { return c.formatFilePath(c.name) } +func formatFilePath(path, fileName string) string { + return filepath.Join(path, fileName+".sqlite") +} + func (c *Connection) formatFilePath(fileName string) string { - return fmt.Sprintf("%s.sqlite", filepath.Join(c.path, fileName)) + return formatFilePath(c.path, fileName) } func (c *Connection) openConn() error { diff --git a/pkg/sql/sqlite/helpers_test.go b/pkg/sql/sqlite/helpers_test.go new file mode 100644 index 000000000..9be798f08 --- /dev/null +++ b/pkg/sql/sqlite/helpers_test.go @@ -0,0 +1,57 @@ +package sqlite + +import ( + "runtime" + "testing" +) + +func Test_formatFilePathNotWindows(t *testing.T) { + // This test defines "want" paths in the *NIX path convention used by linux, + // mac, bsd, etc., but not windows. Rather than using build flags to skip + // this entire file, we'll define this test as such and we can make another + // for Windows hosts if we want to. + if runtime.GOOS == "windows" { + t.Skip("test not applicable to windows paths") + } + type args struct { + path string + fileName string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "abs path no slash", + args: args{ + path: "/tmp", + fileName: "dbname", + }, + want: "/tmp/dbname.sqlite", + }, + { + name: "abs path with trailing slash", + args: args{ + path: "/tmp/", + fileName: "dbname", + }, + want: "/tmp/dbname.sqlite", + }, + { + name: "rel path no slash", + args: args{ + path: "./here", + fileName: "dbname", + }, + want: "here/dbname.sqlite", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := formatFilePath(tt.args.path, tt.args.fileName); got != tt.want { + t.Errorf("formatFilePath() = %v, want %v", got, tt.want) + } + }) + } +}