Last active
December 16, 2015 10:59
-
-
Save riywo/5424458 to your computer and use it in GitHub Desktop.
python mox example with subprocess.Popen and builtin open
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from subprocess import * | |
class Example(object): | |
def run(self): | |
a = open("/etc/example.txt").read() | |
b = Popen("/usr/bin/example.sh", shell=True, stdout=PIPE).communicate()[0] | |
return a + b | |
if __name__ == "__main__": | |
Example().run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
from mox import Mox | |
from StringIO import StringIO | |
from subprocess import * | |
import __builtin__ | |
import example | |
txt = ''' | |
aaaa | |
'''.lstrip() | |
shout = ''' | |
bbbb | |
'''.lstrip() | |
expect = ''' | |
aaaa | |
bbbb | |
'''.lstrip() | |
class MockPopen(object): | |
def __init__(self, stdout): | |
self.stdout = stdout | |
def communicate(self): | |
return [self.stdout] | |
class TestExample(unittest.TestCase): | |
def test_run(self): | |
m = Mox() | |
m.StubOutWithMock(__builtin__, 'open') | |
open("/etc/example.txt").AndReturn(StringIO(txt)) | |
m.StubOutWithMock(example, "Popen") | |
example.Popen("/usr/bin/example.sh", shell=True, stdout=PIPE).AndReturn(MockPopen(shout)) | |
m.ReplayAll() | |
e = example.Example() | |
result = e.run() | |
m.VerifyAll() | |
m.UnsetStubs() | |
self.assertEqual(result, expect) | |
if __name__ == "__main__": | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment