Skip to content

Support more binary. #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions fake_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@
import sys
import time
import warnings
import binascii

try:
import cStringIO as io # pylint: disable-msg=C6204
except ImportError:
Expand Down Expand Up @@ -224,7 +226,7 @@ def SetContents(self, contents):
"""
# 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)
contents = binascii.hexlify(contents).decode('ascii')
self.contents = contents
self.st_size = len(contents)
self.epoch += 1
Expand Down Expand Up @@ -1968,7 +1970,7 @@ def __init__(self, file_object, update=False, read=False, append=False,
if sys.version_info >= (3, 0) and binary:
io_class = io.BytesIO
if contents and isinstance(contents, str):
contents = bytes(contents, 'ascii')
contents = binascii.unhexlify(contents)
if contents:
if update:
self._io = io_class(**newline_arg)
Expand Down
8 changes: 6 additions & 2 deletions fake_filesystem_test.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import sys
import time
import unittest
import binascii

import fake_filesystem

Expand Down Expand Up @@ -2492,7 +2493,7 @@ def setUp(self):
self.file = fake_filesystem.FakeFileOpen(self.filesystem)
self.os = fake_filesystem.FakeOsModule(self.filesystem)
self.file_path = 'some_file'
self.file_contents = b'binary contents'
self.file_contents = b'real binary contents: \x1f\x8b'
self.filesystem.CreateFile(self.file_path, contents=self.file_contents)

def OpenFakeFile(self, mode):
Expand Down Expand Up @@ -2520,7 +2521,10 @@ def testWriteBinary(self):
# reopen the file in text mode
fake_file = self.OpenFakeFile('wb')
fake_file = self.WriteAndReopenFile(fake_file, mode='r')
self.assertEqual(self.file_contents.decode('ascii'), fake_file.read())
if sys.version_info >= (3, 0):
self.assertEqual(binascii.hexlify(self.file_contents).decode('ascii'), fake_file.read())
else:
self.assertEqual(self.file_contents, fake_file.read())

def testWriteAndReadBinary(self):
fake_file = self.OpenFileAndSeek('w+b')
Expand Down