Skip to content

Instantly share code, notes, and snippets.

@riywo
Last active December 16, 2015 10:59
Show Gist options
  • Save riywo/5424458 to your computer and use it in GitHub Desktop.
Save riywo/5424458 to your computer and use it in GitHub Desktop.
python mox example with subprocess.Popen and builtin open
#!/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()
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