diff --git a/website/articles/fstest-mapfs-file-does-not-exist.html b/website/articles/fstest-mapfs-file-does-not-exist.html new file mode 100644 index 0000000..642c2c0 --- /dev/null +++ b/website/articles/fstest-mapfs-file-does-not-exist.html @@ -0,0 +1,78 @@ + + + + + fstest mapfs file does not exist error + + + + + + + +
+
+
+

+ In my tests, I defined an fstest.MapFS like this + +

+contentRoot := fstest.MapFS{
+            "/parentDir/index.html": &fstest.MapFile{Data: []byte("content"), Mode: 0o755},
+            "/parentDir/childDir/1-2-3.html": &fstest.MapFile{Data: []byte("other content"`), Mode: 0o755},
+        }
+    
+ + Simple, and yet when I ran a test against it, I received this error: + +
+2024/03/27 19:42:59 http: panic serving [::1]:57135: open parentDir: file does not exist
+    
+
+ +

+
+ +
+

What's the misunderstanding?

+

+ This one took me a couple of hours to finally understand. +

+

+ An fstest.MapFS is pretty much a hash map. If you don't have a precise match for the key in the map + then you get a file does not exist error. Here's the implementation that shows that: + +

+        file := fsys[name]
+    
+- reference in the go source code. + +

+

What's the fix?

+

+ + In my case, I was performing some path munging in my logic so that I was searching for paths relatively, not absolutely + using a leading "/", so my search string was "parentDir/index.html". +

+

+ Once I understood that the path in the fstest.MapFS does not need to be an absolute path, because it is only + a key in a hash map, I redefined my structure like this and got my tests passing: + +

+contentRoot := fstest.MapFS{
+            "/parentDir/index.html": &fstest.MapFile{Data: []byte("content"), Mode: 0o755},
+            "/parentDir/childDir/1-2-3.html": &fstest.MapFile{Data: []byte("other content"`), Mode: 0o755},
+        }
+    
+ +

+
+ +
+
+ +