1

I'm using PyFilesystem. The code I am testing creates a default filesystem using open_fs(file_url). When I test this code I can now pass in mem://filepath/filename to run the test using a memory filesystem.

However for testing I need to populate the memory filesystem with my test file. Is there a way for me to force a global singeton on filesystems? I would hope that when open_fs is run in code that I don't control, it would open the same filesystem I previously created and seeded with my test file.

martineau
  • 119,623
  • 25
  • 170
  • 301
David Parks
  • 30,789
  • 47
  • 185
  • 328
  • You may be able to monkey-patch the module so when the memory filesystem is opened it first checks to see if that has already been done, and if so, returns what was previously returned rather than creating another instance. See question [What is a monkey patch?](https://stackoverflow.com/questions/5626193/what-is-a-monkey-patch). There a many ways to implement singletons in Python if you do some research. – martineau Mar 09 '19 at 01:18
  • Here's an article I found showing one way to implement [singletons](https://flylib.com/books/en/2.9.1.151/1). The code doesn't display correctly in my browser, but you should be able to figure it out. Here's another [recipe](http://code.activestate.com/recipes/66531). – martineau Mar 09 '19 at 01:31

1 Answers1

1

PyFilesystem author here. Short answer is no, in the case of memory filesystems, once you close the FS object, the memory is discarded. Filesystems will only persist if the underlying storage mechanism is persistent.

Slightly longer answer would be that you could use sub directories of a TempFS to create persistent filesystems.

# Create a temporary filesystem at module scope
temp_fs = open_fs('temp://')

# Acquire new persistent temporary directory
# (this is just a path you can pass to open_fs)
# If you open this multiple times, the data will persist
new_dir = temp_fs.makedir('foo').getsyspath()

# Close temporary filesystem, to delete all directories
temp_fs.close()

That should give you the semantics you describe.

If the project you are using is opening and closing filesystems using the FS url, and still expecting the data to be there, then it will break with filesystems that aren't backed by persistent storage. Maybe you can suggest to the authors that they keep the FS object for as long as it is needed, which is what I'd generally recommend.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Will McGugan
  • 2,005
  • 13
  • 10
  • Thanks for the response! In my case I can simply pass in a filesystem object. The motivation for the question, though, is that it seems counter to PyFilesystem's purpose of being "simple", in particular for mocking in unittests. It feels like a bunch of extra housekeeping to make sure all code that use files accepts and tracks a filesystem object. – David Parks Mar 11 '19 at 18:14