Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create os.DirEntry

Does anyone have a hack to create an os.DirEntry object other than listing the containing directory?

I want to use that for 2 purposes:

  1. tests
  2. API where container and contained are queried at the same time
like image 634
Dima Tisnek Avatar asked Jul 11 '16 13:07

Dima Tisnek


2 Answers

Yes, os.DirEntry is a low-level class not intended to be instantiated. For tests and things, you can create a mock PseudoDirEntry class that mimics the things you want, for example (taken from another answer I wrote here):

class PseudoDirEntry:
    def __init__(self, name, path, is_dir, stat):
        self.name = name
        self.path = path
        self._is_dir = is_dir
        self._stat = stat

    def is_dir(self):
        return self._is_dir

    def stat(self):
        return self._stat
like image 53
Ben Hoyt Avatar answered Sep 22 '22 16:09

Ben Hoyt


Even easier:

class PseudoDirEntry:
   def __init__(self, path):
      import os, os.path
      self.path = os.path.realpath(path)
      self.name = os.path.basename(self.path)
      self.is_dir = os.path.isdir(self.path)
      self.stat = lambda: os.stat(self.path)
like image 42
AlexK Avatar answered Sep 21 '22 16:09

AlexK