Fix mocking the built-in open function for Python2

- fix import of mock module
- account for io.StringIO differences in Python 2
This commit is contained in:
Alexander Todorov 2017-10-24 11:39:34 +03:00 committed by Brian C. Lane
parent 2cd4f73177
commit d71290153e

View File

@ -1,6 +1,6 @@
import io import io
import unittest import unittest
from unittest.mock import patch from mock import patch
from pylorax import buildstamp from pylorax import buildstamp
@ -16,8 +16,13 @@ class BuildStampTestCase(unittest.TestCase):
def test_write_produces_file_with_expected_content(self): def test_write_produces_file_with_expected_content(self):
out_file = io.StringIO() out_file = io.StringIO()
# io.StringIO.write accepts unicode,
# but on Python 2 BuildStamp.write() passes strings to this method
out_file.orig_write = out_file.write
out_file.write = lambda s: out_file.orig_write(unicode(s))
with patch.object(out_file, 'close'): with patch.object(out_file, 'close'):
with patch.object(buildstamp, 'open', return_value=out_file): with patch('pylorax.buildstamp.open', create=True, return_value=out_file):
self.bstamp.write('/tmp/stamp.ini') self.bstamp.write('/tmp/stamp.ini')
self.assertIn("[Main]\nProduct=Lorax Tests\nVersion=0.1\nBugURL=https://github.com/rhinstaller/lorax/issues\nIsFinal=True", out_file.getvalue()) self.assertIn("[Main]\nProduct=Lorax Tests\nVersion=0.1\nBugURL=https://github.com/rhinstaller/lorax/issues\nIsFinal=True", out_file.getvalue())
self.assertIn("[Compose]\nLorax=devel", out_file.getvalue()) self.assertIn("[Compose]\nLorax=devel", out_file.getvalue())