Giter Site home page Giter Site logo

pytest-dev / pyfakefs Goto Github PK

View Code? Open in Web Editor NEW
609.0 11.0 86.0 9.92 MB

Provides a fake file system that mocks the Python file system modules.

Home Page: https://pytest-pyfakefs.readthedocs.io

License: Apache License 2.0

Python 99.85% Dockerfile 0.15%
python mocking filesystem pytest-plugin unit-testing

pyfakefs's People

Contributors

absolutelynowarranty avatar browniebroke avatar dependabot[bot] avatar dotlambda avatar dougluce avatar dunse avatar exvertus avatar hofbi avatar jakespracher avatar jamesbraza avatar janneronkko avatar jleverenz avatar jmcgeheeiv avatar martin-volf avatar matthew16550 avatar mdippery avatar menge101 avatar mgorny avatar mrbean-bremen avatar nesciens avatar okken avatar orsenthil avatar pre-commit-ci[bot] avatar pyup-bot avatar sambrightman avatar satylogin avatar sruggier avatar svozza avatar tomviner avatar wesleykendall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyfakefs's Issues

pyfakefs is incompatible with pytest

This is a rather specific issue. To reproduce this, you need to have a failing doctest that uses Patcher.

Example doctest:

def foo():
    """
    >>> getfixture('fs')
    >>> foo()
    True
    """
    return False

Here's my fs fixture:

from fake_filesystem_unittest import _Patcher

_Patcher.SKIPNAMES.add('py')  # Ignore pytest components when faking filesystem


@pytest.yield_fixture
def fs():
    """ Fake filesystem. """
    patcher = _Patcher()
    patcher.setUp()
    yield
    patcher.tearDown()

Traceback: pastebin

Traceback after altering `_Patcher._findModules to skip literally everything: pastebin

I'm not sure whether this error lies within pyfakefs, or can be resolved my adding some pytest submodules to _Patcher.SKIPNAMES set.

Add support for glob.iglob

The glob package in python supports glob and iglob methods. The former creates the file name array immediately, while iglob creates an iterator and lazy evaluates the sequence.

The latter is not yet supported by this library

Raise OSError when calling fake_filesystem.mkdir() with a trailing "/."

We should correctly raise OSError when calling mkdir() with a trailing "/."

rm -rf /tmp/dir ; python -c 'import os; os.mkdir("/tmp/dir/.")'
OSError: [Errno 2] No such file or directory: '/tmp/dir/.'

A test case for this is already present in fake_filesystem_test: 
TBD_testMkdirRaisesWithSlashDot but disabled at this time.

Original issue reported on code.google.com by [email protected] on 24 Feb 2010 at 11:56

fake_filesystem.py incorrectly resolves the path "a/b/../non_existent_folder/../file"

Given the filesystem
  a
  a/file
  a/b
fake_filesystem resolves "a/b/../non_existent_folder/../file" to file, but is 
should raise OSError

STEPS TO REPRODUCE:
fake_filesystem_vs_real_test.py contains a test case for this 
(testBadRelativePath) which is currently disabled.   Enable it


EXPECTED RESULTS:
 isfile(path) -> False
 exists(path) -> False
 stat(path).st_size -> raise OSError

OBSERVED RESULTS:
 isfile(path) -> True
 exists(path) -> True
 stat(path).st_size -> 8 (size of final file)

Original issue reported on code.google.com by [email protected] on 24 Feb 2010 at 11:49

pyfakefs not installing from pypi

Hello,

I get the following error when trying to install pyfakefs from pypi:

$ pip install pyfakefs
Collecting pyfakefs
  Downloading pyfakefs-2.6.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/private/var/folders/59/y54yv6md5h36hkw9pc537rf80000gn/T/pip-build-wMslO8/pyfakefs/setup.py", line 37, in <module>
        LONG_DESCRIPTION = open(readme).read()
    IOError: [Errno 2] No such file or directory: '/private/var/folders/59/y54yv6md5h36hkw9pc537rf80000gn/T/pip-build-wMslO8/pyfakefs/README.md'

chown incorrectly accepts non-integer uid/gid arguments

What steps will reproduce the problem?
1. Using pyfakefs, run os.chown or a variant (e.g. os.lchown), passing a 
non-integer value as an argument

What is the expected output? What do you see instead?
This should fail with a TypeError.  Here is the same steps run without pyfakefs:

Python 2.7.8 (default, Sep 24 2014, 18:26:21) 
[GCC 4.9.1 20140903 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chown('/tmp/foo', 'foobar', -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

But pyfakefs's chown succeeds.  Here is os.stat output after chown:

posix.stat_result(st_mode=33188, st_ino=None, st_dev=None, st_nlink=None, 
st_uid='baz', st_gid=None, st_size=0, st_atime=1414437220, st_mtime=1414437220, 
st_ctime=1414437220)

Original issue reported on code.google.com by [email protected] on 27 Oct 2014 at 7:25

FakeFileOpen keyword args do not match the __builtin__ equivalents.

I expect to be able to do the following:

#!/usr/bin/python
import fake_filesystem as fakefs

def main():
  fs = fakefs.FakeFilesystem()
  exec('open = fakefs.FakeFileOpen(fs)')
  exec('file = fakefs.FakeFileOpen(fs)')
  open(name='/foo', mode='w', buffering=1)
  file(filename='/bar', mode='w', bufsize=1)

if __name__ == '__main__': main()


I expect to see NO output.  Instead I see:

Traceback (most recent call last):
  File "./test.py", line 13, in <module>
    if __name__ == '__main__': main()
  File "./test.py", line 10, in main
    open(name='/foo', mode='w', buffering=1)
TypeError: __call__() got an unexpected keyword argument 'buffering'


I'm seeing this with the latest sources in Linux.  However, this defect should 
affect all operating systems considering that the Python open and file 
documentation describe the standard named arguments as 'mode' and either 
'buffering' or 'bufsize' (it's different for file and open).  The current code 
only supports named arguments 'flags' and 'bufsize'.
http://docs.python.org/library/functions.html#file
http://docs.python.org/library/functions.html#open


Here is my patch:
me@localhost:~/code/pyfakefs$ hg diff
diff -r 50ec7acd8b72 fake_filesystem.py
--- a/fake_filesystem.py    Sat Jun 11 13:57:58 2011 -0400
+++ b/fake_filesystem.py    Sat May 12 00:09:30 2012 -0700
@@ -2006,6 +2006,54 @@
     return fakefile


+class FakeFileBuiltin(FakeFileOpen):
+  """Faked file() function replacement.
+
+  Returns FakeFile objects in a FakeFilesystem in place of the file() function.
+  """
+  def __call__(self, filename, mode='r', bufsize=-1):
+    """Returns a StringIO object with the contents of the target file object.
+
+    Args:
+      filename: path to target file
+      mode: additional file flags. All r/w/a r+/w+/a+ flags are supported.
+        't', 'b', and 'U' are ignored, e.g., 'wb' is treated as 'w'.
+      bufsize: ignored. (Used for signature compliance with __builtin__.file)
+
+    Returns:
+      a StringIO object containing the contents of the target file
+
+    Raises:
+      IOError: if the target object is a directory, the path is invalid or
+        permission is denied.
+    """
+    return FakeFileOpen.__call__(self, filename, mode, bufsize)
+
+
+class FakeOpenBuiltin(FakeFileOpen):
+  """Faked open() function replacement.
+
+  Returns FakeFile objects in a FakeFilesystem in place of the open() function.
+  """
+  def __call__(self, name, mode='r', buffering=-1):
+    """Returns a StringIO object with the contents of the target file object.
+
+    Args:
+      name: path to target file
+      mode: additional file flags. All r/w/a r+/w+/a+ flags are supported.
+        't', 'b', and 'U' are ignored, e.g., 'wb' is treated as 'w'.
+      buffering: ignored. (Used for signature compliance with __builtin__.open)
+
+    Returns:
+      a StringIO object containing the contents of the target file
+
+    Raises:
+      IOError: if the target object is a directory, the path is invalid or
+        permission is denied.
+    """
+    return FakeFileOpen.__call__(self, name, mode, buffering)
+
+
 def _RunDoctest():
   # pylint: disable-msg=C6204
   import doctest


Here is a dumb test program that demonstrates the named arguments are now 
correct:
#!/usr/bin/python
import fake_filesystem as fakefs

def main():
  fs = fakefs.FakeFilesystem()
  exec('open = fakefs.FakeOpenBuiltin(fs)')
  exec('file = fakefs.FakeFileBuiltin(fs)')
  open(name='/foo', mode='w', buffering=1)
  file(filename='/bar', mode='w', bufsize=1)

if __name__ == '__main__': main()


I would have submitted this patch through mercurial, but the Code Contribution 
page appears to be under construction.

Original issue reported on code.google.com by [email protected] on 12 May 2012 at 7:17

Attachments:

Pyfakefs doesn't support relative paths

Pyfakefs doesn't seem to support using relative paths with operations in the os 
module, such as "mkdir", "remove" or "rename".  The documentation for "mkdir" 
even notes that relative paths are relative to root.

This makes it impossible to do something like 

fake_os.mkdir("foo")  # works
fake_os.rename("foo", "bar") # fails as os.rename doesn't recognize foo as 
relative to root

Or:
fake_os.mkdir("foo")
fake_os.mkdir("foo/bar")  # works
fake_os.chdir("foo")  # works
fake_os.remove("bar") # remove looks for "bar" at the root

When testing code that interacts with the it's helpful to write tests that 
exercise both relative and absolute paths.

Is there a reason this functionality is not implemented to match a real file 
system?

Original issue reported on code.google.com by londinop on 6 May 2013 at 4:13

The pyfakefs on PyPi is obsolete

So I pip install pyfakefs
Then I import fake_filesystem_unittest in one of my test modules
And I get ImportError: No module named fake_filesystem_unittest when running tests with py.test

Is that expected?

tox support

Add a file named tox.ini with these contents:

------------- begin --------------------
[tox]
envlist=py26,py27,py32,py33,pypy

[testenv]
commands=python all_tests.py

[testenv:py26]
deps=unittest2
------------- end --------------------

tests for py32 and py33 currentl fail.  Octal constants need to change. 
cStringIO should just be StringIO. Seeral others.

Original issue reported on code.google.com by [email protected] on 1 Mar 2013 at 11:32

  • Merged into: #14

Can this be added to pypi?

This would be a useful package to have available in pypi. If I was to submit a 
diff packaging this up as a standard python module would there be any interest 
in it?

Original issue reported on code.google.com by [email protected] on 24 Feb 2013 at 4:24

Binary files cannot be retrieved

I'm using Python 3.2 with PyFakeFs 2.2 on Arch Linux.

Certain libraries I am testing against require binary files (eg HDF5), but I 
cannot make PyFakeFs accept binary files. If I use CreateFile to write bytes 
content into the FakeFile, later attempts to invoke FakeFileOpen(filename, 
mode='rb'), cause a "TypeError: initial_value must be str or None, not bytes".

I've pasted a unit test below which shows the issue. The test_text function 
passes, but test_binary does not.

================ test_pyfakefs.py ================

import unittest
import fake_filesystem


class TestPyfakefs(unittest.TestCase):

    def test_text(self):
        self._perform('hello world', 'r')

    def test_binary(self):
        self._perform(bytes('hello world', 'ascii'), 'rb')

    def _perform(self, content, read_mode):
        file_system = fake_filesystem.FakeFilesystem()
        filename = 'the_file'
        fake_file = file_system.CreateFile(filename, contents=None)
        fake_file.contents = content
        self.assertEqual(content, fake_file.contents)
        fake_file_open = fake_filesystem.FakeFileOpen(file_system)
        file = fake_file_open(filename, mode=read_mode)
        self.assertEqual(content, file.read())

Original issue reported on code.google.com by [email protected] on 20 Aug 2013 at 8:12

Please show the canonical way to switch between test and production

Thank you for pyfakefs.

I want to start out from the beginning using pyfakefs the right way.  Please 
show us how to:

* Use pyfakefs during tests
* Not use pyfakefs in production

The *_test.py tests are of course very informative, but they are always in test 
mode.  They do not have a production mode that uses the real file system.

That issue of Testing on the Toilet that introduced pyfakefs would be great.  
Even sample source code somewhere on the net would be sufficient.

I would be using the latest version applicable to Python 2.7.

Stackoverflow issue 
http://stackoverflow.com/questions/16468443/how-to-replace-file-access-reference
s-for-a-module-under-test asks this same question.

Original issue reported on code.google.com by [email protected] on 1 Oct 2013 at 10:57

Paths are case sensitive even on Windows, which is case insensitive

Paths in windows are not case sensitive so windows treats the directory Tmp and tmp as the same directory. pyfakefs will actually treat them as 2 different directories. For example:

class MyTestCase(fake_filesystem_unittest.TestCase):
    def setUp(self):
        os.makedirs('Tmp')
        f = open(os.path.join('Tmp', 'test2.txt'), 'wb')
        f.close()
        f = open(os.path.join('tmp', 'test.txt'), 'wb')
        f.close()

        self.setUpPyfakefs()

        self.fs.CreateDirectory('Tmp')
        f = open(os.path.join('Tmp', 'test2.txt'), 'wb')
        f.close()
        f = open(os.path.join('tmp', 'test.txt'), 'wb')
        f.close()

    def test_test(self):
        pass

will give the following stack trace:

Error
Traceback (most recent call last):
  File "C:\Python27\lib\unittest\case.py", line 320, in run
  File "C:\workspaces\dem\dem\test\Test.py", line 21, in setUp
  File "C:\Python27\lib\site-packages\pyfakefs\fake_filesystem.py", line 1896, in __call__
  File "C:\Python27\lib\site-packages\pyfakefs\fake_filesystem.py", line 1904, in _call_ver2
  File "C:\Python27\lib\site-packages\pyfakefs\fake_filesystem.py", line 1968, in Call
  File "C:\Python27\lib\site-packages\pyfakefs\fake_filesystem.py", line 955, in CreateFile
IOError: [Errno 2] No such fake directory: '\\tmp'

The Tmp directory created before setting up pyfakefs in the test with have both test.txt and test2.txt, meaning that python did not care about the capital T. This causes problems when a module has become dependent on this behavior, especially when it is a 3rd party module.

Improve handling of st_ino

Currently pyfakefs handles st_ino as something optional, which is probably OK 
for many scenarios.

But it would be really nice, if st_ino would be handled properly. 

I'm working on a sort of file syncing application, which needs to detect all FS 
modifications. Comparing st_ino of two files/dirs (e.g. a file from an old FS 
snapshot and a file from a new FS snapshot) is a typical and reliable way to 
detect that both files/dirs correspond to the same object on the file system. 
If st_ino values are the same, then it is the same object (at least on most 
UNIX file systems). 

Therefore, I'd like to propose the following:
1) When a new file or directory is created, it should get a new unique st_ino 
value

2) When objects (files or dirs) are moved inside the same file system, their 
st_ino fields should be preserved.
    (BTW, fake_filesystem_shutil currently tries to preserve most st_* stats for 
files, but st_ino is not included into this set of preserved fields. And for
directory moves, no st_* stats are preserved at all for some reason)

3) Optional: currently fake_filesystem_shutil.move uses copying to move files 
and directories. This does not scale for big nested directories, because it 
needs to move each nested sub-component separately. May be it could use 
"rename" whenever possible? It could provide significant speed-ups.

Original issue reported on code.google.com by romixlev on 6 Jan 2014 at 12:15

"path.relpath" on Windows is relative to the real current directory, not the fake directory

What steps will reproduce the problem?

import os
import fake_filesystem

filesystem = fake_filesystem.FakeFilesystem()
fake_os = fake_filesystem.FakeOsModule(filesystem)

os.chdir('\\foo\\bar')

print "real curdir:\t%s" % os.getcwd()
print "fake curdir:\t%s" % fake_os.getcwd()

print "real relative to root:\t%s" % os.path.relpath('\\')
print "fake relative to root:\t%s" % fake_os.path.relpath('\\')

What version of the product are you using? On what operating system?
2.3 on Windows

Please provide any additional information below.

Original issue reported on code.google.com by londinop on 17 Sep 2013 at 8:02

Permissions for deleting files

pyfakefs doesn't seem to honor permissions when deleting files. I marked a 
directory and the files contained within as read-only using the fake_os 
module's chmod function, but os.remove and shutil.rmtree were able to remove 
the files without issue.

What steps will reproduce the problem?
# Create filesystem with '/dir1/file1'

path = os.path.join('dir1', 'file1')
mode = self.fake_os.stat(path)[stat.ST_MODE]
self.fake_os.chmod('dir1', 0444)
self.fake_os.chmod(path, 0444)
self.fake_os.remove(path)

What is the expected output? What do you see instead?
I would expect an "OSError: [Errno 13] Permission denied" or equivalent, 
instead the file is removed.

What version of the product are you using? On what operating system?
pyfakefs 2.4, tested on Windows 7 and Red Hat 6

Please provide any additional information below.
It would be really helpful to acknowledge permissions, since many tests I write 
are around "how does my program behave if it doesn't have access to the 
necessary files?"

Original issue reported on code.google.com by londinop on 28 Feb 2014 at 5:02

Support for Python 3

Test pyfakefs in Python 3.2 and 3.3 and create changes in a branch to be 
reviewed, and merged to trunk.

Original issue reported on code.google.com by [email protected] on 1 Mar 2013 at 11:40

Support for python 3.4's pathlib

Python 3.4 introduced pathlib, an OOP approach to file paths. This new part of
the standard library also introduces a number of methods for manipulating files
that are not currently handled by pyfakefs.

Original issue reported on code.google.com by [email protected] on 20 May 2014 at 10:26

testExpandUser fails on cygwin

When running python fake_filesystem_test.py on cygwin x86_64 (On windows 8.1), testExpandUser fails.

Output:

FAIL: testExpandUser (__main__.FakePathModuleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "fake_filesystem_test.py", line 1858, in testExpandUser
    self.assertEqual('/root', self.path.expanduser('~root'))
AssertionError: '/root' != '~root'

After changing
1852 if sys.platform.startswith('win'): to:
1852 if sys.platform.startswith('win') or sys.platform == 'cygwin':,
the output is now:

FAIL: testExpandUser (__main__.FakePathModuleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "fake_filesystem_test.py", line 1854, in testExpandUser
    self.os.environ['USERPROFILE'].replace('\\', '/'))
AssertionError: '/home/Filip' != 'C:/Users/Filip'

setup.py is missing license header

To whom it may concern,
We are using pyfakefs as third_party in chromium project. The file pyfakefs/setup.py is missing license header and make chromium license check fails. My current workaround is copying the license header from other files in the project into it.
It would be great if someone can update the license header in pyfakefs/setup.py so we can make the pyfakefs pass Chromium license check without modification.

Thanks,
Ned

should override os.path.normcase on Windows

FakeFilesystem takes a path_separator arg, primarily useful for cross-platform 
faking on Windows.  However it doesn't override os.path.normcase, which on 
Windows replaces forward-slashes with backslashes.

What steps will reproduce the problem?
import fake_filesystem
filesystem = fake_filesystem.FakeFilesystem(path_separator='/')
fake_os = fake_filesystem.FakeOsModule(filesystem)
os = fake_os                    # bash real os
print os.path.normcase('/tmp')

What is the expected output?
/tmp

What do you see instead?
\tmp

What version of the product are you using? On what operating system?
2.4, on Windows

This causes problems with e.g. the tempfile module, because it uses normcase 
which produces invalid filenames in this situation.

I think the simplest solution is to just override os.path.normcase with a null 
implementation that returns its arg on Windows, if the filesystem's 
path_separator is '/'.

Original issue reported on code.google.com by [email protected] on 2 May 2014 at 3:41

fake_tempfile is using AddOpenFile incorrectly.

Code to reproduce:

def Repro():
  fd, fn = tempfile.mkstemp()
  fo = os.fdopen(fd, 'w+b')
  ...

I'd get a stack trace like this:

"myfile.py", line 3, in Repro
    fo = os.fdopen(fd, 'w+b')
  File ".../fakefs/fake_filesystem.py", line 1208, in _fdopen_ver2
    return FakeFileOpen(self.filesystem).Call(file_des, mode=mode)
  File ".../fakefs/fake_filesystem.py", line 1918, in Call
    file_object = self.filesystem.GetOpenFile(filedes).GetObject()
AttributeError: 'FakeFile' object has no attribute 'GetObject'

The offending part in fake_tempfile calls AddOpenFile() with a FakeFile object, 
but according to fake_filesystem.py line 2184 this should be FakeFileWrapper 
which is only visible from the FakeFileOpen class.

liulk

Original issue reported on code.google.com by [email protected] on 6 Dec 2013 at 12:09

`path` is stubbed out too aggressively

I have code that looks like this:

import os

from mymodule import path

print path.MyAwesomeMethod

When I try to unit test it inside of a fake_filesystem_unittest.TestCase, I get:

    ...
    File ".../pyfakefs/pyfakefs/fake_filesystem.py", line N, in __getattr__
  KeyError: 'MyAwesomeMethod'

However, changing the import in the snippet to from mymodule import path as path_module avoids this, which indicates that pyfakefs is stubbing out any module named path, where if possible it should only stub out os.path.

FakePathModule is missing relpath

Solution:

Sets the os module imported in os.path captured by FakePathModule to
FakeOsModule. This ensures that any calls to os.* when redirecting
calls to os.path are calls to methods in FakeOsModule rather than to
the builtin os module over the actual file system. os.path.abspath,
os.path.realpath, and os.path.relpath from tested code gets values
from FakeOsModule.getcwd and the like when calculating path names.

Original issue reported on code.google.com by [email protected] on 17 May 2013 at 10:20

Builtin open methods lack IOError for prohibited operations

When files are opened with the builtin open, then the mode must be considered 
to permit various operations. For example, if the file is opened for reading 
only, then write() and writelines() must result in IOError, when the file is 
not opened for reading, then read() and readlines() must result in IOError. 
Also, when the file is only opened for reading, flush() must do nothing.

Original issue reported on code.google.com by [email protected] on 3 Jun 2013 at 5:24

fake_filesystem's os.chown() doesn't match Python's os.chown() handling of -1

What steps will reproduce the problem?
1. Sets up unit test for fake_filesystem
2. Code under test calls os.chown(xxx, -1, -1)

What is the expected output? What do you see instead?
The stat's st_uid and st_gid should not change, they are set to -1 instead.

Please provide any additional information below.
According to os module documentation, a uid or gid value of -1 preserves the 
existing value.

Original issue reported on code.google.com by [email protected] on 9 Jul 2012 at 8:19

os.utime fails to traverse symlinks

(Tested with 2.4)

Passes:

class TestLink(FakeFS):

    def setUp(self):
        #self.setUpPyfakefs()
        os.makedirs('/tmp/test-foo')
        os.symlink('/tmp/test-foo', '/tmp/test-bar')

    def tearDown(self):
        #self.teardownPyfakefs()
        pass

    def test(self):
        fname = '/tmp/test-bar/a.file'
        with open(fname, 'w') as f:
            f.write('\n')
        os.utime(fname, (time.time(), time.time()))

Fails:

class TestLink(FakeFS):

    def setUp(self):
        self.setUpPyfakefs()
        os.makedirs('/tmp/test-foo')
        os.symlink('/tmp/test-foo', '/tmp/test-bar')

    def tearDown(self):
        self.teardownPyfakefs()
        pass

    def test(self):
        fname = '/tmp/test-bar/a.file'
        with open(fname, 'w') as f:
            f.write('\n')
        os.utime(fname, (time.time(), time.time()))
  File "/home/csb/.local/lib/python2.7/site-packages/fake_filesystem.py", line 1745, in utime
OSError: [Errno 2] No such file or directory in fake filesystem: '/tmp/test-bar/a.file'

(FakeFS is the wraper from https://code.google.com/p/pyfakefs/issues/detail?id=22)

Reading from fake block devices doesn't work

What steps will reproduce the problem?
1. Create a fake block device (dev = fs.CreateFile('name', stat.S_IFBLK))
2. Try and read from it (dev.read())


What is the expected output? What do you see instead?
This should work, but an error is raised about trying to read from a directory.

Patch with fix and test attached.

Original issue reported on code.google.com by [email protected] on 12 Dec 2013 at 3:13

Attachments:

travis build reports green when there are failures

See e.g. https://travis-ci.org/jmcgeheeiv/pyfakefs/jobs/90503441:

[...lots of output...]
======================================================================
ERROR: testByteContents (fake_filesystem_test.FakeFileOpenTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/build/jmcgeheeiv/pyfakefs/fake_filesystem_test.py", line 2079, in testByteContents
    f.write(byte_fractions)
TypeError: string argument expected, got 'bytes'
----------------------------------------------------------------------
Ran 402 tests in 0.265s
FAILED (errors=1, skipped=3)
The command "./all_tests.py" exited with 0.
Done. Your build exited with 0.

all_tests.py does not return a non-zero return code when there were errors in the test suite.
TestRunner.run() returns a TestResult object and you have to return 1 from the script and not result.wasSuccessful().

Fix tests to work on OS X.

Two types of tests fail on OS X.

FAIL: testSymLinkToParent 
(fake_filesystem_vs_real_test.FakeFilesystemVsRealTest)
  -- This fails because HFS+ on OS X behaves in an unexpected way. I essentially comment this out since playing FS games seems unwise.

FAIL: testBrokenRelativePath 
(fake_filesystem_vs_real_test.FakeFilesystemVsRealTest)
  -- The OS X tempdir is softlinked. This fully expands the name of the real tempdir.

Fixed in: 
https://code.google.com/r/kevin-pyfakefs-osx/source/detail?r=8e6ee052ce793f22568
174bf4fc702c74d3c60e0

Original issue reported on code.google.com by [email protected] on 1 Mar 2013 at 11:03

Should use a generic python interpreter and not hard code python2.4

$ ag python2.4
build/lib/fake_filesystem_glob.py
1:#!/usr/bin/python2.4

build/lib/fake_filesystem_shutil.py
1:#!/usr/bin/python2.4

build/lib/fake_tempfile.py
1:#!/usr/bin/python2.4
19:Fake implementation of the python2.4.1 tempfile built-in module that works with
294:    logging.error('tempfile.template= is a NOP in python2.4')

fake_filesystem_glob_test.py
1:#!/usr/bin/python2.4

fake_filesystem_glob.py
1:#!/usr/bin/python2.4

fake_filesystem_shutil.py
1:#!/usr/bin/python2.4

fake_filesystem_shutil_test.py
1:#!/usr/bin/python2.4

fake_tempfile_test.py
1:#!/usr/bin/python2.4
179:    self.assertEqual('tempfile.template= is a NOP in python2.4',

fake_tempfile.py
1:#!/usr/bin/python2.4
19:Fake implementation of the python2.4.1 tempfile built-in module that works with
294:    logging.error('tempfile.template= is a NOP in python2.4')

fake_filesystem_vs_real_test.py
1:#!/usr/bin/python2.4

fake_filesystem's os.rename() doesn't copy uid and gid to the renamed file

What steps will reproduce the problem?
1. setup units for fake_filesystem
3. code under test calls os.chown(from_file, uid, gid) with new uid and gid.
2. code under test calls os.rename(from_file, to_file)

What is the expected output? What do you see instead?
The new file (to_file) doesn't have uid or gid set (set to None), where they 
should be set to the uid and gid of the renamed file (from_file)

Please provide any additional information below.
System 'mv' command will preserve uid and gid on renamed file.

Original issue reported on code.google.com by [email protected] on 9 Jul 2012 at 8:23

Current status has same Version as old Pypi status

First I installed pyfakefs using pip. Then I recognized that the version on Pypi is old and on github are some developments. I tried to upgrade my version to github using pip. It failed, because Pypi version and github version are both 2.4. I had to remove the old installed version to install this one. If the github version shall be used, there should be a new version number.

fake_filesystem_unittest.py uses python2 __builtin__

I have crash as follows

    [...]tests/__init__.py", line 17, in setUp
        self.setUpPyfakefs()
      File "/usr/local/lib/python3.4/dist-packages/pyfakefs-2.4-py3.4.egg/fake_filesystem_unittest.py", line 87, in setUpPyfakefs
        self._stubber.setUp()
      File "/usr/local/lib/python3.4/dist-packages/pyfakefs-2.4-py3.4.egg/fake_filesystem_unittest.py", line 201, in setUp
        startPatch(self, '__builtin__.file', self.fake_open)
      File "/usr/local/lib/python3.4/dist-packages/pyfakefs-2.4-py3.4.egg/fake_filesystem_unittest.py", line 198, in startPatch
        print("Warning: Could not patch '{}' on module '{}' because '{}' resolves to {}".format(attribute, target, target, patch.getter()))
      File "/usr/local/lib/python3.4/dist-packages/mock.py", line 1414, in <lambda>
        getter = lambda: _importer(target)
      File "/usr/local/lib/python3.4/dist-packages/mock.py", line 1098, in _importer
        thing = __import__(import_path)
    nose.proxy.ImportError: No module named '__builtin__'

In Line 201 of fake_filesystem_unittest.py

    startPatch(self, '__builtin__.file', self.fake_open)

the old name __builtin__ is used instead of python3 version builtins.

In mock.py as included in Traceback you can find the line

builtin = '__builtin__'
if inPy3k:
    builtin = 'builtins'

os.remove doesn't work with relative paths

The 'remove' method in the FakeOsModule doesn't support relative paths.

What steps will reproduce the problem?

fake_os.mkdir("foo")
fake_os.mkdir("foo/bar")  # works
fake_os.chdir("foo")  # works
fake_os.remove("bar") # remove looks for "bar" at the root

What is the expected output? What do you see instead?
expected: file is deleted
actual outcome: 'bar' does not exist in fake filesystem

What version of the product are you using? On what operating system?
2.4, Windows 7

Please provide any additional information below.

Original issue reported on code.google.com by londinop on 25 Nov 2014 at 3:28

Revert to using mox.stubout instead of mock.patch

A few months ago, in pyfakefs.pyfakefs_unittest._Patcher I replaced mox with unittest.mock. mox worked fine, but mock seemed like a more reliable dependency:

  • mox is seemingly abandoned while mock is now part of the standard library
  • mox does not support Python 3
  • The OpenStack people created mox3 to support Python 3, but it is marked with the omimous comment, "Use at your own risk". Moreover, OpenStack stopped using mox3.

Now we are seeing all kinds of trouble caused by mock module bug 250:

  • pyfakefs issue #43
  • pyfakefs issue #46

pyfakefs used only one small part of mox, mox.stubout. I do not care to depend on unmaintained mox, (or to take on maintenance of the mox3 module as a whole), so I am considering salvaging just the part of mox3 that pyfakefs needs:

  1. Take just mox3.stubout.py and its test from mox3
  2. Add it to pyfakefs as pyfakefs.stubout
  3. Revert to using pyfakefs.stubout as I used mox.stubout in earlier versions, eliminating the dependency on both mock and mox

Please tell me what you think of this plan.

os.write() and os.close() are not mocked.

What steps will reproduce the problem?
1. Enable fake_filesystem in a unit test.
2. Any code under test calls os.write(fd, '') or os.close(fd)

What is the expected output? What do you see instead?
No problems expected for a valid file descriptor. Gets back OSError exception: 
[Errno 9] Bad file descriptor

Please provide any additional information below.
Pretty easy to fix, with the following code:

def write(self, fd, contents):
  fh = self.fdopen(fd)
  fh.write(contents)

def close(self, fd):
  fh = self.fdopen(fd)
  fh.close()

There are more methods that operate on file descriptors which can be supported 
similarly.

Original issue reported on code.google.com by [email protected] on 9 Jul 2012 at 8:15

Encoding/decoding error in Python3 for non-ASCII binary data

Given the following code:

  #! /usr/bin/env python3

  import fake_filesystem as ff
  fs = ff.FakeFilesystem()

  text_fractions =  '⅓ ⅔ ⅕ ⅖'
  byte_fractions = b'\xe2\x85\x93 \xe2\x85\x94 \xe2\x85\x95 \xe2\x85\x96'

  fake_open = ff.FakeFileOpen(fs)

  if False:
      fractions = text_fractions.encode('utf-8')

      with fake_open('jim', 'wb') as fd:
          fd.write(fractions)
  else:
      with fake_open('jim', 'wb') as fd:
          fd.write(byte_fractions)

  with fake_open('jim', 'rb') as fd:
      jim = fd.read()

  print(type(jim))

with Python 3.4, we get a traceback:

  $ python test.py
  Traceback (most recent call last):
    File "test.py", line 20, in <module>
      with fake_open('jim', 'rb') as fd:
    File "/Users/tibbs/env/py3/lib/python3.4/site-packages/fake_filesystem.py", line 1869, in __call__
      return self.Call(*args, **kwargs)
    File "/Users/tibbs/env/py3/lib/python3.4/site-packages/fake_filesystem.py", line 2180, in Call
      closefd=closefd)
    File "/Users/tibbs/env/py3/lib/python3.4/site-packages/fake_filesystem.py", line 1971, in __init__
      contents = bytes(contents, 'ascii')
  UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

Note that replacing "if False:" with "if True:" gives the same result, as one
would expect.

The problem appears to be that, in fake_filesystem.py, in SetContents,
at lines 225-227 it says:

    # convert a byte array to a string
    if sys.version_info >= (3, 0) and isinstance(contents, bytes):
      contents = ''.join(chr(i) for i in contents)

which makes "contents" be a string. Then in FakeFileWrapper at lines 1967-1971
it has:

        if sys.version_info >= (3, 0) and binary:
          io_class = io.BytesIO
          if contents and isinstance(contents, str):
            contents = bytes(contents, 'ascii')

Given that "contents" is a string, it tries to interpret it as "ascii", which
of course fails.

A possible solution is to enforce utf-8 encoding. Thus in the first piece of
code, use:

    if sys.version_info >= (3, 0) and isinstance(contents, bytes):
      contents = contents.decode('utf-8')

and in the second:

    if contents and isinstance(contents, str):
      contents = bytes(contents, 'utf-8')

The information above is copyrighted Alcatel-Lucent, 2015, All Rights
Reserved. The information is provided AS-IS. NO PATENT LICENSE, EXPRESS
OR IMPLIED, IS GRANTED OR INTENDED.

Original issue reported on code.google.com by [email protected] on 20 Feb 2015 at 2:09

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.