From 31cb2d1fd164cbfc609c398f222461d01a4aeb90 Mon Sep 17 00:00:00 2001 From: Gwyn Date: Wed, 27 Mar 2024 20:21:31 -0600 Subject: [PATCH] Short article about a misunderstanding I had with fstest.mapfs that broke my tests. --- .../fstest-mapfs-file-does-not-exist.html | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 website/articles/fstest-mapfs-file-does-not-exist.html 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},
+        }
+    
+ +

+
+ +
+
+ +