Test cross-platform boundaries
Test cross-platform boundaries
Native path separators, volume names, case sensitivity, reserved names, permissions and symlink support vary by OS and filesystem. Avoid hardcoded native strings in portable tests. Separate portable logical-name tests from tests that depend on the target filesystem. Compare semantic results rather than full system error messages.
package main
import ( "fmt" "os" "path/filepath")
func main() { p := filepath.Join("data", "note.txt") fmt.Println(filepath.Base(p) == "note.txt", filepath.ToSlash(p) == "data/note.txt") fmt.Println(filepath.Separator == os.PathSeparator)}The native separator may differ, so convert to slash before comparing with the logical expected value. On Windows, drive-relative paths are not the same as absolute paths. Case sensitivity can vary even within one OS; do not assume it solely from GOOS.
Expected output:
true truetrueCheck errors semantically
package main
import ( "errors" "fmt" "io/fs" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() _, e := os.Open(filepath.Join(d, "missing.txt")) fmt.Println(errors.Is(e, fs.ErrNotExist)) var pe *fs.PathError fmt.Println(errors.As(e, &pe))}errors.Is checks the missing-file condition through wrapping; errors.As can retrieve a PathError without matching platform-specific wording. Build on each target and execute on each supported OS: cross-compilation checks compilation, not runtime filesystem behavior. Linux execution here does not establish Windows or macOS behavior.
Expected output:
truetrueTry it locally
Create a small file inside lab; try creating it again with exclusive flags and check errors.Is against fs.ErrExist.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 08: Test cross-platform boundaries
Check the lesson objective before moving on.
What does a successful Windows cross-build on Linux establish?
How should a portable test detect a missing file?